repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
horejsek/python-sqlpuzzle | sqlpuzzle/_queryparts/values.py | MultipleValues.all_columns | def all_columns(self):
"""Return list of all columns."""
columns = set()
for values in self._parts:
for value in values._parts:
columns.add(value.column_name)
return sorted(columns) | python | def all_columns(self):
"""Return list of all columns."""
columns = set()
for values in self._parts:
for value in values._parts:
columns.add(value.column_name)
return sorted(columns) | [
"def",
"all_columns",
"(",
"self",
")",
":",
"columns",
"=",
"set",
"(",
")",
"for",
"values",
"in",
"self",
".",
"_parts",
":",
"for",
"value",
"in",
"values",
".",
"_parts",
":",
"columns",
".",
"add",
"(",
"value",
".",
"column_name",
")",
"return... | Return list of all columns. | [
"Return",
"list",
"of",
"all",
"columns",
"."
] | d3a42ed1b339b8eafddb8d2c28a3a5832b3998dd | https://github.com/horejsek/python-sqlpuzzle/blob/d3a42ed1b339b8eafddb8d2c28a3a5832b3998dd/sqlpuzzle/_queryparts/values.py#L79-L85 | train | 50,100 |
upsight/doctor | doctor/resource.py | ResourceSchemaAnnotation.get_annotation | def get_annotation(cls, fn):
"""Find the _schema_annotation attribute for the given function.
This will descend through decorators until it finds something that has
the attribute. If it doesn't find it anywhere, it will return None.
:param func fn: Find the attribute on this function.
:returns: an instance of
:class:`~doctor.resource.ResourceSchemaAnnotation` or
None.
"""
while fn is not None:
if hasattr(fn, '_schema_annotation'):
return fn._schema_annotation
fn = getattr(fn, 'im_func', fn)
closure = getattr(fn, '__closure__', None)
fn = closure[0].cell_contents if closure is not None else None
return None | python | def get_annotation(cls, fn):
"""Find the _schema_annotation attribute for the given function.
This will descend through decorators until it finds something that has
the attribute. If it doesn't find it anywhere, it will return None.
:param func fn: Find the attribute on this function.
:returns: an instance of
:class:`~doctor.resource.ResourceSchemaAnnotation` or
None.
"""
while fn is not None:
if hasattr(fn, '_schema_annotation'):
return fn._schema_annotation
fn = getattr(fn, 'im_func', fn)
closure = getattr(fn, '__closure__', None)
fn = closure[0].cell_contents if closure is not None else None
return None | [
"def",
"get_annotation",
"(",
"cls",
",",
"fn",
")",
":",
"while",
"fn",
"is",
"not",
"None",
":",
"if",
"hasattr",
"(",
"fn",
",",
"'_schema_annotation'",
")",
":",
"return",
"fn",
".",
"_schema_annotation",
"fn",
"=",
"getattr",
"(",
"fn",
",",
"'im_... | Find the _schema_annotation attribute for the given function.
This will descend through decorators until it finds something that has
the attribute. If it doesn't find it anywhere, it will return None.
:param func fn: Find the attribute on this function.
:returns: an instance of
:class:`~doctor.resource.ResourceSchemaAnnotation` or
None. | [
"Find",
"the",
"_schema_annotation",
"attribute",
"for",
"the",
"given",
"function",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/resource.py#L48-L65 | train | 50,101 |
upsight/doctor | doctor/resource.py | ResourceSchema._create_request_schema | def _create_request_schema(self, params, required):
"""Create a JSON schema for a request.
:param list params: A list of keys specifying which definitions from
the base schema should be allowed in the request.
:param list required: A subset of the params that the requester must
specify in the request.
:returns: a JSON schema dict
"""
# We allow additional properties because the data this will validate
# may also include kwargs passed by decorators on the handler method.
schema = {'additionalProperties': True,
'definitions': self.resolve('#/definitions'),
'properties': {},
'required': required or (),
'type': 'object'}
for param in params:
schema['properties'][param] = {
'$ref': '#/definitions/{}'.format(param)}
return schema | python | def _create_request_schema(self, params, required):
"""Create a JSON schema for a request.
:param list params: A list of keys specifying which definitions from
the base schema should be allowed in the request.
:param list required: A subset of the params that the requester must
specify in the request.
:returns: a JSON schema dict
"""
# We allow additional properties because the data this will validate
# may also include kwargs passed by decorators on the handler method.
schema = {'additionalProperties': True,
'definitions': self.resolve('#/definitions'),
'properties': {},
'required': required or (),
'type': 'object'}
for param in params:
schema['properties'][param] = {
'$ref': '#/definitions/{}'.format(param)}
return schema | [
"def",
"_create_request_schema",
"(",
"self",
",",
"params",
",",
"required",
")",
":",
"# We allow additional properties because the data this will validate",
"# may also include kwargs passed by decorators on the handler method.",
"schema",
"=",
"{",
"'additionalProperties'",
":",
... | Create a JSON schema for a request.
:param list params: A list of keys specifying which definitions from
the base schema should be allowed in the request.
:param list required: A subset of the params that the requester must
specify in the request.
:returns: a JSON schema dict | [
"Create",
"a",
"JSON",
"schema",
"for",
"a",
"request",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/resource.py#L116-L135 | train | 50,102 |
upsight/doctor | examples/flask/app.py | update_note | def update_note(note_id: NoteId, body: Body=None, done: Done=None) -> Note:
"""Update an existing note."""
if note_id != 1:
raise NotFoundError('Note does not exist')
new_note = note.copy()
if body is not None:
new_note['body'] = body
if done is not None:
new_note['done'] = done
return new_note | python | def update_note(note_id: NoteId, body: Body=None, done: Done=None) -> Note:
"""Update an existing note."""
if note_id != 1:
raise NotFoundError('Note does not exist')
new_note = note.copy()
if body is not None:
new_note['body'] = body
if done is not None:
new_note['done'] = done
return new_note | [
"def",
"update_note",
"(",
"note_id",
":",
"NoteId",
",",
"body",
":",
"Body",
"=",
"None",
",",
"done",
":",
"Done",
"=",
"None",
")",
"->",
"Note",
":",
"if",
"note_id",
"!=",
"1",
":",
"raise",
"NotFoundError",
"(",
"'Note does not exist'",
")",
"ne... | Update an existing note. | [
"Update",
"an",
"existing",
"note",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/examples/flask/app.py#L71-L80 | train | 50,103 |
Workiva/furious | furious/batcher.py | Message.to_task | def to_task(self):
"""Return a task object representing this message."""
from google.appengine.api.taskqueue import Task
task_args = self.get_task_args().copy()
payload = None
if 'payload' in task_args:
payload = task_args.pop('payload')
kwargs = {
'method': METHOD_TYPE,
'payload': json.dumps(payload)
}
kwargs.update(task_args)
return Task(**kwargs) | python | def to_task(self):
"""Return a task object representing this message."""
from google.appengine.api.taskqueue import Task
task_args = self.get_task_args().copy()
payload = None
if 'payload' in task_args:
payload = task_args.pop('payload')
kwargs = {
'method': METHOD_TYPE,
'payload': json.dumps(payload)
}
kwargs.update(task_args)
return Task(**kwargs) | [
"def",
"to_task",
"(",
"self",
")",
":",
"from",
"google",
".",
"appengine",
".",
"api",
".",
"taskqueue",
"import",
"Task",
"task_args",
"=",
"self",
".",
"get_task_args",
"(",
")",
".",
"copy",
"(",
")",
"payload",
"=",
"None",
"if",
"'payload'",
"in... | Return a task object representing this message. | [
"Return",
"a",
"task",
"object",
"representing",
"this",
"message",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L58-L75 | train | 50,104 |
Workiva/furious | furious/batcher.py | Message.insert | def insert(self):
"""Insert the pull task into the requested queue, 'default' if non
given.
"""
from google.appengine.api.taskqueue import Queue
task = self.to_task()
Queue(name=self.get_queue()).add(task) | python | def insert(self):
"""Insert the pull task into the requested queue, 'default' if non
given.
"""
from google.appengine.api.taskqueue import Queue
task = self.to_task()
Queue(name=self.get_queue()).add(task) | [
"def",
"insert",
"(",
"self",
")",
":",
"from",
"google",
".",
"appengine",
".",
"api",
".",
"taskqueue",
"import",
"Queue",
"task",
"=",
"self",
".",
"to_task",
"(",
")",
"Queue",
"(",
"name",
"=",
"self",
".",
"get_queue",
"(",
")",
")",
".",
"ad... | Insert the pull task into the requested queue, 'default' if non
given. | [
"Insert",
"the",
"pull",
"task",
"into",
"the",
"requested",
"queue",
"default",
"if",
"non",
"given",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L77-L85 | train | 50,105 |
Workiva/furious | furious/batcher.py | Message.to_dict | def to_dict(self):
"""Return this message as a dict suitable for json encoding."""
import copy
options = copy.deepcopy(self._options)
# JSON don't like datetimes.
eta = options.get('task_args', {}).get('eta')
if eta:
options['task_args']['eta'] = time.mktime(eta.timetuple())
return options | python | def to_dict(self):
"""Return this message as a dict suitable for json encoding."""
import copy
options = copy.deepcopy(self._options)
# JSON don't like datetimes.
eta = options.get('task_args', {}).get('eta')
if eta:
options['task_args']['eta'] = time.mktime(eta.timetuple())
return options | [
"def",
"to_dict",
"(",
"self",
")",
":",
"import",
"copy",
"options",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_options",
")",
"# JSON don't like datetimes.",
"eta",
"=",
"options",
".",
"get",
"(",
"'task_args'",
",",
"{",
"}",
")",
".",
"get",
... | Return this message as a dict suitable for json encoding. | [
"Return",
"this",
"message",
"as",
"a",
"dict",
"suitable",
"for",
"json",
"encoding",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L87-L98 | train | 50,106 |
Workiva/furious | furious/batcher.py | Message._get_id | def _get_id(self):
"""If this message has no id, generate one."""
id = self._options.get('id')
if id:
return id
id = uuid.uuid4().hex
self.update_options(id=id)
return id | python | def _get_id(self):
"""If this message has no id, generate one."""
id = self._options.get('id')
if id:
return id
id = uuid.uuid4().hex
self.update_options(id=id)
return id | [
"def",
"_get_id",
"(",
"self",
")",
":",
"id",
"=",
"self",
".",
"_options",
".",
"get",
"(",
"'id'",
")",
"if",
"id",
":",
"return",
"id",
"id",
"=",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
"self",
".",
"update_options",
"(",
"id",
"=",
"i... | If this message has no id, generate one. | [
"If",
"this",
"message",
"has",
"no",
"id",
"generate",
"one",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L100-L108 | train | 50,107 |
Workiva/furious | furious/batcher.py | Message.from_dict | def from_dict(cls, message):
"""Return an message from a dict output by Async.to_dict."""
message_options = message.copy()
# JSON don't like datetimes.
eta = message_options.get('task_args', {}).get('eta')
if eta:
from datetime import datetime
message_options['task_args']['eta'] = datetime.fromtimestamp(eta)
return Message(**message_options) | python | def from_dict(cls, message):
"""Return an message from a dict output by Async.to_dict."""
message_options = message.copy()
# JSON don't like datetimes.
eta = message_options.get('task_args', {}).get('eta')
if eta:
from datetime import datetime
message_options['task_args']['eta'] = datetime.fromtimestamp(eta)
return Message(**message_options) | [
"def",
"from_dict",
"(",
"cls",
",",
"message",
")",
":",
"message_options",
"=",
"message",
".",
"copy",
"(",
")",
"# JSON don't like datetimes.",
"eta",
"=",
"message_options",
".",
"get",
"(",
"'task_args'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'eta'",... | Return an message from a dict output by Async.to_dict. | [
"Return",
"an",
"message",
"from",
"a",
"dict",
"output",
"by",
"Async",
".",
"to_dict",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L116-L128 | train | 50,108 |
Workiva/furious | furious/batcher.py | MessageProcessor.to_task | def to_task(self):
"""Return a task object representing this MessageProcessor job."""
task_args = self.get_task_args()
# check for name in task args
name = task_args.get('name', MESSAGE_PROCESSOR_NAME)
# if the countdown isn't in the task_args set it to the frequency
if not 'countdown' in task_args:
task_args['countdown'] = self.frequency
task_args['name'] = "%s-%s-%s-%s" % (
name, self.tag, self.current_batch, self.time_throttle)
self.update_options(task_args=task_args)
return super(MessageProcessor, self).to_task() | python | def to_task(self):
"""Return a task object representing this MessageProcessor job."""
task_args = self.get_task_args()
# check for name in task args
name = task_args.get('name', MESSAGE_PROCESSOR_NAME)
# if the countdown isn't in the task_args set it to the frequency
if not 'countdown' in task_args:
task_args['countdown'] = self.frequency
task_args['name'] = "%s-%s-%s-%s" % (
name, self.tag, self.current_batch, self.time_throttle)
self.update_options(task_args=task_args)
return super(MessageProcessor, self).to_task() | [
"def",
"to_task",
"(",
"self",
")",
":",
"task_args",
"=",
"self",
".",
"get_task_args",
"(",
")",
"# check for name in task args",
"name",
"=",
"task_args",
".",
"get",
"(",
"'name'",
",",
"MESSAGE_PROCESSOR_NAME",
")",
"# if the countdown isn't in the task_args set ... | Return a task object representing this MessageProcessor job. | [
"Return",
"a",
"task",
"object",
"representing",
"this",
"MessageProcessor",
"job",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L141-L157 | train | 50,109 |
Workiva/furious | furious/batcher.py | MessageProcessor.current_batch | def current_batch(self):
"""Return the batch id for the tag.
:return: :class: `int` current batch id
"""
current_batch = memcache.get(self.group_key)
if not current_batch:
memcache.add(self.group_key, 1)
current_batch = 1
return current_batch | python | def current_batch(self):
"""Return the batch id for the tag.
:return: :class: `int` current batch id
"""
current_batch = memcache.get(self.group_key)
if not current_batch:
memcache.add(self.group_key, 1)
current_batch = 1
return current_batch | [
"def",
"current_batch",
"(",
"self",
")",
":",
"current_batch",
"=",
"memcache",
".",
"get",
"(",
"self",
".",
"group_key",
")",
"if",
"not",
"current_batch",
":",
"memcache",
".",
"add",
"(",
"self",
".",
"group_key",
",",
"1",
")",
"current_batch",
"="... | Return the batch id for the tag.
:return: :class: `int` current batch id | [
"Return",
"the",
"batch",
"id",
"for",
"the",
"tag",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L165-L176 | train | 50,110 |
Workiva/furious | furious/batcher.py | MessageIterator.fetch_messages | def fetch_messages(self):
"""Fetch messages from the specified pull-queue.
This should only be called a single time by a given MessageIterator
object. If the MessageIterator is iterated over again, it should
return the originally leased messages.
"""
if self._fetched:
return
start = time.time()
loaded_messages = self.queue.lease_tasks_by_tag(
self.duration, self.size, tag=self.tag, deadline=self.deadline)
# If we are within 0.1 sec of our deadline and no messages were
# returned, then we are hitting queue contention issues and this
# should be a DeadlineExceederError.
# TODO: investigate other ways around this, perhaps async leases, etc.
if (not loaded_messages and
round(time.time() - start, 1) >= self.deadline - 0.1):
raise DeadlineExceededError()
self._messages.extend(loaded_messages)
self._fetched = True
logging.debug("Calling fetch messages with %s:%s:%s:%s:%s:%s" % (
len(self._messages), len(loaded_messages),
len(self._processed_messages), self.duration, self.size, self.tag)) | python | def fetch_messages(self):
"""Fetch messages from the specified pull-queue.
This should only be called a single time by a given MessageIterator
object. If the MessageIterator is iterated over again, it should
return the originally leased messages.
"""
if self._fetched:
return
start = time.time()
loaded_messages = self.queue.lease_tasks_by_tag(
self.duration, self.size, tag=self.tag, deadline=self.deadline)
# If we are within 0.1 sec of our deadline and no messages were
# returned, then we are hitting queue contention issues and this
# should be a DeadlineExceederError.
# TODO: investigate other ways around this, perhaps async leases, etc.
if (not loaded_messages and
round(time.time() - start, 1) >= self.deadline - 0.1):
raise DeadlineExceededError()
self._messages.extend(loaded_messages)
self._fetched = True
logging.debug("Calling fetch messages with %s:%s:%s:%s:%s:%s" % (
len(self._messages), len(loaded_messages),
len(self._processed_messages), self.duration, self.size, self.tag)) | [
"def",
"fetch_messages",
"(",
"self",
")",
":",
"if",
"self",
".",
"_fetched",
":",
"return",
"start",
"=",
"time",
".",
"time",
"(",
")",
"loaded_messages",
"=",
"self",
".",
"queue",
".",
"lease_tasks_by_tag",
"(",
"self",
".",
"duration",
",",
"self",... | Fetch messages from the specified pull-queue.
This should only be called a single time by a given MessageIterator
object. If the MessageIterator is iterated over again, it should
return the originally leased messages. | [
"Fetch",
"messages",
"from",
"the",
"specified",
"pull",
"-",
"queue",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L228-L257 | train | 50,111 |
Workiva/furious | furious/batcher.py | MessageIterator.next | def next(self):
"""Get the next batch of messages from the previously fetched messages.
If there's no more messages, check if we should auto-delete the
messages and raise StopIteration.
"""
if not self._messages:
if self.auto_delete:
self.delete_messages()
raise StopIteration
message = self._messages.pop(0)
self._processed_messages.append(message)
return json.loads(message.payload) | python | def next(self):
"""Get the next batch of messages from the previously fetched messages.
If there's no more messages, check if we should auto-delete the
messages and raise StopIteration.
"""
if not self._messages:
if self.auto_delete:
self.delete_messages()
raise StopIteration
message = self._messages.pop(0)
self._processed_messages.append(message)
return json.loads(message.payload) | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_messages",
":",
"if",
"self",
".",
"auto_delete",
":",
"self",
".",
"delete_messages",
"(",
")",
"raise",
"StopIteration",
"message",
"=",
"self",
".",
"_messages",
".",
"pop",
"(",
"0",... | Get the next batch of messages from the previously fetched messages.
If there's no more messages, check if we should auto-delete the
messages and raise StopIteration. | [
"Get",
"the",
"next",
"batch",
"of",
"messages",
"from",
"the",
"previously",
"fetched",
"messages",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L280-L293 | train | 50,112 |
Workiva/furious | furious/batcher.py | MessageIterator.delete_messages | def delete_messages(self, only_processed=True):
"""Delete the messages previously leased.
Unless otherwise directed, only the messages iterated over will be
deleted.
"""
messages = self._processed_messages
if not only_processed:
messages += self._messages
if messages:
try:
self.queue.delete_tasks(messages)
except Exception:
logging.exception("Error deleting messages")
raise | python | def delete_messages(self, only_processed=True):
"""Delete the messages previously leased.
Unless otherwise directed, only the messages iterated over will be
deleted.
"""
messages = self._processed_messages
if not only_processed:
messages += self._messages
if messages:
try:
self.queue.delete_tasks(messages)
except Exception:
logging.exception("Error deleting messages")
raise | [
"def",
"delete_messages",
"(",
"self",
",",
"only_processed",
"=",
"True",
")",
":",
"messages",
"=",
"self",
".",
"_processed_messages",
"if",
"not",
"only_processed",
":",
"messages",
"+=",
"self",
".",
"_messages",
"if",
"messages",
":",
"try",
":",
"self... | Delete the messages previously leased.
Unless otherwise directed, only the messages iterated over will be
deleted. | [
"Delete",
"the",
"messages",
"previously",
"leased",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L295-L310 | train | 50,113 |
upsight/doctor | doctor/utils/__init__.py | copy_func | def copy_func(func: Callable) -> Callable:
"""Returns a copy of a function.
:param func: The function to copy.
:returns: The copied function.
"""
copied = types.FunctionType(
func.__code__, func.__globals__, name=func.__name__,
argdefs=func.__defaults__, closure=func.__closure__)
copied = functools.update_wrapper(copied, func)
copied.__kwdefaults__ = func.__kwdefaults__
return copied | python | def copy_func(func: Callable) -> Callable:
"""Returns a copy of a function.
:param func: The function to copy.
:returns: The copied function.
"""
copied = types.FunctionType(
func.__code__, func.__globals__, name=func.__name__,
argdefs=func.__defaults__, closure=func.__closure__)
copied = functools.update_wrapper(copied, func)
copied.__kwdefaults__ = func.__kwdefaults__
return copied | [
"def",
"copy_func",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"copied",
"=",
"types",
".",
"FunctionType",
"(",
"func",
".",
"__code__",
",",
"func",
".",
"__globals__",
",",
"name",
"=",
"func",
".",
"__name__",
",",
"argdefs",
"=",
"f... | Returns a copy of a function.
:param func: The function to copy.
:returns: The copied function. | [
"Returns",
"a",
"copy",
"of",
"a",
"function",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/utils/__init__.py#L25-L36 | train | 50,114 |
upsight/doctor | doctor/utils/__init__.py | get_params_from_func | def get_params_from_func(func: Callable, signature: Signature=None) -> Params:
"""Gets all parameters from a function signature.
:param func: The function to inspect.
:param signature: An inspect.Signature instance.
:returns: A named tuple containing information about all, optional,
required and logic function parameters.
"""
if signature is None:
# Check if the function already parsed the signature
signature = getattr(func, '_doctor_signature', None)
# Otherwise parse the signature
if signature is None:
signature = inspect.signature(func)
# Check if a `req_obj_type` was provided for the function. If so we should
# derrive the parameters from that defined type instead of the signature.
if getattr(func, '_doctor_req_obj_type', None):
annotation = func._doctor_req_obj_type
all_params = list(annotation.properties.keys())
required = annotation.required
optional = list(set(all_params) - set(required))
else:
# Required is a positional argument with no defualt value and it's
# annotation must sub class SuperType. This is so we don't try to
# require parameters passed to a logic function by a decorator that are
# not part of a request.
required = [key for key, p in signature.parameters.items()
if p.default == p.empty and
issubclass(p.annotation, SuperType)]
optional = [key for key, p in signature.parameters.items()
if p.default != p.empty]
all_params = [key for key in signature.parameters.keys()]
# Logic params are all parameters that are part of the logic signature.
logic_params = copy(all_params)
return Params(all_params, required, optional, logic_params) | python | def get_params_from_func(func: Callable, signature: Signature=None) -> Params:
"""Gets all parameters from a function signature.
:param func: The function to inspect.
:param signature: An inspect.Signature instance.
:returns: A named tuple containing information about all, optional,
required and logic function parameters.
"""
if signature is None:
# Check if the function already parsed the signature
signature = getattr(func, '_doctor_signature', None)
# Otherwise parse the signature
if signature is None:
signature = inspect.signature(func)
# Check if a `req_obj_type` was provided for the function. If so we should
# derrive the parameters from that defined type instead of the signature.
if getattr(func, '_doctor_req_obj_type', None):
annotation = func._doctor_req_obj_type
all_params = list(annotation.properties.keys())
required = annotation.required
optional = list(set(all_params) - set(required))
else:
# Required is a positional argument with no defualt value and it's
# annotation must sub class SuperType. This is so we don't try to
# require parameters passed to a logic function by a decorator that are
# not part of a request.
required = [key for key, p in signature.parameters.items()
if p.default == p.empty and
issubclass(p.annotation, SuperType)]
optional = [key for key, p in signature.parameters.items()
if p.default != p.empty]
all_params = [key for key in signature.parameters.keys()]
# Logic params are all parameters that are part of the logic signature.
logic_params = copy(all_params)
return Params(all_params, required, optional, logic_params) | [
"def",
"get_params_from_func",
"(",
"func",
":",
"Callable",
",",
"signature",
":",
"Signature",
"=",
"None",
")",
"->",
"Params",
":",
"if",
"signature",
"is",
"None",
":",
"# Check if the function already parsed the signature",
"signature",
"=",
"getattr",
"(",
... | Gets all parameters from a function signature.
:param func: The function to inspect.
:param signature: An inspect.Signature instance.
:returns: A named tuple containing information about all, optional,
required and logic function parameters. | [
"Gets",
"all",
"parameters",
"from",
"a",
"function",
"signature",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/utils/__init__.py#L88-L124 | train | 50,115 |
upsight/doctor | doctor/utils/__init__.py | add_param_annotations | def add_param_annotations(
logic: Callable, params: List[RequestParamAnnotation]) -> Callable:
"""Adds parameter annotations to a logic function.
This adds additional required and/or optional parameters to the logic
function that are not part of it's signature. It's intended to be used
by decorators decorating logic functions or middleware.
:param logic: The logic function to add the parameter annotations to.
:param params: The list of RequestParamAnnotations to add to the logic func.
:returns: The logic func with updated parameter annotations.
"""
# If we've already added param annotations to this function get the
# values from the logic, otherwise we need to inspect it.
if hasattr(logic, '_doctor_signature'):
sig = logic._doctor_signature
doctor_params = logic._doctor_params
else:
sig = inspect.signature(logic)
doctor_params = get_params_from_func(logic, sig)
prev_parameters = {name: param for name, param in sig.parameters.items()}
new_params = []
for param in params:
# If the parameter already exists in the function signature, log
# a warning and skip it.
if param.name in prev_parameters:
logging.warning('Not adding %s to signature of %s, function '
'already has that parameter in its signature.',
param.name, logic.__name__)
continue
doctor_params.all.append(param.name)
default = None
if param.required:
default = Parameter.empty
doctor_params.required.append(param.name)
else:
doctor_params.optional.append(param.name)
new_params.append(
Parameter(param.name, Parameter.KEYWORD_ONLY, default=default,
annotation=param.annotation))
new_sig = sig.replace(
parameters=list(prev_parameters.values()) + new_params)
logic._doctor_signature = new_sig
logic._doctor_params = doctor_params
return logic | python | def add_param_annotations(
logic: Callable, params: List[RequestParamAnnotation]) -> Callable:
"""Adds parameter annotations to a logic function.
This adds additional required and/or optional parameters to the logic
function that are not part of it's signature. It's intended to be used
by decorators decorating logic functions or middleware.
:param logic: The logic function to add the parameter annotations to.
:param params: The list of RequestParamAnnotations to add to the logic func.
:returns: The logic func with updated parameter annotations.
"""
# If we've already added param annotations to this function get the
# values from the logic, otherwise we need to inspect it.
if hasattr(logic, '_doctor_signature'):
sig = logic._doctor_signature
doctor_params = logic._doctor_params
else:
sig = inspect.signature(logic)
doctor_params = get_params_from_func(logic, sig)
prev_parameters = {name: param for name, param in sig.parameters.items()}
new_params = []
for param in params:
# If the parameter already exists in the function signature, log
# a warning and skip it.
if param.name in prev_parameters:
logging.warning('Not adding %s to signature of %s, function '
'already has that parameter in its signature.',
param.name, logic.__name__)
continue
doctor_params.all.append(param.name)
default = None
if param.required:
default = Parameter.empty
doctor_params.required.append(param.name)
else:
doctor_params.optional.append(param.name)
new_params.append(
Parameter(param.name, Parameter.KEYWORD_ONLY, default=default,
annotation=param.annotation))
new_sig = sig.replace(
parameters=list(prev_parameters.values()) + new_params)
logic._doctor_signature = new_sig
logic._doctor_params = doctor_params
return logic | [
"def",
"add_param_annotations",
"(",
"logic",
":",
"Callable",
",",
"params",
":",
"List",
"[",
"RequestParamAnnotation",
"]",
")",
"->",
"Callable",
":",
"# If we've already added param annotations to this function get the",
"# values from the logic, otherwise we need to inspect... | Adds parameter annotations to a logic function.
This adds additional required and/or optional parameters to the logic
function that are not part of it's signature. It's intended to be used
by decorators decorating logic functions or middleware.
:param logic: The logic function to add the parameter annotations to.
:param params: The list of RequestParamAnnotations to add to the logic func.
:returns: The logic func with updated parameter annotations. | [
"Adds",
"parameter",
"annotations",
"to",
"a",
"logic",
"function",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/utils/__init__.py#L127-L173 | train | 50,116 |
upsight/doctor | doctor/utils/__init__.py | get_module_attr | def get_module_attr(module_filename, module_attr, namespace=None):
"""Get an attribute from a module.
This uses exec to load the module with a private namespace, and then
plucks and returns the given attribute from that module's namespace.
Note that, while this method doesn't have any explicit unit tests, it is
tested implicitly by the doctor's own documentation. The Sphinx
build process will fail to generate docs if this does not work.
:param str module_filename: Path to the module to execute (e.g.
"../src/app.py").
:param str module_attr: Attribute to pluck from the module's namespace.
(e.g. "app").
:param dict namespace: Optional namespace. If one is not passed, an empty
dict will be used instead. Note that this function mutates the passed
namespace, so you can inspect a passed dict after calling this method
to see how the module changed it.
:returns: The attribute from the module.
:raises KeyError: if the module doesn't have the given attribute.
"""
if namespace is None:
namespace = {}
module_filename = os.path.abspath(module_filename)
namespace['__file__'] = module_filename
module_dir = os.path.dirname(module_filename)
old_cwd = os.getcwd()
old_sys_path = sys.path[:]
try:
os.chdir(module_dir)
sys.path.append(module_dir)
with open(module_filename, 'r') as mf:
exec(compile(mf.read(), module_filename, 'exec'), namespace)
return namespace[module_attr]
finally:
os.chdir(old_cwd)
sys.path = old_sys_path | python | def get_module_attr(module_filename, module_attr, namespace=None):
"""Get an attribute from a module.
This uses exec to load the module with a private namespace, and then
plucks and returns the given attribute from that module's namespace.
Note that, while this method doesn't have any explicit unit tests, it is
tested implicitly by the doctor's own documentation. The Sphinx
build process will fail to generate docs if this does not work.
:param str module_filename: Path to the module to execute (e.g.
"../src/app.py").
:param str module_attr: Attribute to pluck from the module's namespace.
(e.g. "app").
:param dict namespace: Optional namespace. If one is not passed, an empty
dict will be used instead. Note that this function mutates the passed
namespace, so you can inspect a passed dict after calling this method
to see how the module changed it.
:returns: The attribute from the module.
:raises KeyError: if the module doesn't have the given attribute.
"""
if namespace is None:
namespace = {}
module_filename = os.path.abspath(module_filename)
namespace['__file__'] = module_filename
module_dir = os.path.dirname(module_filename)
old_cwd = os.getcwd()
old_sys_path = sys.path[:]
try:
os.chdir(module_dir)
sys.path.append(module_dir)
with open(module_filename, 'r') as mf:
exec(compile(mf.read(), module_filename, 'exec'), namespace)
return namespace[module_attr]
finally:
os.chdir(old_cwd)
sys.path = old_sys_path | [
"def",
"get_module_attr",
"(",
"module_filename",
",",
"module_attr",
",",
"namespace",
"=",
"None",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"namespace",
"=",
"{",
"}",
"module_filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"module_filename"... | Get an attribute from a module.
This uses exec to load the module with a private namespace, and then
plucks and returns the given attribute from that module's namespace.
Note that, while this method doesn't have any explicit unit tests, it is
tested implicitly by the doctor's own documentation. The Sphinx
build process will fail to generate docs if this does not work.
:param str module_filename: Path to the module to execute (e.g.
"../src/app.py").
:param str module_attr: Attribute to pluck from the module's namespace.
(e.g. "app").
:param dict namespace: Optional namespace. If one is not passed, an empty
dict will be used instead. Note that this function mutates the passed
namespace, so you can inspect a passed dict after calling this method
to see how the module changed it.
:returns: The attribute from the module.
:raises KeyError: if the module doesn't have the given attribute. | [
"Get",
"an",
"attribute",
"from",
"a",
"module",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/utils/__init__.py#L176-L212 | train | 50,117 |
upsight/doctor | doctor/utils/__init__.py | get_description_lines | def get_description_lines(docstring):
"""Extract the description from the given docstring.
This grabs everything up to the first occurrence of something that looks
like a parameter description. The docstring will be dedented and cleaned
up using the standard Sphinx methods.
:param str docstring: The source docstring.
:returns: list
"""
if prepare_docstring is None:
raise ImportError('sphinx must be installed to use this function.')
if not isinstance(docstring, str):
return []
lines = []
for line in prepare_docstring(docstring):
if DESCRIPTION_END_RE.match(line):
break
lines.append(line)
if lines and lines[-1] != '':
lines.append('')
return lines | python | def get_description_lines(docstring):
"""Extract the description from the given docstring.
This grabs everything up to the first occurrence of something that looks
like a parameter description. The docstring will be dedented and cleaned
up using the standard Sphinx methods.
:param str docstring: The source docstring.
:returns: list
"""
if prepare_docstring is None:
raise ImportError('sphinx must be installed to use this function.')
if not isinstance(docstring, str):
return []
lines = []
for line in prepare_docstring(docstring):
if DESCRIPTION_END_RE.match(line):
break
lines.append(line)
if lines and lines[-1] != '':
lines.append('')
return lines | [
"def",
"get_description_lines",
"(",
"docstring",
")",
":",
"if",
"prepare_docstring",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"'sphinx must be installed to use this function.'",
")",
"if",
"not",
"isinstance",
"(",
"docstring",
",",
"str",
")",
":",
"return... | Extract the description from the given docstring.
This grabs everything up to the first occurrence of something that looks
like a parameter description. The docstring will be dedented and cleaned
up using the standard Sphinx methods.
:param str docstring: The source docstring.
:returns: list | [
"Extract",
"the",
"description",
"from",
"the",
"given",
"docstring",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/utils/__init__.py#L215-L237 | train | 50,118 |
upsight/doctor | doctor/utils/__init__.py | get_valid_class_name | def get_valid_class_name(s: str) -> str:
"""Return the given string converted so that it can be used for a class name
Remove leading and trailing spaces; removes spaces and capitalizes each
word; and remove anything that is not alphanumeric. Returns a pep8
compatible class name.
:param s: The string to convert.
:returns: The updated string.
"""
s = str(s).strip()
s = ''.join([w.title() for w in re.split(r'\W+|_', s)])
return re.sub(r'[^\w|_]', '', s) | python | def get_valid_class_name(s: str) -> str:
"""Return the given string converted so that it can be used for a class name
Remove leading and trailing spaces; removes spaces and capitalizes each
word; and remove anything that is not alphanumeric. Returns a pep8
compatible class name.
:param s: The string to convert.
:returns: The updated string.
"""
s = str(s).strip()
s = ''.join([w.title() for w in re.split(r'\W+|_', s)])
return re.sub(r'[^\w|_]', '', s) | [
"def",
"get_valid_class_name",
"(",
"s",
":",
"str",
")",
"->",
"str",
":",
"s",
"=",
"str",
"(",
"s",
")",
".",
"strip",
"(",
")",
"s",
"=",
"''",
".",
"join",
"(",
"[",
"w",
".",
"title",
"(",
")",
"for",
"w",
"in",
"re",
".",
"split",
"(... | Return the given string converted so that it can be used for a class name
Remove leading and trailing spaces; removes spaces and capitalizes each
word; and remove anything that is not alphanumeric. Returns a pep8
compatible class name.
:param s: The string to convert.
:returns: The updated string. | [
"Return",
"the",
"given",
"string",
"converted",
"so",
"that",
"it",
"can",
"be",
"used",
"for",
"a",
"class",
"name"
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/utils/__init__.py#L240-L252 | train | 50,119 |
Workiva/furious | furious/context/_execution.py | execution_context_from_async | def execution_context_from_async(async):
"""Instantiate a new _ExecutionContext and store a reference to it in the
global async context to make later retrieval easier.
"""
local_context = _local.get_local_context()
if local_context._executing_async_context:
raise errors.ContextExistsError
execution_context = _ExecutionContext(async)
local_context._executing_async_context = execution_context
return execution_context | python | def execution_context_from_async(async):
"""Instantiate a new _ExecutionContext and store a reference to it in the
global async context to make later retrieval easier.
"""
local_context = _local.get_local_context()
if local_context._executing_async_context:
raise errors.ContextExistsError
execution_context = _ExecutionContext(async)
local_context._executing_async_context = execution_context
return execution_context | [
"def",
"execution_context_from_async",
"(",
"async",
")",
":",
"local_context",
"=",
"_local",
".",
"get_local_context",
"(",
")",
"if",
"local_context",
".",
"_executing_async_context",
":",
"raise",
"errors",
".",
"ContextExistsError",
"execution_context",
"=",
"_Ex... | Instantiate a new _ExecutionContext and store a reference to it in the
global async context to make later retrieval easier. | [
"Instantiate",
"a",
"new",
"_ExecutionContext",
"and",
"store",
"a",
"reference",
"to",
"it",
"in",
"the",
"global",
"async",
"context",
"to",
"make",
"later",
"retrieval",
"easier",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/_execution.py#L40-L51 | train | 50,120 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/cli_handler_impl.py | CliHandlerImpl.get_cli_service | def get_cli_service(self, command_mode):
"""Use cli.get_session to open CLI connection and switch into required mode
:param CommandMode command_mode: operation mode, can be default_mode/enable_mode/config_mode/etc.
:return: created session in provided mode
:rtype: CommandModeContextManager
"""
return self._cli.get_session(self._new_sessions(), command_mode, self._logger) | python | def get_cli_service(self, command_mode):
"""Use cli.get_session to open CLI connection and switch into required mode
:param CommandMode command_mode: operation mode, can be default_mode/enable_mode/config_mode/etc.
:return: created session in provided mode
:rtype: CommandModeContextManager
"""
return self._cli.get_session(self._new_sessions(), command_mode, self._logger) | [
"def",
"get_cli_service",
"(",
"self",
",",
"command_mode",
")",
":",
"return",
"self",
".",
"_cli",
".",
"get_session",
"(",
"self",
".",
"_new_sessions",
"(",
")",
",",
"command_mode",
",",
"self",
".",
"_logger",
")"
] | Use cli.get_session to open CLI connection and switch into required mode
:param CommandMode command_mode: operation mode, can be default_mode/enable_mode/config_mode/etc.
:return: created session in provided mode
:rtype: CommandModeContextManager | [
"Use",
"cli",
".",
"get_session",
"to",
"open",
"CLI",
"connection",
"and",
"switch",
"into",
"required",
"mode"
] | 009aab33edb30035b52fe10dbb91db61c95ba4d9 | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/cli_handler_impl.py#L111-L118 | train | 50,121 |
aiidalab/aiidalab-widgets-base | aiidalab_widgets_base/crystal_sim_crystal.py | check_crystal_equivalence | def check_crystal_equivalence(crystal_a, crystal_b):
"""Function that identifies whether two crystals are equivalent"""
# getting symmetry datasets for both crystals
cryst_a = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_a), symprec=1e-5, angle_tolerance=-1.0, hall_number=0)
cryst_b = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_b), symprec=1e-5, angle_tolerance=-1.0, hall_number=0)
samecell = np.allclose(cryst_a['std_lattice'], cryst_b['std_lattice'], atol=1e-5)
samenatoms = len(cryst_a['std_positions']) == len(cryst_b['std_positions'])
samespg = cryst_a['number'] == cryst_b['number']
def test_rotations_translations(cryst_a, cryst_b, repeat):
cell = cryst_a['std_lattice']
pristine = crystal('Mg', [(0, 0., 0.)],
spacegroup=int(cryst_a['number']),
cellpar=[cell[0]/repeat[0], cell[1]/repeat[1], cell[2]/repeat[2]]).repeat(repeat)
sym_set_p = spglib.get_symmetry_dataset(ase_to_spgcell(pristine), symprec=1e-5,
angle_tolerance=-1.0, hall_number=0)
for _,trans in enumerate(zip(sym_set_p['rotations'], sym_set_p['translations'])):
pnew=(np.matmul(trans[0],cryst_a['std_positions'].T).T + trans[1]) % 1.0
fulln = np.concatenate([cryst_a['std_types'][:, None], pnew], axis=1)
fullb = np.concatenate([cryst_b['std_types'][:, None], cryst_b['std_positions']], axis=1)
sorted_n = np.array(sorted([ list(row) for row in list(fulln) ]))
sorted_b = np.array(sorted([ list(row) for row in list(fullb) ]))
if np.allclose(sorted_n, sorted_b, atol=1e-5):
return True
return False
if samecell and samenatoms and samespg:
cell = cryst_a['std_lattice']
# we assume there are no crystals with a lattice parameter smaller than 2 A
rng1 = range(1, int(norm(cell[0])/2.))
rng2 = range(1, int(norm(cell[1])/2.))
rng3 = range(1, int(norm(cell[2])/2.))
for repeat in itertools.product(rng1, rng2, rng3):
if test_rotations_translations(cryst_a, cryst_b, repeat):
return True
return False | python | def check_crystal_equivalence(crystal_a, crystal_b):
"""Function that identifies whether two crystals are equivalent"""
# getting symmetry datasets for both crystals
cryst_a = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_a), symprec=1e-5, angle_tolerance=-1.0, hall_number=0)
cryst_b = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_b), symprec=1e-5, angle_tolerance=-1.0, hall_number=0)
samecell = np.allclose(cryst_a['std_lattice'], cryst_b['std_lattice'], atol=1e-5)
samenatoms = len(cryst_a['std_positions']) == len(cryst_b['std_positions'])
samespg = cryst_a['number'] == cryst_b['number']
def test_rotations_translations(cryst_a, cryst_b, repeat):
cell = cryst_a['std_lattice']
pristine = crystal('Mg', [(0, 0., 0.)],
spacegroup=int(cryst_a['number']),
cellpar=[cell[0]/repeat[0], cell[1]/repeat[1], cell[2]/repeat[2]]).repeat(repeat)
sym_set_p = spglib.get_symmetry_dataset(ase_to_spgcell(pristine), symprec=1e-5,
angle_tolerance=-1.0, hall_number=0)
for _,trans in enumerate(zip(sym_set_p['rotations'], sym_set_p['translations'])):
pnew=(np.matmul(trans[0],cryst_a['std_positions'].T).T + trans[1]) % 1.0
fulln = np.concatenate([cryst_a['std_types'][:, None], pnew], axis=1)
fullb = np.concatenate([cryst_b['std_types'][:, None], cryst_b['std_positions']], axis=1)
sorted_n = np.array(sorted([ list(row) for row in list(fulln) ]))
sorted_b = np.array(sorted([ list(row) for row in list(fullb) ]))
if np.allclose(sorted_n, sorted_b, atol=1e-5):
return True
return False
if samecell and samenatoms and samespg:
cell = cryst_a['std_lattice']
# we assume there are no crystals with a lattice parameter smaller than 2 A
rng1 = range(1, int(norm(cell[0])/2.))
rng2 = range(1, int(norm(cell[1])/2.))
rng3 = range(1, int(norm(cell[2])/2.))
for repeat in itertools.product(rng1, rng2, rng3):
if test_rotations_translations(cryst_a, cryst_b, repeat):
return True
return False | [
"def",
"check_crystal_equivalence",
"(",
"crystal_a",
",",
"crystal_b",
")",
":",
"# getting symmetry datasets for both crystals",
"cryst_a",
"=",
"spglib",
".",
"get_symmetry_dataset",
"(",
"ase_to_spgcell",
"(",
"crystal_a",
")",
",",
"symprec",
"=",
"1e-5",
",",
"a... | Function that identifies whether two crystals are equivalent | [
"Function",
"that",
"identifies",
"whether",
"two",
"crystals",
"are",
"equivalent"
] | 291a9b159eac902aee655862322670ec1b0cd5b1 | https://github.com/aiidalab/aiidalab-widgets-base/blob/291a9b159eac902aee655862322670ec1b0cd5b1/aiidalab_widgets_base/crystal_sim_crystal.py#L15-L56 | train | 50,122 |
eumis/pyviews | pyviews/core/common.py | CoreError.add_view_info | def add_view_info(self, view_info: ViewInfo):
'''Adds view information to error message'''
try:
next(info for info in self._view_infos if info.view == view_info.view)
except StopIteration:
indent = len(self._view_infos) * '\t'
self._view_infos.append(view_info)
info = 'Line {0} in "{1}"'.format(view_info.line, view_info.view)
self.add_info(indent + 'View info', info) | python | def add_view_info(self, view_info: ViewInfo):
'''Adds view information to error message'''
try:
next(info for info in self._view_infos if info.view == view_info.view)
except StopIteration:
indent = len(self._view_infos) * '\t'
self._view_infos.append(view_info)
info = 'Line {0} in "{1}"'.format(view_info.line, view_info.view)
self.add_info(indent + 'View info', info) | [
"def",
"add_view_info",
"(",
"self",
",",
"view_info",
":",
"ViewInfo",
")",
":",
"try",
":",
"next",
"(",
"info",
"for",
"info",
"in",
"self",
".",
"_view_infos",
"if",
"info",
".",
"view",
"==",
"view_info",
".",
"view",
")",
"except",
"StopIteration",... | Adds view information to error message | [
"Adds",
"view",
"information",
"to",
"error",
"message"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/common.py#L18-L26 | train | 50,123 |
eumis/pyviews | pyviews/core/common.py | CoreError.add_cause | def add_cause(self, error: Exception):
'''Adds cause error to error message'''
self.add_info('Cause error', '{0} - {1}'.format(type(error).__name__, error)) | python | def add_cause(self, error: Exception):
'''Adds cause error to error message'''
self.add_info('Cause error', '{0} - {1}'.format(type(error).__name__, error)) | [
"def",
"add_cause",
"(",
"self",
",",
"error",
":",
"Exception",
")",
":",
"self",
".",
"add_info",
"(",
"'Cause error'",
",",
"'{0} - {1}'",
".",
"format",
"(",
"type",
"(",
"error",
")",
".",
"__name__",
",",
"error",
")",
")"
] | Adds cause error to error message | [
"Adds",
"cause",
"error",
"to",
"error",
"message"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/common.py#L38-L40 | train | 50,124 |
Workiva/furious | furious/handlers/__init__.py | _log_task_info | def _log_task_info(headers, extra_task_info=None):
"""Processes the header from task requests to log analytical data."""
ran_at = time.time()
task_eta = float(headers.get('X-Appengine-Tasketa', 0.0))
task_info = {
'retry_count': headers.get('X-Appengine-Taskretrycount', ''),
'execution_count': headers.get('X-Appengine-Taskexecutioncount', ''),
'task_eta': task_eta,
'ran': ran_at,
'gae_latency_seconds': ran_at - task_eta
}
if extra_task_info:
task_info['extra'] = extra_task_info
logging.debug('TASK-INFO: %s', json.dumps(task_info)) | python | def _log_task_info(headers, extra_task_info=None):
"""Processes the header from task requests to log analytical data."""
ran_at = time.time()
task_eta = float(headers.get('X-Appengine-Tasketa', 0.0))
task_info = {
'retry_count': headers.get('X-Appengine-Taskretrycount', ''),
'execution_count': headers.get('X-Appengine-Taskexecutioncount', ''),
'task_eta': task_eta,
'ran': ran_at,
'gae_latency_seconds': ran_at - task_eta
}
if extra_task_info:
task_info['extra'] = extra_task_info
logging.debug('TASK-INFO: %s', json.dumps(task_info)) | [
"def",
"_log_task_info",
"(",
"headers",
",",
"extra_task_info",
"=",
"None",
")",
":",
"ran_at",
"=",
"time",
".",
"time",
"(",
")",
"task_eta",
"=",
"float",
"(",
"headers",
".",
"get",
"(",
"'X-Appengine-Tasketa'",
",",
"0.0",
")",
")",
"task_info",
"... | Processes the header from task requests to log analytical data. | [
"Processes",
"the",
"header",
"from",
"task",
"requests",
"to",
"log",
"analytical",
"data",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/handlers/__init__.py#L43-L58 | train | 50,125 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/standards/sdn/configuration_attributes_structure.py | GenericSDNResource._parse_ports | def _parse_ports(self, ports):
"""Parse ports string into the list
:param str ports:
:rtype: list[tuple[str, str]]
"""
if not ports:
return []
return [tuple(port_pair.split("::")) for port_pair in ports.strip(";").split(";")] | python | def _parse_ports(self, ports):
"""Parse ports string into the list
:param str ports:
:rtype: list[tuple[str, str]]
"""
if not ports:
return []
return [tuple(port_pair.split("::")) for port_pair in ports.strip(";").split(";")] | [
"def",
"_parse_ports",
"(",
"self",
",",
"ports",
")",
":",
"if",
"not",
"ports",
":",
"return",
"[",
"]",
"return",
"[",
"tuple",
"(",
"port_pair",
".",
"split",
"(",
"\"::\"",
")",
")",
"for",
"port_pair",
"in",
"ports",
".",
"strip",
"(",
"\";\"",... | Parse ports string into the list
:param str ports:
:rtype: list[tuple[str, str]] | [
"Parse",
"ports",
"string",
"into",
"the",
"list"
] | 009aab33edb30035b52fe10dbb91db61c95ba4d9 | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/standards/sdn/configuration_attributes_structure.py#L24-L33 | train | 50,126 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/standards/sdn/configuration_attributes_structure.py | GenericSDNResource.add_trunk_ports | def add_trunk_ports(self):
"""SDN Controller enable trunk ports
:rtype: list[tuple[str, str]]
"""
ports = self.attributes.get("{}Enable Full Trunk Ports".format(self.namespace_prefix), None)
return self._parse_ports(ports=ports) | python | def add_trunk_ports(self):
"""SDN Controller enable trunk ports
:rtype: list[tuple[str, str]]
"""
ports = self.attributes.get("{}Enable Full Trunk Ports".format(self.namespace_prefix), None)
return self._parse_ports(ports=ports) | [
"def",
"add_trunk_ports",
"(",
"self",
")",
":",
"ports",
"=",
"self",
".",
"attributes",
".",
"get",
"(",
"\"{}Enable Full Trunk Ports\"",
".",
"format",
"(",
"self",
".",
"namespace_prefix",
")",
",",
"None",
")",
"return",
"self",
".",
"_parse_ports",
"("... | SDN Controller enable trunk ports
:rtype: list[tuple[str, str]] | [
"SDN",
"Controller",
"enable",
"trunk",
"ports"
] | 009aab33edb30035b52fe10dbb91db61c95ba4d9 | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/standards/sdn/configuration_attributes_structure.py#L68-L74 | train | 50,127 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/standards/sdn/configuration_attributes_structure.py | GenericSDNResource.remove_trunk_ports | def remove_trunk_ports(self):
"""SDN Controller disable trunk ports
:rtype: list[tuple[str, str]]
"""
ports = self.attributes.get("{}Disable Full Trunk Ports".format(self.namespace_prefix), None)
return self._parse_ports(ports=ports) | python | def remove_trunk_ports(self):
"""SDN Controller disable trunk ports
:rtype: list[tuple[str, str]]
"""
ports = self.attributes.get("{}Disable Full Trunk Ports".format(self.namespace_prefix), None)
return self._parse_ports(ports=ports) | [
"def",
"remove_trunk_ports",
"(",
"self",
")",
":",
"ports",
"=",
"self",
".",
"attributes",
".",
"get",
"(",
"\"{}Disable Full Trunk Ports\"",
".",
"format",
"(",
"self",
".",
"namespace_prefix",
")",
",",
"None",
")",
"return",
"self",
".",
"_parse_ports",
... | SDN Controller disable trunk ports
:rtype: list[tuple[str, str]] | [
"SDN",
"Controller",
"disable",
"trunk",
"ports"
] | 009aab33edb30035b52fe10dbb91db61c95ba4d9 | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/standards/sdn/configuration_attributes_structure.py#L77-L83 | train | 50,128 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/autoload/autoload_builder.py | AutoloadDetailsBuilder._validate_build_resource_structure | def _validate_build_resource_structure(autoload_resource):
"""Validate resource structure
:param dict autoload_resource:
:return correct autoload resource structure
:rtype: dict
"""
result = {}
for resource_prefix, resources in autoload_resource.iteritems():
max_free_index = max(map(int, resources)) + 1 or 1
for index, sub_resources in resources.iteritems():
if not index or index == -1:
index = max_free_index
max_free_index += 1
if len(sub_resources) > 1:
result["{0}{1}".format(resource_prefix, index)] = sub_resources[0]
for resource in sub_resources[1:]:
result["{0}{1}".format(resource_prefix, str(max_free_index))] = resource
max_free_index += 1
else:
result["{0}{1}".format(resource_prefix, index)] = sub_resources[0]
return result | python | def _validate_build_resource_structure(autoload_resource):
"""Validate resource structure
:param dict autoload_resource:
:return correct autoload resource structure
:rtype: dict
"""
result = {}
for resource_prefix, resources in autoload_resource.iteritems():
max_free_index = max(map(int, resources)) + 1 or 1
for index, sub_resources in resources.iteritems():
if not index or index == -1:
index = max_free_index
max_free_index += 1
if len(sub_resources) > 1:
result["{0}{1}".format(resource_prefix, index)] = sub_resources[0]
for resource in sub_resources[1:]:
result["{0}{1}".format(resource_prefix, str(max_free_index))] = resource
max_free_index += 1
else:
result["{0}{1}".format(resource_prefix, index)] = sub_resources[0]
return result | [
"def",
"_validate_build_resource_structure",
"(",
"autoload_resource",
")",
":",
"result",
"=",
"{",
"}",
"for",
"resource_prefix",
",",
"resources",
"in",
"autoload_resource",
".",
"iteritems",
"(",
")",
":",
"max_free_index",
"=",
"max",
"(",
"map",
"(",
"int"... | Validate resource structure
:param dict autoload_resource:
:return correct autoload resource structure
:rtype: dict | [
"Validate",
"resource",
"structure"
] | 009aab33edb30035b52fe10dbb91db61c95ba4d9 | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/autoload/autoload_builder.py#L23-L49 | train | 50,129 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/autoload/autoload_builder.py | AutoloadDetailsBuilder._build_autoload_details | def _build_autoload_details(self, autoload_data, relative_path=""):
""" Build autoload details
:param autoload_data: dict:
:param relative_path: str: full relative path of current autoload resource
"""
self._autoload_details.attributes.extend([AutoLoadAttribute(relative_address=relative_path,
attribute_name=attribute_name,
attribute_value=attribute_value)
for attribute_name, attribute_value in
autoload_data.attributes.iteritems()])
for resource_relative_path, resource in self._validate_build_resource_structure(autoload_data.resources).iteritems():
full_relative_path = posixpath.join(relative_path, resource_relative_path)
self._autoload_details.resources.append(AutoLoadResource(model=resource.cloudshell_model_name,
name=resource.name,
relative_address=full_relative_path,
unique_identifier=resource.unique_identifier))
self._build_autoload_details(autoload_data=resource, relative_path=full_relative_path) | python | def _build_autoload_details(self, autoload_data, relative_path=""):
""" Build autoload details
:param autoload_data: dict:
:param relative_path: str: full relative path of current autoload resource
"""
self._autoload_details.attributes.extend([AutoLoadAttribute(relative_address=relative_path,
attribute_name=attribute_name,
attribute_value=attribute_value)
for attribute_name, attribute_value in
autoload_data.attributes.iteritems()])
for resource_relative_path, resource in self._validate_build_resource_structure(autoload_data.resources).iteritems():
full_relative_path = posixpath.join(relative_path, resource_relative_path)
self._autoload_details.resources.append(AutoLoadResource(model=resource.cloudshell_model_name,
name=resource.name,
relative_address=full_relative_path,
unique_identifier=resource.unique_identifier))
self._build_autoload_details(autoload_data=resource, relative_path=full_relative_path) | [
"def",
"_build_autoload_details",
"(",
"self",
",",
"autoload_data",
",",
"relative_path",
"=",
"\"\"",
")",
":",
"self",
".",
"_autoload_details",
".",
"attributes",
".",
"extend",
"(",
"[",
"AutoLoadAttribute",
"(",
"relative_address",
"=",
"relative_path",
",",... | Build autoload details
:param autoload_data: dict:
:param relative_path: str: full relative path of current autoload resource | [
"Build",
"autoload",
"details"
] | 009aab33edb30035b52fe10dbb91db61c95ba4d9 | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/autoload/autoload_builder.py#L51-L71 | train | 50,130 |
eumis/pyviews | pyviews/core/node.py | Node.set_attr | def set_attr(self, key: str, value):
"""Sets node attribute. Can be customized by attr_setter property"""
self.attr_setter(self, key, value) | python | def set_attr(self, key: str, value):
"""Sets node attribute. Can be customized by attr_setter property"""
self.attr_setter(self, key, value) | [
"def",
"set_attr",
"(",
"self",
",",
"key",
":",
"str",
",",
"value",
")",
":",
"self",
".",
"attr_setter",
"(",
"self",
",",
"key",
",",
"value",
")"
] | Sets node attribute. Can be customized by attr_setter property | [
"Sets",
"node",
"attribute",
".",
"Can",
"be",
"customized",
"by",
"attr_setter",
"property"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/node.py#L38-L40 | train | 50,131 |
eumis/pyviews | pyviews/core/node.py | Property.new | def new(self, node: Node):
"""Creates property for node"""
return Property(self.name, self._setter, node) | python | def new(self, node: Node):
"""Creates property for node"""
return Property(self.name, self._setter, node) | [
"def",
"new",
"(",
"self",
",",
"node",
":",
"Node",
")",
":",
"return",
"Property",
"(",
"self",
".",
"name",
",",
"self",
".",
"_setter",
",",
"node",
")"
] | Creates property for node | [
"Creates",
"property",
"for",
"node"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/node.py#L125-L127 | train | 50,132 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/standards/traffic/virtual/blade/configuration_attributes_structure.py | TrafficGeneratorVBladeResource.from_context | def from_context(cls, context, shell_type=None, shell_name=None):
"""Create an instance of TrafficGeneratorVBladeResource from the given context
:param cloudshell.shell.core.driver_context.ResourceCommandContext context:
:param str shell_type: shell type
:param str shell_name: shell name
:rtype: TrafficGeneratorVChassisResource
"""
return cls(address=context.resource.address,
family=context.resource.family,
shell_type=shell_type,
shell_name=shell_name,
fullname=context.resource.fullname,
attributes=dict(context.resource.attributes),
name=context.resource.name) | python | def from_context(cls, context, shell_type=None, shell_name=None):
"""Create an instance of TrafficGeneratorVBladeResource from the given context
:param cloudshell.shell.core.driver_context.ResourceCommandContext context:
:param str shell_type: shell type
:param str shell_name: shell name
:rtype: TrafficGeneratorVChassisResource
"""
return cls(address=context.resource.address,
family=context.resource.family,
shell_type=shell_type,
shell_name=shell_name,
fullname=context.resource.fullname,
attributes=dict(context.resource.attributes),
name=context.resource.name) | [
"def",
"from_context",
"(",
"cls",
",",
"context",
",",
"shell_type",
"=",
"None",
",",
"shell_name",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"address",
"=",
"context",
".",
"resource",
".",
"address",
",",
"family",
"=",
"context",
".",
"resource",... | Create an instance of TrafficGeneratorVBladeResource from the given context
:param cloudshell.shell.core.driver_context.ResourceCommandContext context:
:param str shell_type: shell type
:param str shell_name: shell name
:rtype: TrafficGeneratorVChassisResource | [
"Create",
"an",
"instance",
"of",
"TrafficGeneratorVBladeResource",
"from",
"the",
"given",
"context"
] | 009aab33edb30035b52fe10dbb91db61c95ba4d9 | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/standards/traffic/virtual/blade/configuration_attributes_structure.py#L28-L42 | train | 50,133 |
idlesign/django-siteflags | siteflags/models.py | update_filter_dict | def update_filter_dict(d, user, status):
"""Helper. Updates filter dict for a queryset.
:param dict d:
:param User|None user:
:param int|None status:
:return:
"""
if user is not None:
if not user.id:
return None
d['user'] = user
if status is not None:
d['status'] = status | python | def update_filter_dict(d, user, status):
"""Helper. Updates filter dict for a queryset.
:param dict d:
:param User|None user:
:param int|None status:
:return:
"""
if user is not None:
if not user.id:
return None
d['user'] = user
if status is not None:
d['status'] = status | [
"def",
"update_filter_dict",
"(",
"d",
",",
"user",
",",
"status",
")",
":",
"if",
"user",
"is",
"not",
"None",
":",
"if",
"not",
"user",
".",
"id",
":",
"return",
"None",
"d",
"[",
"'user'",
"]",
"=",
"user",
"if",
"status",
"is",
"not",
"None",
... | Helper. Updates filter dict for a queryset.
:param dict d:
:param User|None user:
:param int|None status:
:return: | [
"Helper",
".",
"Updates",
"filter",
"dict",
"for",
"a",
"queryset",
"."
] | c8d1a40afb2f60d68ad6d34af3f528e76bdb7142 | https://github.com/idlesign/django-siteflags/blob/c8d1a40afb2f60d68ad6d34af3f528e76bdb7142/siteflags/models.py#L233-L246 | train | 50,134 |
idlesign/django-siteflags | siteflags/models.py | ModelWithFlag.get_flags_for_objects | def get_flags_for_objects(cls, objects_list, user=None, status=None):
"""Returns a dictionary with flag objects associated with the given model objects.
The dictionary is indexed by objects IDs.
Each dict entry contains a list of associated flag objects.
:param list, QuerySet objects_list:
:param User user:
:param int status:
:rtype: dict
"""
return get_model_class_from_string(MODEL_FLAG).get_flags_for_objects(objects_list, user=user, status=status) | python | def get_flags_for_objects(cls, objects_list, user=None, status=None):
"""Returns a dictionary with flag objects associated with the given model objects.
The dictionary is indexed by objects IDs.
Each dict entry contains a list of associated flag objects.
:param list, QuerySet objects_list:
:param User user:
:param int status:
:rtype: dict
"""
return get_model_class_from_string(MODEL_FLAG).get_flags_for_objects(objects_list, user=user, status=status) | [
"def",
"get_flags_for_objects",
"(",
"cls",
",",
"objects_list",
",",
"user",
"=",
"None",
",",
"status",
"=",
"None",
")",
":",
"return",
"get_model_class_from_string",
"(",
"MODEL_FLAG",
")",
".",
"get_flags_for_objects",
"(",
"objects_list",
",",
"user",
"=",... | Returns a dictionary with flag objects associated with the given model objects.
The dictionary is indexed by objects IDs.
Each dict entry contains a list of associated flag objects.
:param list, QuerySet objects_list:
:param User user:
:param int status:
:rtype: dict | [
"Returns",
"a",
"dictionary",
"with",
"flag",
"objects",
"associated",
"with",
"the",
"given",
"model",
"objects",
".",
"The",
"dictionary",
"is",
"indexed",
"by",
"objects",
"IDs",
".",
"Each",
"dict",
"entry",
"contains",
"a",
"list",
"of",
"associated",
"... | c8d1a40afb2f60d68ad6d34af3f528e76bdb7142 | https://github.com/idlesign/django-siteflags/blob/c8d1a40afb2f60d68ad6d34af3f528e76bdb7142/siteflags/models.py#L154-L164 | train | 50,135 |
idlesign/django-siteflags | siteflags/models.py | ModelWithFlag.get_flags | def get_flags(self, user=None, status=None):
"""Returns flags for the object optionally filtered by status.
:param User user: Optional user filter
:param int status: Optional status filter
:rtype: QuerySet
"""
filter_kwargs = {}
update_filter_dict(filter_kwargs, user, status)
return self.flags.filter(**filter_kwargs).all() | python | def get_flags(self, user=None, status=None):
"""Returns flags for the object optionally filtered by status.
:param User user: Optional user filter
:param int status: Optional status filter
:rtype: QuerySet
"""
filter_kwargs = {}
update_filter_dict(filter_kwargs, user, status)
return self.flags.filter(**filter_kwargs).all() | [
"def",
"get_flags",
"(",
"self",
",",
"user",
"=",
"None",
",",
"status",
"=",
"None",
")",
":",
"filter_kwargs",
"=",
"{",
"}",
"update_filter_dict",
"(",
"filter_kwargs",
",",
"user",
",",
"status",
")",
"return",
"self",
".",
"flags",
".",
"filter",
... | Returns flags for the object optionally filtered by status.
:param User user: Optional user filter
:param int status: Optional status filter
:rtype: QuerySet | [
"Returns",
"flags",
"for",
"the",
"object",
"optionally",
"filtered",
"by",
"status",
"."
] | c8d1a40afb2f60d68ad6d34af3f528e76bdb7142 | https://github.com/idlesign/django-siteflags/blob/c8d1a40afb2f60d68ad6d34af3f528e76bdb7142/siteflags/models.py#L166-L175 | train | 50,136 |
idlesign/django-siteflags | siteflags/models.py | ModelWithFlag.set_flag | def set_flag(self, user, note=None, status=None):
"""Flags the object.
:param User user:
:param str note: User-defined note for this flag.
:param int status: Optional status integer (the meaning is defined by a developer).
:return:
"""
if not user.id:
return None
init_kwargs = {
'user': user,
'linked_object': self,
}
if note is not None:
init_kwargs['note'] = note
if status is not None:
init_kwargs['status'] = status
flag = get_flag_model()(**init_kwargs)
try:
flag.save()
except IntegrityError: # Record already exists.
pass
return flag | python | def set_flag(self, user, note=None, status=None):
"""Flags the object.
:param User user:
:param str note: User-defined note for this flag.
:param int status: Optional status integer (the meaning is defined by a developer).
:return:
"""
if not user.id:
return None
init_kwargs = {
'user': user,
'linked_object': self,
}
if note is not None:
init_kwargs['note'] = note
if status is not None:
init_kwargs['status'] = status
flag = get_flag_model()(**init_kwargs)
try:
flag.save()
except IntegrityError: # Record already exists.
pass
return flag | [
"def",
"set_flag",
"(",
"self",
",",
"user",
",",
"note",
"=",
"None",
",",
"status",
"=",
"None",
")",
":",
"if",
"not",
"user",
".",
"id",
":",
"return",
"None",
"init_kwargs",
"=",
"{",
"'user'",
":",
"user",
",",
"'linked_object'",
":",
"self",
... | Flags the object.
:param User user:
:param str note: User-defined note for this flag.
:param int status: Optional status integer (the meaning is defined by a developer).
:return: | [
"Flags",
"the",
"object",
"."
] | c8d1a40afb2f60d68ad6d34af3f528e76bdb7142 | https://github.com/idlesign/django-siteflags/blob/c8d1a40afb2f60d68ad6d34af3f528e76bdb7142/siteflags/models.py#L177-L202 | train | 50,137 |
idlesign/django-siteflags | siteflags/models.py | ModelWithFlag.is_flagged | def is_flagged(self, user=None, status=None):
"""Returns boolean whether the objects is flagged by a user.
:param User user: Optional user filter
:param int status: Optional status filter
:return:
"""
filter_kwargs = {
'content_type': ContentType.objects.get_for_model(self),
'object_id': self.id,
}
update_filter_dict(filter_kwargs, user, status)
return self.flags.filter(**filter_kwargs).count() | python | def is_flagged(self, user=None, status=None):
"""Returns boolean whether the objects is flagged by a user.
:param User user: Optional user filter
:param int status: Optional status filter
:return:
"""
filter_kwargs = {
'content_type': ContentType.objects.get_for_model(self),
'object_id': self.id,
}
update_filter_dict(filter_kwargs, user, status)
return self.flags.filter(**filter_kwargs).count() | [
"def",
"is_flagged",
"(",
"self",
",",
"user",
"=",
"None",
",",
"status",
"=",
"None",
")",
":",
"filter_kwargs",
"=",
"{",
"'content_type'",
":",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"self",
")",
",",
"'object_id'",
":",
"self",
".... | Returns boolean whether the objects is flagged by a user.
:param User user: Optional user filter
:param int status: Optional status filter
:return: | [
"Returns",
"boolean",
"whether",
"the",
"objects",
"is",
"flagged",
"by",
"a",
"user",
"."
] | c8d1a40afb2f60d68ad6d34af3f528e76bdb7142 | https://github.com/idlesign/django-siteflags/blob/c8d1a40afb2f60d68ad6d34af3f528e76bdb7142/siteflags/models.py#L218-L230 | train | 50,138 |
horejsek/python-sqlpuzzle | sqlpuzzle/_backends/__init__.py | set_backend | def set_backend(database):
"""
Configure used database, so sqlpuzzle can generate queries which are needed.
For now there is only support of MySQL and PostgreSQL.
"""
new_backend = BACKENDS.get(database.lower())
if not new_backend:
raise Exception('Backend {} is not supported.'.format(database))
global BACKEND # pylint: disable=global-statement
BACKEND = new_backend | python | def set_backend(database):
"""
Configure used database, so sqlpuzzle can generate queries which are needed.
For now there is only support of MySQL and PostgreSQL.
"""
new_backend = BACKENDS.get(database.lower())
if not new_backend:
raise Exception('Backend {} is not supported.'.format(database))
global BACKEND # pylint: disable=global-statement
BACKEND = new_backend | [
"def",
"set_backend",
"(",
"database",
")",
":",
"new_backend",
"=",
"BACKENDS",
".",
"get",
"(",
"database",
".",
"lower",
"(",
")",
")",
"if",
"not",
"new_backend",
":",
"raise",
"Exception",
"(",
"'Backend {} is not supported.'",
".",
"format",
"(",
"data... | Configure used database, so sqlpuzzle can generate queries which are needed.
For now there is only support of MySQL and PostgreSQL. | [
"Configure",
"used",
"database",
"so",
"sqlpuzzle",
"can",
"generate",
"queries",
"which",
"are",
"needed",
".",
"For",
"now",
"there",
"is",
"only",
"support",
"of",
"MySQL",
"and",
"PostgreSQL",
"."
] | d3a42ed1b339b8eafddb8d2c28a3a5832b3998dd | https://github.com/horejsek/python-sqlpuzzle/blob/d3a42ed1b339b8eafddb8d2c28a3a5832b3998dd/sqlpuzzle/_backends/__init__.py#L19-L28 | train | 50,139 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/runners/state_runner.py | StateRunner.health_check | def health_check(self):
""" Verify that device is accessible over CLI by sending ENTER for cli session """
api_response = 'Online'
result = 'Health check on resource {}'.format(self._resource_name)
try:
health_check_flow = RunCommandFlow(self.cli_handler, self._logger)
health_check_flow.execute_flow()
result += ' passed.'
except Exception as e:
self._logger.exception(e)
api_response = 'Error'
result += ' failed.'
try:
self._api.SetResourceLiveStatus(self._resource_name, api_response, result)
except Exception:
self._logger.error('Cannot update {} resource status on portal'.format(self._resource_name))
return result | python | def health_check(self):
""" Verify that device is accessible over CLI by sending ENTER for cli session """
api_response = 'Online'
result = 'Health check on resource {}'.format(self._resource_name)
try:
health_check_flow = RunCommandFlow(self.cli_handler, self._logger)
health_check_flow.execute_flow()
result += ' passed.'
except Exception as e:
self._logger.exception(e)
api_response = 'Error'
result += ' failed.'
try:
self._api.SetResourceLiveStatus(self._resource_name, api_response, result)
except Exception:
self._logger.error('Cannot update {} resource status on portal'.format(self._resource_name))
return result | [
"def",
"health_check",
"(",
"self",
")",
":",
"api_response",
"=",
"'Online'",
"result",
"=",
"'Health check on resource {}'",
".",
"format",
"(",
"self",
".",
"_resource_name",
")",
"try",
":",
"health_check_flow",
"=",
"RunCommandFlow",
"(",
"self",
".",
"cli_... | Verify that device is accessible over CLI by sending ENTER for cli session | [
"Verify",
"that",
"device",
"is",
"accessible",
"over",
"CLI",
"by",
"sending",
"ENTER",
"for",
"cli",
"session"
] | 009aab33edb30035b52fe10dbb91db61c95ba4d9 | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/runners/state_runner.py#L26-L46 | train | 50,140 |
horejsek/python-sqlpuzzle | sqlpuzzle/_backends/sql.py | SqlBackend.reference | def reference(cls, value):
"""
Convert as reference on column.
table => "table"
table.column => "table"."column"
db.table.column => "db"."table"."column"
table."col.umn" => "table"."col.umn"
"table"."col.umn" => "table"."col.umn"
"""
from sqlpuzzle._common.utils import force_text
value = force_text(value)
parts = re.split(r'{quote}([^{quote}]+){quote}|\.'.format(quote=cls.reference_quote), value)
parts = ('{quote}{i}{quote}'.format(quote=cls.reference_quote, i=i) if i != '*' else i for i in parts if i)
return '.'.join(parts) | python | def reference(cls, value):
"""
Convert as reference on column.
table => "table"
table.column => "table"."column"
db.table.column => "db"."table"."column"
table."col.umn" => "table"."col.umn"
"table"."col.umn" => "table"."col.umn"
"""
from sqlpuzzle._common.utils import force_text
value = force_text(value)
parts = re.split(r'{quote}([^{quote}]+){quote}|\.'.format(quote=cls.reference_quote), value)
parts = ('{quote}{i}{quote}'.format(quote=cls.reference_quote, i=i) if i != '*' else i for i in parts if i)
return '.'.join(parts) | [
"def",
"reference",
"(",
"cls",
",",
"value",
")",
":",
"from",
"sqlpuzzle",
".",
"_common",
".",
"utils",
"import",
"force_text",
"value",
"=",
"force_text",
"(",
"value",
")",
"parts",
"=",
"re",
".",
"split",
"(",
"r'{quote}([^{quote}]+){quote}|\\.'",
"."... | Convert as reference on column.
table => "table"
table.column => "table"."column"
db.table.column => "db"."table"."column"
table."col.umn" => "table"."col.umn"
"table"."col.umn" => "table"."col.umn" | [
"Convert",
"as",
"reference",
"on",
"column",
".",
"table",
"=",
">",
"table",
"table",
".",
"column",
"=",
">",
"table",
".",
"column",
"db",
".",
"table",
".",
"column",
"=",
">",
"db",
".",
"table",
".",
"column",
"table",
".",
"col",
".",
"umn"... | d3a42ed1b339b8eafddb8d2c28a3a5832b3998dd | https://github.com/horejsek/python-sqlpuzzle/blob/d3a42ed1b339b8eafddb8d2c28a3a5832b3998dd/sqlpuzzle/_backends/sql.py#L31-L44 | train | 50,141 |
Workiva/furious | furious/job_utils.py | reference_to_path | def reference_to_path(reference):
"""Convert a reference to a Python object to a string path."""
# Try to pop the options off whatever they passed in.
if isinstance(reference, basestring):
# This is an object path name in str form.
import re
if not re.match(r'^[^\d\W]([a-zA-Z._]|((?<!\.)\d))+$', reference):
raise errors.BadObjectPathError(
'Invalid reference path, must meet Python\'s identifier '
'requirements, passed value was "%s".', reference)
return reference
if callable(reference):
# This is a function or a class.
# Try to figure out the path to the reference.
parts = [reference.__module__]
if hasattr(reference, 'im_class'):
parts.append(reference.im_class.__name__)
if hasattr(reference, 'func_name'):
parts.append(reference.func_name)
elif reference.__module__ == '__builtin__':
return reference.__name__
elif hasattr(reference, '__name__'):
# Probably a class
parts.append(reference.__name__)
else:
raise errors.BadObjectPathError("Invalid object type.")
return '.'.join(parts)
raise errors.BadObjectPathError("Unable to determine path to callable.")
elif hasattr(reference, '__package__'):
# This is probably a module.
return reference.__name__
raise errors.BadObjectPathError("Must provide a reference path or reference.") | python | def reference_to_path(reference):
"""Convert a reference to a Python object to a string path."""
# Try to pop the options off whatever they passed in.
if isinstance(reference, basestring):
# This is an object path name in str form.
import re
if not re.match(r'^[^\d\W]([a-zA-Z._]|((?<!\.)\d))+$', reference):
raise errors.BadObjectPathError(
'Invalid reference path, must meet Python\'s identifier '
'requirements, passed value was "%s".', reference)
return reference
if callable(reference):
# This is a function or a class.
# Try to figure out the path to the reference.
parts = [reference.__module__]
if hasattr(reference, 'im_class'):
parts.append(reference.im_class.__name__)
if hasattr(reference, 'func_name'):
parts.append(reference.func_name)
elif reference.__module__ == '__builtin__':
return reference.__name__
elif hasattr(reference, '__name__'):
# Probably a class
parts.append(reference.__name__)
else:
raise errors.BadObjectPathError("Invalid object type.")
return '.'.join(parts)
raise errors.BadObjectPathError("Unable to determine path to callable.")
elif hasattr(reference, '__package__'):
# This is probably a module.
return reference.__name__
raise errors.BadObjectPathError("Must provide a reference path or reference.") | [
"def",
"reference_to_path",
"(",
"reference",
")",
":",
"# Try to pop the options off whatever they passed in.",
"if",
"isinstance",
"(",
"reference",
",",
"basestring",
")",
":",
"# This is an object path name in str form.",
"import",
"re",
"if",
"not",
"re",
".",
"match... | Convert a reference to a Python object to a string path. | [
"Convert",
"a",
"reference",
"to",
"a",
"Python",
"object",
"to",
"a",
"string",
"path",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/job_utils.py#L42-L79 | train | 50,142 |
Workiva/furious | furious/job_utils.py | path_to_reference | def path_to_reference(path):
"""Convert an object path reference to a reference."""
# By default JSON decodes strings as unicode. The Python __import__ does
# not like that choice. So we'll just cast all function paths to a string.
# NOTE: that there is no corresponding unit test for the classmethod
# version of this problem. It only impacts importing modules.
path = str(path)
if '.' not in path:
try:
return globals()["__builtins__"][path]
except KeyError:
try:
return getattr(globals()["__builtins__"], path)
except AttributeError:
pass
try:
return globals()[path]
except KeyError:
pass
raise errors.BadObjectPathError(
'Unable to find function "%s".' % (path,))
module_path, function_name = path.rsplit('.', 1)
try:
module = __import__(name=module_path,
fromlist=[function_name])
except ImportError:
module_path, class_name = module_path.rsplit('.', 1)
module = __import__(name=module_path, fromlist=[class_name])
module = getattr(module, class_name)
try:
return getattr(module, function_name)
except AttributeError:
raise errors.BadObjectPathError(
'Unable to find function "%s".' % (path,)) | python | def path_to_reference(path):
"""Convert an object path reference to a reference."""
# By default JSON decodes strings as unicode. The Python __import__ does
# not like that choice. So we'll just cast all function paths to a string.
# NOTE: that there is no corresponding unit test for the classmethod
# version of this problem. It only impacts importing modules.
path = str(path)
if '.' not in path:
try:
return globals()["__builtins__"][path]
except KeyError:
try:
return getattr(globals()["__builtins__"], path)
except AttributeError:
pass
try:
return globals()[path]
except KeyError:
pass
raise errors.BadObjectPathError(
'Unable to find function "%s".' % (path,))
module_path, function_name = path.rsplit('.', 1)
try:
module = __import__(name=module_path,
fromlist=[function_name])
except ImportError:
module_path, class_name = module_path.rsplit('.', 1)
module = __import__(name=module_path, fromlist=[class_name])
module = getattr(module, class_name)
try:
return getattr(module, function_name)
except AttributeError:
raise errors.BadObjectPathError(
'Unable to find function "%s".' % (path,)) | [
"def",
"path_to_reference",
"(",
"path",
")",
":",
"# By default JSON decodes strings as unicode. The Python __import__ does",
"# not like that choice. So we'll just cast all function paths to a string.",
"# NOTE: that there is no corresponding unit test for the classmethod",
"# version of this pr... | Convert an object path reference to a reference. | [
"Convert",
"an",
"object",
"path",
"reference",
"to",
"a",
"reference",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/job_utils.py#L82-L123 | train | 50,143 |
Workiva/furious | furious/job_utils.py | encode_callbacks | def encode_callbacks(callbacks):
"""Encode callbacks to as a dict suitable for JSON encoding."""
from furious.async import Async
if not callbacks:
return
encoded_callbacks = {}
for event, callback in callbacks.iteritems():
if callable(callback):
callback, _ = get_function_path_and_options(callback)
elif isinstance(callback, Async):
callback = callback.to_dict()
encoded_callbacks[event] = callback
return encoded_callbacks | python | def encode_callbacks(callbacks):
"""Encode callbacks to as a dict suitable for JSON encoding."""
from furious.async import Async
if not callbacks:
return
encoded_callbacks = {}
for event, callback in callbacks.iteritems():
if callable(callback):
callback, _ = get_function_path_and_options(callback)
elif isinstance(callback, Async):
callback = callback.to_dict()
encoded_callbacks[event] = callback
return encoded_callbacks | [
"def",
"encode_callbacks",
"(",
"callbacks",
")",
":",
"from",
"furious",
".",
"async",
"import",
"Async",
"if",
"not",
"callbacks",
":",
"return",
"encoded_callbacks",
"=",
"{",
"}",
"for",
"event",
",",
"callback",
"in",
"callbacks",
".",
"iteritems",
"(",... | Encode callbacks to as a dict suitable for JSON encoding. | [
"Encode",
"callbacks",
"to",
"as",
"a",
"dict",
"suitable",
"for",
"JSON",
"encoding",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/job_utils.py#L126-L143 | train | 50,144 |
Workiva/furious | furious/job_utils.py | decode_callbacks | def decode_callbacks(encoded_callbacks):
"""Decode the callbacks to an executable form."""
from furious.async import Async
callbacks = {}
for event, callback in encoded_callbacks.iteritems():
if isinstance(callback, dict):
async_type = Async
if '_type' in callback:
async_type = path_to_reference(callback['_type'])
callback = async_type.from_dict(callback)
else:
callback = path_to_reference(callback)
callbacks[event] = callback
return callbacks | python | def decode_callbacks(encoded_callbacks):
"""Decode the callbacks to an executable form."""
from furious.async import Async
callbacks = {}
for event, callback in encoded_callbacks.iteritems():
if isinstance(callback, dict):
async_type = Async
if '_type' in callback:
async_type = path_to_reference(callback['_type'])
callback = async_type.from_dict(callback)
else:
callback = path_to_reference(callback)
callbacks[event] = callback
return callbacks | [
"def",
"decode_callbacks",
"(",
"encoded_callbacks",
")",
":",
"from",
"furious",
".",
"async",
"import",
"Async",
"callbacks",
"=",
"{",
"}",
"for",
"event",
",",
"callback",
"in",
"encoded_callbacks",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(... | Decode the callbacks to an executable form. | [
"Decode",
"the",
"callbacks",
"to",
"an",
"executable",
"form",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/job_utils.py#L146-L162 | train | 50,145 |
upsight/doctor | doctor/schema.py | SchemaRefResolver._format_stack | def _format_stack(self, stack, current=None):
"""Prettifies a scope stack for use in error messages.
:param list(str) stack: List of scopes.
:param str current: The current scope. If specified, will be appended
onto the stack before formatting.
:returns: str
"""
if current is not None:
stack = stack + [current]
if len(stack) > 1:
prefix = os.path.commonprefix(stack)
if prefix.endswith('/'):
prefix = prefix[:-1]
stack = [scope[len(prefix):] for scope in stack]
return ' => '.join(stack) | python | def _format_stack(self, stack, current=None):
"""Prettifies a scope stack for use in error messages.
:param list(str) stack: List of scopes.
:param str current: The current scope. If specified, will be appended
onto the stack before formatting.
:returns: str
"""
if current is not None:
stack = stack + [current]
if len(stack) > 1:
prefix = os.path.commonprefix(stack)
if prefix.endswith('/'):
prefix = prefix[:-1]
stack = [scope[len(prefix):] for scope in stack]
return ' => '.join(stack) | [
"def",
"_format_stack",
"(",
"self",
",",
"stack",
",",
"current",
"=",
"None",
")",
":",
"if",
"current",
"is",
"not",
"None",
":",
"stack",
"=",
"stack",
"+",
"[",
"current",
"]",
"if",
"len",
"(",
"stack",
")",
">",
"1",
":",
"prefix",
"=",
"o... | Prettifies a scope stack for use in error messages.
:param list(str) stack: List of scopes.
:param str current: The current scope. If specified, will be appended
onto the stack before formatting.
:returns: str | [
"Prettifies",
"a",
"scope",
"stack",
"for",
"use",
"in",
"error",
"messages",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/schema.py#L20-L35 | train | 50,146 |
upsight/doctor | doctor/schema.py | SchemaRefResolver.resolve | def resolve(self, ref, document=None):
"""Resolve a fragment within the schema.
If the resolved value contains a $ref, it will attempt to resolve that
as well, until it gets something that is not a reference. Circular
references will raise a SchemaError.
:param str ref: URI to resolve.
:param dict document: Optional schema in which to resolve the URI.
:returns: a tuple of the final, resolved URI (after any recursion) and
resolved value in the schema that the URI references.
:raises SchemaError:
"""
try:
# This logic is basically the RefResolver's resolve function, but
# updated to support fragments of dynamic documents. The jsonschema
# module supports passing documents when resolving fragments, but
# it doesn't expose that capability in the resolve function.
url = self._urljoin_cache(self.resolution_scope, ref)
if document is None:
# No document passed, so just resolve it as we normally would.
resolved = self._remote_cache(url)
else:
# Document passed, so assume it's a fragment.
_, fragment = urldefrag(url)
resolved = self.resolve_fragment(document, fragment)
except jsonschema.RefResolutionError as e:
# Failed to find a ref. Make the error a bit prettier so we can
# figure out where it came from.
message = e.args[0]
if self._scopes_stack:
message = '{} (from {})'.format(
message, self._format_stack(self._scopes_stack))
raise SchemaError(message)
if isinstance(resolved, dict) and '$ref' in resolved:
# Try to resolve the reference, so we can get the actual value we
# want, instead of a useless dict with a $ref in it.
if url in self._scopes_stack:
# We've already tried to look up this URL, so this must
# be a circular reference in the schema.
raise SchemaError(
'Circular reference in schema: {}'.format(
self._format_stack(self._scopes_stack + [url])))
try:
self.push_scope(url)
return self.resolve(resolved['$ref'])
finally:
self.pop_scope()
else:
return url, resolved | python | def resolve(self, ref, document=None):
"""Resolve a fragment within the schema.
If the resolved value contains a $ref, it will attempt to resolve that
as well, until it gets something that is not a reference. Circular
references will raise a SchemaError.
:param str ref: URI to resolve.
:param dict document: Optional schema in which to resolve the URI.
:returns: a tuple of the final, resolved URI (after any recursion) and
resolved value in the schema that the URI references.
:raises SchemaError:
"""
try:
# This logic is basically the RefResolver's resolve function, but
# updated to support fragments of dynamic documents. The jsonschema
# module supports passing documents when resolving fragments, but
# it doesn't expose that capability in the resolve function.
url = self._urljoin_cache(self.resolution_scope, ref)
if document is None:
# No document passed, so just resolve it as we normally would.
resolved = self._remote_cache(url)
else:
# Document passed, so assume it's a fragment.
_, fragment = urldefrag(url)
resolved = self.resolve_fragment(document, fragment)
except jsonschema.RefResolutionError as e:
# Failed to find a ref. Make the error a bit prettier so we can
# figure out where it came from.
message = e.args[0]
if self._scopes_stack:
message = '{} (from {})'.format(
message, self._format_stack(self._scopes_stack))
raise SchemaError(message)
if isinstance(resolved, dict) and '$ref' in resolved:
# Try to resolve the reference, so we can get the actual value we
# want, instead of a useless dict with a $ref in it.
if url in self._scopes_stack:
# We've already tried to look up this URL, so this must
# be a circular reference in the schema.
raise SchemaError(
'Circular reference in schema: {}'.format(
self._format_stack(self._scopes_stack + [url])))
try:
self.push_scope(url)
return self.resolve(resolved['$ref'])
finally:
self.pop_scope()
else:
return url, resolved | [
"def",
"resolve",
"(",
"self",
",",
"ref",
",",
"document",
"=",
"None",
")",
":",
"try",
":",
"# This logic is basically the RefResolver's resolve function, but",
"# updated to support fragments of dynamic documents. The jsonschema",
"# module supports passing documents when resolvi... | Resolve a fragment within the schema.
If the resolved value contains a $ref, it will attempt to resolve that
as well, until it gets something that is not a reference. Circular
references will raise a SchemaError.
:param str ref: URI to resolve.
:param dict document: Optional schema in which to resolve the URI.
:returns: a tuple of the final, resolved URI (after any recursion) and
resolved value in the schema that the URI references.
:raises SchemaError: | [
"Resolve",
"a",
"fragment",
"within",
"the",
"schema",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/schema.py#L37-L87 | train | 50,147 |
upsight/doctor | doctor/schema.py | SchemaRefResolver.resolve_remote | def resolve_remote(self, uri):
"""Add support to load YAML files.
This will attempt to load a YAML file first, and then go back to the
default behavior.
:param str uri: the URI to resolve
:returns: the retrieved document
"""
if uri.startswith('file://'):
try:
path = uri[7:]
with open(path, 'r') as schema_file:
result = yaml.load(schema_file)
if self.cache_remote:
self.store[uri] = result
return result
except yaml.parser.ParserError as e:
logging.debug('Error parsing {!r} as YAML: {}'.format(
uri, e))
return super(SchemaRefResolver, self).resolve_remote(uri) | python | def resolve_remote(self, uri):
"""Add support to load YAML files.
This will attempt to load a YAML file first, and then go back to the
default behavior.
:param str uri: the URI to resolve
:returns: the retrieved document
"""
if uri.startswith('file://'):
try:
path = uri[7:]
with open(path, 'r') as schema_file:
result = yaml.load(schema_file)
if self.cache_remote:
self.store[uri] = result
return result
except yaml.parser.ParserError as e:
logging.debug('Error parsing {!r} as YAML: {}'.format(
uri, e))
return super(SchemaRefResolver, self).resolve_remote(uri) | [
"def",
"resolve_remote",
"(",
"self",
",",
"uri",
")",
":",
"if",
"uri",
".",
"startswith",
"(",
"'file://'",
")",
":",
"try",
":",
"path",
"=",
"uri",
"[",
"7",
":",
"]",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"schema_file",
":",
"r... | Add support to load YAML files.
This will attempt to load a YAML file first, and then go back to the
default behavior.
:param str uri: the URI to resolve
:returns: the retrieved document | [
"Add",
"support",
"to",
"load",
"YAML",
"files",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/schema.py#L89-L109 | train | 50,148 |
upsight/doctor | doctor/schema.py | Schema.get_validator | def get_validator(self, schema=None):
"""Get a jsonschema validator.
:param dict schema: A custom schema to validate against.
:returns: an instance of jsonschema Draft4Validator.
"""
schema = schema if schema is not None else self.schema
return jsonschema.Draft4Validator(
schema, resolver=self.resolver,
format_checker=jsonschema.draft4_format_checker) | python | def get_validator(self, schema=None):
"""Get a jsonschema validator.
:param dict schema: A custom schema to validate against.
:returns: an instance of jsonschema Draft4Validator.
"""
schema = schema if schema is not None else self.schema
return jsonschema.Draft4Validator(
schema, resolver=self.resolver,
format_checker=jsonschema.draft4_format_checker) | [
"def",
"get_validator",
"(",
"self",
",",
"schema",
"=",
"None",
")",
":",
"schema",
"=",
"schema",
"if",
"schema",
"is",
"not",
"None",
"else",
"self",
".",
"schema",
"return",
"jsonschema",
".",
"Draft4Validator",
"(",
"schema",
",",
"resolver",
"=",
"... | Get a jsonschema validator.
:param dict schema: A custom schema to validate against.
:returns: an instance of jsonschema Draft4Validator. | [
"Get",
"a",
"jsonschema",
"validator",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/schema.py#L127-L136 | train | 50,149 |
upsight/doctor | doctor/schema.py | Schema.resolve | def resolve(self, ref, document=None):
"""Resolve a ref within the schema.
This is just a convenience method, since RefResolver returns both a URI
and the resolved value, and we usually just need the resolved value.
:param str ref: URI to resolve.
:param dict document: Optional schema in which to resolve the URI.
:returns: the portion of the schema that the URI references.
:see: :meth:`SchemaRefResolver.resolve`
"""
_, resolved = self.resolver.resolve(ref, document=document)
return resolved | python | def resolve(self, ref, document=None):
"""Resolve a ref within the schema.
This is just a convenience method, since RefResolver returns both a URI
and the resolved value, and we usually just need the resolved value.
:param str ref: URI to resolve.
:param dict document: Optional schema in which to resolve the URI.
:returns: the portion of the schema that the URI references.
:see: :meth:`SchemaRefResolver.resolve`
"""
_, resolved = self.resolver.resolve(ref, document=document)
return resolved | [
"def",
"resolve",
"(",
"self",
",",
"ref",
",",
"document",
"=",
"None",
")",
":",
"_",
",",
"resolved",
"=",
"self",
".",
"resolver",
".",
"resolve",
"(",
"ref",
",",
"document",
"=",
"document",
")",
"return",
"resolved"
] | Resolve a ref within the schema.
This is just a convenience method, since RefResolver returns both a URI
and the resolved value, and we usually just need the resolved value.
:param str ref: URI to resolve.
:param dict document: Optional schema in which to resolve the URI.
:returns: the portion of the schema that the URI references.
:see: :meth:`SchemaRefResolver.resolve` | [
"Resolve",
"a",
"ref",
"within",
"the",
"schema",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/schema.py#L138-L150 | train | 50,150 |
upsight/doctor | doctor/schema.py | Schema.resolver | def resolver(self):
"""jsonschema RefResolver object for the base schema."""
if self._resolver is not None:
return self._resolver
if self._schema_path is not None:
# the documentation for ref resolving
# https://github.com/Julian/jsonschema/issues/98
# https://python-jsonschema.readthedocs.org/en/latest/references/
self._resolver = SchemaRefResolver(
'file://' + self._schema_path + '/', self.schema)
else:
self._resolver = SchemaRefResolver.from_schema(self.schema)
return self._resolver | python | def resolver(self):
"""jsonschema RefResolver object for the base schema."""
if self._resolver is not None:
return self._resolver
if self._schema_path is not None:
# the documentation for ref resolving
# https://github.com/Julian/jsonschema/issues/98
# https://python-jsonschema.readthedocs.org/en/latest/references/
self._resolver = SchemaRefResolver(
'file://' + self._schema_path + '/', self.schema)
else:
self._resolver = SchemaRefResolver.from_schema(self.schema)
return self._resolver | [
"def",
"resolver",
"(",
"self",
")",
":",
"if",
"self",
".",
"_resolver",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_resolver",
"if",
"self",
".",
"_schema_path",
"is",
"not",
"None",
":",
"# the documentation for ref resolving",
"# https://github.com/Ju... | jsonschema RefResolver object for the base schema. | [
"jsonschema",
"RefResolver",
"object",
"for",
"the",
"base",
"schema",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/schema.py#L153-L165 | train | 50,151 |
upsight/doctor | doctor/schema.py | Schema.validate | def validate(self, value, validator):
"""Validates and returns the value.
If the value does not validate against the schema, SchemaValidationError
will be raised.
:param value: A value to validate (usually a dict).
:param validator: An instance of a jsonschema validator class, as
created by Schema.get_validator().
:returns: the passed value.
:raises SchemaValidationError:
:raises Exception:
"""
try:
validator.validate(value)
except Exception as e:
logging.debug(e, exc_info=e)
if isinstance(e, DoctorError):
raise
else:
# Gather all the validation errors
validation_errors = sorted(
validator.iter_errors(value), key=lambda e: e.path)
errors = {}
for error in validation_errors:
try:
key = error.path[0]
except IndexError:
key = '_other'
errors[key] = error.args[0]
raise SchemaValidationError(e.args[0], errors=errors)
return value | python | def validate(self, value, validator):
"""Validates and returns the value.
If the value does not validate against the schema, SchemaValidationError
will be raised.
:param value: A value to validate (usually a dict).
:param validator: An instance of a jsonschema validator class, as
created by Schema.get_validator().
:returns: the passed value.
:raises SchemaValidationError:
:raises Exception:
"""
try:
validator.validate(value)
except Exception as e:
logging.debug(e, exc_info=e)
if isinstance(e, DoctorError):
raise
else:
# Gather all the validation errors
validation_errors = sorted(
validator.iter_errors(value), key=lambda e: e.path)
errors = {}
for error in validation_errors:
try:
key = error.path[0]
except IndexError:
key = '_other'
errors[key] = error.args[0]
raise SchemaValidationError(e.args[0], errors=errors)
return value | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"validator",
")",
":",
"try",
":",
"validator",
".",
"validate",
"(",
"value",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"debug",
"(",
"e",
",",
"exc_info",
"=",
"e",
")",
"if",
"... | Validates and returns the value.
If the value does not validate against the schema, SchemaValidationError
will be raised.
:param value: A value to validate (usually a dict).
:param validator: An instance of a jsonschema validator class, as
created by Schema.get_validator().
:returns: the passed value.
:raises SchemaValidationError:
:raises Exception: | [
"Validates",
"and",
"returns",
"the",
"value",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/schema.py#L167-L198 | train | 50,152 |
upsight/doctor | doctor/schema.py | Schema.validate_json | def validate_json(self, json_value, validator):
"""Validates and returns the parsed JSON string.
If the value is not valid JSON, ParseError will be raised. If it is
valid JSON, but does not validate against the schema,
SchemaValidationError will be raised.
:param str json_value: JSON value.
:param validator: An instance of a jsonschema validator class, as
created by Schema.get_validator().
:returns: the parsed JSON value.
"""
value = parse_json(json_value)
return self.validate(value, validator) | python | def validate_json(self, json_value, validator):
"""Validates and returns the parsed JSON string.
If the value is not valid JSON, ParseError will be raised. If it is
valid JSON, but does not validate against the schema,
SchemaValidationError will be raised.
:param str json_value: JSON value.
:param validator: An instance of a jsonschema validator class, as
created by Schema.get_validator().
:returns: the parsed JSON value.
"""
value = parse_json(json_value)
return self.validate(value, validator) | [
"def",
"validate_json",
"(",
"self",
",",
"json_value",
",",
"validator",
")",
":",
"value",
"=",
"parse_json",
"(",
"json_value",
")",
"return",
"self",
".",
"validate",
"(",
"value",
",",
"validator",
")"
] | Validates and returns the parsed JSON string.
If the value is not valid JSON, ParseError will be raised. If it is
valid JSON, but does not validate against the schema,
SchemaValidationError will be raised.
:param str json_value: JSON value.
:param validator: An instance of a jsonschema validator class, as
created by Schema.get_validator().
:returns: the parsed JSON value. | [
"Validates",
"and",
"returns",
"the",
"parsed",
"JSON",
"string",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/schema.py#L200-L213 | train | 50,153 |
upsight/doctor | doctor/schema.py | Schema.from_file | def from_file(cls, schema_filepath, *args, **kwargs):
"""Create an instance from a YAML or JSON schema file.
Any additional args or kwargs will be passed on when constructing the
new schema instance (useful for subclasses).
:param str schema_filepath: Path to the schema file.
:returns: an instance of the class.
:raises SchemaLoadingError: for invalid input files.
"""
schema_filepath = os.path.abspath(schema_filepath)
try:
with open(schema_filepath, 'r') as schema_file:
schema = yaml.load(schema_file.read())
except Exception:
msg = 'Error loading schema file {}'.format(schema_filepath)
logging.exception(msg)
raise SchemaLoadingError(msg)
return cls(schema, *args, schema_path=os.path.dirname(schema_filepath),
**kwargs) | python | def from_file(cls, schema_filepath, *args, **kwargs):
"""Create an instance from a YAML or JSON schema file.
Any additional args or kwargs will be passed on when constructing the
new schema instance (useful for subclasses).
:param str schema_filepath: Path to the schema file.
:returns: an instance of the class.
:raises SchemaLoadingError: for invalid input files.
"""
schema_filepath = os.path.abspath(schema_filepath)
try:
with open(schema_filepath, 'r') as schema_file:
schema = yaml.load(schema_file.read())
except Exception:
msg = 'Error loading schema file {}'.format(schema_filepath)
logging.exception(msg)
raise SchemaLoadingError(msg)
return cls(schema, *args, schema_path=os.path.dirname(schema_filepath),
**kwargs) | [
"def",
"from_file",
"(",
"cls",
",",
"schema_filepath",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"schema_filepath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"schema_filepath",
")",
"try",
":",
"with",
"open",
"(",
"schema_filepath",
",",
... | Create an instance from a YAML or JSON schema file.
Any additional args or kwargs will be passed on when constructing the
new schema instance (useful for subclasses).
:param str schema_filepath: Path to the schema file.
:returns: an instance of the class.
:raises SchemaLoadingError: for invalid input files. | [
"Create",
"an",
"instance",
"from",
"a",
"YAML",
"or",
"JSON",
"schema",
"file",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/schema.py#L216-L235 | train | 50,154 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/flows/action_flows.py | RunCommandFlow.execute_flow | def execute_flow(self, custom_command="", is_config=False):
""" Execute flow which run custom command on device
:param custom_command: the command to execute on device
:param is_config: if True then run command in configuration mode
:return: command execution output
"""
responses = []
if isinstance(custom_command, str):
commands = [custom_command]
elif isinstance(custom_command, tuple):
commands = list(custom_command)
else:
commands = custom_command
if is_config:
mode = self._cli_handler.config_mode
if not mode:
raise Exception(self.__class__.__name__,
"CliHandler configuration is missing. Config Mode has to be defined")
else:
mode = self._cli_handler.enable_mode
if not mode:
raise Exception(self.__class__.__name__,
"CliHandler configuration is missing. Enable Mode has to be defined")
with self._cli_handler.get_cli_service(mode) as session:
for cmd in commands:
responses.append(session.send_command(command=cmd))
return '\n'.join(responses) | python | def execute_flow(self, custom_command="", is_config=False):
""" Execute flow which run custom command on device
:param custom_command: the command to execute on device
:param is_config: if True then run command in configuration mode
:return: command execution output
"""
responses = []
if isinstance(custom_command, str):
commands = [custom_command]
elif isinstance(custom_command, tuple):
commands = list(custom_command)
else:
commands = custom_command
if is_config:
mode = self._cli_handler.config_mode
if not mode:
raise Exception(self.__class__.__name__,
"CliHandler configuration is missing. Config Mode has to be defined")
else:
mode = self._cli_handler.enable_mode
if not mode:
raise Exception(self.__class__.__name__,
"CliHandler configuration is missing. Enable Mode has to be defined")
with self._cli_handler.get_cli_service(mode) as session:
for cmd in commands:
responses.append(session.send_command(command=cmd))
return '\n'.join(responses) | [
"def",
"execute_flow",
"(",
"self",
",",
"custom_command",
"=",
"\"\"",
",",
"is_config",
"=",
"False",
")",
":",
"responses",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"custom_command",
",",
"str",
")",
":",
"commands",
"=",
"[",
"custom_command",
"]",
"e... | Execute flow which run custom command on device
:param custom_command: the command to execute on device
:param is_config: if True then run command in configuration mode
:return: command execution output | [
"Execute",
"flow",
"which",
"run",
"custom",
"command",
"on",
"device"
] | 009aab33edb30035b52fe10dbb91db61c95ba4d9 | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/flows/action_flows.py#L109-L139 | train | 50,155 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/runners/run_command_runner.py | RunCommandRunner.run_custom_config_command | def run_custom_config_command(self, custom_command):
""" Execute custom command in configuration mode on device
:param custom_command: command
:return: result of command execution
"""
return self.run_command_flow.execute_flow(custom_command=custom_command, is_config=True) | python | def run_custom_config_command(self, custom_command):
""" Execute custom command in configuration mode on device
:param custom_command: command
:return: result of command execution
"""
return self.run_command_flow.execute_flow(custom_command=custom_command, is_config=True) | [
"def",
"run_custom_config_command",
"(",
"self",
",",
"custom_command",
")",
":",
"return",
"self",
".",
"run_command_flow",
".",
"execute_flow",
"(",
"custom_command",
"=",
"custom_command",
",",
"is_config",
"=",
"True",
")"
] | Execute custom command in configuration mode on device
:param custom_command: command
:return: result of command execution | [
"Execute",
"custom",
"command",
"in",
"configuration",
"mode",
"on",
"device"
] | 009aab33edb30035b52fe10dbb91db61c95ba4d9 | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/runners/run_command_runner.py#L41-L48 | train | 50,156 |
Workiva/furious | furious/async.py | async_from_options | def async_from_options(options):
"""Deserialize an Async or Async subclass from an options dict."""
_type = options.pop('_type', 'furious.async.Async')
_type = path_to_reference(_type)
return _type.from_dict(options) | python | def async_from_options(options):
"""Deserialize an Async or Async subclass from an options dict."""
_type = options.pop('_type', 'furious.async.Async')
_type = path_to_reference(_type)
return _type.from_dict(options) | [
"def",
"async_from_options",
"(",
"options",
")",
":",
"_type",
"=",
"options",
".",
"pop",
"(",
"'_type'",
",",
"'furious.async.Async'",
")",
"_type",
"=",
"path_to_reference",
"(",
"_type",
")",
"return",
"_type",
".",
"from_dict",
"(",
"options",
")"
] | Deserialize an Async or Async subclass from an options dict. | [
"Deserialize",
"an",
"Async",
"or",
"Async",
"subclass",
"from",
"an",
"options",
"dict",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L590-L596 | train | 50,157 |
Workiva/furious | furious/async.py | encode_async_options | def encode_async_options(async):
"""Encode Async options for JSON encoding."""
options = copy.deepcopy(async._options)
options['_type'] = reference_to_path(async.__class__)
# JSON don't like datetimes.
eta = options.get('task_args', {}).get('eta')
if eta:
options['task_args']['eta'] = time.mktime(eta.timetuple())
callbacks = async._options.get('callbacks')
if callbacks:
options['callbacks'] = encode_callbacks(callbacks)
if '_context_checker' in options:
_checker = options.pop('_context_checker')
options['__context_checker'] = reference_to_path(_checker)
if '_process_results' in options:
_processor = options.pop('_process_results')
options['__process_results'] = reference_to_path(_processor)
return options | python | def encode_async_options(async):
"""Encode Async options for JSON encoding."""
options = copy.deepcopy(async._options)
options['_type'] = reference_to_path(async.__class__)
# JSON don't like datetimes.
eta = options.get('task_args', {}).get('eta')
if eta:
options['task_args']['eta'] = time.mktime(eta.timetuple())
callbacks = async._options.get('callbacks')
if callbacks:
options['callbacks'] = encode_callbacks(callbacks)
if '_context_checker' in options:
_checker = options.pop('_context_checker')
options['__context_checker'] = reference_to_path(_checker)
if '_process_results' in options:
_processor = options.pop('_process_results')
options['__process_results'] = reference_to_path(_processor)
return options | [
"def",
"encode_async_options",
"(",
"async",
")",
":",
"options",
"=",
"copy",
".",
"deepcopy",
"(",
"async",
".",
"_options",
")",
"options",
"[",
"'_type'",
"]",
"=",
"reference_to_path",
"(",
"async",
".",
"__class__",
")",
"# JSON don't like datetimes.",
"... | Encode Async options for JSON encoding. | [
"Encode",
"Async",
"options",
"for",
"JSON",
"encoding",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L599-L622 | train | 50,158 |
Workiva/furious | furious/async.py | decode_async_options | def decode_async_options(options):
"""Decode Async options from JSON decoding."""
async_options = copy.deepcopy(options)
# JSON don't like datetimes.
eta = async_options.get('task_args', {}).get('eta')
if eta:
from datetime import datetime
async_options['task_args']['eta'] = datetime.fromtimestamp(eta)
# If there are callbacks, reconstitute them.
callbacks = async_options.get('callbacks', {})
if callbacks:
async_options['callbacks'] = decode_callbacks(callbacks)
if '__context_checker' in options:
_checker = options['__context_checker']
async_options['_context_checker'] = path_to_reference(_checker)
if '__process_results' in options:
_processor = options['__process_results']
async_options['_process_results'] = path_to_reference(_processor)
return async_options | python | def decode_async_options(options):
"""Decode Async options from JSON decoding."""
async_options = copy.deepcopy(options)
# JSON don't like datetimes.
eta = async_options.get('task_args', {}).get('eta')
if eta:
from datetime import datetime
async_options['task_args']['eta'] = datetime.fromtimestamp(eta)
# If there are callbacks, reconstitute them.
callbacks = async_options.get('callbacks', {})
if callbacks:
async_options['callbacks'] = decode_callbacks(callbacks)
if '__context_checker' in options:
_checker = options['__context_checker']
async_options['_context_checker'] = path_to_reference(_checker)
if '__process_results' in options:
_processor = options['__process_results']
async_options['_process_results'] = path_to_reference(_processor)
return async_options | [
"def",
"decode_async_options",
"(",
"options",
")",
":",
"async_options",
"=",
"copy",
".",
"deepcopy",
"(",
"options",
")",
"# JSON don't like datetimes.",
"eta",
"=",
"async_options",
".",
"get",
"(",
"'task_args'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'e... | Decode Async options from JSON decoding. | [
"Decode",
"Async",
"options",
"from",
"JSON",
"decoding",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L625-L648 | train | 50,159 |
Workiva/furious | furious/async.py | defaults | def defaults(**options):
"""Set default Async options on the function decorated.
Note: you must pass the decorated function by reference, not as a
"path.string.to.function" for this to have any effect.
"""
_check_options(options)
def real_decorator(function):
function._async_options = options
@wraps(function)
def wrapper(*args, **kwargs):
return function(*args, **kwargs)
return wrapper
return real_decorator | python | def defaults(**options):
"""Set default Async options on the function decorated.
Note: you must pass the decorated function by reference, not as a
"path.string.to.function" for this to have any effect.
"""
_check_options(options)
def real_decorator(function):
function._async_options = options
@wraps(function)
def wrapper(*args, **kwargs):
return function(*args, **kwargs)
return wrapper
return real_decorator | [
"def",
"defaults",
"(",
"*",
"*",
"options",
")",
":",
"_check_options",
"(",
"options",
")",
"def",
"real_decorator",
"(",
"function",
")",
":",
"function",
".",
"_async_options",
"=",
"options",
"@",
"wraps",
"(",
"function",
")",
"def",
"wrapper",
"(",
... | Set default Async options on the function decorated.
Note: you must pass the decorated function by reference, not as a
"path.string.to.function" for this to have any effect. | [
"Set",
"default",
"Async",
"options",
"on",
"the",
"function",
"decorated",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L651-L667 | train | 50,160 |
Workiva/furious | furious/async.py | Async._persist_result | def _persist_result(self):
"""Store this Async's result in persistent storage."""
self._prepare_persistence_engine()
return self._persistence_engine.store_async_result(
self.id, self.result) | python | def _persist_result(self):
"""Store this Async's result in persistent storage."""
self._prepare_persistence_engine()
return self._persistence_engine.store_async_result(
self.id, self.result) | [
"def",
"_persist_result",
"(",
"self",
")",
":",
"self",
".",
"_prepare_persistence_engine",
"(",
")",
"return",
"self",
".",
"_persistence_engine",
".",
"store_async_result",
"(",
"self",
".",
"id",
",",
"self",
".",
"result",
")"
] | Store this Async's result in persistent storage. | [
"Store",
"this",
"Async",
"s",
"result",
"in",
"persistent",
"storage",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L169-L174 | train | 50,161 |
Workiva/furious | furious/async.py | Async._initialize_recursion_depth | def _initialize_recursion_depth(self):
"""Ensure recursion info is initialized, if not, initialize it."""
from furious.context import get_current_async
recursion_options = self._options.get('_recursion', {})
current_depth = recursion_options.get('current', 0)
max_depth = recursion_options.get('max', MAX_DEPTH)
try:
executing_async = get_current_async()
# If this async is within an executing async, use the depth off
# that async. Otherwise use the depth set in the async's options.
current_depth = executing_async.recursion_depth
# If max_depth does not equal MAX_DEPTH, it is custom. Otherwise
# use the max_depth from the containing async.
if max_depth == MAX_DEPTH:
executing_options = executing_async.get_options().get(
'_recursion', {})
max_depth = executing_options.get('max', max_depth)
except errors.NotInContextError:
# This Async is not being constructed inside an executing Async.
pass
# Store the recursion info.
self.update_options(_recursion={'current': current_depth,
'max': max_depth}) | python | def _initialize_recursion_depth(self):
"""Ensure recursion info is initialized, if not, initialize it."""
from furious.context import get_current_async
recursion_options = self._options.get('_recursion', {})
current_depth = recursion_options.get('current', 0)
max_depth = recursion_options.get('max', MAX_DEPTH)
try:
executing_async = get_current_async()
# If this async is within an executing async, use the depth off
# that async. Otherwise use the depth set in the async's options.
current_depth = executing_async.recursion_depth
# If max_depth does not equal MAX_DEPTH, it is custom. Otherwise
# use the max_depth from the containing async.
if max_depth == MAX_DEPTH:
executing_options = executing_async.get_options().get(
'_recursion', {})
max_depth = executing_options.get('max', max_depth)
except errors.NotInContextError:
# This Async is not being constructed inside an executing Async.
pass
# Store the recursion info.
self.update_options(_recursion={'current': current_depth,
'max': max_depth}) | [
"def",
"_initialize_recursion_depth",
"(",
"self",
")",
":",
"from",
"furious",
".",
"context",
"import",
"get_current_async",
"recursion_options",
"=",
"self",
".",
"_options",
".",
"get",
"(",
"'_recursion'",
",",
"{",
"}",
")",
"current_depth",
"=",
"recursio... | Ensure recursion info is initialized, if not, initialize it. | [
"Ensure",
"recursion",
"info",
"is",
"initialized",
"if",
"not",
"initialize",
"it",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L208-L237 | train | 50,162 |
Workiva/furious | furious/async.py | Async.check_recursion_depth | def check_recursion_depth(self):
"""Check recursion depth, raise AsyncRecursionError if too deep."""
from furious.async import MAX_DEPTH
recursion_options = self._options.get('_recursion', {})
max_depth = recursion_options.get('max', MAX_DEPTH)
# Check if recursion check has been disabled, then check depth.
if (max_depth != DISABLE_RECURSION_CHECK and
self.recursion_depth > max_depth):
raise errors.AsyncRecursionError('Max recursion depth reached.') | python | def check_recursion_depth(self):
"""Check recursion depth, raise AsyncRecursionError if too deep."""
from furious.async import MAX_DEPTH
recursion_options = self._options.get('_recursion', {})
max_depth = recursion_options.get('max', MAX_DEPTH)
# Check if recursion check has been disabled, then check depth.
if (max_depth != DISABLE_RECURSION_CHECK and
self.recursion_depth > max_depth):
raise errors.AsyncRecursionError('Max recursion depth reached.') | [
"def",
"check_recursion_depth",
"(",
"self",
")",
":",
"from",
"furious",
".",
"async",
"import",
"MAX_DEPTH",
"recursion_options",
"=",
"self",
".",
"_options",
".",
"get",
"(",
"'_recursion'",
",",
"{",
"}",
")",
"max_depth",
"=",
"recursion_options",
".",
... | Check recursion depth, raise AsyncRecursionError if too deep. | [
"Check",
"recursion",
"depth",
"raise",
"AsyncRecursionError",
"if",
"too",
"deep",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L239-L249 | train | 50,163 |
Workiva/furious | furious/async.py | Async._update_job | def _update_job(self, target, args, kwargs):
"""Specify the function this async job is to execute when run."""
target_path, options = get_function_path_and_options(target)
assert isinstance(args, (tuple, list)) or args is None
assert isinstance(kwargs, dict) or kwargs is None
if options:
self.update_options(**options)
self._options['job'] = (target_path, args, kwargs) | python | def _update_job(self, target, args, kwargs):
"""Specify the function this async job is to execute when run."""
target_path, options = get_function_path_and_options(target)
assert isinstance(args, (tuple, list)) or args is None
assert isinstance(kwargs, dict) or kwargs is None
if options:
self.update_options(**options)
self._options['job'] = (target_path, args, kwargs) | [
"def",
"_update_job",
"(",
"self",
",",
"target",
",",
"args",
",",
"kwargs",
")",
":",
"target_path",
",",
"options",
"=",
"get_function_path_and_options",
"(",
"target",
")",
"assert",
"isinstance",
"(",
"args",
",",
"(",
"tuple",
",",
"list",
")",
")",
... | Specify the function this async job is to execute when run. | [
"Specify",
"the",
"function",
"this",
"async",
"job",
"is",
"to",
"execute",
"when",
"run",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L251-L261 | train | 50,164 |
Workiva/furious | furious/async.py | Async.set_execution_context | def set_execution_context(self, execution_context):
"""Set the ExecutionContext this async is executing under."""
if self._execution_context:
raise errors.AlreadyInContextError
self._execution_context = execution_context | python | def set_execution_context(self, execution_context):
"""Set the ExecutionContext this async is executing under."""
if self._execution_context:
raise errors.AlreadyInContextError
self._execution_context = execution_context | [
"def",
"set_execution_context",
"(",
"self",
",",
"execution_context",
")",
":",
"if",
"self",
".",
"_execution_context",
":",
"raise",
"errors",
".",
"AlreadyInContextError",
"self",
".",
"_execution_context",
"=",
"execution_context"
] | Set the ExecutionContext this async is executing under. | [
"Set",
"the",
"ExecutionContext",
"this",
"async",
"is",
"executing",
"under",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L263-L268 | train | 50,165 |
Workiva/furious | furious/async.py | Async.update_options | def update_options(self, **options):
"""Safely update this async job's configuration options."""
_check_options(options)
if 'persistence_engine' in options:
options['persistence_engine'] = reference_to_path(
options['persistence_engine'])
if 'id' in options:
self._id = options['id']
self._options.update(options) | python | def update_options(self, **options):
"""Safely update this async job's configuration options."""
_check_options(options)
if 'persistence_engine' in options:
options['persistence_engine'] = reference_to_path(
options['persistence_engine'])
if 'id' in options:
self._id = options['id']
self._options.update(options) | [
"def",
"update_options",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"_check_options",
"(",
"options",
")",
"if",
"'persistence_engine'",
"in",
"options",
":",
"options",
"[",
"'persistence_engine'",
"]",
"=",
"reference_to_path",
"(",
"options",
"[",
"'p... | Safely update this async job's configuration options. | [
"Safely",
"update",
"this",
"async",
"job",
"s",
"configuration",
"options",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L274-L286 | train | 50,166 |
Workiva/furious | furious/async.py | Async.to_task | def to_task(self):
"""Return a task object representing this async job."""
from google.appengine.api.taskqueue import Task
from google.appengine.api.taskqueue import TaskRetryOptions
self._increment_recursion_level()
self.check_recursion_depth()
url = "%s/%s" % (ASYNC_ENDPOINT, self.function_path)
kwargs = {
'url': url,
'headers': self.get_headers().copy(),
'payload': json.dumps(self.to_dict())
}
kwargs.update(copy.deepcopy(self.get_task_args()))
# Set task_retry_limit
retry_options = copy.deepcopy(DEFAULT_RETRY_OPTIONS)
retry_options.update(kwargs.pop('retry_options', {}))
kwargs['retry_options'] = TaskRetryOptions(**retry_options)
return Task(**kwargs) | python | def to_task(self):
"""Return a task object representing this async job."""
from google.appengine.api.taskqueue import Task
from google.appengine.api.taskqueue import TaskRetryOptions
self._increment_recursion_level()
self.check_recursion_depth()
url = "%s/%s" % (ASYNC_ENDPOINT, self.function_path)
kwargs = {
'url': url,
'headers': self.get_headers().copy(),
'payload': json.dumps(self.to_dict())
}
kwargs.update(copy.deepcopy(self.get_task_args()))
# Set task_retry_limit
retry_options = copy.deepcopy(DEFAULT_RETRY_OPTIONS)
retry_options.update(kwargs.pop('retry_options', {}))
kwargs['retry_options'] = TaskRetryOptions(**retry_options)
return Task(**kwargs) | [
"def",
"to_task",
"(",
"self",
")",
":",
"from",
"google",
".",
"appengine",
".",
"api",
".",
"taskqueue",
"import",
"Task",
"from",
"google",
".",
"appengine",
".",
"api",
".",
"taskqueue",
"import",
"TaskRetryOptions",
"self",
".",
"_increment_recursion_leve... | Return a task object representing this async job. | [
"Return",
"a",
"task",
"object",
"representing",
"this",
"async",
"job",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L305-L327 | train | 50,167 |
Workiva/furious | furious/async.py | Async.start | def start(self, transactional=False, async=False, rpc=None):
"""Insert the task into the requested queue, 'default' if non given.
If a TransientError is hit the task will re-insert the task. If a
TaskAlreadyExistsError or TombstonedTaskError is hit the task will
silently fail.
If the async flag is set, then the add will be done asynchronously and
the return value will be the rpc object; otherwise the return value is
the task itself. If the rpc kwarg is provided, but we're not in async
mode, then it is ignored.
"""
from google.appengine.api import taskqueue
task = self.to_task()
queue = taskqueue.Queue(name=self.get_queue())
retry_transient = self._options.get('retry_transient_errors', True)
retry_delay = self._options.get('retry_delay', RETRY_SLEEP_SECS)
add = queue.add
if async:
add = partial(queue.add_async, rpc=rpc)
try:
ret = add(task, transactional=transactional)
except taskqueue.TransientError:
# Always re-raise for transactional insert, or if specified by
# options.
if transactional or not retry_transient:
raise
time.sleep(retry_delay)
ret = add(task, transactional=transactional)
except (taskqueue.TaskAlreadyExistsError,
taskqueue.TombstonedTaskError):
return
# TODO: Return a "result" object.
return ret | python | def start(self, transactional=False, async=False, rpc=None):
"""Insert the task into the requested queue, 'default' if non given.
If a TransientError is hit the task will re-insert the task. If a
TaskAlreadyExistsError or TombstonedTaskError is hit the task will
silently fail.
If the async flag is set, then the add will be done asynchronously and
the return value will be the rpc object; otherwise the return value is
the task itself. If the rpc kwarg is provided, but we're not in async
mode, then it is ignored.
"""
from google.appengine.api import taskqueue
task = self.to_task()
queue = taskqueue.Queue(name=self.get_queue())
retry_transient = self._options.get('retry_transient_errors', True)
retry_delay = self._options.get('retry_delay', RETRY_SLEEP_SECS)
add = queue.add
if async:
add = partial(queue.add_async, rpc=rpc)
try:
ret = add(task, transactional=transactional)
except taskqueue.TransientError:
# Always re-raise for transactional insert, or if specified by
# options.
if transactional or not retry_transient:
raise
time.sleep(retry_delay)
ret = add(task, transactional=transactional)
except (taskqueue.TaskAlreadyExistsError,
taskqueue.TombstonedTaskError):
return
# TODO: Return a "result" object.
return ret | [
"def",
"start",
"(",
"self",
",",
"transactional",
"=",
"False",
",",
"async",
"=",
"False",
",",
"rpc",
"=",
"None",
")",
":",
"from",
"google",
".",
"appengine",
".",
"api",
"import",
"taskqueue",
"task",
"=",
"self",
".",
"to_task",
"(",
")",
"que... | Insert the task into the requested queue, 'default' if non given.
If a TransientError is hit the task will re-insert the task. If a
TaskAlreadyExistsError or TombstonedTaskError is hit the task will
silently fail.
If the async flag is set, then the add will be done asynchronously and
the return value will be the rpc object; otherwise the return value is
the task itself. If the rpc kwarg is provided, but we're not in async
mode, then it is ignored. | [
"Insert",
"the",
"task",
"into",
"the",
"requested",
"queue",
"default",
"if",
"non",
"given",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L329-L368 | train | 50,168 |
Workiva/furious | furious/async.py | Async.from_dict | def from_dict(cls, async):
"""Return an async job from a dict output by Async.to_dict."""
async_options = decode_async_options(async)
target, args, kwargs = async_options.pop('job')
return cls(target, args, kwargs, **async_options) | python | def from_dict(cls, async):
"""Return an async job from a dict output by Async.to_dict."""
async_options = decode_async_options(async)
target, args, kwargs = async_options.pop('job')
return cls(target, args, kwargs, **async_options) | [
"def",
"from_dict",
"(",
"cls",
",",
"async",
")",
":",
"async_options",
"=",
"decode_async_options",
"(",
"async",
")",
"target",
",",
"args",
",",
"kwargs",
"=",
"async_options",
".",
"pop",
"(",
"'job'",
")",
"return",
"cls",
"(",
"target",
",",
"args... | Return an async job from a dict output by Async.to_dict. | [
"Return",
"an",
"async",
"job",
"from",
"a",
"dict",
"output",
"by",
"Async",
".",
"to_dict",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L381-L387 | train | 50,169 |
Workiva/furious | furious/async.py | Async._prepare_persistence_engine | def _prepare_persistence_engine(self):
"""Load the specified persistence engine, or the default if none is
set.
"""
if self._persistence_engine:
return
persistence_engine = self._options.get('persistence_engine')
if persistence_engine:
self._persistence_engine = path_to_reference(persistence_engine)
return
from furious.config import get_default_persistence_engine
self._persistence_engine = get_default_persistence_engine() | python | def _prepare_persistence_engine(self):
"""Load the specified persistence engine, or the default if none is
set.
"""
if self._persistence_engine:
return
persistence_engine = self._options.get('persistence_engine')
if persistence_engine:
self._persistence_engine = path_to_reference(persistence_engine)
return
from furious.config import get_default_persistence_engine
self._persistence_engine = get_default_persistence_engine() | [
"def",
"_prepare_persistence_engine",
"(",
"self",
")",
":",
"if",
"self",
".",
"_persistence_engine",
":",
"return",
"persistence_engine",
"=",
"self",
".",
"_options",
".",
"get",
"(",
"'persistence_engine'",
")",
"if",
"persistence_engine",
":",
"self",
".",
... | Load the specified persistence engine, or the default if none is
set. | [
"Load",
"the",
"specified",
"persistence",
"engine",
"or",
"the",
"default",
"if",
"none",
"is",
"set",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L389-L403 | train | 50,170 |
Workiva/furious | furious/async.py | Async._get_context_id | def _get_context_id(self):
"""If this async is in a context set the context id."""
from furious.context import get_current_context
context_id = self._options.get('context_id')
if context_id:
return context_id
try:
context = get_current_context()
except errors.NotInContextError:
context = None
self.update_options(context_id=None)
if context:
context_id = context.id
self.update_options(context_id=context_id)
return context_id | python | def _get_context_id(self):
"""If this async is in a context set the context id."""
from furious.context import get_current_context
context_id = self._options.get('context_id')
if context_id:
return context_id
try:
context = get_current_context()
except errors.NotInContextError:
context = None
self.update_options(context_id=None)
if context:
context_id = context.id
self.update_options(context_id=context_id)
return context_id | [
"def",
"_get_context_id",
"(",
"self",
")",
":",
"from",
"furious",
".",
"context",
"import",
"get_current_context",
"context_id",
"=",
"self",
".",
"_options",
".",
"get",
"(",
"'context_id'",
")",
"if",
"context_id",
":",
"return",
"context_id",
"try",
":",
... | If this async is in a context set the context id. | [
"If",
"this",
"async",
"is",
"in",
"a",
"context",
"set",
"the",
"context",
"id",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L405-L425 | train | 50,171 |
Workiva/furious | furious/async.py | Async.full_id | def full_id(self):
"""Return the full_id for this Async. Consists of the parent id, id and
context id.
"""
full_id = ""
if self.parent_id:
full_id = ":".join([self.parent_id, self.id])
else:
full_id = self.id
if self.context_id:
full_id = "|".join([full_id, self.context_id])
return full_id | python | def full_id(self):
"""Return the full_id for this Async. Consists of the parent id, id and
context id.
"""
full_id = ""
if self.parent_id:
full_id = ":".join([self.parent_id, self.id])
else:
full_id = self.id
if self.context_id:
full_id = "|".join([full_id, self.context_id])
return full_id | [
"def",
"full_id",
"(",
"self",
")",
":",
"full_id",
"=",
"\"\"",
"if",
"self",
".",
"parent_id",
":",
"full_id",
"=",
"\":\"",
".",
"join",
"(",
"[",
"self",
".",
"parent_id",
",",
"self",
".",
"id",
"]",
")",
"else",
":",
"full_id",
"=",
"self",
... | Return the full_id for this Async. Consists of the parent id, id and
context id. | [
"Return",
"the",
"full_id",
"for",
"this",
"Async",
".",
"Consists",
"of",
"the",
"parent",
"id",
"id",
"and",
"context",
"id",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L477-L491 | train | 50,172 |
Workiva/furious | furious/async.py | Async._increment_recursion_level | def _increment_recursion_level(self):
"""Increment current_depth based on either defaults or the enclosing
Async.
"""
# Update the recursion info. This is done so that if an async created
# outside an executing context, or one previously created is later
# loaded from storage, that the "current" setting is correctly set.
self._initialize_recursion_depth()
recursion_options = self._options.get('_recursion', {})
current_depth = recursion_options.get('current', 0) + 1
max_depth = recursion_options.get('max', MAX_DEPTH)
# Increment and store
self.update_options(_recursion={'current': current_depth,
'max': max_depth}) | python | def _increment_recursion_level(self):
"""Increment current_depth based on either defaults or the enclosing
Async.
"""
# Update the recursion info. This is done so that if an async created
# outside an executing context, or one previously created is later
# loaded from storage, that the "current" setting is correctly set.
self._initialize_recursion_depth()
recursion_options = self._options.get('_recursion', {})
current_depth = recursion_options.get('current', 0) + 1
max_depth = recursion_options.get('max', MAX_DEPTH)
# Increment and store
self.update_options(_recursion={'current': current_depth,
'max': max_depth}) | [
"def",
"_increment_recursion_level",
"(",
"self",
")",
":",
"# Update the recursion info. This is done so that if an async created",
"# outside an executing context, or one previously created is later",
"# loaded from storage, that the \"current\" setting is correctly set.",
"self",
".",
"_in... | Increment current_depth based on either defaults or the enclosing
Async. | [
"Increment",
"current_depth",
"based",
"on",
"either",
"defaults",
"or",
"the",
"enclosing",
"Async",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L497-L512 | train | 50,173 |
Workiva/furious | furious/async.py | Async.context_id | def context_id(self):
"""Return this Async's Context Id if it exists."""
if not self._context_id:
self._context_id = self._get_context_id()
self.update_options(context_id=self._context_id)
return self._context_id | python | def context_id(self):
"""Return this Async's Context Id if it exists."""
if not self._context_id:
self._context_id = self._get_context_id()
self.update_options(context_id=self._context_id)
return self._context_id | [
"def",
"context_id",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_context_id",
":",
"self",
".",
"_context_id",
"=",
"self",
".",
"_get_context_id",
"(",
")",
"self",
".",
"update_options",
"(",
"context_id",
"=",
"self",
".",
"_context_id",
")",
"... | Return this Async's Context Id if it exists. | [
"Return",
"this",
"Async",
"s",
"Context",
"Id",
"if",
"it",
"exists",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L515-L521 | train | 50,174 |
Workiva/furious | furious/async.py | AsyncResult._payload_to_dict | def _payload_to_dict(self):
"""When an error status the payload is holding an AsyncException that
is converted to a serializable dict.
"""
if self.status != self.ERROR or not self.payload:
return self.payload
import traceback
return {
"error": self.payload.error,
"args": self.payload.args,
"traceback": traceback.format_exception(*self.payload.traceback)
} | python | def _payload_to_dict(self):
"""When an error status the payload is holding an AsyncException that
is converted to a serializable dict.
"""
if self.status != self.ERROR or not self.payload:
return self.payload
import traceback
return {
"error": self.payload.error,
"args": self.payload.args,
"traceback": traceback.format_exception(*self.payload.traceback)
} | [
"def",
"_payload_to_dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"!=",
"self",
".",
"ERROR",
"or",
"not",
"self",
".",
"payload",
":",
"return",
"self",
".",
"payload",
"import",
"traceback",
"return",
"{",
"\"error\"",
":",
"self",
".",
... | When an error status the payload is holding an AsyncException that
is converted to a serializable dict. | [
"When",
"an",
"error",
"status",
"the",
"payload",
"is",
"holding",
"an",
"AsyncException",
"that",
"is",
"converted",
"to",
"a",
"serializable",
"dict",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L574-L587 | train | 50,175 |
upsight/doctor | doctor/routing.py | put | def put(func: Callable, allowed_exceptions: List = None,
title: str = None, req_obj_type: Callable = None) -> HTTPMethod:
"""Returns a HTTPMethod instance to create a PUT route.
:see: :class:`~doctor.routing.HTTPMethod`
"""
return HTTPMethod('put', func, allowed_exceptions=allowed_exceptions,
title=title, req_obj_type=req_obj_type) | python | def put(func: Callable, allowed_exceptions: List = None,
title: str = None, req_obj_type: Callable = None) -> HTTPMethod:
"""Returns a HTTPMethod instance to create a PUT route.
:see: :class:`~doctor.routing.HTTPMethod`
"""
return HTTPMethod('put', func, allowed_exceptions=allowed_exceptions,
title=title, req_obj_type=req_obj_type) | [
"def",
"put",
"(",
"func",
":",
"Callable",
",",
"allowed_exceptions",
":",
"List",
"=",
"None",
",",
"title",
":",
"str",
"=",
"None",
",",
"req_obj_type",
":",
"Callable",
"=",
"None",
")",
"->",
"HTTPMethod",
":",
"return",
"HTTPMethod",
"(",
"'put'",... | Returns a HTTPMethod instance to create a PUT route.
:see: :class:`~doctor.routing.HTTPMethod` | [
"Returns",
"a",
"HTTPMethod",
"instance",
"to",
"create",
"a",
"PUT",
"route",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/routing.py#L78-L85 | train | 50,176 |
upsight/doctor | doctor/routing.py | create_http_method | def create_http_method(logic: Callable, http_method: str,
handle_http: Callable, before: Callable = None,
after: Callable = None) -> Callable:
"""Create a handler method to be used in a handler class.
:param callable logic: The underlying function to execute with the
parsed and validated parameters.
:param str http_method: HTTP method this will handle.
:param handle_http: The HTTP handler function that should be
used to wrap the logic functions.
:param before: A function to be called before the logic function associated
with the route.
:param after: A function to be called after the logic function associated
with the route.
:returns: A handler function.
"""
@functools.wraps(logic)
def fn(handler, *args, **kwargs):
if before is not None and callable(before):
before()
result = handle_http(handler, args, kwargs, logic)
if after is not None and callable(after):
after(result)
return result
return fn | python | def create_http_method(logic: Callable, http_method: str,
handle_http: Callable, before: Callable = None,
after: Callable = None) -> Callable:
"""Create a handler method to be used in a handler class.
:param callable logic: The underlying function to execute with the
parsed and validated parameters.
:param str http_method: HTTP method this will handle.
:param handle_http: The HTTP handler function that should be
used to wrap the logic functions.
:param before: A function to be called before the logic function associated
with the route.
:param after: A function to be called after the logic function associated
with the route.
:returns: A handler function.
"""
@functools.wraps(logic)
def fn(handler, *args, **kwargs):
if before is not None and callable(before):
before()
result = handle_http(handler, args, kwargs, logic)
if after is not None and callable(after):
after(result)
return result
return fn | [
"def",
"create_http_method",
"(",
"logic",
":",
"Callable",
",",
"http_method",
":",
"str",
",",
"handle_http",
":",
"Callable",
",",
"before",
":",
"Callable",
"=",
"None",
",",
"after",
":",
"Callable",
"=",
"None",
")",
"->",
"Callable",
":",
"@",
"fu... | Create a handler method to be used in a handler class.
:param callable logic: The underlying function to execute with the
parsed and validated parameters.
:param str http_method: HTTP method this will handle.
:param handle_http: The HTTP handler function that should be
used to wrap the logic functions.
:param before: A function to be called before the logic function associated
with the route.
:param after: A function to be called after the logic function associated
with the route.
:returns: A handler function. | [
"Create",
"a",
"handler",
"method",
"to",
"be",
"used",
"in",
"a",
"handler",
"class",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/routing.py#L88-L112 | train | 50,177 |
upsight/doctor | doctor/routing.py | get_handler_name | def get_handler_name(route: Route, logic: Callable) -> str:
"""Gets the handler name.
:param route: A Route instance.
:param logic: The logic function.
:returns: A handler class name.
"""
if route.handler_name is not None:
return route.handler_name
if any(m for m in route.methods if m.method.lower() == 'post'):
# A list endpoint
if route.heading != 'API':
return '{}ListHandler'.format(get_valid_class_name(route.heading))
return '{}ListHandler'.format(get_valid_class_name(logic.__name__))
if route.heading != 'API':
return '{}Handler'.format(get_valid_class_name(route.heading))
return '{}Handler'.format(get_valid_class_name(logic.__name__)) | python | def get_handler_name(route: Route, logic: Callable) -> str:
"""Gets the handler name.
:param route: A Route instance.
:param logic: The logic function.
:returns: A handler class name.
"""
if route.handler_name is not None:
return route.handler_name
if any(m for m in route.methods if m.method.lower() == 'post'):
# A list endpoint
if route.heading != 'API':
return '{}ListHandler'.format(get_valid_class_name(route.heading))
return '{}ListHandler'.format(get_valid_class_name(logic.__name__))
if route.heading != 'API':
return '{}Handler'.format(get_valid_class_name(route.heading))
return '{}Handler'.format(get_valid_class_name(logic.__name__)) | [
"def",
"get_handler_name",
"(",
"route",
":",
"Route",
",",
"logic",
":",
"Callable",
")",
"->",
"str",
":",
"if",
"route",
".",
"handler_name",
"is",
"not",
"None",
":",
"return",
"route",
".",
"handler_name",
"if",
"any",
"(",
"m",
"for",
"m",
"in",
... | Gets the handler name.
:param route: A Route instance.
:param logic: The logic function.
:returns: A handler class name. | [
"Gets",
"the",
"handler",
"name",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/routing.py#L143-L159 | train | 50,178 |
upsight/doctor | doctor/routing.py | create_routes | def create_routes(routes: Tuple[HTTPMethod], handle_http: Callable,
default_base_handler_class: Any) -> List[Tuple[str, Any]]:
"""Creates handler routes from the provided routes.
:param routes: A tuple containing the route and another tuple with
all http methods allowed for the route.
:param handle_http: The HTTP handler function that should be
used to wrap the logic functions.
:param default_base_handler_class: The default base handler class that
should be used.
:returns: A list of tuples containing the route and generated handler.
"""
created_routes = []
all_handler_names = []
for r in routes:
handler = None
if r.base_handler_class is not None:
base_handler_class = r.base_handler_class
else:
base_handler_class = default_base_handler_class
# Define the handler name. To prevent issues where auto-generated
# handler names conflict with existing, appending a number to the
# end of the hanlder name if it already exists.
handler_name = get_handler_name(r, r.methods[0].logic)
if handler_name in all_handler_names:
handler_name = '{}{}'.format(
handler_name, len(all_handler_names))
all_handler_names.append(handler_name)
for method in r.methods:
logic = method.logic
http_method = method.method
http_func = create_http_method(logic, http_method, handle_http,
before=r.before, after=r.after)
handler_methods_and_properties = {
'__name__': handler_name,
'_doctor_heading': r.heading,
'methods': set([http_method.upper()]),
http_method: http_func,
}
if handler is None:
handler = type(
handler_name, (base_handler_class,),
handler_methods_and_properties)
else:
setattr(handler, http_method, http_func)
# This is specific to Flask. Its MethodView class
# initializes the methods attribute in __new__ so we
# need to add all the other http methods we are defining
# on the handler after it gets created by type.
if hasattr(handler, 'methods'):
handler.methods.add(http_method.upper())
created_routes.append((r.route, handler))
return created_routes | python | def create_routes(routes: Tuple[HTTPMethod], handle_http: Callable,
default_base_handler_class: Any) -> List[Tuple[str, Any]]:
"""Creates handler routes from the provided routes.
:param routes: A tuple containing the route and another tuple with
all http methods allowed for the route.
:param handle_http: The HTTP handler function that should be
used to wrap the logic functions.
:param default_base_handler_class: The default base handler class that
should be used.
:returns: A list of tuples containing the route and generated handler.
"""
created_routes = []
all_handler_names = []
for r in routes:
handler = None
if r.base_handler_class is not None:
base_handler_class = r.base_handler_class
else:
base_handler_class = default_base_handler_class
# Define the handler name. To prevent issues where auto-generated
# handler names conflict with existing, appending a number to the
# end of the hanlder name if it already exists.
handler_name = get_handler_name(r, r.methods[0].logic)
if handler_name in all_handler_names:
handler_name = '{}{}'.format(
handler_name, len(all_handler_names))
all_handler_names.append(handler_name)
for method in r.methods:
logic = method.logic
http_method = method.method
http_func = create_http_method(logic, http_method, handle_http,
before=r.before, after=r.after)
handler_methods_and_properties = {
'__name__': handler_name,
'_doctor_heading': r.heading,
'methods': set([http_method.upper()]),
http_method: http_func,
}
if handler is None:
handler = type(
handler_name, (base_handler_class,),
handler_methods_and_properties)
else:
setattr(handler, http_method, http_func)
# This is specific to Flask. Its MethodView class
# initializes the methods attribute in __new__ so we
# need to add all the other http methods we are defining
# on the handler after it gets created by type.
if hasattr(handler, 'methods'):
handler.methods.add(http_method.upper())
created_routes.append((r.route, handler))
return created_routes | [
"def",
"create_routes",
"(",
"routes",
":",
"Tuple",
"[",
"HTTPMethod",
"]",
",",
"handle_http",
":",
"Callable",
",",
"default_base_handler_class",
":",
"Any",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"created_routes",
"=",
... | Creates handler routes from the provided routes.
:param routes: A tuple containing the route and another tuple with
all http methods allowed for the route.
:param handle_http: The HTTP handler function that should be
used to wrap the logic functions.
:param default_base_handler_class: The default base handler class that
should be used.
:returns: A list of tuples containing the route and generated handler. | [
"Creates",
"handler",
"routes",
"from",
"the",
"provided",
"routes",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/routing.py#L162-L217 | train | 50,179 |
horejsek/python-sqlpuzzle | sqlpuzzle/_common/argsparser.py | parse_args | def parse_args(options={}, *args, **kwds):
"""
Parser of arguments.
dict options {
int min_items: Min of required items to fold one tuple. (default: 1)
int max_items: Count of items in one tuple. Last `max_items-min_items`
items is by default set to None. (default: 1)
bool allow_dict: Flag allowing dictionary as first (and only one)
argument or dictinary as **kwds. (default: False)
bool allow_list: Flag allowing list as first (and only one) argument.
(default: False)
}
Examples:
calling with min_items=1, max_items=2, allow_dict=False:
arg1, arg2 => ((arg1, None), (arg2, None))
(arg1a, arg1b), arg2 => ((arg1a, arg1b), arg2, None))
arg1=val1 => FAIL
{key1: val1} => FAIL
calling with min_items=2, max_items=3, allow_dict=True:
arg1, arg2 => ((arg1, arg2, None),)
arg1, arg2, arg3 => ((arg1, arg2, arg3),)
(arg1a, arg1b, arg1c) => ((arg1a, arg1b, arg1c),)
arg1=val1, arg2=val2 => ((arg1, val1, None), (arg2, val2, None))
{key1: val1, key2: val2} => ((key1, val1, None), (key2, val2, None))
(arg1a, arg1b), arg2a, arg2b => FAIL
"""
parser_options = ParserOptions(options)
parser_input = ParserInput(args, kwds)
parser = Parser(parser_options, parser_input)
parser.parse()
return parser.output_data | python | def parse_args(options={}, *args, **kwds):
"""
Parser of arguments.
dict options {
int min_items: Min of required items to fold one tuple. (default: 1)
int max_items: Count of items in one tuple. Last `max_items-min_items`
items is by default set to None. (default: 1)
bool allow_dict: Flag allowing dictionary as first (and only one)
argument or dictinary as **kwds. (default: False)
bool allow_list: Flag allowing list as first (and only one) argument.
(default: False)
}
Examples:
calling with min_items=1, max_items=2, allow_dict=False:
arg1, arg2 => ((arg1, None), (arg2, None))
(arg1a, arg1b), arg2 => ((arg1a, arg1b), arg2, None))
arg1=val1 => FAIL
{key1: val1} => FAIL
calling with min_items=2, max_items=3, allow_dict=True:
arg1, arg2 => ((arg1, arg2, None),)
arg1, arg2, arg3 => ((arg1, arg2, arg3),)
(arg1a, arg1b, arg1c) => ((arg1a, arg1b, arg1c),)
arg1=val1, arg2=val2 => ((arg1, val1, None), (arg2, val2, None))
{key1: val1, key2: val2} => ((key1, val1, None), (key2, val2, None))
(arg1a, arg1b), arg2a, arg2b => FAIL
"""
parser_options = ParserOptions(options)
parser_input = ParserInput(args, kwds)
parser = Parser(parser_options, parser_input)
parser.parse()
return parser.output_data | [
"def",
"parse_args",
"(",
"options",
"=",
"{",
"}",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"parser_options",
"=",
"ParserOptions",
"(",
"options",
")",
"parser_input",
"=",
"ParserInput",
"(",
"args",
",",
"kwds",
")",
"parser",
"=",
"Parse... | Parser of arguments.
dict options {
int min_items: Min of required items to fold one tuple. (default: 1)
int max_items: Count of items in one tuple. Last `max_items-min_items`
items is by default set to None. (default: 1)
bool allow_dict: Flag allowing dictionary as first (and only one)
argument or dictinary as **kwds. (default: False)
bool allow_list: Flag allowing list as first (and only one) argument.
(default: False)
}
Examples:
calling with min_items=1, max_items=2, allow_dict=False:
arg1, arg2 => ((arg1, None), (arg2, None))
(arg1a, arg1b), arg2 => ((arg1a, arg1b), arg2, None))
arg1=val1 => FAIL
{key1: val1} => FAIL
calling with min_items=2, max_items=3, allow_dict=True:
arg1, arg2 => ((arg1, arg2, None),)
arg1, arg2, arg3 => ((arg1, arg2, arg3),)
(arg1a, arg1b, arg1c) => ((arg1a, arg1b, arg1c),)
arg1=val1, arg2=val2 => ((arg1, val1, None), (arg2, val2, None))
{key1: val1, key2: val2} => ((key1, val1, None), (key2, val2, None))
(arg1a, arg1b), arg2a, arg2b => FAIL | [
"Parser",
"of",
"arguments",
"."
] | d3a42ed1b339b8eafddb8d2c28a3a5832b3998dd | https://github.com/horejsek/python-sqlpuzzle/blob/d3a42ed1b339b8eafddb8d2c28a3a5832b3998dd/sqlpuzzle/_common/argsparser.py#L7-L42 | train | 50,180 |
Workiva/furious | example/simple_workflow.py | simple_state_machine | def simple_state_machine():
"""Pick a number, if it is more than some cuttoff continue the chain."""
from random import random
from furious.async import Async
number = random()
logging.info('Generating a number... %s', number)
if number > 0.25:
logging.info('Continuing to do stuff.')
return Async(target=simple_state_machine)
return number | python | def simple_state_machine():
"""Pick a number, if it is more than some cuttoff continue the chain."""
from random import random
from furious.async import Async
number = random()
logging.info('Generating a number... %s', number)
if number > 0.25:
logging.info('Continuing to do stuff.')
return Async(target=simple_state_machine)
return number | [
"def",
"simple_state_machine",
"(",
")",
":",
"from",
"random",
"import",
"random",
"from",
"furious",
".",
"async",
"import",
"Async",
"number",
"=",
"random",
"(",
")",
"logging",
".",
"info",
"(",
"'Generating a number... %s'",
",",
"number",
")",
"if",
"... | Pick a number, if it is more than some cuttoff continue the chain. | [
"Pick",
"a",
"number",
"if",
"it",
"is",
"more",
"than",
"some",
"cuttoff",
"continue",
"the",
"chain",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/example/simple_workflow.py#L44-L57 | train | 50,181 |
TriOptima/tri.form | lib/tri/form/render.py | render_attrs | def render_attrs(attrs):
"""
Render HTML attributes, or return '' if no attributes needs to be rendered.
"""
if attrs is not None:
def parts():
for key, value in sorted(attrs.items()):
if value is None:
continue
if value is True:
yield '%s' % (key, )
continue
if key == 'class' and isinstance(value, dict):
if not value:
continue
value = render_class(value)
if key == 'style' and isinstance(value, dict):
if not value:
continue
value = render_style(value)
yield '%s="%s"' % (key, ('%s' % value).replace('"', '"'))
return mark_safe(' %s' % ' '.join(parts()))
return '' | python | def render_attrs(attrs):
"""
Render HTML attributes, or return '' if no attributes needs to be rendered.
"""
if attrs is not None:
def parts():
for key, value in sorted(attrs.items()):
if value is None:
continue
if value is True:
yield '%s' % (key, )
continue
if key == 'class' and isinstance(value, dict):
if not value:
continue
value = render_class(value)
if key == 'style' and isinstance(value, dict):
if not value:
continue
value = render_style(value)
yield '%s="%s"' % (key, ('%s' % value).replace('"', '"'))
return mark_safe(' %s' % ' '.join(parts()))
return '' | [
"def",
"render_attrs",
"(",
"attrs",
")",
":",
"if",
"attrs",
"is",
"not",
"None",
":",
"def",
"parts",
"(",
")",
":",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"attrs",
".",
"items",
"(",
")",
")",
":",
"if",
"value",
"is",
"None",
":",
... | Render HTML attributes, or return '' if no attributes needs to be rendered. | [
"Render",
"HTML",
"attributes",
"or",
"return",
"if",
"no",
"attributes",
"needs",
"to",
"be",
"rendered",
"."
] | 0c8efaac8fe113619932def1570befe11b634927 | https://github.com/TriOptima/tri.form/blob/0c8efaac8fe113619932def1570befe11b634927/lib/tri/form/render.py#L4-L26 | train | 50,182 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | context_completion_checker | def context_completion_checker(async):
"""Persist async marker and async the completion check"""
store_async_marker(async.id, async.result.status if async.result else -1)
logging.debug("Async check completion for: %s", async.context_id)
current_queue = _get_current_queue()
from furious.async import Async
logging.debug("Completion Check queue:%s", current_queue)
Async(_completion_checker, queue=current_queue,
args=(async.id, async.context_id)).start()
return True | python | def context_completion_checker(async):
"""Persist async marker and async the completion check"""
store_async_marker(async.id, async.result.status if async.result else -1)
logging.debug("Async check completion for: %s", async.context_id)
current_queue = _get_current_queue()
from furious.async import Async
logging.debug("Completion Check queue:%s", current_queue)
Async(_completion_checker, queue=current_queue,
args=(async.id, async.context_id)).start()
return True | [
"def",
"context_completion_checker",
"(",
"async",
")",
":",
"store_async_marker",
"(",
"async",
".",
"id",
",",
"async",
".",
"result",
".",
"status",
"if",
"async",
".",
"result",
"else",
"-",
"1",
")",
"logging",
".",
"debug",
"(",
"\"Async check completi... | Persist async marker and async the completion check | [
"Persist",
"async",
"marker",
"and",
"async",
"the",
"completion",
"check"
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L136-L148 | train | 50,183 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | _completion_checker | def _completion_checker(async_id, context_id):
"""Check if all Async jobs within a Context have been run."""
if not context_id:
logging.debug("Context for async %s does not exist", async_id)
return
context = FuriousContext.from_id(context_id)
marker = FuriousCompletionMarker.get_by_id(context_id)
if marker and marker.complete:
logging.info("Context %s already complete" % context_id)
return True
task_ids = context.task_ids
if async_id in task_ids:
task_ids.remove(async_id)
logging.debug("Loaded context.")
logging.debug(task_ids)
done, has_errors = _check_markers(task_ids)
if not done:
return False
_mark_context_complete(marker, context, has_errors)
return True | python | def _completion_checker(async_id, context_id):
"""Check if all Async jobs within a Context have been run."""
if not context_id:
logging.debug("Context for async %s does not exist", async_id)
return
context = FuriousContext.from_id(context_id)
marker = FuriousCompletionMarker.get_by_id(context_id)
if marker and marker.complete:
logging.info("Context %s already complete" % context_id)
return True
task_ids = context.task_ids
if async_id in task_ids:
task_ids.remove(async_id)
logging.debug("Loaded context.")
logging.debug(task_ids)
done, has_errors = _check_markers(task_ids)
if not done:
return False
_mark_context_complete(marker, context, has_errors)
return True | [
"def",
"_completion_checker",
"(",
"async_id",
",",
"context_id",
")",
":",
"if",
"not",
"context_id",
":",
"logging",
".",
"debug",
"(",
"\"Context for async %s does not exist\"",
",",
"async_id",
")",
"return",
"context",
"=",
"FuriousContext",
".",
"from_id",
"... | Check if all Async jobs within a Context have been run. | [
"Check",
"if",
"all",
"Async",
"jobs",
"within",
"a",
"Context",
"have",
"been",
"run",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L156-L184 | train | 50,184 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | _check_markers | def _check_markers(task_ids, offset=10):
"""Returns a flag for markers being found for the task_ids. If all task ids
have markers True will be returned. Otherwise it will return False as soon
as a None result is hit.
"""
shuffle(task_ids)
has_errors = False
for index in xrange(0, len(task_ids), offset):
keys = [ndb.Key(FuriousAsyncMarker, id)
for id in task_ids[index:index + offset]]
markers = ndb.get_multi(keys)
if not all(markers):
logging.debug("Not all Async's complete")
return False, None
# Did any of the aync's fail? Check the success property on the
# AsyncResult.
has_errors = not all((marker.success for marker in markers))
return True, has_errors | python | def _check_markers(task_ids, offset=10):
"""Returns a flag for markers being found for the task_ids. If all task ids
have markers True will be returned. Otherwise it will return False as soon
as a None result is hit.
"""
shuffle(task_ids)
has_errors = False
for index in xrange(0, len(task_ids), offset):
keys = [ndb.Key(FuriousAsyncMarker, id)
for id in task_ids[index:index + offset]]
markers = ndb.get_multi(keys)
if not all(markers):
logging.debug("Not all Async's complete")
return False, None
# Did any of the aync's fail? Check the success property on the
# AsyncResult.
has_errors = not all((marker.success for marker in markers))
return True, has_errors | [
"def",
"_check_markers",
"(",
"task_ids",
",",
"offset",
"=",
"10",
")",
":",
"shuffle",
"(",
"task_ids",
")",
"has_errors",
"=",
"False",
"for",
"index",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"task_ids",
")",
",",
"offset",
")",
":",
"keys",
"=... | Returns a flag for markers being found for the task_ids. If all task ids
have markers True will be returned. Otherwise it will return False as soon
as a None result is hit. | [
"Returns",
"a",
"flag",
"for",
"markers",
"being",
"found",
"for",
"the",
"task_ids",
".",
"If",
"all",
"task",
"ids",
"have",
"markers",
"True",
"will",
"be",
"returned",
".",
"Otherwise",
"it",
"will",
"return",
"False",
"as",
"soon",
"as",
"a",
"None"... | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L187-L210 | train | 50,185 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | _mark_context_complete | def _mark_context_complete(marker, context, has_errors):
"""Transactionally 'complete' the context."""
current = None
if marker:
current = marker.key.get()
if not current:
return False
if current and current.complete:
return False
current.complete = True
current.has_errors = has_errors
current.put()
# Kick off completion tasks.
_insert_post_complete_tasks(context)
return True | python | def _mark_context_complete(marker, context, has_errors):
"""Transactionally 'complete' the context."""
current = None
if marker:
current = marker.key.get()
if not current:
return False
if current and current.complete:
return False
current.complete = True
current.has_errors = has_errors
current.put()
# Kick off completion tasks.
_insert_post_complete_tasks(context)
return True | [
"def",
"_mark_context_complete",
"(",
"marker",
",",
"context",
",",
"has_errors",
")",
":",
"current",
"=",
"None",
"if",
"marker",
":",
"current",
"=",
"marker",
".",
"key",
".",
"get",
"(",
")",
"if",
"not",
"current",
":",
"return",
"False",
"if",
... | Transactionally 'complete' the context. | [
"Transactionally",
"complete",
"the",
"context",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L214-L235 | train | 50,186 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | _insert_post_complete_tasks | def _insert_post_complete_tasks(context):
"""Insert the event's asyncs and cleanup tasks."""
logging.debug("Context %s is complete.", context.id)
# Async event handlers
context.exec_event_handler('complete', transactional=True)
# Insert cleanup tasks
try:
# TODO: If tracking results we may not want to auto cleanup and instead
# wait until the results have been accessed.
from furious.async import Async
Async(_cleanup_markers, queue=CLEAN_QUEUE,
args=[context.id, context.task_ids],
task_args={'countdown': CLEAN_DELAY}).start()
except:
pass | python | def _insert_post_complete_tasks(context):
"""Insert the event's asyncs and cleanup tasks."""
logging.debug("Context %s is complete.", context.id)
# Async event handlers
context.exec_event_handler('complete', transactional=True)
# Insert cleanup tasks
try:
# TODO: If tracking results we may not want to auto cleanup and instead
# wait until the results have been accessed.
from furious.async import Async
Async(_cleanup_markers, queue=CLEAN_QUEUE,
args=[context.id, context.task_ids],
task_args={'countdown': CLEAN_DELAY}).start()
except:
pass | [
"def",
"_insert_post_complete_tasks",
"(",
"context",
")",
":",
"logging",
".",
"debug",
"(",
"\"Context %s is complete.\"",
",",
"context",
".",
"id",
")",
"# Async event handlers",
"context",
".",
"exec_event_handler",
"(",
"'complete'",
",",
"transactional",
"=",
... | Insert the event's asyncs and cleanup tasks. | [
"Insert",
"the",
"event",
"s",
"asyncs",
"and",
"cleanup",
"tasks",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L238-L255 | train | 50,187 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | _cleanup_markers | def _cleanup_markers(context_id, task_ids):
"""Delete the FuriousAsyncMarker entities corresponding to ids."""
logging.debug("Cleanup %d markers for Context %s",
len(task_ids), context_id)
# TODO: Handle exceptions and retries here.
delete_entities = [ndb.Key(FuriousAsyncMarker, id) for id in task_ids]
delete_entities.append(ndb.Key(FuriousCompletionMarker, context_id))
ndb.delete_multi(delete_entities)
logging.debug("Markers cleaned.") | python | def _cleanup_markers(context_id, task_ids):
"""Delete the FuriousAsyncMarker entities corresponding to ids."""
logging.debug("Cleanup %d markers for Context %s",
len(task_ids), context_id)
# TODO: Handle exceptions and retries here.
delete_entities = [ndb.Key(FuriousAsyncMarker, id) for id in task_ids]
delete_entities.append(ndb.Key(FuriousCompletionMarker, context_id))
ndb.delete_multi(delete_entities)
logging.debug("Markers cleaned.") | [
"def",
"_cleanup_markers",
"(",
"context_id",
",",
"task_ids",
")",
":",
"logging",
".",
"debug",
"(",
"\"Cleanup %d markers for Context %s\"",
",",
"len",
"(",
"task_ids",
")",
",",
"context_id",
")",
"# TODO: Handle exceptions and retries here.",
"delete_entities",
"=... | Delete the FuriousAsyncMarker entities corresponding to ids. | [
"Delete",
"the",
"FuriousAsyncMarker",
"entities",
"corresponding",
"to",
"ids",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L258-L270 | train | 50,188 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | store_context | def store_context(context):
"""Persist a furious.context.Context object to the datastore by loading it
into a FuriousContext ndb.Model.
"""
logging.debug("Attempting to store Context %s.", context.id)
entity = FuriousContext.from_context(context)
# TODO: Handle exceptions and retries here.
marker = FuriousCompletionMarker(id=context.id)
key, _ = ndb.put_multi((entity, marker))
logging.debug("Stored Context with key: %s.", key)
return key | python | def store_context(context):
"""Persist a furious.context.Context object to the datastore by loading it
into a FuriousContext ndb.Model.
"""
logging.debug("Attempting to store Context %s.", context.id)
entity = FuriousContext.from_context(context)
# TODO: Handle exceptions and retries here.
marker = FuriousCompletionMarker(id=context.id)
key, _ = ndb.put_multi((entity, marker))
logging.debug("Stored Context with key: %s.", key)
return key | [
"def",
"store_context",
"(",
"context",
")",
":",
"logging",
".",
"debug",
"(",
"\"Attempting to store Context %s.\"",
",",
"context",
".",
"id",
")",
"entity",
"=",
"FuriousContext",
".",
"from_context",
"(",
"context",
")",
"# TODO: Handle exceptions and retries her... | Persist a furious.context.Context object to the datastore by loading it
into a FuriousContext ndb.Model. | [
"Persist",
"a",
"furious",
".",
"context",
".",
"Context",
"object",
"to",
"the",
"datastore",
"by",
"loading",
"it",
"into",
"a",
"FuriousContext",
"ndb",
".",
"Model",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L279-L294 | train | 50,189 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | store_async_result | def store_async_result(async_id, async_result):
"""Persist the Async's result to the datastore."""
logging.debug("Storing result for %s", async_id)
key = FuriousAsyncMarker(
id=async_id, result=json.dumps(async_result.to_dict()),
status=async_result.status).put()
logging.debug("Setting Async result %s using marker: %s.", async_result,
key) | python | def store_async_result(async_id, async_result):
"""Persist the Async's result to the datastore."""
logging.debug("Storing result for %s", async_id)
key = FuriousAsyncMarker(
id=async_id, result=json.dumps(async_result.to_dict()),
status=async_result.status).put()
logging.debug("Setting Async result %s using marker: %s.", async_result,
key) | [
"def",
"store_async_result",
"(",
"async_id",
",",
"async_result",
")",
":",
"logging",
".",
"debug",
"(",
"\"Storing result for %s\"",
",",
"async_id",
")",
"key",
"=",
"FuriousAsyncMarker",
"(",
"id",
"=",
"async_id",
",",
"result",
"=",
"json",
".",
"dumps"... | Persist the Async's result to the datastore. | [
"Persist",
"the",
"Async",
"s",
"result",
"to",
"the",
"datastore",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L297-L307 | train | 50,190 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | store_async_marker | def store_async_marker(async_id, status):
"""Persist a marker indicating the Async ran to the datastore."""
logging.debug("Attempting to mark Async %s complete.", async_id)
# QUESTION: Do we trust if the marker had a flag result to just trust it?
marker = FuriousAsyncMarker.get_by_id(async_id)
if marker:
logging.debug("Marker already exists for %s.", async_id)
return
# TODO: Handle exceptions and retries here.
key = FuriousAsyncMarker(id=async_id, status=status).put()
logging.debug("Marked Async complete using marker: %s.", key) | python | def store_async_marker(async_id, status):
"""Persist a marker indicating the Async ran to the datastore."""
logging.debug("Attempting to mark Async %s complete.", async_id)
# QUESTION: Do we trust if the marker had a flag result to just trust it?
marker = FuriousAsyncMarker.get_by_id(async_id)
if marker:
logging.debug("Marker already exists for %s.", async_id)
return
# TODO: Handle exceptions and retries here.
key = FuriousAsyncMarker(id=async_id, status=status).put()
logging.debug("Marked Async complete using marker: %s.", key) | [
"def",
"store_async_marker",
"(",
"async_id",
",",
"status",
")",
":",
"logging",
".",
"debug",
"(",
"\"Attempting to mark Async %s complete.\"",
",",
"async_id",
")",
"# QUESTION: Do we trust if the marker had a flag result to just trust it?",
"marker",
"=",
"FuriousAsyncMarke... | Persist a marker indicating the Async ran to the datastore. | [
"Persist",
"a",
"marker",
"indicating",
"the",
"Async",
"ran",
"to",
"the",
"datastore",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L310-L325 | train | 50,191 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | iter_context_results | def iter_context_results(context, batch_size=10, task_cache=None):
"""Yield out the results found on the markers for the context task ids."""
for futures in iget_batches(context.task_ids, batch_size=batch_size):
for key, future in futures:
task = future.get_result()
if task_cache is not None:
task_cache[key.id()] = task
yield key.id(), task | python | def iter_context_results(context, batch_size=10, task_cache=None):
"""Yield out the results found on the markers for the context task ids."""
for futures in iget_batches(context.task_ids, batch_size=batch_size):
for key, future in futures:
task = future.get_result()
if task_cache is not None:
task_cache[key.id()] = task
yield key.id(), task | [
"def",
"iter_context_results",
"(",
"context",
",",
"batch_size",
"=",
"10",
",",
"task_cache",
"=",
"None",
")",
":",
"for",
"futures",
"in",
"iget_batches",
"(",
"context",
".",
"task_ids",
",",
"batch_size",
"=",
"batch_size",
")",
":",
"for",
"key",
",... | Yield out the results found on the markers for the context task ids. | [
"Yield",
"out",
"the",
"results",
"found",
"on",
"the",
"markers",
"for",
"the",
"context",
"task",
"ids",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L328-L338 | train | 50,192 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | iget_batches | def iget_batches(task_ids, batch_size=10):
"""Yield out a map of the keys and futures in batches of the batch size
passed in.
"""
make_key = lambda _id: ndb.Key(FuriousAsyncMarker, _id)
for keys in i_batch(imap(make_key, task_ids), batch_size):
yield izip(keys, ndb.get_multi_async(keys)) | python | def iget_batches(task_ids, batch_size=10):
"""Yield out a map of the keys and futures in batches of the batch size
passed in.
"""
make_key = lambda _id: ndb.Key(FuriousAsyncMarker, _id)
for keys in i_batch(imap(make_key, task_ids), batch_size):
yield izip(keys, ndb.get_multi_async(keys)) | [
"def",
"iget_batches",
"(",
"task_ids",
",",
"batch_size",
"=",
"10",
")",
":",
"make_key",
"=",
"lambda",
"_id",
":",
"ndb",
".",
"Key",
"(",
"FuriousAsyncMarker",
",",
"_id",
")",
"for",
"keys",
"in",
"i_batch",
"(",
"imap",
"(",
"make_key",
",",
"ta... | Yield out a map of the keys and futures in batches of the batch size
passed in. | [
"Yield",
"out",
"a",
"map",
"of",
"the",
"keys",
"and",
"futures",
"in",
"batches",
"of",
"the",
"batch",
"size",
"passed",
"in",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L341-L348 | train | 50,193 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | i_batch | def i_batch(items, size):
"""Generator that iteratively batches items to a max size and consumes the
items as each batch is yielded.
"""
for items_batch in iter(lambda: tuple(islice(items, size)),
tuple()):
yield items_batch | python | def i_batch(items, size):
"""Generator that iteratively batches items to a max size and consumes the
items as each batch is yielded.
"""
for items_batch in iter(lambda: tuple(islice(items, size)),
tuple()):
yield items_batch | [
"def",
"i_batch",
"(",
"items",
",",
"size",
")",
":",
"for",
"items_batch",
"in",
"iter",
"(",
"lambda",
":",
"tuple",
"(",
"islice",
"(",
"items",
",",
"size",
")",
")",
",",
"tuple",
"(",
")",
")",
":",
"yield",
"items_batch"
] | Generator that iteratively batches items to a max size and consumes the
items as each batch is yielded. | [
"Generator",
"that",
"iteratively",
"batches",
"items",
"to",
"a",
"max",
"size",
"and",
"consumes",
"the",
"items",
"as",
"each",
"batch",
"is",
"yielded",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L351-L357 | train | 50,194 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | FuriousContext.from_context | def from_context(cls, context):
"""Create a `cls` entity from a context."""
return cls(id=context.id, context=context.to_dict()) | python | def from_context(cls, context):
"""Create a `cls` entity from a context."""
return cls(id=context.id, context=context.to_dict()) | [
"def",
"from_context",
"(",
"cls",
",",
"context",
")",
":",
"return",
"cls",
"(",
"id",
"=",
"context",
".",
"id",
",",
"context",
"=",
"context",
".",
"to_dict",
"(",
")",
")"
] | Create a `cls` entity from a context. | [
"Create",
"a",
"cls",
"entity",
"from",
"a",
"context",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L50-L52 | train | 50,195 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | FuriousContext.from_id | def from_id(cls, id):
"""Load a `cls` entity and instantiate the Context it stores."""
from furious.context import Context
# TODO: Handle exceptions and retries here.
entity = cls.get_by_id(id)
if not entity:
raise FuriousContextNotFoundError(
"Context entity not found for: {}".format(id))
return Context.from_dict(entity.context) | python | def from_id(cls, id):
"""Load a `cls` entity and instantiate the Context it stores."""
from furious.context import Context
# TODO: Handle exceptions and retries here.
entity = cls.get_by_id(id)
if not entity:
raise FuriousContextNotFoundError(
"Context entity not found for: {}".format(id))
return Context.from_dict(entity.context) | [
"def",
"from_id",
"(",
"cls",
",",
"id",
")",
":",
"from",
"furious",
".",
"context",
"import",
"Context",
"# TODO: Handle exceptions and retries here.",
"entity",
"=",
"cls",
".",
"get_by_id",
"(",
"id",
")",
"if",
"not",
"entity",
":",
"raise",
"FuriousConte... | Load a `cls` entity and instantiate the Context it stores. | [
"Load",
"a",
"cls",
"entity",
"and",
"instantiate",
"the",
"Context",
"it",
"stores",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L55-L65 | train | 50,196 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | ContextResult.items | def items(self):
"""Yield the async reuslts for the context."""
for key, task in self._tasks:
if not (task and task.result):
yield key, None
else:
yield key, json.loads(task.result)["payload"] | python | def items(self):
"""Yield the async reuslts for the context."""
for key, task in self._tasks:
if not (task and task.result):
yield key, None
else:
yield key, json.loads(task.result)["payload"] | [
"def",
"items",
"(",
"self",
")",
":",
"for",
"key",
",",
"task",
"in",
"self",
".",
"_tasks",
":",
"if",
"not",
"(",
"task",
"and",
"task",
".",
"result",
")",
":",
"yield",
"key",
",",
"None",
"else",
":",
"yield",
"key",
",",
"json",
".",
"l... | Yield the async reuslts for the context. | [
"Yield",
"the",
"async",
"reuslts",
"for",
"the",
"context",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L112-L118 | train | 50,197 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | ContextResult.values | def values(self):
"""Yield the async reuslt values for the context."""
for _, task in self._tasks:
if not (task and task.result):
yield None
else:
yield json.loads(task.result)["payload"] | python | def values(self):
"""Yield the async reuslt values for the context."""
for _, task in self._tasks:
if not (task and task.result):
yield None
else:
yield json.loads(task.result)["payload"] | [
"def",
"values",
"(",
"self",
")",
":",
"for",
"_",
",",
"task",
"in",
"self",
".",
"_tasks",
":",
"if",
"not",
"(",
"task",
"and",
"task",
".",
"result",
")",
":",
"yield",
"None",
"else",
":",
"yield",
"json",
".",
"loads",
"(",
"task",
".",
... | Yield the async reuslt values for the context. | [
"Yield",
"the",
"async",
"reuslt",
"values",
"for",
"the",
"context",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L120-L126 | train | 50,198 |
aiidalab/aiidalab-widgets-base | aiidalab_widgets_base/display.py | aiidalab_display | def aiidalab_display(obj, downloadable=True, **kwargs):
"""Display AiiDA data types in Jupyter notebooks.
:param downloadable: If True, add link/button to download content of displayed AiiDA object.
Defers to IPython.display.display for any objects it does not recognize.
"""
from aiidalab_widgets_base import aiida_visualizers
try:
visualizer = getattr(aiida_visualizers, AIIDA_VISUALIZER_MAPPING[obj.type])
display(visualizer(obj, downloadable=downloadable), **kwargs)
except KeyError:
display(obj, **kwargs) | python | def aiidalab_display(obj, downloadable=True, **kwargs):
"""Display AiiDA data types in Jupyter notebooks.
:param downloadable: If True, add link/button to download content of displayed AiiDA object.
Defers to IPython.display.display for any objects it does not recognize.
"""
from aiidalab_widgets_base import aiida_visualizers
try:
visualizer = getattr(aiida_visualizers, AIIDA_VISUALIZER_MAPPING[obj.type])
display(visualizer(obj, downloadable=downloadable), **kwargs)
except KeyError:
display(obj, **kwargs) | [
"def",
"aiidalab_display",
"(",
"obj",
",",
"downloadable",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"aiidalab_widgets_base",
"import",
"aiida_visualizers",
"try",
":",
"visualizer",
"=",
"getattr",
"(",
"aiida_visualizers",
",",
"AIIDA_VISUALIZER_M... | Display AiiDA data types in Jupyter notebooks.
:param downloadable: If True, add link/button to download content of displayed AiiDA object.
Defers to IPython.display.display for any objects it does not recognize. | [
"Display",
"AiiDA",
"data",
"types",
"in",
"Jupyter",
"notebooks",
"."
] | 291a9b159eac902aee655862322670ec1b0cd5b1 | https://github.com/aiidalab/aiidalab-widgets-base/blob/291a9b159eac902aee655862322670ec1b0cd5b1/aiidalab_widgets_base/display.py#L14-L26 | train | 50,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.