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 |
|---|---|---|---|---|---|---|---|---|---|---|
lucasmaystre/choix | choix/mm.py | choicerank | def choicerank(
digraph, traffic_in, traffic_out, weight=None,
initial_params=None, alpha=1.0, max_iter=10000, tol=1e-8):
"""Compute the MAP estimate of a network choice model's parameters.
This function computes the maximum-a-posteriori (MAP) estimate of model
parameters given a network st... | python | def choicerank(
digraph, traffic_in, traffic_out, weight=None,
initial_params=None, alpha=1.0, max_iter=10000, tol=1e-8):
"""Compute the MAP estimate of a network choice model's parameters.
This function computes the maximum-a-posteriori (MAP) estimate of model
parameters given a network st... | [
"def",
"choicerank",
"(",
"digraph",
",",
"traffic_in",
",",
"traffic_out",
",",
"weight",
"=",
"None",
",",
"initial_params",
"=",
"None",
",",
"alpha",
"=",
"1.0",
",",
"max_iter",
"=",
"10000",
",",
"tol",
"=",
"1e-8",
")",
":",
"import",
"networkx",
... | Compute the MAP estimate of a network choice model's parameters.
This function computes the maximum-a-posteriori (MAP) estimate of model
parameters given a network structure and node-level traffic data (see
:ref:`data-network`), using the ChoiceRank algorithm [MG17]_, [KTVV15]_.
The nodes are assumed ... | [
"Compute",
"the",
"MAP",
"estimate",
"of",
"a",
"network",
"choice",
"model",
"s",
"parameters",
"."
] | train | https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/mm.py#L198-L252 |
balabit/typesafety | typesafety/validator.py | Validator.decorate | def decorate(cls, function):
'''
Decorate a function so the function call is checked whenever
a call is made. The calls that do not need any checks are skipped.
The `function` argument is the function to be decorated.
The return value will be either
* the function itse... | python | def decorate(cls, function):
'''
Decorate a function so the function call is checked whenever
a call is made. The calls that do not need any checks are skipped.
The `function` argument is the function to be decorated.
The return value will be either
* the function itse... | [
"def",
"decorate",
"(",
"cls",
",",
"function",
")",
":",
"should_skip",
"=",
"getattr",
"(",
"function",
",",
"'typesafety_skip'",
",",
"False",
")",
"if",
"cls",
".",
"is_function_validated",
"(",
"function",
")",
"or",
"should_skip",
":",
"return",
"funct... | Decorate a function so the function call is checked whenever
a call is made. The calls that do not need any checks are skipped.
The `function` argument is the function to be decorated.
The return value will be either
* the function itself, if there is nothing to validate, or
*... | [
"Decorate",
"a",
"function",
"so",
"the",
"function",
"call",
"is",
"checked",
"whenever",
"a",
"call",
"is",
"made",
".",
"The",
"calls",
"that",
"do",
"not",
"need",
"any",
"checks",
"are",
"skipped",
"."
] | train | https://github.com/balabit/typesafety/blob/452242dd93da9ebd53c173c243156d1351cd96fd/typesafety/validator.py#L75-L104 |
balabit/typesafety | typesafety/validator.py | Validator.undecorate | def undecorate(cls, function):
'''
Remove validator decoration from a function.
The `function` argument is the function to be cleaned from
the validator decorator.
'''
if cls.is_function_validated(function):
return cls.get_function_validator(function).functi... | python | def undecorate(cls, function):
'''
Remove validator decoration from a function.
The `function` argument is the function to be cleaned from
the validator decorator.
'''
if cls.is_function_validated(function):
return cls.get_function_validator(function).functi... | [
"def",
"undecorate",
"(",
"cls",
",",
"function",
")",
":",
"if",
"cls",
".",
"is_function_validated",
"(",
"function",
")",
":",
"return",
"cls",
".",
"get_function_validator",
"(",
"function",
")",
".",
"function",
"return",
"function"
] | Remove validator decoration from a function.
The `function` argument is the function to be cleaned from
the validator decorator. | [
"Remove",
"validator",
"decoration",
"from",
"a",
"function",
"."
] | train | https://github.com/balabit/typesafety/blob/452242dd93da9ebd53c173c243156d1351cd96fd/typesafety/validator.py#L107-L118 |
balabit/typesafety | typesafety/validator.py | Validator.validate_arguments | def validate_arguments(self, locals_dict):
'''
Validate the arguments passed to a function. If an error occurred,
the function will throw a TypesafetyError.
The `locals_dict` argument should be the local value dictionary of
the function. An example call would be like:
''... | python | def validate_arguments(self, locals_dict):
'''
Validate the arguments passed to a function. If an error occurred,
the function will throw a TypesafetyError.
The `locals_dict` argument should be the local value dictionary of
the function. An example call would be like:
''... | [
"def",
"validate_arguments",
"(",
"self",
",",
"locals_dict",
")",
":",
"for",
"key",
",",
"value",
",",
"validator",
"in",
"self",
".",
"__map_arguments",
"(",
"locals_dict",
")",
":",
"if",
"not",
"self",
".",
"__is_valid",
"(",
"value",
",",
"validator"... | Validate the arguments passed to a function. If an error occurred,
the function will throw a TypesafetyError.
The `locals_dict` argument should be the local value dictionary of
the function. An example call would be like: | [
"Validate",
"the",
"arguments",
"passed",
"to",
"a",
"function",
".",
"If",
"an",
"error",
"occurred",
"the",
"function",
"will",
"throw",
"a",
"TypesafetyError",
"."
] | train | https://github.com/balabit/typesafety/blob/452242dd93da9ebd53c173c243156d1351cd96fd/typesafety/validator.py#L155-L174 |
balabit/typesafety | typesafety/validator.py | Validator.validate_return_value | def validate_return_value(self, retval):
'''
Validate the return value of a function call. If an error occurred,
the function will throw a TypesafetyError.
The `retval` should contain the return value of the function call.
'''
if self.__return_annotation is None:
... | python | def validate_return_value(self, retval):
'''
Validate the return value of a function call. If an error occurred,
the function will throw a TypesafetyError.
The `retval` should contain the return value of the function call.
'''
if self.__return_annotation is None:
... | [
"def",
"validate_return_value",
"(",
"self",
",",
"retval",
")",
":",
"if",
"self",
".",
"__return_annotation",
"is",
"None",
":",
"return",
"if",
"not",
"self",
".",
"__is_valid",
"(",
"retval",
",",
"self",
".",
"__return_annotation",
")",
":",
"func_name"... | Validate the return value of a function call. If an error occurred,
the function will throw a TypesafetyError.
The `retval` should contain the return value of the function call. | [
"Validate",
"the",
"return",
"value",
"of",
"a",
"function",
"call",
".",
"If",
"an",
"error",
"occurred",
"the",
"function",
"will",
"throw",
"a",
"TypesafetyError",
"."
] | train | https://github.com/balabit/typesafety/blob/452242dd93da9ebd53c173c243156d1351cd96fd/typesafety/validator.py#L190-L208 |
balabit/typesafety | typesafety/finder.py | ModuleFinder.uninstall | def uninstall(self):
'''
Uninstall the module finder. If not installed, this will do nothing.
After uninstallation, none of the newly loaded modules will be
decorated (that is, everything will be back to normal).
'''
if self.installed:
sys.meta_path.remove(se... | python | def uninstall(self):
'''
Uninstall the module finder. If not installed, this will do nothing.
After uninstallation, none of the newly loaded modules will be
decorated (that is, everything will be back to normal).
'''
if self.installed:
sys.meta_path.remove(se... | [
"def",
"uninstall",
"(",
"self",
")",
":",
"if",
"self",
".",
"installed",
":",
"sys",
".",
"meta_path",
".",
"remove",
"(",
"self",
")",
"# Reload all decorated items",
"import_list",
"=",
"[",
"]",
"for",
"name",
"in",
"self",
".",
"__loaded_modules",
":... | Uninstall the module finder. If not installed, this will do nothing.
After uninstallation, none of the newly loaded modules will be
decorated (that is, everything will be back to normal). | [
"Uninstall",
"the",
"module",
"finder",
".",
"If",
"not",
"installed",
"this",
"will",
"do",
"nothing",
".",
"After",
"uninstallation",
"none",
"of",
"the",
"newly",
"loaded",
"modules",
"will",
"be",
"decorated",
"(",
"that",
"is",
"everything",
"will",
"be... | train | https://github.com/balabit/typesafety/blob/452242dd93da9ebd53c173c243156d1351cd96fd/typesafety/finder.py#L116-L135 |
balabit/typesafety | typesafety/finder.py | ModuleFinder.find_module | def find_module(self, fullname, path=None):
'''
Find the module. Required for the Python meta-loading mechanism.
This will do nothing, since we use the system to locate a module.
'''
loader = None
if self.__filter is None or self.__filter(fullname):
loader =... | python | def find_module(self, fullname, path=None):
'''
Find the module. Required for the Python meta-loading mechanism.
This will do nothing, since we use the system to locate a module.
'''
loader = None
if self.__filter is None or self.__filter(fullname):
loader =... | [
"def",
"find_module",
"(",
"self",
",",
"fullname",
",",
"path",
"=",
"None",
")",
":",
"loader",
"=",
"None",
"if",
"self",
".",
"__filter",
"is",
"None",
"or",
"self",
".",
"__filter",
"(",
"fullname",
")",
":",
"loader",
"=",
"ModuleLoader",
"(",
... | Find the module. Required for the Python meta-loading mechanism.
This will do nothing, since we use the system to locate a module. | [
"Find",
"the",
"module",
".",
"Required",
"for",
"the",
"Python",
"meta",
"-",
"loading",
"mechanism",
"."
] | train | https://github.com/balabit/typesafety/blob/452242dd93da9ebd53c173c243156d1351cd96fd/typesafety/finder.py#L137-L148 |
balabit/typesafety | typesafety/finder.py | ModuleFinder.load_module | def load_module(self, loader):
'''
Load the module. Required for the Python meta-loading mechanism.
'''
modfile, pathname, description = loader.info
module = imp.load_module(
loader.fullname,
modfile,
pathname,
description
... | python | def load_module(self, loader):
'''
Load the module. Required for the Python meta-loading mechanism.
'''
modfile, pathname, description = loader.info
module = imp.load_module(
loader.fullname,
modfile,
pathname,
description
... | [
"def",
"load_module",
"(",
"self",
",",
"loader",
")",
":",
"modfile",
",",
"pathname",
",",
"description",
"=",
"loader",
".",
"info",
"module",
"=",
"imp",
".",
"load_module",
"(",
"loader",
".",
"fullname",
",",
"modfile",
",",
"pathname",
",",
"descr... | Load the module. Required for the Python meta-loading mechanism. | [
"Load",
"the",
"module",
".",
"Required",
"for",
"the",
"Python",
"meta",
"-",
"loading",
"mechanism",
"."
] | train | https://github.com/balabit/typesafety/blob/452242dd93da9ebd53c173c243156d1351cd96fd/typesafety/finder.py#L150-L167 |
OnroerendErfgoed/oe_utils | oe_utils/search/indexer.py | Indexer._register_event_listeners | def _register_event_listeners(self, cls):
"""
:param cls: DB class
"""
event.listen(cls, 'after_insert', self._new_listener)
event.listen(cls, 'after_update', self._update_listener)
event.listen(cls, 'after_delete', self._delete_listener) | python | def _register_event_listeners(self, cls):
"""
:param cls: DB class
"""
event.listen(cls, 'after_insert', self._new_listener)
event.listen(cls, 'after_update', self._update_listener)
event.listen(cls, 'after_delete', self._delete_listener) | [
"def",
"_register_event_listeners",
"(",
"self",
",",
"cls",
")",
":",
"event",
".",
"listen",
"(",
"cls",
",",
"'after_insert'",
",",
"self",
".",
"_new_listener",
")",
"event",
".",
"listen",
"(",
"cls",
",",
"'after_update'",
",",
"self",
".",
"_update_... | :param cls: DB class | [
":",
"param",
"cls",
":",
"DB",
"class"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/search/indexer.py#L31-L37 |
OnroerendErfgoed/oe_utils | oe_utils/search/indexer.py | Indexer.after_commit_listener | def after_commit_listener(self, session):
"""
Processing the changes.
All new or changed items are now indexed. All deleted items are now removed from the index.
"""
log.info('Commiting indexing orders for session %s' % session)
try:
if not any((session.index_... | python | def after_commit_listener(self, session):
"""
Processing the changes.
All new or changed items are now indexed. All deleted items are now removed from the index.
"""
log.info('Commiting indexing orders for session %s' % session)
try:
if not any((session.index_... | [
"def",
"after_commit_listener",
"(",
"self",
",",
"session",
")",
":",
"log",
".",
"info",
"(",
"'Commiting indexing orders for session %s'",
"%",
"session",
")",
"try",
":",
"if",
"not",
"any",
"(",
"(",
"session",
".",
"index_new",
"[",
"self",
".",
"cls_n... | Processing the changes.
All new or changed items are now indexed. All deleted items are now removed from the index. | [
"Processing",
"the",
"changes",
".",
"All",
"new",
"or",
"changed",
"items",
"are",
"now",
"indexed",
".",
"All",
"deleted",
"items",
"are",
"now",
"removed",
"from",
"the",
"index",
"."
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/search/indexer.py#L63-L94 |
OnroerendErfgoed/oe_utils | oe_utils/search/indexer.py | Indexer._queue_job | def _queue_job(redis, queue_name, delegate, *args):
"""
creates a new job on the queue
:param redis: redis
:param delegate: method to be executed by the queue. Use fully qualified method name as String.
:param args: arguments of the method
:return: jo... | python | def _queue_job(redis, queue_name, delegate, *args):
"""
creates a new job on the queue
:param redis: redis
:param delegate: method to be executed by the queue. Use fully qualified method name as String.
:param args: arguments of the method
:return: jo... | [
"def",
"_queue_job",
"(",
"redis",
",",
"queue_name",
",",
"delegate",
",",
"*",
"args",
")",
":",
"log",
".",
"info",
"(",
"'Queuing job...'",
")",
"with",
"Connection",
"(",
"redis",
")",
":",
"q",
"=",
"Queue",
"(",
"queue_name",
")",
"job",
"=",
... | creates a new job on the queue
:param redis: redis
:param delegate: method to be executed by the queue. Use fully qualified method name as String.
:param args: arguments of the method
:return: job_id | [
"creates",
"a",
"new",
"job",
"on",
"the",
"queue",
":",
"param",
"redis",
":",
"redis",
":",
"param",
"delegate",
":",
"method",
"to",
"be",
"executed",
"by",
"the",
"queue",
".",
"Use",
"fully",
"qualified",
"method",
"name",
"as",
"String",
".",
":"... | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/search/indexer.py#L97-L109 |
OnroerendErfgoed/oe_utils | oe_utils/search/indexer.py | Indexer.after_rollback_listener | def after_rollback_listener(self, session):
"""
Rollback of the transaction, undo the indexes.
If our transaction is terminated, we will reset the
indexing assignments.
"""
log.info('Removing indexing orders.')
try:
session.index_new[self.cls_name].cle... | python | def after_rollback_listener(self, session):
"""
Rollback of the transaction, undo the indexes.
If our transaction is terminated, we will reset the
indexing assignments.
"""
log.info('Removing indexing orders.')
try:
session.index_new[self.cls_name].cle... | [
"def",
"after_rollback_listener",
"(",
"self",
",",
"session",
")",
":",
"log",
".",
"info",
"(",
"'Removing indexing orders.'",
")",
"try",
":",
"session",
".",
"index_new",
"[",
"self",
".",
"cls_name",
"]",
".",
"clear",
"(",
")",
"session",
".",
"index... | Rollback of the transaction, undo the indexes.
If our transaction is terminated, we will reset the
indexing assignments. | [
"Rollback",
"of",
"the",
"transaction",
"undo",
"the",
"indexes",
".",
"If",
"our",
"transaction",
"is",
"terminated",
"we",
"will",
"reset",
"the",
"indexing",
"assignments",
"."
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/search/indexer.py#L111-L123 |
OnroerendErfgoed/oe_utils | oe_utils/search/indexer.py | Indexer.remove_session | def remove_session(self, session):
"""
:param sqlalchemy.session.Session session: Database session to remove
"""
try:
del session.redis
except AttributeError:
pass
try:
del session.index_new[self.cls_name]
del session.index_... | python | def remove_session(self, session):
"""
:param sqlalchemy.session.Session session: Database session to remove
"""
try:
del session.redis
except AttributeError:
pass
try:
del session.index_new[self.cls_name]
del session.index_... | [
"def",
"remove_session",
"(",
"self",
",",
"session",
")",
":",
"try",
":",
"del",
"session",
".",
"redis",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"del",
"session",
".",
"index_new",
"[",
"self",
".",
"cls_name",
"]",
"del",
"session",
".",... | :param sqlalchemy.session.Session session: Database session to remove | [
":",
"param",
"sqlalchemy",
".",
"session",
".",
"Session",
"session",
":",
"Database",
"session",
"to",
"remove"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/search/indexer.py#L125-L139 |
OnroerendErfgoed/oe_utils | oe_utils/search/__init__.py | parse_sort_string | def parse_sort_string(sort):
"""
Parse a sort string for use with elasticsearch
:param: sort: the sort string
"""
if sort is None:
return ['_score']
l = sort.rsplit(',')
sortlist = []
for se in l:
se = se.strip()
order = 'desc' if se[0:1] == '-' else 'asc'
... | python | def parse_sort_string(sort):
"""
Parse a sort string for use with elasticsearch
:param: sort: the sort string
"""
if sort is None:
return ['_score']
l = sort.rsplit(',')
sortlist = []
for se in l:
se = se.strip()
order = 'desc' if se[0:1] == '-' else 'asc'
... | [
"def",
"parse_sort_string",
"(",
"sort",
")",
":",
"if",
"sort",
"is",
"None",
":",
"return",
"[",
"'_score'",
"]",
"l",
"=",
"sort",
".",
"rsplit",
"(",
"','",
")",
"sortlist",
"=",
"[",
"]",
"for",
"se",
"in",
"l",
":",
"se",
"=",
"se",
".",
... | Parse a sort string for use with elasticsearch
:param: sort: the sort string | [
"Parse",
"a",
"sort",
"string",
"for",
"use",
"with",
"elasticsearch"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/search/__init__.py#L22-L39 |
OnroerendErfgoed/oe_utils | oe_utils/search/__init__.py | parse_filter_params | def parse_filter_params(query_params, filterable):
"""
Parse query_params to a filter params dict. Merge multiple values for one key to a list.
Filter out keys that aren't filterable.
:param query_params: query params
:param filterable: list of filterable keys
:return: dict of filter values
... | python | def parse_filter_params(query_params, filterable):
"""
Parse query_params to a filter params dict. Merge multiple values for one key to a list.
Filter out keys that aren't filterable.
:param query_params: query params
:param filterable: list of filterable keys
:return: dict of filter values
... | [
"def",
"parse_filter_params",
"(",
"query_params",
",",
"filterable",
")",
":",
"if",
"query_params",
"is",
"not",
"None",
":",
"filter_params",
"=",
"{",
"}",
"for",
"fq",
"in",
"query_params",
".",
"mixed",
"(",
")",
":",
"if",
"fq",
"in",
"filterable",
... | Parse query_params to a filter params dict. Merge multiple values for one key to a list.
Filter out keys that aren't filterable.
:param query_params: query params
:param filterable: list of filterable keys
:return: dict of filter values | [
"Parse",
"query_params",
"to",
"a",
"filter",
"params",
"dict",
".",
"Merge",
"multiple",
"values",
"for",
"one",
"key",
"to",
"a",
"list",
".",
"Filter",
"out",
"keys",
"that",
"aren",
"t",
"filterable",
"."
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/search/__init__.py#L42-L58 |
OnroerendErfgoed/oe_utils | oe_utils/views/atom.py | AtomFeedView.link_to_sibling | def link_to_sibling(self, feed, sibling_type, atom_feed):
"""
Adding previous or next links to the given feed
self._link_to_sibling(feed, 'previous', atom_feed)
self._link_to_sibling(feed, 'next', atom_feed)
:param feed: a feed object
:param sibling_type: 'previous' or '... | python | def link_to_sibling(self, feed, sibling_type, atom_feed):
"""
Adding previous or next links to the given feed
self._link_to_sibling(feed, 'previous', atom_feed)
self._link_to_sibling(feed, 'next', atom_feed)
:param feed: a feed object
:param sibling_type: 'previous' or '... | [
"def",
"link_to_sibling",
"(",
"self",
",",
"feed",
",",
"sibling_type",
",",
"atom_feed",
")",
":",
"sibling",
"=",
"self",
".",
"atom_feed_manager",
".",
"get_sibling",
"(",
"feed",
".",
"id",
",",
"sibling_type",
")",
"if",
"sibling",
":",
"rel",
"=",
... | Adding previous or next links to the given feed
self._link_to_sibling(feed, 'previous', atom_feed)
self._link_to_sibling(feed, 'next', atom_feed)
:param feed: a feed object
:param sibling_type: 'previous' or 'next'
:param atom_feed: an atom feed like `feedgen.feed.FeedGenerator` | [
"Adding",
"previous",
"or",
"next",
"links",
"to",
"the",
"given",
"feed",
"self",
".",
"_link_to_sibling",
"(",
"feed",
"previous",
"atom_feed",
")",
"self",
".",
"_link_to_sibling",
"(",
"feed",
"next",
"atom_feed",
")"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/views/atom.py#L116-L130 |
OnroerendErfgoed/oe_utils | oe_utils/views/atom.py | AtomFeedView.init_atom_feed | def init_atom_feed(self, feed):
"""
Initializing an atom feed `feedgen.feed.FeedGenerator` given a feed object
:param feed: a feed object
:return: an atom feed `feedgen.feed.FeedGenerator`
"""
atom_feed = FeedGenerator()
atom_feed.id(id=self.request.route_url(sel... | python | def init_atom_feed(self, feed):
"""
Initializing an atom feed `feedgen.feed.FeedGenerator` given a feed object
:param feed: a feed object
:return: an atom feed `feedgen.feed.FeedGenerator`
"""
atom_feed = FeedGenerator()
atom_feed.id(id=self.request.route_url(sel... | [
"def",
"init_atom_feed",
"(",
"self",
",",
"feed",
")",
":",
"atom_feed",
"=",
"FeedGenerator",
"(",
")",
"atom_feed",
".",
"id",
"(",
"id",
"=",
"self",
".",
"request",
".",
"route_url",
"(",
"self",
".",
"get_atom_feed_url",
",",
"id",
"=",
"feed",
"... | Initializing an atom feed `feedgen.feed.FeedGenerator` given a feed object
:param feed: a feed object
:return: an atom feed `feedgen.feed.FeedGenerator` | [
"Initializing",
"an",
"atom",
"feed",
"feedgen",
".",
"feed",
".",
"FeedGenerator",
"given",
"a",
"feed",
"object"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/views/atom.py#L132-L145 |
OnroerendErfgoed/oe_utils | oe_utils/views/atom.py | AtomFeedView._generate_atom_feed | def _generate_atom_feed(self, feed):
"""
A function returning a feed like `feedgen.feed.FeedGenerator`.
The function can be overwritten when used in other applications.
:param feed: a feed object
:return: an atom feed `feedgen.feed.FeedGenerator`
"""
atom_feed = ... | python | def _generate_atom_feed(self, feed):
"""
A function returning a feed like `feedgen.feed.FeedGenerator`.
The function can be overwritten when used in other applications.
:param feed: a feed object
:return: an atom feed `feedgen.feed.FeedGenerator`
"""
atom_feed = ... | [
"def",
"_generate_atom_feed",
"(",
"self",
",",
"feed",
")",
":",
"atom_feed",
"=",
"self",
".",
"init_atom_feed",
"(",
"feed",
")",
"atom_feed",
".",
"title",
"(",
"\"Feed\"",
")",
"return",
"atom_feed"
] | A function returning a feed like `feedgen.feed.FeedGenerator`.
The function can be overwritten when used in other applications.
:param feed: a feed object
:return: an atom feed `feedgen.feed.FeedGenerator` | [
"A",
"function",
"returning",
"a",
"feed",
"like",
"feedgen",
".",
"feed",
".",
"FeedGenerator",
".",
"The",
"function",
"can",
"be",
"overwritten",
"when",
"used",
"in",
"other",
"applications",
"."
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/views/atom.py#L147-L157 |
alphagov/gapy | gapy/client.py | from_private_key | def from_private_key(account_name, private_key=None, private_key_path=None,
storage=None, storage_path=None, api_version="v3",
readonly=False, http_client=None, ga_hook=None):
"""Create a client for a service account.
Create a client with an account name and a private ... | python | def from_private_key(account_name, private_key=None, private_key_path=None,
storage=None, storage_path=None, api_version="v3",
readonly=False, http_client=None, ga_hook=None):
"""Create a client for a service account.
Create a client with an account name and a private ... | [
"def",
"from_private_key",
"(",
"account_name",
",",
"private_key",
"=",
"None",
",",
"private_key_path",
"=",
"None",
",",
"storage",
"=",
"None",
",",
"storage_path",
"=",
"None",
",",
"api_version",
"=",
"\"v3\"",
",",
"readonly",
"=",
"False",
",",
"http... | Create a client for a service account.
Create a client with an account name and a private key.
Args:
account_name: str, the account identifier (probably the account email).
private_key: str, the private key as a string.
private_key_path: str, path to a file with the private key in.
st... | [
"Create",
"a",
"client",
"for",
"a",
"service",
"account",
"."
] | train | https://github.com/alphagov/gapy/blob/5e8cc058c54d6034fa0f5177d5a6d3d2e71fa5ea/gapy/client.py#L24-L59 |
alphagov/gapy | gapy/client.py | from_secrets_file | def from_secrets_file(client_secrets, storage=None, flags=None,
storage_path=None, api_version="v3", readonly=False,
http_client=None, ga_hook=None):
"""Create a client for a web or installed application.
Create a client with a client secrets file.
Args:
... | python | def from_secrets_file(client_secrets, storage=None, flags=None,
storage_path=None, api_version="v3", readonly=False,
http_client=None, ga_hook=None):
"""Create a client for a web or installed application.
Create a client with a client secrets file.
Args:
... | [
"def",
"from_secrets_file",
"(",
"client_secrets",
",",
"storage",
"=",
"None",
",",
"flags",
"=",
"None",
",",
"storage_path",
"=",
"None",
",",
"api_version",
"=",
"\"v3\"",
",",
"readonly",
"=",
"False",
",",
"http_client",
"=",
"None",
",",
"ga_hook",
... | Create a client for a web or installed application.
Create a client with a client secrets file.
Args:
client_secrets: str, path to the client secrets file (downloadable from
Google API Console)
storage: oauth2client.client.Storage, a Storage implementation to store
... | [
"Create",
"a",
"client",
"for",
"a",
"web",
"or",
"installed",
"application",
"."
] | train | https://github.com/alphagov/gapy/blob/5e8cc058c54d6034fa0f5177d5a6d3d2e71fa5ea/gapy/client.py#L62-L89 |
alphagov/gapy | gapy/client.py | from_credentials_db | def from_credentials_db(client_secrets, storage, api_version="v3",
readonly=False, http_client=None, ga_hook=None):
"""Create a client for a web or installed application.
Create a client with a credentials stored in stagecraft db.
Args:
client_secrets: dict, client secrets ... | python | def from_credentials_db(client_secrets, storage, api_version="v3",
readonly=False, http_client=None, ga_hook=None):
"""Create a client for a web or installed application.
Create a client with a credentials stored in stagecraft db.
Args:
client_secrets: dict, client secrets ... | [
"def",
"from_credentials_db",
"(",
"client_secrets",
",",
"storage",
",",
"api_version",
"=",
"\"v3\"",
",",
"readonly",
"=",
"False",
",",
"http_client",
"=",
"None",
",",
"ga_hook",
"=",
"None",
")",
":",
"credentials",
"=",
"storage",
".",
"get",
"(",
"... | Create a client for a web or installed application.
Create a client with a credentials stored in stagecraft db.
Args:
client_secrets: dict, client secrets (downloadable from
Google API Console)
storage: stagecraft.apps.collectors.libs.ga.CredentialStorage,
... | [
"Create",
"a",
"client",
"for",
"a",
"web",
"or",
"installed",
"application",
"."
] | train | https://github.com/alphagov/gapy/blob/5e8cc058c54d6034fa0f5177d5a6d3d2e71fa5ea/gapy/client.py#L92-L111 |
alphagov/gapy | gapy/client.py | _build | def _build(credentials, api_version, http_client=None):
"""Build the client object."""
if not http_client:
http_client = httplib2.Http()
authorised_client = credentials.authorize(http_client)
return build("analytics", api_version, http=authorised_client) | python | def _build(credentials, api_version, http_client=None):
"""Build the client object."""
if not http_client:
http_client = httplib2.Http()
authorised_client = credentials.authorize(http_client)
return build("analytics", api_version, http=authorised_client) | [
"def",
"_build",
"(",
"credentials",
",",
"api_version",
",",
"http_client",
"=",
"None",
")",
":",
"if",
"not",
"http_client",
":",
"http_client",
"=",
"httplib2",
".",
"Http",
"(",
")",
"authorised_client",
"=",
"credentials",
".",
"authorize",
"(",
"http_... | Build the client object. | [
"Build",
"the",
"client",
"object",
"."
] | train | https://github.com/alphagov/gapy/blob/5e8cc058c54d6034fa0f5177d5a6d3d2e71fa5ea/gapy/client.py#L114-L121 |
alphagov/gapy | gapy/client.py | _prefix_ga | def _prefix_ga(value):
"""Prefix a string with 'ga:' if it is not already
Sort values may be prefixed with '-' to indicate negative sort.
>>> _prefix_ga('foo')
'ga:foo'
>>> _prefix_ga('ga:foo')
'ga:foo'
>>> _prefix_ga('-foo')
'-ga:foo'
>>> _prefix_ga('-ga:foo')
'-ga:foo'
""... | python | def _prefix_ga(value):
"""Prefix a string with 'ga:' if it is not already
Sort values may be prefixed with '-' to indicate negative sort.
>>> _prefix_ga('foo')
'ga:foo'
>>> _prefix_ga('ga:foo')
'ga:foo'
>>> _prefix_ga('-foo')
'-ga:foo'
>>> _prefix_ga('-ga:foo')
'-ga:foo'
""... | [
"def",
"_prefix_ga",
"(",
"value",
")",
":",
"prefix",
"=",
"''",
"if",
"value",
"[",
"0",
"]",
"==",
"'-'",
":",
"value",
"=",
"value",
"[",
"1",
":",
"]",
"prefix",
"=",
"'-'",
"if",
"not",
"value",
".",
"startswith",
"(",
"'ga:'",
")",
":",
... | Prefix a string with 'ga:' if it is not already
Sort values may be prefixed with '-' to indicate negative sort.
>>> _prefix_ga('foo')
'ga:foo'
>>> _prefix_ga('ga:foo')
'ga:foo'
>>> _prefix_ga('-foo')
'-ga:foo'
>>> _prefix_ga('-ga:foo')
'-ga:foo' | [
"Prefix",
"a",
"string",
"with",
"ga",
":",
"if",
"it",
"is",
"not",
"already"
] | train | https://github.com/alphagov/gapy/blob/5e8cc058c54d6034fa0f5177d5a6d3d2e71fa5ea/gapy/client.py#L246-L266 |
wrwrwr/scikit-gof | skgof/addist.py | ad_unif_inf | def ad_unif_inf(statistic):
"""
Approximates the limiting distribution to about 5 decimal digits.
"""
z = statistic
if z < 2:
return (exp(-1.2337141 / z) / sqrt(z) *
(2.00012 + (.247105 - (.0649821 - (.0347962 -
(.011672 - .0016... | python | def ad_unif_inf(statistic):
"""
Approximates the limiting distribution to about 5 decimal digits.
"""
z = statistic
if z < 2:
return (exp(-1.2337141 / z) / sqrt(z) *
(2.00012 + (.247105 - (.0649821 - (.0347962 -
(.011672 - .0016... | [
"def",
"ad_unif_inf",
"(",
"statistic",
")",
":",
"z",
"=",
"statistic",
"if",
"z",
"<",
"2",
":",
"return",
"(",
"exp",
"(",
"-",
"1.2337141",
"/",
"z",
")",
"/",
"sqrt",
"(",
"z",
")",
"*",
"(",
"2.00012",
"+",
"(",
".247105",
"-",
"(",
".064... | Approximates the limiting distribution to about 5 decimal digits. | [
"Approximates",
"the",
"limiting",
"distribution",
"to",
"about",
"5",
"decimal",
"digits",
"."
] | train | https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/addist.py#L38-L49 |
wrwrwr/scikit-gof | skgof/addist.py | ad_unif_fix | def ad_unif_fix(samples, pinf):
"""
Corrects the limiting distribution for a finite sample size.
"""
n = samples
c = .01265 + .1757 / n
if pinf < c:
return (((.0037 / n + .00078) / n + .00006) / n) * g1(pinf / c)
elif pinf < .8:
return ((.01365 / n + .04213) / n) * g2((pinf -... | python | def ad_unif_fix(samples, pinf):
"""
Corrects the limiting distribution for a finite sample size.
"""
n = samples
c = .01265 + .1757 / n
if pinf < c:
return (((.0037 / n + .00078) / n + .00006) / n) * g1(pinf / c)
elif pinf < .8:
return ((.01365 / n + .04213) / n) * g2((pinf -... | [
"def",
"ad_unif_fix",
"(",
"samples",
",",
"pinf",
")",
":",
"n",
"=",
"samples",
"c",
"=",
".01265",
"+",
".1757",
"/",
"n",
"if",
"pinf",
"<",
"c",
":",
"return",
"(",
"(",
"(",
".0037",
"/",
"n",
"+",
".00078",
")",
"/",
"n",
"+",
".00006",
... | Corrects the limiting distribution for a finite sample size. | [
"Corrects",
"the",
"limiting",
"distribution",
"for",
"a",
"finite",
"sample",
"size",
"."
] | train | https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/addist.py#L59-L70 |
jambonrose/markdown_superscript_extension | setup.py | CustomCheckCommand.check_metadata | def check_metadata(self):
"""Ensure all required meta-data are supplied.
Specifically: name, version, URL, author or maintainer
Warns if any are missing.
If enforce-email option is true, author and/or maintainer must
specify an email.
"""
metadata = self.distri... | python | def check_metadata(self):
"""Ensure all required meta-data are supplied.
Specifically: name, version, URL, author or maintainer
Warns if any are missing.
If enforce-email option is true, author and/or maintainer must
specify an email.
"""
metadata = self.distri... | [
"def",
"check_metadata",
"(",
"self",
")",
":",
"metadata",
"=",
"self",
".",
"distribution",
".",
"metadata",
"missing",
"=",
"[",
"]",
"for",
"attr",
"in",
"(",
"\"name\"",
",",
"\"version\"",
",",
"\"url\"",
")",
":",
"if",
"not",
"(",
"hasattr",
"(... | Ensure all required meta-data are supplied.
Specifically: name, version, URL, author or maintainer
Warns if any are missing.
If enforce-email option is true, author and/or maintainer must
specify an email. | [
"Ensure",
"all",
"required",
"meta",
"-",
"data",
"are",
"supplied",
"."
] | train | https://github.com/jambonrose/markdown_superscript_extension/blob/82e500182036fd754cd12cb1a3a7f71e2eeb05b1/setup.py#L61-L122 |
quantopian/serializable-traitlets | straitlets/builtin_models.py | PostgresConfig.from_url | def from_url(cls, url):
"""
Construct a PostgresConfig from a URL.
"""
parsed = urlparse(url)
return cls(
username=parsed.username,
password=parsed.password,
hostname=parsed.hostname,
port=parsed.port,
database=parsed.pa... | python | def from_url(cls, url):
"""
Construct a PostgresConfig from a URL.
"""
parsed = urlparse(url)
return cls(
username=parsed.username,
password=parsed.password,
hostname=parsed.hostname,
port=parsed.port,
database=parsed.pa... | [
"def",
"from_url",
"(",
"cls",
",",
"url",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"return",
"cls",
"(",
"username",
"=",
"parsed",
".",
"username",
",",
"password",
"=",
"parsed",
".",
"password",
",",
"hostname",
"=",
"parsed",
".",
"... | Construct a PostgresConfig from a URL. | [
"Construct",
"a",
"PostgresConfig",
"from",
"a",
"URL",
"."
] | train | https://github.com/quantopian/serializable-traitlets/blob/dd334366d1130825aea55d3dfecd6756973594e0/straitlets/builtin_models.py#L78-L93 |
wrwrwr/scikit-gof | skgof/vect.py | vectorize | def vectorize(*args, **kwargs):
"""
Allows using `@vectorize` as well as `@vectorize()`.
"""
if args and callable(args[0]):
# Guessing the argument is the method.
return _vectorize(args[0])
else:
# Wait for the second call.
return lambda m: _vectorize(m, *args, **kwar... | python | def vectorize(*args, **kwargs):
"""
Allows using `@vectorize` as well as `@vectorize()`.
"""
if args and callable(args[0]):
# Guessing the argument is the method.
return _vectorize(args[0])
else:
# Wait for the second call.
return lambda m: _vectorize(m, *args, **kwar... | [
"def",
"vectorize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
"and",
"callable",
"(",
"args",
"[",
"0",
"]",
")",
":",
"# Guessing the argument is the method.",
"return",
"_vectorize",
"(",
"args",
"[",
"0",
"]",
")",
"else",
"... | Allows using `@vectorize` as well as `@vectorize()`. | [
"Allows",
"using"
] | train | https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/vect.py#L32-L41 |
wrwrwr/scikit-gof | skgof/vect.py | varange | def varange(starts, count):
"""
Vectorized `arange()` taking a sequence of starts and a count of elements.
For example::
>>> varange(1, 5)
array([1, 2, 3, 4, 5])
>>> varange((1, 3), 5)
array([[1, 2, 3, 4, 5],
[3, 4, 5, 6, 7]])
"""
try:
return... | python | def varange(starts, count):
"""
Vectorized `arange()` taking a sequence of starts and a count of elements.
For example::
>>> varange(1, 5)
array([1, 2, 3, 4, 5])
>>> varange((1, 3), 5)
array([[1, 2, 3, 4, 5],
[3, 4, 5, 6, 7]])
"""
try:
return... | [
"def",
"varange",
"(",
"starts",
",",
"count",
")",
":",
"try",
":",
"return",
"stack",
"(",
"arange",
"(",
"s",
",",
"s",
"+",
"count",
")",
"for",
"s",
"in",
"starts",
")",
"except",
"TypeError",
":",
"return",
"arange",
"(",
"starts",
",",
"star... | Vectorized `arange()` taking a sequence of starts and a count of elements.
For example::
>>> varange(1, 5)
array([1, 2, 3, 4, 5])
>>> varange((1, 3), 5)
array([[1, 2, 3, 4, 5],
[3, 4, 5, 6, 7]]) | [
"Vectorized",
"arange",
"()",
"taking",
"a",
"sequence",
"of",
"starts",
"and",
"a",
"count",
"of",
"elements",
"."
] | train | https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/vect.py#L44-L60 |
OnroerendErfgoed/oe_utils | oe_utils/__init__.py | conditional_http_tween_factory | def conditional_http_tween_factory(handler, registry):
"""
Tween that adds ETag headers and tells Pyramid to enable
conditional responses where appropriate.
"""
settings = registry.settings if hasattr(registry, 'settings') else {}
not_cacheble_list = []
if 'not.cachable.list' in settings:
... | python | def conditional_http_tween_factory(handler, registry):
"""
Tween that adds ETag headers and tells Pyramid to enable
conditional responses where appropriate.
"""
settings = registry.settings if hasattr(registry, 'settings') else {}
not_cacheble_list = []
if 'not.cachable.list' in settings:
... | [
"def",
"conditional_http_tween_factory",
"(",
"handler",
",",
"registry",
")",
":",
"settings",
"=",
"registry",
".",
"settings",
"if",
"hasattr",
"(",
"registry",
",",
"'settings'",
")",
"else",
"{",
"}",
"not_cacheble_list",
"=",
"[",
"]",
"if",
"'not.cachab... | Tween that adds ETag headers and tells Pyramid to enable
conditional responses where appropriate. | [
"Tween",
"that",
"adds",
"ETag",
"headers",
"and",
"tells",
"Pyramid",
"to",
"enable",
"conditional",
"responses",
"where",
"appropriate",
"."
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/__init__.py#L5-L37 |
OnroerendErfgoed/oe_utils | oe_utils/utils/file_utils.py | get_last_modified_date | def get_last_modified_date(filename):
"""
Get the last modified date of a given file
:param filename: string: pathname of a file
:return: Date
"""
if os.path.isfile(filename):
t = os.path.getmtime(filename)
return datetime.date.fromtimestamp(t).strftime('%d/%m/%Y')
return No... | python | def get_last_modified_date(filename):
"""
Get the last modified date of a given file
:param filename: string: pathname of a file
:return: Date
"""
if os.path.isfile(filename):
t = os.path.getmtime(filename)
return datetime.date.fromtimestamp(t).strftime('%d/%m/%Y')
return No... | [
"def",
"get_last_modified_date",
"(",
"filename",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"t",
"=",
"os",
".",
"path",
".",
"getmtime",
"(",
"filename",
")",
"return",
"datetime",
".",
"date",
".",
"fromtimestamp",
... | Get the last modified date of a given file
:param filename: string: pathname of a file
:return: Date | [
"Get",
"the",
"last",
"modified",
"date",
"of",
"a",
"given",
"file"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/utils/file_utils.py#L7-L17 |
OnroerendErfgoed/oe_utils | oe_utils/utils/file_utils.py | get_file_size | def get_file_size(filename):
"""
Get the file size of a given file
:param filename: string: pathname of a file
:return: human readable filesize
"""
if os.path.isfile(filename):
return convert_size(os.path.getsize(filename))
return None | python | def get_file_size(filename):
"""
Get the file size of a given file
:param filename: string: pathname of a file
:return: human readable filesize
"""
if os.path.isfile(filename):
return convert_size(os.path.getsize(filename))
return None | [
"def",
"get_file_size",
"(",
"filename",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"return",
"convert_size",
"(",
"os",
".",
"path",
".",
"getsize",
"(",
"filename",
")",
")",
"return",
"None"
] | Get the file size of a given file
:param filename: string: pathname of a file
:return: human readable filesize | [
"Get",
"the",
"file",
"size",
"of",
"a",
"given",
"file"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/utils/file_utils.py#L20-L29 |
OnroerendErfgoed/oe_utils | oe_utils/utils/file_utils.py | convert_size | def convert_size(size_bytes):
"""
Transform bytesize to a human readable filesize
:param size_bytes: bytesize
:return: human readable filesize
"""
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_b... | python | def convert_size(size_bytes):
"""
Transform bytesize to a human readable filesize
:param size_bytes: bytesize
:return: human readable filesize
"""
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_b... | [
"def",
"convert_size",
"(",
"size_bytes",
")",
":",
"if",
"size_bytes",
"==",
"0",
":",
"return",
"\"0B\"",
"size_name",
"=",
"(",
"\"B\"",
",",
"\"KB\"",
",",
"\"MB\"",
",",
"\"GB\"",
",",
"\"TB\"",
",",
"\"PB\"",
",",
"\"EB\"",
",",
"\"ZB\"",
",",
"\... | Transform bytesize to a human readable filesize
:param size_bytes: bytesize
:return: human readable filesize | [
"Transform",
"bytesize",
"to",
"a",
"human",
"readable",
"filesize"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/utils/file_utils.py#L32-L45 |
quantopian/serializable-traitlets | straitlets/serializable.py | Serializable.validate_all_attributes | def validate_all_attributes(self):
"""
Force validation of all traits.
Useful for circumstances where an attribute won't be accessed until
well after construction, but we want to fail eagerly if that attribute
is passed incorrectly.
Consider using ``StrictSerializable``... | python | def validate_all_attributes(self):
"""
Force validation of all traits.
Useful for circumstances where an attribute won't be accessed until
well after construction, but we want to fail eagerly if that attribute
is passed incorrectly.
Consider using ``StrictSerializable``... | [
"def",
"validate_all_attributes",
"(",
"self",
")",
":",
"errors",
"=",
"{",
"}",
"for",
"name",
"in",
"self",
".",
"trait_names",
"(",
")",
":",
"try",
":",
"getattr",
"(",
"self",
",",
"name",
")",
"except",
"TraitError",
"as",
"e",
":",
"errors",
... | Force validation of all traits.
Useful for circumstances where an attribute won't be accessed until
well after construction, but we want to fail eagerly if that attribute
is passed incorrectly.
Consider using ``StrictSerializable`` for classes where you always want
this called ... | [
"Force",
"validation",
"of",
"all",
"traits",
"."
] | train | https://github.com/quantopian/serializable-traitlets/blob/dd334366d1130825aea55d3dfecd6756973594e0/straitlets/serializable.py#L84-L106 |
quantopian/serializable-traitlets | straitlets/serializable.py | Serializable.example_instance | def example_instance(cls, skip=()):
"""
Generate an example instance of a Serializable subclass.
If traits have been tagged with an `example` value, then we use that
value. Otherwise we fall back the default_value for the instance.
Traits with names in ``skip`` will not have e... | python | def example_instance(cls, skip=()):
"""
Generate an example instance of a Serializable subclass.
If traits have been tagged with an `example` value, then we use that
value. Otherwise we fall back the default_value for the instance.
Traits with names in ``skip`` will not have e... | [
"def",
"example_instance",
"(",
"cls",
",",
"skip",
"=",
"(",
")",
")",
":",
"kwargs",
"=",
"{",
"}",
"for",
"name",
",",
"trait",
"in",
"iteritems",
"(",
"cls",
".",
"class_traits",
"(",
")",
")",
":",
"if",
"name",
"in",
"skip",
":",
"continue",
... | Generate an example instance of a Serializable subclass.
If traits have been tagged with an `example` value, then we use that
value. Otherwise we fall back the default_value for the instance.
Traits with names in ``skip`` will not have example values set. | [
"Generate",
"an",
"example",
"instance",
"of",
"a",
"Serializable",
"subclass",
"."
] | train | https://github.com/quantopian/serializable-traitlets/blob/dd334366d1130825aea55d3dfecd6756973594e0/straitlets/serializable.py#L136-L154 |
quantopian/serializable-traitlets | straitlets/serializable.py | Serializable.example_yaml | def example_yaml(cls, skip=()):
"""
Generate an example yaml string for a Serializable subclass.
If traits have been tagged with an `example` value, then we use that
value. Otherwise we fall back the default_value for the instance.
"""
return cls.example_instance(skip=s... | python | def example_yaml(cls, skip=()):
"""
Generate an example yaml string for a Serializable subclass.
If traits have been tagged with an `example` value, then we use that
value. Otherwise we fall back the default_value for the instance.
"""
return cls.example_instance(skip=s... | [
"def",
"example_yaml",
"(",
"cls",
",",
"skip",
"=",
"(",
")",
")",
":",
"return",
"cls",
".",
"example_instance",
"(",
"skip",
"=",
"skip",
")",
".",
"to_yaml",
"(",
"skip",
"=",
"skip",
")"
] | Generate an example yaml string for a Serializable subclass.
If traits have been tagged with an `example` value, then we use that
value. Otherwise we fall back the default_value for the instance. | [
"Generate",
"an",
"example",
"yaml",
"string",
"for",
"a",
"Serializable",
"subclass",
"."
] | train | https://github.com/quantopian/serializable-traitlets/blob/dd334366d1130825aea55d3dfecd6756973594e0/straitlets/serializable.py#L157-L164 |
quantopian/serializable-traitlets | straitlets/serializable.py | Serializable.write_example_yaml | def write_example_yaml(cls, dest, skip=()):
"""
Write a file containing an example yaml string for a Serializable
subclass.
"""
# Make sure we can make an instance before we open a file.
inst = cls.example_instance(skip=skip)
with open(dest, 'w') as f:
... | python | def write_example_yaml(cls, dest, skip=()):
"""
Write a file containing an example yaml string for a Serializable
subclass.
"""
# Make sure we can make an instance before we open a file.
inst = cls.example_instance(skip=skip)
with open(dest, 'w') as f:
... | [
"def",
"write_example_yaml",
"(",
"cls",
",",
"dest",
",",
"skip",
"=",
"(",
")",
")",
":",
"# Make sure we can make an instance before we open a file.",
"inst",
"=",
"cls",
".",
"example_instance",
"(",
"skip",
"=",
"skip",
")",
"with",
"open",
"(",
"dest",
"... | Write a file containing an example yaml string for a Serializable
subclass. | [
"Write",
"a",
"file",
"containing",
"an",
"example",
"yaml",
"string",
"for",
"a",
"Serializable",
"subclass",
"."
] | train | https://github.com/quantopian/serializable-traitlets/blob/dd334366d1130825aea55d3dfecd6756973594e0/straitlets/serializable.py#L167-L175 |
quantopian/serializable-traitlets | straitlets/serializable.py | Serializable.to_base64 | def to_base64(self, skip=()):
"""
Construct from base64-encoded JSON.
"""
return base64.b64encode(
ensure_bytes(
self.to_json(skip=skip),
encoding='utf-8',
)
) | python | def to_base64(self, skip=()):
"""
Construct from base64-encoded JSON.
"""
return base64.b64encode(
ensure_bytes(
self.to_json(skip=skip),
encoding='utf-8',
)
) | [
"def",
"to_base64",
"(",
"self",
",",
"skip",
"=",
"(",
")",
")",
":",
"return",
"base64",
".",
"b64encode",
"(",
"ensure_bytes",
"(",
"self",
".",
"to_json",
"(",
"skip",
"=",
"skip",
")",
",",
"encoding",
"=",
"'utf-8'",
",",
")",
")"
] | Construct from base64-encoded JSON. | [
"Construct",
"from",
"base64",
"-",
"encoded",
"JSON",
"."
] | train | https://github.com/quantopian/serializable-traitlets/blob/dd334366d1130825aea55d3dfecd6756973594e0/straitlets/serializable.py#L219-L228 |
quantopian/serializable-traitlets | straitlets/serializable.py | Serializable.to_environ | def to_environ(self, environ, skip=()):
"""
Serialize and write self to environ[self._envvar].
Parameters
----------
environ : dict-like
Dict-like object (e.g. os.environ) into which to write ``self``.
"""
environ[ensure_unicode(type(self).__name__)] ... | python | def to_environ(self, environ, skip=()):
"""
Serialize and write self to environ[self._envvar].
Parameters
----------
environ : dict-like
Dict-like object (e.g. os.environ) into which to write ``self``.
"""
environ[ensure_unicode(type(self).__name__)] ... | [
"def",
"to_environ",
"(",
"self",
",",
"environ",
",",
"skip",
"=",
"(",
")",
")",
":",
"environ",
"[",
"ensure_unicode",
"(",
"type",
"(",
"self",
")",
".",
"__name__",
")",
"]",
"=",
"(",
"ensure_unicode",
"(",
"self",
".",
"to_base64",
"(",
"skip"... | Serialize and write self to environ[self._envvar].
Parameters
----------
environ : dict-like
Dict-like object (e.g. os.environ) into which to write ``self``. | [
"Serialize",
"and",
"write",
"self",
"to",
"environ",
"[",
"self",
".",
"_envvar",
"]",
"."
] | train | https://github.com/quantopian/serializable-traitlets/blob/dd334366d1130825aea55d3dfecd6756973594e0/straitlets/serializable.py#L243-L254 |
OnroerendErfgoed/oe_utils | oe_utils/data/data_managers.py | DataManager.get_one | def get_one(self, object_id):
"""
Retrieve an object by its object_id
:param object_id: the objects id.
:return: the requested object
:raises: :class: NoResultFound when the object could not be found
"""
return self.session.query(self.cls).filter_by(id=object_id)... | python | def get_one(self, object_id):
"""
Retrieve an object by its object_id
:param object_id: the objects id.
:return: the requested object
:raises: :class: NoResultFound when the object could not be found
"""
return self.session.query(self.cls).filter_by(id=object_id)... | [
"def",
"get_one",
"(",
"self",
",",
"object_id",
")",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"self",
".",
"cls",
")",
".",
"filter_by",
"(",
"id",
"=",
"object_id",
")",
".",
"one",
"(",
")"
] | Retrieve an object by its object_id
:param object_id: the objects id.
:return: the requested object
:raises: :class: NoResultFound when the object could not be found | [
"Retrieve",
"an",
"object",
"by",
"its",
"object_id"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/data/data_managers.py#L51-L59 |
OnroerendErfgoed/oe_utils | oe_utils/data/data_managers.py | DataManager.get_one_for_update | def get_one_for_update(self, object_id):
"""
Retrieve an object by its object_id
Does a select for update on the row, results in row level lock for the duration of the transaction
:param object_id: the objects id.
:return: the requested object
:raises: :class: NoResultFo... | python | def get_one_for_update(self, object_id):
"""
Retrieve an object by its object_id
Does a select for update on the row, results in row level lock for the duration of the transaction
:param object_id: the objects id.
:return: the requested object
:raises: :class: NoResultFo... | [
"def",
"get_one_for_update",
"(",
"self",
",",
"object_id",
")",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"self",
".",
"cls",
")",
".",
"with_for_update",
"(",
")",
".",
"filter_by",
"(",
"id",
"=",
"object_id",
")",
".",
"one",
"(",
... | Retrieve an object by its object_id
Does a select for update on the row, results in row level lock for the duration of the transaction
:param object_id: the objects id.
:return: the requested object
:raises: :class: NoResultFound when the object could not be found | [
"Retrieve",
"an",
"object",
"by",
"its",
"object_id",
"Does",
"a",
"select",
"for",
"update",
"on",
"the",
"row",
"results",
"in",
"row",
"level",
"lock",
"for",
"the",
"duration",
"of",
"the",
"transaction"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/data/data_managers.py#L61-L70 |
OnroerendErfgoed/oe_utils | oe_utils/data/data_managers.py | DataManager.get | def get(self, object_id, cls=None):
"""
Retrieve an object by its object_id
:param: object_id: the objects id.
:param: cls: the objects class, if None use the default class from the datamanager
:return: the requested object or None if not found
"""
cls = self.cls... | python | def get(self, object_id, cls=None):
"""
Retrieve an object by its object_id
:param: object_id: the objects id.
:param: cls: the objects class, if None use the default class from the datamanager
:return: the requested object or None if not found
"""
cls = self.cls... | [
"def",
"get",
"(",
"self",
",",
"object_id",
",",
"cls",
"=",
"None",
")",
":",
"cls",
"=",
"self",
".",
"cls",
"if",
"cls",
"is",
"None",
"else",
"cls",
"return",
"self",
".",
"session",
".",
"query",
"(",
"cls",
")",
".",
"get",
"(",
"object_id... | Retrieve an object by its object_id
:param: object_id: the objects id.
:param: cls: the objects class, if None use the default class from the datamanager
:return: the requested object or None if not found | [
"Retrieve",
"an",
"object",
"by",
"its",
"object_id"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/data/data_managers.py#L72-L81 |
OnroerendErfgoed/oe_utils | oe_utils/data/data_managers.py | DataManager.get_for_update | def get_for_update(self, object_id, cls=None):
"""
Retrieve an object by its object_id
Does a select for update on the row, results in row level lock for the duration of the transaction
:param: object_id: the objects id.
:param: cls: the objects class, if None use the default cl... | python | def get_for_update(self, object_id, cls=None):
"""
Retrieve an object by its object_id
Does a select for update on the row, results in row level lock for the duration of the transaction
:param: object_id: the objects id.
:param: cls: the objects class, if None use the default cl... | [
"def",
"get_for_update",
"(",
"self",
",",
"object_id",
",",
"cls",
"=",
"None",
")",
":",
"cls",
"=",
"self",
".",
"cls",
"if",
"cls",
"is",
"None",
"else",
"cls",
"return",
"self",
".",
"session",
".",
"query",
"(",
"cls",
")",
".",
"with_for_updat... | Retrieve an object by its object_id
Does a select for update on the row, results in row level lock for the duration of the transaction
:param: object_id: the objects id.
:param: cls: the objects class, if None use the default class from the datamanager
:return: the requested object or N... | [
"Retrieve",
"an",
"object",
"by",
"its",
"object_id",
"Does",
"a",
"select",
"for",
"update",
"on",
"the",
"row",
"results",
"in",
"row",
"level",
"lock",
"for",
"the",
"duration",
"of",
"the",
"transaction"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/data/data_managers.py#L83-L93 |
OnroerendErfgoed/oe_utils | oe_utils/data/data_managers.py | DataManager.delete | def delete(self, object_id):
"""
Delete an object by its id
:param object_id: the objects id.
:return: the deleted object
:raises: :class: NoResultFound when the object could not be found
"""
obj = self.session.query(self.cls).filter_by(id=object_id).one()
... | python | def delete(self, object_id):
"""
Delete an object by its id
:param object_id: the objects id.
:return: the deleted object
:raises: :class: NoResultFound when the object could not be found
"""
obj = self.session.query(self.cls).filter_by(id=object_id).one()
... | [
"def",
"delete",
"(",
"self",
",",
"object_id",
")",
":",
"obj",
"=",
"self",
".",
"session",
".",
"query",
"(",
"self",
".",
"cls",
")",
".",
"filter_by",
"(",
"id",
"=",
"object_id",
")",
".",
"one",
"(",
")",
"self",
".",
"session",
".",
"dele... | Delete an object by its id
:param object_id: the objects id.
:return: the deleted object
:raises: :class: NoResultFound when the object could not be found | [
"Delete",
"an",
"object",
"by",
"its",
"id"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/data/data_managers.py#L95-L105 |
OnroerendErfgoed/oe_utils | oe_utils/data/data_managers.py | DataManager.save | def save(self, obj):
"""
save an object
:param obj: the object
:return: the saved object
"""
if obj not in self.session:
self.session.add(obj)
else:
obj = self.session.merge(obj)
self.session.flush()
self.session.refresh(ob... | python | def save(self, obj):
"""
save an object
:param obj: the object
:return: the saved object
"""
if obj not in self.session:
self.session.add(obj)
else:
obj = self.session.merge(obj)
self.session.flush()
self.session.refresh(ob... | [
"def",
"save",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
"not",
"in",
"self",
".",
"session",
":",
"self",
".",
"session",
".",
"add",
"(",
"obj",
")",
"else",
":",
"obj",
"=",
"self",
".",
"session",
".",
"merge",
"(",
"obj",
")",
"self"... | save an object
:param obj: the object
:return: the saved object | [
"save",
"an",
"object"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/data/data_managers.py#L107-L120 |
OnroerendErfgoed/oe_utils | oe_utils/data/data_managers.py | AtomFeedManager.get_sibling | def get_sibling(self, feed_id, sibling_type):
"""
get a previous/next sibling from a feed
:param feed_id: id of the feed
:param sibling_type: sibling type ('previous', 'next')
:return: the sibling
"""
if sibling_type == 'previous':
query = self.session... | python | def get_sibling(self, feed_id, sibling_type):
"""
get a previous/next sibling from a feed
:param feed_id: id of the feed
:param sibling_type: sibling type ('previous', 'next')
:return: the sibling
"""
if sibling_type == 'previous':
query = self.session... | [
"def",
"get_sibling",
"(",
"self",
",",
"feed_id",
",",
"sibling_type",
")",
":",
"if",
"sibling_type",
"==",
"'previous'",
":",
"query",
"=",
"self",
".",
"session",
".",
"query",
"(",
"self",
".",
"feed_model",
")",
".",
"filter",
"(",
"self",
".",
"... | get a previous/next sibling from a feed
:param feed_id: id of the feed
:param sibling_type: sibling type ('previous', 'next')
:return: the sibling | [
"get",
"a",
"previous",
"/",
"next",
"sibling",
"from",
"a",
"feed",
":",
"param",
"feed_id",
":",
"id",
"of",
"the",
"feed",
":",
"param",
"sibling_type",
":",
"sibling",
"type",
"(",
"previous",
"next",
")",
":",
"return",
":",
"the",
"sibling"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/data/data_managers.py#L148-L166 |
OnroerendErfgoed/oe_utils | oe_utils/data/data_managers.py | AtomFeedManager.save_object | def save_object(self, obj):
"""
Save an object to the db
:param obj: the object to save
:return: the saved object
"""
self.session.add(obj)
self.session.flush()
return obj | python | def save_object(self, obj):
"""
Save an object to the db
:param obj: the object to save
:return: the saved object
"""
self.session.add(obj)
self.session.flush()
return obj | [
"def",
"save_object",
"(",
"self",
",",
"obj",
")",
":",
"self",
".",
"session",
".",
"add",
"(",
"obj",
")",
"self",
".",
"session",
".",
"flush",
"(",
")",
"return",
"obj"
] | Save an object to the db
:param obj: the object to save
:return: the saved object | [
"Save",
"an",
"object",
"to",
"the",
"db",
":",
"param",
"obj",
":",
"the",
"object",
"to",
"save",
":",
"return",
":",
"the",
"saved",
"object"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/data/data_managers.py#L176-L184 |
OnroerendErfgoed/oe_utils | oe_utils/data/data_managers.py | AtomFeedManager.get_from_archive | def get_from_archive(self, feed_id):
"""
Retrieves feed that was persisted as .xml file by its id (= filename)
Note: No check on feed validity. file content is assumed correct
:param feed_id:
:return: the atom feed as string
"""
file_path = self.feed_repository + ... | python | def get_from_archive(self, feed_id):
"""
Retrieves feed that was persisted as .xml file by its id (= filename)
Note: No check on feed validity. file content is assumed correct
:param feed_id:
:return: the atom feed as string
"""
file_path = self.feed_repository + ... | [
"def",
"get_from_archive",
"(",
"self",
",",
"feed_id",
")",
":",
"file_path",
"=",
"self",
".",
"feed_repository",
"+",
"'/'",
"+",
"str",
"(",
"feed_id",
")",
"+",
"'.xml'",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
":",
... | Retrieves feed that was persisted as .xml file by its id (= filename)
Note: No check on feed validity. file content is assumed correct
:param feed_id:
:return: the atom feed as string | [
"Retrieves",
"feed",
"that",
"was",
"persisted",
"as",
".",
"xml",
"file",
"by",
"its",
"id",
"(",
"=",
"filename",
")",
"Note",
":",
"No",
"check",
"on",
"feed",
"validity",
".",
"file",
"content",
"is",
"assumed",
"correct",
":",
"param",
"feed_id",
... | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/data/data_managers.py#L186-L197 |
OnroerendErfgoed/oe_utils | oe_utils/data/data_managers.py | AtomFeedManager.get_atom_feed_entry | def get_atom_feed_entry(self, feedentry_id):
"""
Get a specific feed entry
:param id: id of the feed entry to retrieve
:return: the feed entry
"""
return self.session.query(self.feedentry_model).filter(
self.feedentry_model.id == feedentry_id
).one() | python | def get_atom_feed_entry(self, feedentry_id):
"""
Get a specific feed entry
:param id: id of the feed entry to retrieve
:return: the feed entry
"""
return self.session.query(self.feedentry_model).filter(
self.feedentry_model.id == feedentry_id
).one() | [
"def",
"get_atom_feed_entry",
"(",
"self",
",",
"feedentry_id",
")",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"self",
".",
"feedentry_model",
")",
".",
"filter",
"(",
"self",
".",
"feedentry_model",
".",
"id",
"==",
"feedentry_id",
")",
".... | Get a specific feed entry
:param id: id of the feed entry to retrieve
:return: the feed entry | [
"Get",
"a",
"specific",
"feed",
"entry",
":",
"param",
"id",
":",
"id",
"of",
"the",
"feed",
"entry",
"to",
"retrieve",
":",
"return",
":",
"the",
"feed",
"entry"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/data/data_managers.py#L199-L207 |
OnroerendErfgoed/oe_utils | oe_utils/data/data_managers.py | AtomFeedManager.archive_feed | def archive_feed(self, feed_id, feed):
"""
Archive a feed
:param feed_id: the feed id of the feed to archive
:param feed: the feed to archive
"""
with open(self.feed_repository + '/' + str(feed_id) + '.xml', 'w') as rec_file:
rec_file.write(feed.atom_str(prett... | python | def archive_feed(self, feed_id, feed):
"""
Archive a feed
:param feed_id: the feed id of the feed to archive
:param feed: the feed to archive
"""
with open(self.feed_repository + '/' + str(feed_id) + '.xml', 'w') as rec_file:
rec_file.write(feed.atom_str(prett... | [
"def",
"archive_feed",
"(",
"self",
",",
"feed_id",
",",
"feed",
")",
":",
"with",
"open",
"(",
"self",
".",
"feed_repository",
"+",
"'/'",
"+",
"str",
"(",
"feed_id",
")",
"+",
"'.xml'",
",",
"'w'",
")",
"as",
"rec_file",
":",
"rec_file",
".",
"writ... | Archive a feed
:param feed_id: the feed id of the feed to archive
:param feed: the feed to archive | [
"Archive",
"a",
"feed",
":",
"param",
"feed_id",
":",
"the",
"feed",
"id",
"of",
"the",
"feed",
"to",
"archive",
":",
"param",
"feed",
":",
"the",
"feed",
"to",
"archive"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/data/data_managers.py#L209-L218 |
OnroerendErfgoed/oe_utils | oe_utils/search/query_builder.py | QueryBuilder.add_named_concept_filters | def add_named_concept_filters(self, named_filter_concepts):
"""
Adds named concept filters
:param named_filter_concepts: dict with named filter concepts which will be mapped as the key as query param and the value as search string
"""
for concept_key, concept_name in named_filte... | python | def add_named_concept_filters(self, named_filter_concepts):
"""
Adds named concept filters
:param named_filter_concepts: dict with named filter concepts which will be mapped as the key as query param and the value as search string
"""
for concept_key, concept_name in named_filte... | [
"def",
"add_named_concept_filters",
"(",
"self",
",",
"named_filter_concepts",
")",
":",
"for",
"concept_key",
",",
"concept_name",
"in",
"named_filter_concepts",
".",
"items",
"(",
")",
":",
"self",
".",
"add_concept_filter",
"(",
"concept_key",
",",
"concept_name"... | Adds named concept filters
:param named_filter_concepts: dict with named filter concepts which will be mapped as the key as query param and the value as search string | [
"Adds",
"named",
"concept",
"filters"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/search/query_builder.py#L27-L34 |
OnroerendErfgoed/oe_utils | oe_utils/search/query_builder.py | QueryBuilder.add_concept_filter | def add_concept_filter(self, concept, concept_name=None):
"""
Add a concept filter
:param concept: concept which will be used as lowercase string in a search term
:param concept_name: name of the place where there will be searched for
"""
if concept in self.query_params.... | python | def add_concept_filter(self, concept, concept_name=None):
"""
Add a concept filter
:param concept: concept which will be used as lowercase string in a search term
:param concept_name: name of the place where there will be searched for
"""
if concept in self.query_params.... | [
"def",
"add_concept_filter",
"(",
"self",
",",
"concept",
",",
"concept_name",
"=",
"None",
")",
":",
"if",
"concept",
"in",
"self",
".",
"query_params",
".",
"keys",
"(",
")",
":",
"if",
"not",
"concept_name",
":",
"concept_name",
"=",
"concept",
"if",
... | Add a concept filter
:param concept: concept which will be used as lowercase string in a search term
:param concept_name: name of the place where there will be searched for | [
"Add",
"a",
"concept",
"filter"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/search/query_builder.py#L45-L66 |
OnroerendErfgoed/oe_utils | oe_utils/search/query_builder.py | QueryBuilder.build | def build(self):
"""
Builds the query string, which can be used for a search query
:return: the query string
"""
if self.es_version == '1':
if len(self.filters) > 0:
return {
'filtered': {
'query': self.quer... | python | def build(self):
"""
Builds the query string, which can be used for a search query
:return: the query string
"""
if self.es_version == '1':
if len(self.filters) > 0:
return {
'filtered': {
'query': self.quer... | [
"def",
"build",
"(",
"self",
")",
":",
"if",
"self",
".",
"es_version",
"==",
"'1'",
":",
"if",
"len",
"(",
"self",
".",
"filters",
")",
">",
"0",
":",
"return",
"{",
"'filtered'",
":",
"{",
"'query'",
":",
"self",
".",
"query",
",",
"'filter'",
... | Builds the query string, which can be used for a search query
:return: the query string | [
"Builds",
"the",
"query",
"string",
"which",
"can",
"be",
"used",
"for",
"a",
"search",
"query"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/search/query_builder.py#L74-L100 |
OnroerendErfgoed/oe_utils | oe_utils/range_parser.py | Range.parse | def parse(cls, request, default_start=0, default_end=9, max_end=50):
'''
Parse the range headers into a range object. When there are no range headers,
check for a page 'pagina' parameter, otherwise use the defaults defaults
:param request: a request object
:param default_start: ... | python | def parse(cls, request, default_start=0, default_end=9, max_end=50):
'''
Parse the range headers into a range object. When there are no range headers,
check for a page 'pagina' parameter, otherwise use the defaults defaults
:param request: a request object
:param default_start: ... | [
"def",
"parse",
"(",
"cls",
",",
"request",
",",
"default_start",
"=",
"0",
",",
"default_end",
"=",
"9",
",",
"max_end",
"=",
"50",
")",
":",
"settings",
"=",
"request",
".",
"registry",
".",
"settings",
"page_param",
"=",
"settings",
".",
"get",
"(",... | Parse the range headers into a range object. When there are no range headers,
check for a page 'pagina' parameter, otherwise use the defaults defaults
:param request: a request object
:param default_start: default start for paging (optional, default is 0)
:param default_end: default en... | [
"Parse",
"the",
"range",
"headers",
"into",
"a",
"range",
"object",
".",
"When",
"there",
"are",
"no",
"range",
"headers",
"check",
"for",
"a",
"page",
"pagina",
"parameter",
"otherwise",
"use",
"the",
"defaults",
"defaults"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/range_parser.py#L42-L82 |
OnroerendErfgoed/oe_utils | oe_utils/range_parser.py | Range.set_response_headers | def set_response_headers(self, request, total_count):
'''
Set the correct range headers on the response
:param request: a request object
:param total_count: the total number of results
'''
response = request.response
response.headerlist.append(('Access-Control-Ex... | python | def set_response_headers(self, request, total_count):
'''
Set the correct range headers on the response
:param request: a request object
:param total_count: the total number of results
'''
response = request.response
response.headerlist.append(('Access-Control-Ex... | [
"def",
"set_response_headers",
"(",
"self",
",",
"request",
",",
"total_count",
")",
":",
"response",
"=",
"request",
".",
"response",
"response",
".",
"headerlist",
".",
"append",
"(",
"(",
"'Access-Control-Expose-Headers'",
",",
"'Content-Range, X-Content-Range'",
... | Set the correct range headers on the response
:param request: a request object
:param total_count: the total number of results | [
"Set",
"the",
"correct",
"range",
"headers",
"on",
"the",
"response"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/range_parser.py#L84-L99 |
OnroerendErfgoed/oe_utils | oe_utils/range_parser.py | Range.set_link_headers | def set_link_headers(self, request, total_count):
"""
Sets Link headers on the response.
When the Range header is present in the request no Link headers will
be added.
4 links will be added: first, prev, next, last.
If the current page is already the first page, the prev... | python | def set_link_headers(self, request, total_count):
"""
Sets Link headers on the response.
When the Range header is present in the request no Link headers will
be added.
4 links will be added: first, prev, next, last.
If the current page is already the first page, the prev... | [
"def",
"set_link_headers",
"(",
"self",
",",
"request",
",",
"total_count",
")",
":",
"response",
"=",
"request",
".",
"response",
"if",
"request",
".",
"headers",
".",
"get",
"(",
"'Range'",
")",
":",
"# Don't set the Link headers when custom ranges were used.",
... | Sets Link headers on the response.
When the Range header is present in the request no Link headers will
be added.
4 links will be added: first, prev, next, last.
If the current page is already the first page, the prev link will
not be present.
If the current page is alre... | [
"Sets",
"Link",
"headers",
"on",
"the",
"response",
"."
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/range_parser.py#L101-L143 |
OnroerendErfgoed/oe_utils | oe_utils/validation/validators_actor.py | RRNSchemaNode.validator | def validator(node, rrn):
'''
Colander validator that checks whether a given value is a valid
Belgian national ID number .
:raises colander.Invalid: If the value is no valid Belgian national ID number.
'''
def _valid(_rrn):
x = 97 - (int(_rrn[:-2]) - (int(_rr... | python | def validator(node, rrn):
'''
Colander validator that checks whether a given value is a valid
Belgian national ID number .
:raises colander.Invalid: If the value is no valid Belgian national ID number.
'''
def _valid(_rrn):
x = 97 - (int(_rrn[:-2]) - (int(_rr... | [
"def",
"validator",
"(",
"node",
",",
"rrn",
")",
":",
"def",
"_valid",
"(",
"_rrn",
")",
":",
"x",
"=",
"97",
"-",
"(",
"int",
"(",
"_rrn",
"[",
":",
"-",
"2",
"]",
")",
"-",
"(",
"int",
"(",
"_rrn",
"[",
":",
"-",
"2",
"]",
")",
"//",
... | Colander validator that checks whether a given value is a valid
Belgian national ID number .
:raises colander.Invalid: If the value is no valid Belgian national ID number. | [
"Colander",
"validator",
"that",
"checks",
"whether",
"a",
"given",
"value",
"is",
"a",
"valid",
"Belgian",
"national",
"ID",
"number",
".",
":",
"raises",
"colander",
".",
"Invalid",
":",
"If",
"the",
"value",
"is",
"no",
"valid",
"Belgian",
"national",
"... | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/validation/validators_actor.py#L24-L49 |
OnroerendErfgoed/oe_utils | oe_utils/validation/validators_actor.py | KBOSchemaNode.preparer | def preparer(value):
'''
Edit a value to a value that can be validated as a
kbo number.
'''
if value is None or value == colander.null:
return colander.null
return value.strip().replace('.', '') | python | def preparer(value):
'''
Edit a value to a value that can be validated as a
kbo number.
'''
if value is None or value == colander.null:
return colander.null
return value.strip().replace('.', '') | [
"def",
"preparer",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
"or",
"value",
"==",
"colander",
".",
"null",
":",
"return",
"colander",
".",
"null",
"return",
"value",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"'.'",
",",
"''",
")"
] | Edit a value to a value that can be validated as a
kbo number. | [
"Edit",
"a",
"value",
"to",
"a",
"value",
"that",
"can",
"be",
"validated",
"as",
"a",
"kbo",
"number",
"."
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/validation/validators_actor.py#L57-L64 |
OnroerendErfgoed/oe_utils | oe_utils/validation/validators_actor.py | KBOSchemaNode.validator | def validator(node, value):
'''
Colander validator that checks whether a given value is a valid
is company number.
For our purposes , we expect a firm number that
is composed of nine or ten characters like 2028445291.
Sometimes a company number is formatted with separatio... | python | def validator(node, value):
'''
Colander validator that checks whether a given value is a valid
is company number.
For our purposes , we expect a firm number that
is composed of nine or ten characters like 2028445291.
Sometimes a company number is formatted with separatio... | [
"def",
"validator",
"(",
"node",
",",
"value",
")",
":",
"if",
"not",
"re",
".",
"match",
"(",
"r'^[0-9]{9,10}$'",
",",
"value",
")",
":",
"raise",
"colander",
".",
"Invalid",
"(",
"node",
",",
"'Dit is geen correct ondernemingsnummer.'",
")"
] | Colander validator that checks whether a given value is a valid
is company number.
For our purposes , we expect a firm number that
is composed of nine or ten characters like 2028445291.
Sometimes a company number is formatted with separation marks like 0.400.378.485.
Therefore, t... | [
"Colander",
"validator",
"that",
"checks",
"whether",
"a",
"given",
"value",
"is",
"a",
"valid",
"is",
"company",
"number",
".",
"For",
"our",
"purposes",
"we",
"expect",
"a",
"firm",
"number",
"that",
"is",
"composed",
"of",
"nine",
"or",
"ten",
"characte... | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/validation/validators_actor.py#L67-L82 |
OnroerendErfgoed/oe_utils | oe_utils/validation/validators_actor.py | TelefoonSchemaNode.preparer | def preparer(telefoon):
'''
Edit a phone value to a value that can be validated as a
phone number.
This takes the incoming value and :
Removes all whitespace ( space, tab , newline , ... ) characters
Removes the following characters: " / - . "
If no + ... | python | def preparer(telefoon):
'''
Edit a phone value to a value that can be validated as a
phone number.
This takes the incoming value and :
Removes all whitespace ( space, tab , newline , ... ) characters
Removes the following characters: " / - . "
If no + ... | [
"def",
"preparer",
"(",
"telefoon",
")",
":",
"if",
"telefoon",
"is",
"None",
"or",
"telefoon",
"==",
"colander",
".",
"null",
":",
"return",
"colander",
".",
"null",
"if",
"'landcode'",
"in",
"telefoon",
"and",
"telefoon",
".",
"get",
"(",
"'landcode'",
... | Edit a phone value to a value that can be validated as a
phone number.
This takes the incoming value and :
Removes all whitespace ( space, tab , newline , ... ) characters
Removes the following characters: " / - . "
If no + is present at frond, add the country code
... | [
"Edit",
"a",
"phone",
"value",
"to",
"a",
"value",
"that",
"can",
"be",
"validated",
"as",
"a",
"phone",
"number",
".",
"This",
"takes",
"the",
"incoming",
"value",
"and",
":",
"Removes",
"all",
"whitespace",
"(",
"space",
"tab",
"newline",
"...",
")",
... | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/validation/validators_actor.py#L96-L118 |
OnroerendErfgoed/oe_utils | oe_utils/validation/validators_actor.py | TelefoonSchemaNode.validator | def validator(node, telefoon):
''' A valid international phone number looks like this: + .
It is up to 15 digits long . The country code consists of 1 to 4 digits.
The actual number may even 15 - cells ( country code) figures cover . We're going to keep the phone numbers including a + to indicat... | python | def validator(node, telefoon):
''' A valid international phone number looks like this: + .
It is up to 15 digits long . The country code consists of 1 to 4 digits.
The actual number may even 15 - cells ( country code) figures cover . We're going to keep the phone numbers including a + to indicat... | [
"def",
"validator",
"(",
"node",
",",
"telefoon",
")",
":",
"if",
"telefoon",
".",
"get",
"(",
"'nummer'",
",",
"''",
")",
"!=",
"\"\"",
":",
"msg",
"=",
"\"Invalid phone number\"",
"landcode",
"=",
"telefoon",
".",
"get",
"(",
"'landcode'",
",",
"''",
... | A valid international phone number looks like this: + .
It is up to 15 digits long . The country code consists of 1 to 4 digits.
The actual number may even 15 - cells ( country code) figures cover . We're going to keep the phone numbers including a + to indicate the international call prefix.
A ... | [
"A",
"valid",
"international",
"phone",
"number",
"looks",
"like",
"this",
":",
"+",
".",
"It",
"is",
"up",
"to",
"15",
"digits",
"long",
".",
"The",
"country",
"code",
"consists",
"of",
"1",
"to",
"4",
"digits",
".",
"The",
"actual",
"number",
"may",
... | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/validation/validators_actor.py#L121-L141 |
wrwrwr/scikit-gof | skgof/cvmdist.py | cvm_unif_inf | def cvm_unif_inf(statistic):
"""
Calculates the limiting distribution of the Cramer-von Mises statistic.
After the second line of equation 1.3 from the Csorgo and Faraway paper.
"""
args = inf_args / statistic
return (inf_cs * exp(-args) * kv(.25, args)).sum() / statistic ** .5 | python | def cvm_unif_inf(statistic):
"""
Calculates the limiting distribution of the Cramer-von Mises statistic.
After the second line of equation 1.3 from the Csorgo and Faraway paper.
"""
args = inf_args / statistic
return (inf_cs * exp(-args) * kv(.25, args)).sum() / statistic ** .5 | [
"def",
"cvm_unif_inf",
"(",
"statistic",
")",
":",
"args",
"=",
"inf_args",
"/",
"statistic",
"return",
"(",
"inf_cs",
"*",
"exp",
"(",
"-",
"args",
")",
"*",
"kv",
"(",
".25",
",",
"args",
")",
")",
".",
"sum",
"(",
")",
"/",
"statistic",
"**",
... | Calculates the limiting distribution of the Cramer-von Mises statistic.
After the second line of equation 1.3 from the Csorgo and Faraway paper. | [
"Calculates",
"the",
"limiting",
"distribution",
"of",
"the",
"Cramer",
"-",
"von",
"Mises",
"statistic",
"."
] | train | https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/cvmdist.py#L48-L55 |
wrwrwr/scikit-gof | skgof/cvmdist.py | cvm_unif_fix1 | def cvm_unif_fix1(statistic):
"""
Approximates the first-term of the small sample count Gotze expansion.
After equation 1.10 (with coefficients pulled out as csa / csb).
"""
args = fix1_args / statistic
kvs = kv((.25, .75, 1.25), args[:, :, newaxis])
gs, hs = exp(-args) * tensordot(((1, 1, ... | python | def cvm_unif_fix1(statistic):
"""
Approximates the first-term of the small sample count Gotze expansion.
After equation 1.10 (with coefficients pulled out as csa / csb).
"""
args = fix1_args / statistic
kvs = kv((.25, .75, 1.25), args[:, :, newaxis])
gs, hs = exp(-args) * tensordot(((1, 1, ... | [
"def",
"cvm_unif_fix1",
"(",
"statistic",
")",
":",
"args",
"=",
"fix1_args",
"/",
"statistic",
"kvs",
"=",
"kv",
"(",
"(",
".25",
",",
".75",
",",
"1.25",
")",
",",
"args",
"[",
":",
",",
":",
",",
"newaxis",
"]",
")",
"gs",
",",
"hs",
"=",
"e... | Approximates the first-term of the small sample count Gotze expansion.
After equation 1.10 (with coefficients pulled out as csa / csb). | [
"Approximates",
"the",
"first",
"-",
"term",
"of",
"the",
"small",
"sample",
"count",
"Gotze",
"expansion",
"."
] | train | https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/cvmdist.py#L64-L75 |
quantopian/serializable-traitlets | straitlets/utils.py | merge | def merge(*ds):
"""
Merge together a sequence if dictionaries.
Later entries overwrite values from earlier entries.
>>> merge({'a': 'b', 'c': 'd'}, {'a': 'z', 'e': 'f'})
{'a': 'z', 'c': 'd', 'e': 'f'}
"""
if not ds:
raise ValueError("Must provide at least one dict to merge().")
... | python | def merge(*ds):
"""
Merge together a sequence if dictionaries.
Later entries overwrite values from earlier entries.
>>> merge({'a': 'b', 'c': 'd'}, {'a': 'z', 'e': 'f'})
{'a': 'z', 'c': 'd', 'e': 'f'}
"""
if not ds:
raise ValueError("Must provide at least one dict to merge().")
... | [
"def",
"merge",
"(",
"*",
"ds",
")",
":",
"if",
"not",
"ds",
":",
"raise",
"ValueError",
"(",
"\"Must provide at least one dict to merge().\"",
")",
"out",
"=",
"{",
"}",
"for",
"d",
"in",
"ds",
":",
"out",
".",
"update",
"(",
"d",
")",
"return",
"out"... | Merge together a sequence if dictionaries.
Later entries overwrite values from earlier entries.
>>> merge({'a': 'b', 'c': 'd'}, {'a': 'z', 'e': 'f'})
{'a': 'z', 'c': 'd', 'e': 'f'} | [
"Merge",
"together",
"a",
"sequence",
"if",
"dictionaries",
"."
] | train | https://github.com/quantopian/serializable-traitlets/blob/dd334366d1130825aea55d3dfecd6756973594e0/straitlets/utils.py#L2-L16 |
OnroerendErfgoed/oe_utils | oe_utils/validation/__init__.py | sqlalchemy_validator | def sqlalchemy_validator(node, value, model, session=None, msg='%s is ongeldig'):
"""
Validate a sqlalchemy object or identifier.
Function checks if value is an instance of sqlalchemy model
or an id of one.
:param node: A colander SchemaNode.
:param value: The value to be validated. Is the key o... | python | def sqlalchemy_validator(node, value, model, session=None, msg='%s is ongeldig'):
"""
Validate a sqlalchemy object or identifier.
Function checks if value is an instance of sqlalchemy model
or an id of one.
:param node: A colander SchemaNode.
:param value: The value to be validated. Is the key o... | [
"def",
"sqlalchemy_validator",
"(",
"node",
",",
"value",
",",
"model",
",",
"session",
"=",
"None",
",",
"msg",
"=",
"'%s is ongeldig'",
")",
":",
"m",
"=",
"session",
".",
"query",
"(",
"model",
")",
".",
"get",
"(",
"value",
")",
"if",
"not",
"m",... | Validate a sqlalchemy object or identifier.
Function checks if value is an instance of sqlalchemy model
or an id of one.
:param node: A colander SchemaNode.
:param value: The value to be validated. Is the key of the
SQLAlchemy model.
:param model: A SQLAlchemy model.
:param session: A SQ... | [
"Validate",
"a",
"sqlalchemy",
"object",
"or",
"identifier",
".",
"Function",
"checks",
"if",
"value",
"is",
"an",
"instance",
"of",
"sqlalchemy",
"model",
"or",
"an",
"id",
"of",
"one",
".",
":",
"param",
"node",
":",
"A",
"colander",
"SchemaNode",
".",
... | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/validation/__init__.py#L12-L35 |
wrwrwr/scikit-gof | skgof/ecdfgof.py | ks_stat | def ks_stat(data):
"""
Calculates the Kolmogorov-Smirnov statistic for sorted values from U(0, 1).
"""
samples = len(data)
uniform = arange(0, samples + 1) / samples
d_plus = (uniform[1:] - data).max()
d_minus = (data - uniform[:-1]).max()
return max(d_plus, d_minus) | python | def ks_stat(data):
"""
Calculates the Kolmogorov-Smirnov statistic for sorted values from U(0, 1).
"""
samples = len(data)
uniform = arange(0, samples + 1) / samples
d_plus = (uniform[1:] - data).max()
d_minus = (data - uniform[:-1]).max()
return max(d_plus, d_minus) | [
"def",
"ks_stat",
"(",
"data",
")",
":",
"samples",
"=",
"len",
"(",
"data",
")",
"uniform",
"=",
"arange",
"(",
"0",
",",
"samples",
"+",
"1",
")",
"/",
"samples",
"d_plus",
"=",
"(",
"uniform",
"[",
"1",
":",
"]",
"-",
"data",
")",
".",
"max"... | Calculates the Kolmogorov-Smirnov statistic for sorted values from U(0, 1). | [
"Calculates",
"the",
"Kolmogorov",
"-",
"Smirnov",
"statistic",
"for",
"sorted",
"values",
"from",
"U",
"(",
"0",
"1",
")",
"."
] | train | https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/ecdfgof.py#L51-L59 |
wrwrwr/scikit-gof | skgof/ecdfgof.py | cvm_stat | def cvm_stat(data):
"""
Calculates the Cramer-von Mises statistic for sorted values from U(0, 1).
"""
samples2 = 2 * len(data)
minuends = arange(1, samples2, 2) / samples2
return 1 / (6 * samples2) + ((minuends - data) ** 2).sum() | python | def cvm_stat(data):
"""
Calculates the Cramer-von Mises statistic for sorted values from U(0, 1).
"""
samples2 = 2 * len(data)
minuends = arange(1, samples2, 2) / samples2
return 1 / (6 * samples2) + ((minuends - data) ** 2).sum() | [
"def",
"cvm_stat",
"(",
"data",
")",
":",
"samples2",
"=",
"2",
"*",
"len",
"(",
"data",
")",
"minuends",
"=",
"arange",
"(",
"1",
",",
"samples2",
",",
"2",
")",
"/",
"samples2",
"return",
"1",
"/",
"(",
"6",
"*",
"samples2",
")",
"+",
"(",
"(... | Calculates the Cramer-von Mises statistic for sorted values from U(0, 1). | [
"Calculates",
"the",
"Cramer",
"-",
"von",
"Mises",
"statistic",
"for",
"sorted",
"values",
"from",
"U",
"(",
"0",
"1",
")",
"."
] | train | https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/ecdfgof.py#L62-L68 |
wrwrwr/scikit-gof | skgof/ecdfgof.py | ad_stat | def ad_stat(data):
"""
Calculates the Anderson-Darling statistic for sorted values from U(0, 1).
The statistic is not defined if any of the values is exactly 0 or 1. You
will get infinity as a result and a divide-by-zero warning for such values.
The warning can be silenced or raised using numpy.err... | python | def ad_stat(data):
"""
Calculates the Anderson-Darling statistic for sorted values from U(0, 1).
The statistic is not defined if any of the values is exactly 0 or 1. You
will get infinity as a result and a divide-by-zero warning for such values.
The warning can be silenced or raised using numpy.err... | [
"def",
"ad_stat",
"(",
"data",
")",
":",
"samples",
"=",
"len",
"(",
"data",
")",
"factors",
"=",
"arange",
"(",
"1",
",",
"2",
"*",
"samples",
",",
"2",
")",
"return",
"-",
"samples",
"-",
"(",
"factors",
"*",
"log",
"(",
"data",
"*",
"(",
"1"... | Calculates the Anderson-Darling statistic for sorted values from U(0, 1).
The statistic is not defined if any of the values is exactly 0 or 1. You
will get infinity as a result and a divide-by-zero warning for such values.
The warning can be silenced or raised using numpy.errstate(divide=...). | [
"Calculates",
"the",
"Anderson",
"-",
"Darling",
"statistic",
"for",
"sorted",
"values",
"from",
"U",
"(",
"0",
"1",
")",
"."
] | train | https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/ecdfgof.py#L71-L81 |
wrwrwr/scikit-gof | skgof/ksdist.py | ks_unif_durbin_matrix | def ks_unif_durbin_matrix(samples, statistic):
"""
Calculates the probability that the statistic is less than the given value,
using a fairly accurate implementation of the Durbin's matrix formula.
Not an exact transliteration of the Marsaglia code, but using the same
ideas. Assumes samples > 0. Se... | python | def ks_unif_durbin_matrix(samples, statistic):
"""
Calculates the probability that the statistic is less than the given value,
using a fairly accurate implementation of the Durbin's matrix formula.
Not an exact transliteration of the Marsaglia code, but using the same
ideas. Assumes samples > 0. Se... | [
"def",
"ks_unif_durbin_matrix",
"(",
"samples",
",",
"statistic",
")",
":",
"# Construct the Durbin matrix.",
"h",
",",
"k",
"=",
"modf",
"(",
"samples",
"*",
"statistic",
")",
"k",
"=",
"int",
"(",
"k",
")",
"h",
"=",
"1",
"-",
"h",
"m",
"=",
"2",
"... | Calculates the probability that the statistic is less than the given value,
using a fairly accurate implementation of the Durbin's matrix formula.
Not an exact transliteration of the Marsaglia code, but using the same
ideas. Assumes samples > 0. See: doi:10.18637/jss.v008.i18. | [
"Calculates",
"the",
"probability",
"that",
"the",
"statistic",
"is",
"less",
"than",
"the",
"given",
"value",
"using",
"a",
"fairly",
"accurate",
"implementation",
"of",
"the",
"Durbin",
"s",
"matrix",
"formula",
"."
] | train | https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/ksdist.py#L87-L133 |
wrwrwr/scikit-gof | skgof/ksdist.py | ks_unif_durbin_recurrence_rational | def ks_unif_durbin_recurrence_rational(samples, statistic):
"""
Calculates the probability that the statistic is less than the given value,
using Durbin's recurrence and employing the standard fractions module.
This is a (hopefully) exact reference implementation, likely too slow for
practical usag... | python | def ks_unif_durbin_recurrence_rational(samples, statistic):
"""
Calculates the probability that the statistic is less than the given value,
using Durbin's recurrence and employing the standard fractions module.
This is a (hopefully) exact reference implementation, likely too slow for
practical usag... | [
"def",
"ks_unif_durbin_recurrence_rational",
"(",
"samples",
",",
"statistic",
")",
":",
"t",
"=",
"statistic",
"*",
"samples",
"# Python 3: int()s can be skipped.",
"ft1",
"=",
"int",
"(",
"floor",
"(",
"t",
")",
")",
"+",
"1",
"fmt1",
"=",
"int",
"(",
"flo... | Calculates the probability that the statistic is less than the given value,
using Durbin's recurrence and employing the standard fractions module.
This is a (hopefully) exact reference implementation, likely too slow for
practical usage. The statistic should be given as a Fraction instance and
the resu... | [
"Calculates",
"the",
"probability",
"that",
"the",
"statistic",
"is",
"less",
"than",
"the",
"given",
"value",
"using",
"Durbin",
"s",
"recurrence",
"and",
"employing",
"the",
"standard",
"fractions",
"module",
"."
] | train | https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/ksdist.py#L136-L159 |
wrwrwr/scikit-gof | skgof/ksdist.py | ks_unif_pelz_good | def ks_unif_pelz_good(samples, statistic):
"""
Approximates the statistic distribution by a transformed Li-Chien formula.
This ought to be a bit more accurate than using the Kolmogorov limit, but
should only be used with large squared sample count times statistic.
See: doi:10.18637/jss.v039.i11 and... | python | def ks_unif_pelz_good(samples, statistic):
"""
Approximates the statistic distribution by a transformed Li-Chien formula.
This ought to be a bit more accurate than using the Kolmogorov limit, but
should only be used with large squared sample count times statistic.
See: doi:10.18637/jss.v039.i11 and... | [
"def",
"ks_unif_pelz_good",
"(",
"samples",
",",
"statistic",
")",
":",
"x",
"=",
"1",
"/",
"statistic",
"r2",
"=",
"1",
"/",
"samples",
"rx",
"=",
"sqrt",
"(",
"r2",
")",
"*",
"x",
"r2x",
"=",
"r2",
"*",
"x",
"r2x2",
"=",
"r2x",
"*",
"x",
"r4x... | Approximates the statistic distribution by a transformed Li-Chien formula.
This ought to be a bit more accurate than using the Kolmogorov limit, but
should only be used with large squared sample count times statistic.
See: doi:10.18637/jss.v039.i11 and http://www.jstor.org/stable/2985019. | [
"Approximates",
"the",
"statistic",
"distribution",
"by",
"a",
"transformed",
"Li",
"-",
"Chien",
"formula",
"."
] | train | https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/ksdist.py#L172-L202 |
balabit/typesafety | typesafety/__init__.py | Typesafety.activate | def activate(self, *, filter_func=None):
'''
Activate the type safety checker. After the call all functions
that need to be checked will be.
'''
if self.active:
raise RuntimeError("Type safety check already active")
self.__module_finder = ModuleFinder(Valida... | python | def activate(self, *, filter_func=None):
'''
Activate the type safety checker. After the call all functions
that need to be checked will be.
'''
if self.active:
raise RuntimeError("Type safety check already active")
self.__module_finder = ModuleFinder(Valida... | [
"def",
"activate",
"(",
"self",
",",
"*",
",",
"filter_func",
"=",
"None",
")",
":",
"if",
"self",
".",
"active",
":",
"raise",
"RuntimeError",
"(",
"\"Type safety check already active\"",
")",
"self",
".",
"__module_finder",
"=",
"ModuleFinder",
"(",
"Validat... | Activate the type safety checker. After the call all functions
that need to be checked will be. | [
"Activate",
"the",
"type",
"safety",
"checker",
".",
"After",
"the",
"call",
"all",
"functions",
"that",
"need",
"to",
"be",
"checked",
"will",
"be",
"."
] | train | https://github.com/balabit/typesafety/blob/452242dd93da9ebd53c173c243156d1351cd96fd/typesafety/__init__.py#L62-L74 |
OnroerendErfgoed/oe_utils | oe_utils/audit.py | audit | def audit(**kwargs):
"""
use this decorator to audit an operation
"""
def wrap(fn):
@functools.wraps(fn)
def advice(parent_object, *args, **kw):
request = parent_object.request
wijziging = request.audit_manager.create_revision()
result = fn(parent_o... | python | def audit(**kwargs):
"""
use this decorator to audit an operation
"""
def wrap(fn):
@functools.wraps(fn)
def advice(parent_object, *args, **kw):
request = parent_object.request
wijziging = request.audit_manager.create_revision()
result = fn(parent_o... | [
"def",
"audit",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrap",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"advice",
"(",
"parent_object",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"request",
"=",
"pare... | use this decorator to audit an operation | [
"use",
"this",
"decorator",
"to",
"audit",
"an",
"operation"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/audit.py#L40-L94 |
OnroerendErfgoed/oe_utils | oe_utils/audit.py | audit_with_request | def audit_with_request(**kwargs):
"""
use this decorator to audit an operation with a request as input variable
"""
def wrap(fn):
@audit(**kwargs)
def operation(parent_object, *args, **kw):
return fn(parent_object.request, *args, **kw)
@functools.wraps(fn)
de... | python | def audit_with_request(**kwargs):
"""
use this decorator to audit an operation with a request as input variable
"""
def wrap(fn):
@audit(**kwargs)
def operation(parent_object, *args, **kw):
return fn(parent_object.request, *args, **kw)
@functools.wraps(fn)
de... | [
"def",
"audit_with_request",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrap",
"(",
"fn",
")",
":",
"@",
"audit",
"(",
"*",
"*",
"kwargs",
")",
"def",
"operation",
"(",
"parent_object",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"... | use this decorator to audit an operation with a request as input variable | [
"use",
"this",
"decorator",
"to",
"audit",
"an",
"operation",
"with",
"a",
"request",
"as",
"input",
"variable"
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/audit.py#L97-L115 |
quantopian/serializable-traitlets | straitlets/traits.py | cross_validation_lock | def cross_validation_lock(obj):
"""
A contextmanager for holding Traited object's cross-validators.
This should be used in circumstances where you want to call _validate, but
don't want to fire cross-validators.
"""
# TODO: Replace this with usage of public API when
# https://github.com/ipy... | python | def cross_validation_lock(obj):
"""
A contextmanager for holding Traited object's cross-validators.
This should be used in circumstances where you want to call _validate, but
don't want to fire cross-validators.
"""
# TODO: Replace this with usage of public API when
# https://github.com/ipy... | [
"def",
"cross_validation_lock",
"(",
"obj",
")",
":",
"# TODO: Replace this with usage of public API when",
"# https://github.com/ipython/traitlets/pull/166 lands upstream.",
"orig",
"=",
"getattr",
"(",
"obj",
",",
"'_cross_validation_lock'",
",",
"False",
")",
"try",
":",
"... | A contextmanager for holding Traited object's cross-validators.
This should be used in circumstances where you want to call _validate, but
don't want to fire cross-validators. | [
"A",
"contextmanager",
"for",
"holding",
"Traited",
"object",
"s",
"cross",
"-",
"validators",
"."
] | train | https://github.com/quantopian/serializable-traitlets/blob/dd334366d1130825aea55d3dfecd6756973594e0/straitlets/traits.py#L19-L33 |
quantopian/serializable-traitlets | straitlets/traits.py | Instance.example_value | def example_value(self):
"""
If we're an instance of a Serializable, fall back to its
`example_instance()` method.
"""
from .serializable import Serializable
inst = self._static_example_value()
if inst is tr.Undefined and issubclass(self.klass, Serializable):
... | python | def example_value(self):
"""
If we're an instance of a Serializable, fall back to its
`example_instance()` method.
"""
from .serializable import Serializable
inst = self._static_example_value()
if inst is tr.Undefined and issubclass(self.klass, Serializable):
... | [
"def",
"example_value",
"(",
"self",
")",
":",
"from",
".",
"serializable",
"import",
"Serializable",
"inst",
"=",
"self",
".",
"_static_example_value",
"(",
")",
"if",
"inst",
"is",
"tr",
".",
"Undefined",
"and",
"issubclass",
"(",
"self",
".",
"klass",
"... | If we're an instance of a Serializable, fall back to its
`example_instance()` method. | [
"If",
"we",
"re",
"an",
"instance",
"of",
"a",
"Serializable",
"fall",
"back",
"to",
"its",
"example_instance",
"()",
"method",
"."
] | train | https://github.com/quantopian/serializable-traitlets/blob/dd334366d1130825aea55d3dfecd6756973594e0/straitlets/traits.py#L208-L217 |
OnroerendErfgoed/oe_utils | oe_utils/deploy/__init__.py | copy_and_replace | def copy_and_replace(file_in, file_out, mapping, **kwargs):
'''
Copy a file and replace some placeholders with new values.
'''
separator = '@@'
if 'separator' in kwargs:
separator = kwargs['separator']
file_in = open(file_in, 'r')
file_out = open(file_out, 'w')
s = file_in.read()... | python | def copy_and_replace(file_in, file_out, mapping, **kwargs):
'''
Copy a file and replace some placeholders with new values.
'''
separator = '@@'
if 'separator' in kwargs:
separator = kwargs['separator']
file_in = open(file_in, 'r')
file_out = open(file_out, 'w')
s = file_in.read()... | [
"def",
"copy_and_replace",
"(",
"file_in",
",",
"file_out",
",",
"mapping",
",",
"*",
"*",
"kwargs",
")",
":",
"separator",
"=",
"'@@'",
"if",
"'separator'",
"in",
"kwargs",
":",
"separator",
"=",
"kwargs",
"[",
"'separator'",
"]",
"file_in",
"=",
"open",
... | Copy a file and replace some placeholders with new values. | [
"Copy",
"a",
"file",
"and",
"replace",
"some",
"placeholders",
"with",
"new",
"values",
"."
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/deploy/__init__.py#L4-L18 |
OnroerendErfgoed/oe_utils | oe_utils/data/data_types.py | MutableList.coerce | def coerce(cls, key, value):
"""
Convert plain list to MutableList.
"""
if not isinstance(value, MutableList):
if isinstance(value, list):
return MutableList(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
... | python | def coerce(cls, key, value):
"""
Convert plain list to MutableList.
"""
if not isinstance(value, MutableList):
if isinstance(value, list):
return MutableList(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
... | [
"def",
"coerce",
"(",
"cls",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"MutableList",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"MutableList",
"(",
"value",
")",
"# this call wi... | Convert plain list to MutableList. | [
"Convert",
"plain",
"list",
"to",
"MutableList",
"."
] | train | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/data/data_types.py#L8-L18 |
LordGaav/python-chaos | chaos/multiprocessing/workers.py | Workers.registerWorker | def registerWorker(self, name, worker):
"""
Register a new Worker, under the given descriptive name.
Trying to register multiple workers under the same name will raise an Exception.
Parameters
----------
name: string
Name to register the given worker under.
worker: multiprocessing.Process, or a subcl... | python | def registerWorker(self, name, worker):
"""
Register a new Worker, under the given descriptive name.
Trying to register multiple workers under the same name will raise an Exception.
Parameters
----------
name: string
Name to register the given worker under.
worker: multiprocessing.Process, or a subcl... | [
"def",
"registerWorker",
"(",
"self",
",",
"name",
",",
"worker",
")",
":",
"if",
"not",
"isinstance",
"(",
"worker",
",",
"multiprocessing",
".",
"Process",
")",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Process {0} is not actually a Process!\"",
".",... | Register a new Worker, under the given descriptive name.
Trying to register multiple workers under the same name will raise an Exception.
Parameters
----------
name: string
Name to register the given worker under.
worker: multiprocessing.Process, or a subclass
Process object to register. | [
"Register",
"a",
"new",
"Worker",
"under",
"the",
"given",
"descriptive",
"name",
"."
] | train | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/multiprocessing/workers.py#L33-L57 |
LordGaav/python-chaos | chaos/multiprocessing/workers.py | Workers.getWorker | def getWorker(self, name):
"""
Retrieve the Worker registered under the given name.
If the given name does not exists in the Worker list, an Exception is raised.
Parameters
----------
name: string
Name of the Worker to retrieve
"""
if not name in self.worker_list:
self.logger.error("Worker {0} i... | python | def getWorker(self, name):
"""
Retrieve the Worker registered under the given name.
If the given name does not exists in the Worker list, an Exception is raised.
Parameters
----------
name: string
Name of the Worker to retrieve
"""
if not name in self.worker_list:
self.logger.error("Worker {0} i... | [
"def",
"getWorker",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"name",
"in",
"self",
".",
"worker_list",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Worker {0} is not registered!\"",
".",
"format",
"(",
"name",
")",
")",
"raise",
"Exception",
... | Retrieve the Worker registered under the given name.
If the given name does not exists in the Worker list, an Exception is raised.
Parameters
----------
name: string
Name of the Worker to retrieve | [
"Retrieve",
"the",
"Worker",
"registered",
"under",
"the",
"given",
"name",
"."
] | train | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/multiprocessing/workers.py#L65-L80 |
LordGaav/python-chaos | chaos/multiprocessing/workers.py | Workers.unregisterWorker | def unregisterWorker(self, name):
"""
Unregister the Worker registered under the given name.
Make sure that the given Worker is properly stopped, or that a reference is
kept in another place. Once unregistered, this class will not keep any
other references to the Worker.
Parameters
----------
name: st... | python | def unregisterWorker(self, name):
"""
Unregister the Worker registered under the given name.
Make sure that the given Worker is properly stopped, or that a reference is
kept in another place. Once unregistered, this class will not keep any
other references to the Worker.
Parameters
----------
name: st... | [
"def",
"unregisterWorker",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"name",
"in",
"self",
".",
"worker_list",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Worker {0} is not registered!\"",
".",
"format",
"(",
"name",
")",
")",
"raise",
"Except... | Unregister the Worker registered under the given name.
Make sure that the given Worker is properly stopped, or that a reference is
kept in another place. Once unregistered, this class will not keep any
other references to the Worker.
Parameters
----------
name: string
Name of the Worker to unregister | [
"Unregister",
"the",
"Worker",
"registered",
"under",
"the",
"given",
"name",
"."
] | train | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/multiprocessing/workers.py#L82-L100 |
LordGaav/python-chaos | chaos/multiprocessing/workers.py | Workers.startAll | def startAll(self):
"""
Start all registered Workers.
"""
self.logger.info("Starting all workers...")
for worker in self.getWorkers():
process = self.getWorker(worker)
self.logger.debug("Starting {0}".format(process.name))
process.start()
self.logger.info("Started all workers") | python | def startAll(self):
"""
Start all registered Workers.
"""
self.logger.info("Starting all workers...")
for worker in self.getWorkers():
process = self.getWorker(worker)
self.logger.debug("Starting {0}".format(process.name))
process.start()
self.logger.info("Started all workers") | [
"def",
"startAll",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Starting all workers...\"",
")",
"for",
"worker",
"in",
"self",
".",
"getWorkers",
"(",
")",
":",
"process",
"=",
"self",
".",
"getWorker",
"(",
"worker",
")",
"self",
... | Start all registered Workers. | [
"Start",
"all",
"registered",
"Workers",
"."
] | train | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/multiprocessing/workers.py#L102-L113 |
LordGaav/python-chaos | chaos/multiprocessing/workers.py | Workers.stopAll | def stopAll(self, timeout=10, stop=False):
"""
Stop all registered Workers. This is method assumes that the Worker has already
received a stop message somehow, and simply joins the Process until it dies, as
follows:
1. The Worker is retrieved.
2. The Worker is joined, and will wait until the Worker exits.... | python | def stopAll(self, timeout=10, stop=False):
"""
Stop all registered Workers. This is method assumes that the Worker has already
received a stop message somehow, and simply joins the Process until it dies, as
follows:
1. The Worker is retrieved.
2. The Worker is joined, and will wait until the Worker exits.... | [
"def",
"stopAll",
"(",
"self",
",",
"timeout",
"=",
"10",
",",
"stop",
"=",
"False",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Stopping all workers...\"",
")",
"for",
"worker",
"in",
"self",
".",
"getWorkers",
"(",
")",
":",
"process",
"=",... | Stop all registered Workers. This is method assumes that the Worker has already
received a stop message somehow, and simply joins the Process until it dies, as
follows:
1. The Worker is retrieved.
2. The Worker is joined, and will wait until the Worker exits.
3. The Worker is unregistered.
4. If $stop = T... | [
"Stop",
"all",
"registered",
"Workers",
".",
"This",
"is",
"method",
"assumes",
"that",
"the",
"Worker",
"has",
"already",
"received",
"a",
"stop",
"message",
"somehow",
"and",
"simply",
"joins",
"the",
"Process",
"until",
"it",
"dies",
"as",
"follows",
":"
... | train | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/multiprocessing/workers.py#L115-L142 |
jeremymcrae/denovonear | denovonear/ensembl_cache.py | EnsemblCache.get_cached_data | def get_cached_data(self, url):
""" get cached data for a url if stored in the cache and not outdated
Args:
url: URL for the Ensembl REST service
Returns:
data if data in cache, else None
"""
key = self.get_key_from_url(url)
... | python | def get_cached_data(self, url):
""" get cached data for a url if stored in the cache and not outdated
Args:
url: URL for the Ensembl REST service
Returns:
data if data in cache, else None
"""
key = self.get_key_from_url(url)
... | [
"def",
"get_cached_data",
"(",
"self",
",",
"url",
")",
":",
"key",
"=",
"self",
".",
"get_key_from_url",
"(",
"url",
")",
"with",
"self",
".",
"conn",
"as",
"conn",
":",
"cursor",
"=",
"conn",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
... | get cached data for a url if stored in the cache and not outdated
Args:
url: URL for the Ensembl REST service
Returns:
data if data in cache, else None | [
"get",
"cached",
"data",
"for",
"a",
"url",
"if",
"stored",
"in",
"the",
"cache",
"and",
"not",
"outdated",
"Args",
":",
"url",
":",
"URL",
"for",
"the",
"Ensembl",
"REST",
"service",
"Returns",
":",
"data",
"if",
"data",
"in",
"cache",
"else",
"None"
... | train | https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/ensembl_cache.py#L58-L90 |
jeremymcrae/denovonear | denovonear/ensembl_cache.py | EnsemblCache.cache_url_data | def cache_url_data(self, url, data, attempt=0):
""" cache the data retrieved from ensembl
Args:
url: URL for the Ensembl REST service
data: response data from Ensembl
"""
if attempt > 5:
raise ValueError('too many attempts at writing ... | python | def cache_url_data(self, url, data, attempt=0):
""" cache the data retrieved from ensembl
Args:
url: URL for the Ensembl REST service
data: response data from Ensembl
"""
if attempt > 5:
raise ValueError('too many attempts at writing ... | [
"def",
"cache_url_data",
"(",
"self",
",",
"url",
",",
"data",
",",
"attempt",
"=",
"0",
")",
":",
"if",
"attempt",
">",
"5",
":",
"raise",
"ValueError",
"(",
"'too many attempts at writing to the cache'",
")",
"key",
"=",
"self",
".",
"get_key_from_url",
"(... | cache the data retrieved from ensembl
Args:
url: URL for the Ensembl REST service
data: response data from Ensembl | [
"cache",
"the",
"data",
"retrieved",
"from",
"ensembl",
"Args",
":",
"url",
":",
"URL",
"for",
"the",
"Ensembl",
"REST",
"service",
"data",
":",
"response",
"data",
"from",
"Ensembl"
] | train | https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/ensembl_cache.py#L92-L133 |
jeremymcrae/denovonear | denovonear/ensembl_cache.py | EnsemblCache.get_key_from_url | def get_key_from_url(self, url):
""" parses the url into a list of folder locations
We take a URL like:
http://rest.ensembl.org/sequence/id/ENST00000538324?type=genomic;expand_3prime=10;expand_5prime=10
and turn it into 'sequence.id.ENST00000538324.genomic'
... | python | def get_key_from_url(self, url):
""" parses the url into a list of folder locations
We take a URL like:
http://rest.ensembl.org/sequence/id/ENST00000538324?type=genomic;expand_3prime=10;expand_5prime=10
and turn it into 'sequence.id.ENST00000538324.genomic'
... | [
"def",
"get_key_from_url",
"(",
"self",
",",
"url",
")",
":",
"key",
"=",
"url",
".",
"split",
"(",
"\"/\"",
")",
"[",
"3",
":",
"]",
"# fix the final bit of the url, none of which uniquely define the data",
"suffix",
"=",
"key",
".",
"pop",
"(",
")",
"suffix"... | parses the url into a list of folder locations
We take a URL like:
http://rest.ensembl.org/sequence/id/ENST00000538324?type=genomic;expand_3prime=10;expand_5prime=10
and turn it into 'sequence.id.ENST00000538324.genomic'
Args:
url: URL for the Ensembl RE... | [
"parses",
"the",
"url",
"into",
"a",
"list",
"of",
"folder",
"locations",
"We",
"take",
"a",
"URL",
"like",
":",
"http",
":",
"//",
"rest",
".",
"ensembl",
".",
"org",
"/",
"sequence",
"/",
"id",
"/",
"ENST00000538324?type",
"=",
"genomic",
";",
"expan... | train | https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/ensembl_cache.py#L135-L167 |
ReadabilityHoldings/python-readability-api | readability/utils.py | cast_datetime_filter | def cast_datetime_filter(value):
"""Cast a datetime filter value.
:param value: string representation of a value that needs to be casted to
a `datetime` object.
"""
if isinstance(value, str):
dtime = parse_datetime(value)
elif isinstance(value, datetime):
dtime = value
... | python | def cast_datetime_filter(value):
"""Cast a datetime filter value.
:param value: string representation of a value that needs to be casted to
a `datetime` object.
"""
if isinstance(value, str):
dtime = parse_datetime(value)
elif isinstance(value, datetime):
dtime = value
... | [
"def",
"cast_datetime_filter",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"dtime",
"=",
"parse_datetime",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
")",
":",
"dtime",
"=",
"value",
"else"... | Cast a datetime filter value.
:param value: string representation of a value that needs to be casted to
a `datetime` object. | [
"Cast",
"a",
"datetime",
"filter",
"value",
"."
] | train | https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/utils.py#L46-L61 |
ReadabilityHoldings/python-readability-api | readability/utils.py | filter_args_to_dict | def filter_args_to_dict(filter_dict, accepted_filter_keys=[]):
"""Cast and validate filter args.
:param filter_dict: Filter kwargs
:param accepted_filter_keys: List of keys that are acceptable to use.
"""
out_dict = {}
for k, v in filter_dict.items():
# make sure that the filter k is a... | python | def filter_args_to_dict(filter_dict, accepted_filter_keys=[]):
"""Cast and validate filter args.
:param filter_dict: Filter kwargs
:param accepted_filter_keys: List of keys that are acceptable to use.
"""
out_dict = {}
for k, v in filter_dict.items():
# make sure that the filter k is a... | [
"def",
"filter_args_to_dict",
"(",
"filter_dict",
",",
"accepted_filter_keys",
"=",
"[",
"]",
")",
":",
"out_dict",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"filter_dict",
".",
"items",
"(",
")",
":",
"# make sure that the filter k is acceptable",
"# and that ... | Cast and validate filter args.
:param filter_dict: Filter kwargs
:param accepted_filter_keys: List of keys that are acceptable to use. | [
"Cast",
"and",
"validate",
"filter",
"args",
"."
] | train | https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/utils.py#L75-L113 |
hyperboria/python-cjdns | cjdns/bencode.py | bencode | def bencode(obj):
"""Bencodes obj and returns it as a string"""
if isinstance(obj, int):
return "i" + str(obj) + "e"
if isinstance(obj, str):
if not obj:
return None
return str(len(obj)) + ":" + obj
if isinstance(obj, list):
res = "l"
for elem in obj... | python | def bencode(obj):
"""Bencodes obj and returns it as a string"""
if isinstance(obj, int):
return "i" + str(obj) + "e"
if isinstance(obj, str):
if not obj:
return None
return str(len(obj)) + ":" + obj
if isinstance(obj, list):
res = "l"
for elem in obj... | [
"def",
"bencode",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"int",
")",
":",
"return",
"\"i\"",
"+",
"str",
"(",
"obj",
")",
"+",
"\"e\"",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"if",
"not",
"obj",
":",
"return",
... | Bencodes obj and returns it as a string | [
"Bencodes",
"obj",
"and",
"returns",
"it",
"as",
"a",
"string"
] | train | https://github.com/hyperboria/python-cjdns/blob/a9ae5d6d2e99c18f9fc50a9589729cd176efa900/cjdns/bencode.py#L26-L60 |
hyperboria/python-cjdns | cjdns/bencode.py | bdecode | def bdecode(text):
"""Decodes a bencoded bytearray and returns it as a python object"""
text = text.decode('utf-8')
def bdecode_next(start):
"""bdecode helper function"""
if text[start] == 'i':
end = text.find('e', start)
return int(text[start+1:end], 10), end + 1
... | python | def bdecode(text):
"""Decodes a bencoded bytearray and returns it as a python object"""
text = text.decode('utf-8')
def bdecode_next(start):
"""bdecode helper function"""
if text[start] == 'i':
end = text.find('e', start)
return int(text[start+1:end], 10), end + 1
... | [
"def",
"bdecode",
"(",
"text",
")",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"'utf-8'",
")",
"def",
"bdecode_next",
"(",
"start",
")",
":",
"\"\"\"bdecode helper function\"\"\"",
"if",
"text",
"[",
"start",
"]",
"==",
"'i'",
":",
"end",
"=",
"text",... | Decodes a bencoded bytearray and returns it as a python object | [
"Decodes",
"a",
"bencoded",
"bytearray",
"and",
"returns",
"it",
"as",
"a",
"python",
"object"
] | train | https://github.com/hyperboria/python-cjdns/blob/a9ae5d6d2e99c18f9fc50a9589729cd176efa900/cjdns/bencode.py#L63-L94 |
jakewins/neo4jdb-python | pavement.py | change_password | def change_password():
"""
Changes the standard password from neo4j to testing to be able to run the test suite.
"""
basic_auth = '%s:%s' % (DEFAULT_USERNAME, DEFAULT_PASSWORD)
try: # Python 2
auth = base64.encodestring(basic_auth)
except TypeError: # Python 3
auth = base64.enc... | python | def change_password():
"""
Changes the standard password from neo4j to testing to be able to run the test suite.
"""
basic_auth = '%s:%s' % (DEFAULT_USERNAME, DEFAULT_PASSWORD)
try: # Python 2
auth = base64.encodestring(basic_auth)
except TypeError: # Python 3
auth = base64.enc... | [
"def",
"change_password",
"(",
")",
":",
"basic_auth",
"=",
"'%s:%s'",
"%",
"(",
"DEFAULT_USERNAME",
",",
"DEFAULT_PASSWORD",
")",
"try",
":",
"# Python 2",
"auth",
"=",
"base64",
".",
"encodestring",
"(",
"basic_auth",
")",
"except",
"TypeError",
":",
"# Pyth... | Changes the standard password from neo4j to testing to be able to run the test suite. | [
"Changes",
"the",
"standard",
"password",
"from",
"neo4j",
"to",
"testing",
"to",
"be",
"able",
"to",
"run",
"the",
"test",
"suite",
"."
] | train | https://github.com/jakewins/neo4jdb-python/blob/cd78cb8397885f219500fb1080d301f0c900f7be/pavement.py#L75-L109 |
LordGaav/python-chaos | chaos/arguments.py | get_config_argparse | def get_config_argparse(suppress=None):
"""
Create an ArgumentParser which listens for the following common options:
- --config
- --help
- --quiet
- --verbose
- --version
Arguments
---------
suppress_help: list of strings
Defines what options to suppress from being added to the ArgumentParser. Provide
th... | python | def get_config_argparse(suppress=None):
"""
Create an ArgumentParser which listens for the following common options:
- --config
- --help
- --quiet
- --verbose
- --version
Arguments
---------
suppress_help: list of strings
Defines what options to suppress from being added to the ArgumentParser. Provide
th... | [
"def",
"get_config_argparse",
"(",
"suppress",
"=",
"None",
")",
":",
"if",
"suppress",
"is",
"None",
":",
"suppress",
"=",
"[",
"]",
"config_parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"\"Looking for config\"",
",",
"add_help",
"=",
"(",
"not",
... | Create an ArgumentParser which listens for the following common options:
- --config
- --help
- --quiet
- --verbose
- --version
Arguments
---------
suppress_help: list of strings
Defines what options to suppress from being added to the ArgumentParser. Provide
the name of the options to suppress, without "--... | [
"Create",
"an",
"ArgumentParser",
"which",
"listens",
"for",
"the",
"following",
"common",
"options",
":",
"-",
"--",
"config",
"-",
"--",
"help",
"-",
"--",
"quiet",
"-",
"--",
"verbose",
"-",
"--",
"version"
] | train | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/arguments.py#L27-L64 |
LordGaav/python-chaos | chaos/arguments.py | get_config_arguments | def get_config_arguments():
"""
Parse command line arguments, and try to find common options. Internally
this method uses the ArgumentParser returned by get_config_argparse().
All variables are stored as True if set, --config will contain a string.
Returns a tuple containing parsed variables and unknown variable... | python | def get_config_arguments():
"""
Parse command line arguments, and try to find common options. Internally
this method uses the ArgumentParser returned by get_config_argparse().
All variables are stored as True if set, --config will contain a string.
Returns a tuple containing parsed variables and unknown variable... | [
"def",
"get_config_arguments",
"(",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"Parsing configuration arguments\"",
")",
"return",
"get_config_argparse",
"(",
"suppress",
"=",
"[",
"\"help\"",
"]",
... | Parse command line arguments, and try to find common options. Internally
this method uses the ArgumentParser returned by get_config_argparse().
All variables are stored as True if set, --config will contain a string.
Returns a tuple containing parsed variables and unknown variables,
just like ArgumentParser.parse... | [
"Parse",
"command",
"line",
"arguments",
"and",
"try",
"to",
"find",
"common",
"options",
".",
"Internally",
"this",
"method",
"uses",
"the",
"ArgumentParser",
"returned",
"by",
"get_config_argparse",
"()",
"."
] | train | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/arguments.py#L66-L80 |
LordGaav/python-chaos | chaos/arguments.py | get_default_config_file | def get_default_config_file(argparser, suppress=None, default_override=None):
"""
Turn an ArgumentParser into a ConfigObj compatible configuration file.
This method will take the given argparser, and loop over all options contained. The configuration file is formatted
as follows:
# <option help info>
<option de... | python | def get_default_config_file(argparser, suppress=None, default_override=None):
"""
Turn an ArgumentParser into a ConfigObj compatible configuration file.
This method will take the given argparser, and loop over all options contained. The configuration file is formatted
as follows:
# <option help info>
<option de... | [
"def",
"get_default_config_file",
"(",
"argparser",
",",
"suppress",
"=",
"None",
",",
"default_override",
"=",
"None",
")",
":",
"if",
"not",
"suppress",
":",
"suppress",
"=",
"[",
"]",
"if",
"not",
"default_override",
":",
"default_override",
"=",
"{",
"}"... | Turn an ArgumentParser into a ConfigObj compatible configuration file.
This method will take the given argparser, and loop over all options contained. The configuration file is formatted
as follows:
# <option help info>
<option destination variable>=<option default value>
Arguments
---------
argparser: Argume... | [
"Turn",
"an",
"ArgumentParser",
"into",
"a",
"ConfigObj",
"compatible",
"configuration",
"file",
"."
] | train | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/arguments.py#L82-L119 |
LordGaav/python-chaos | chaos/amqp/queue.py | Queue._perform_binds | def _perform_binds(self, binds):
"""
Binds queues to exchanges.
Parameters
----------
binds: list of dicts
a list of dicts with the following keys:
queue: string - name of the queue to bind
exchange: string - name of the exchange to bind
routing_key: string - routing key to use for this bind
... | python | def _perform_binds(self, binds):
"""
Binds queues to exchanges.
Parameters
----------
binds: list of dicts
a list of dicts with the following keys:
queue: string - name of the queue to bind
exchange: string - name of the exchange to bind
routing_key: string - routing key to use for this bind
... | [
"def",
"_perform_binds",
"(",
"self",
",",
"binds",
")",
":",
"for",
"bind",
"in",
"binds",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Binding queue {0} to exchange {1} with key {2}\"",
".",
"format",
"(",
"bind",
"[",
"'queue'",
"]",
",",
"bind",
"["... | Binds queues to exchanges.
Parameters
----------
binds: list of dicts
a list of dicts with the following keys:
queue: string - name of the queue to bind
exchange: string - name of the exchange to bind
routing_key: string - routing key to use for this bind | [
"Binds",
"queues",
"to",
"exchanges",
"."
] | train | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/amqp/queue.py#L70-L84 |
LordGaav/python-chaos | chaos/amqp/queue.py | Queue._perform_unbinds | def _perform_unbinds(self, binds):
"""
Unbinds queues from exchanges.
Parameters
----------
binds: list of dicts
A list of dicts with the following keys:
queue: string - name of the queue to bind
exchange: string - name of the exchange to bind
routing_key: string - routing key to use for this ... | python | def _perform_unbinds(self, binds):
"""
Unbinds queues from exchanges.
Parameters
----------
binds: list of dicts
A list of dicts with the following keys:
queue: string - name of the queue to bind
exchange: string - name of the exchange to bind
routing_key: string - routing key to use for this ... | [
"def",
"_perform_unbinds",
"(",
"self",
",",
"binds",
")",
":",
"for",
"bind",
"in",
"binds",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Unbinding queue {0} from exchange {1} with key {2}\"",
".",
"format",
"(",
"bind",
"[",
"'queue'",
"]",
",",
"bind",... | Unbinds queues from exchanges.
Parameters
----------
binds: list of dicts
A list of dicts with the following keys:
queue: string - name of the queue to bind
exchange: string - name of the exchange to bind
routing_key: string - routing key to use for this bind | [
"Unbinds",
"queues",
"from",
"exchanges",
"."
] | train | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/amqp/queue.py#L86-L100 |
LordGaav/python-chaos | chaos/amqp/queue.py | Queue.close | def close(self):
"""
Closes the internal connection.
"""
self.cancel()
self.logger.debug("Closing AMQP connection")
try:
self.connection.close()
except Exception, eee:
self.logger.warning("Received an error while trying to close AMQP connection: " + str(eee)) | python | def close(self):
"""
Closes the internal connection.
"""
self.cancel()
self.logger.debug("Closing AMQP connection")
try:
self.connection.close()
except Exception, eee:
self.logger.warning("Received an error while trying to close AMQP connection: " + str(eee)) | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"cancel",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Closing AMQP connection\"",
")",
"try",
":",
"self",
".",
"connection",
".",
"close",
"(",
")",
"except",
"Exception",
",",
"eee",
":",... | Closes the internal connection. | [
"Closes",
"the",
"internal",
"connection",
"."
] | train | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/amqp/queue.py#L102-L111 |
LordGaav/python-chaos | chaos/amqp/queue.py | Queue.cancel | def cancel(self, consumer_tag=None):
"""
Cancels the current consuming action by using the stored consumer_tag. If a consumer_tag is given, that one is used instead.
Parameters
----------
consumer_tag: string
Tag of consumer to cancel
"""
if not consumer_tag:
if not hasattr(self, "consumer_tag"):
... | python | def cancel(self, consumer_tag=None):
"""
Cancels the current consuming action by using the stored consumer_tag. If a consumer_tag is given, that one is used instead.
Parameters
----------
consumer_tag: string
Tag of consumer to cancel
"""
if not consumer_tag:
if not hasattr(self, "consumer_tag"):
... | [
"def",
"cancel",
"(",
"self",
",",
"consumer_tag",
"=",
"None",
")",
":",
"if",
"not",
"consumer_tag",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"consumer_tag\"",
")",
":",
"return",
"consumer_tag",
"=",
"self",
".",
"consumer_tag",
"self",
".",
"... | Cancels the current consuming action by using the stored consumer_tag. If a consumer_tag is given, that one is used instead.
Parameters
----------
consumer_tag: string
Tag of consumer to cancel | [
"Cancels",
"the",
"current",
"consuming",
"action",
"by",
"using",
"the",
"stored",
"consumer_tag",
".",
"If",
"a",
"consumer_tag",
"is",
"given",
"that",
"one",
"is",
"used",
"instead",
"."
] | train | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/amqp/queue.py#L113-L126 |
LordGaav/python-chaos | chaos/amqp/queue.py | Queue.consume | def consume(self, consumer_callback, exclusive=False, recover=False):
"""
Initialize consuming of messages from an AMQP queue. Messages will be consumed after start_consuming() is called.
Calling this method multiple times with exclusive active will result in a pika.exceptions.ChannelClosed Error.
Parameters
... | python | def consume(self, consumer_callback, exclusive=False, recover=False):
"""
Initialize consuming of messages from an AMQP queue. Messages will be consumed after start_consuming() is called.
Calling this method multiple times with exclusive active will result in a pika.exceptions.ChannelClosed Error.
Parameters
... | [
"def",
"consume",
"(",
"self",
",",
"consumer_callback",
",",
"exclusive",
"=",
"False",
",",
"recover",
"=",
"False",
")",
":",
"if",
"recover",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Asking server to requeue all unacknowledged messages\"",
")",
"self... | Initialize consuming of messages from an AMQP queue. Messages will be consumed after start_consuming() is called.
Calling this method multiple times with exclusive active will result in a pika.exceptions.ChannelClosed Error.
Parameters
----------
consumer_callback: callback
Function to call when a message ... | [
"Initialize",
"consuming",
"of",
"messages",
"from",
"an",
"AMQP",
"queue",
".",
"Messages",
"will",
"be",
"consumed",
"after",
"start_consuming",
"()",
"is",
"called",
"."
] | train | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/amqp/queue.py#L128-L158 |
unfoldingWord-dev/python-gogs-client | gogs_client/entities.py | json_get | def json_get(parsed_json, key):
"""
Retrieves the key from a parsed_json dictionary, or raises an exception if the
key is not present
"""
if key not in parsed_json:
raise ValueError("JSON does not contain a {} field".format(key))
return parsed_json[key] | python | def json_get(parsed_json, key):
"""
Retrieves the key from a parsed_json dictionary, or raises an exception if the
key is not present
"""
if key not in parsed_json:
raise ValueError("JSON does not contain a {} field".format(key))
return parsed_json[key] | [
"def",
"json_get",
"(",
"parsed_json",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"parsed_json",
":",
"raise",
"ValueError",
"(",
"\"JSON does not contain a {} field\"",
".",
"format",
"(",
"key",
")",
")",
"return",
"parsed_json",
"[",
"key",
"]"
] | Retrieves the key from a parsed_json dictionary, or raises an exception if the
key is not present | [
"Retrieves",
"the",
"key",
"from",
"a",
"parsed_json",
"dictionary",
"or",
"raises",
"an",
"exception",
"if",
"the",
"key",
"is",
"not",
"present"
] | train | https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/entities.py#L10-L17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.