repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
emilydolson/avida-spatial-tools | avidaspatial/parse_files.py | make_niche_grid | def make_niche_grid(res_dict, world_size=(60, 60)):
"""
Converts dictionary specifying where resources are to nested lists
specifying what sets of resources are where.
res_dict - a dictionary in which keys are resources in the environment
and values are list of tuples representing the cells they're... | python | def make_niche_grid(res_dict, world_size=(60, 60)):
"""
Converts dictionary specifying where resources are to nested lists
specifying what sets of resources are where.
res_dict - a dictionary in which keys are resources in the environment
and values are list of tuples representing the cells they're... | [
"def",
"make_niche_grid",
"(",
"res_dict",
",",
"world_size",
"=",
"(",
"60",
",",
"60",
")",
")",
":",
"# Initialize array to represent world",
"world",
"=",
"initialize_grid",
"(",
"world_size",
",",
"set",
"(",
")",
")",
"# Fill in data on niches present in each ... | Converts dictionary specifying where resources are to nested lists
specifying what sets of resources are where.
res_dict - a dictionary in which keys are resources in the environment
and values are list of tuples representing the cells they're in.
world_size - a tuple indicating the dimensions of the ... | [
"Converts",
"dictionary",
"specifying",
"where",
"resources",
"are",
"to",
"nested",
"lists",
"specifying",
"what",
"sets",
"of",
"resources",
"are",
"where",
"."
] | train | https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/parse_files.py#L73-L96 |
emilydolson/avida-spatial-tools | avidaspatial/parse_files.py | parse_environment_file_list | def parse_environment_file_list(names, world_size=(60, 60)):
"""
Extract information about spatial resources from all environment files in
a list.
Arguments:
names - a list of strings representing the paths to the environment files.
world_size - a tuple representing the x and y coordinates of t... | python | def parse_environment_file_list(names, world_size=(60, 60)):
"""
Extract information about spatial resources from all environment files in
a list.
Arguments:
names - a list of strings representing the paths to the environment files.
world_size - a tuple representing the x and y coordinates of t... | [
"def",
"parse_environment_file_list",
"(",
"names",
",",
"world_size",
"=",
"(",
"60",
",",
"60",
")",
")",
":",
"# Convert single file to list if necessary",
"try",
":",
"names",
"[",
"0",
"]",
"=",
"names",
"[",
"0",
"]",
"except",
":",
"names",
"=",
"["... | Extract information about spatial resources from all environment files in
a list.
Arguments:
names - a list of strings representing the paths to the environment files.
world_size - a tuple representing the x and y coordinates of the world.
(default: 60x60)
Returns a dictionary in ... | [
"Extract",
"information",
"about",
"spatial",
"resources",
"from",
"all",
"environment",
"files",
"in",
"a",
"list",
"."
] | train | https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/parse_files.py#L99-L124 |
emilydolson/avida-spatial-tools | avidaspatial/parse_files.py | reduce_resource_name_to_task | def reduce_resource_name_to_task(res_name):
"""
Assuming that the convention of naming resources associated with tasks as
res[TASK][number], reduces such resource names to just the name of the
task. This ensures that multiple copies of the same resource are treated
the same. Resource names of differ... | python | def reduce_resource_name_to_task(res_name):
"""
Assuming that the convention of naming resources associated with tasks as
res[TASK][number], reduces such resource names to just the name of the
task. This ensures that multiple copies of the same resource are treated
the same. Resource names of differ... | [
"def",
"reduce_resource_name_to_task",
"(",
"res_name",
")",
":",
"# Reduce resource names to tasks being rewarded",
"if",
"res_name",
"[",
":",
"3",
"]",
".",
"lower",
"(",
")",
"!=",
"\"res\"",
":",
"return",
"res_name",
"res_name",
"=",
"res_name",
"[",
"3",
... | Assuming that the convention of naming resources associated with tasks as
res[TASK][number], reduces such resource names to just the name of the
task. This ensures that multiple copies of the same resource are treated
the same. Resource names of different formats will be left untouched. | [
"Assuming",
"that",
"the",
"convention",
"of",
"naming",
"resources",
"associated",
"with",
"tasks",
"as",
"res",
"[",
"TASK",
"]",
"[",
"number",
"]",
"reduces",
"such",
"resource",
"names",
"to",
"just",
"the",
"name",
"of",
"the",
"task",
".",
"This",
... | train | https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/parse_files.py#L127-L140 |
emilydolson/avida-spatial-tools | avidaspatial/parse_files.py | parse_environment_file | def parse_environment_file(filename, world_size=(60, 60)):
"""
Extract information about spatial resources from an environment file.
Arguments:
filename - a string representing the path to the environment file.
world_size - a tuple representing the x and y coordinates of the world.
... | python | def parse_environment_file(filename, world_size=(60, 60)):
"""
Extract information about spatial resources from an environment file.
Arguments:
filename - a string representing the path to the environment file.
world_size - a tuple representing the x and y coordinates of the world.
... | [
"def",
"parse_environment_file",
"(",
"filename",
",",
"world_size",
"=",
"(",
"60",
",",
"60",
")",
")",
":",
"infile",
"=",
"open",
"(",
"filename",
")",
"lines",
"=",
"infile",
".",
"readlines",
"(",
")",
"infile",
".",
"close",
"(",
")",
"tasks",
... | Extract information about spatial resources from an environment file.
Arguments:
filename - a string representing the path to the environment file.
world_size - a tuple representing the x and y coordinates of the world.
(default: 60x60)
Returns a list of lists of sets indicating the s... | [
"Extract",
"information",
"about",
"spatial",
"resources",
"from",
"an",
"environment",
"file",
"."
] | train | https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/parse_files.py#L143-L184 |
emilydolson/avida-spatial-tools | avidaspatial/parse_files.py | parse_gradient | def parse_gradient(line, world_size):
"""
Takes a string representing a GRADIENT_RESOURCE (as specified in Avida
environment files) and a tuple representing the x and y dimensions of the
world, and returns the name of the gradient resource and a list of
tuples representing the cells it's in.
"""... | python | def parse_gradient(line, world_size):
"""
Takes a string representing a GRADIENT_RESOURCE (as specified in Avida
environment files) and a tuple representing the x and y dimensions of the
world, and returns the name of the gradient resource and a list of
tuples representing the cells it's in.
"""... | [
"def",
"parse_gradient",
"(",
"line",
",",
"world_size",
")",
":",
"# remove \"GRADIENT_RESOURCE\"",
"line",
"=",
"line",
"[",
"18",
":",
"]",
"sline",
"=",
"[",
"el",
".",
"strip",
"(",
")",
"for",
"el",
"in",
"line",
".",
"split",
"(",
"\":\"",
")",
... | Takes a string representing a GRADIENT_RESOURCE (as specified in Avida
environment files) and a tuple representing the x and y dimensions of the
world, and returns the name of the gradient resource and a list of
tuples representing the cells it's in. | [
"Takes",
"a",
"string",
"representing",
"a",
"GRADIENT_RESOURCE",
"(",
"as",
"specified",
"in",
"Avida",
"environment",
"files",
")",
"and",
"a",
"tuple",
"representing",
"the",
"x",
"and",
"y",
"dimensions",
"of",
"the",
"world",
"and",
"returns",
"the",
"n... | train | https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/parse_files.py#L196-L229 |
emilydolson/avida-spatial-tools | avidaspatial/parse_files.py | parse_cell | def parse_cell(line, world_size):
"""
Takes a string representing a CELL resource (as specified in Avida
environment files) and a tuple representing the x and y dimensions of the
world, and returns the name of the resource and a list of
tuples representing the cells it's in.
"""
# Remove "CE... | python | def parse_cell(line, world_size):
"""
Takes a string representing a CELL resource (as specified in Avida
environment files) and a tuple representing the x and y dimensions of the
world, and returns the name of the resource and a list of
tuples representing the cells it's in.
"""
# Remove "CE... | [
"def",
"parse_cell",
"(",
"line",
",",
"world_size",
")",
":",
"# Remove \"CELL \"",
"line",
"=",
"line",
"[",
"4",
":",
"]",
"# Extract information",
"sline",
"=",
"[",
"i",
".",
"strip",
"(",
")",
"for",
"i",
"in",
"line",
".",
"split",
"(",
"\":\"",... | Takes a string representing a CELL resource (as specified in Avida
environment files) and a tuple representing the x and y dimensions of the
world, and returns the name of the resource and a list of
tuples representing the cells it's in. | [
"Takes",
"a",
"string",
"representing",
"a",
"CELL",
"resource",
"(",
"as",
"specified",
"in",
"Avida",
"environment",
"files",
")",
"and",
"a",
"tuple",
"representing",
"the",
"x",
"and",
"y",
"dimensions",
"of",
"the",
"world",
"and",
"returns",
"the",
"... | train | https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/parse_files.py#L232-L263 |
CenterForOpenScience/sharepa | sharepa/experimental_analysis_functions.py | convert_nested_to_dataframe | def convert_nested_to_dataframe(agg, dates_as_key=True):
'''A function that takes nested elasticsearch response with aggregation and returns a nested dataframe
Warning: This is a recursive function, and rather non-intuitive to understand
This function takes nested and crossed aggregations and conve... | python | def convert_nested_to_dataframe(agg, dates_as_key=True):
'''A function that takes nested elasticsearch response with aggregation and returns a nested dataframe
Warning: This is a recursive function, and rather non-intuitive to understand
This function takes nested and crossed aggregations and conve... | [
"def",
"convert_nested_to_dataframe",
"(",
"agg",
",",
"dates_as_key",
"=",
"True",
")",
":",
"crossed_cats_expanded",
"=",
"[",
"]",
"high_level_returning",
"=",
"False",
"agg_as_dict",
"=",
"agg",
".",
"to_dict",
"(",
")",
"cat_names",
"=",
"[",
"item",
"for... | A function that takes nested elasticsearch response with aggregation and returns a nested dataframe
Warning: This is a recursive function, and rather non-intuitive to understand
This function takes nested and crossed aggregations and converts them to an easy to manipulates pandas dataframe
e.g... | [
"A",
"function",
"that",
"takes",
"nested",
"elasticsearch",
"response",
"with",
"aggregation",
"and",
"returns",
"a",
"nested",
"dataframe",
"Warning",
":",
"This",
"is",
"a",
"recursive",
"function",
"and",
"rather",
"non",
"-",
"intuitive",
"to",
"understand"... | train | https://github.com/CenterForOpenScience/sharepa/blob/5ea69b160080f0b9c655012f17fabaa1bcc02ae0/sharepa/experimental_analysis_functions.py#L4-L78 |
CenterForOpenScience/sharepa | sharepa/experimental_analysis_functions.py | add_category_labels | def add_category_labels(level_name, cat_name, dataframe_needing_cat):
'''A function that adds a category name column to a pandas dataframe
:param level_name: an aggregation from elasticsearch results with nesting
:type level_name: elasticsearch response.aggregation object
:param cat_name: a... | python | def add_category_labels(level_name, cat_name, dataframe_needing_cat):
'''A function that adds a category name column to a pandas dataframe
:param level_name: an aggregation from elasticsearch results with nesting
:type level_name: elasticsearch response.aggregation object
:param cat_name: a... | [
"def",
"add_category_labels",
"(",
"level_name",
",",
"cat_name",
",",
"dataframe_needing_cat",
")",
":",
"cat_name_dataframe",
"=",
"pd",
".",
"DataFrame",
"(",
"[",
"level_name",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"dataframe_needing_cat",
".",
"shape",
... | A function that adds a category name column to a pandas dataframe
:param level_name: an aggregation from elasticsearch results with nesting
:type level_name: elasticsearch response.aggregation object
:param cat_name: an aggregation from elasticsearch results with nesting
:type cat_name:... | [
"A",
"function",
"that",
"adds",
"a",
"category",
"name",
"column",
"to",
"a",
"pandas",
"dataframe"
] | train | https://github.com/CenterForOpenScience/sharepa/blob/5ea69b160080f0b9c655012f17fabaa1bcc02ae0/sharepa/experimental_analysis_functions.py#L81-L95 |
siemens/django-dingos | dingos/core/datastructures.py | dict2tuple | def dict2tuple(mydict):
"""
Turn a dictionary of the form used by DINGO
(i.e., a key is mapped to either another dictionary,
a list or a value) into a tuple-representation.
This is useful for providing a standard python object that
observes the order of elements (which standard dictionaries don'... | python | def dict2tuple(mydict):
"""
Turn a dictionary of the form used by DINGO
(i.e., a key is mapped to either another dictionary,
a list or a value) into a tuple-representation.
This is useful for providing a standard python object that
observes the order of elements (which standard dictionaries don'... | [
"def",
"dict2tuple",
"(",
"mydict",
")",
":",
"result",
"=",
"[",
"]",
"for",
"key",
"in",
"mydict",
".",
"keys",
"(",
")",
":",
"# There are three cases we need to consider:",
"# dictionary, list, and other values",
"try",
":",
"# We test whether the object is a dictio... | Turn a dictionary of the form used by DINGO
(i.e., a key is mapped to either another dictionary,
a list or a value) into a tuple-representation.
This is useful for providing a standard python object that
observes the order of elements (which standard dictionaries don't). | [
"Turn",
"a",
"dictionary",
"of",
"the",
"form",
"used",
"by",
"DINGO",
"(",
"i",
".",
"e",
".",
"a",
"key",
"is",
"mapped",
"to",
"either",
"another",
"dictionary",
"a",
"list",
"or",
"a",
"value",
")",
"into",
"a",
"tuple",
"-",
"representation",
".... | train | https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/core/datastructures.py#L29-L55 |
siemens/django-dingos | dingos/core/datastructures.py | tuple2dict | def tuple2dict(mytuple, constructor=dict):
"""
Turn a tuple as returned by dict2tuple back
into a dictionary structure. The optional
parameter "constructor" governs, what class
is used to create the dictionary: by default,
the standard dict class is used, but in DINGO
we mostly use the Dingo... | python | def tuple2dict(mytuple, constructor=dict):
"""
Turn a tuple as returned by dict2tuple back
into a dictionary structure. The optional
parameter "constructor" governs, what class
is used to create the dictionary: by default,
the standard dict class is used, but in DINGO
we mostly use the Dingo... | [
"def",
"tuple2dict",
"(",
"mytuple",
",",
"constructor",
"=",
"dict",
")",
":",
"result",
"=",
"constructor",
"(",
")",
"for",
"elt",
"in",
"mytuple",
":",
"key",
",",
"value",
"=",
"elt",
"if",
"type",
"(",
"value",
")",
"==",
"type",
"(",
"(",
")... | Turn a tuple as returned by dict2tuple back
into a dictionary structure. The optional
parameter "constructor" governs, what class
is used to create the dictionary: by default,
the standard dict class is used, but in DINGO
we mostly use the DingoObjDict class. | [
"Turn",
"a",
"tuple",
"as",
"returned",
"by",
"dict2tuple",
"back",
"into",
"a",
"dictionary",
"structure",
".",
"The",
"optional",
"parameter",
"constructor",
"governs",
"what",
"class",
"is",
"used",
"to",
"create",
"the",
"dictionary",
":",
"by",
"default",... | train | https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/core/datastructures.py#L58-L79 |
siemens/django-dingos | dingos/core/datastructures.py | dict2DingoObjDict | def dict2DingoObjDict(data):
"""
Turn a dictionary of the form used by DINGO
(i.e., a key is mapped to either another dictionary,
a list or a value) into a DingoObjDict.
"""
info_tuple = dict2tuple(data)
info_dict = tuple2dict(info_tuple, constructor=DingoObjDict)
return info_dict | python | def dict2DingoObjDict(data):
"""
Turn a dictionary of the form used by DINGO
(i.e., a key is mapped to either another dictionary,
a list or a value) into a DingoObjDict.
"""
info_tuple = dict2tuple(data)
info_dict = tuple2dict(info_tuple, constructor=DingoObjDict)
return info_dict | [
"def",
"dict2DingoObjDict",
"(",
"data",
")",
":",
"info_tuple",
"=",
"dict2tuple",
"(",
"data",
")",
"info_dict",
"=",
"tuple2dict",
"(",
"info_tuple",
",",
"constructor",
"=",
"DingoObjDict",
")",
"return",
"info_dict"
] | Turn a dictionary of the form used by DINGO
(i.e., a key is mapped to either another dictionary,
a list or a value) into a DingoObjDict. | [
"Turn",
"a",
"dictionary",
"of",
"the",
"form",
"used",
"by",
"DINGO",
"(",
"i",
".",
"e",
".",
"a",
"key",
"is",
"mapped",
"to",
"either",
"another",
"dictionary",
"a",
"list",
"or",
"a",
"value",
")",
"into",
"a",
"DingoObjDict",
"."
] | train | https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/core/datastructures.py#L641-L649 |
siemens/django-dingos | dingos/core/datastructures.py | ExtendedSortedDict.chained_get | def chained_get(self, *keys):
"""
This function allows traversals over several keys to
be performed by passing a list of keys::
d.chained_get(key1,key2,key3) = d[key1][key2][key3]
"""
existing = self
for i in range(0, len(keys)):
if keys[i] in ex... | python | def chained_get(self, *keys):
"""
This function allows traversals over several keys to
be performed by passing a list of keys::
d.chained_get(key1,key2,key3) = d[key1][key2][key3]
"""
existing = self
for i in range(0, len(keys)):
if keys[i] in ex... | [
"def",
"chained_get",
"(",
"self",
",",
"*",
"keys",
")",
":",
"existing",
"=",
"self",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"keys",
")",
")",
":",
"if",
"keys",
"[",
"i",
"]",
"in",
"existing",
":",
"existing",
"=",
"existing",
... | This function allows traversals over several keys to
be performed by passing a list of keys::
d.chained_get(key1,key2,key3) = d[key1][key2][key3] | [
"This",
"function",
"allows",
"traversals",
"over",
"several",
"keys",
"to",
"be",
"performed",
"by",
"passing",
"a",
"list",
"of",
"keys",
"::"
] | train | https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/core/datastructures.py#L113-L127 |
siemens/django-dingos | dingos/core/datastructures.py | ExtendedSortedDict.chained_set | def chained_set(self, value, command='set', *keys):
"""
chained_set takes the value to
enter into the dictionary, a command of what
to do with the value, and a sequence of keys.
Examples:
d = {}
d.chained_set(1,'append','level 1','level 2')
-> d['level... | python | def chained_set(self, value, command='set', *keys):
"""
chained_set takes the value to
enter into the dictionary, a command of what
to do with the value, and a sequence of keys.
Examples:
d = {}
d.chained_set(1,'append','level 1','level 2')
-> d['level... | [
"def",
"chained_set",
"(",
"self",
",",
"value",
",",
"command",
"=",
"'set'",
",",
"*",
"keys",
")",
":",
"new_object",
"=",
"self",
".",
"__class__",
"(",
")",
"existing",
"=",
"self",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"keys",... | chained_set takes the value to
enter into the dictionary, a command of what
to do with the value, and a sequence of keys.
Examples:
d = {}
d.chained_set(1,'append','level 1','level 2')
-> d['level 1']['level 2'] = [1]
d.chained_set(2,'append','level 1','level... | [
"chained_set",
"takes",
"the",
"value",
"to",
"enter",
"into",
"the",
"dictionary",
"a",
"command",
"of",
"what",
"to",
"do",
"with",
"the",
"value",
"and",
"a",
"sequence",
"of",
"keys",
"."
] | train | https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/core/datastructures.py#L129-L177 |
siemens/django-dingos | dingos/core/datastructures.py | DingoObjDict.flatten | def flatten(self, attr_ignore_predicate=None,force_nonleaf_fact_predicate=None,namespace_dict=None):
"""
Flatten a Dingo dictionary representation of into a list
of fact-term/value pairs and associated information about tree structure (in node_id)
and a dictionary mapping XML attributes ... | python | def flatten(self, attr_ignore_predicate=None,force_nonleaf_fact_predicate=None,namespace_dict=None):
"""
Flatten a Dingo dictionary representation of into a list
of fact-term/value pairs and associated information about tree structure (in node_id)
and a dictionary mapping XML attributes ... | [
"def",
"flatten",
"(",
"self",
",",
"attr_ignore_predicate",
"=",
"None",
",",
"force_nonleaf_fact_predicate",
"=",
"None",
",",
"namespace_dict",
"=",
"None",
")",
":",
"if",
"not",
"namespace_dict",
":",
"namespace_dict",
"=",
"{",
"}",
"def",
"node_id_gen",
... | Flatten a Dingo dictionary representation of into a list
of fact-term/value pairs and associated information about tree structure (in node_id)
and a dictionary mapping XML attributes to node identifiers.
This all is best explained by example (see below).
Note that attributes are also r... | [
"Flatten",
"a",
"Dingo",
"dictionary",
"representation",
"of",
"into",
"a",
"list",
"of",
"fact",
"-",
"term",
"/",
"value",
"pairs",
"and",
"associated",
"information",
"about",
"tree",
"structure",
"(",
"in",
"node_id",
")",
"and",
"a",
"dictionary",
"mapp... | train | https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/core/datastructures.py#L200-L435 |
siemens/django-dingos | dingos/core/datastructures.py | DingoObjDict.from_flat_repr | def from_flat_repr(self,fact_list,include_node_id=False,no_attributes=False,track_namespaces=True,namespace_mapping=None):
"""
Convert a flat representation of information (consisting of a fact list and a dictionary
mapping node ids to attributes into a dictionary representation information.
... | python | def from_flat_repr(self,fact_list,include_node_id=False,no_attributes=False,track_namespaces=True,namespace_mapping=None):
"""
Convert a flat representation of information (consisting of a fact list and a dictionary
mapping node ids to attributes into a dictionary representation information.
... | [
"def",
"from_flat_repr",
"(",
"self",
",",
"fact_list",
",",
"include_node_id",
"=",
"False",
",",
"no_attributes",
"=",
"False",
",",
"track_namespaces",
"=",
"True",
",",
"namespace_mapping",
"=",
"None",
")",
":",
"if",
"not",
"namespace_mapping",
":",
"nam... | Convert a flat representation of information (consisting of a fact list and a dictionary
mapping node ids to attributes into a dictionary representation information.
Input Example (CybOx)::
{ '00': { 'condition': 'Equals', 'datatype': 'String'},
'01:L00:00': { 'condition': 'Equa... | [
"Convert",
"a",
"flat",
"representation",
"of",
"information",
"(",
"consisting",
"of",
"a",
"fact",
"list",
"and",
"a",
"dictionary",
"mapping",
"node",
"ids",
"to",
"attributes",
"into",
"a",
"dictionary",
"representation",
"information",
"."
] | train | https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/core/datastructures.py#L437-L634 |
usc-isi-i2/dig-extractor | digExtractor/extractor.py | Extractor.set_renamed_input_fields | def set_renamed_input_fields(self, renamed_input_fields):
"""This method expects a scalar string or a list of input_fields
to """
if not (isinstance(renamed_input_fields, basestring) or
isinstance(renamed_input_fields, ListType)):
raise ValueError("renamed_input_field... | python | def set_renamed_input_fields(self, renamed_input_fields):
"""This method expects a scalar string or a list of input_fields
to """
if not (isinstance(renamed_input_fields, basestring) or
isinstance(renamed_input_fields, ListType)):
raise ValueError("renamed_input_field... | [
"def",
"set_renamed_input_fields",
"(",
"self",
",",
"renamed_input_fields",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"renamed_input_fields",
",",
"basestring",
")",
"or",
"isinstance",
"(",
"renamed_input_fields",
",",
"ListType",
")",
")",
":",
"raise",
... | This method expects a scalar string or a list of input_fields
to | [
"This",
"method",
"expects",
"a",
"scalar",
"string",
"or",
"a",
"list",
"of",
"input_fields",
"to"
] | train | https://github.com/usc-isi-i2/dig-extractor/blob/87c138e0300d77e35ebeb5f5e9488c3d71e60eb3/digExtractor/extractor.py#L36-L43 |
wooga/play-deliver | playdeliver/file_util.py | list_dir_abspath | def list_dir_abspath(path):
"""
Return a list absolute file paths.
see mkdir_p os.listdir.
"""
return map(lambda f: os.path.join(path, f), os.listdir(path)) | python | def list_dir_abspath(path):
"""
Return a list absolute file paths.
see mkdir_p os.listdir.
"""
return map(lambda f: os.path.join(path, f), os.listdir(path)) | [
"def",
"list_dir_abspath",
"(",
"path",
")",
":",
"return",
"map",
"(",
"lambda",
"f",
":",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"f",
")",
",",
"os",
".",
"listdir",
"(",
"path",
")",
")"
] | Return a list absolute file paths.
see mkdir_p os.listdir. | [
"Return",
"a",
"list",
"absolute",
"file",
"paths",
"."
] | train | https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/file_util.py#L7-L13 |
tarvitz/django-unity-asset-server-http-client | duashttp/models.py | AssetVersion.get_digest | def get_digest(self):
""" return int uuid number for digest
:rtype: int
:return: digest
"""
a, b = struct.unpack('>QQ', self.digest)
return (a << 64) | b | python | def get_digest(self):
""" return int uuid number for digest
:rtype: int
:return: digest
"""
a, b = struct.unpack('>QQ', self.digest)
return (a << 64) | b | [
"def",
"get_digest",
"(",
"self",
")",
":",
"a",
",",
"b",
"=",
"struct",
".",
"unpack",
"(",
"'>QQ'",
",",
"self",
".",
"digest",
")",
"return",
"(",
"a",
"<<",
"64",
")",
"|",
"b"
] | return int uuid number for digest
:rtype: int
:return: digest | [
"return",
"int",
"uuid",
"number",
"for",
"digest"
] | train | https://github.com/tarvitz/django-unity-asset-server-http-client/blob/2b7e3b1116b5e98b31c2e267bdd66a77e0579ad1/duashttp/models.py#L102-L109 |
tarvitz/django-unity-asset-server-http-client | duashttp/models.py | AssetVersion.get_blob_hash | def get_blob_hash(self, h=hashlib.md5):
"""
get hash instance of blob content
:param h: callable hash generator
:type h: builtin_function_or_method
:rtype: _hashlib.HASH
:return: hash instance
"""
assert callable(h)
return h(self.get_blob_data()) | python | def get_blob_hash(self, h=hashlib.md5):
"""
get hash instance of blob content
:param h: callable hash generator
:type h: builtin_function_or_method
:rtype: _hashlib.HASH
:return: hash instance
"""
assert callable(h)
return h(self.get_blob_data()) | [
"def",
"get_blob_hash",
"(",
"self",
",",
"h",
"=",
"hashlib",
".",
"md5",
")",
":",
"assert",
"callable",
"(",
"h",
")",
"return",
"h",
"(",
"self",
".",
"get_blob_data",
"(",
")",
")"
] | get hash instance of blob content
:param h: callable hash generator
:type h: builtin_function_or_method
:rtype: _hashlib.HASH
:return: hash instance | [
"get",
"hash",
"instance",
"of",
"blob",
"content"
] | train | https://github.com/tarvitz/django-unity-asset-server-http-client/blob/2b7e3b1116b5e98b31c2e267bdd66a77e0579ad1/duashttp/models.py#L111-L121 |
tarvitz/django-unity-asset-server-http-client | duashttp/models.py | AssetVersion.get_blob_data | def get_blob_data(self, tag_target='asset', force=False):
"""
get asset version content using pg large object streams
:param bool force: False by default, forces get content from database
instead of using cached value
:rtype: str
:return: content in raw format
... | python | def get_blob_data(self, tag_target='asset', force=False):
"""
get asset version content using pg large object streams
:param bool force: False by default, forces get content from database
instead of using cached value
:rtype: str
:return: content in raw format
... | [
"def",
"get_blob_data",
"(",
"self",
",",
"tag_target",
"=",
"'asset'",
",",
"force",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_blob_data'",
")",
"and",
"not",
"force",
":",
"return",
"self",
".",
"_blob_data",
"if",
"six",
".",
"PY... | get asset version content using pg large object streams
:param bool force: False by default, forces get content from database
instead of using cached value
:rtype: str
:return: content in raw format | [
"get",
"asset",
"version",
"content",
"using",
"pg",
"large",
"object",
"streams"
] | train | https://github.com/tarvitz/django-unity-asset-server-http-client/blob/2b7e3b1116b5e98b31c2e267bdd66a77e0579ad1/duashttp/models.py#L123-L144 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/action.py | ActionUnit.run | def run(self, obj):
"""Execute the actions on the given object.
:param obj: The object that the action should process
:type obj: :class:`object`
:returns: None
:rtype: None
:raises: None
"""
for d in self.depsuccess:
if d.status.value != Actio... | python | def run(self, obj):
"""Execute the actions on the given object.
:param obj: The object that the action should process
:type obj: :class:`object`
:returns: None
:rtype: None
:raises: None
"""
for d in self.depsuccess:
if d.status.value != Actio... | [
"def",
"run",
"(",
"self",
",",
"obj",
")",
":",
"for",
"d",
"in",
"self",
".",
"depsuccess",
":",
"if",
"d",
".",
"status",
".",
"value",
"!=",
"ActionStatus",
".",
"SUCCESS",
":",
"self",
".",
"status",
"=",
"ActionStatus",
"(",
"ActionStatus",
"."... | Execute the actions on the given object.
:param obj: The object that the action should process
:type obj: :class:`object`
:returns: None
:rtype: None
:raises: None | [
"Execute",
"the",
"actions",
"on",
"the",
"given",
"object",
"."
] | train | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/action.py#L109-L131 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/action.py | ActionCollection.status | def status(self, ):
"""The global status that summerizes all actions
The status will be calculated in the following order:
If any error occured, the status will be :data:`ActionStatus.ERROR`.
If any failure occured, the status will be :data:`ActionStatus.FAILURE`.
If all ... | python | def status(self, ):
"""The global status that summerizes all actions
The status will be calculated in the following order:
If any error occured, the status will be :data:`ActionStatus.ERROR`.
If any failure occured, the status will be :data:`ActionStatus.FAILURE`.
If all ... | [
"def",
"status",
"(",
"self",
",",
")",
":",
"status",
"=",
"ActionStatus",
"(",
"ActionStatus",
".",
"SUCCESS",
",",
"\"All actions succeeded.\"",
")",
"for",
"a",
"in",
"self",
".",
"actions",
":",
"if",
"a",
".",
"status",
".",
"value",
"==",
"ActionS... | The global status that summerizes all actions
The status will be calculated in the following order:
If any error occured, the status will be :data:`ActionStatus.ERROR`.
If any failure occured, the status will be :data:`ActionStatus.FAILURE`.
If all actions were successful or skip... | [
"The",
"global",
"status",
"that",
"summerizes",
"all",
"actions"
] | train | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/action.py#L169-L189 |
vmalloc/dessert | dessert/util.py | format_explanation | def format_explanation(explanation, original_msg=None):
"""This formats an explanation
Normally all embedded newlines are escaped, however there are
three exceptions: \n{, \n} and \n~. The first two are intended
cover nested explanations, see function and attribute explanations
for examples (.visi... | python | def format_explanation(explanation, original_msg=None):
"""This formats an explanation
Normally all embedded newlines are escaped, however there are
three exceptions: \n{, \n} and \n~. The first two are intended
cover nested explanations, see function and attribute explanations
for examples (.visi... | [
"def",
"format_explanation",
"(",
"explanation",
",",
"original_msg",
"=",
"None",
")",
":",
"if",
"not",
"conf",
".",
"is_message_introspection_enabled",
"(",
")",
"and",
"original_msg",
":",
"return",
"original_msg",
"explanation",
"=",
"ecu",
"(",
"explanation"... | This formats an explanation
Normally all embedded newlines are escaped, however there are
three exceptions: \n{, \n} and \n~. The first two are intended
cover nested explanations, see function and attribute explanations
for examples (.visit_Call(), visit_Attribute()). The last one is
for when one... | [
"This",
"formats",
"an",
"explanation"
] | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/util.py#L33-L48 |
vmalloc/dessert | dessert/util.py | _split_explanation | def _split_explanation(explanation):
"""Return a list of individual lines in the explanation
This will return a list of lines split on '\n{', '\n}' and '\n~'.
Any other newlines will be escaped and appear in the line as the
literal '\n' characters.
"""
raw_lines = (explanation or u('')).split('... | python | def _split_explanation(explanation):
"""Return a list of individual lines in the explanation
This will return a list of lines split on '\n{', '\n}' and '\n~'.
Any other newlines will be escaped and appear in the line as the
literal '\n' characters.
"""
raw_lines = (explanation or u('')).split('... | [
"def",
"_split_explanation",
"(",
"explanation",
")",
":",
"raw_lines",
"=",
"(",
"explanation",
"or",
"u",
"(",
"''",
")",
")",
".",
"split",
"(",
"'\\n'",
")",
"lines",
"=",
"[",
"raw_lines",
"[",
"0",
"]",
"]",
"for",
"l",
"in",
"raw_lines",
"[",
... | Return a list of individual lines in the explanation
This will return a list of lines split on '\n{', '\n}' and '\n~'.
Any other newlines will be escaped and appear in the line as the
literal '\n' characters. | [
"Return",
"a",
"list",
"of",
"individual",
"lines",
"in",
"the",
"explanation"
] | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/util.py#L51-L65 |
vmalloc/dessert | dessert/util.py | _format_lines | def _format_lines(lines):
"""Format the individual lines
This will replace the '{', '}' and '~' characters of our mini
formatting language with the proper 'where ...', 'and ...' and ' +
...' text, taking care of indentation along the way.
Return a list of formatted lines.
"""
result = line... | python | def _format_lines(lines):
"""Format the individual lines
This will replace the '{', '}' and '~' characters of our mini
formatting language with the proper 'where ...', 'and ...' and ' +
...' text, taking care of indentation along the way.
Return a list of formatted lines.
"""
result = line... | [
"def",
"_format_lines",
"(",
"lines",
")",
":",
"result",
"=",
"lines",
"[",
":",
"1",
"]",
"stack",
"=",
"[",
"0",
"]",
"stackcnt",
"=",
"[",
"0",
"]",
"for",
"line",
"in",
"lines",
"[",
"1",
":",
"]",
":",
"if",
"line",
".",
"startswith",
"("... | Format the individual lines
This will replace the '{', '}' and '~' characters of our mini
formatting language with the proper 'where ...', 'and ...' and ' +
...' text, taking care of indentation along the way.
Return a list of formatted lines. | [
"Format",
"the",
"individual",
"lines"
] | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/util.py#L68-L100 |
vmalloc/dessert | dessert/util.py | assertrepr_compare | def assertrepr_compare(config, op, left, right):
"""Return specialised explanations for some operators/operands"""
width = 80 - 15 - len(op) - 2 # 15 chars indentation, 1 space around op
left_repr = py.io.saferepr(left, maxsize=int(width//2))
right_repr = py.io.saferepr(right, maxsize=width-len(left_re... | python | def assertrepr_compare(config, op, left, right):
"""Return specialised explanations for some operators/operands"""
width = 80 - 15 - len(op) - 2 # 15 chars indentation, 1 space around op
left_repr = py.io.saferepr(left, maxsize=int(width//2))
right_repr = py.io.saferepr(right, maxsize=width-len(left_re... | [
"def",
"assertrepr_compare",
"(",
"config",
",",
"op",
",",
"left",
",",
"right",
")",
":",
"width",
"=",
"80",
"-",
"15",
"-",
"len",
"(",
"op",
")",
"-",
"2",
"# 15 chars indentation, 1 space around op",
"left_repr",
"=",
"py",
".",
"io",
".",
"saferep... | Return specialised explanations for some operators/operands | [
"Return",
"specialised",
"explanations",
"for",
"some",
"operators",
"/",
"operands"
] | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/util.py#L110-L160 |
vmalloc/dessert | dessert/util.py | _diff_text | def _diff_text(left, right, verbose=False):
"""Return the explanation for the diff between text or bytes
Unless --verbose is used this will skip leading and trailing
characters which are identical to keep the diff minimal.
If the input are bytes they will be safely converted to text.
"""
from ... | python | def _diff_text(left, right, verbose=False):
"""Return the explanation for the diff between text or bytes
Unless --verbose is used this will skip leading and trailing
characters which are identical to keep the diff minimal.
If the input are bytes they will be safely converted to text.
"""
from ... | [
"def",
"_diff_text",
"(",
"left",
",",
"right",
",",
"verbose",
"=",
"False",
")",
":",
"from",
"difflib",
"import",
"ndiff",
"explanation",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"left",
",",
"py",
".",
"builtin",
".",
"bytes",
")",
":",
"left",
"=... | Return the explanation for the diff between text or bytes
Unless --verbose is used this will skip leading and trailing
characters which are identical to keep the diff minimal.
If the input are bytes they will be safely converted to text. | [
"Return",
"the",
"explanation",
"for",
"the",
"diff",
"between",
"text",
"or",
"bytes"
] | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/util.py#L163-L202 |
jespino/anillo | anillo/middlewares/cors.py | wrap_cors | def wrap_cors(func=None, *, allow_origin='*', allow_headers=DEFAULT_HEADERS):
"""
A middleware that allow CORS calls, by adding the
headers Access-Control-Allow-Origin and Access-Control-Allow-Headers.
This middlware accepts two optional parameters `allow_origin` and
`allow_headers` for customizatio... | python | def wrap_cors(func=None, *, allow_origin='*', allow_headers=DEFAULT_HEADERS):
"""
A middleware that allow CORS calls, by adding the
headers Access-Control-Allow-Origin and Access-Control-Allow-Headers.
This middlware accepts two optional parameters `allow_origin` and
`allow_headers` for customizatio... | [
"def",
"wrap_cors",
"(",
"func",
"=",
"None",
",",
"*",
",",
"allow_origin",
"=",
"'*'",
",",
"allow_headers",
"=",
"DEFAULT_HEADERS",
")",
":",
"if",
"func",
"is",
"None",
":",
"return",
"functools",
".",
"partial",
"(",
"wrap_cors",
",",
"allow_origin",
... | A middleware that allow CORS calls, by adding the
headers Access-Control-Allow-Origin and Access-Control-Allow-Headers.
This middlware accepts two optional parameters `allow_origin` and
`allow_headers` for customization of the headers values. By default
will be `*` and a set of `[Origin, X-Requested-Wit... | [
"A",
"middleware",
"that",
"allow",
"CORS",
"calls",
"by",
"adding",
"the",
"headers",
"Access",
"-",
"Control",
"-",
"Allow",
"-",
"Origin",
"and",
"Access",
"-",
"Control",
"-",
"Allow",
"-",
"Headers",
".",
"This",
"middlware",
"accepts",
"two",
"option... | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/middlewares/cors.py#L6-L34 |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/validate/Schema.py | Schema.with_rule | def with_rule(self, rule):
"""
Adds validation rule to this schema.
This method returns reference to this exception to implement Builder pattern
to chain additional calls.
:param rule: a validation rule to be added.
:return: this validation schema.
"""
... | python | def with_rule(self, rule):
"""
Adds validation rule to this schema.
This method returns reference to this exception to implement Builder pattern
to chain additional calls.
:param rule: a validation rule to be added.
:return: this validation schema.
"""
... | [
"def",
"with_rule",
"(",
"self",
",",
"rule",
")",
":",
"self",
".",
"rules",
"=",
"self",
".",
"rules",
"if",
"self",
".",
"rules",
"!=",
"None",
"else",
"[",
"]",
"self",
".",
"rules",
".",
"append",
"(",
"rule",
")",
"return",
"self"
] | Adds validation rule to this schema.
This method returns reference to this exception to implement Builder pattern
to chain additional calls.
:param rule: a validation rule to be added.
:return: this validation schema. | [
"Adds",
"validation",
"rule",
"to",
"this",
"schema",
"."
] | train | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/validate/Schema.py#L66-L79 |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/validate/Schema.py | Schema._perform_validation | def _perform_validation(self, path, value, results):
"""
Validates a given value against the schema and configured validation rules.
:param path: a dot notation path to the value.
:param value: a value to be validated.
:param results: a list with validation results to add new ... | python | def _perform_validation(self, path, value, results):
"""
Validates a given value against the schema and configured validation rules.
:param path: a dot notation path to the value.
:param value: a value to be validated.
:param results: a list with validation results to add new ... | [
"def",
"_perform_validation",
"(",
"self",
",",
"path",
",",
"value",
",",
"results",
")",
":",
"name",
"=",
"path",
"if",
"path",
"!=",
"None",
"else",
"\"value\"",
"if",
"value",
"==",
"None",
":",
"# Check for required values",
"if",
"self",
".",
"requi... | Validates a given value against the schema and configured validation rules.
:param path: a dot notation path to the value.
:param value: a value to be validated.
:param results: a list with validation results to add new results. | [
"Validates",
"a",
"given",
"value",
"against",
"the",
"schema",
"and",
"configured",
"validation",
"rules",
"."
] | train | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/validate/Schema.py#L81-L112 |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/validate/Schema.py | Schema._perform_type_validation | def _perform_type_validation(self, path, typ, value, results):
"""
Validates a given value to match specified type.
The type can be defined as a Schema, type, a type name or [[TypeCode]].
When type is a Schema, it executes validation recursively against that Schema.
:param path:... | python | def _perform_type_validation(self, path, typ, value, results):
"""
Validates a given value to match specified type.
The type can be defined as a Schema, type, a type name or [[TypeCode]].
When type is a Schema, it executes validation recursively against that Schema.
:param path:... | [
"def",
"_perform_type_validation",
"(",
"self",
",",
"path",
",",
"typ",
",",
"value",
",",
"results",
")",
":",
"# If type it not defined then skip",
"if",
"typ",
"==",
"None",
":",
"return",
"# Perform validation against schema",
"if",
"isinstance",
"(",
"typ",
... | Validates a given value to match specified type.
The type can be defined as a Schema, type, a type name or [[TypeCode]].
When type is a Schema, it executes validation recursively against that Schema.
:param path: a dot notation path to the value.
:param typ: a type to match the value t... | [
"Validates",
"a",
"given",
"value",
"to",
"match",
"specified",
"type",
".",
"The",
"type",
"can",
"be",
"defined",
"as",
"a",
"Schema",
"type",
"a",
"type",
"name",
"or",
"[[",
"TypeCode",
"]]",
".",
"When",
"type",
"is",
"a",
"Schema",
"it",
"execute... | train | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/validate/Schema.py#L119-L165 |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/validate/Schema.py | Schema.validate_and_throw_exception | def validate_and_throw_exception(self, correlation_id, value, strict = False):
"""
Validates the given value and throws a [[ValidationException]] if errors were found.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param value: a value to be va... | python | def validate_and_throw_exception(self, correlation_id, value, strict = False):
"""
Validates the given value and throws a [[ValidationException]] if errors were found.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param value: a value to be va... | [
"def",
"validate_and_throw_exception",
"(",
"self",
",",
"correlation_id",
",",
"value",
",",
"strict",
"=",
"False",
")",
":",
"results",
"=",
"self",
".",
"validate",
"(",
"value",
")",
"ValidationException",
".",
"throw_exception_if_needed",
"(",
"correlation_i... | Validates the given value and throws a [[ValidationException]] if errors were found.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param value: a value to be validated.
:param strict: true to treat warnings as errors. | [
"Validates",
"the",
"given",
"value",
"and",
"throws",
"a",
"[[",
"ValidationException",
"]]",
"if",
"errors",
"were",
"found",
"."
] | train | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/validate/Schema.py#L179-L190 |
wickman/compactor | compactor/context.py | Context._make_socket | def _make_socket(cls, ip, port):
"""Bind to a new socket.
If LIBPROCESS_PORT or LIBPROCESS_IP are configured in the environment,
these will be used for socket connectivity.
"""
bound_socket = bind_sockets(port, address=ip)[0]
ip, port = bound_socket.getsockname()
if not ip or ip == '0.0.0.... | python | def _make_socket(cls, ip, port):
"""Bind to a new socket.
If LIBPROCESS_PORT or LIBPROCESS_IP are configured in the environment,
these will be used for socket connectivity.
"""
bound_socket = bind_sockets(port, address=ip)[0]
ip, port = bound_socket.getsockname()
if not ip or ip == '0.0.0.... | [
"def",
"_make_socket",
"(",
"cls",
",",
"ip",
",",
"port",
")",
":",
"bound_socket",
"=",
"bind_sockets",
"(",
"port",
",",
"address",
"=",
"ip",
")",
"[",
"0",
"]",
"ip",
",",
"port",
"=",
"bound_socket",
".",
"getsockname",
"(",
")",
"if",
"not",
... | Bind to a new socket.
If LIBPROCESS_PORT or LIBPROCESS_IP are configured in the environment,
these will be used for socket connectivity. | [
"Bind",
"to",
"a",
"new",
"socket",
"."
] | train | https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L45-L57 |
wickman/compactor | compactor/context.py | Context.stop | def stop(self):
"""Stops the context. This terminates all PIDs and closes all connections."""
log.info('Stopping %s' % self)
pids = list(self._processes)
# Clean up the context
for pid in pids:
self.terminate(pid)
while self._connections:
pid = next(iter(self._connections))
... | python | def stop(self):
"""Stops the context. This terminates all PIDs and closes all connections."""
log.info('Stopping %s' % self)
pids = list(self._processes)
# Clean up the context
for pid in pids:
self.terminate(pid)
while self._connections:
pid = next(iter(self._connections))
... | [
"def",
"stop",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Stopping %s'",
"%",
"self",
")",
"pids",
"=",
"list",
"(",
"self",
".",
"_processes",
")",
"# Clean up the context",
"for",
"pid",
"in",
"pids",
":",
"self",
".",
"terminate",
"(",
"pid",... | Stops the context. This terminates all PIDs and closes all connections. | [
"Stops",
"the",
"context",
".",
"This",
"terminates",
"all",
"PIDs",
"and",
"closes",
"all",
"connections",
"."
] | train | https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L151-L168 |
wickman/compactor | compactor/context.py | Context.spawn | def spawn(self, process):
"""Spawn a process.
Spawning a process binds it to this context and assigns the process a
pid which is returned. The process' ``initialize`` method is called.
Note: A process cannot send messages until it is bound to a context.
:param process: The process to bind to thi... | python | def spawn(self, process):
"""Spawn a process.
Spawning a process binds it to this context and assigns the process a
pid which is returned. The process' ``initialize`` method is called.
Note: A process cannot send messages until it is bound to a context.
:param process: The process to bind to thi... | [
"def",
"spawn",
"(",
"self",
",",
"process",
")",
":",
"self",
".",
"_assert_started",
"(",
")",
"process",
".",
"bind",
"(",
"self",
")",
"self",
".",
"http",
".",
"mount_process",
"(",
"process",
")",
"self",
".",
"_processes",
"[",
"process",
".",
... | Spawn a process.
Spawning a process binds it to this context and assigns the process a
pid which is returned. The process' ``initialize`` method is called.
Note: A process cannot send messages until it is bound to a context.
:param process: The process to bind to this context.
:type process: :cl... | [
"Spawn",
"a",
"process",
"."
] | train | https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L170-L188 |
wickman/compactor | compactor/context.py | Context.dispatch | def dispatch(self, pid, method, *args):
"""Call a method on another process by its pid.
The method on the other process does not need to be installed with
``Process.install``. The call is serialized with all other calls on the
context's event loop. The pid must be bound to this context.
This fun... | python | def dispatch(self, pid, method, *args):
"""Call a method on another process by its pid.
The method on the other process does not need to be installed with
``Process.install``. The call is serialized with all other calls on the
context's event loop. The pid must be bound to this context.
This fun... | [
"def",
"dispatch",
"(",
"self",
",",
"pid",
",",
"method",
",",
"*",
"args",
")",
":",
"self",
".",
"_assert_started",
"(",
")",
"self",
".",
"_assert_local_pid",
"(",
"pid",
")",
"function",
"=",
"self",
".",
"_get_dispatch_method",
"(",
"pid",
",",
"... | Call a method on another process by its pid.
The method on the other process does not need to be installed with
``Process.install``. The call is serialized with all other calls on the
context's event loop. The pid must be bound to this context.
This function returns immediately.
:param pid: The... | [
"Call",
"a",
"method",
"on",
"another",
"process",
"by",
"its",
"pid",
"."
] | train | https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L198-L216 |
wickman/compactor | compactor/context.py | Context.delay | def delay(self, amount, pid, method, *args):
"""Call a method on another process after a specified delay.
This is equivalent to ``dispatch`` except with an additional amount of
time to wait prior to invoking the call.
This function returns immediately.
:param amount: The amount of time to wait in... | python | def delay(self, amount, pid, method, *args):
"""Call a method on another process after a specified delay.
This is equivalent to ``dispatch`` except with an additional amount of
time to wait prior to invoking the call.
This function returns immediately.
:param amount: The amount of time to wait in... | [
"def",
"delay",
"(",
"self",
",",
"amount",
",",
"pid",
",",
"method",
",",
"*",
"args",
")",
":",
"self",
".",
"_assert_started",
"(",
")",
"self",
".",
"_assert_local_pid",
"(",
"pid",
")",
"function",
"=",
"self",
".",
"_get_dispatch_method",
"(",
"... | Call a method on another process after a specified delay.
This is equivalent to ``dispatch`` except with an additional amount of
time to wait prior to invoking the call.
This function returns immediately.
:param amount: The amount of time to wait in seconds before making the call.
:type amount: `... | [
"Call",
"a",
"method",
"on",
"another",
"process",
"after",
"a",
"specified",
"delay",
"."
] | train | https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L218-L237 |
wickman/compactor | compactor/context.py | Context._maybe_connect | def _maybe_connect(self, to_pid, callback=None):
"""Asynchronously establish a connection to the remote pid."""
callback = stack_context.wrap(callback or (lambda stream: None))
def streaming_callback(data):
# we are not guaranteed to get an acknowledgment, but log and discard bytes if we do.
l... | python | def _maybe_connect(self, to_pid, callback=None):
"""Asynchronously establish a connection to the remote pid."""
callback = stack_context.wrap(callback or (lambda stream: None))
def streaming_callback(data):
# we are not guaranteed to get an acknowledgment, but log and discard bytes if we do.
l... | [
"def",
"_maybe_connect",
"(",
"self",
",",
"to_pid",
",",
"callback",
"=",
"None",
")",
":",
"callback",
"=",
"stack_context",
".",
"wrap",
"(",
"callback",
"or",
"(",
"lambda",
"stream",
":",
"None",
")",
")",
"def",
"streaming_callback",
"(",
"data",
"... | Asynchronously establish a connection to the remote pid. | [
"Asynchronously",
"establish",
"a",
"connection",
"to",
"the",
"remote",
"pid",
"."
] | train | https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L247-L302 |
wickman/compactor | compactor/context.py | Context.send | def send(self, from_pid, to_pid, method, body=None):
"""Send a message method from one pid to another with an optional body.
Note: It is more idiomatic to send directly from a bound process rather than
calling send on the context.
If the destination pid is on the same context, the Context may skip the... | python | def send(self, from_pid, to_pid, method, body=None):
"""Send a message method from one pid to another with an optional body.
Note: It is more idiomatic to send directly from a bound process rather than
calling send on the context.
If the destination pid is on the same context, the Context may skip the... | [
"def",
"send",
"(",
"self",
",",
"from_pid",
",",
"to_pid",
",",
"method",
",",
"body",
"=",
"None",
")",
":",
"self",
".",
"_assert_started",
"(",
")",
"self",
".",
"_assert_local_pid",
"(",
"from_pid",
")",
"if",
"self",
".",
"_is_local",
"(",
"to_pi... | Send a message method from one pid to another with an optional body.
Note: It is more idiomatic to send directly from a bound process rather than
calling send on the context.
If the destination pid is on the same context, the Context may skip the
wire and route directly to process itself. ``from_pid`... | [
"Send",
"a",
"message",
"method",
"from",
"one",
"pid",
"to",
"another",
"with",
"an",
"optional",
"body",
"."
] | train | https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L309-L356 |
wickman/compactor | compactor/context.py | Context.link | def link(self, pid, to):
"""Link a local process to a possibly remote process.
Note: It is more idiomatic to call ``link`` directly on the bound Process
object instead.
When ``pid`` is linked to ``to``, the termination of the ``to`` process
(or the severing of its connection from the Process ``pid... | python | def link(self, pid, to):
"""Link a local process to a possibly remote process.
Note: It is more idiomatic to call ``link`` directly on the bound Process
object instead.
When ``pid`` is linked to ``to``, the termination of the ``to`` process
(or the severing of its connection from the Process ``pid... | [
"def",
"link",
"(",
"self",
",",
"pid",
",",
"to",
")",
":",
"self",
".",
"_assert_started",
"(",
")",
"def",
"really_link",
"(",
")",
":",
"self",
".",
"_links",
"[",
"pid",
"]",
".",
"add",
"(",
"to",
")",
"log",
".",
"info",
"(",
"'Added link ... | Link a local process to a possibly remote process.
Note: It is more idiomatic to call ``link`` directly on the bound Process
object instead.
When ``pid`` is linked to ``to``, the termination of the ``to`` process
(or the severing of its connection from the Process ``pid``) will result
in the local... | [
"Link",
"a",
"local",
"process",
"to",
"a",
"possibly",
"remote",
"process",
"."
] | train | https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L374-L405 |
wickman/compactor | compactor/context.py | Context.terminate | def terminate(self, pid):
"""Terminate a process bound to this context.
When a process is terminated, all the processes to which it is linked
will be have their ``exited`` methods called. Messages to this process
will no longer be delivered.
This method returns immediately.
:param pid: The p... | python | def terminate(self, pid):
"""Terminate a process bound to this context.
When a process is terminated, all the processes to which it is linked
will be have their ``exited`` methods called. Messages to this process
will no longer be delivered.
This method returns immediately.
:param pid: The p... | [
"def",
"terminate",
"(",
"self",
",",
"pid",
")",
":",
"self",
".",
"_assert_started",
"(",
")",
"log",
".",
"info",
"(",
"'Terminating %s'",
"%",
"pid",
")",
"process",
"=",
"self",
".",
"_processes",
".",
"pop",
"(",
"pid",
",",
"None",
")",
"if",
... | Terminate a process bound to this context.
When a process is terminated, all the processes to which it is linked
will be have their ``exited`` methods called. Messages to this process
will no longer be delivered.
This method returns immediately.
:param pid: The pid of the process to terminate.
... | [
"Terminate",
"a",
"process",
"bound",
"to",
"this",
"context",
"."
] | train | https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/context.py#L407-L427 |
DolphDev/ezurl | ezurl/__init__.py | Url._page_gen | def _page_gen(self):
"""
Generates The String for pages
"""
track = ""
for page in self.__pages__:
track += "/{page}".format(page=page)
return track | python | def _page_gen(self):
"""
Generates The String for pages
"""
track = ""
for page in self.__pages__:
track += "/{page}".format(page=page)
return track | [
"def",
"_page_gen",
"(",
"self",
")",
":",
"track",
"=",
"\"\"",
"for",
"page",
"in",
"self",
".",
"__pages__",
":",
"track",
"+=",
"\"/{page}\"",
".",
"format",
"(",
"page",
"=",
"page",
")",
"return",
"track"
] | Generates The String for pages | [
"Generates",
"The",
"String",
"for",
"pages"
] | train | https://github.com/DolphDev/ezurl/blob/deaa755db2c0532c237f9eb4192aa51c7e928a07/ezurl/__init__.py#L102-L109 |
DolphDev/ezurl | ezurl/__init__.py | Url._query_gen | def _query_gen(self):
"""Generates The String for queries"""
return urlencode(self.__query__, safe=self.safe, querydelimiter=self.__querydelimiter__) | python | def _query_gen(self):
"""Generates The String for queries"""
return urlencode(self.__query__, safe=self.safe, querydelimiter=self.__querydelimiter__) | [
"def",
"_query_gen",
"(",
"self",
")",
":",
"return",
"urlencode",
"(",
"self",
".",
"__query__",
",",
"safe",
"=",
"self",
".",
"safe",
",",
"querydelimiter",
"=",
"self",
".",
"__querydelimiter__",
")"
] | Generates The String for queries | [
"Generates",
"The",
"String",
"for",
"queries"
] | train | https://github.com/DolphDev/ezurl/blob/deaa755db2c0532c237f9eb4192aa51c7e928a07/ezurl/__init__.py#L111-L113 |
DolphDev/ezurl | ezurl/__init__.py | Url.page | def page(self, *args):
"""
Pages takes *args and adds pages in order
"""
for arg in args:
self.__pages__.append(arg)
return self | python | def page(self, *args):
"""
Pages takes *args and adds pages in order
"""
for arg in args:
self.__pages__.append(arg)
return self | [
"def",
"page",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"arg",
"in",
"args",
":",
"self",
".",
"__pages__",
".",
"append",
"(",
"arg",
")",
"return",
"self"
] | Pages takes *args and adds pages in order | [
"Pages",
"takes",
"*",
"args",
"and",
"adds",
"pages",
"in",
"order"
] | train | https://github.com/DolphDev/ezurl/blob/deaa755db2c0532c237f9eb4192aa51c7e928a07/ezurl/__init__.py#L123-L129 |
DolphDev/ezurl | ezurl/__init__.py | Url.query | def query(self, listdelimiter="+", safe="", **kwargs):
"""
Url queries
:param listdelimiter: Specifies what list delimiter should be
:param safe: string that includes all the characters that should not be ignored
Kwargs (Since its a dictionary) are not ordered. You must call th... | python | def query(self, listdelimiter="+", safe="", **kwargs):
"""
Url queries
:param listdelimiter: Specifies what list delimiter should be
:param safe: string that includes all the characters that should not be ignored
Kwargs (Since its a dictionary) are not ordered. You must call th... | [
"def",
"query",
"(",
"self",
",",
"listdelimiter",
"=",
"\"+\"",
",",
"safe",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"safe",
"=",
"safe",
"if",
"safe",
"else",
"self",
".",
"safe",
"for",
"arg",
"in",
"list",
"(",
"kwargs",
".",
"keys",
... | Url queries
:param listdelimiter: Specifies what list delimiter should be
:param safe: string that includes all the characters that should not be ignored
Kwargs (Since its a dictionary) are not ordered. You must call the
method again if you absolutely need one query
after anoth... | [
"Url",
"queries"
] | train | https://github.com/DolphDev/ezurl/blob/deaa755db2c0532c237f9eb4192aa51c7e928a07/ezurl/__init__.py#L131-L153 |
sbarham/dsrt | build/lib/dsrt/models/Encoder.py | Encoder.build | def build(self):
"""
The encoder computational graph consists of four components:
(1) the input node `encoder_input`
(2) the embedding node `encoder_embed`
(3) the recurrent (RNN) part `encoder_rnn`
(4) the hidden state output ... | python | def build(self):
"""
The encoder computational graph consists of four components:
(1) the input node `encoder_input`
(2) the embedding node `encoder_embed`
(3) the recurrent (RNN) part `encoder_rnn`
(4) the hidden state output ... | [
"def",
"build",
"(",
"self",
")",
":",
"# Grab hyperparameters from self.config:",
"hidden_dim",
"=",
"self",
".",
"config",
"[",
"'encoding-layer-width'",
"]",
"recurrent_unit",
"=",
"self",
".",
"config",
"[",
"'recurrent-unit-type'",
"]",
"bidirectional",
"=",
"F... | The encoder computational graph consists of four components:
(1) the input node `encoder_input`
(2) the embedding node `encoder_embed`
(3) the recurrent (RNN) part `encoder_rnn`
(4) the hidden state output `encoder_hidden_state`
For co... | [
"The",
"encoder",
"computational",
"graph",
"consists",
"of",
"four",
"components",
":",
"(",
"1",
")",
"the",
"input",
"node",
"encoder_input",
"(",
"2",
")",
"the",
"embedding",
"node",
"encoder_embed",
"(",
"3",
")",
"the",
"recurrent",
"(",
"RNN",
")",... | train | https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/build/lib/dsrt/models/Encoder.py#L33-L83 |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/convert/StringConverter.py | StringConverter.to_nullable_string | def to_nullable_string(value):
"""
Converts value into string or returns None when value is None.
:param value: the value to convert.
:return: string value or None when value is None.
"""
if value == None:
return None
if type(value) == datetime.date:... | python | def to_nullable_string(value):
"""
Converts value into string or returns None when value is None.
:param value: the value to convert.
:return: string value or None when value is None.
"""
if value == None:
return None
if type(value) == datetime.date:... | [
"def",
"to_nullable_string",
"(",
"value",
")",
":",
"if",
"value",
"==",
"None",
":",
"return",
"None",
"if",
"type",
"(",
"value",
")",
"==",
"datetime",
".",
"date",
":",
"return",
"value",
".",
"isoformat",
"(",
")",
"if",
"type",
"(",
"value",
"... | Converts value into string or returns None when value is None.
:param value: the value to convert.
:return: string value or None when value is None. | [
"Converts",
"value",
"into",
"string",
"or",
"returns",
"None",
"when",
"value",
"is",
"None",
"."
] | train | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/convert/StringConverter.py#L30-L55 |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/convert/StringConverter.py | StringConverter.to_string_with_default | def to_string_with_default(value, default_value):
"""
Converts value into string or returns default when value is None.
:param value: the value to convert.
:param default_value: the default value.
:return: string value or default when value is null.
"""
result ... | python | def to_string_with_default(value, default_value):
"""
Converts value into string or returns default when value is None.
:param value: the value to convert.
:param default_value: the default value.
:return: string value or default when value is null.
"""
result ... | [
"def",
"to_string_with_default",
"(",
"value",
",",
"default_value",
")",
":",
"result",
"=",
"StringConverter",
".",
"to_nullable_string",
"(",
"value",
")",
"return",
"result",
"if",
"result",
"!=",
"None",
"else",
"default_value"
] | Converts value into string or returns default when value is None.
:param value: the value to convert.
:param default_value: the default value.
:return: string value or default when value is null. | [
"Converts",
"value",
"into",
"string",
"or",
"returns",
"default",
"when",
"value",
"is",
"None",
"."
] | train | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/convert/StringConverter.py#L69-L80 |
rvswift/EB | EB/builder/postanalysis/postanalysis.py | run | def run(itf):
"""
Run postanalyze functions.
"""
if not itf:
return 1
# access user input
options = SplitInput(itf)
# check input args
error_check(options)
# read input files
try:
molecules, ensemble_lookup = ReadFiles(options)
except:
return 1
if o... | python | def run(itf):
"""
Run postanalyze functions.
"""
if not itf:
return 1
# access user input
options = SplitInput(itf)
# check input args
error_check(options)
# read input files
try:
molecules, ensemble_lookup = ReadFiles(options)
except:
return 1
if o... | [
"def",
"run",
"(",
"itf",
")",
":",
"if",
"not",
"itf",
":",
"return",
"1",
"# access user input",
"options",
"=",
"SplitInput",
"(",
"itf",
")",
"# check input args",
"error_check",
"(",
"options",
")",
"# read input files",
"try",
":",
"molecules",
",",
"e... | Run postanalyze functions. | [
"Run",
"postanalyze",
"functions",
"."
] | train | https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/postanalysis/postanalysis.py#L11-L34 |
rvswift/EB | EB/builder/postanalysis/postanalysis.py | compare | def compare(molecules, ensemble_lookup, options):
"""
compare stuff
:param molecules:
:param ensemble_lookup:
:param options:
:return:
"""
print(" Analyzing differences ... ")
print('')
sort_order = classification.get_sort_order(molecules)
ensemble1 = sorted(ensemble_lookup... | python | def compare(molecules, ensemble_lookup, options):
"""
compare stuff
:param molecules:
:param ensemble_lookup:
:param options:
:return:
"""
print(" Analyzing differences ... ")
print('')
sort_order = classification.get_sort_order(molecules)
ensemble1 = sorted(ensemble_lookup... | [
"def",
"compare",
"(",
"molecules",
",",
"ensemble_lookup",
",",
"options",
")",
":",
"print",
"(",
"\" Analyzing differences ... \"",
")",
"print",
"(",
"''",
")",
"sort_order",
"=",
"classification",
".",
"get_sort_order",
"(",
"molecules",
")",
"ensemble1",
"... | compare stuff
:param molecules:
:param ensemble_lookup:
:param options:
:return: | [
"compare",
"stuff",
":",
"param",
"molecules",
":",
":",
"param",
"ensemble_lookup",
":",
":",
"param",
"options",
":",
":",
"return",
":"
] | train | https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/postanalysis/postanalysis.py#L37-L103 |
rvswift/EB | EB/builder/postanalysis/postanalysis.py | evaluate_list | def evaluate_list(molecules, ensemble_lookup, options):
"""
Evaluate a list of ensembles and return statistics and ROC plots if appropriate
"""
# create stats dictionaries to store results from each ensemble
stats = {} # {file name : metric_List}
# print progress messages
if options.write... | python | def evaluate_list(molecules, ensemble_lookup, options):
"""
Evaluate a list of ensembles and return statistics and ROC plots if appropriate
"""
# create stats dictionaries to store results from each ensemble
stats = {} # {file name : metric_List}
# print progress messages
if options.write... | [
"def",
"evaluate_list",
"(",
"molecules",
",",
"ensemble_lookup",
",",
"options",
")",
":",
"# create stats dictionaries to store results from each ensemble",
"stats",
"=",
"{",
"}",
"# {file name : metric_List}",
"# print progress messages",
"if",
"options",
".",
"write_roc"... | Evaluate a list of ensembles and return statistics and ROC plots if appropriate | [
"Evaluate",
"a",
"list",
"of",
"ensembles",
"and",
"return",
"statistics",
"and",
"ROC",
"plots",
"if",
"appropriate"
] | train | https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/postanalysis/postanalysis.py#L106-L133 |
rvswift/EB | EB/builder/postanalysis/postanalysis.py | calculate_metrics | def calculate_metrics(molecules, ensemble_lookup, filename, options):
"""
Determine the virtual screening performance of the ensemble
:param molecules: list [mol_object_1, mol_object_2, .... ]
:param ensemble: tuple (receptor_x, receptor_y, .... )
:param options: interface object that makes command ... | python | def calculate_metrics(molecules, ensemble_lookup, filename, options):
"""
Determine the virtual screening performance of the ensemble
:param molecules: list [mol_object_1, mol_object_2, .... ]
:param ensemble: tuple (receptor_x, receptor_y, .... )
:param options: interface object that makes command ... | [
"def",
"calculate_metrics",
"(",
"molecules",
",",
"ensemble_lookup",
",",
"filename",
",",
"options",
")",
":",
"metric_List",
"=",
"[",
"]",
"# [(auc, auclow, auchigh), (fpf, ef, eflow, efhigh), (fpf, ef, eflow, efhigh), ..., ]",
"sort_order",
"=",
"'asc'",
"# set up the ap... | Determine the virtual screening performance of the ensemble
:param molecules: list [mol_object_1, mol_object_2, .... ]
:param ensemble: tuple (receptor_x, receptor_y, .... )
:param options: interface object that makes command line arguments available.
:return: | [
"Determine",
"the",
"virtual",
"screening",
"performance",
"of",
"the",
"ensemble",
":",
"param",
"molecules",
":",
"list",
"[",
"mol_object_1",
"mol_object_2",
"....",
"]",
":",
"param",
"ensemble",
":",
"tuple",
"(",
"receptor_x",
"receptor_y",
"....",
")",
... | train | https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/postanalysis/postanalysis.py#L136-L166 |
rvswift/EB | EB/builder/postanalysis/postanalysis.py | make_fpfList | def make_fpfList(options):
"""
aggregate default fpf values and user-defined fpf values where enrichment factor calculations will be attempted.
:param options: SplitInput object
:return defaults: list includes default fpf values & unique user-defined values
"""
user_values = options.fpf
de... | python | def make_fpfList(options):
"""
aggregate default fpf values and user-defined fpf values where enrichment factor calculations will be attempted.
:param options: SplitInput object
:return defaults: list includes default fpf values & unique user-defined values
"""
user_values = options.fpf
de... | [
"def",
"make_fpfList",
"(",
"options",
")",
":",
"user_values",
"=",
"options",
".",
"fpf",
"defaults",
"=",
"[",
"'0.0001'",
",",
"'0.001'",
",",
"'0.01'",
",",
"'0.05'",
"]",
"if",
"user_values",
":",
"for",
"fpf",
"in",
"user_values",
":",
"if",
"fpf"... | aggregate default fpf values and user-defined fpf values where enrichment factor calculations will be attempted.
:param options: SplitInput object
:return defaults: list includes default fpf values & unique user-defined values | [
"aggregate",
"default",
"fpf",
"values",
"and",
"user",
"-",
"defined",
"fpf",
"values",
"where",
"enrichment",
"factor",
"calculations",
"will",
"be",
"attempted",
".",
":",
"param",
"options",
":",
"SplitInput",
"object",
":",
"return",
"defaults",
":",
"lis... | train | https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/postanalysis/postanalysis.py#L169-L187 |
rvswift/EB | EB/builder/postanalysis/postanalysis.py | error_check | def error_check(options):
"""
Error check
:rtype : object
"""
compare = options.compare
ensemble_paths = options.ensemble_paths
if compare and len(ensemble_paths) > 2:
print("\n Only 2 ensembles can be compared, {d} were specified\n".format(d=len(ensemble_paths)))
sys.exit(... | python | def error_check(options):
"""
Error check
:rtype : object
"""
compare = options.compare
ensemble_paths = options.ensemble_paths
if compare and len(ensemble_paths) > 2:
print("\n Only 2 ensembles can be compared, {d} were specified\n".format(d=len(ensemble_paths)))
sys.exit(... | [
"def",
"error_check",
"(",
"options",
")",
":",
"compare",
"=",
"options",
".",
"compare",
"ensemble_paths",
"=",
"options",
".",
"ensemble_paths",
"if",
"compare",
"and",
"len",
"(",
"ensemble_paths",
")",
">",
"2",
":",
"print",
"(",
"\"\\n Only 2 ensembles ... | Error check
:rtype : object | [
"Error",
"check",
":",
"rtype",
":",
"object"
] | train | https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/postanalysis/postanalysis.py#L190-L201 |
rvswift/EB | EB/builder/postanalysis/postanalysis.py | plotter | def plotter(molecules, ensemble_lookup, options):
"""
plot ROC curves for ensembles in ensemble_lookup
:param molecules:
:param ensemble_lookup:
:param options:
:return:
"""
try:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
except ... | python | def plotter(molecules, ensemble_lookup, options):
"""
plot ROC curves for ensembles in ensemble_lookup
:param molecules:
:param ensemble_lookup:
:param options:
:return:
"""
try:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
except ... | [
"def",
"plotter",
"(",
"molecules",
",",
"ensemble_lookup",
",",
"options",
")",
":",
"try",
":",
"import",
"matplotlib",
"matplotlib",
".",
"use",
"(",
"'Agg'",
")",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"except",
"ImportError",
":",
"print",
... | plot ROC curves for ensembles in ensemble_lookup
:param molecules:
:param ensemble_lookup:
:param options:
:return: | [
"plot",
"ROC",
"curves",
"for",
"ensembles",
"in",
"ensemble_lookup",
":",
"param",
"molecules",
":",
":",
"param",
"ensemble_lookup",
":",
":",
"param",
"options",
":",
":",
"return",
":"
] | train | https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/postanalysis/postanalysis.py#L204-L291 |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/random/RandomDateTime.py | RandomDateTime.next_date | def next_date(min_year = None, max_year = None):
"""
Generates a random Date in the range ['minYear', 'maxYear'].
This method generate dates without time (or time set to 00:00:00)
:param min_year: (optional) minimum range value
:param max_year: max range value
:return:... | python | def next_date(min_year = None, max_year = None):
"""
Generates a random Date in the range ['minYear', 'maxYear'].
This method generate dates without time (or time set to 00:00:00)
:param min_year: (optional) minimum range value
:param max_year: max range value
:return:... | [
"def",
"next_date",
"(",
"min_year",
"=",
"None",
",",
"max_year",
"=",
"None",
")",
":",
"current_year",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"year",
"min_year",
"=",
"min_year",
"if",
"min_year",
"!=",
"None",
"else",
"curren... | Generates a random Date in the range ['minYear', 'maxYear'].
This method generate dates without time (or time set to 00:00:00)
:param min_year: (optional) minimum range value
:param max_year: max range value
:return: a random Date value. | [
"Generates",
"a",
"random",
"Date",
"in",
"the",
"range",
"[",
"minYear",
"maxYear",
"]",
".",
"This",
"method",
"generate",
"dates",
"without",
"time",
"(",
"or",
"time",
"set",
"to",
"00",
":",
"00",
":",
"00",
")"
] | train | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/random/RandomDateTime.py#L30-L54 |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/random/RandomDateTime.py | RandomDateTime.next_datetime | def next_datetime(min_year = None, max_year = None):
"""
Generates a random Date and time in the range ['minYear', 'maxYear'].
This method generate dates without time (or time set to 00:00:00)
:param min_year: (optional) minimum range value
:param max_year: max range value
... | python | def next_datetime(min_year = None, max_year = None):
"""
Generates a random Date and time in the range ['minYear', 'maxYear'].
This method generate dates without time (or time set to 00:00:00)
:param min_year: (optional) minimum range value
:param max_year: max range value
... | [
"def",
"next_datetime",
"(",
"min_year",
"=",
"None",
",",
"max_year",
"=",
"None",
")",
":",
"date",
"=",
"RandomDateTime",
".",
"next_date",
"(",
"min_year",
",",
"max_year",
")",
".",
"date",
"(",
")",
"time",
"=",
"RandomDateTime",
".",
"next_time",
... | Generates a random Date and time in the range ['minYear', 'maxYear'].
This method generate dates without time (or time set to 00:00:00)
:param min_year: (optional) minimum range value
:param max_year: max range value
:return: a random Date and time value. | [
"Generates",
"a",
"random",
"Date",
"and",
"time",
"in",
"the",
"range",
"[",
"minYear",
"maxYear",
"]",
".",
"This",
"method",
"generate",
"dates",
"without",
"time",
"(",
"or",
"time",
"set",
"to",
"00",
":",
"00",
":",
"00",
")"
] | train | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/random/RandomDateTime.py#L66-L79 |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/random/RandomDateTime.py | RandomDateTime.update_datetime | def update_datetime(value, range = None):
"""
Updates (drifts) a Date value within specified range defined
:param value: a Date value to drift.
:param range: (optional) a range in milliseconds. Default: 10 days
:return: an updated DateTime value.
"""
range = ra... | python | def update_datetime(value, range = None):
"""
Updates (drifts) a Date value within specified range defined
:param value: a Date value to drift.
:param range: (optional) a range in milliseconds. Default: 10 days
:return: an updated DateTime value.
"""
range = ra... | [
"def",
"update_datetime",
"(",
"value",
",",
"range",
"=",
"None",
")",
":",
"range",
"=",
"range",
"if",
"range",
"!=",
"None",
"else",
"10",
"if",
"range",
"<",
"0",
":",
"return",
"value",
"days",
"=",
"RandomFloat",
".",
"next_float",
"(",
"-",
"... | Updates (drifts) a Date value within specified range defined
:param value: a Date value to drift.
:param range: (optional) a range in milliseconds. Default: 10 days
:return: an updated DateTime value. | [
"Updates",
"(",
"drifts",
")",
"a",
"Date",
"value",
"within",
"specified",
"range",
"defined"
] | train | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/random/RandomDateTime.py#L82-L98 |
humilis/humilis-lambdautils | lambdautils/monitor.py | _sentry_context_dict | def _sentry_context_dict(context):
"""Create a dict with context information for Sentry."""
d = {
"function_name": context.function_name,
"function_version": context.function_version,
"invoked_function_arn": context.invoked_function_arn,
"memory_limit_in_mb": context.memory_limit... | python | def _sentry_context_dict(context):
"""Create a dict with context information for Sentry."""
d = {
"function_name": context.function_name,
"function_version": context.function_version,
"invoked_function_arn": context.invoked_function_arn,
"memory_limit_in_mb": context.memory_limit... | [
"def",
"_sentry_context_dict",
"(",
"context",
")",
":",
"d",
"=",
"{",
"\"function_name\"",
":",
"context",
".",
"function_name",
",",
"\"function_version\"",
":",
"context",
".",
"function_version",
",",
"\"invoked_function_arn\"",
":",
"context",
".",
"invoked_fu... | Create a dict with context information for Sentry. | [
"Create",
"a",
"dict",
"with",
"context",
"information",
"for",
"Sentry",
"."
] | train | https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/monitor.py#L27-L44 |
humilis/humilis-lambdautils | lambdautils/monitor.py | sentry_monitor | def sentry_monitor(error_stream=None, **kwargs):
"""Sentry monitoring for AWS Lambda handler."""
def decorator(func):
"""A decorator that adds Sentry monitoring to a Lambda handler."""
def wrapper(event, context):
"""Wrap the target function."""
client = _setup_sentry_cli... | python | def sentry_monitor(error_stream=None, **kwargs):
"""Sentry monitoring for AWS Lambda handler."""
def decorator(func):
"""A decorator that adds Sentry monitoring to a Lambda handler."""
def wrapper(event, context):
"""Wrap the target function."""
client = _setup_sentry_cli... | [
"def",
"sentry_monitor",
"(",
"error_stream",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"\"\"\"A decorator that adds Sentry monitoring to a Lambda handler.\"\"\"",
"def",
"wrapper",
"(",
"event",
",",
"context",
")",
... | Sentry monitoring for AWS Lambda handler. | [
"Sentry",
"monitoring",
"for",
"AWS",
"Lambda",
"handler",
"."
] | train | https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/monitor.py#L47-L66 |
humilis/humilis-lambdautils | lambdautils/monitor.py | _setup_sentry_client | def _setup_sentry_client(context):
"""Produce and configure the sentry client."""
# get_secret will be deprecated soon
dsn = os.environ.get("SENTRY_DSN")
try:
client = raven.Client(dsn, sample_rate=SENTRY_SAMPLE_RATE)
client.user_context(_sentry_context_dict(context))
return cli... | python | def _setup_sentry_client(context):
"""Produce and configure the sentry client."""
# get_secret will be deprecated soon
dsn = os.environ.get("SENTRY_DSN")
try:
client = raven.Client(dsn, sample_rate=SENTRY_SAMPLE_RATE)
client.user_context(_sentry_context_dict(context))
return cli... | [
"def",
"_setup_sentry_client",
"(",
"context",
")",
":",
"# get_secret will be deprecated soon",
"dsn",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"SENTRY_DSN\"",
")",
"try",
":",
"client",
"=",
"raven",
".",
"Client",
"(",
"dsn",
",",
"sample_rate",
"=",
... | Produce and configure the sentry client. | [
"Produce",
"and",
"configure",
"the",
"sentry",
"client",
"."
] | train | https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/monitor.py#L69-L80 |
humilis/humilis-lambdautils | lambdautils/monitor.py | _handle_processing_error | def _handle_processing_error(err, errstream, client):
"""Handle ProcessingError exceptions."""
errors = sorted(err.events, key=operator.attrgetter("index"))
failed = [e.event for e in errors]
silent = all(isinstance(e.error, OutOfOrderError) for e in errors)
if errstream:
_deliver_errored_e... | python | def _handle_processing_error(err, errstream, client):
"""Handle ProcessingError exceptions."""
errors = sorted(err.events, key=operator.attrgetter("index"))
failed = [e.event for e in errors]
silent = all(isinstance(e.error, OutOfOrderError) for e in errors)
if errstream:
_deliver_errored_e... | [
"def",
"_handle_processing_error",
"(",
"err",
",",
"errstream",
",",
"client",
")",
":",
"errors",
"=",
"sorted",
"(",
"err",
".",
"events",
",",
"key",
"=",
"operator",
".",
"attrgetter",
"(",
"\"index\"",
")",
")",
"failed",
"=",
"[",
"e",
".",
"eve... | Handle ProcessingError exceptions. | [
"Handle",
"ProcessingError",
"exceptions",
"."
] | train | https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/monitor.py#L83-L107 |
humilis/humilis-lambdautils | lambdautils/monitor.py | _deliver_errored_events | def _deliver_errored_events(errstream, recs):
"""Deliver errors to error stream."""
rlogger.info("Going to handle %s failed events", len(recs))
rlogger.info(
"First failed event: %s", json.dumps(recs[0], indent=4))
kinesis_stream = errstream.get("kinesis_stream")
randomkey = str(uuid.uuid4(... | python | def _deliver_errored_events(errstream, recs):
"""Deliver errors to error stream."""
rlogger.info("Going to handle %s failed events", len(recs))
rlogger.info(
"First failed event: %s", json.dumps(recs[0], indent=4))
kinesis_stream = errstream.get("kinesis_stream")
randomkey = str(uuid.uuid4(... | [
"def",
"_deliver_errored_events",
"(",
"errstream",
",",
"recs",
")",
":",
"rlogger",
".",
"info",
"(",
"\"Going to handle %s failed events\"",
",",
"len",
"(",
"recs",
")",
")",
"rlogger",
".",
"info",
"(",
"\"First failed event: %s\"",
",",
"json",
".",
"dumps... | Deliver errors to error stream. | [
"Deliver",
"errors",
"to",
"error",
"stream",
"."
] | train | https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/monitor.py#L110-L129 |
humilis/humilis-lambdautils | lambdautils/monitor.py | _get_records | def _get_records(event):
"""Get records from an AWS Lambda trigger event."""
try:
recs, _ = unpack_kinesis_event(event, deserializer=None)
except KeyError:
# If not a Kinesis event, just unpack the records
recs = event["Records"]
return recs | python | def _get_records(event):
"""Get records from an AWS Lambda trigger event."""
try:
recs, _ = unpack_kinesis_event(event, deserializer=None)
except KeyError:
# If not a Kinesis event, just unpack the records
recs = event["Records"]
return recs | [
"def",
"_get_records",
"(",
"event",
")",
":",
"try",
":",
"recs",
",",
"_",
"=",
"unpack_kinesis_event",
"(",
"event",
",",
"deserializer",
"=",
"None",
")",
"except",
"KeyError",
":",
"# If not a Kinesis event, just unpack the records",
"recs",
"=",
"event",
"... | Get records from an AWS Lambda trigger event. | [
"Get",
"records",
"from",
"an",
"AWS",
"Lambda",
"trigger",
"event",
"."
] | train | https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/monitor.py#L132-L139 |
gnullByte/dotcolors | dotcolors/utils.py | rgb_to_hex | def rgb_to_hex(rgba):
"""
expects: rgba value, ex: 0000/0000/0000/dddd
returns: hex value, ex: #000000
ignores alpha value
"""
rgba = rgba.split('/')
hex_value = '#' + rgba[0][:2] + rgba[1][:2] + rgba[2][:2]
return hex_value | python | def rgb_to_hex(rgba):
"""
expects: rgba value, ex: 0000/0000/0000/dddd
returns: hex value, ex: #000000
ignores alpha value
"""
rgba = rgba.split('/')
hex_value = '#' + rgba[0][:2] + rgba[1][:2] + rgba[2][:2]
return hex_value | [
"def",
"rgb_to_hex",
"(",
"rgba",
")",
":",
"rgba",
"=",
"rgba",
".",
"split",
"(",
"'/'",
")",
"hex_value",
"=",
"'#'",
"+",
"rgba",
"[",
"0",
"]",
"[",
":",
"2",
"]",
"+",
"rgba",
"[",
"1",
"]",
"[",
":",
"2",
"]",
"+",
"rgba",
"[",
"2",
... | expects: rgba value, ex: 0000/0000/0000/dddd
returns: hex value, ex: #000000
ignores alpha value | [
"expects",
":",
"rgba",
"value",
"ex",
":",
"0000",
"/",
"0000",
"/",
"0000",
"/",
"dddd",
"returns",
":",
"hex",
"value",
"ex",
":",
"#000000",
"ignores",
"alpha",
"value"
] | train | https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/utils.py#L55-L63 |
gnullByte/dotcolors | dotcolors/utils.py | hex_to_rgb | def hex_to_rgb(hex_value):
"""
expects: hex value, ex: #ffffff
returns: rgb value, ex: ff00/ff00/ff00
"""
if '#' in hex_value:
hex_value = hex_value.replace('#', '')
if len(hex_value) < 6:
return '0000/0000/0000'
r = hex_value[:2]
g = hex_value[2:4]
b = hex_value[4:]
... | python | def hex_to_rgb(hex_value):
"""
expects: hex value, ex: #ffffff
returns: rgb value, ex: ff00/ff00/ff00
"""
if '#' in hex_value:
hex_value = hex_value.replace('#', '')
if len(hex_value) < 6:
return '0000/0000/0000'
r = hex_value[:2]
g = hex_value[2:4]
b = hex_value[4:]
... | [
"def",
"hex_to_rgb",
"(",
"hex_value",
")",
":",
"if",
"'#'",
"in",
"hex_value",
":",
"hex_value",
"=",
"hex_value",
".",
"replace",
"(",
"'#'",
",",
"''",
")",
"if",
"len",
"(",
"hex_value",
")",
"<",
"6",
":",
"return",
"'0000/0000/0000'",
"r",
"=",
... | expects: hex value, ex: #ffffff
returns: rgb value, ex: ff00/ff00/ff00 | [
"expects",
":",
"hex",
"value",
"ex",
":",
"#ffffff",
"returns",
":",
"rgb",
"value",
"ex",
":",
"ff00",
"/",
"ff00",
"/",
"ff00"
] | train | https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/utils.py#L66-L78 |
gnullByte/dotcolors | dotcolors/utils.py | decimal_to_alpha | def decimal_to_alpha(dec):
"""
expects: decimal between 0 and 100
returns: alpha value for rgba
"""
dec /= 100.0
alpha = hex(int(dec*65535))[2:]
while len(alpha) < 4:
alpha = '0' + alpha
return alpha | python | def decimal_to_alpha(dec):
"""
expects: decimal between 0 and 100
returns: alpha value for rgba
"""
dec /= 100.0
alpha = hex(int(dec*65535))[2:]
while len(alpha) < 4:
alpha = '0' + alpha
return alpha | [
"def",
"decimal_to_alpha",
"(",
"dec",
")",
":",
"dec",
"/=",
"100.0",
"alpha",
"=",
"hex",
"(",
"int",
"(",
"dec",
"*",
"65535",
")",
")",
"[",
"2",
":",
"]",
"while",
"len",
"(",
"alpha",
")",
"<",
"4",
":",
"alpha",
"=",
"'0'",
"+",
"alpha",... | expects: decimal between 0 and 100
returns: alpha value for rgba | [
"expects",
":",
"decimal",
"between",
"0",
"and",
"100",
"returns",
":",
"alpha",
"value",
"for",
"rgba"
] | train | https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/utils.py#L81-L90 |
macbre/elasticsearch-query | elasticsearch_query.py | ElasticsearchQuery.format_index | def format_index(prefix, timestamp, sep='-'):
"""
:type prefix str
:type timestamp int
:type sep str
:rtype: str
"""
tz_info = tz.tzutc()
# ex. logstash-other-2017.05.09
return "{prefix}{sep}{date}".format(
prefix=prefix, sep=sep, date... | python | def format_index(prefix, timestamp, sep='-'):
"""
:type prefix str
:type timestamp int
:type sep str
:rtype: str
"""
tz_info = tz.tzutc()
# ex. logstash-other-2017.05.09
return "{prefix}{sep}{date}".format(
prefix=prefix, sep=sep, date... | [
"def",
"format_index",
"(",
"prefix",
",",
"timestamp",
",",
"sep",
"=",
"'-'",
")",
":",
"tz_info",
"=",
"tz",
".",
"tzutc",
"(",
")",
"# ex. logstash-other-2017.05.09",
"return",
"\"{prefix}{sep}{date}\"",
".",
"format",
"(",
"prefix",
"=",
"prefix",
",",
... | :type prefix str
:type timestamp int
:type sep str
:rtype: str | [
":",
"type",
"prefix",
"str",
":",
"type",
"timestamp",
"int",
":",
"type",
"sep",
"str",
":",
"rtype",
":",
"str"
] | train | https://github.com/macbre/elasticsearch-query/blob/d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf/elasticsearch_query.py#L84-L95 |
macbre/elasticsearch-query | elasticsearch_query.py | ElasticsearchQuery.format_timestamp | def format_timestamp(timestamp):
"""
Format the UTC timestamp for Elasticsearch
eg. 2014-07-09T08:37:18.000Z
@see https://docs.python.org/2/library/time.html#time.strftime
:type timestamp int
:rtype: str
"""
tz_info = tz.tzutc()
return datetime.f... | python | def format_timestamp(timestamp):
"""
Format the UTC timestamp for Elasticsearch
eg. 2014-07-09T08:37:18.000Z
@see https://docs.python.org/2/library/time.html#time.strftime
:type timestamp int
:rtype: str
"""
tz_info = tz.tzutc()
return datetime.f... | [
"def",
"format_timestamp",
"(",
"timestamp",
")",
":",
"tz_info",
"=",
"tz",
".",
"tzutc",
"(",
")",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"timestamp",
",",
"tz",
"=",
"tz_info",
")",
".",
"strftime",
"(",
"\"%Y-%m-%dT%H:%M:%S.000Z\"",
")"
] | Format the UTC timestamp for Elasticsearch
eg. 2014-07-09T08:37:18.000Z
@see https://docs.python.org/2/library/time.html#time.strftime
:type timestamp int
:rtype: str | [
"Format",
"the",
"UTC",
"timestamp",
"for",
"Elasticsearch",
"eg",
".",
"2014",
"-",
"07",
"-",
"09T08",
":",
"37",
":",
"18",
".",
"000Z"
] | train | https://github.com/macbre/elasticsearch-query/blob/d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf/elasticsearch_query.py#L98-L109 |
macbre/elasticsearch-query | elasticsearch_query.py | ElasticsearchQuery._search | def _search(self, query, fields=None, limit=50000, sampling=None):
"""
Perform the search and return raw rows
:type query object
:type fields list[str] or None
:type limit int
:type sampling int or None
:arg sampling: Percentage of results to be returned (0,100)... | python | def _search(self, query, fields=None, limit=50000, sampling=None):
"""
Perform the search and return raw rows
:type query object
:type fields list[str] or None
:type limit int
:type sampling int or None
:arg sampling: Percentage of results to be returned (0,100)... | [
"def",
"_search",
"(",
"self",
",",
"query",
",",
"fields",
"=",
"None",
",",
"limit",
"=",
"50000",
",",
"sampling",
"=",
"None",
")",
":",
"body",
"=",
"{",
"\"query\"",
":",
"{",
"\"bool\"",
":",
"{",
"\"must\"",
":",
"[",
"query",
"]",
"}",
"... | Perform the search and return raw rows
:type query object
:type fields list[str] or None
:type limit int
:type sampling int or None
:arg sampling: Percentage of results to be returned (0,100)
:rtype: list | [
"Perform",
"the",
"search",
"and",
"return",
"raw",
"rows"
] | train | https://github.com/macbre/elasticsearch-query/blob/d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf/elasticsearch_query.py#L121-L190 |
macbre/elasticsearch-query | elasticsearch_query.py | ElasticsearchQuery.get_rows | def get_rows(self, match, fields=None, limit=10, sampling=None):
"""
Returns raw rows that matches given query
:arg match: query to be run against Kibana log messages (ex. {"@message": "Foo Bar DB queries"})
:type fields list[str] or None
:arg limit: the number of results (defau... | python | def get_rows(self, match, fields=None, limit=10, sampling=None):
"""
Returns raw rows that matches given query
:arg match: query to be run against Kibana log messages (ex. {"@message": "Foo Bar DB queries"})
:type fields list[str] or None
:arg limit: the number of results (defau... | [
"def",
"get_rows",
"(",
"self",
",",
"match",
",",
"fields",
"=",
"None",
",",
"limit",
"=",
"10",
",",
"sampling",
"=",
"None",
")",
":",
"query",
"=",
"{",
"\"match\"",
":",
"match",
",",
"}",
"return",
"self",
".",
"_search",
"(",
"query",
",",
... | Returns raw rows that matches given query
:arg match: query to be run against Kibana log messages (ex. {"@message": "Foo Bar DB queries"})
:type fields list[str] or None
:arg limit: the number of results (defaults to 10)
:type sampling int or None
:arg sampling: Percentage of re... | [
"Returns",
"raw",
"rows",
"that",
"matches",
"given",
"query"
] | train | https://github.com/macbre/elasticsearch-query/blob/d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf/elasticsearch_query.py#L192-L206 |
macbre/elasticsearch-query | elasticsearch_query.py | ElasticsearchQuery.query_by_string | def query_by_string(self, query, fields=None, limit=10, sampling=None):
"""
Returns raw rows that matches the given query string
:arg query: query string to be run against Kibana log messages (ex. @message:"^PHP Fatal").
:type fields list[str] or None
:arg limit: the number of r... | python | def query_by_string(self, query, fields=None, limit=10, sampling=None):
"""
Returns raw rows that matches the given query string
:arg query: query string to be run against Kibana log messages (ex. @message:"^PHP Fatal").
:type fields list[str] or None
:arg limit: the number of r... | [
"def",
"query_by_string",
"(",
"self",
",",
"query",
",",
"fields",
"=",
"None",
",",
"limit",
"=",
"10",
",",
"sampling",
"=",
"None",
")",
":",
"query",
"=",
"{",
"\"query_string\"",
":",
"{",
"\"query\"",
":",
"query",
",",
"}",
"}",
"return",
"se... | Returns raw rows that matches the given query string
:arg query: query string to be run against Kibana log messages (ex. @message:"^PHP Fatal").
:type fields list[str] or None
:arg limit: the number of results (defaults to 10)
:type sampling int or None
:arg sampling: Percentage... | [
"Returns",
"raw",
"rows",
"that",
"matches",
"the",
"given",
"query",
"string"
] | train | https://github.com/macbre/elasticsearch-query/blob/d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf/elasticsearch_query.py#L208-L224 |
macbre/elasticsearch-query | elasticsearch_query.py | ElasticsearchQuery.count | def count(self, query):
"""
Returns number of matching entries
:type query str
:rtype: int
"""
body = {
"query": {
"bool": {
"must": [{
"query_string": {
"query": query,
... | python | def count(self, query):
"""
Returns number of matching entries
:type query str
:rtype: int
"""
body = {
"query": {
"bool": {
"must": [{
"query_string": {
"query": query,
... | [
"def",
"count",
"(",
"self",
",",
"query",
")",
":",
"body",
"=",
"{",
"\"query\"",
":",
"{",
"\"bool\"",
":",
"{",
"\"must\"",
":",
"[",
"{",
"\"query_string\"",
":",
"{",
"\"query\"",
":",
"query",
",",
"}",
"}",
"]",
"}",
"}",
"}",
"body",
"["... | Returns number of matching entries
:type query str
:rtype: int | [
"Returns",
"number",
"of",
"matching",
"entries"
] | train | https://github.com/macbre/elasticsearch-query/blob/d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf/elasticsearch_query.py#L226-L247 |
macbre/elasticsearch-query | elasticsearch_query.py | ElasticsearchQuery.query_by_sql | def query_by_sql(self, sql):
"""
Returns entries matching given SQL query
:type sql str
:rtype: list[dict]
"""
# https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-rest.html
# https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-sy... | python | def query_by_sql(self, sql):
"""
Returns entries matching given SQL query
:type sql str
:rtype: list[dict]
"""
# https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-rest.html
# https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-sy... | [
"def",
"query_by_sql",
"(",
"self",
",",
"sql",
")",
":",
"# https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-rest.html",
"# https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-syntax-select.html",
"body",
"=",
"{",
"'query'",
":",
"sql",
"}",
"re... | Returns entries matching given SQL query
:type sql str
:rtype: list[dict] | [
"Returns",
"entries",
"matching",
"given",
"SQL",
"query"
] | train | https://github.com/macbre/elasticsearch-query/blob/d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf/elasticsearch_query.py#L249-L265 |
macbre/elasticsearch-query | elasticsearch_query.py | ElasticsearchQuery.get_aggregations | def get_aggregations(self, query, group_by, stats_field, percents=(50, 95, 99, 99.9), size=100):
"""
Returns aggregations (rows count + percentile stats) for a given query
This is basically the same as the following pseudo-SQL query:
SELECT PERCENTILE(stats_field, 75) FROM query GROUP B... | python | def get_aggregations(self, query, group_by, stats_field, percents=(50, 95, 99, 99.9), size=100):
"""
Returns aggregations (rows count + percentile stats) for a given query
This is basically the same as the following pseudo-SQL query:
SELECT PERCENTILE(stats_field, 75) FROM query GROUP B... | [
"def",
"get_aggregations",
"(",
"self",
",",
"query",
",",
"group_by",
",",
"stats_field",
",",
"percents",
"=",
"(",
"50",
",",
"95",
",",
"99",
",",
"99.9",
")",
",",
"size",
"=",
"100",
")",
":",
"body",
"=",
"{",
"\"query\"",
":",
"{",
"\"bool\... | Returns aggregations (rows count + percentile stats) for a given query
This is basically the same as the following pseudo-SQL query:
SELECT PERCENTILE(stats_field, 75) FROM query GROUP BY group_by LIMIT size
https://www.elastic.co/guide/en/elasticsearch/reference/5.5/search-aggregations-bucket... | [
"Returns",
"aggregations",
"(",
"rows",
"count",
"+",
"percentile",
"stats",
")",
"for",
"a",
"given",
"query"
] | train | https://github.com/macbre/elasticsearch-query/blob/d5e0fa43fde20b7f38f9d99c3fc24f681d6e5baf/elasticsearch_query.py#L271-L360 |
koriakin/binflakes | binflakes/types/int.py | BinInt.extract | def extract(self, pos, width):
"""Extracts a subword with a given width, starting from a given
bit position.
"""
pos = operator.index(pos)
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
if pos < 0:
... | python | def extract(self, pos, width):
"""Extracts a subword with a given width, starting from a given
bit position.
"""
pos = operator.index(pos)
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
if pos < 0:
... | [
"def",
"extract",
"(",
"self",
",",
"pos",
",",
"width",
")",
":",
"pos",
"=",
"operator",
".",
"index",
"(",
"pos",
")",
"width",
"=",
"operator",
".",
"index",
"(",
"width",
")",
"if",
"width",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'width m... | Extracts a subword with a given width, starting from a given
bit position. | [
"Extracts",
"a",
"subword",
"with",
"a",
"given",
"width",
"starting",
"from",
"a",
"given",
"bit",
"position",
"."
] | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/int.py#L72-L82 |
koriakin/binflakes | binflakes/types/int.py | BinInt.deposit | def deposit(self, pos, val):
"""Returns a copy of this BinInt, with a given word deposited
at a given position (ie. with bits pos:pos+len(val) replaced
with bits from val).
"""
if not isinstance(val, BinWord):
raise TypeError('deposit needs a BinWord')
pos = o... | python | def deposit(self, pos, val):
"""Returns a copy of this BinInt, with a given word deposited
at a given position (ie. with bits pos:pos+len(val) replaced
with bits from val).
"""
if not isinstance(val, BinWord):
raise TypeError('deposit needs a BinWord')
pos = o... | [
"def",
"deposit",
"(",
"self",
",",
"pos",
",",
"val",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"BinWord",
")",
":",
"raise",
"TypeError",
"(",
"'deposit needs a BinWord'",
")",
"pos",
"=",
"operator",
".",
"index",
"(",
"pos",
")",
"if",
... | Returns a copy of this BinInt, with a given word deposited
at a given position (ie. with bits pos:pos+len(val) replaced
with bits from val). | [
"Returns",
"a",
"copy",
"of",
"this",
"BinInt",
"with",
"a",
"given",
"word",
"deposited",
"at",
"a",
"given",
"position",
"(",
"ie",
".",
"with",
"bits",
"pos",
":",
"pos",
"+",
"len",
"(",
"val",
")",
"replaced",
"with",
"bits",
"from",
"val",
")",... | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/int.py#L84-L97 |
Brazelton-Lab/bio_utils | bio_utils/blast_tools/blast_to_cigar.py | blast_to_cigar | def blast_to_cigar(query_seq, match_seq, subject_seq, cigar_age='new'):
"""converts BLAST alignment into a old or new CIGAR line
Args:
query_seq (str): Aligned portion of query sequence
match_seq (str): Alignment sequence
subject_seq (str): Aligned portion of subject/reference sequenc... | python | def blast_to_cigar(query_seq, match_seq, subject_seq, cigar_age='new'):
"""converts BLAST alignment into a old or new CIGAR line
Args:
query_seq (str): Aligned portion of query sequence
match_seq (str): Alignment sequence
subject_seq (str): Aligned portion of subject/reference sequenc... | [
"def",
"blast_to_cigar",
"(",
"query_seq",
",",
"match_seq",
",",
"subject_seq",
",",
"cigar_age",
"=",
"'new'",
")",
":",
"if",
"not",
"len",
"(",
"query_seq",
")",
"==",
"len",
"(",
"match_seq",
")",
"or",
"not",
"len",
"(",
"query_seq",
")",
"==",
"... | converts BLAST alignment into a old or new CIGAR line
Args:
query_seq (str): Aligned portion of query sequence
match_seq (str): Alignment sequence
subject_seq (str): Aligned portion of subject/reference sequence
cigar_age (str): ['old', 'new'] CIGAR format to use, new is highly
... | [
"converts",
"BLAST",
"alignment",
"into",
"a",
"old",
"or",
"new",
"CIGAR",
"line"
] | train | https://github.com/Brazelton-Lab/bio_utils/blob/5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7/bio_utils/blast_tools/blast_to_cigar.py#L32-L113 |
edeposit/isbn_validator | src/isbn_validator/isbn_validator.py | _clean_isbn | def _clean_isbn(isbn):
"""
Remove all non-digit and non "x" characters from given string.
Args:
isbn (str): isbn string, which will be cleaned.
Returns:
list: array of numbers (if "x" is found, it is converted to 10).
"""
if isinstance(isbn, basestring):
isbn = list(isb... | python | def _clean_isbn(isbn):
"""
Remove all non-digit and non "x" characters from given string.
Args:
isbn (str): isbn string, which will be cleaned.
Returns:
list: array of numbers (if "x" is found, it is converted to 10).
"""
if isinstance(isbn, basestring):
isbn = list(isb... | [
"def",
"_clean_isbn",
"(",
"isbn",
")",
":",
"if",
"isinstance",
"(",
"isbn",
",",
"basestring",
")",
":",
"isbn",
"=",
"list",
"(",
"isbn",
".",
"lower",
"(",
")",
")",
"# filter digits and \"x\"",
"isbn",
"=",
"filter",
"(",
"lambda",
"x",
":",
"x",
... | Remove all non-digit and non "x" characters from given string.
Args:
isbn (str): isbn string, which will be cleaned.
Returns:
list: array of numbers (if "x" is found, it is converted to 10). | [
"Remove",
"all",
"non",
"-",
"digit",
"and",
"non",
"x",
"characters",
"from",
"given",
"string",
"."
] | train | https://github.com/edeposit/isbn_validator/blob/d285846940a8f71bac5a4694f640c026510d9063/src/isbn_validator/isbn_validator.py#L18-L35 |
edeposit/isbn_validator | src/isbn_validator/isbn_validator.py | _isbn_cleaner | def _isbn_cleaner(fn):
"""
Decorator for calling other functions from this module.
Purpose of this decorator is to clean the ISBN string from garbage and
return list of digits.
Args:
fn (function): function in which will be :func:`_clean_isbn(isbn)` call
wrapped.
... | python | def _isbn_cleaner(fn):
"""
Decorator for calling other functions from this module.
Purpose of this decorator is to clean the ISBN string from garbage and
return list of digits.
Args:
fn (function): function in which will be :func:`_clean_isbn(isbn)` call
wrapped.
... | [
"def",
"_isbn_cleaner",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"isbn",
")",
":",
"return",
"fn",
"(",
"_clean_isbn",
"(",
"isbn",
")",
")",
"return",
"wrapper"
] | Decorator for calling other functions from this module.
Purpose of this decorator is to clean the ISBN string from garbage and
return list of digits.
Args:
fn (function): function in which will be :func:`_clean_isbn(isbn)` call
wrapped. | [
"Decorator",
"for",
"calling",
"other",
"functions",
"from",
"this",
"module",
"."
] | train | https://github.com/edeposit/isbn_validator/blob/d285846940a8f71bac5a4694f640c026510d9063/src/isbn_validator/isbn_validator.py#L38-L53 |
edeposit/isbn_validator | src/isbn_validator/isbn_validator.py | get_isbn13_checksum | def get_isbn13_checksum(isbn):
"""
Args:
isbn (str/list): ISBN number as string or list of digits.
Warning:
Function expects that `isbn` is only 12 digits long.
Returns:
int: Last checksum digit for given `isbn`.
"""
multipliers = map(lambda x: int(x), list("13" * 6))
... | python | def get_isbn13_checksum(isbn):
"""
Args:
isbn (str/list): ISBN number as string or list of digits.
Warning:
Function expects that `isbn` is only 12 digits long.
Returns:
int: Last checksum digit for given `isbn`.
"""
multipliers = map(lambda x: int(x), list("13" * 6))
... | [
"def",
"get_isbn13_checksum",
"(",
"isbn",
")",
":",
"multipliers",
"=",
"map",
"(",
"lambda",
"x",
":",
"int",
"(",
"x",
")",
",",
"list",
"(",
"\"13\"",
"*",
"6",
")",
")",
"rest",
"=",
"sum",
"(",
"[",
"i",
"*",
"x",
"for",
"i",
",",
"x",
... | Args:
isbn (str/list): ISBN number as string or list of digits.
Warning:
Function expects that `isbn` is only 12 digits long.
Returns:
int: Last checksum digit for given `isbn`. | [
"Args",
":",
"isbn",
"(",
"str",
"/",
"list",
")",
":",
"ISBN",
"number",
"as",
"string",
"or",
"list",
"of",
"digits",
"."
] | train | https://github.com/edeposit/isbn_validator/blob/d285846940a8f71bac5a4694f640c026510d9063/src/isbn_validator/isbn_validator.py#L89-L107 |
edeposit/isbn_validator | src/isbn_validator/isbn_validator.py | is_valid_isbn | def is_valid_isbn(isbn):
"""
Validate given `isbn`. Wrapper for :func:`is_isbn10_valid`/
:func:`is_isbn13_valid`.
Args:
isbn (str/list): ISBN number as string or list of digits.
Note:
Function doesn't require `isbn` type to be specified (it can be both
10/13 isbn's versions... | python | def is_valid_isbn(isbn):
"""
Validate given `isbn`. Wrapper for :func:`is_isbn10_valid`/
:func:`is_isbn13_valid`.
Args:
isbn (str/list): ISBN number as string or list of digits.
Note:
Function doesn't require `isbn` type to be specified (it can be both
10/13 isbn's versions... | [
"def",
"is_valid_isbn",
"(",
"isbn",
")",
":",
"length",
"=",
"len",
"(",
"isbn",
")",
"if",
"length",
"==",
"10",
":",
"return",
"is_isbn10_valid",
"(",
"isbn",
")",
"elif",
"length",
"==",
"13",
":",
"return",
"is_isbn13_valid",
"(",
"isbn",
")",
"re... | Validate given `isbn`. Wrapper for :func:`is_isbn10_valid`/
:func:`is_isbn13_valid`.
Args:
isbn (str/list): ISBN number as string or list of digits.
Note:
Function doesn't require `isbn` type to be specified (it can be both
10/13 isbn's versions).
Returns:
bool: ``True... | [
"Validate",
"given",
"isbn",
".",
"Wrapper",
"for",
":",
"func",
":",
"is_isbn10_valid",
"/",
":",
"func",
":",
"is_isbn13_valid",
"."
] | train | https://github.com/edeposit/isbn_validator/blob/d285846940a8f71bac5a4694f640c026510d9063/src/isbn_validator/isbn_validator.py#L128-L150 |
jespino/anillo | anillo/app.py | application | def application(handler, adapter_cls=WerkzeugAdapter):
"""Converts an anillo function based handler in a
wsgi compiliant application function.
:param adapter_cls: the wsgi adapter implementation (default: wekrzeug)
:returns: wsgi function
:rtype: callable
"""
adapter = adapter_cls()
de... | python | def application(handler, adapter_cls=WerkzeugAdapter):
"""Converts an anillo function based handler in a
wsgi compiliant application function.
:param adapter_cls: the wsgi adapter implementation (default: wekrzeug)
:returns: wsgi function
:rtype: callable
"""
adapter = adapter_cls()
de... | [
"def",
"application",
"(",
"handler",
",",
"adapter_cls",
"=",
"WerkzeugAdapter",
")",
":",
"adapter",
"=",
"adapter_cls",
"(",
")",
"def",
"wrapper",
"(",
"environ",
",",
"start_response",
")",
":",
"request",
"=",
"adapter",
".",
"to_request",
"(",
"enviro... | Converts an anillo function based handler in a
wsgi compiliant application function.
:param adapter_cls: the wsgi adapter implementation (default: wekrzeug)
:returns: wsgi function
:rtype: callable | [
"Converts",
"an",
"anillo",
"function",
"based",
"handler",
"in",
"a",
"wsgi",
"compiliant",
"application",
"function",
"."
] | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/app.py#L4-L20 |
iceb0y/aiowrap | aiowrap/wrap.py | wrap_async | def wrap_async(func):
"""Wraps an asynchronous function into a synchronous function."""
@functools.wraps(func)
def wrapped(*args, **kwargs):
fut = asyncio.ensure_future(func(*args, **kwargs))
cur = greenlet.getcurrent()
def callback(fut):
try:
cur.switch(f... | python | def wrap_async(func):
"""Wraps an asynchronous function into a synchronous function."""
@functools.wraps(func)
def wrapped(*args, **kwargs):
fut = asyncio.ensure_future(func(*args, **kwargs))
cur = greenlet.getcurrent()
def callback(fut):
try:
cur.switch(f... | [
"def",
"wrap_async",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"fut",
"=",
"asyncio",
".",
"ensure_future",
"(",
"func",
"(",
"*",
"args",
",",
... | Wraps an asynchronous function into a synchronous function. | [
"Wraps",
"an",
"asynchronous",
"function",
"into",
"a",
"synchronous",
"function",
"."
] | train | https://github.com/iceb0y/aiowrap/blob/7a155e68c0faee0eea7a3f43c1e96a36ccc2fd84/aiowrap/wrap.py#L5-L18 |
iceb0y/aiowrap | aiowrap/wrap.py | wrap_sync | def wrap_sync(func):
"""Wraps a synchronous function into an asynchronous function."""
@functools.wraps(func)
def wrapped(*args, **kwargs):
fut = asyncio.Future()
def green():
try:
fut.set_result(func(*args, **kwargs))
except BaseException as e:
... | python | def wrap_sync(func):
"""Wraps a synchronous function into an asynchronous function."""
@functools.wraps(func)
def wrapped(*args, **kwargs):
fut = asyncio.Future()
def green():
try:
fut.set_result(func(*args, **kwargs))
except BaseException as e:
... | [
"def",
"wrap_sync",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"fut",
"=",
"asyncio",
".",
"Future",
"(",
")",
"def",
"green",
"(",
")",
":",
"... | Wraps a synchronous function into an asynchronous function. | [
"Wraps",
"a",
"synchronous",
"function",
"into",
"an",
"asynchronous",
"function",
"."
] | train | https://github.com/iceb0y/aiowrap/blob/7a155e68c0faee0eea7a3f43c1e96a36ccc2fd84/aiowrap/wrap.py#L20-L32 |
dwwkelly/note | note/server.py | Note_Server.Run | def Run(self):
"""
Wait for clients to connect and service them
:returns: None
"""
while True:
try:
events = self.poller.poll()
except KeyboardInterrupt:
self.context.destroy()
sys.exit()
self... | python | def Run(self):
"""
Wait for clients to connect and service them
:returns: None
"""
while True:
try:
events = self.poller.poll()
except KeyboardInterrupt:
self.context.destroy()
sys.exit()
self... | [
"def",
"Run",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"events",
"=",
"self",
".",
"poller",
".",
"poll",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"self",
".",
"context",
".",
"destroy",
"(",
")",
"sys",
".",
"exit",
"(",
")",
... | Wait for clients to connect and service them
:returns: None | [
"Wait",
"for",
"clients",
"to",
"connect",
"and",
"service",
"them"
] | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L31-L46 |
dwwkelly/note | note/server.py | Note_Server.Handle_Events | def Handle_Events(self, events):
"""
Handle events from poll()
:events: A list of tuples form zmq.poll()
:type events: list
:returns: None
"""
for e in events:
sock = e[0]
event_type = e[1]
if event_type == zmq.POLLIN:
... | python | def Handle_Events(self, events):
"""
Handle events from poll()
:events: A list of tuples form zmq.poll()
:type events: list
:returns: None
"""
for e in events:
sock = e[0]
event_type = e[1]
if event_type == zmq.POLLIN:
... | [
"def",
"Handle_Events",
"(",
"self",
",",
"events",
")",
":",
"for",
"e",
"in",
"events",
":",
"sock",
"=",
"e",
"[",
"0",
"]",
"event_type",
"=",
"e",
"[",
"1",
"]",
"if",
"event_type",
"==",
"zmq",
".",
"POLLIN",
":",
"msg",
"=",
"sock",
".",
... | Handle events from poll()
:events: A list of tuples form zmq.poll()
:type events: list
:returns: None | [
"Handle",
"events",
"from",
"poll",
"()"
] | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L48-L71 |
dwwkelly/note | note/server.py | Note_Server.Handle_Receive | def Handle_Receive(self, msg):
"""
Handle a received message.
:param msg: the received message
:type msg: str
:returns: The message to reply with
:rtype: str
"""
msg = self.Check_Message(msg)
msg_type = msg['type']
f_name = "Handle_{0}".... | python | def Handle_Receive(self, msg):
"""
Handle a received message.
:param msg: the received message
:type msg: str
:returns: The message to reply with
:rtype: str
"""
msg = self.Check_Message(msg)
msg_type = msg['type']
f_name = "Handle_{0}".... | [
"def",
"Handle_Receive",
"(",
"self",
",",
"msg",
")",
":",
"msg",
"=",
"self",
".",
"Check_Message",
"(",
"msg",
")",
"msg_type",
"=",
"msg",
"[",
"'type'",
"]",
"f_name",
"=",
"\"Handle_{0}\"",
".",
"format",
"(",
"msg_type",
")",
"try",
":",
"f",
... | Handle a received message.
:param msg: the received message
:type msg: str
:returns: The message to reply with
:rtype: str | [
"Handle",
"a",
"received",
"message",
"."
] | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L73-L93 |
dwwkelly/note | note/server.py | Note_Server.Handle_Search | def Handle_Search(self, msg):
"""
Handle a search.
:param msg: the received search
:type msg: dict
:returns: The message to reply with
:rtype: str
"""
search_term = msg['object']['searchTerm']
results = self.db.searchForItem(search_term)
... | python | def Handle_Search(self, msg):
"""
Handle a search.
:param msg: the received search
:type msg: dict
:returns: The message to reply with
:rtype: str
"""
search_term = msg['object']['searchTerm']
results = self.db.searchForItem(search_term)
... | [
"def",
"Handle_Search",
"(",
"self",
",",
"msg",
")",
":",
"search_term",
"=",
"msg",
"[",
"'object'",
"]",
"[",
"'searchTerm'",
"]",
"results",
"=",
"self",
".",
"db",
".",
"searchForItem",
"(",
"search_term",
")",
"reply",
"=",
"{",
"\"status\"",
":",
... | Handle a search.
:param msg: the received search
:type msg: dict
:returns: The message to reply with
:rtype: str | [
"Handle",
"a",
"search",
"."
] | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L103-L123 |
dwwkelly/note | note/server.py | Note_Server.Handle_Note | def Handle_Note(self, msg):
""" Handle a new note.
:param msg: the received note
:type msg: dict
:returns: The message to reply with
:rtype: str
"""
note_text = msg['object']['note']
note_tags = msg['object']['tags']
if 'ID' in msg['object']:
... | python | def Handle_Note(self, msg):
""" Handle a new note.
:param msg: the received note
:type msg: dict
:returns: The message to reply with
:rtype: str
"""
note_text = msg['object']['note']
note_tags = msg['object']['tags']
if 'ID' in msg['object']:
... | [
"def",
"Handle_Note",
"(",
"self",
",",
"msg",
")",
":",
"note_text",
"=",
"msg",
"[",
"'object'",
"]",
"[",
"'note'",
"]",
"note_tags",
"=",
"msg",
"[",
"'object'",
"]",
"[",
"'tags'",
"]",
"if",
"'ID'",
"in",
"msg",
"[",
"'object'",
"]",
":",
"no... | Handle a new note.
:param msg: the received note
:type msg: dict
:returns: The message to reply with
:rtype: str | [
"Handle",
"a",
"new",
"note",
"."
] | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L125-L154 |
dwwkelly/note | note/server.py | Note_Server.Handle_Label | def Handle_Label(self, msg):
"""
:desc: Set a label
:param dict msg: The message received from the client
:rval: str
:returns: A status message (JSON serialized to a string)
"""
obj = msg['object']
if 'name' not in obj or 'id' not in obj:
... | python | def Handle_Label(self, msg):
"""
:desc: Set a label
:param dict msg: The message received from the client
:rval: str
:returns: A status message (JSON serialized to a string)
"""
obj = msg['object']
if 'name' not in obj or 'id' not in obj:
... | [
"def",
"Handle_Label",
"(",
"self",
",",
"msg",
")",
":",
"obj",
"=",
"msg",
"[",
"'object'",
"]",
"if",
"'name'",
"not",
"in",
"obj",
"or",
"'id'",
"not",
"in",
"obj",
":",
"r_msg",
"=",
"{",
"'status'",
":",
"'ERROR'",
",",
"'type'",
":",
"'Label... | :desc: Set a label
:param dict msg: The message received from the client
:rval: str
:returns: A status message (JSON serialized to a string) | [
":",
"desc",
":",
"Set",
"a",
"label",
":",
"param",
"dict",
"msg",
":",
"The",
"message",
"received",
"from",
"the",
"client",
":",
"rval",
":",
"str",
":",
"returns",
":",
"A",
"status",
"message",
"(",
"JSON",
"serialized",
"to",
"a",
"string",
")... | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L345-L373 |
dwwkelly/note | note/server.py | Note_Server.Handle_Delete_Label | def Handle_Delete_Label(self, msg):
"""
:desc: Deletes a label
:param dic msg: The message with the instruction and the label
name to delete
:rval: str
:returns: The message from the database
"""
try:
label_... | python | def Handle_Delete_Label(self, msg):
"""
:desc: Deletes a label
:param dic msg: The message with the instruction and the label
name to delete
:rval: str
:returns: The message from the database
"""
try:
label_... | [
"def",
"Handle_Delete_Label",
"(",
"self",
",",
"msg",
")",
":",
"try",
":",
"label_name",
"=",
"msg",
"[",
"'object'",
"]",
"[",
"'label'",
"]",
"except",
"KeyError",
":",
"r_msg",
"=",
"{",
"'status'",
":",
"'ERROR'",
",",
"'type'",
":",
"'Delete_Label... | :desc: Deletes a label
:param dic msg: The message with the instruction and the label
name to delete
:rval: str
:returns: The message from the database | [
":",
"desc",
":",
"Deletes",
"a",
"label",
":",
"param",
"dic",
"msg",
":",
"The",
"message",
"with",
"the",
"instruction",
"and",
"the",
"label",
"name",
"to",
"delete",
":",
"rval",
":",
"str",
":",
"returns",
":",
"The",
"message",
"from",
"the",
... | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L375-L395 |
zimmermanncode/ganymede | ganymede/__init__.py | load | def load(shell=None, logo_src=None):
"""
Generate and return Ganymede HTML containing CSS and JavaScript
for modifying the Jupyter notebook web interface,
wrapped in a ``IPython.display.HTML`` object:
* Must be called with IPython `shell` instance as first argument.
* Optionally takes a custom ... | python | def load(shell=None, logo_src=None):
"""
Generate and return Ganymede HTML containing CSS and JavaScript
for modifying the Jupyter notebook web interface,
wrapped in a ``IPython.display.HTML`` object:
* Must be called with IPython `shell` instance as first argument.
* Optionally takes a custom ... | [
"def",
"load",
"(",
"shell",
"=",
"None",
",",
"logo_src",
"=",
"None",
")",
":",
"# make sure that .static pkg gets reloaded on %reload_ext ganymede",
"# to recompile ganymede.coffee in development (non-installed) mode",
"sys",
".",
"modules",
".",
"pop",
"(",
"'ganymede.sta... | Generate and return Ganymede HTML containing CSS and JavaScript
for modifying the Jupyter notebook web interface,
wrapped in a ``IPython.display.HTML`` object:
* Must be called with IPython `shell` instance as first argument.
* Optionally takes a custom `logo_src` value for the ``src=`` attribute
... | [
"Generate",
"and",
"return",
"Ganymede",
"HTML",
"containing",
"CSS",
"and",
"JavaScript",
"for",
"modifying",
"the",
"Jupyter",
"notebook",
"web",
"interface",
"wrapped",
"in",
"a",
"IPython",
".",
"display",
".",
"HTML",
"object",
":"
] | train | https://github.com/zimmermanncode/ganymede/blob/3f37bbade93f37e5f80eaf1afcbc01f11ad1d153/ganymede/__init__.py#L27-L69 |
ericflo/hurricane | hurricane/utils.py | RingBuffer.after_match | def after_match(self, func, full_fallback=False):
"""Returns an iterator for all the elements after the first
match. If `full_fallback` is `True`, it will return all the
messages if the function never matched.
"""
iterator = iter(self)
for item in iterator:
i... | python | def after_match(self, func, full_fallback=False):
"""Returns an iterator for all the elements after the first
match. If `full_fallback` is `True`, it will return all the
messages if the function never matched.
"""
iterator = iter(self)
for item in iterator:
i... | [
"def",
"after_match",
"(",
"self",
",",
"func",
",",
"full_fallback",
"=",
"False",
")",
":",
"iterator",
"=",
"iter",
"(",
"self",
")",
"for",
"item",
"in",
"iterator",
":",
"if",
"func",
"(",
"item",
")",
":",
"return",
"iterator",
"if",
"full_fallba... | Returns an iterator for all the elements after the first
match. If `full_fallback` is `True`, it will return all the
messages if the function never matched. | [
"Returns",
"an",
"iterator",
"for",
"all",
"the",
"elements",
"after",
"the",
"first",
"match",
".",
"If",
"full_fallback",
"is",
"True",
"it",
"will",
"return",
"all",
"the",
"messages",
"if",
"the",
"function",
"never",
"matched",
"."
] | train | https://github.com/ericflo/hurricane/blob/c192b711b2b1c06a386d1a1a47f538b13a659cde/hurricane/utils.py#L112-L123 |
FujiMakoto/AgentML | agentml/parser/trigger/__init__.py | Trigger.match | def match(self, user, message):
"""
Returns a response message if a match is found, otherwise None
:param user: The requesting client
:type user: agentml.User
:param message: The message to match
:type message: agentml.Message
:rtype: str or None
"""
... | python | def match(self, user, message):
"""
Returns a response message if a match is found, otherwise None
:param user: The requesting client
:type user: agentml.User
:param message: The message to match
:type message: agentml.Message
:rtype: str or None
"""
... | [
"def",
"match",
"(",
"self",
",",
"user",
",",
"message",
")",
":",
"self",
".",
"_log",
".",
"info",
"(",
"'Attempting to match message against Pattern: {pattern}'",
".",
"format",
"(",
"pattern",
"=",
"self",
".",
"pattern",
".",
"pattern",
"if",
"hasattr",
... | Returns a response message if a match is found, otherwise None
:param user: The requesting client
:type user: agentml.User
:param message: The message to match
:type message: agentml.Message
:rtype: str or None | [
"Returns",
"a",
"response",
"message",
"if",
"a",
"match",
"is",
"found",
"otherwise",
"None",
":",
"param",
"user",
":",
"The",
"requesting",
"client",
":",
"type",
"user",
":",
"agentml",
".",
"User"
] | train | https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/parser/trigger/__init__.py#L63-L158 |
FujiMakoto/AgentML | agentml/parser/trigger/__init__.py | Trigger.apply_reactions | def apply_reactions(self, user):
"""
Set active topics and limits after a response has been triggered
:param user: The user triggering the response
:type user: agentml.User
"""
# User attributes
if self.global_limit:
self._log.info('Enforcing Global T... | python | def apply_reactions(self, user):
"""
Set active topics and limits after a response has been triggered
:param user: The user triggering the response
:type user: agentml.User
"""
# User attributes
if self.global_limit:
self._log.info('Enforcing Global T... | [
"def",
"apply_reactions",
"(",
"self",
",",
"user",
")",
":",
"# User attributes",
"if",
"self",
".",
"global_limit",
":",
"self",
".",
"_log",
".",
"info",
"(",
"'Enforcing Global Trigger Limit of {num} seconds'",
".",
"format",
"(",
"num",
"=",
"self",
".",
... | Set active topics and limits after a response has been triggered
:param user: The user triggering the response
:type user: agentml.User | [
"Set",
"active",
"topics",
"and",
"limits",
"after",
"a",
"response",
"has",
"been",
"triggered",
":",
"param",
"user",
":",
"The",
"user",
"triggering",
"the",
"response",
":",
"type",
"user",
":",
"agentml",
".",
"User"
] | train | https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/parser/trigger/__init__.py#L160-L186 |
FujiMakoto/AgentML | agentml/parser/trigger/__init__.py | Trigger._add_response | def _add_response(self, response, weight=1):
"""
Add a new trigger
:param response: The Response object
:type response: Response or Condition
:param weight: The weight of the response
:type weight: int
"""
# If no response with this priority level has b... | python | def _add_response(self, response, weight=1):
"""
Add a new trigger
:param response: The Response object
:type response: Response or Condition
:param weight: The weight of the response
:type weight: int
"""
# If no response with this priority level has b... | [
"def",
"_add_response",
"(",
"self",
",",
"response",
",",
"weight",
"=",
"1",
")",
":",
"# If no response with this priority level has been defined yet, create a new list",
"if",
"response",
".",
"priority",
"not",
"in",
"self",
".",
"_responses",
":",
"self",
".",
... | Add a new trigger
:param response: The Response object
:type response: Response or Condition
:param weight: The weight of the response
:type weight: int | [
"Add",
"a",
"new",
"trigger",
":",
"param",
"response",
":",
"The",
"Response",
"object",
":",
"type",
"response",
":",
"Response",
"or",
"Condition"
] | train | https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/parser/trigger/__init__.py#L190-L205 |
FujiMakoto/AgentML | agentml/parser/trigger/__init__.py | Trigger.replace_wildcards | def replace_wildcards(string, wildcard, regex):
"""
Replace wildcard symbols with regular expressions
:param wildcard:
:type wildcard: _sre.SRE_Pattern
:param regex:
:type regex: str
:rtype: tuple of (str, bool)
"""
replaced = False
mat... | python | def replace_wildcards(string, wildcard, regex):
"""
Replace wildcard symbols with regular expressions
:param wildcard:
:type wildcard: _sre.SRE_Pattern
:param regex:
:type regex: str
:rtype: tuple of (str, bool)
"""
replaced = False
mat... | [
"def",
"replace_wildcards",
"(",
"string",
",",
"wildcard",
",",
"regex",
")",
":",
"replaced",
"=",
"False",
"match",
"=",
"wildcard",
".",
"search",
"(",
"string",
")",
"if",
"match",
":",
"string",
"=",
"wildcard",
".",
"sub",
"(",
"regex",
",",
"st... | Replace wildcard symbols with regular expressions
:param wildcard:
:type wildcard: _sre.SRE_Pattern
:param regex:
:type regex: str
:rtype: tuple of (str, bool) | [
"Replace",
"wildcard",
"symbols",
"with",
"regular",
"expressions",
":",
"param",
"wildcard",
":",
":",
"type",
"wildcard",
":",
"_sre",
".",
"SRE_Pattern"
] | train | https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/parser/trigger/__init__.py#L208-L227 |
FujiMakoto/AgentML | agentml/parser/trigger/__init__.py | Trigger.count_words | def count_words(pattern):
"""
Count the number of words in a pattern as well as the total length of those words
:param pattern: The pattern to parse
:type pattern: str
:return: The word count first, then the total length of all words
:rtype : tuple of (int, int)
... | python | def count_words(pattern):
"""
Count the number of words in a pattern as well as the total length of those words
:param pattern: The pattern to parse
:type pattern: str
:return: The word count first, then the total length of all words
:rtype : tuple of (int, int)
... | [
"def",
"count_words",
"(",
"pattern",
")",
":",
"word_pattern",
"=",
"re",
".",
"compile",
"(",
"r'(\\b(?<![\\(\\)\\[\\]\\|])\\w\\w*\\b(?![\\(\\)\\[\\]\\|]))'",
",",
"re",
".",
"IGNORECASE",
")",
"words",
"=",
"word_pattern",
".",
"findall",
"(",
"pattern",
")",
"... | Count the number of words in a pattern as well as the total length of those words
:param pattern: The pattern to parse
:type pattern: str
:return: The word count first, then the total length of all words
:rtype : tuple of (int, int) | [
"Count",
"the",
"number",
"of",
"words",
"in",
"a",
"pattern",
"as",
"well",
"as",
"the",
"total",
"length",
"of",
"those",
"words",
":",
"param",
"pattern",
":",
"The",
"pattern",
"to",
"parse",
":",
"type",
"pattern",
":",
"str"
] | train | https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/parser/trigger/__init__.py#L230-L245 |
FujiMakoto/AgentML | agentml/parser/trigger/__init__.py | Trigger._parse_group | def _parse_group(self, element):
"""
Parse and add a group requirement for this trigger
:param element: The XML Element object
:type element: etree._Element
"""
self._log.debug('Adding Trigger group: {group}'.format(group=element.text))
if isinstance(self.groups,... | python | def _parse_group(self, element):
"""
Parse and add a group requirement for this trigger
:param element: The XML Element object
:type element: etree._Element
"""
self._log.debug('Adding Trigger group: {group}'.format(group=element.text))
if isinstance(self.groups,... | [
"def",
"_parse_group",
"(",
"self",
",",
"element",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"'Adding Trigger group: {group}'",
".",
"format",
"(",
"group",
"=",
"element",
".",
"text",
")",
")",
"if",
"isinstance",
"(",
"self",
".",
"groups",
"... | Parse and add a group requirement for this trigger
:param element: The XML Element object
:type element: etree._Element | [
"Parse",
"and",
"add",
"a",
"group",
"requirement",
"for",
"this",
"trigger",
":",
"param",
"element",
":",
"The",
"XML",
"Element",
"object",
":",
"type",
"element",
":",
"etree",
".",
"_Element"
] | train | https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/parser/trigger/__init__.py#L256-L269 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.