repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
dwavesystems/dwave-cloud-client | dwave/cloud/client.py | Client.get_solver | def get_solver(self, name=None, refresh=False, **filters):
"""Load the configuration for a single solver.
Makes a blocking web call to `{endpoint}/solvers/remote/{solver_name}/`, where `{endpoint}`
is a URL configured for the client, and returns a :class:`.Solver` instance
that can be used to submit sampling problems to the D-Wave API and retrieve results.
Args:
name (str):
ID of the requested solver. ``None`` returns the default solver.
If default solver is not configured, ``None`` returns the first available
solver in ``Client``'s class (QPU/software/base).
**filters (keyword arguments, optional):
Dictionary of filters over features this solver has to have. For a list of
feature names and values, see: :meth:`~dwave.cloud.client.Client.get_solvers`.
order_by (callable/str, default='id'):
Solver sorting key function (or :class:`Solver` attribute name).
By default, solvers are sorted by ID/name.
refresh (bool):
Return solver from cache (if cached with ``get_solvers()``),
unless set to ``True``.
Returns:
:class:`.Solver`
Examples:
This example creates two solvers for a client instantiated from
a local system's auto-detected default configuration file, which configures
a connection to a D-Wave resource that provides two solvers. The first
uses the default solver, the second explicitly selects another solver.
>>> from dwave.cloud import Client
>>> client = Client.from_config()
>>> client.get_solvers() # doctest: +SKIP
[Solver(id='2000Q_ONLINE_SOLVER1'), Solver(id='2000Q_ONLINE_SOLVER2')]
>>> solver1 = client.get_solver() # doctest: +SKIP
>>> solver2 = client.get_solver(name='2000Q_ONLINE_SOLVER2') # doctest: +SKIP
>>> solver1.id # doctest: +SKIP
'2000Q_ONLINE_SOLVER1'
>>> solver2.id # doctest: +SKIP
'2000Q_ONLINE_SOLVER2'
>>> # code that uses client
>>> client.close() # doctest: +SKIP
"""
_LOGGER.debug("Requested a solver that best matches feature filters=%r", filters)
# backward compatibility: name as the first feature
if name is not None:
filters.setdefault('name', name)
# in absence of other filters, config/env solver filters/name are used
if not filters and self.default_solver:
filters = self.default_solver
# get the first solver that satisfies all filters
try:
_LOGGER.debug("Fetching solvers according to filters=%r", filters)
return self.get_solvers(refresh=refresh, **filters)[0]
except IndexError:
raise SolverNotFoundError("Solver with the requested features not available") | python | def get_solver(self, name=None, refresh=False, **filters):
"""Load the configuration for a single solver.
Makes a blocking web call to `{endpoint}/solvers/remote/{solver_name}/`, where `{endpoint}`
is a URL configured for the client, and returns a :class:`.Solver` instance
that can be used to submit sampling problems to the D-Wave API and retrieve results.
Args:
name (str):
ID of the requested solver. ``None`` returns the default solver.
If default solver is not configured, ``None`` returns the first available
solver in ``Client``'s class (QPU/software/base).
**filters (keyword arguments, optional):
Dictionary of filters over features this solver has to have. For a list of
feature names and values, see: :meth:`~dwave.cloud.client.Client.get_solvers`.
order_by (callable/str, default='id'):
Solver sorting key function (or :class:`Solver` attribute name).
By default, solvers are sorted by ID/name.
refresh (bool):
Return solver from cache (if cached with ``get_solvers()``),
unless set to ``True``.
Returns:
:class:`.Solver`
Examples:
This example creates two solvers for a client instantiated from
a local system's auto-detected default configuration file, which configures
a connection to a D-Wave resource that provides two solvers. The first
uses the default solver, the second explicitly selects another solver.
>>> from dwave.cloud import Client
>>> client = Client.from_config()
>>> client.get_solvers() # doctest: +SKIP
[Solver(id='2000Q_ONLINE_SOLVER1'), Solver(id='2000Q_ONLINE_SOLVER2')]
>>> solver1 = client.get_solver() # doctest: +SKIP
>>> solver2 = client.get_solver(name='2000Q_ONLINE_SOLVER2') # doctest: +SKIP
>>> solver1.id # doctest: +SKIP
'2000Q_ONLINE_SOLVER1'
>>> solver2.id # doctest: +SKIP
'2000Q_ONLINE_SOLVER2'
>>> # code that uses client
>>> client.close() # doctest: +SKIP
"""
_LOGGER.debug("Requested a solver that best matches feature filters=%r", filters)
# backward compatibility: name as the first feature
if name is not None:
filters.setdefault('name', name)
# in absence of other filters, config/env solver filters/name are used
if not filters and self.default_solver:
filters = self.default_solver
# get the first solver that satisfies all filters
try:
_LOGGER.debug("Fetching solvers according to filters=%r", filters)
return self.get_solvers(refresh=refresh, **filters)[0]
except IndexError:
raise SolverNotFoundError("Solver with the requested features not available") | [
"def",
"get_solver",
"(",
"self",
",",
"name",
"=",
"None",
",",
"refresh",
"=",
"False",
",",
"*",
"*",
"filters",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Requested a solver that best matches feature filters=%r\"",
",",
"filters",
")",
"# backward compatibility: name as the first feature",
"if",
"name",
"is",
"not",
"None",
":",
"filters",
".",
"setdefault",
"(",
"'name'",
",",
"name",
")",
"# in absence of other filters, config/env solver filters/name are used",
"if",
"not",
"filters",
"and",
"self",
".",
"default_solver",
":",
"filters",
"=",
"self",
".",
"default_solver",
"# get the first solver that satisfies all filters",
"try",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Fetching solvers according to filters=%r\"",
",",
"filters",
")",
"return",
"self",
".",
"get_solvers",
"(",
"refresh",
"=",
"refresh",
",",
"*",
"*",
"filters",
")",
"[",
"0",
"]",
"except",
"IndexError",
":",
"raise",
"SolverNotFoundError",
"(",
"\"Solver with the requested features not available\"",
")"
] | Load the configuration for a single solver.
Makes a blocking web call to `{endpoint}/solvers/remote/{solver_name}/`, where `{endpoint}`
is a URL configured for the client, and returns a :class:`.Solver` instance
that can be used to submit sampling problems to the D-Wave API and retrieve results.
Args:
name (str):
ID of the requested solver. ``None`` returns the default solver.
If default solver is not configured, ``None`` returns the first available
solver in ``Client``'s class (QPU/software/base).
**filters (keyword arguments, optional):
Dictionary of filters over features this solver has to have. For a list of
feature names and values, see: :meth:`~dwave.cloud.client.Client.get_solvers`.
order_by (callable/str, default='id'):
Solver sorting key function (or :class:`Solver` attribute name).
By default, solvers are sorted by ID/name.
refresh (bool):
Return solver from cache (if cached with ``get_solvers()``),
unless set to ``True``.
Returns:
:class:`.Solver`
Examples:
This example creates two solvers for a client instantiated from
a local system's auto-detected default configuration file, which configures
a connection to a D-Wave resource that provides two solvers. The first
uses the default solver, the second explicitly selects another solver.
>>> from dwave.cloud import Client
>>> client = Client.from_config()
>>> client.get_solvers() # doctest: +SKIP
[Solver(id='2000Q_ONLINE_SOLVER1'), Solver(id='2000Q_ONLINE_SOLVER2')]
>>> solver1 = client.get_solver() # doctest: +SKIP
>>> solver2 = client.get_solver(name='2000Q_ONLINE_SOLVER2') # doctest: +SKIP
>>> solver1.id # doctest: +SKIP
'2000Q_ONLINE_SOLVER1'
>>> solver2.id # doctest: +SKIP
'2000Q_ONLINE_SOLVER2'
>>> # code that uses client
>>> client.close() # doctest: +SKIP | [
"Load",
"the",
"configuration",
"for",
"a",
"single",
"solver",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L892-L955 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/client.py | Client._submit | def _submit(self, body, future):
"""Enqueue a problem for submission to the server.
This method is thread safe.
"""
self._submission_queue.put(self._submit.Message(body, future)) | python | def _submit(self, body, future):
"""Enqueue a problem for submission to the server.
This method is thread safe.
"""
self._submission_queue.put(self._submit.Message(body, future)) | [
"def",
"_submit",
"(",
"self",
",",
"body",
",",
"future",
")",
":",
"self",
".",
"_submission_queue",
".",
"put",
"(",
"self",
".",
"_submit",
".",
"Message",
"(",
"body",
",",
"future",
")",
")"
] | Enqueue a problem for submission to the server.
This method is thread safe. | [
"Enqueue",
"a",
"problem",
"for",
"submission",
"to",
"the",
"server",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L957-L962 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/client.py | Client._do_submit_problems | def _do_submit_problems(self):
"""Pull problems from the submission queue and submit them.
Note:
This method is always run inside of a daemon thread.
"""
try:
while True:
# Pull as many problems as we can, block on the first one,
# but once we have one problem, switch to non-blocking then
# submit without blocking again.
# `None` task is used to signal thread termination
item = self._submission_queue.get()
if item is None:
break
ready_problems = [item]
while len(ready_problems) < self._SUBMIT_BATCH_SIZE:
try:
ready_problems.append(self._submission_queue.get_nowait())
except queue.Empty:
break
# Submit the problems
_LOGGER.debug("Submitting %d problems", len(ready_problems))
body = '[' + ','.join(mess.body for mess in ready_problems) + ']'
try:
try:
response = self.session.post(posixpath.join(self.endpoint, 'problems/'), body)
localtime_of_response = epochnow()
except requests.exceptions.Timeout:
raise RequestTimeout
if response.status_code == 401:
raise SolverAuthenticationError()
response.raise_for_status()
message = response.json()
_LOGGER.debug("Finished submitting %d problems", len(ready_problems))
except BaseException as exception:
_LOGGER.debug("Submit failed for %d problems", len(ready_problems))
if not isinstance(exception, SolverAuthenticationError):
exception = IOError(exception)
for mess in ready_problems:
mess.future._set_error(exception, sys.exc_info())
self._submission_queue.task_done()
continue
# Pass on the information
for submission, res in zip(ready_problems, message):
submission.future._set_clock_diff(response, localtime_of_response)
self._handle_problem_status(res, submission.future)
self._submission_queue.task_done()
# this is equivalent to a yield to scheduler in other threading libraries
time.sleep(0)
except BaseException as err:
_LOGGER.exception(err) | python | def _do_submit_problems(self):
"""Pull problems from the submission queue and submit them.
Note:
This method is always run inside of a daemon thread.
"""
try:
while True:
# Pull as many problems as we can, block on the first one,
# but once we have one problem, switch to non-blocking then
# submit without blocking again.
# `None` task is used to signal thread termination
item = self._submission_queue.get()
if item is None:
break
ready_problems = [item]
while len(ready_problems) < self._SUBMIT_BATCH_SIZE:
try:
ready_problems.append(self._submission_queue.get_nowait())
except queue.Empty:
break
# Submit the problems
_LOGGER.debug("Submitting %d problems", len(ready_problems))
body = '[' + ','.join(mess.body for mess in ready_problems) + ']'
try:
try:
response = self.session.post(posixpath.join(self.endpoint, 'problems/'), body)
localtime_of_response = epochnow()
except requests.exceptions.Timeout:
raise RequestTimeout
if response.status_code == 401:
raise SolverAuthenticationError()
response.raise_for_status()
message = response.json()
_LOGGER.debug("Finished submitting %d problems", len(ready_problems))
except BaseException as exception:
_LOGGER.debug("Submit failed for %d problems", len(ready_problems))
if not isinstance(exception, SolverAuthenticationError):
exception = IOError(exception)
for mess in ready_problems:
mess.future._set_error(exception, sys.exc_info())
self._submission_queue.task_done()
continue
# Pass on the information
for submission, res in zip(ready_problems, message):
submission.future._set_clock_diff(response, localtime_of_response)
self._handle_problem_status(res, submission.future)
self._submission_queue.task_done()
# this is equivalent to a yield to scheduler in other threading libraries
time.sleep(0)
except BaseException as err:
_LOGGER.exception(err) | [
"def",
"_do_submit_problems",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"# Pull as many problems as we can, block on the first one,",
"# but once we have one problem, switch to non-blocking then",
"# submit without blocking again.",
"# `None` task is used to signal thread termination",
"item",
"=",
"self",
".",
"_submission_queue",
".",
"get",
"(",
")",
"if",
"item",
"is",
"None",
":",
"break",
"ready_problems",
"=",
"[",
"item",
"]",
"while",
"len",
"(",
"ready_problems",
")",
"<",
"self",
".",
"_SUBMIT_BATCH_SIZE",
":",
"try",
":",
"ready_problems",
".",
"append",
"(",
"self",
".",
"_submission_queue",
".",
"get_nowait",
"(",
")",
")",
"except",
"queue",
".",
"Empty",
":",
"break",
"# Submit the problems",
"_LOGGER",
".",
"debug",
"(",
"\"Submitting %d problems\"",
",",
"len",
"(",
"ready_problems",
")",
")",
"body",
"=",
"'['",
"+",
"','",
".",
"join",
"(",
"mess",
".",
"body",
"for",
"mess",
"in",
"ready_problems",
")",
"+",
"']'",
"try",
":",
"try",
":",
"response",
"=",
"self",
".",
"session",
".",
"post",
"(",
"posixpath",
".",
"join",
"(",
"self",
".",
"endpoint",
",",
"'problems/'",
")",
",",
"body",
")",
"localtime_of_response",
"=",
"epochnow",
"(",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
":",
"raise",
"RequestTimeout",
"if",
"response",
".",
"status_code",
"==",
"401",
":",
"raise",
"SolverAuthenticationError",
"(",
")",
"response",
".",
"raise_for_status",
"(",
")",
"message",
"=",
"response",
".",
"json",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Finished submitting %d problems\"",
",",
"len",
"(",
"ready_problems",
")",
")",
"except",
"BaseException",
"as",
"exception",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Submit failed for %d problems\"",
",",
"len",
"(",
"ready_problems",
")",
")",
"if",
"not",
"isinstance",
"(",
"exception",
",",
"SolverAuthenticationError",
")",
":",
"exception",
"=",
"IOError",
"(",
"exception",
")",
"for",
"mess",
"in",
"ready_problems",
":",
"mess",
".",
"future",
".",
"_set_error",
"(",
"exception",
",",
"sys",
".",
"exc_info",
"(",
")",
")",
"self",
".",
"_submission_queue",
".",
"task_done",
"(",
")",
"continue",
"# Pass on the information",
"for",
"submission",
",",
"res",
"in",
"zip",
"(",
"ready_problems",
",",
"message",
")",
":",
"submission",
".",
"future",
".",
"_set_clock_diff",
"(",
"response",
",",
"localtime_of_response",
")",
"self",
".",
"_handle_problem_status",
"(",
"res",
",",
"submission",
".",
"future",
")",
"self",
".",
"_submission_queue",
".",
"task_done",
"(",
")",
"# this is equivalent to a yield to scheduler in other threading libraries",
"time",
".",
"sleep",
"(",
"0",
")",
"except",
"BaseException",
"as",
"err",
":",
"_LOGGER",
".",
"exception",
"(",
"err",
")"
] | Pull problems from the submission queue and submit them.
Note:
This method is always run inside of a daemon thread. | [
"Pull",
"problems",
"from",
"the",
"submission",
"queue",
"and",
"submit",
"them",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L965-L1025 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/client.py | Client._handle_problem_status | def _handle_problem_status(self, message, future):
"""Handle the results of a problem submission or results request.
This method checks the status of the problem and puts it in the correct queue.
Args:
message (dict): Update message from the SAPI server wrt. this problem.
future `Future`: future corresponding to the problem
Note:
This method is always run inside of a daemon thread.
"""
try:
_LOGGER.trace("Handling response: %r", message)
_LOGGER.debug("Handling response for %s with status %s", message.get('id'), message.get('status'))
# Handle errors in batch mode
if 'error_code' in message and 'error_msg' in message:
raise SolverFailureError(message['error_msg'])
if 'status' not in message:
raise InvalidAPIResponseError("'status' missing in problem description response")
if 'id' not in message:
raise InvalidAPIResponseError("'id' missing in problem description response")
future.id = message['id']
future.remote_status = status = message['status']
# The future may not have the ID set yet
with future._single_cancel_lock:
# This handles the case where cancel has been called on a future
# before that future received the problem id
if future._cancel_requested:
if not future._cancel_sent and status == self.STATUS_PENDING:
# The problem has been canceled but the status says its still in queue
# try to cancel it
self._cancel(message['id'], future)
# If a cancel request could meaningfully be sent it has been now
future._cancel_sent = True
if not future.time_received and message.get('submitted_on'):
future.time_received = parse_datetime(message['submitted_on'])
if not future.time_solved and message.get('solved_on'):
future.time_solved = parse_datetime(message['solved_on'])
if not future.eta_min and message.get('earliest_estimated_completion'):
future.eta_min = parse_datetime(message['earliest_estimated_completion'])
if not future.eta_max and message.get('latest_estimated_completion'):
future.eta_max = parse_datetime(message['latest_estimated_completion'])
if status == self.STATUS_COMPLETE:
# TODO: find a better way to differentiate between
# `completed-on-submit` and `completed-on-poll`.
# Loading should happen only once, not every time when response
# doesn't contain 'answer'.
# If the message is complete, forward it to the future object
if 'answer' in message:
future._set_message(message)
# If the problem is complete, but we don't have the result data
# put the problem in the queue for loading results.
else:
self._load(future)
elif status in self.ANY_STATUS_ONGOING:
# If the response is pending add it to the queue.
self._poll(future)
elif status == self.STATUS_CANCELLED:
# If canceled return error
raise CanceledFutureError()
else:
# Return an error to the future object
errmsg = message.get('error_message', 'An unknown error has occurred.')
if 'solver is offline' in errmsg.lower():
raise SolverOfflineError(errmsg)
else:
raise SolverFailureError(errmsg)
except Exception as error:
# If there were any unhandled errors we need to release the
# lock in the future, otherwise deadlock occurs.
future._set_error(error, sys.exc_info()) | python | def _handle_problem_status(self, message, future):
"""Handle the results of a problem submission or results request.
This method checks the status of the problem and puts it in the correct queue.
Args:
message (dict): Update message from the SAPI server wrt. this problem.
future `Future`: future corresponding to the problem
Note:
This method is always run inside of a daemon thread.
"""
try:
_LOGGER.trace("Handling response: %r", message)
_LOGGER.debug("Handling response for %s with status %s", message.get('id'), message.get('status'))
# Handle errors in batch mode
if 'error_code' in message and 'error_msg' in message:
raise SolverFailureError(message['error_msg'])
if 'status' not in message:
raise InvalidAPIResponseError("'status' missing in problem description response")
if 'id' not in message:
raise InvalidAPIResponseError("'id' missing in problem description response")
future.id = message['id']
future.remote_status = status = message['status']
# The future may not have the ID set yet
with future._single_cancel_lock:
# This handles the case where cancel has been called on a future
# before that future received the problem id
if future._cancel_requested:
if not future._cancel_sent and status == self.STATUS_PENDING:
# The problem has been canceled but the status says its still in queue
# try to cancel it
self._cancel(message['id'], future)
# If a cancel request could meaningfully be sent it has been now
future._cancel_sent = True
if not future.time_received and message.get('submitted_on'):
future.time_received = parse_datetime(message['submitted_on'])
if not future.time_solved and message.get('solved_on'):
future.time_solved = parse_datetime(message['solved_on'])
if not future.eta_min and message.get('earliest_estimated_completion'):
future.eta_min = parse_datetime(message['earliest_estimated_completion'])
if not future.eta_max and message.get('latest_estimated_completion'):
future.eta_max = parse_datetime(message['latest_estimated_completion'])
if status == self.STATUS_COMPLETE:
# TODO: find a better way to differentiate between
# `completed-on-submit` and `completed-on-poll`.
# Loading should happen only once, not every time when response
# doesn't contain 'answer'.
# If the message is complete, forward it to the future object
if 'answer' in message:
future._set_message(message)
# If the problem is complete, but we don't have the result data
# put the problem in the queue for loading results.
else:
self._load(future)
elif status in self.ANY_STATUS_ONGOING:
# If the response is pending add it to the queue.
self._poll(future)
elif status == self.STATUS_CANCELLED:
# If canceled return error
raise CanceledFutureError()
else:
# Return an error to the future object
errmsg = message.get('error_message', 'An unknown error has occurred.')
if 'solver is offline' in errmsg.lower():
raise SolverOfflineError(errmsg)
else:
raise SolverFailureError(errmsg)
except Exception as error:
# If there were any unhandled errors we need to release the
# lock in the future, otherwise deadlock occurs.
future._set_error(error, sys.exc_info()) | [
"def",
"_handle_problem_status",
"(",
"self",
",",
"message",
",",
"future",
")",
":",
"try",
":",
"_LOGGER",
".",
"trace",
"(",
"\"Handling response: %r\"",
",",
"message",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Handling response for %s with status %s\"",
",",
"message",
".",
"get",
"(",
"'id'",
")",
",",
"message",
".",
"get",
"(",
"'status'",
")",
")",
"# Handle errors in batch mode",
"if",
"'error_code'",
"in",
"message",
"and",
"'error_msg'",
"in",
"message",
":",
"raise",
"SolverFailureError",
"(",
"message",
"[",
"'error_msg'",
"]",
")",
"if",
"'status'",
"not",
"in",
"message",
":",
"raise",
"InvalidAPIResponseError",
"(",
"\"'status' missing in problem description response\"",
")",
"if",
"'id'",
"not",
"in",
"message",
":",
"raise",
"InvalidAPIResponseError",
"(",
"\"'id' missing in problem description response\"",
")",
"future",
".",
"id",
"=",
"message",
"[",
"'id'",
"]",
"future",
".",
"remote_status",
"=",
"status",
"=",
"message",
"[",
"'status'",
"]",
"# The future may not have the ID set yet",
"with",
"future",
".",
"_single_cancel_lock",
":",
"# This handles the case where cancel has been called on a future",
"# before that future received the problem id",
"if",
"future",
".",
"_cancel_requested",
":",
"if",
"not",
"future",
".",
"_cancel_sent",
"and",
"status",
"==",
"self",
".",
"STATUS_PENDING",
":",
"# The problem has been canceled but the status says its still in queue",
"# try to cancel it",
"self",
".",
"_cancel",
"(",
"message",
"[",
"'id'",
"]",
",",
"future",
")",
"# If a cancel request could meaningfully be sent it has been now",
"future",
".",
"_cancel_sent",
"=",
"True",
"if",
"not",
"future",
".",
"time_received",
"and",
"message",
".",
"get",
"(",
"'submitted_on'",
")",
":",
"future",
".",
"time_received",
"=",
"parse_datetime",
"(",
"message",
"[",
"'submitted_on'",
"]",
")",
"if",
"not",
"future",
".",
"time_solved",
"and",
"message",
".",
"get",
"(",
"'solved_on'",
")",
":",
"future",
".",
"time_solved",
"=",
"parse_datetime",
"(",
"message",
"[",
"'solved_on'",
"]",
")",
"if",
"not",
"future",
".",
"eta_min",
"and",
"message",
".",
"get",
"(",
"'earliest_estimated_completion'",
")",
":",
"future",
".",
"eta_min",
"=",
"parse_datetime",
"(",
"message",
"[",
"'earliest_estimated_completion'",
"]",
")",
"if",
"not",
"future",
".",
"eta_max",
"and",
"message",
".",
"get",
"(",
"'latest_estimated_completion'",
")",
":",
"future",
".",
"eta_max",
"=",
"parse_datetime",
"(",
"message",
"[",
"'latest_estimated_completion'",
"]",
")",
"if",
"status",
"==",
"self",
".",
"STATUS_COMPLETE",
":",
"# TODO: find a better way to differentiate between",
"# `completed-on-submit` and `completed-on-poll`.",
"# Loading should happen only once, not every time when response",
"# doesn't contain 'answer'.",
"# If the message is complete, forward it to the future object",
"if",
"'answer'",
"in",
"message",
":",
"future",
".",
"_set_message",
"(",
"message",
")",
"# If the problem is complete, but we don't have the result data",
"# put the problem in the queue for loading results.",
"else",
":",
"self",
".",
"_load",
"(",
"future",
")",
"elif",
"status",
"in",
"self",
".",
"ANY_STATUS_ONGOING",
":",
"# If the response is pending add it to the queue.",
"self",
".",
"_poll",
"(",
"future",
")",
"elif",
"status",
"==",
"self",
".",
"STATUS_CANCELLED",
":",
"# If canceled return error",
"raise",
"CanceledFutureError",
"(",
")",
"else",
":",
"# Return an error to the future object",
"errmsg",
"=",
"message",
".",
"get",
"(",
"'error_message'",
",",
"'An unknown error has occurred.'",
")",
"if",
"'solver is offline'",
"in",
"errmsg",
".",
"lower",
"(",
")",
":",
"raise",
"SolverOfflineError",
"(",
"errmsg",
")",
"else",
":",
"raise",
"SolverFailureError",
"(",
"errmsg",
")",
"except",
"Exception",
"as",
"error",
":",
"# If there were any unhandled errors we need to release the",
"# lock in the future, otherwise deadlock occurs.",
"future",
".",
"_set_error",
"(",
"error",
",",
"sys",
".",
"exc_info",
"(",
")",
")"
] | Handle the results of a problem submission or results request.
This method checks the status of the problem and puts it in the correct queue.
Args:
message (dict): Update message from the SAPI server wrt. this problem.
future `Future`: future corresponding to the problem
Note:
This method is always run inside of a daemon thread. | [
"Handle",
"the",
"results",
"of",
"a",
"problem",
"submission",
"or",
"results",
"request",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1027-L1109 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/client.py | Client._do_cancel_problems | def _do_cancel_problems(self):
"""Pull ids from the cancel queue and submit them.
Note:
This method is always run inside of a daemon thread.
"""
try:
while True:
# Pull as many problems as we can, block when none are available.
# `None` task is used to signal thread termination
item = self._cancel_queue.get()
if item is None:
break
item_list = [item]
while True:
try:
item_list.append(self._cancel_queue.get_nowait())
except queue.Empty:
break
# Submit the problems, attach the ids as a json list in the
# body of the delete query.
try:
body = [item[0] for item in item_list]
try:
self.session.delete(posixpath.join(self.endpoint, 'problems/'), json=body)
except requests.exceptions.Timeout:
raise RequestTimeout
except Exception as err:
for _, future in item_list:
if future is not None:
future._set_error(err, sys.exc_info())
# Mark all the ids as processed regardless of success or failure.
[self._cancel_queue.task_done() for _ in item_list]
# this is equivalent to a yield to scheduler in other threading libraries
time.sleep(0)
except Exception as err:
_LOGGER.exception(err) | python | def _do_cancel_problems(self):
"""Pull ids from the cancel queue and submit them.
Note:
This method is always run inside of a daemon thread.
"""
try:
while True:
# Pull as many problems as we can, block when none are available.
# `None` task is used to signal thread termination
item = self._cancel_queue.get()
if item is None:
break
item_list = [item]
while True:
try:
item_list.append(self._cancel_queue.get_nowait())
except queue.Empty:
break
# Submit the problems, attach the ids as a json list in the
# body of the delete query.
try:
body = [item[0] for item in item_list]
try:
self.session.delete(posixpath.join(self.endpoint, 'problems/'), json=body)
except requests.exceptions.Timeout:
raise RequestTimeout
except Exception as err:
for _, future in item_list:
if future is not None:
future._set_error(err, sys.exc_info())
# Mark all the ids as processed regardless of success or failure.
[self._cancel_queue.task_done() for _ in item_list]
# this is equivalent to a yield to scheduler in other threading libraries
time.sleep(0)
except Exception as err:
_LOGGER.exception(err) | [
"def",
"_do_cancel_problems",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"# Pull as many problems as we can, block when none are available.",
"# `None` task is used to signal thread termination",
"item",
"=",
"self",
".",
"_cancel_queue",
".",
"get",
"(",
")",
"if",
"item",
"is",
"None",
":",
"break",
"item_list",
"=",
"[",
"item",
"]",
"while",
"True",
":",
"try",
":",
"item_list",
".",
"append",
"(",
"self",
".",
"_cancel_queue",
".",
"get_nowait",
"(",
")",
")",
"except",
"queue",
".",
"Empty",
":",
"break",
"# Submit the problems, attach the ids as a json list in the",
"# body of the delete query.",
"try",
":",
"body",
"=",
"[",
"item",
"[",
"0",
"]",
"for",
"item",
"in",
"item_list",
"]",
"try",
":",
"self",
".",
"session",
".",
"delete",
"(",
"posixpath",
".",
"join",
"(",
"self",
".",
"endpoint",
",",
"'problems/'",
")",
",",
"json",
"=",
"body",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
":",
"raise",
"RequestTimeout",
"except",
"Exception",
"as",
"err",
":",
"for",
"_",
",",
"future",
"in",
"item_list",
":",
"if",
"future",
"is",
"not",
"None",
":",
"future",
".",
"_set_error",
"(",
"err",
",",
"sys",
".",
"exc_info",
"(",
")",
")",
"# Mark all the ids as processed regardless of success or failure.",
"[",
"self",
".",
"_cancel_queue",
".",
"task_done",
"(",
")",
"for",
"_",
"in",
"item_list",
"]",
"# this is equivalent to a yield to scheduler in other threading libraries",
"time",
".",
"sleep",
"(",
"0",
")",
"except",
"Exception",
"as",
"err",
":",
"_LOGGER",
".",
"exception",
"(",
"err",
")"
] | Pull ids from the cancel queue and submit them.
Note:
This method is always run inside of a daemon thread. | [
"Pull",
"ids",
"from",
"the",
"cancel",
"queue",
"and",
"submit",
"them",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1118-L1162 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/client.py | Client._poll | def _poll(self, future):
"""Enqueue a problem to poll the server for status."""
if future._poll_backoff is None:
# on first poll, start with minimal back-off
future._poll_backoff = self._POLL_BACKOFF_MIN
# if we have ETA of results, schedule the first poll for then
if future.eta_min and self._is_clock_diff_acceptable(future):
at = datetime_to_timestamp(future.eta_min)
_LOGGER.debug("Response ETA indicated and local clock reliable. "
"Scheduling first polling at +%.2f sec", at - epochnow())
else:
at = time.time() + future._poll_backoff
_LOGGER.debug("Response ETA not indicated, or local clock unreliable. "
"Scheduling first polling at +%.2f sec", at - epochnow())
else:
# update exponential poll back-off, clipped to a range
future._poll_backoff = \
max(self._POLL_BACKOFF_MIN,
min(future._poll_backoff * 2, self._POLL_BACKOFF_MAX))
# for poll priority we use timestamp of next scheduled poll
at = time.time() + future._poll_backoff
now = utcnow()
future_age = (now - future.time_created).total_seconds()
_LOGGER.debug("Polling scheduled at %.2f with %.2f sec new back-off for: %s (future's age: %.2f sec)",
at, future._poll_backoff, future.id, future_age)
# don't enqueue for next poll if polling_timeout is exceeded by then
future_age_on_next_poll = future_age + (at - datetime_to_timestamp(now))
if self.polling_timeout is not None and future_age_on_next_poll > self.polling_timeout:
_LOGGER.debug("Polling timeout exceeded before next poll: %.2f sec > %.2f sec, aborting polling!",
future_age_on_next_poll, self.polling_timeout)
raise PollingTimeout
self._poll_queue.put((at, future)) | python | def _poll(self, future):
"""Enqueue a problem to poll the server for status."""
if future._poll_backoff is None:
# on first poll, start with minimal back-off
future._poll_backoff = self._POLL_BACKOFF_MIN
# if we have ETA of results, schedule the first poll for then
if future.eta_min and self._is_clock_diff_acceptable(future):
at = datetime_to_timestamp(future.eta_min)
_LOGGER.debug("Response ETA indicated and local clock reliable. "
"Scheduling first polling at +%.2f sec", at - epochnow())
else:
at = time.time() + future._poll_backoff
_LOGGER.debug("Response ETA not indicated, or local clock unreliable. "
"Scheduling first polling at +%.2f sec", at - epochnow())
else:
# update exponential poll back-off, clipped to a range
future._poll_backoff = \
max(self._POLL_BACKOFF_MIN,
min(future._poll_backoff * 2, self._POLL_BACKOFF_MAX))
# for poll priority we use timestamp of next scheduled poll
at = time.time() + future._poll_backoff
now = utcnow()
future_age = (now - future.time_created).total_seconds()
_LOGGER.debug("Polling scheduled at %.2f with %.2f sec new back-off for: %s (future's age: %.2f sec)",
at, future._poll_backoff, future.id, future_age)
# don't enqueue for next poll if polling_timeout is exceeded by then
future_age_on_next_poll = future_age + (at - datetime_to_timestamp(now))
if self.polling_timeout is not None and future_age_on_next_poll > self.polling_timeout:
_LOGGER.debug("Polling timeout exceeded before next poll: %.2f sec > %.2f sec, aborting polling!",
future_age_on_next_poll, self.polling_timeout)
raise PollingTimeout
self._poll_queue.put((at, future)) | [
"def",
"_poll",
"(",
"self",
",",
"future",
")",
":",
"if",
"future",
".",
"_poll_backoff",
"is",
"None",
":",
"# on first poll, start with minimal back-off",
"future",
".",
"_poll_backoff",
"=",
"self",
".",
"_POLL_BACKOFF_MIN",
"# if we have ETA of results, schedule the first poll for then",
"if",
"future",
".",
"eta_min",
"and",
"self",
".",
"_is_clock_diff_acceptable",
"(",
"future",
")",
":",
"at",
"=",
"datetime_to_timestamp",
"(",
"future",
".",
"eta_min",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Response ETA indicated and local clock reliable. \"",
"\"Scheduling first polling at +%.2f sec\"",
",",
"at",
"-",
"epochnow",
"(",
")",
")",
"else",
":",
"at",
"=",
"time",
".",
"time",
"(",
")",
"+",
"future",
".",
"_poll_backoff",
"_LOGGER",
".",
"debug",
"(",
"\"Response ETA not indicated, or local clock unreliable. \"",
"\"Scheduling first polling at +%.2f sec\"",
",",
"at",
"-",
"epochnow",
"(",
")",
")",
"else",
":",
"# update exponential poll back-off, clipped to a range",
"future",
".",
"_poll_backoff",
"=",
"max",
"(",
"self",
".",
"_POLL_BACKOFF_MIN",
",",
"min",
"(",
"future",
".",
"_poll_backoff",
"*",
"2",
",",
"self",
".",
"_POLL_BACKOFF_MAX",
")",
")",
"# for poll priority we use timestamp of next scheduled poll",
"at",
"=",
"time",
".",
"time",
"(",
")",
"+",
"future",
".",
"_poll_backoff",
"now",
"=",
"utcnow",
"(",
")",
"future_age",
"=",
"(",
"now",
"-",
"future",
".",
"time_created",
")",
".",
"total_seconds",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Polling scheduled at %.2f with %.2f sec new back-off for: %s (future's age: %.2f sec)\"",
",",
"at",
",",
"future",
".",
"_poll_backoff",
",",
"future",
".",
"id",
",",
"future_age",
")",
"# don't enqueue for next poll if polling_timeout is exceeded by then",
"future_age_on_next_poll",
"=",
"future_age",
"+",
"(",
"at",
"-",
"datetime_to_timestamp",
"(",
"now",
")",
")",
"if",
"self",
".",
"polling_timeout",
"is",
"not",
"None",
"and",
"future_age_on_next_poll",
">",
"self",
".",
"polling_timeout",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Polling timeout exceeded before next poll: %.2f sec > %.2f sec, aborting polling!\"",
",",
"future_age_on_next_poll",
",",
"self",
".",
"polling_timeout",
")",
"raise",
"PollingTimeout",
"self",
".",
"_poll_queue",
".",
"put",
"(",
"(",
"at",
",",
"future",
")",
")"
] | Enqueue a problem to poll the server for status. | [
"Enqueue",
"a",
"problem",
"to",
"poll",
"the",
"server",
"for",
"status",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1174-L1212 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/client.py | Client._do_poll_problems | def _do_poll_problems(self):
"""Poll the server for the status of a set of problems.
Note:
This method is always run inside of a daemon thread.
"""
try:
# grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME)
frame_futures = {}
def task_done():
self._poll_queue.task_done()
def add(future):
# add future to query frame_futures
# returns: worker lives on?
# `None` task signifies thread termination
if future is None:
task_done()
return False
if future.id not in frame_futures and not future.done():
frame_futures[future.id] = future
else:
task_done()
return True
while True:
frame_futures.clear()
# blocking add first scheduled
frame_earliest, future = self._poll_queue.get()
if not add(future):
return
# try grouping if scheduled within grouping timeframe
while len(frame_futures) < self._STATUS_QUERY_SIZE:
try:
task = self._poll_queue.get_nowait()
except queue.Empty:
break
at, future = task
if at - frame_earliest <= self._POLL_GROUP_TIMEFRAME:
if not add(future):
return
else:
task_done()
self._poll_queue.put(task)
break
# build a query string with ids of all futures in this frame
ids = [future.id for future in frame_futures.values()]
_LOGGER.debug("Polling for status of futures: %s", ids)
query_string = 'problems/?id=' + ','.join(ids)
# if futures were cancelled while `add`ing, skip empty frame
if not ids:
continue
# wait until `frame_earliest` before polling
delay = frame_earliest - time.time()
if delay > 0:
_LOGGER.debug("Pausing polling %.2f sec for futures: %s", delay, ids)
time.sleep(delay)
else:
_LOGGER.trace("Skipping non-positive delay of %.2f sec", delay)
try:
_LOGGER.trace("Executing poll API request")
try:
response = self.session.get(posixpath.join(self.endpoint, query_string))
except requests.exceptions.Timeout:
raise RequestTimeout
if response.status_code == 401:
raise SolverAuthenticationError()
response.raise_for_status()
statuses = response.json()
for status in statuses:
self._handle_problem_status(status, frame_futures[status['id']])
except BaseException as exception:
if not isinstance(exception, SolverAuthenticationError):
exception = IOError(exception)
for id_ in frame_futures.keys():
frame_futures[id_]._set_error(IOError(exception), sys.exc_info())
for id_ in frame_futures.keys():
task_done()
time.sleep(0)
except Exception as err:
_LOGGER.exception(err) | python | def _do_poll_problems(self):
"""Poll the server for the status of a set of problems.
Note:
This method is always run inside of a daemon thread.
"""
try:
# grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME)
frame_futures = {}
def task_done():
self._poll_queue.task_done()
def add(future):
# add future to query frame_futures
# returns: worker lives on?
# `None` task signifies thread termination
if future is None:
task_done()
return False
if future.id not in frame_futures and not future.done():
frame_futures[future.id] = future
else:
task_done()
return True
while True:
frame_futures.clear()
# blocking add first scheduled
frame_earliest, future = self._poll_queue.get()
if not add(future):
return
# try grouping if scheduled within grouping timeframe
while len(frame_futures) < self._STATUS_QUERY_SIZE:
try:
task = self._poll_queue.get_nowait()
except queue.Empty:
break
at, future = task
if at - frame_earliest <= self._POLL_GROUP_TIMEFRAME:
if not add(future):
return
else:
task_done()
self._poll_queue.put(task)
break
# build a query string with ids of all futures in this frame
ids = [future.id for future in frame_futures.values()]
_LOGGER.debug("Polling for status of futures: %s", ids)
query_string = 'problems/?id=' + ','.join(ids)
# if futures were cancelled while `add`ing, skip empty frame
if not ids:
continue
# wait until `frame_earliest` before polling
delay = frame_earliest - time.time()
if delay > 0:
_LOGGER.debug("Pausing polling %.2f sec for futures: %s", delay, ids)
time.sleep(delay)
else:
_LOGGER.trace("Skipping non-positive delay of %.2f sec", delay)
try:
_LOGGER.trace("Executing poll API request")
try:
response = self.session.get(posixpath.join(self.endpoint, query_string))
except requests.exceptions.Timeout:
raise RequestTimeout
if response.status_code == 401:
raise SolverAuthenticationError()
response.raise_for_status()
statuses = response.json()
for status in statuses:
self._handle_problem_status(status, frame_futures[status['id']])
except BaseException as exception:
if not isinstance(exception, SolverAuthenticationError):
exception = IOError(exception)
for id_ in frame_futures.keys():
frame_futures[id_]._set_error(IOError(exception), sys.exc_info())
for id_ in frame_futures.keys():
task_done()
time.sleep(0)
except Exception as err:
_LOGGER.exception(err) | [
"def",
"_do_poll_problems",
"(",
"self",
")",
":",
"try",
":",
"# grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME)",
"frame_futures",
"=",
"{",
"}",
"def",
"task_done",
"(",
")",
":",
"self",
".",
"_poll_queue",
".",
"task_done",
"(",
")",
"def",
"add",
"(",
"future",
")",
":",
"# add future to query frame_futures",
"# returns: worker lives on?",
"# `None` task signifies thread termination",
"if",
"future",
"is",
"None",
":",
"task_done",
"(",
")",
"return",
"False",
"if",
"future",
".",
"id",
"not",
"in",
"frame_futures",
"and",
"not",
"future",
".",
"done",
"(",
")",
":",
"frame_futures",
"[",
"future",
".",
"id",
"]",
"=",
"future",
"else",
":",
"task_done",
"(",
")",
"return",
"True",
"while",
"True",
":",
"frame_futures",
".",
"clear",
"(",
")",
"# blocking add first scheduled",
"frame_earliest",
",",
"future",
"=",
"self",
".",
"_poll_queue",
".",
"get",
"(",
")",
"if",
"not",
"add",
"(",
"future",
")",
":",
"return",
"# try grouping if scheduled within grouping timeframe",
"while",
"len",
"(",
"frame_futures",
")",
"<",
"self",
".",
"_STATUS_QUERY_SIZE",
":",
"try",
":",
"task",
"=",
"self",
".",
"_poll_queue",
".",
"get_nowait",
"(",
")",
"except",
"queue",
".",
"Empty",
":",
"break",
"at",
",",
"future",
"=",
"task",
"if",
"at",
"-",
"frame_earliest",
"<=",
"self",
".",
"_POLL_GROUP_TIMEFRAME",
":",
"if",
"not",
"add",
"(",
"future",
")",
":",
"return",
"else",
":",
"task_done",
"(",
")",
"self",
".",
"_poll_queue",
".",
"put",
"(",
"task",
")",
"break",
"# build a query string with ids of all futures in this frame",
"ids",
"=",
"[",
"future",
".",
"id",
"for",
"future",
"in",
"frame_futures",
".",
"values",
"(",
")",
"]",
"_LOGGER",
".",
"debug",
"(",
"\"Polling for status of futures: %s\"",
",",
"ids",
")",
"query_string",
"=",
"'problems/?id='",
"+",
"','",
".",
"join",
"(",
"ids",
")",
"# if futures were cancelled while `add`ing, skip empty frame",
"if",
"not",
"ids",
":",
"continue",
"# wait until `frame_earliest` before polling",
"delay",
"=",
"frame_earliest",
"-",
"time",
".",
"time",
"(",
")",
"if",
"delay",
">",
"0",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Pausing polling %.2f sec for futures: %s\"",
",",
"delay",
",",
"ids",
")",
"time",
".",
"sleep",
"(",
"delay",
")",
"else",
":",
"_LOGGER",
".",
"trace",
"(",
"\"Skipping non-positive delay of %.2f sec\"",
",",
"delay",
")",
"try",
":",
"_LOGGER",
".",
"trace",
"(",
"\"Executing poll API request\"",
")",
"try",
":",
"response",
"=",
"self",
".",
"session",
".",
"get",
"(",
"posixpath",
".",
"join",
"(",
"self",
".",
"endpoint",
",",
"query_string",
")",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
":",
"raise",
"RequestTimeout",
"if",
"response",
".",
"status_code",
"==",
"401",
":",
"raise",
"SolverAuthenticationError",
"(",
")",
"response",
".",
"raise_for_status",
"(",
")",
"statuses",
"=",
"response",
".",
"json",
"(",
")",
"for",
"status",
"in",
"statuses",
":",
"self",
".",
"_handle_problem_status",
"(",
"status",
",",
"frame_futures",
"[",
"status",
"[",
"'id'",
"]",
"]",
")",
"except",
"BaseException",
"as",
"exception",
":",
"if",
"not",
"isinstance",
"(",
"exception",
",",
"SolverAuthenticationError",
")",
":",
"exception",
"=",
"IOError",
"(",
"exception",
")",
"for",
"id_",
"in",
"frame_futures",
".",
"keys",
"(",
")",
":",
"frame_futures",
"[",
"id_",
"]",
".",
"_set_error",
"(",
"IOError",
"(",
"exception",
")",
",",
"sys",
".",
"exc_info",
"(",
")",
")",
"for",
"id_",
"in",
"frame_futures",
".",
"keys",
"(",
")",
":",
"task_done",
"(",
")",
"time",
".",
"sleep",
"(",
"0",
")",
"except",
"Exception",
"as",
"err",
":",
"_LOGGER",
".",
"exception",
"(",
"err",
")"
] | Poll the server for the status of a set of problems.
Note:
This method is always run inside of a daemon thread. | [
"Poll",
"the",
"server",
"for",
"the",
"status",
"of",
"a",
"set",
"of",
"problems",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1214-L1313 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/client.py | Client._do_load_results | def _do_load_results(self):
"""Submit a query asking for the results for a particular problem.
To request the results of a problem: ``GET /problems/{problem_id}/``
Note:
This method is always run inside of a daemon thread.
"""
try:
while True:
# Select a problem
future = self._load_queue.get()
# `None` task signifies thread termination
if future is None:
break
_LOGGER.debug("Loading results of: %s", future.id)
# Submit the query
query_string = 'problems/{}/'.format(future.id)
try:
try:
response = self.session.get(posixpath.join(self.endpoint, query_string))
except requests.exceptions.Timeout:
raise RequestTimeout
if response.status_code == 401:
raise SolverAuthenticationError()
response.raise_for_status()
message = response.json()
except BaseException as exception:
if not isinstance(exception, SolverAuthenticationError):
exception = IOError(exception)
future._set_error(IOError(exception), sys.exc_info())
continue
# Dispatch the results, mark the task complete
self._handle_problem_status(message, future)
self._load_queue.task_done()
# this is equivalent to a yield to scheduler in other threading libraries
time.sleep(0)
except Exception as err:
_LOGGER.error('Load result error: ' + str(err)) | python | def _do_load_results(self):
"""Submit a query asking for the results for a particular problem.
To request the results of a problem: ``GET /problems/{problem_id}/``
Note:
This method is always run inside of a daemon thread.
"""
try:
while True:
# Select a problem
future = self._load_queue.get()
# `None` task signifies thread termination
if future is None:
break
_LOGGER.debug("Loading results of: %s", future.id)
# Submit the query
query_string = 'problems/{}/'.format(future.id)
try:
try:
response = self.session.get(posixpath.join(self.endpoint, query_string))
except requests.exceptions.Timeout:
raise RequestTimeout
if response.status_code == 401:
raise SolverAuthenticationError()
response.raise_for_status()
message = response.json()
except BaseException as exception:
if not isinstance(exception, SolverAuthenticationError):
exception = IOError(exception)
future._set_error(IOError(exception), sys.exc_info())
continue
# Dispatch the results, mark the task complete
self._handle_problem_status(message, future)
self._load_queue.task_done()
# this is equivalent to a yield to scheduler in other threading libraries
time.sleep(0)
except Exception as err:
_LOGGER.error('Load result error: ' + str(err)) | [
"def",
"_do_load_results",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"# Select a problem",
"future",
"=",
"self",
".",
"_load_queue",
".",
"get",
"(",
")",
"# `None` task signifies thread termination",
"if",
"future",
"is",
"None",
":",
"break",
"_LOGGER",
".",
"debug",
"(",
"\"Loading results of: %s\"",
",",
"future",
".",
"id",
")",
"# Submit the query",
"query_string",
"=",
"'problems/{}/'",
".",
"format",
"(",
"future",
".",
"id",
")",
"try",
":",
"try",
":",
"response",
"=",
"self",
".",
"session",
".",
"get",
"(",
"posixpath",
".",
"join",
"(",
"self",
".",
"endpoint",
",",
"query_string",
")",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
":",
"raise",
"RequestTimeout",
"if",
"response",
".",
"status_code",
"==",
"401",
":",
"raise",
"SolverAuthenticationError",
"(",
")",
"response",
".",
"raise_for_status",
"(",
")",
"message",
"=",
"response",
".",
"json",
"(",
")",
"except",
"BaseException",
"as",
"exception",
":",
"if",
"not",
"isinstance",
"(",
"exception",
",",
"SolverAuthenticationError",
")",
":",
"exception",
"=",
"IOError",
"(",
"exception",
")",
"future",
".",
"_set_error",
"(",
"IOError",
"(",
"exception",
")",
",",
"sys",
".",
"exc_info",
"(",
")",
")",
"continue",
"# Dispatch the results, mark the task complete",
"self",
".",
"_handle_problem_status",
"(",
"message",
",",
"future",
")",
"self",
".",
"_load_queue",
".",
"task_done",
"(",
")",
"# this is equivalent to a yield to scheduler in other threading libraries",
"time",
".",
"sleep",
"(",
"0",
")",
"except",
"Exception",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"'Load result error: '",
"+",
"str",
"(",
"err",
")",
")"
] | Submit a query asking for the results for a particular problem.
To request the results of a problem: ``GET /problems/{problem_id}/``
Note:
This method is always run inside of a daemon thread. | [
"Submit",
"a",
"query",
"asking",
"for",
"the",
"results",
"for",
"a",
"particular",
"problem",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1325-L1370 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/coders.py | encode_bqm_as_qp | def encode_bqm_as_qp(solver, linear, quadratic):
"""Encode the binary quadratic problem for submission to a given solver,
using the `qp` format for data.
Args:
solver (:class:`dwave.cloud.solver.Solver`):
The solver used.
linear (dict[variable, bias]/list[variable, bias]):
Linear terms of the model.
quadratic (dict[(variable, variable), bias]):
Quadratic terms of the model.
Returns:
encoded submission dictionary
"""
active = active_qubits(linear, quadratic)
# Encode linear terms. The coefficients of the linear terms of the objective
# are encoded as an array of little endian 64 bit doubles.
# This array is then base64 encoded into a string safe for json.
# The order of the terms is determined by the _encoding_qubits property
# specified by the server.
# Note: only active qubits are coded with double, inactive with NaN
nan = float('nan')
lin = [uniform_get(linear, qubit, 0 if qubit in active else nan)
for qubit in solver._encoding_qubits]
lin = base64.b64encode(struct.pack('<' + ('d' * len(lin)), *lin))
# Encode the coefficients of the quadratic terms of the objective
# in the same manner as the linear terms, in the order given by the
# _encoding_couplers property, discarding tailing zero couplings
quad = [quadratic.get((q1,q2), 0) + quadratic.get((q2,q1), 0)
for (q1,q2) in solver._encoding_couplers
if q1 in active and q2 in active]
quad = base64.b64encode(struct.pack('<' + ('d' * len(quad)), *quad))
# The name for this encoding is 'qp' and is explicitly included in the
# message for easier extension in the future.
return {
'format': 'qp',
'lin': lin.decode('utf-8'),
'quad': quad.decode('utf-8')
} | python | def encode_bqm_as_qp(solver, linear, quadratic):
"""Encode the binary quadratic problem for submission to a given solver,
using the `qp` format for data.
Args:
solver (:class:`dwave.cloud.solver.Solver`):
The solver used.
linear (dict[variable, bias]/list[variable, bias]):
Linear terms of the model.
quadratic (dict[(variable, variable), bias]):
Quadratic terms of the model.
Returns:
encoded submission dictionary
"""
active = active_qubits(linear, quadratic)
# Encode linear terms. The coefficients of the linear terms of the objective
# are encoded as an array of little endian 64 bit doubles.
# This array is then base64 encoded into a string safe for json.
# The order of the terms is determined by the _encoding_qubits property
# specified by the server.
# Note: only active qubits are coded with double, inactive with NaN
nan = float('nan')
lin = [uniform_get(linear, qubit, 0 if qubit in active else nan)
for qubit in solver._encoding_qubits]
lin = base64.b64encode(struct.pack('<' + ('d' * len(lin)), *lin))
# Encode the coefficients of the quadratic terms of the objective
# in the same manner as the linear terms, in the order given by the
# _encoding_couplers property, discarding tailing zero couplings
quad = [quadratic.get((q1,q2), 0) + quadratic.get((q2,q1), 0)
for (q1,q2) in solver._encoding_couplers
if q1 in active and q2 in active]
quad = base64.b64encode(struct.pack('<' + ('d' * len(quad)), *quad))
# The name for this encoding is 'qp' and is explicitly included in the
# message for easier extension in the future.
return {
'format': 'qp',
'lin': lin.decode('utf-8'),
'quad': quad.decode('utf-8')
} | [
"def",
"encode_bqm_as_qp",
"(",
"solver",
",",
"linear",
",",
"quadratic",
")",
":",
"active",
"=",
"active_qubits",
"(",
"linear",
",",
"quadratic",
")",
"# Encode linear terms. The coefficients of the linear terms of the objective",
"# are encoded as an array of little endian 64 bit doubles.",
"# This array is then base64 encoded into a string safe for json.",
"# The order of the terms is determined by the _encoding_qubits property",
"# specified by the server.",
"# Note: only active qubits are coded with double, inactive with NaN",
"nan",
"=",
"float",
"(",
"'nan'",
")",
"lin",
"=",
"[",
"uniform_get",
"(",
"linear",
",",
"qubit",
",",
"0",
"if",
"qubit",
"in",
"active",
"else",
"nan",
")",
"for",
"qubit",
"in",
"solver",
".",
"_encoding_qubits",
"]",
"lin",
"=",
"base64",
".",
"b64encode",
"(",
"struct",
".",
"pack",
"(",
"'<'",
"+",
"(",
"'d'",
"*",
"len",
"(",
"lin",
")",
")",
",",
"*",
"lin",
")",
")",
"# Encode the coefficients of the quadratic terms of the objective",
"# in the same manner as the linear terms, in the order given by the",
"# _encoding_couplers property, discarding tailing zero couplings",
"quad",
"=",
"[",
"quadratic",
".",
"get",
"(",
"(",
"q1",
",",
"q2",
")",
",",
"0",
")",
"+",
"quadratic",
".",
"get",
"(",
"(",
"q2",
",",
"q1",
")",
",",
"0",
")",
"for",
"(",
"q1",
",",
"q2",
")",
"in",
"solver",
".",
"_encoding_couplers",
"if",
"q1",
"in",
"active",
"and",
"q2",
"in",
"active",
"]",
"quad",
"=",
"base64",
".",
"b64encode",
"(",
"struct",
".",
"pack",
"(",
"'<'",
"+",
"(",
"'d'",
"*",
"len",
"(",
"quad",
")",
")",
",",
"*",
"quad",
")",
")",
"# The name for this encoding is 'qp' and is explicitly included in the",
"# message for easier extension in the future.",
"return",
"{",
"'format'",
":",
"'qp'",
",",
"'lin'",
":",
"lin",
".",
"decode",
"(",
"'utf-8'",
")",
",",
"'quad'",
":",
"quad",
".",
"decode",
"(",
"'utf-8'",
")",
"}"
] | Encode the binary quadratic problem for submission to a given solver,
using the `qp` format for data.
Args:
solver (:class:`dwave.cloud.solver.Solver`):
The solver used.
linear (dict[variable, bias]/list[variable, bias]):
Linear terms of the model.
quadratic (dict[(variable, variable), bias]):
Quadratic terms of the model.
Returns:
encoded submission dictionary | [
"Encode",
"the",
"binary",
"quadratic",
"problem",
"for",
"submission",
"to",
"a",
"given",
"solver",
"using",
"the",
"qp",
"format",
"for",
"data",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L26-L70 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/coders.py | decode_qp | def decode_qp(msg):
"""Decode SAPI response that uses `qp` format, without numpy.
The 'qp' format is the current encoding used for problems and samples.
In this encoding the reply is generally json, but the samples, energy,
and histogram data (the occurrence count of each solution), are all
base64 encoded arrays.
"""
# Decode the simple buffers
result = msg['answer']
result['active_variables'] = _decode_ints(result['active_variables'])
active_variables = result['active_variables']
if 'num_occurrences' in result:
result['num_occurrences'] = _decode_ints(result['num_occurrences'])
result['energies'] = _decode_doubles(result['energies'])
# Measure out the size of the binary solution data
num_solutions = len(result['energies'])
num_variables = len(result['active_variables'])
solution_bytes = -(-num_variables // 8) # equivalent to int(math.ceil(num_variables / 8.))
total_variables = result['num_variables']
# Figure out the null value for output
default = 3 if msg['type'] == 'qubo' else 0
# Decode the solutions, which will be byte aligned in binary format
binary = base64.b64decode(result['solutions'])
solutions = []
for solution_index in range(num_solutions):
# Grab the section of the buffer related to the current
buffer_index = solution_index * solution_bytes
solution_buffer = binary[buffer_index:buffer_index + solution_bytes]
bytes = struct.unpack('B' * solution_bytes, solution_buffer)
# Assume None values
solution = [default] * total_variables
index = 0
for byte in bytes:
# Parse each byte and read how ever many bits can be
values = _decode_byte(byte)
for _ in range(min(8, len(active_variables) - index)):
i = active_variables[index]
index += 1
solution[i] = values.pop()
# Switch to the right variable space
if msg['type'] == 'ising':
values = {0: -1, 1: 1}
solution = [values.get(v, default) for v in solution]
solutions.append(solution)
result['solutions'] = solutions
return result | python | def decode_qp(msg):
"""Decode SAPI response that uses `qp` format, without numpy.
The 'qp' format is the current encoding used for problems and samples.
In this encoding the reply is generally json, but the samples, energy,
and histogram data (the occurrence count of each solution), are all
base64 encoded arrays.
"""
# Decode the simple buffers
result = msg['answer']
result['active_variables'] = _decode_ints(result['active_variables'])
active_variables = result['active_variables']
if 'num_occurrences' in result:
result['num_occurrences'] = _decode_ints(result['num_occurrences'])
result['energies'] = _decode_doubles(result['energies'])
# Measure out the size of the binary solution data
num_solutions = len(result['energies'])
num_variables = len(result['active_variables'])
solution_bytes = -(-num_variables // 8) # equivalent to int(math.ceil(num_variables / 8.))
total_variables = result['num_variables']
# Figure out the null value for output
default = 3 if msg['type'] == 'qubo' else 0
# Decode the solutions, which will be byte aligned in binary format
binary = base64.b64decode(result['solutions'])
solutions = []
for solution_index in range(num_solutions):
# Grab the section of the buffer related to the current
buffer_index = solution_index * solution_bytes
solution_buffer = binary[buffer_index:buffer_index + solution_bytes]
bytes = struct.unpack('B' * solution_bytes, solution_buffer)
# Assume None values
solution = [default] * total_variables
index = 0
for byte in bytes:
# Parse each byte and read how ever many bits can be
values = _decode_byte(byte)
for _ in range(min(8, len(active_variables) - index)):
i = active_variables[index]
index += 1
solution[i] = values.pop()
# Switch to the right variable space
if msg['type'] == 'ising':
values = {0: -1, 1: 1}
solution = [values.get(v, default) for v in solution]
solutions.append(solution)
result['solutions'] = solutions
return result | [
"def",
"decode_qp",
"(",
"msg",
")",
":",
"# Decode the simple buffers",
"result",
"=",
"msg",
"[",
"'answer'",
"]",
"result",
"[",
"'active_variables'",
"]",
"=",
"_decode_ints",
"(",
"result",
"[",
"'active_variables'",
"]",
")",
"active_variables",
"=",
"result",
"[",
"'active_variables'",
"]",
"if",
"'num_occurrences'",
"in",
"result",
":",
"result",
"[",
"'num_occurrences'",
"]",
"=",
"_decode_ints",
"(",
"result",
"[",
"'num_occurrences'",
"]",
")",
"result",
"[",
"'energies'",
"]",
"=",
"_decode_doubles",
"(",
"result",
"[",
"'energies'",
"]",
")",
"# Measure out the size of the binary solution data",
"num_solutions",
"=",
"len",
"(",
"result",
"[",
"'energies'",
"]",
")",
"num_variables",
"=",
"len",
"(",
"result",
"[",
"'active_variables'",
"]",
")",
"solution_bytes",
"=",
"-",
"(",
"-",
"num_variables",
"//",
"8",
")",
"# equivalent to int(math.ceil(num_variables / 8.))",
"total_variables",
"=",
"result",
"[",
"'num_variables'",
"]",
"# Figure out the null value for output",
"default",
"=",
"3",
"if",
"msg",
"[",
"'type'",
"]",
"==",
"'qubo'",
"else",
"0",
"# Decode the solutions, which will be byte aligned in binary format",
"binary",
"=",
"base64",
".",
"b64decode",
"(",
"result",
"[",
"'solutions'",
"]",
")",
"solutions",
"=",
"[",
"]",
"for",
"solution_index",
"in",
"range",
"(",
"num_solutions",
")",
":",
"# Grab the section of the buffer related to the current",
"buffer_index",
"=",
"solution_index",
"*",
"solution_bytes",
"solution_buffer",
"=",
"binary",
"[",
"buffer_index",
":",
"buffer_index",
"+",
"solution_bytes",
"]",
"bytes",
"=",
"struct",
".",
"unpack",
"(",
"'B'",
"*",
"solution_bytes",
",",
"solution_buffer",
")",
"# Assume None values",
"solution",
"=",
"[",
"default",
"]",
"*",
"total_variables",
"index",
"=",
"0",
"for",
"byte",
"in",
"bytes",
":",
"# Parse each byte and read how ever many bits can be",
"values",
"=",
"_decode_byte",
"(",
"byte",
")",
"for",
"_",
"in",
"range",
"(",
"min",
"(",
"8",
",",
"len",
"(",
"active_variables",
")",
"-",
"index",
")",
")",
":",
"i",
"=",
"active_variables",
"[",
"index",
"]",
"index",
"+=",
"1",
"solution",
"[",
"i",
"]",
"=",
"values",
".",
"pop",
"(",
")",
"# Switch to the right variable space",
"if",
"msg",
"[",
"'type'",
"]",
"==",
"'ising'",
":",
"values",
"=",
"{",
"0",
":",
"-",
"1",
",",
"1",
":",
"1",
"}",
"solution",
"=",
"[",
"values",
".",
"get",
"(",
"v",
",",
"default",
")",
"for",
"v",
"in",
"solution",
"]",
"solutions",
".",
"append",
"(",
"solution",
")",
"result",
"[",
"'solutions'",
"]",
"=",
"solutions",
"return",
"result"
] | Decode SAPI response that uses `qp` format, without numpy.
The 'qp' format is the current encoding used for problems and samples.
In this encoding the reply is generally json, but the samples, energy,
and histogram data (the occurrence count of each solution), are all
base64 encoded arrays. | [
"Decode",
"SAPI",
"response",
"that",
"uses",
"qp",
"format",
"without",
"numpy",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L73-L125 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/coders.py | _decode_byte | def _decode_byte(byte):
"""Helper for decode_qp, turns a single byte into a list of bits.
Args:
byte: byte to be decoded
Returns:
list of bits corresponding to byte
"""
bits = []
for _ in range(8):
bits.append(byte & 1)
byte >>= 1
return bits | python | def _decode_byte(byte):
"""Helper for decode_qp, turns a single byte into a list of bits.
Args:
byte: byte to be decoded
Returns:
list of bits corresponding to byte
"""
bits = []
for _ in range(8):
bits.append(byte & 1)
byte >>= 1
return bits | [
"def",
"_decode_byte",
"(",
"byte",
")",
":",
"bits",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"8",
")",
":",
"bits",
".",
"append",
"(",
"byte",
"&",
"1",
")",
"byte",
">>=",
"1",
"return",
"bits"
] | Helper for decode_qp, turns a single byte into a list of bits.
Args:
byte: byte to be decoded
Returns:
list of bits corresponding to byte | [
"Helper",
"for",
"decode_qp",
"turns",
"a",
"single",
"byte",
"into",
"a",
"list",
"of",
"bits",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L128-L141 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/coders.py | _decode_ints | def _decode_ints(message):
"""Helper for decode_qp, decodes an int array.
The int array is stored as little endian 32 bit integers.
The array has then been base64 encoded. Since we are decoding we do these
steps in reverse.
"""
binary = base64.b64decode(message)
return struct.unpack('<' + ('i' * (len(binary) // 4)), binary) | python | def _decode_ints(message):
"""Helper for decode_qp, decodes an int array.
The int array is stored as little endian 32 bit integers.
The array has then been base64 encoded. Since we are decoding we do these
steps in reverse.
"""
binary = base64.b64decode(message)
return struct.unpack('<' + ('i' * (len(binary) // 4)), binary) | [
"def",
"_decode_ints",
"(",
"message",
")",
":",
"binary",
"=",
"base64",
".",
"b64decode",
"(",
"message",
")",
"return",
"struct",
".",
"unpack",
"(",
"'<'",
"+",
"(",
"'i'",
"*",
"(",
"len",
"(",
"binary",
")",
"//",
"4",
")",
")",
",",
"binary",
")"
] | Helper for decode_qp, decodes an int array.
The int array is stored as little endian 32 bit integers.
The array has then been base64 encoded. Since we are decoding we do these
steps in reverse. | [
"Helper",
"for",
"decode_qp",
"decodes",
"an",
"int",
"array",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L144-L152 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/coders.py | _decode_doubles | def _decode_doubles(message):
"""Helper for decode_qp, decodes a double array.
The double array is stored as little endian 64 bit doubles.
The array has then been base64 encoded. Since we are decoding we do these
steps in reverse.
Args:
message: the double array
Returns:
decoded double array
"""
binary = base64.b64decode(message)
return struct.unpack('<' + ('d' * (len(binary) // 8)), binary) | python | def _decode_doubles(message):
"""Helper for decode_qp, decodes a double array.
The double array is stored as little endian 64 bit doubles.
The array has then been base64 encoded. Since we are decoding we do these
steps in reverse.
Args:
message: the double array
Returns:
decoded double array
"""
binary = base64.b64decode(message)
return struct.unpack('<' + ('d' * (len(binary) // 8)), binary) | [
"def",
"_decode_doubles",
"(",
"message",
")",
":",
"binary",
"=",
"base64",
".",
"b64decode",
"(",
"message",
")",
"return",
"struct",
".",
"unpack",
"(",
"'<'",
"+",
"(",
"'d'",
"*",
"(",
"len",
"(",
"binary",
")",
"//",
"8",
")",
")",
",",
"binary",
")"
] | Helper for decode_qp, decodes a double array.
The double array is stored as little endian 64 bit doubles.
The array has then been base64 encoded. Since we are decoding we do these
steps in reverse.
Args:
message: the double array
Returns:
decoded double array | [
"Helper",
"for",
"decode_qp",
"decodes",
"a",
"double",
"array",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L155-L169 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/coders.py | decode_qp_numpy | def decode_qp_numpy(msg, return_matrix=True):
"""Decode SAPI response, results in a `qp` format, explicitly using numpy.
If numpy is not installed, the method will fail.
To use numpy for decoding, but return the results a lists (instead of
numpy matrices), set `return_matrix=False`.
"""
import numpy as np
result = msg['answer']
# Build some little endian type encodings
double_type = np.dtype(np.double)
double_type = double_type.newbyteorder('<')
int_type = np.dtype(np.int32)
int_type = int_type.newbyteorder('<')
# Decode the simple buffers
result['energies'] = np.frombuffer(base64.b64decode(result['energies']),
dtype=double_type)
if 'num_occurrences' in result:
result['num_occurrences'] = \
np.frombuffer(base64.b64decode(result['num_occurrences']),
dtype=int_type)
result['active_variables'] = \
np.frombuffer(base64.b64decode(result['active_variables']),
dtype=int_type)
# Measure out the binary data size
num_solutions = len(result['energies'])
active_variables = result['active_variables']
num_variables = len(active_variables)
total_variables = result['num_variables']
# Decode the solutions, which will be a continuous run of bits
byte_type = np.dtype(np.uint8)
byte_type = byte_type.newbyteorder('<')
bits = np.unpackbits(np.frombuffer(base64.b64decode(result['solutions']),
dtype=byte_type))
# Clip off the extra bits from encoding
if num_solutions:
bits = np.reshape(bits, (num_solutions, bits.size // num_solutions))
bits = np.delete(bits, range(num_variables, bits.shape[1]), 1)
# Switch from bits to spins
default = 3
if msg['type'] == 'ising':
bits = bits.astype(np.int8)
bits *= 2
bits -= 1
default = 0
# Fill in the missing variables
solutions = np.full((num_solutions, total_variables), default, dtype=np.int8)
solutions[:, active_variables] = bits
result['solutions'] = solutions
# If the final result shouldn't be numpy formats switch back to python objects
if not return_matrix:
result['energies'] = result['energies'].tolist()
if 'num_occurrences' in result:
result['num_occurrences'] = result['num_occurrences'].tolist()
result['active_variables'] = result['active_variables'].tolist()
result['solutions'] = result['solutions'].tolist()
return result | python | def decode_qp_numpy(msg, return_matrix=True):
"""Decode SAPI response, results in a `qp` format, explicitly using numpy.
If numpy is not installed, the method will fail.
To use numpy for decoding, but return the results a lists (instead of
numpy matrices), set `return_matrix=False`.
"""
import numpy as np
result = msg['answer']
# Build some little endian type encodings
double_type = np.dtype(np.double)
double_type = double_type.newbyteorder('<')
int_type = np.dtype(np.int32)
int_type = int_type.newbyteorder('<')
# Decode the simple buffers
result['energies'] = np.frombuffer(base64.b64decode(result['energies']),
dtype=double_type)
if 'num_occurrences' in result:
result['num_occurrences'] = \
np.frombuffer(base64.b64decode(result['num_occurrences']),
dtype=int_type)
result['active_variables'] = \
np.frombuffer(base64.b64decode(result['active_variables']),
dtype=int_type)
# Measure out the binary data size
num_solutions = len(result['energies'])
active_variables = result['active_variables']
num_variables = len(active_variables)
total_variables = result['num_variables']
# Decode the solutions, which will be a continuous run of bits
byte_type = np.dtype(np.uint8)
byte_type = byte_type.newbyteorder('<')
bits = np.unpackbits(np.frombuffer(base64.b64decode(result['solutions']),
dtype=byte_type))
# Clip off the extra bits from encoding
if num_solutions:
bits = np.reshape(bits, (num_solutions, bits.size // num_solutions))
bits = np.delete(bits, range(num_variables, bits.shape[1]), 1)
# Switch from bits to spins
default = 3
if msg['type'] == 'ising':
bits = bits.astype(np.int8)
bits *= 2
bits -= 1
default = 0
# Fill in the missing variables
solutions = np.full((num_solutions, total_variables), default, dtype=np.int8)
solutions[:, active_variables] = bits
result['solutions'] = solutions
# If the final result shouldn't be numpy formats switch back to python objects
if not return_matrix:
result['energies'] = result['energies'].tolist()
if 'num_occurrences' in result:
result['num_occurrences'] = result['num_occurrences'].tolist()
result['active_variables'] = result['active_variables'].tolist()
result['solutions'] = result['solutions'].tolist()
return result | [
"def",
"decode_qp_numpy",
"(",
"msg",
",",
"return_matrix",
"=",
"True",
")",
":",
"import",
"numpy",
"as",
"np",
"result",
"=",
"msg",
"[",
"'answer'",
"]",
"# Build some little endian type encodings",
"double_type",
"=",
"np",
".",
"dtype",
"(",
"np",
".",
"double",
")",
"double_type",
"=",
"double_type",
".",
"newbyteorder",
"(",
"'<'",
")",
"int_type",
"=",
"np",
".",
"dtype",
"(",
"np",
".",
"int32",
")",
"int_type",
"=",
"int_type",
".",
"newbyteorder",
"(",
"'<'",
")",
"# Decode the simple buffers",
"result",
"[",
"'energies'",
"]",
"=",
"np",
".",
"frombuffer",
"(",
"base64",
".",
"b64decode",
"(",
"result",
"[",
"'energies'",
"]",
")",
",",
"dtype",
"=",
"double_type",
")",
"if",
"'num_occurrences'",
"in",
"result",
":",
"result",
"[",
"'num_occurrences'",
"]",
"=",
"np",
".",
"frombuffer",
"(",
"base64",
".",
"b64decode",
"(",
"result",
"[",
"'num_occurrences'",
"]",
")",
",",
"dtype",
"=",
"int_type",
")",
"result",
"[",
"'active_variables'",
"]",
"=",
"np",
".",
"frombuffer",
"(",
"base64",
".",
"b64decode",
"(",
"result",
"[",
"'active_variables'",
"]",
")",
",",
"dtype",
"=",
"int_type",
")",
"# Measure out the binary data size",
"num_solutions",
"=",
"len",
"(",
"result",
"[",
"'energies'",
"]",
")",
"active_variables",
"=",
"result",
"[",
"'active_variables'",
"]",
"num_variables",
"=",
"len",
"(",
"active_variables",
")",
"total_variables",
"=",
"result",
"[",
"'num_variables'",
"]",
"# Decode the solutions, which will be a continuous run of bits",
"byte_type",
"=",
"np",
".",
"dtype",
"(",
"np",
".",
"uint8",
")",
"byte_type",
"=",
"byte_type",
".",
"newbyteorder",
"(",
"'<'",
")",
"bits",
"=",
"np",
".",
"unpackbits",
"(",
"np",
".",
"frombuffer",
"(",
"base64",
".",
"b64decode",
"(",
"result",
"[",
"'solutions'",
"]",
")",
",",
"dtype",
"=",
"byte_type",
")",
")",
"# Clip off the extra bits from encoding",
"if",
"num_solutions",
":",
"bits",
"=",
"np",
".",
"reshape",
"(",
"bits",
",",
"(",
"num_solutions",
",",
"bits",
".",
"size",
"//",
"num_solutions",
")",
")",
"bits",
"=",
"np",
".",
"delete",
"(",
"bits",
",",
"range",
"(",
"num_variables",
",",
"bits",
".",
"shape",
"[",
"1",
"]",
")",
",",
"1",
")",
"# Switch from bits to spins",
"default",
"=",
"3",
"if",
"msg",
"[",
"'type'",
"]",
"==",
"'ising'",
":",
"bits",
"=",
"bits",
".",
"astype",
"(",
"np",
".",
"int8",
")",
"bits",
"*=",
"2",
"bits",
"-=",
"1",
"default",
"=",
"0",
"# Fill in the missing variables",
"solutions",
"=",
"np",
".",
"full",
"(",
"(",
"num_solutions",
",",
"total_variables",
")",
",",
"default",
",",
"dtype",
"=",
"np",
".",
"int8",
")",
"solutions",
"[",
":",
",",
"active_variables",
"]",
"=",
"bits",
"result",
"[",
"'solutions'",
"]",
"=",
"solutions",
"# If the final result shouldn't be numpy formats switch back to python objects",
"if",
"not",
"return_matrix",
":",
"result",
"[",
"'energies'",
"]",
"=",
"result",
"[",
"'energies'",
"]",
".",
"tolist",
"(",
")",
"if",
"'num_occurrences'",
"in",
"result",
":",
"result",
"[",
"'num_occurrences'",
"]",
"=",
"result",
"[",
"'num_occurrences'",
"]",
".",
"tolist",
"(",
")",
"result",
"[",
"'active_variables'",
"]",
"=",
"result",
"[",
"'active_variables'",
"]",
".",
"tolist",
"(",
")",
"result",
"[",
"'solutions'",
"]",
"=",
"result",
"[",
"'solutions'",
"]",
".",
"tolist",
"(",
")",
"return",
"result"
] | Decode SAPI response, results in a `qp` format, explicitly using numpy.
If numpy is not installed, the method will fail.
To use numpy for decoding, but return the results a lists (instead of
numpy matrices), set `return_matrix=False`. | [
"Decode",
"SAPI",
"response",
"results",
"in",
"a",
"qp",
"format",
"explicitly",
"using",
"numpy",
".",
"If",
"numpy",
"is",
"not",
"installed",
"the",
"method",
"will",
"fail",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L172-L240 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/utils.py | evaluate_ising | def evaluate_ising(linear, quad, state):
"""Calculate the energy of a state given the Hamiltonian.
Args:
linear: Linear Hamiltonian terms.
quad: Quadratic Hamiltonian terms.
state: Vector of spins describing the system state.
Returns:
Energy of the state evaluated by the given energy function.
"""
# If we were given a numpy array cast to list
if _numpy and isinstance(state, np.ndarray):
return evaluate_ising(linear, quad, state.tolist())
# Accumulate the linear and quadratic values
energy = 0.0
for index, value in uniform_iterator(linear):
energy += state[index] * value
for (index_a, index_b), value in six.iteritems(quad):
energy += value * state[index_a] * state[index_b]
return energy | python | def evaluate_ising(linear, quad, state):
"""Calculate the energy of a state given the Hamiltonian.
Args:
linear: Linear Hamiltonian terms.
quad: Quadratic Hamiltonian terms.
state: Vector of spins describing the system state.
Returns:
Energy of the state evaluated by the given energy function.
"""
# If we were given a numpy array cast to list
if _numpy and isinstance(state, np.ndarray):
return evaluate_ising(linear, quad, state.tolist())
# Accumulate the linear and quadratic values
energy = 0.0
for index, value in uniform_iterator(linear):
energy += state[index] * value
for (index_a, index_b), value in six.iteritems(quad):
energy += value * state[index_a] * state[index_b]
return energy | [
"def",
"evaluate_ising",
"(",
"linear",
",",
"quad",
",",
"state",
")",
":",
"# If we were given a numpy array cast to list",
"if",
"_numpy",
"and",
"isinstance",
"(",
"state",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"evaluate_ising",
"(",
"linear",
",",
"quad",
",",
"state",
".",
"tolist",
"(",
")",
")",
"# Accumulate the linear and quadratic values",
"energy",
"=",
"0.0",
"for",
"index",
",",
"value",
"in",
"uniform_iterator",
"(",
"linear",
")",
":",
"energy",
"+=",
"state",
"[",
"index",
"]",
"*",
"value",
"for",
"(",
"index_a",
",",
"index_b",
")",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"quad",
")",
":",
"energy",
"+=",
"value",
"*",
"state",
"[",
"index_a",
"]",
"*",
"state",
"[",
"index_b",
"]",
"return",
"energy"
] | Calculate the energy of a state given the Hamiltonian.
Args:
linear: Linear Hamiltonian terms.
quad: Quadratic Hamiltonian terms.
state: Vector of spins describing the system state.
Returns:
Energy of the state evaluated by the given energy function. | [
"Calculate",
"the",
"energy",
"of",
"a",
"state",
"given",
"the",
"Hamiltonian",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L49-L71 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/utils.py | active_qubits | def active_qubits(linear, quadratic):
"""Calculate a set of all active qubits. Qubit is "active" if it has
bias or coupling attached.
Args:
linear (dict[variable, bias]/list[variable, bias]):
Linear terms of the model.
quadratic (dict[(variable, variable), bias]):
Quadratic terms of the model.
Returns:
set:
Active qubits' indices.
"""
active = {idx for idx,bias in uniform_iterator(linear)}
for edge, _ in six.iteritems(quadratic):
active.update(edge)
return active | python | def active_qubits(linear, quadratic):
"""Calculate a set of all active qubits. Qubit is "active" if it has
bias or coupling attached.
Args:
linear (dict[variable, bias]/list[variable, bias]):
Linear terms of the model.
quadratic (dict[(variable, variable), bias]):
Quadratic terms of the model.
Returns:
set:
Active qubits' indices.
"""
active = {idx for idx,bias in uniform_iterator(linear)}
for edge, _ in six.iteritems(quadratic):
active.update(edge)
return active | [
"def",
"active_qubits",
"(",
"linear",
",",
"quadratic",
")",
":",
"active",
"=",
"{",
"idx",
"for",
"idx",
",",
"bias",
"in",
"uniform_iterator",
"(",
"linear",
")",
"}",
"for",
"edge",
",",
"_",
"in",
"six",
".",
"iteritems",
"(",
"quadratic",
")",
":",
"active",
".",
"update",
"(",
"edge",
")",
"return",
"active"
] | Calculate a set of all active qubits. Qubit is "active" if it has
bias or coupling attached.
Args:
linear (dict[variable, bias]/list[variable, bias]):
Linear terms of the model.
quadratic (dict[(variable, variable), bias]):
Quadratic terms of the model.
Returns:
set:
Active qubits' indices. | [
"Calculate",
"a",
"set",
"of",
"all",
"active",
"qubits",
".",
"Qubit",
"is",
"active",
"if",
"it",
"has",
"bias",
"or",
"coupling",
"attached",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L74-L93 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/utils.py | generate_random_ising_problem | def generate_random_ising_problem(solver, h_range=None, j_range=None):
"""Generates an Ising problem formulation valid for a particular solver,
using all qubits and all couplings and linear/quadratic biases sampled
uniformly from `h_range`/`j_range`.
"""
if h_range is None:
h_range = solver.properties.get('h_range', [-1, 1])
if j_range is None:
j_range = solver.properties.get('j_range', [-1, 1])
lin = {qubit: random.uniform(*h_range) for qubit in solver.nodes}
quad = {edge: random.uniform(*j_range) for edge in solver.undirected_edges}
return lin, quad | python | def generate_random_ising_problem(solver, h_range=None, j_range=None):
"""Generates an Ising problem formulation valid for a particular solver,
using all qubits and all couplings and linear/quadratic biases sampled
uniformly from `h_range`/`j_range`.
"""
if h_range is None:
h_range = solver.properties.get('h_range', [-1, 1])
if j_range is None:
j_range = solver.properties.get('j_range', [-1, 1])
lin = {qubit: random.uniform(*h_range) for qubit in solver.nodes}
quad = {edge: random.uniform(*j_range) for edge in solver.undirected_edges}
return lin, quad | [
"def",
"generate_random_ising_problem",
"(",
"solver",
",",
"h_range",
"=",
"None",
",",
"j_range",
"=",
"None",
")",
":",
"if",
"h_range",
"is",
"None",
":",
"h_range",
"=",
"solver",
".",
"properties",
".",
"get",
"(",
"'h_range'",
",",
"[",
"-",
"1",
",",
"1",
"]",
")",
"if",
"j_range",
"is",
"None",
":",
"j_range",
"=",
"solver",
".",
"properties",
".",
"get",
"(",
"'j_range'",
",",
"[",
"-",
"1",
",",
"1",
"]",
")",
"lin",
"=",
"{",
"qubit",
":",
"random",
".",
"uniform",
"(",
"*",
"h_range",
")",
"for",
"qubit",
"in",
"solver",
".",
"nodes",
"}",
"quad",
"=",
"{",
"edge",
":",
"random",
".",
"uniform",
"(",
"*",
"j_range",
")",
"for",
"edge",
"in",
"solver",
".",
"undirected_edges",
"}",
"return",
"lin",
",",
"quad"
] | Generates an Ising problem formulation valid for a particular solver,
using all qubits and all couplings and linear/quadratic biases sampled
uniformly from `h_range`/`j_range`. | [
"Generates",
"an",
"Ising",
"problem",
"formulation",
"valid",
"for",
"a",
"particular",
"solver",
"using",
"all",
"qubits",
"and",
"all",
"couplings",
"and",
"linear",
"/",
"quadratic",
"biases",
"sampled",
"uniformly",
"from",
"h_range",
"/",
"j_range",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L96-L110 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/utils.py | uniform_iterator | def uniform_iterator(sequence):
"""Uniform (key, value) iteration on a `dict`,
or (idx, value) on a `list`."""
if isinstance(sequence, abc.Mapping):
return six.iteritems(sequence)
else:
return enumerate(sequence) | python | def uniform_iterator(sequence):
"""Uniform (key, value) iteration on a `dict`,
or (idx, value) on a `list`."""
if isinstance(sequence, abc.Mapping):
return six.iteritems(sequence)
else:
return enumerate(sequence) | [
"def",
"uniform_iterator",
"(",
"sequence",
")",
":",
"if",
"isinstance",
"(",
"sequence",
",",
"abc",
".",
"Mapping",
")",
":",
"return",
"six",
".",
"iteritems",
"(",
"sequence",
")",
"else",
":",
"return",
"enumerate",
"(",
"sequence",
")"
] | Uniform (key, value) iteration on a `dict`,
or (idx, value) on a `list`. | [
"Uniform",
"(",
"key",
"value",
")",
"iteration",
"on",
"a",
"dict",
"or",
"(",
"idx",
"value",
")",
"on",
"a",
"list",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L113-L120 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/utils.py | uniform_get | def uniform_get(sequence, index, default=None):
"""Uniform `dict`/`list` item getter, where `index` is interpreted as a key
for maps and as numeric index for lists."""
if isinstance(sequence, abc.Mapping):
return sequence.get(index, default)
else:
return sequence[index] if index < len(sequence) else default | python | def uniform_get(sequence, index, default=None):
"""Uniform `dict`/`list` item getter, where `index` is interpreted as a key
for maps and as numeric index for lists."""
if isinstance(sequence, abc.Mapping):
return sequence.get(index, default)
else:
return sequence[index] if index < len(sequence) else default | [
"def",
"uniform_get",
"(",
"sequence",
",",
"index",
",",
"default",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"sequence",
",",
"abc",
".",
"Mapping",
")",
":",
"return",
"sequence",
".",
"get",
"(",
"index",
",",
"default",
")",
"else",
":",
"return",
"sequence",
"[",
"index",
"]",
"if",
"index",
"<",
"len",
"(",
"sequence",
")",
"else",
"default"
] | Uniform `dict`/`list` item getter, where `index` is interpreted as a key
for maps and as numeric index for lists. | [
"Uniform",
"dict",
"/",
"list",
"item",
"getter",
"where",
"index",
"is",
"interpreted",
"as",
"a",
"key",
"for",
"maps",
"and",
"as",
"numeric",
"index",
"for",
"lists",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L123-L130 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/utils.py | strip_head | def strip_head(sequence, values):
"""Strips elements of `values` from the beginning of `sequence`."""
values = set(values)
return list(itertools.dropwhile(lambda x: x in values, sequence)) | python | def strip_head(sequence, values):
"""Strips elements of `values` from the beginning of `sequence`."""
values = set(values)
return list(itertools.dropwhile(lambda x: x in values, sequence)) | [
"def",
"strip_head",
"(",
"sequence",
",",
"values",
")",
":",
"values",
"=",
"set",
"(",
"values",
")",
"return",
"list",
"(",
"itertools",
".",
"dropwhile",
"(",
"lambda",
"x",
":",
"x",
"in",
"values",
",",
"sequence",
")",
")"
] | Strips elements of `values` from the beginning of `sequence`. | [
"Strips",
"elements",
"of",
"values",
"from",
"the",
"beginning",
"of",
"sequence",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L133-L136 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/utils.py | strip_tail | def strip_tail(sequence, values):
"""Strip `values` from the end of `sequence`."""
return list(reversed(list(strip_head(reversed(sequence), values)))) | python | def strip_tail(sequence, values):
"""Strip `values` from the end of `sequence`."""
return list(reversed(list(strip_head(reversed(sequence), values)))) | [
"def",
"strip_tail",
"(",
"sequence",
",",
"values",
")",
":",
"return",
"list",
"(",
"reversed",
"(",
"list",
"(",
"strip_head",
"(",
"reversed",
"(",
"sequence",
")",
",",
"values",
")",
")",
")",
")"
] | Strip `values` from the end of `sequence`. | [
"Strip",
"values",
"from",
"the",
"end",
"of",
"sequence",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L139-L141 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/utils.py | click_info_switch | def click_info_switch(f):
"""Decorator to create eager Click info switch option, as described in:
http://click.pocoo.org/6/options/#callbacks-and-eager-options.
Takes a no-argument function and abstracts the boilerplate required by
Click (value checking, exit on done).
Example:
@click.option('--my-option', is_flag=True, callback=my_option,
expose_value=False, is_eager=True)
def test():
pass
@click_info_switch
def my_option()
click.echo('some info related to my switch')
"""
@wraps(f)
def wrapped(ctx, param, value):
if not value or ctx.resilient_parsing:
return
f()
ctx.exit()
return wrapped | python | def click_info_switch(f):
"""Decorator to create eager Click info switch option, as described in:
http://click.pocoo.org/6/options/#callbacks-and-eager-options.
Takes a no-argument function and abstracts the boilerplate required by
Click (value checking, exit on done).
Example:
@click.option('--my-option', is_flag=True, callback=my_option,
expose_value=False, is_eager=True)
def test():
pass
@click_info_switch
def my_option()
click.echo('some info related to my switch')
"""
@wraps(f)
def wrapped(ctx, param, value):
if not value or ctx.resilient_parsing:
return
f()
ctx.exit()
return wrapped | [
"def",
"click_info_switch",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"not",
"value",
"or",
"ctx",
".",
"resilient_parsing",
":",
"return",
"f",
"(",
")",
"ctx",
".",
"exit",
"(",
")",
"return",
"wrapped"
] | Decorator to create eager Click info switch option, as described in:
http://click.pocoo.org/6/options/#callbacks-and-eager-options.
Takes a no-argument function and abstracts the boilerplate required by
Click (value checking, exit on done).
Example:
@click.option('--my-option', is_flag=True, callback=my_option,
expose_value=False, is_eager=True)
def test():
pass
@click_info_switch
def my_option()
click.echo('some info related to my switch') | [
"Decorator",
"to",
"create",
"eager",
"Click",
"info",
"switch",
"option",
"as",
"described",
"in",
":",
"http",
":",
"//",
"click",
".",
"pocoo",
".",
"org",
"/",
"6",
"/",
"options",
"/",
"#callbacks",
"-",
"and",
"-",
"eager",
"-",
"options",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L165-L190 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/utils.py | datetime_to_timestamp | def datetime_to_timestamp(dt):
"""Convert timezone-aware `datetime` to POSIX timestamp and
return seconds since UNIX epoch.
Note: similar to `datetime.timestamp()` in Python 3.3+.
"""
epoch = datetime.utcfromtimestamp(0).replace(tzinfo=UTC)
return (dt - epoch).total_seconds() | python | def datetime_to_timestamp(dt):
"""Convert timezone-aware `datetime` to POSIX timestamp and
return seconds since UNIX epoch.
Note: similar to `datetime.timestamp()` in Python 3.3+.
"""
epoch = datetime.utcfromtimestamp(0).replace(tzinfo=UTC)
return (dt - epoch).total_seconds() | [
"def",
"datetime_to_timestamp",
"(",
"dt",
")",
":",
"epoch",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"0",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"UTC",
")",
"return",
"(",
"dt",
"-",
"epoch",
")",
".",
"total_seconds",
"(",
")"
] | Convert timezone-aware `datetime` to POSIX timestamp and
return seconds since UNIX epoch.
Note: similar to `datetime.timestamp()` in Python 3.3+. | [
"Convert",
"timezone",
"-",
"aware",
"datetime",
"to",
"POSIX",
"timestamp",
"and",
"return",
"seconds",
"since",
"UNIX",
"epoch",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L193-L201 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/utils.py | user_agent | def user_agent(name, version):
"""Return User-Agent ~ "name/version language/version interpreter/version os/version"."""
def _interpreter():
name = platform.python_implementation()
version = platform.python_version()
bitness = platform.architecture()[0]
if name == 'PyPy':
version = '.'.join(map(str, sys.pypy_version_info[:3]))
full_version = [version]
if bitness:
full_version.append(bitness)
return name, "-".join(full_version)
tags = [
(name, version),
("python", platform.python_version()),
_interpreter(),
("machine", platform.machine() or 'unknown'),
("system", platform.system() or 'unknown'),
("platform", platform.platform() or 'unknown'),
]
return ' '.join("{}/{}".format(name, version) for name, version in tags) | python | def user_agent(name, version):
"""Return User-Agent ~ "name/version language/version interpreter/version os/version"."""
def _interpreter():
name = platform.python_implementation()
version = platform.python_version()
bitness = platform.architecture()[0]
if name == 'PyPy':
version = '.'.join(map(str, sys.pypy_version_info[:3]))
full_version = [version]
if bitness:
full_version.append(bitness)
return name, "-".join(full_version)
tags = [
(name, version),
("python", platform.python_version()),
_interpreter(),
("machine", platform.machine() or 'unknown'),
("system", platform.system() or 'unknown'),
("platform", platform.platform() or 'unknown'),
]
return ' '.join("{}/{}".format(name, version) for name, version in tags) | [
"def",
"user_agent",
"(",
"name",
",",
"version",
")",
":",
"def",
"_interpreter",
"(",
")",
":",
"name",
"=",
"platform",
".",
"python_implementation",
"(",
")",
"version",
"=",
"platform",
".",
"python_version",
"(",
")",
"bitness",
"=",
"platform",
".",
"architecture",
"(",
")",
"[",
"0",
"]",
"if",
"name",
"==",
"'PyPy'",
":",
"version",
"=",
"'.'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"sys",
".",
"pypy_version_info",
"[",
":",
"3",
"]",
")",
")",
"full_version",
"=",
"[",
"version",
"]",
"if",
"bitness",
":",
"full_version",
".",
"append",
"(",
"bitness",
")",
"return",
"name",
",",
"\"-\"",
".",
"join",
"(",
"full_version",
")",
"tags",
"=",
"[",
"(",
"name",
",",
"version",
")",
",",
"(",
"\"python\"",
",",
"platform",
".",
"python_version",
"(",
")",
")",
",",
"_interpreter",
"(",
")",
",",
"(",
"\"machine\"",
",",
"platform",
".",
"machine",
"(",
")",
"or",
"'unknown'",
")",
",",
"(",
"\"system\"",
",",
"platform",
".",
"system",
"(",
")",
"or",
"'unknown'",
")",
",",
"(",
"\"platform\"",
",",
"platform",
".",
"platform",
"(",
")",
"or",
"'unknown'",
")",
",",
"]",
"return",
"' '",
".",
"join",
"(",
"\"{}/{}\"",
".",
"format",
"(",
"name",
",",
"version",
")",
"for",
"name",
",",
"version",
"in",
"tags",
")"
] | Return User-Agent ~ "name/version language/version interpreter/version os/version". | [
"Return",
"User",
"-",
"Agent",
"~",
"name",
"/",
"version",
"language",
"/",
"version",
"interpreter",
"/",
"version",
"os",
"/",
"version",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L252-L275 | train |
dwavesystems/dwave-cloud-client | dwave/cloud/utils.py | cached.argshash | def argshash(self, args, kwargs):
"Hash mutable arguments' containers with immutable keys and values."
a = repr(args)
b = repr(sorted((repr(k), repr(v)) for k, v in kwargs.items()))
return a + b | python | def argshash(self, args, kwargs):
"Hash mutable arguments' containers with immutable keys and values."
a = repr(args)
b = repr(sorted((repr(k), repr(v)) for k, v in kwargs.items()))
return a + b | [
"def",
"argshash",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"a",
"=",
"repr",
"(",
"args",
")",
"b",
"=",
"repr",
"(",
"sorted",
"(",
"(",
"repr",
"(",
"k",
")",
",",
"repr",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
")",
")",
"return",
"a",
"+",
"b"
] | Hash mutable arguments' containers with immutable keys and values. | [
"Hash",
"mutable",
"arguments",
"containers",
"with",
"immutable",
"keys",
"and",
"values",
"."
] | df3221a8385dc0c04d7b4d84f740bf3ad6706230 | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L316-L320 | train |
bitlabstudio/django-user-media | user_media/views.py | UserMediaImageViewMixin.get_context_data | def get_context_data(self, **kwargs):
"""
Adds `next` to the context.
This makes sure that the `next` parameter doesn't get lost if the
form was submitted invalid.
"""
ctx = super(UserMediaImageViewMixin, self).get_context_data(**kwargs)
ctx.update({
'action': self.action,
'next': self.next,
})
return ctx | python | def get_context_data(self, **kwargs):
"""
Adds `next` to the context.
This makes sure that the `next` parameter doesn't get lost if the
form was submitted invalid.
"""
ctx = super(UserMediaImageViewMixin, self).get_context_data(**kwargs)
ctx.update({
'action': self.action,
'next': self.next,
})
return ctx | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"super",
"(",
"UserMediaImageViewMixin",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"update",
"(",
"{",
"'action'",
":",
"self",
".",
"action",
",",
"'next'",
":",
"self",
".",
"next",
",",
"}",
")",
"return",
"ctx"
] | Adds `next` to the context.
This makes sure that the `next` parameter doesn't get lost if the
form was submitted invalid. | [
"Adds",
"next",
"to",
"the",
"context",
"."
] | 63905aeb57640f116320ab8d7116e0ec35fde377 | https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/views.py#L34-L47 | train |
bitlabstudio/django-user-media | user_media/views.py | UserMediaImageViewMixin.get_success_url | def get_success_url(self):
"""
Returns the success URL.
This is either the given `next` URL parameter or the content object's
`get_absolute_url` method's return value.
"""
if self.next:
return self.next
if self.object and self.object.content_object:
return self.object.content_object.get_absolute_url()
raise Exception(
'No content object given. Please provide ``next`` in your POST'
' data') | python | def get_success_url(self):
"""
Returns the success URL.
This is either the given `next` URL parameter or the content object's
`get_absolute_url` method's return value.
"""
if self.next:
return self.next
if self.object and self.object.content_object:
return self.object.content_object.get_absolute_url()
raise Exception(
'No content object given. Please provide ``next`` in your POST'
' data') | [
"def",
"get_success_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"next",
":",
"return",
"self",
".",
"next",
"if",
"self",
".",
"object",
"and",
"self",
".",
"object",
".",
"content_object",
":",
"return",
"self",
".",
"object",
".",
"content_object",
".",
"get_absolute_url",
"(",
")",
"raise",
"Exception",
"(",
"'No content object given. Please provide ``next`` in your POST'",
"' data'",
")"
] | Returns the success URL.
This is either the given `next` URL parameter or the content object's
`get_absolute_url` method's return value. | [
"Returns",
"the",
"success",
"URL",
"."
] | 63905aeb57640f116320ab8d7116e0ec35fde377 | https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/views.py#L49-L63 | train |
bitlabstudio/django-user-media | user_media/views.py | CreateImageView.dispatch | def dispatch(self, request, *args, **kwargs):
"""Adds useful objects to the class and performs security checks."""
self._add_next_and_user(request)
self.content_object = None
self.content_type = None
self.object_id = kwargs.get('object_id', None)
if kwargs.get('content_type'):
# Check if the user forged the URL and posted a non existant
# content type
try:
self.content_type = ContentType.objects.get(
model=kwargs.get('content_type'))
except ContentType.DoesNotExist:
raise Http404
if self.content_type:
# Check if the user forged the URL and tries to append the image to
# an object that does not exist
try:
self.content_object = \
self.content_type.get_object_for_this_type(
pk=self.object_id)
except ObjectDoesNotExist:
raise Http404
if self.content_object and hasattr(self.content_object, 'user'):
# Check if the user forged the URL and tries to append the image to
# an object that does not belong to him
if not self.content_object.user == self.user:
raise Http404
return super(CreateImageView, self).dispatch(request, *args, **kwargs) | python | def dispatch(self, request, *args, **kwargs):
"""Adds useful objects to the class and performs security checks."""
self._add_next_and_user(request)
self.content_object = None
self.content_type = None
self.object_id = kwargs.get('object_id', None)
if kwargs.get('content_type'):
# Check if the user forged the URL and posted a non existant
# content type
try:
self.content_type = ContentType.objects.get(
model=kwargs.get('content_type'))
except ContentType.DoesNotExist:
raise Http404
if self.content_type:
# Check if the user forged the URL and tries to append the image to
# an object that does not exist
try:
self.content_object = \
self.content_type.get_object_for_this_type(
pk=self.object_id)
except ObjectDoesNotExist:
raise Http404
if self.content_object and hasattr(self.content_object, 'user'):
# Check if the user forged the URL and tries to append the image to
# an object that does not belong to him
if not self.content_object.user == self.user:
raise Http404
return super(CreateImageView, self).dispatch(request, *args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_add_next_and_user",
"(",
"request",
")",
"self",
".",
"content_object",
"=",
"None",
"self",
".",
"content_type",
"=",
"None",
"self",
".",
"object_id",
"=",
"kwargs",
".",
"get",
"(",
"'object_id'",
",",
"None",
")",
"if",
"kwargs",
".",
"get",
"(",
"'content_type'",
")",
":",
"# Check if the user forged the URL and posted a non existant",
"# content type",
"try",
":",
"self",
".",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"model",
"=",
"kwargs",
".",
"get",
"(",
"'content_type'",
")",
")",
"except",
"ContentType",
".",
"DoesNotExist",
":",
"raise",
"Http404",
"if",
"self",
".",
"content_type",
":",
"# Check if the user forged the URL and tries to append the image to",
"# an object that does not exist",
"try",
":",
"self",
".",
"content_object",
"=",
"self",
".",
"content_type",
".",
"get_object_for_this_type",
"(",
"pk",
"=",
"self",
".",
"object_id",
")",
"except",
"ObjectDoesNotExist",
":",
"raise",
"Http404",
"if",
"self",
".",
"content_object",
"and",
"hasattr",
"(",
"self",
".",
"content_object",
",",
"'user'",
")",
":",
"# Check if the user forged the URL and tries to append the image to",
"# an object that does not belong to him",
"if",
"not",
"self",
".",
"content_object",
".",
"user",
"==",
"self",
".",
"user",
":",
"raise",
"Http404",
"return",
"super",
"(",
"CreateImageView",
",",
"self",
")",
".",
"dispatch",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Adds useful objects to the class and performs security checks. | [
"Adds",
"useful",
"objects",
"to",
"the",
"class",
"and",
"performs",
"security",
"checks",
"."
] | 63905aeb57640f116320ab8d7116e0ec35fde377 | https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/views.py#L72-L104 | train |
bitlabstudio/django-user-media | user_media/views.py | DeleteImageView.dispatch | def dispatch(self, request, *args, **kwargs):
"""Adds useful objects to the class."""
self._add_next_and_user(request)
return super(DeleteImageView, self).dispatch(request, *args, **kwargs) | python | def dispatch(self, request, *args, **kwargs):
"""Adds useful objects to the class."""
self._add_next_and_user(request)
return super(DeleteImageView, self).dispatch(request, *args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_add_next_and_user",
"(",
"request",
")",
"return",
"super",
"(",
"DeleteImageView",
",",
"self",
")",
".",
"dispatch",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Adds useful objects to the class. | [
"Adds",
"useful",
"objects",
"to",
"the",
"class",
"."
] | 63905aeb57640f116320ab8d7116e0ec35fde377 | https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/views.py#L131-L134 | train |
bitlabstudio/django-user-media | user_media/views.py | DeleteImageView.get_queryset | def get_queryset(self):
"""
Making sure that a user can only delete his own images.
Even when he forges the request URL.
"""
queryset = super(DeleteImageView, self).get_queryset()
queryset = queryset.filter(user=self.user)
return queryset | python | def get_queryset(self):
"""
Making sure that a user can only delete his own images.
Even when he forges the request URL.
"""
queryset = super(DeleteImageView, self).get_queryset()
queryset = queryset.filter(user=self.user)
return queryset | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"queryset",
"=",
"super",
"(",
"DeleteImageView",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"user",
"=",
"self",
".",
"user",
")",
"return",
"queryset"
] | Making sure that a user can only delete his own images.
Even when he forges the request URL. | [
"Making",
"sure",
"that",
"a",
"user",
"can",
"only",
"delete",
"his",
"own",
"images",
"."
] | 63905aeb57640f116320ab8d7116e0ec35fde377 | https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/views.py#L143-L152 | train |
bitlabstudio/django-user-media | user_media/views.py | UpdateImageView.dispatch | def dispatch(self, request, *args, **kwargs):
"""Adds useful objects to the class."""
self._add_next_and_user(request)
return super(UpdateImageView, self).dispatch(request, *args, **kwargs) | python | def dispatch(self, request, *args, **kwargs):
"""Adds useful objects to the class."""
self._add_next_and_user(request)
return super(UpdateImageView, self).dispatch(request, *args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_add_next_and_user",
"(",
"request",
")",
"return",
"super",
"(",
"UpdateImageView",
",",
"self",
")",
".",
"dispatch",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Adds useful objects to the class. | [
"Adds",
"useful",
"objects",
"to",
"the",
"class",
"."
] | 63905aeb57640f116320ab8d7116e0ec35fde377 | https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/views.py#L163-L166 | train |
bitlabstudio/django-user-media | user_media/views.py | UpdateImageView.get_queryset | def get_queryset(self):
"""
Making sure that a user can only edit his own images.
Even when he forges the request URL.
"""
queryset = super(UpdateImageView, self).get_queryset()
queryset = queryset.filter(user=self.user)
return queryset | python | def get_queryset(self):
"""
Making sure that a user can only edit his own images.
Even when he forges the request URL.
"""
queryset = super(UpdateImageView, self).get_queryset()
queryset = queryset.filter(user=self.user)
return queryset | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"queryset",
"=",
"super",
"(",
"UpdateImageView",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"user",
"=",
"self",
".",
"user",
")",
"return",
"queryset"
] | Making sure that a user can only edit his own images.
Even when he forges the request URL. | [
"Making",
"sure",
"that",
"a",
"user",
"can",
"only",
"edit",
"his",
"own",
"images",
"."
] | 63905aeb57640f116320ab8d7116e0ec35fde377 | https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/views.py#L186-L195 | train |
bitlabstudio/django-user-media | user_media/forms.py | UserMediaImageFormMixin._delete_images | def _delete_images(self, instance):
"""Deletes all user media images of the given instance."""
UserMediaImage.objects.filter(
content_type=ContentType.objects.get_for_model(instance),
object_id=instance.pk,
user=instance.user,
).delete() | python | def _delete_images(self, instance):
"""Deletes all user media images of the given instance."""
UserMediaImage.objects.filter(
content_type=ContentType.objects.get_for_model(instance),
object_id=instance.pk,
user=instance.user,
).delete() | [
"def",
"_delete_images",
"(",
"self",
",",
"instance",
")",
":",
"UserMediaImage",
".",
"objects",
".",
"filter",
"(",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"instance",
")",
",",
"object_id",
"=",
"instance",
".",
"pk",
",",
"user",
"=",
"instance",
".",
"user",
",",
")",
".",
"delete",
"(",
")"
] | Deletes all user media images of the given instance. | [
"Deletes",
"all",
"user",
"media",
"images",
"of",
"the",
"given",
"instance",
"."
] | 63905aeb57640f116320ab8d7116e0ec35fde377 | https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/forms.py#L51-L57 | train |
bitlabstudio/django-user-media | user_media/forms.py | UserMediaImageForm.clean_image | def clean_image(self):
"""
It seems like in Django 1.5 something has changed.
When Django tries to validate the form, it checks if the generated
filename fit into the max_length. But at this point, self.instance.user
is not yet set so our filename generation function cannot create
the new file path because it needs the user id. Setting
self.instance.user at this point seems to work as a workaround.
"""
self.instance.user = self.user
data = self.cleaned_data.get('image')
return data | python | def clean_image(self):
"""
It seems like in Django 1.5 something has changed.
When Django tries to validate the form, it checks if the generated
filename fit into the max_length. But at this point, self.instance.user
is not yet set so our filename generation function cannot create
the new file path because it needs the user id. Setting
self.instance.user at this point seems to work as a workaround.
"""
self.instance.user = self.user
data = self.cleaned_data.get('image')
return data | [
"def",
"clean_image",
"(",
"self",
")",
":",
"self",
".",
"instance",
".",
"user",
"=",
"self",
".",
"user",
"data",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'image'",
")",
"return",
"data"
] | It seems like in Django 1.5 something has changed.
When Django tries to validate the form, it checks if the generated
filename fit into the max_length. But at this point, self.instance.user
is not yet set so our filename generation function cannot create
the new file path because it needs the user id. Setting
self.instance.user at this point seems to work as a workaround. | [
"It",
"seems",
"like",
"in",
"Django",
"1",
".",
"5",
"something",
"has",
"changed",
"."
] | 63905aeb57640f116320ab8d7116e0ec35fde377 | https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/forms.py#L90-L103 | train |
bitlabstudio/django-user-media | user_media/models.py | get_image_file_path | def get_image_file_path(instance, filename):
"""Returns a unique filename for images."""
ext = filename.split('.')[-1]
filename = '%s.%s' % (uuid.uuid4(), ext)
return os.path.join(
'user_media', str(instance.user.pk), 'images', filename) | python | def get_image_file_path(instance, filename):
"""Returns a unique filename for images."""
ext = filename.split('.')[-1]
filename = '%s.%s' % (uuid.uuid4(), ext)
return os.path.join(
'user_media', str(instance.user.pk), 'images', filename) | [
"def",
"get_image_file_path",
"(",
"instance",
",",
"filename",
")",
":",
"ext",
"=",
"filename",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"filename",
"=",
"'%s.%s'",
"%",
"(",
"uuid",
".",
"uuid4",
"(",
")",
",",
"ext",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"'user_media'",
",",
"str",
"(",
"instance",
".",
"user",
".",
"pk",
")",
",",
"'images'",
",",
"filename",
")"
] | Returns a unique filename for images. | [
"Returns",
"a",
"unique",
"filename",
"for",
"images",
"."
] | 63905aeb57640f116320ab8d7116e0ec35fde377 | https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/models.py#L15-L20 | train |
bitlabstudio/django-user-media | user_media/models.py | image_post_delete_handler | def image_post_delete_handler(sender, instance, **kwargs):
"""
Makes sure that a an image is also deleted from the media directory.
This should prevent a load of "dead" image files on disc.
"""
for f in glob.glob('{}/{}*'.format(instance.image.storage.location,
instance.image.name)):
if not os.path.isdir(f):
instance.image.storage.delete(f) | python | def image_post_delete_handler(sender, instance, **kwargs):
"""
Makes sure that a an image is also deleted from the media directory.
This should prevent a load of "dead" image files on disc.
"""
for f in glob.glob('{}/{}*'.format(instance.image.storage.location,
instance.image.name)):
if not os.path.isdir(f):
instance.image.storage.delete(f) | [
"def",
"image_post_delete_handler",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"f",
"in",
"glob",
".",
"glob",
"(",
"'{}/{}*'",
".",
"format",
"(",
"instance",
".",
"image",
".",
"storage",
".",
"location",
",",
"instance",
".",
"image",
".",
"name",
")",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"f",
")",
":",
"instance",
".",
"image",
".",
"storage",
".",
"delete",
"(",
"f",
")"
] | Makes sure that a an image is also deleted from the media directory.
This should prevent a load of "dead" image files on disc. | [
"Makes",
"sure",
"that",
"a",
"an",
"image",
"is",
"also",
"deleted",
"from",
"the",
"media",
"directory",
"."
] | 63905aeb57640f116320ab8d7116e0ec35fde377 | https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/models.py#L138-L148 | train |
bitlabstudio/django-user-media | user_media/models.py | UserMediaImage.box_coordinates | def box_coordinates(self):
"""Returns a thumbnail's coordinates."""
if (
self.thumb_x is not None and
self.thumb_y is not None and
self.thumb_x2 is not None and
self.thumb_y2 is not None
):
return (
int(self.thumb_x),
int(self.thumb_y),
int(self.thumb_x2),
int(self.thumb_y2),
)
return False | python | def box_coordinates(self):
"""Returns a thumbnail's coordinates."""
if (
self.thumb_x is not None and
self.thumb_y is not None and
self.thumb_x2 is not None and
self.thumb_y2 is not None
):
return (
int(self.thumb_x),
int(self.thumb_y),
int(self.thumb_x2),
int(self.thumb_y2),
)
return False | [
"def",
"box_coordinates",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"thumb_x",
"is",
"not",
"None",
"and",
"self",
".",
"thumb_y",
"is",
"not",
"None",
"and",
"self",
".",
"thumb_x2",
"is",
"not",
"None",
"and",
"self",
".",
"thumb_y2",
"is",
"not",
"None",
")",
":",
"return",
"(",
"int",
"(",
"self",
".",
"thumb_x",
")",
",",
"int",
"(",
"self",
".",
"thumb_y",
")",
",",
"int",
"(",
"self",
".",
"thumb_x2",
")",
",",
"int",
"(",
"self",
".",
"thumb_y2",
")",
",",
")",
"return",
"False"
] | Returns a thumbnail's coordinates. | [
"Returns",
"a",
"thumbnail",
"s",
"coordinates",
"."
] | 63905aeb57640f116320ab8d7116e0ec35fde377 | https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/models.py#L106-L120 | train |
bitlabstudio/django-user-media | user_media/models.py | UserMediaImage.large_size | def large_size(self, as_string=True):
"""Returns a thumbnail's large size."""
size = getattr(settings, 'USER_MEDIA_THUMB_SIZE_LARGE', (150, 150))
if as_string:
return u'{}x{}'.format(size[0], size[1])
return size | python | def large_size(self, as_string=True):
"""Returns a thumbnail's large size."""
size = getattr(settings, 'USER_MEDIA_THUMB_SIZE_LARGE', (150, 150))
if as_string:
return u'{}x{}'.format(size[0], size[1])
return size | [
"def",
"large_size",
"(",
"self",
",",
"as_string",
"=",
"True",
")",
":",
"size",
"=",
"getattr",
"(",
"settings",
",",
"'USER_MEDIA_THUMB_SIZE_LARGE'",
",",
"(",
"150",
",",
"150",
")",
")",
"if",
"as_string",
":",
"return",
"u'{}x{}'",
".",
"format",
"(",
"size",
"[",
"0",
"]",
",",
"size",
"[",
"1",
"]",
")",
"return",
"size"
] | Returns a thumbnail's large size. | [
"Returns",
"a",
"thumbnail",
"s",
"large",
"size",
"."
] | 63905aeb57640f116320ab8d7116e0ec35fde377 | https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/models.py#L122-L127 | train |
bitlabstudio/django-user-media | user_media/processors.py | crop_box | def crop_box(im, box=False, **kwargs):
"""Uses box coordinates to crop an image without resizing it first."""
if box:
im = im.crop(box)
return im | python | def crop_box(im, box=False, **kwargs):
"""Uses box coordinates to crop an image without resizing it first."""
if box:
im = im.crop(box)
return im | [
"def",
"crop_box",
"(",
"im",
",",
"box",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"box",
":",
"im",
"=",
"im",
".",
"crop",
"(",
"box",
")",
"return",
"im"
] | Uses box coordinates to crop an image without resizing it first. | [
"Uses",
"box",
"coordinates",
"to",
"crop",
"an",
"image",
"without",
"resizing",
"it",
"first",
"."
] | 63905aeb57640f116320ab8d7116e0ec35fde377 | https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/processors.py#L4-L8 | train |
wroberts/pygermanet | pygermanet/germanet.py | load_germanet | def load_germanet(host = None, port = None, database_name = 'germanet'):
'''
Loads a GermaNet instance connected to the given MongoDB instance.
Arguments:
- `host`: the hostname of the MongoDB instance
- `port`: the port number of the MongoDB instance
- `database_name`: the name of the GermaNet database on the
MongoDB instance
'''
client = MongoClient(host, port)
germanet_db = client[database_name]
return GermaNet(germanet_db) | python | def load_germanet(host = None, port = None, database_name = 'germanet'):
'''
Loads a GermaNet instance connected to the given MongoDB instance.
Arguments:
- `host`: the hostname of the MongoDB instance
- `port`: the port number of the MongoDB instance
- `database_name`: the name of the GermaNet database on the
MongoDB instance
'''
client = MongoClient(host, port)
germanet_db = client[database_name]
return GermaNet(germanet_db) | [
"def",
"load_germanet",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"database_name",
"=",
"'germanet'",
")",
":",
"client",
"=",
"MongoClient",
"(",
"host",
",",
"port",
")",
"germanet_db",
"=",
"client",
"[",
"database_name",
"]",
"return",
"GermaNet",
"(",
"germanet_db",
")"
] | Loads a GermaNet instance connected to the given MongoDB instance.
Arguments:
- `host`: the hostname of the MongoDB instance
- `port`: the port number of the MongoDB instance
- `database_name`: the name of the GermaNet database on the
MongoDB instance | [
"Loads",
"a",
"GermaNet",
"instance",
"connected",
"to",
"the",
"given",
"MongoDB",
"instance",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L664-L676 | train |
wroberts/pygermanet | pygermanet/germanet.py | GermaNet.cache_size | def cache_size(self, new_value):
'''
Set the cache size used to reduce the number of database
access operations.
'''
if type(new_value) == int and 0 < new_value:
if self._lemma_cache is not None:
self._lemma_cache = repoze.lru.LRUCache(new_value)
self._synset_cache = repoze.lru.LRUCache(new_value) | python | def cache_size(self, new_value):
'''
Set the cache size used to reduce the number of database
access operations.
'''
if type(new_value) == int and 0 < new_value:
if self._lemma_cache is not None:
self._lemma_cache = repoze.lru.LRUCache(new_value)
self._synset_cache = repoze.lru.LRUCache(new_value) | [
"def",
"cache_size",
"(",
"self",
",",
"new_value",
")",
":",
"if",
"type",
"(",
"new_value",
")",
"==",
"int",
"and",
"0",
"<",
"new_value",
":",
"if",
"self",
".",
"_lemma_cache",
"is",
"not",
"None",
":",
"self",
".",
"_lemma_cache",
"=",
"repoze",
".",
"lru",
".",
"LRUCache",
"(",
"new_value",
")",
"self",
".",
"_synset_cache",
"=",
"repoze",
".",
"lru",
".",
"LRUCache",
"(",
"new_value",
")"
] | Set the cache size used to reduce the number of database
access operations. | [
"Set",
"the",
"cache",
"size",
"used",
"to",
"reduce",
"the",
"number",
"of",
"database",
"access",
"operations",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L75-L83 | train |
wroberts/pygermanet | pygermanet/germanet.py | GermaNet.all_lemmas | def all_lemmas(self):
'''
A generator over all the lemmas in the GermaNet database.
'''
for lemma_dict in self._mongo_db.lexunits.find():
yield Lemma(self, lemma_dict) | python | def all_lemmas(self):
'''
A generator over all the lemmas in the GermaNet database.
'''
for lemma_dict in self._mongo_db.lexunits.find():
yield Lemma(self, lemma_dict) | [
"def",
"all_lemmas",
"(",
"self",
")",
":",
"for",
"lemma_dict",
"in",
"self",
".",
"_mongo_db",
".",
"lexunits",
".",
"find",
"(",
")",
":",
"yield",
"Lemma",
"(",
"self",
",",
"lemma_dict",
")"
] | A generator over all the lemmas in the GermaNet database. | [
"A",
"generator",
"over",
"all",
"the",
"lemmas",
"in",
"the",
"GermaNet",
"database",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L85-L90 | train |
wroberts/pygermanet | pygermanet/germanet.py | GermaNet.lemmas | def lemmas(self, lemma, pos = None):
'''
Looks up lemmas in the GermaNet database.
Arguments:
- `lemma`:
- `pos`:
'''
if pos is not None:
if pos not in SHORT_POS_TO_LONG:
return None
pos = SHORT_POS_TO_LONG[pos]
lemma_dicts = self._mongo_db.lexunits.find({'orthForm': lemma,
'category': pos})
else:
lemma_dicts = self._mongo_db.lexunits.find({'orthForm': lemma})
return sorted([Lemma(self, lemma_dict) for lemma_dict in lemma_dicts]) | python | def lemmas(self, lemma, pos = None):
'''
Looks up lemmas in the GermaNet database.
Arguments:
- `lemma`:
- `pos`:
'''
if pos is not None:
if pos not in SHORT_POS_TO_LONG:
return None
pos = SHORT_POS_TO_LONG[pos]
lemma_dicts = self._mongo_db.lexunits.find({'orthForm': lemma,
'category': pos})
else:
lemma_dicts = self._mongo_db.lexunits.find({'orthForm': lemma})
return sorted([Lemma(self, lemma_dict) for lemma_dict in lemma_dicts]) | [
"def",
"lemmas",
"(",
"self",
",",
"lemma",
",",
"pos",
"=",
"None",
")",
":",
"if",
"pos",
"is",
"not",
"None",
":",
"if",
"pos",
"not",
"in",
"SHORT_POS_TO_LONG",
":",
"return",
"None",
"pos",
"=",
"SHORT_POS_TO_LONG",
"[",
"pos",
"]",
"lemma_dicts",
"=",
"self",
".",
"_mongo_db",
".",
"lexunits",
".",
"find",
"(",
"{",
"'orthForm'",
":",
"lemma",
",",
"'category'",
":",
"pos",
"}",
")",
"else",
":",
"lemma_dicts",
"=",
"self",
".",
"_mongo_db",
".",
"lexunits",
".",
"find",
"(",
"{",
"'orthForm'",
":",
"lemma",
"}",
")",
"return",
"sorted",
"(",
"[",
"Lemma",
"(",
"self",
",",
"lemma_dict",
")",
"for",
"lemma_dict",
"in",
"lemma_dicts",
"]",
")"
] | Looks up lemmas in the GermaNet database.
Arguments:
- `lemma`:
- `pos`: | [
"Looks",
"up",
"lemmas",
"in",
"the",
"GermaNet",
"database",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L92-L108 | train |
wroberts/pygermanet | pygermanet/germanet.py | GermaNet.all_synsets | def all_synsets(self):
'''
A generator over all the synsets in the GermaNet database.
'''
for synset_dict in self._mongo_db.synsets.find():
yield Synset(self, synset_dict) | python | def all_synsets(self):
'''
A generator over all the synsets in the GermaNet database.
'''
for synset_dict in self._mongo_db.synsets.find():
yield Synset(self, synset_dict) | [
"def",
"all_synsets",
"(",
"self",
")",
":",
"for",
"synset_dict",
"in",
"self",
".",
"_mongo_db",
".",
"synsets",
".",
"find",
"(",
")",
":",
"yield",
"Synset",
"(",
"self",
",",
"synset_dict",
")"
] | A generator over all the synsets in the GermaNet database. | [
"A",
"generator",
"over",
"all",
"the",
"synsets",
"in",
"the",
"GermaNet",
"database",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L110-L115 | train |
wroberts/pygermanet | pygermanet/germanet.py | GermaNet.synsets | def synsets(self, lemma, pos = None):
'''
Looks up synsets in the GermaNet database.
Arguments:
- `lemma`:
- `pos`:
'''
return sorted(set(lemma_obj.synset
for lemma_obj in self.lemmas(lemma, pos))) | python | def synsets(self, lemma, pos = None):
'''
Looks up synsets in the GermaNet database.
Arguments:
- `lemma`:
- `pos`:
'''
return sorted(set(lemma_obj.synset
for lemma_obj in self.lemmas(lemma, pos))) | [
"def",
"synsets",
"(",
"self",
",",
"lemma",
",",
"pos",
"=",
"None",
")",
":",
"return",
"sorted",
"(",
"set",
"(",
"lemma_obj",
".",
"synset",
"for",
"lemma_obj",
"in",
"self",
".",
"lemmas",
"(",
"lemma",
",",
"pos",
")",
")",
")"
] | Looks up synsets in the GermaNet database.
Arguments:
- `lemma`:
- `pos`: | [
"Looks",
"up",
"synsets",
"in",
"the",
"GermaNet",
"database",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L117-L126 | train |
wroberts/pygermanet | pygermanet/germanet.py | GermaNet.synset | def synset(self, synset_repr):
'''
Looks up a synset in GermaNet using its string representation.
Arguments:
- `synset_repr`: a unicode string containing the lemma, part
of speech, and sense number of the first lemma of the synset
>>> gn.synset(u'funktionieren.v.2')
Synset(funktionieren.v.2)
'''
parts = synset_repr.split('.')
if len(parts) != 3:
return None
lemma, pos, sensenum = parts
if not sensenum.isdigit() or pos not in SHORT_POS_TO_LONG:
return None
sensenum = int(sensenum, 10)
pos = SHORT_POS_TO_LONG[pos]
lemma_dict = self._mongo_db.lexunits.find_one({'orthForm': lemma,
'category': pos,
'sense': sensenum})
if lemma_dict:
return Lemma(self, lemma_dict).synset | python | def synset(self, synset_repr):
'''
Looks up a synset in GermaNet using its string representation.
Arguments:
- `synset_repr`: a unicode string containing the lemma, part
of speech, and sense number of the first lemma of the synset
>>> gn.synset(u'funktionieren.v.2')
Synset(funktionieren.v.2)
'''
parts = synset_repr.split('.')
if len(parts) != 3:
return None
lemma, pos, sensenum = parts
if not sensenum.isdigit() or pos not in SHORT_POS_TO_LONG:
return None
sensenum = int(sensenum, 10)
pos = SHORT_POS_TO_LONG[pos]
lemma_dict = self._mongo_db.lexunits.find_one({'orthForm': lemma,
'category': pos,
'sense': sensenum})
if lemma_dict:
return Lemma(self, lemma_dict).synset | [
"def",
"synset",
"(",
"self",
",",
"synset_repr",
")",
":",
"parts",
"=",
"synset_repr",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
"!=",
"3",
":",
"return",
"None",
"lemma",
",",
"pos",
",",
"sensenum",
"=",
"parts",
"if",
"not",
"sensenum",
".",
"isdigit",
"(",
")",
"or",
"pos",
"not",
"in",
"SHORT_POS_TO_LONG",
":",
"return",
"None",
"sensenum",
"=",
"int",
"(",
"sensenum",
",",
"10",
")",
"pos",
"=",
"SHORT_POS_TO_LONG",
"[",
"pos",
"]",
"lemma_dict",
"=",
"self",
".",
"_mongo_db",
".",
"lexunits",
".",
"find_one",
"(",
"{",
"'orthForm'",
":",
"lemma",
",",
"'category'",
":",
"pos",
",",
"'sense'",
":",
"sensenum",
"}",
")",
"if",
"lemma_dict",
":",
"return",
"Lemma",
"(",
"self",
",",
"lemma_dict",
")",
".",
"synset"
] | Looks up a synset in GermaNet using its string representation.
Arguments:
- `synset_repr`: a unicode string containing the lemma, part
of speech, and sense number of the first lemma of the synset
>>> gn.synset(u'funktionieren.v.2')
Synset(funktionieren.v.2) | [
"Looks",
"up",
"a",
"synset",
"in",
"GermaNet",
"using",
"its",
"string",
"representation",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L128-L151 | train |
wroberts/pygermanet | pygermanet/germanet.py | GermaNet.get_synset_by_id | def get_synset_by_id(self, mongo_id):
'''
Builds a Synset object from the database entry with the given
ObjectId.
Arguments:
- `mongo_id`: a bson.objectid.ObjectId object
'''
cache_hit = None
if self._synset_cache is not None:
cache_hit = self._synset_cache.get(mongo_id)
if cache_hit is not None:
return cache_hit
synset_dict = self._mongo_db.synsets.find_one({'_id': mongo_id})
if synset_dict is not None:
synset = Synset(self, synset_dict)
if self._synset_cache is not None:
self._synset_cache.put(mongo_id, synset)
return synset | python | def get_synset_by_id(self, mongo_id):
'''
Builds a Synset object from the database entry with the given
ObjectId.
Arguments:
- `mongo_id`: a bson.objectid.ObjectId object
'''
cache_hit = None
if self._synset_cache is not None:
cache_hit = self._synset_cache.get(mongo_id)
if cache_hit is not None:
return cache_hit
synset_dict = self._mongo_db.synsets.find_one({'_id': mongo_id})
if synset_dict is not None:
synset = Synset(self, synset_dict)
if self._synset_cache is not None:
self._synset_cache.put(mongo_id, synset)
return synset | [
"def",
"get_synset_by_id",
"(",
"self",
",",
"mongo_id",
")",
":",
"cache_hit",
"=",
"None",
"if",
"self",
".",
"_synset_cache",
"is",
"not",
"None",
":",
"cache_hit",
"=",
"self",
".",
"_synset_cache",
".",
"get",
"(",
"mongo_id",
")",
"if",
"cache_hit",
"is",
"not",
"None",
":",
"return",
"cache_hit",
"synset_dict",
"=",
"self",
".",
"_mongo_db",
".",
"synsets",
".",
"find_one",
"(",
"{",
"'_id'",
":",
"mongo_id",
"}",
")",
"if",
"synset_dict",
"is",
"not",
"None",
":",
"synset",
"=",
"Synset",
"(",
"self",
",",
"synset_dict",
")",
"if",
"self",
".",
"_synset_cache",
"is",
"not",
"None",
":",
"self",
".",
"_synset_cache",
".",
"put",
"(",
"mongo_id",
",",
"synset",
")",
"return",
"synset"
] | Builds a Synset object from the database entry with the given
ObjectId.
Arguments:
- `mongo_id`: a bson.objectid.ObjectId object | [
"Builds",
"a",
"Synset",
"object",
"from",
"the",
"database",
"entry",
"with",
"the",
"given",
"ObjectId",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L153-L171 | train |
wroberts/pygermanet | pygermanet/germanet.py | GermaNet.get_lemma_by_id | def get_lemma_by_id(self, mongo_id):
'''
Builds a Lemma object from the database entry with the given
ObjectId.
Arguments:
- `mongo_id`: a bson.objectid.ObjectId object
'''
cache_hit = None
if self._lemma_cache is not None:
cache_hit = self._lemma_cache.get(mongo_id)
if cache_hit is not None:
return cache_hit
lemma_dict = self._mongo_db.lexunits.find_one({'_id': mongo_id})
if lemma_dict is not None:
lemma = Lemma(self, lemma_dict)
if self._lemma_cache is not None:
self._lemma_cache.put(mongo_id, lemma)
return lemma | python | def get_lemma_by_id(self, mongo_id):
'''
Builds a Lemma object from the database entry with the given
ObjectId.
Arguments:
- `mongo_id`: a bson.objectid.ObjectId object
'''
cache_hit = None
if self._lemma_cache is not None:
cache_hit = self._lemma_cache.get(mongo_id)
if cache_hit is not None:
return cache_hit
lemma_dict = self._mongo_db.lexunits.find_one({'_id': mongo_id})
if lemma_dict is not None:
lemma = Lemma(self, lemma_dict)
if self._lemma_cache is not None:
self._lemma_cache.put(mongo_id, lemma)
return lemma | [
"def",
"get_lemma_by_id",
"(",
"self",
",",
"mongo_id",
")",
":",
"cache_hit",
"=",
"None",
"if",
"self",
".",
"_lemma_cache",
"is",
"not",
"None",
":",
"cache_hit",
"=",
"self",
".",
"_lemma_cache",
".",
"get",
"(",
"mongo_id",
")",
"if",
"cache_hit",
"is",
"not",
"None",
":",
"return",
"cache_hit",
"lemma_dict",
"=",
"self",
".",
"_mongo_db",
".",
"lexunits",
".",
"find_one",
"(",
"{",
"'_id'",
":",
"mongo_id",
"}",
")",
"if",
"lemma_dict",
"is",
"not",
"None",
":",
"lemma",
"=",
"Lemma",
"(",
"self",
",",
"lemma_dict",
")",
"if",
"self",
".",
"_lemma_cache",
"is",
"not",
"None",
":",
"self",
".",
"_lemma_cache",
".",
"put",
"(",
"mongo_id",
",",
"lemma",
")",
"return",
"lemma"
] | Builds a Lemma object from the database entry with the given
ObjectId.
Arguments:
- `mongo_id`: a bson.objectid.ObjectId object | [
"Builds",
"a",
"Lemma",
"object",
"from",
"the",
"database",
"entry",
"with",
"the",
"given",
"ObjectId",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L173-L191 | train |
wroberts/pygermanet | pygermanet/germanet.py | GermaNet.lemmatise | def lemmatise(self, word):
'''
Tries to find the base form (lemma) of the given word, using
the data provided by the Projekt deutscher Wortschatz. This
method returns a list of potential lemmas.
>>> gn.lemmatise(u'Männer')
[u'Mann']
>>> gn.lemmatise(u'XYZ123')
[u'XYZ123']
'''
lemmas = list(self._mongo_db.lemmatiser.find({'word': word}))
if lemmas:
return [lemma['lemma'] for lemma in lemmas]
else:
return [word] | python | def lemmatise(self, word):
'''
Tries to find the base form (lemma) of the given word, using
the data provided by the Projekt deutscher Wortschatz. This
method returns a list of potential lemmas.
>>> gn.lemmatise(u'Männer')
[u'Mann']
>>> gn.lemmatise(u'XYZ123')
[u'XYZ123']
'''
lemmas = list(self._mongo_db.lemmatiser.find({'word': word}))
if lemmas:
return [lemma['lemma'] for lemma in lemmas]
else:
return [word] | [
"def",
"lemmatise",
"(",
"self",
",",
"word",
")",
":",
"lemmas",
"=",
"list",
"(",
"self",
".",
"_mongo_db",
".",
"lemmatiser",
".",
"find",
"(",
"{",
"'word'",
":",
"word",
"}",
")",
")",
"if",
"lemmas",
":",
"return",
"[",
"lemma",
"[",
"'lemma'",
"]",
"for",
"lemma",
"in",
"lemmas",
"]",
"else",
":",
"return",
"[",
"word",
"]"
] | Tries to find the base form (lemma) of the given word, using
the data provided by the Projekt deutscher Wortschatz. This
method returns a list of potential lemmas.
>>> gn.lemmatise(u'Männer')
[u'Mann']
>>> gn.lemmatise(u'XYZ123')
[u'XYZ123'] | [
"Tries",
"to",
"find",
"the",
"base",
"form",
"(",
"lemma",
")",
"of",
"the",
"given",
"word",
"using",
"the",
"data",
"provided",
"by",
"the",
"Projekt",
"deutscher",
"Wortschatz",
".",
"This",
"method",
"returns",
"a",
"list",
"of",
"potential",
"lemmas",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L193-L208 | train |
wroberts/pygermanet | pygermanet/mongo_import.py | find_germanet_xml_files | def find_germanet_xml_files(xml_path):
'''
Globs the XML files contained in the given directory and sorts
them into sections for import into the MongoDB database.
Arguments:
- `xml_path`: the path to the directory containing the GermaNet
XML files
'''
xml_files = sorted(glob.glob(os.path.join(xml_path, '*.xml')))
# sort out the lexical files
lex_files = [xml_file for xml_file in xml_files if
re.match(r'(adj|nomen|verben)\.',
os.path.basename(xml_file).lower())]
xml_files = sorted(set(xml_files) - set(lex_files))
if not lex_files:
print('ERROR: cannot find lexical information files')
# sort out the GermaNet relations file
gn_rels_file = [xml_file for xml_file in xml_files if
os.path.basename(xml_file).lower() == 'gn_relations.xml']
xml_files = sorted(set(xml_files) - set(gn_rels_file))
if not gn_rels_file:
print('ERROR: cannot find relations file gn_relations.xml')
gn_rels_file = None
else:
if 1 < len(gn_rels_file):
print ('WARNING: more than one relations file gn_relations.xml, '
'taking first match')
gn_rels_file = gn_rels_file[0]
# sort out the wiktionary paraphrase files
wiktionary_files = [xml_file for xml_file in xml_files if
re.match(r'wiktionaryparaphrases-',
os.path.basename(xml_file).lower())]
xml_files = sorted(set(xml_files) - set(wiktionary_files))
if not wiktionary_files:
print('WARNING: cannot find wiktionary paraphrase files')
# sort out the interlingual index file
ili_files = [xml_file for xml_file in xml_files if
os.path.basename(xml_file).lower().startswith(
'interlingualindex')]
xml_files = sorted(set(xml_files) - set(ili_files))
if not ili_files:
print('WARNING: cannot find interlingual index file')
if xml_files:
print('WARNING: unrecognised xml files:', xml_files)
return lex_files, gn_rels_file, wiktionary_files, ili_files | python | def find_germanet_xml_files(xml_path):
'''
Globs the XML files contained in the given directory and sorts
them into sections for import into the MongoDB database.
Arguments:
- `xml_path`: the path to the directory containing the GermaNet
XML files
'''
xml_files = sorted(glob.glob(os.path.join(xml_path, '*.xml')))
# sort out the lexical files
lex_files = [xml_file for xml_file in xml_files if
re.match(r'(adj|nomen|verben)\.',
os.path.basename(xml_file).lower())]
xml_files = sorted(set(xml_files) - set(lex_files))
if not lex_files:
print('ERROR: cannot find lexical information files')
# sort out the GermaNet relations file
gn_rels_file = [xml_file for xml_file in xml_files if
os.path.basename(xml_file).lower() == 'gn_relations.xml']
xml_files = sorted(set(xml_files) - set(gn_rels_file))
if not gn_rels_file:
print('ERROR: cannot find relations file gn_relations.xml')
gn_rels_file = None
else:
if 1 < len(gn_rels_file):
print ('WARNING: more than one relations file gn_relations.xml, '
'taking first match')
gn_rels_file = gn_rels_file[0]
# sort out the wiktionary paraphrase files
wiktionary_files = [xml_file for xml_file in xml_files if
re.match(r'wiktionaryparaphrases-',
os.path.basename(xml_file).lower())]
xml_files = sorted(set(xml_files) - set(wiktionary_files))
if not wiktionary_files:
print('WARNING: cannot find wiktionary paraphrase files')
# sort out the interlingual index file
ili_files = [xml_file for xml_file in xml_files if
os.path.basename(xml_file).lower().startswith(
'interlingualindex')]
xml_files = sorted(set(xml_files) - set(ili_files))
if not ili_files:
print('WARNING: cannot find interlingual index file')
if xml_files:
print('WARNING: unrecognised xml files:', xml_files)
return lex_files, gn_rels_file, wiktionary_files, ili_files | [
"def",
"find_germanet_xml_files",
"(",
"xml_path",
")",
":",
"xml_files",
"=",
"sorted",
"(",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"xml_path",
",",
"'*.xml'",
")",
")",
")",
"# sort out the lexical files",
"lex_files",
"=",
"[",
"xml_file",
"for",
"xml_file",
"in",
"xml_files",
"if",
"re",
".",
"match",
"(",
"r'(adj|nomen|verben)\\.'",
",",
"os",
".",
"path",
".",
"basename",
"(",
"xml_file",
")",
".",
"lower",
"(",
")",
")",
"]",
"xml_files",
"=",
"sorted",
"(",
"set",
"(",
"xml_files",
")",
"-",
"set",
"(",
"lex_files",
")",
")",
"if",
"not",
"lex_files",
":",
"print",
"(",
"'ERROR: cannot find lexical information files'",
")",
"# sort out the GermaNet relations file",
"gn_rels_file",
"=",
"[",
"xml_file",
"for",
"xml_file",
"in",
"xml_files",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"xml_file",
")",
".",
"lower",
"(",
")",
"==",
"'gn_relations.xml'",
"]",
"xml_files",
"=",
"sorted",
"(",
"set",
"(",
"xml_files",
")",
"-",
"set",
"(",
"gn_rels_file",
")",
")",
"if",
"not",
"gn_rels_file",
":",
"print",
"(",
"'ERROR: cannot find relations file gn_relations.xml'",
")",
"gn_rels_file",
"=",
"None",
"else",
":",
"if",
"1",
"<",
"len",
"(",
"gn_rels_file",
")",
":",
"print",
"(",
"'WARNING: more than one relations file gn_relations.xml, '",
"'taking first match'",
")",
"gn_rels_file",
"=",
"gn_rels_file",
"[",
"0",
"]",
"# sort out the wiktionary paraphrase files",
"wiktionary_files",
"=",
"[",
"xml_file",
"for",
"xml_file",
"in",
"xml_files",
"if",
"re",
".",
"match",
"(",
"r'wiktionaryparaphrases-'",
",",
"os",
".",
"path",
".",
"basename",
"(",
"xml_file",
")",
".",
"lower",
"(",
")",
")",
"]",
"xml_files",
"=",
"sorted",
"(",
"set",
"(",
"xml_files",
")",
"-",
"set",
"(",
"wiktionary_files",
")",
")",
"if",
"not",
"wiktionary_files",
":",
"print",
"(",
"'WARNING: cannot find wiktionary paraphrase files'",
")",
"# sort out the interlingual index file",
"ili_files",
"=",
"[",
"xml_file",
"for",
"xml_file",
"in",
"xml_files",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"xml_file",
")",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'interlingualindex'",
")",
"]",
"xml_files",
"=",
"sorted",
"(",
"set",
"(",
"xml_files",
")",
"-",
"set",
"(",
"ili_files",
")",
")",
"if",
"not",
"ili_files",
":",
"print",
"(",
"'WARNING: cannot find interlingual index file'",
")",
"if",
"xml_files",
":",
"print",
"(",
"'WARNING: unrecognised xml files:'",
",",
"xml_files",
")",
"return",
"lex_files",
",",
"gn_rels_file",
",",
"wiktionary_files",
",",
"ili_files"
] | Globs the XML files contained in the given directory and sorts
them into sections for import into the MongoDB database.
Arguments:
- `xml_path`: the path to the directory containing the GermaNet
XML files | [
"Globs",
"the",
"XML",
"files",
"contained",
"in",
"the",
"given",
"directory",
"and",
"sorts",
"them",
"into",
"sections",
"for",
"import",
"into",
"the",
"MongoDB",
"database",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L30-L85 | train |
wroberts/pygermanet | pygermanet/mongo_import.py | warn_attribs | def warn_attribs(loc,
node,
recognised_attribs,
reqd_attribs=None):
'''
Error checking of XML input: check that the given node has certain
required attributes, and does not have any unrecognised
attributes.
Arguments:
- `loc`: a string with some information about the location of the
error in the XML file
- `node`: the node to check
- `recognised_attribs`: a set of node attributes which we know how
to handle
- `reqd_attribs`: a set of node attributes which we require to be
present; if this argument is None, it will take the same value
as `recognised_attribs`
'''
if reqd_attribs is None:
reqd_attribs = recognised_attribs
found_attribs = set(node.keys())
if reqd_attribs - found_attribs:
print(loc, 'missing <{0}> attributes'.format(node.tag),
reqd_attribs - found_attribs)
if found_attribs - recognised_attribs:
print(loc, 'unrecognised <{0}> properties'.format(node.tag),
found_attribs - recognised_attribs) | python | def warn_attribs(loc,
node,
recognised_attribs,
reqd_attribs=None):
'''
Error checking of XML input: check that the given node has certain
required attributes, and does not have any unrecognised
attributes.
Arguments:
- `loc`: a string with some information about the location of the
error in the XML file
- `node`: the node to check
- `recognised_attribs`: a set of node attributes which we know how
to handle
- `reqd_attribs`: a set of node attributes which we require to be
present; if this argument is None, it will take the same value
as `recognised_attribs`
'''
if reqd_attribs is None:
reqd_attribs = recognised_attribs
found_attribs = set(node.keys())
if reqd_attribs - found_attribs:
print(loc, 'missing <{0}> attributes'.format(node.tag),
reqd_attribs - found_attribs)
if found_attribs - recognised_attribs:
print(loc, 'unrecognised <{0}> properties'.format(node.tag),
found_attribs - recognised_attribs) | [
"def",
"warn_attribs",
"(",
"loc",
",",
"node",
",",
"recognised_attribs",
",",
"reqd_attribs",
"=",
"None",
")",
":",
"if",
"reqd_attribs",
"is",
"None",
":",
"reqd_attribs",
"=",
"recognised_attribs",
"found_attribs",
"=",
"set",
"(",
"node",
".",
"keys",
"(",
")",
")",
"if",
"reqd_attribs",
"-",
"found_attribs",
":",
"print",
"(",
"loc",
",",
"'missing <{0}> attributes'",
".",
"format",
"(",
"node",
".",
"tag",
")",
",",
"reqd_attribs",
"-",
"found_attribs",
")",
"if",
"found_attribs",
"-",
"recognised_attribs",
":",
"print",
"(",
"loc",
",",
"'unrecognised <{0}> properties'",
".",
"format",
"(",
"node",
".",
"tag",
")",
",",
"found_attribs",
"-",
"recognised_attribs",
")"
] | Error checking of XML input: check that the given node has certain
required attributes, and does not have any unrecognised
attributes.
Arguments:
- `loc`: a string with some information about the location of the
error in the XML file
- `node`: the node to check
- `recognised_attribs`: a set of node attributes which we know how
to handle
- `reqd_attribs`: a set of node attributes which we require to be
present; if this argument is None, it will take the same value
as `recognised_attribs` | [
"Error",
"checking",
"of",
"XML",
"input",
":",
"check",
"that",
"the",
"given",
"node",
"has",
"certain",
"required",
"attributes",
"and",
"does",
"not",
"have",
"any",
"unrecognised",
"attributes",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L92-L119 | train |
wroberts/pygermanet | pygermanet/mongo_import.py | read_lexical_file | def read_lexical_file(filename):
'''
Reads in a GermaNet lexical information file and returns its
contents as a list of dictionary structures.
Arguments:
- `filename`: the name of the XML file to read
'''
with open(filename, 'rb') as input_file:
doc = etree.parse(input_file)
synsets = []
assert doc.getroot().tag == 'synsets'
for synset in doc.getroot():
if synset.tag != 'synset':
print('unrecognised child of <synsets>', synset)
continue
synset_dict = dict(synset.items())
synloc = '{0} synset {1},'.format(filename,
synset_dict.get('id', '???'))
warn_attribs(synloc, synset, SYNSET_ATTRIBS)
synset_dict['lexunits'] = []
synsets.append(synset_dict)
for child in synset:
if child.tag == 'lexUnit':
lexunit = child
lexunit_dict = dict(lexunit.items())
lexloc = synloc + ' lexUnit {0},'.format(
lexunit_dict.get('id', '???'))
warn_attribs(lexloc, lexunit, LEXUNIT_ATTRIBS)
# convert some properties to booleans
for key in ['styleMarking', 'artificial', 'namedEntity']:
if key in lexunit_dict:
if lexunit_dict[key] not in MAP_YESNO_TO_BOOL:
print(lexloc, ('lexunit property {0} has '
'non-boolean value').format(key),
lexunit_dict[key])
continue
lexunit_dict[key] = MAP_YESNO_TO_BOOL[lexunit_dict[key]]
# convert sense to integer number
if 'sense' in lexunit_dict:
if lexunit_dict['sense'].isdigit():
lexunit_dict['sense'] = int(lexunit_dict['sense'], 10)
else:
print(lexloc,
'lexunit property sense has non-numeric value',
lexunit_dict['sense'])
synset_dict['lexunits'].append(lexunit_dict)
lexunit_dict['examples'] = []
lexunit_dict['frames'] = []
for child in lexunit:
if child.tag in ['orthForm',
'orthVar',
'oldOrthForm',
'oldOrthVar']:
warn_attribs(lexloc, child, set())
if not child.text:
print(lexloc, '{0} with no text'.format(child.tag))
continue
if child.tag in lexunit_dict:
print(lexloc, 'more than one {0}'.format(child.tag))
lexunit_dict[child.tag] = str(child.text)
elif child.tag == 'example':
example = child
text = [child for child in example
if child.tag == 'text']
if len(text) != 1 or not text[0].text:
print(lexloc, '<example> tag without text')
example_dict = {'text': str(text[0].text)}
for child in example:
if child.tag == 'text':
continue
elif child.tag == 'exframe':
if 'exframe' in example_dict:
print(lexloc,
'more than one <exframe> '
'for <example>')
warn_attribs(lexloc, child, set())
if not child.text:
print(lexloc, '<exframe> with no text')
continue
example_dict['exframe'] = str(child.text)
else:
print(lexloc,
'unrecognised child of <example>',
child)
lexunit_dict['examples'].append(example_dict)
elif child.tag == 'frame':
frame = child
warn_attribs(lexloc, frame, set())
if 0 < len(frame):
print(lexloc, 'unrecognised <frame> children',
list(frame))
if not frame.text:
print(lexloc, '<frame> without text')
continue
lexunit_dict['frames'].append(str(frame.text))
elif child.tag == 'compound':
compound = child
warn_attribs(lexloc, compound, set())
compound_dict = {}
for child in compound:
if child.tag == 'modifier':
modifier_dict = dict(child.items())
warn_attribs(lexloc, child,
MODIFIER_ATTRIBS, set())
if not child.text:
print(lexloc, 'modifier without text')
continue
modifier_dict['text'] = str(child.text)
if 'modifier' not in compound_dict:
compound_dict['modifier'] = []
compound_dict['modifier'].append(modifier_dict)
elif child.tag == 'head':
head_dict = dict(child.items())
warn_attribs(lexloc, child, HEAD_ATTRIBS, set())
if not child.text:
print(lexloc, '<head> without text')
continue
head_dict['text'] = str(child.text)
if 'head' in compound_dict:
print(lexloc,
'more than one head in <compound>')
compound_dict['head'] = head_dict
else:
print(lexloc,
'unrecognised child of <compound>',
child)
continue
else:
print(lexloc, 'unrecognised child of <lexUnit>', child)
continue
elif child.tag == 'paraphrase':
paraphrase = child
warn_attribs(synloc, paraphrase, set())
paraphrase_text = str(paraphrase.text)
if not paraphrase_text:
print(synloc, 'WARNING: <paraphrase> tag with no text')
else:
print(synloc, 'unrecognised child of <synset>', child)
continue
return synsets | python | def read_lexical_file(filename):
'''
Reads in a GermaNet lexical information file and returns its
contents as a list of dictionary structures.
Arguments:
- `filename`: the name of the XML file to read
'''
with open(filename, 'rb') as input_file:
doc = etree.parse(input_file)
synsets = []
assert doc.getroot().tag == 'synsets'
for synset in doc.getroot():
if synset.tag != 'synset':
print('unrecognised child of <synsets>', synset)
continue
synset_dict = dict(synset.items())
synloc = '{0} synset {1},'.format(filename,
synset_dict.get('id', '???'))
warn_attribs(synloc, synset, SYNSET_ATTRIBS)
synset_dict['lexunits'] = []
synsets.append(synset_dict)
for child in synset:
if child.tag == 'lexUnit':
lexunit = child
lexunit_dict = dict(lexunit.items())
lexloc = synloc + ' lexUnit {0},'.format(
lexunit_dict.get('id', '???'))
warn_attribs(lexloc, lexunit, LEXUNIT_ATTRIBS)
# convert some properties to booleans
for key in ['styleMarking', 'artificial', 'namedEntity']:
if key in lexunit_dict:
if lexunit_dict[key] not in MAP_YESNO_TO_BOOL:
print(lexloc, ('lexunit property {0} has '
'non-boolean value').format(key),
lexunit_dict[key])
continue
lexunit_dict[key] = MAP_YESNO_TO_BOOL[lexunit_dict[key]]
# convert sense to integer number
if 'sense' in lexunit_dict:
if lexunit_dict['sense'].isdigit():
lexunit_dict['sense'] = int(lexunit_dict['sense'], 10)
else:
print(lexloc,
'lexunit property sense has non-numeric value',
lexunit_dict['sense'])
synset_dict['lexunits'].append(lexunit_dict)
lexunit_dict['examples'] = []
lexunit_dict['frames'] = []
for child in lexunit:
if child.tag in ['orthForm',
'orthVar',
'oldOrthForm',
'oldOrthVar']:
warn_attribs(lexloc, child, set())
if not child.text:
print(lexloc, '{0} with no text'.format(child.tag))
continue
if child.tag in lexunit_dict:
print(lexloc, 'more than one {0}'.format(child.tag))
lexunit_dict[child.tag] = str(child.text)
elif child.tag == 'example':
example = child
text = [child for child in example
if child.tag == 'text']
if len(text) != 1 or not text[0].text:
print(lexloc, '<example> tag without text')
example_dict = {'text': str(text[0].text)}
for child in example:
if child.tag == 'text':
continue
elif child.tag == 'exframe':
if 'exframe' in example_dict:
print(lexloc,
'more than one <exframe> '
'for <example>')
warn_attribs(lexloc, child, set())
if not child.text:
print(lexloc, '<exframe> with no text')
continue
example_dict['exframe'] = str(child.text)
else:
print(lexloc,
'unrecognised child of <example>',
child)
lexunit_dict['examples'].append(example_dict)
elif child.tag == 'frame':
frame = child
warn_attribs(lexloc, frame, set())
if 0 < len(frame):
print(lexloc, 'unrecognised <frame> children',
list(frame))
if not frame.text:
print(lexloc, '<frame> without text')
continue
lexunit_dict['frames'].append(str(frame.text))
elif child.tag == 'compound':
compound = child
warn_attribs(lexloc, compound, set())
compound_dict = {}
for child in compound:
if child.tag == 'modifier':
modifier_dict = dict(child.items())
warn_attribs(lexloc, child,
MODIFIER_ATTRIBS, set())
if not child.text:
print(lexloc, 'modifier without text')
continue
modifier_dict['text'] = str(child.text)
if 'modifier' not in compound_dict:
compound_dict['modifier'] = []
compound_dict['modifier'].append(modifier_dict)
elif child.tag == 'head':
head_dict = dict(child.items())
warn_attribs(lexloc, child, HEAD_ATTRIBS, set())
if not child.text:
print(lexloc, '<head> without text')
continue
head_dict['text'] = str(child.text)
if 'head' in compound_dict:
print(lexloc,
'more than one head in <compound>')
compound_dict['head'] = head_dict
else:
print(lexloc,
'unrecognised child of <compound>',
child)
continue
else:
print(lexloc, 'unrecognised child of <lexUnit>', child)
continue
elif child.tag == 'paraphrase':
paraphrase = child
warn_attribs(synloc, paraphrase, set())
paraphrase_text = str(paraphrase.text)
if not paraphrase_text:
print(synloc, 'WARNING: <paraphrase> tag with no text')
else:
print(synloc, 'unrecognised child of <synset>', child)
continue
return synsets | [
"def",
"read_lexical_file",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"input_file",
":",
"doc",
"=",
"etree",
".",
"parse",
"(",
"input_file",
")",
"synsets",
"=",
"[",
"]",
"assert",
"doc",
".",
"getroot",
"(",
")",
".",
"tag",
"==",
"'synsets'",
"for",
"synset",
"in",
"doc",
".",
"getroot",
"(",
")",
":",
"if",
"synset",
".",
"tag",
"!=",
"'synset'",
":",
"print",
"(",
"'unrecognised child of <synsets>'",
",",
"synset",
")",
"continue",
"synset_dict",
"=",
"dict",
"(",
"synset",
".",
"items",
"(",
")",
")",
"synloc",
"=",
"'{0} synset {1},'",
".",
"format",
"(",
"filename",
",",
"synset_dict",
".",
"get",
"(",
"'id'",
",",
"'???'",
")",
")",
"warn_attribs",
"(",
"synloc",
",",
"synset",
",",
"SYNSET_ATTRIBS",
")",
"synset_dict",
"[",
"'lexunits'",
"]",
"=",
"[",
"]",
"synsets",
".",
"append",
"(",
"synset_dict",
")",
"for",
"child",
"in",
"synset",
":",
"if",
"child",
".",
"tag",
"==",
"'lexUnit'",
":",
"lexunit",
"=",
"child",
"lexunit_dict",
"=",
"dict",
"(",
"lexunit",
".",
"items",
"(",
")",
")",
"lexloc",
"=",
"synloc",
"+",
"' lexUnit {0},'",
".",
"format",
"(",
"lexunit_dict",
".",
"get",
"(",
"'id'",
",",
"'???'",
")",
")",
"warn_attribs",
"(",
"lexloc",
",",
"lexunit",
",",
"LEXUNIT_ATTRIBS",
")",
"# convert some properties to booleans",
"for",
"key",
"in",
"[",
"'styleMarking'",
",",
"'artificial'",
",",
"'namedEntity'",
"]",
":",
"if",
"key",
"in",
"lexunit_dict",
":",
"if",
"lexunit_dict",
"[",
"key",
"]",
"not",
"in",
"MAP_YESNO_TO_BOOL",
":",
"print",
"(",
"lexloc",
",",
"(",
"'lexunit property {0} has '",
"'non-boolean value'",
")",
".",
"format",
"(",
"key",
")",
",",
"lexunit_dict",
"[",
"key",
"]",
")",
"continue",
"lexunit_dict",
"[",
"key",
"]",
"=",
"MAP_YESNO_TO_BOOL",
"[",
"lexunit_dict",
"[",
"key",
"]",
"]",
"# convert sense to integer number",
"if",
"'sense'",
"in",
"lexunit_dict",
":",
"if",
"lexunit_dict",
"[",
"'sense'",
"]",
".",
"isdigit",
"(",
")",
":",
"lexunit_dict",
"[",
"'sense'",
"]",
"=",
"int",
"(",
"lexunit_dict",
"[",
"'sense'",
"]",
",",
"10",
")",
"else",
":",
"print",
"(",
"lexloc",
",",
"'lexunit property sense has non-numeric value'",
",",
"lexunit_dict",
"[",
"'sense'",
"]",
")",
"synset_dict",
"[",
"'lexunits'",
"]",
".",
"append",
"(",
"lexunit_dict",
")",
"lexunit_dict",
"[",
"'examples'",
"]",
"=",
"[",
"]",
"lexunit_dict",
"[",
"'frames'",
"]",
"=",
"[",
"]",
"for",
"child",
"in",
"lexunit",
":",
"if",
"child",
".",
"tag",
"in",
"[",
"'orthForm'",
",",
"'orthVar'",
",",
"'oldOrthForm'",
",",
"'oldOrthVar'",
"]",
":",
"warn_attribs",
"(",
"lexloc",
",",
"child",
",",
"set",
"(",
")",
")",
"if",
"not",
"child",
".",
"text",
":",
"print",
"(",
"lexloc",
",",
"'{0} with no text'",
".",
"format",
"(",
"child",
".",
"tag",
")",
")",
"continue",
"if",
"child",
".",
"tag",
"in",
"lexunit_dict",
":",
"print",
"(",
"lexloc",
",",
"'more than one {0}'",
".",
"format",
"(",
"child",
".",
"tag",
")",
")",
"lexunit_dict",
"[",
"child",
".",
"tag",
"]",
"=",
"str",
"(",
"child",
".",
"text",
")",
"elif",
"child",
".",
"tag",
"==",
"'example'",
":",
"example",
"=",
"child",
"text",
"=",
"[",
"child",
"for",
"child",
"in",
"example",
"if",
"child",
".",
"tag",
"==",
"'text'",
"]",
"if",
"len",
"(",
"text",
")",
"!=",
"1",
"or",
"not",
"text",
"[",
"0",
"]",
".",
"text",
":",
"print",
"(",
"lexloc",
",",
"'<example> tag without text'",
")",
"example_dict",
"=",
"{",
"'text'",
":",
"str",
"(",
"text",
"[",
"0",
"]",
".",
"text",
")",
"}",
"for",
"child",
"in",
"example",
":",
"if",
"child",
".",
"tag",
"==",
"'text'",
":",
"continue",
"elif",
"child",
".",
"tag",
"==",
"'exframe'",
":",
"if",
"'exframe'",
"in",
"example_dict",
":",
"print",
"(",
"lexloc",
",",
"'more than one <exframe> '",
"'for <example>'",
")",
"warn_attribs",
"(",
"lexloc",
",",
"child",
",",
"set",
"(",
")",
")",
"if",
"not",
"child",
".",
"text",
":",
"print",
"(",
"lexloc",
",",
"'<exframe> with no text'",
")",
"continue",
"example_dict",
"[",
"'exframe'",
"]",
"=",
"str",
"(",
"child",
".",
"text",
")",
"else",
":",
"print",
"(",
"lexloc",
",",
"'unrecognised child of <example>'",
",",
"child",
")",
"lexunit_dict",
"[",
"'examples'",
"]",
".",
"append",
"(",
"example_dict",
")",
"elif",
"child",
".",
"tag",
"==",
"'frame'",
":",
"frame",
"=",
"child",
"warn_attribs",
"(",
"lexloc",
",",
"frame",
",",
"set",
"(",
")",
")",
"if",
"0",
"<",
"len",
"(",
"frame",
")",
":",
"print",
"(",
"lexloc",
",",
"'unrecognised <frame> children'",
",",
"list",
"(",
"frame",
")",
")",
"if",
"not",
"frame",
".",
"text",
":",
"print",
"(",
"lexloc",
",",
"'<frame> without text'",
")",
"continue",
"lexunit_dict",
"[",
"'frames'",
"]",
".",
"append",
"(",
"str",
"(",
"frame",
".",
"text",
")",
")",
"elif",
"child",
".",
"tag",
"==",
"'compound'",
":",
"compound",
"=",
"child",
"warn_attribs",
"(",
"lexloc",
",",
"compound",
",",
"set",
"(",
")",
")",
"compound_dict",
"=",
"{",
"}",
"for",
"child",
"in",
"compound",
":",
"if",
"child",
".",
"tag",
"==",
"'modifier'",
":",
"modifier_dict",
"=",
"dict",
"(",
"child",
".",
"items",
"(",
")",
")",
"warn_attribs",
"(",
"lexloc",
",",
"child",
",",
"MODIFIER_ATTRIBS",
",",
"set",
"(",
")",
")",
"if",
"not",
"child",
".",
"text",
":",
"print",
"(",
"lexloc",
",",
"'modifier without text'",
")",
"continue",
"modifier_dict",
"[",
"'text'",
"]",
"=",
"str",
"(",
"child",
".",
"text",
")",
"if",
"'modifier'",
"not",
"in",
"compound_dict",
":",
"compound_dict",
"[",
"'modifier'",
"]",
"=",
"[",
"]",
"compound_dict",
"[",
"'modifier'",
"]",
".",
"append",
"(",
"modifier_dict",
")",
"elif",
"child",
".",
"tag",
"==",
"'head'",
":",
"head_dict",
"=",
"dict",
"(",
"child",
".",
"items",
"(",
")",
")",
"warn_attribs",
"(",
"lexloc",
",",
"child",
",",
"HEAD_ATTRIBS",
",",
"set",
"(",
")",
")",
"if",
"not",
"child",
".",
"text",
":",
"print",
"(",
"lexloc",
",",
"'<head> without text'",
")",
"continue",
"head_dict",
"[",
"'text'",
"]",
"=",
"str",
"(",
"child",
".",
"text",
")",
"if",
"'head'",
"in",
"compound_dict",
":",
"print",
"(",
"lexloc",
",",
"'more than one head in <compound>'",
")",
"compound_dict",
"[",
"'head'",
"]",
"=",
"head_dict",
"else",
":",
"print",
"(",
"lexloc",
",",
"'unrecognised child of <compound>'",
",",
"child",
")",
"continue",
"else",
":",
"print",
"(",
"lexloc",
",",
"'unrecognised child of <lexUnit>'",
",",
"child",
")",
"continue",
"elif",
"child",
".",
"tag",
"==",
"'paraphrase'",
":",
"paraphrase",
"=",
"child",
"warn_attribs",
"(",
"synloc",
",",
"paraphrase",
",",
"set",
"(",
")",
")",
"paraphrase_text",
"=",
"str",
"(",
"paraphrase",
".",
"text",
")",
"if",
"not",
"paraphrase_text",
":",
"print",
"(",
"synloc",
",",
"'WARNING: <paraphrase> tag with no text'",
")",
"else",
":",
"print",
"(",
"synloc",
",",
"'unrecognised child of <synset>'",
",",
"child",
")",
"continue",
"return",
"synsets"
] | Reads in a GermaNet lexical information file and returns its
contents as a list of dictionary structures.
Arguments:
- `filename`: the name of the XML file to read | [
"Reads",
"in",
"a",
"GermaNet",
"lexical",
"information",
"file",
"and",
"returns",
"its",
"contents",
"as",
"a",
"list",
"of",
"dictionary",
"structures",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L132-L275 | train |
wroberts/pygermanet | pygermanet/mongo_import.py | read_relation_file | def read_relation_file(filename):
'''
Reads the GermaNet relation file ``gn_relations.xml`` which lists
all the relations holding between lexical units and synsets.
Arguments:
- `filename`:
'''
with open(filename, 'rb') as input_file:
doc = etree.parse(input_file)
lex_rels = []
con_rels = []
assert doc.getroot().tag == 'relations'
for child in doc.getroot():
if child.tag == 'lex_rel':
if 0 < len(child):
print('<lex_rel> has unexpected child node')
child_dict = dict(child.items())
warn_attribs('', child, RELATION_ATTRIBS, RELATION_ATTRIBS_REQD)
if child_dict['dir'] not in LEX_REL_DIRS:
print('unrecognized <lex_rel> dir', child_dict['dir'])
if child_dict['dir'] == 'both' and 'inv' not in child_dict:
print('<lex_rel> has dir=both but does not specify inv')
lex_rels.append(child_dict)
elif child.tag == 'con_rel':
if 0 < len(child):
print('<con_rel> has unexpected child node')
child_dict = dict(child.items())
warn_attribs('', child, RELATION_ATTRIBS, RELATION_ATTRIBS_REQD)
if child_dict['dir'] not in CON_REL_DIRS:
print('unrecognised <con_rel> dir', child_dict['dir'])
if (child_dict['dir'] in ['both', 'revert'] and
'inv' not in child_dict):
print('<con_rel> has dir={0} but does not specify inv'.format(
child_dict['dir']))
con_rels.append(child_dict)
else:
print('unrecognised child of <relations>', child)
continue
return lex_rels, con_rels | python | def read_relation_file(filename):
'''
Reads the GermaNet relation file ``gn_relations.xml`` which lists
all the relations holding between lexical units and synsets.
Arguments:
- `filename`:
'''
with open(filename, 'rb') as input_file:
doc = etree.parse(input_file)
lex_rels = []
con_rels = []
assert doc.getroot().tag == 'relations'
for child in doc.getroot():
if child.tag == 'lex_rel':
if 0 < len(child):
print('<lex_rel> has unexpected child node')
child_dict = dict(child.items())
warn_attribs('', child, RELATION_ATTRIBS, RELATION_ATTRIBS_REQD)
if child_dict['dir'] not in LEX_REL_DIRS:
print('unrecognized <lex_rel> dir', child_dict['dir'])
if child_dict['dir'] == 'both' and 'inv' not in child_dict:
print('<lex_rel> has dir=both but does not specify inv')
lex_rels.append(child_dict)
elif child.tag == 'con_rel':
if 0 < len(child):
print('<con_rel> has unexpected child node')
child_dict = dict(child.items())
warn_attribs('', child, RELATION_ATTRIBS, RELATION_ATTRIBS_REQD)
if child_dict['dir'] not in CON_REL_DIRS:
print('unrecognised <con_rel> dir', child_dict['dir'])
if (child_dict['dir'] in ['both', 'revert'] and
'inv' not in child_dict):
print('<con_rel> has dir={0} but does not specify inv'.format(
child_dict['dir']))
con_rels.append(child_dict)
else:
print('unrecognised child of <relations>', child)
continue
return lex_rels, con_rels | [
"def",
"read_relation_file",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"input_file",
":",
"doc",
"=",
"etree",
".",
"parse",
"(",
"input_file",
")",
"lex_rels",
"=",
"[",
"]",
"con_rels",
"=",
"[",
"]",
"assert",
"doc",
".",
"getroot",
"(",
")",
".",
"tag",
"==",
"'relations'",
"for",
"child",
"in",
"doc",
".",
"getroot",
"(",
")",
":",
"if",
"child",
".",
"tag",
"==",
"'lex_rel'",
":",
"if",
"0",
"<",
"len",
"(",
"child",
")",
":",
"print",
"(",
"'<lex_rel> has unexpected child node'",
")",
"child_dict",
"=",
"dict",
"(",
"child",
".",
"items",
"(",
")",
")",
"warn_attribs",
"(",
"''",
",",
"child",
",",
"RELATION_ATTRIBS",
",",
"RELATION_ATTRIBS_REQD",
")",
"if",
"child_dict",
"[",
"'dir'",
"]",
"not",
"in",
"LEX_REL_DIRS",
":",
"print",
"(",
"'unrecognized <lex_rel> dir'",
",",
"child_dict",
"[",
"'dir'",
"]",
")",
"if",
"child_dict",
"[",
"'dir'",
"]",
"==",
"'both'",
"and",
"'inv'",
"not",
"in",
"child_dict",
":",
"print",
"(",
"'<lex_rel> has dir=both but does not specify inv'",
")",
"lex_rels",
".",
"append",
"(",
"child_dict",
")",
"elif",
"child",
".",
"tag",
"==",
"'con_rel'",
":",
"if",
"0",
"<",
"len",
"(",
"child",
")",
":",
"print",
"(",
"'<con_rel> has unexpected child node'",
")",
"child_dict",
"=",
"dict",
"(",
"child",
".",
"items",
"(",
")",
")",
"warn_attribs",
"(",
"''",
",",
"child",
",",
"RELATION_ATTRIBS",
",",
"RELATION_ATTRIBS_REQD",
")",
"if",
"child_dict",
"[",
"'dir'",
"]",
"not",
"in",
"CON_REL_DIRS",
":",
"print",
"(",
"'unrecognised <con_rel> dir'",
",",
"child_dict",
"[",
"'dir'",
"]",
")",
"if",
"(",
"child_dict",
"[",
"'dir'",
"]",
"in",
"[",
"'both'",
",",
"'revert'",
"]",
"and",
"'inv'",
"not",
"in",
"child_dict",
")",
":",
"print",
"(",
"'<con_rel> has dir={0} but does not specify inv'",
".",
"format",
"(",
"child_dict",
"[",
"'dir'",
"]",
")",
")",
"con_rels",
".",
"append",
"(",
"child_dict",
")",
"else",
":",
"print",
"(",
"'unrecognised child of <relations>'",
",",
"child",
")",
"continue",
"return",
"lex_rels",
",",
"con_rels"
] | Reads the GermaNet relation file ``gn_relations.xml`` which lists
all the relations holding between lexical units and synsets.
Arguments:
- `filename`: | [
"Reads",
"the",
"GermaNet",
"relation",
"file",
"gn_relations",
".",
"xml",
"which",
"lists",
"all",
"the",
"relations",
"holding",
"between",
"lexical",
"units",
"and",
"synsets",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L288-L329 | train |
wroberts/pygermanet | pygermanet/mongo_import.py | read_paraphrase_file | def read_paraphrase_file(filename):
'''
Reads in a GermaNet wiktionary paraphrase file and returns its
contents as a list of dictionary structures.
Arguments:
- `filename`:
'''
with open(filename, 'rb') as input_file:
doc = etree.parse(input_file)
assert doc.getroot().tag == 'wiktionaryParaphrases'
paraphrases = []
for child in doc.getroot():
if child.tag == 'wiktionaryParaphrase':
paraphrase = child
warn_attribs('', paraphrase, PARAPHRASE_ATTRIBS)
if 0 < len(paraphrase):
print('unrecognised child of <wiktionaryParaphrase>',
list(paraphrase))
paraphrase_dict = dict(paraphrase.items())
if paraphrase_dict['edited'] not in MAP_YESNO_TO_BOOL:
print('<paraphrase> attribute "edited" has unexpected value',
paraphrase_dict['edited'])
else:
paraphrase_dict['edited'] = MAP_YESNO_TO_BOOL[
paraphrase_dict['edited']]
if not paraphrase_dict['wiktionarySenseId'].isdigit():
print('<paraphrase> attribute "wiktionarySenseId" has '
'non-integer value', paraphrase_dict['edited'])
else:
paraphrase_dict['wiktionarySenseId'] = \
int(paraphrase_dict['wiktionarySenseId'], 10)
paraphrases.append(paraphrase_dict)
else:
print('unknown child of <wiktionaryParaphrases>', child)
return paraphrases | python | def read_paraphrase_file(filename):
'''
Reads in a GermaNet wiktionary paraphrase file and returns its
contents as a list of dictionary structures.
Arguments:
- `filename`:
'''
with open(filename, 'rb') as input_file:
doc = etree.parse(input_file)
assert doc.getroot().tag == 'wiktionaryParaphrases'
paraphrases = []
for child in doc.getroot():
if child.tag == 'wiktionaryParaphrase':
paraphrase = child
warn_attribs('', paraphrase, PARAPHRASE_ATTRIBS)
if 0 < len(paraphrase):
print('unrecognised child of <wiktionaryParaphrase>',
list(paraphrase))
paraphrase_dict = dict(paraphrase.items())
if paraphrase_dict['edited'] not in MAP_YESNO_TO_BOOL:
print('<paraphrase> attribute "edited" has unexpected value',
paraphrase_dict['edited'])
else:
paraphrase_dict['edited'] = MAP_YESNO_TO_BOOL[
paraphrase_dict['edited']]
if not paraphrase_dict['wiktionarySenseId'].isdigit():
print('<paraphrase> attribute "wiktionarySenseId" has '
'non-integer value', paraphrase_dict['edited'])
else:
paraphrase_dict['wiktionarySenseId'] = \
int(paraphrase_dict['wiktionarySenseId'], 10)
paraphrases.append(paraphrase_dict)
else:
print('unknown child of <wiktionaryParaphrases>', child)
return paraphrases | [
"def",
"read_paraphrase_file",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"input_file",
":",
"doc",
"=",
"etree",
".",
"parse",
"(",
"input_file",
")",
"assert",
"doc",
".",
"getroot",
"(",
")",
".",
"tag",
"==",
"'wiktionaryParaphrases'",
"paraphrases",
"=",
"[",
"]",
"for",
"child",
"in",
"doc",
".",
"getroot",
"(",
")",
":",
"if",
"child",
".",
"tag",
"==",
"'wiktionaryParaphrase'",
":",
"paraphrase",
"=",
"child",
"warn_attribs",
"(",
"''",
",",
"paraphrase",
",",
"PARAPHRASE_ATTRIBS",
")",
"if",
"0",
"<",
"len",
"(",
"paraphrase",
")",
":",
"print",
"(",
"'unrecognised child of <wiktionaryParaphrase>'",
",",
"list",
"(",
"paraphrase",
")",
")",
"paraphrase_dict",
"=",
"dict",
"(",
"paraphrase",
".",
"items",
"(",
")",
")",
"if",
"paraphrase_dict",
"[",
"'edited'",
"]",
"not",
"in",
"MAP_YESNO_TO_BOOL",
":",
"print",
"(",
"'<paraphrase> attribute \"edited\" has unexpected value'",
",",
"paraphrase_dict",
"[",
"'edited'",
"]",
")",
"else",
":",
"paraphrase_dict",
"[",
"'edited'",
"]",
"=",
"MAP_YESNO_TO_BOOL",
"[",
"paraphrase_dict",
"[",
"'edited'",
"]",
"]",
"if",
"not",
"paraphrase_dict",
"[",
"'wiktionarySenseId'",
"]",
".",
"isdigit",
"(",
")",
":",
"print",
"(",
"'<paraphrase> attribute \"wiktionarySenseId\" has '",
"'non-integer value'",
",",
"paraphrase_dict",
"[",
"'edited'",
"]",
")",
"else",
":",
"paraphrase_dict",
"[",
"'wiktionarySenseId'",
"]",
"=",
"int",
"(",
"paraphrase_dict",
"[",
"'wiktionarySenseId'",
"]",
",",
"10",
")",
"paraphrases",
".",
"append",
"(",
"paraphrase_dict",
")",
"else",
":",
"print",
"(",
"'unknown child of <wiktionaryParaphrases>'",
",",
"child",
")",
"return",
"paraphrases"
] | Reads in a GermaNet wiktionary paraphrase file and returns its
contents as a list of dictionary structures.
Arguments:
- `filename`: | [
"Reads",
"in",
"a",
"GermaNet",
"wiktionary",
"paraphrase",
"file",
"and",
"returns",
"its",
"contents",
"as",
"a",
"list",
"of",
"dictionary",
"structures",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L339-L376 | train |
wroberts/pygermanet | pygermanet/mongo_import.py | insert_lexical_information | def insert_lexical_information(germanet_db, lex_files):
'''
Reads in the given lexical information files and inserts their
contents into the given MongoDB database.
Arguments:
- `germanet_db`: a pymongo.database.Database object
- `lex_files`: a list of paths to XML files containing lexial
information
'''
# drop the database collections if they already exist
germanet_db.lexunits.drop()
germanet_db.synsets.drop()
# inject data from XML files into the database
for lex_file in lex_files:
synsets = read_lexical_file(lex_file)
for synset in synsets:
synset = dict((SYNSET_KEY_REWRITES.get(key, key), value)
for (key, value) in synset.items())
lexunits = synset['lexunits']
synset['lexunits'] = germanet_db.lexunits.insert(lexunits)
synset_id = germanet_db.synsets.insert(synset)
for lexunit in lexunits:
lexunit['synset'] = synset_id
lexunit['category'] = synset['category']
germanet_db.lexunits.save(lexunit)
# index the two collections by id
germanet_db.synsets.create_index('id')
germanet_db.lexunits.create_index('id')
# also index lexunits by lemma, lemma-pos, and lemma-pos-sensenum
germanet_db.lexunits.create_index([('orthForm', DESCENDING)])
germanet_db.lexunits.create_index([('orthForm', DESCENDING),
('category', DESCENDING)])
germanet_db.lexunits.create_index([('orthForm', DESCENDING),
('category', DESCENDING),
('sense', DESCENDING)])
print('Inserted {0} synsets, {1} lexical units.'.format(
germanet_db.synsets.count(),
germanet_db.lexunits.count())) | python | def insert_lexical_information(germanet_db, lex_files):
'''
Reads in the given lexical information files and inserts their
contents into the given MongoDB database.
Arguments:
- `germanet_db`: a pymongo.database.Database object
- `lex_files`: a list of paths to XML files containing lexial
information
'''
# drop the database collections if they already exist
germanet_db.lexunits.drop()
germanet_db.synsets.drop()
# inject data from XML files into the database
for lex_file in lex_files:
synsets = read_lexical_file(lex_file)
for synset in synsets:
synset = dict((SYNSET_KEY_REWRITES.get(key, key), value)
for (key, value) in synset.items())
lexunits = synset['lexunits']
synset['lexunits'] = germanet_db.lexunits.insert(lexunits)
synset_id = germanet_db.synsets.insert(synset)
for lexunit in lexunits:
lexunit['synset'] = synset_id
lexunit['category'] = synset['category']
germanet_db.lexunits.save(lexunit)
# index the two collections by id
germanet_db.synsets.create_index('id')
germanet_db.lexunits.create_index('id')
# also index lexunits by lemma, lemma-pos, and lemma-pos-sensenum
germanet_db.lexunits.create_index([('orthForm', DESCENDING)])
germanet_db.lexunits.create_index([('orthForm', DESCENDING),
('category', DESCENDING)])
germanet_db.lexunits.create_index([('orthForm', DESCENDING),
('category', DESCENDING),
('sense', DESCENDING)])
print('Inserted {0} synsets, {1} lexical units.'.format(
germanet_db.synsets.count(),
germanet_db.lexunits.count())) | [
"def",
"insert_lexical_information",
"(",
"germanet_db",
",",
"lex_files",
")",
":",
"# drop the database collections if they already exist",
"germanet_db",
".",
"lexunits",
".",
"drop",
"(",
")",
"germanet_db",
".",
"synsets",
".",
"drop",
"(",
")",
"# inject data from XML files into the database",
"for",
"lex_file",
"in",
"lex_files",
":",
"synsets",
"=",
"read_lexical_file",
"(",
"lex_file",
")",
"for",
"synset",
"in",
"synsets",
":",
"synset",
"=",
"dict",
"(",
"(",
"SYNSET_KEY_REWRITES",
".",
"get",
"(",
"key",
",",
"key",
")",
",",
"value",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"synset",
".",
"items",
"(",
")",
")",
"lexunits",
"=",
"synset",
"[",
"'lexunits'",
"]",
"synset",
"[",
"'lexunits'",
"]",
"=",
"germanet_db",
".",
"lexunits",
".",
"insert",
"(",
"lexunits",
")",
"synset_id",
"=",
"germanet_db",
".",
"synsets",
".",
"insert",
"(",
"synset",
")",
"for",
"lexunit",
"in",
"lexunits",
":",
"lexunit",
"[",
"'synset'",
"]",
"=",
"synset_id",
"lexunit",
"[",
"'category'",
"]",
"=",
"synset",
"[",
"'category'",
"]",
"germanet_db",
".",
"lexunits",
".",
"save",
"(",
"lexunit",
")",
"# index the two collections by id",
"germanet_db",
".",
"synsets",
".",
"create_index",
"(",
"'id'",
")",
"germanet_db",
".",
"lexunits",
".",
"create_index",
"(",
"'id'",
")",
"# also index lexunits by lemma, lemma-pos, and lemma-pos-sensenum",
"germanet_db",
".",
"lexunits",
".",
"create_index",
"(",
"[",
"(",
"'orthForm'",
",",
"DESCENDING",
")",
"]",
")",
"germanet_db",
".",
"lexunits",
".",
"create_index",
"(",
"[",
"(",
"'orthForm'",
",",
"DESCENDING",
")",
",",
"(",
"'category'",
",",
"DESCENDING",
")",
"]",
")",
"germanet_db",
".",
"lexunits",
".",
"create_index",
"(",
"[",
"(",
"'orthForm'",
",",
"DESCENDING",
")",
",",
"(",
"'category'",
",",
"DESCENDING",
")",
",",
"(",
"'sense'",
",",
"DESCENDING",
")",
"]",
")",
"print",
"(",
"'Inserted {0} synsets, {1} lexical units.'",
".",
"format",
"(",
"germanet_db",
".",
"synsets",
".",
"count",
"(",
")",
",",
"germanet_db",
".",
"lexunits",
".",
"count",
"(",
")",
")",
")"
] | Reads in the given lexical information files and inserts their
contents into the given MongoDB database.
Arguments:
- `germanet_db`: a pymongo.database.Database object
- `lex_files`: a list of paths to XML files containing lexial
information | [
"Reads",
"in",
"the",
"given",
"lexical",
"information",
"files",
"and",
"inserts",
"their",
"contents",
"into",
"the",
"given",
"MongoDB",
"database",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L389-L427 | train |
wroberts/pygermanet | pygermanet/mongo_import.py | insert_relation_information | def insert_relation_information(germanet_db, gn_rels_file):
'''
Reads in the given GermaNet relation file and inserts its contents
into the given MongoDB database.
Arguments:
- `germanet_db`: a pymongo.database.Database object
- `gn_rels_file`:
'''
lex_rels, con_rels = read_relation_file(gn_rels_file)
# cache the lexunits while we work on them
lexunits = {}
for lex_rel in lex_rels:
if lex_rel['from'] not in lexunits:
lexunits[lex_rel['from']] = germanet_db.lexunits.find_one(
{'id': lex_rel['from']})
from_lexunit = lexunits[lex_rel['from']]
if lex_rel['to'] not in lexunits:
lexunits[lex_rel['to']] = germanet_db.lexunits.find_one(
{'id': lex_rel['to']})
to_lexunit = lexunits[lex_rel['to']]
if 'rels' not in from_lexunit:
from_lexunit['rels'] = set()
from_lexunit['rels'].add((lex_rel['name'], to_lexunit['_id']))
if lex_rel['dir'] == 'both':
if 'rels' not in to_lexunit:
to_lexunit['rels'] = set()
to_lexunit['rels'].add((lex_rel['inv'], from_lexunit['_id']))
for lexunit in lexunits.values():
if 'rels' in lexunit:
lexunit['rels'] = sorted(lexunit['rels'])
germanet_db.lexunits.save(lexunit)
# cache the synsets while we work on them
synsets = {}
for con_rel in con_rels:
if con_rel['from'] not in synsets:
synsets[con_rel['from']] = germanet_db.synsets.find_one(
{'id': con_rel['from']})
from_synset = synsets[con_rel['from']]
if con_rel['to'] not in synsets:
synsets[con_rel['to']] = germanet_db.synsets.find_one(
{'id': con_rel['to']})
to_synset = synsets[con_rel['to']]
if 'rels' not in from_synset:
from_synset['rels'] = set()
from_synset['rels'].add((con_rel['name'], to_synset['_id']))
if con_rel['dir'] in ['both', 'revert']:
if 'rels' not in to_synset:
to_synset['rels'] = set()
to_synset['rels'].add((con_rel['inv'], from_synset['_id']))
for synset in synsets.values():
if 'rels' in synset:
synset['rels'] = sorted(synset['rels'])
germanet_db.synsets.save(synset)
print('Inserted {0} lexical relations, {1} synset relations.'.format(
len(lex_rels), len(con_rels))) | python | def insert_relation_information(germanet_db, gn_rels_file):
'''
Reads in the given GermaNet relation file and inserts its contents
into the given MongoDB database.
Arguments:
- `germanet_db`: a pymongo.database.Database object
- `gn_rels_file`:
'''
lex_rels, con_rels = read_relation_file(gn_rels_file)
# cache the lexunits while we work on them
lexunits = {}
for lex_rel in lex_rels:
if lex_rel['from'] not in lexunits:
lexunits[lex_rel['from']] = germanet_db.lexunits.find_one(
{'id': lex_rel['from']})
from_lexunit = lexunits[lex_rel['from']]
if lex_rel['to'] not in lexunits:
lexunits[lex_rel['to']] = germanet_db.lexunits.find_one(
{'id': lex_rel['to']})
to_lexunit = lexunits[lex_rel['to']]
if 'rels' not in from_lexunit:
from_lexunit['rels'] = set()
from_lexunit['rels'].add((lex_rel['name'], to_lexunit['_id']))
if lex_rel['dir'] == 'both':
if 'rels' not in to_lexunit:
to_lexunit['rels'] = set()
to_lexunit['rels'].add((lex_rel['inv'], from_lexunit['_id']))
for lexunit in lexunits.values():
if 'rels' in lexunit:
lexunit['rels'] = sorted(lexunit['rels'])
germanet_db.lexunits.save(lexunit)
# cache the synsets while we work on them
synsets = {}
for con_rel in con_rels:
if con_rel['from'] not in synsets:
synsets[con_rel['from']] = germanet_db.synsets.find_one(
{'id': con_rel['from']})
from_synset = synsets[con_rel['from']]
if con_rel['to'] not in synsets:
synsets[con_rel['to']] = germanet_db.synsets.find_one(
{'id': con_rel['to']})
to_synset = synsets[con_rel['to']]
if 'rels' not in from_synset:
from_synset['rels'] = set()
from_synset['rels'].add((con_rel['name'], to_synset['_id']))
if con_rel['dir'] in ['both', 'revert']:
if 'rels' not in to_synset:
to_synset['rels'] = set()
to_synset['rels'].add((con_rel['inv'], from_synset['_id']))
for synset in synsets.values():
if 'rels' in synset:
synset['rels'] = sorted(synset['rels'])
germanet_db.synsets.save(synset)
print('Inserted {0} lexical relations, {1} synset relations.'.format(
len(lex_rels), len(con_rels))) | [
"def",
"insert_relation_information",
"(",
"germanet_db",
",",
"gn_rels_file",
")",
":",
"lex_rels",
",",
"con_rels",
"=",
"read_relation_file",
"(",
"gn_rels_file",
")",
"# cache the lexunits while we work on them",
"lexunits",
"=",
"{",
"}",
"for",
"lex_rel",
"in",
"lex_rels",
":",
"if",
"lex_rel",
"[",
"'from'",
"]",
"not",
"in",
"lexunits",
":",
"lexunits",
"[",
"lex_rel",
"[",
"'from'",
"]",
"]",
"=",
"germanet_db",
".",
"lexunits",
".",
"find_one",
"(",
"{",
"'id'",
":",
"lex_rel",
"[",
"'from'",
"]",
"}",
")",
"from_lexunit",
"=",
"lexunits",
"[",
"lex_rel",
"[",
"'from'",
"]",
"]",
"if",
"lex_rel",
"[",
"'to'",
"]",
"not",
"in",
"lexunits",
":",
"lexunits",
"[",
"lex_rel",
"[",
"'to'",
"]",
"]",
"=",
"germanet_db",
".",
"lexunits",
".",
"find_one",
"(",
"{",
"'id'",
":",
"lex_rel",
"[",
"'to'",
"]",
"}",
")",
"to_lexunit",
"=",
"lexunits",
"[",
"lex_rel",
"[",
"'to'",
"]",
"]",
"if",
"'rels'",
"not",
"in",
"from_lexunit",
":",
"from_lexunit",
"[",
"'rels'",
"]",
"=",
"set",
"(",
")",
"from_lexunit",
"[",
"'rels'",
"]",
".",
"add",
"(",
"(",
"lex_rel",
"[",
"'name'",
"]",
",",
"to_lexunit",
"[",
"'_id'",
"]",
")",
")",
"if",
"lex_rel",
"[",
"'dir'",
"]",
"==",
"'both'",
":",
"if",
"'rels'",
"not",
"in",
"to_lexunit",
":",
"to_lexunit",
"[",
"'rels'",
"]",
"=",
"set",
"(",
")",
"to_lexunit",
"[",
"'rels'",
"]",
".",
"add",
"(",
"(",
"lex_rel",
"[",
"'inv'",
"]",
",",
"from_lexunit",
"[",
"'_id'",
"]",
")",
")",
"for",
"lexunit",
"in",
"lexunits",
".",
"values",
"(",
")",
":",
"if",
"'rels'",
"in",
"lexunit",
":",
"lexunit",
"[",
"'rels'",
"]",
"=",
"sorted",
"(",
"lexunit",
"[",
"'rels'",
"]",
")",
"germanet_db",
".",
"lexunits",
".",
"save",
"(",
"lexunit",
")",
"# cache the synsets while we work on them",
"synsets",
"=",
"{",
"}",
"for",
"con_rel",
"in",
"con_rels",
":",
"if",
"con_rel",
"[",
"'from'",
"]",
"not",
"in",
"synsets",
":",
"synsets",
"[",
"con_rel",
"[",
"'from'",
"]",
"]",
"=",
"germanet_db",
".",
"synsets",
".",
"find_one",
"(",
"{",
"'id'",
":",
"con_rel",
"[",
"'from'",
"]",
"}",
")",
"from_synset",
"=",
"synsets",
"[",
"con_rel",
"[",
"'from'",
"]",
"]",
"if",
"con_rel",
"[",
"'to'",
"]",
"not",
"in",
"synsets",
":",
"synsets",
"[",
"con_rel",
"[",
"'to'",
"]",
"]",
"=",
"germanet_db",
".",
"synsets",
".",
"find_one",
"(",
"{",
"'id'",
":",
"con_rel",
"[",
"'to'",
"]",
"}",
")",
"to_synset",
"=",
"synsets",
"[",
"con_rel",
"[",
"'to'",
"]",
"]",
"if",
"'rels'",
"not",
"in",
"from_synset",
":",
"from_synset",
"[",
"'rels'",
"]",
"=",
"set",
"(",
")",
"from_synset",
"[",
"'rels'",
"]",
".",
"add",
"(",
"(",
"con_rel",
"[",
"'name'",
"]",
",",
"to_synset",
"[",
"'_id'",
"]",
")",
")",
"if",
"con_rel",
"[",
"'dir'",
"]",
"in",
"[",
"'both'",
",",
"'revert'",
"]",
":",
"if",
"'rels'",
"not",
"in",
"to_synset",
":",
"to_synset",
"[",
"'rels'",
"]",
"=",
"set",
"(",
")",
"to_synset",
"[",
"'rels'",
"]",
".",
"add",
"(",
"(",
"con_rel",
"[",
"'inv'",
"]",
",",
"from_synset",
"[",
"'_id'",
"]",
")",
")",
"for",
"synset",
"in",
"synsets",
".",
"values",
"(",
")",
":",
"if",
"'rels'",
"in",
"synset",
":",
"synset",
"[",
"'rels'",
"]",
"=",
"sorted",
"(",
"synset",
"[",
"'rels'",
"]",
")",
"germanet_db",
".",
"synsets",
".",
"save",
"(",
"synset",
")",
"print",
"(",
"'Inserted {0} lexical relations, {1} synset relations.'",
".",
"format",
"(",
"len",
"(",
"lex_rels",
")",
",",
"len",
"(",
"con_rels",
")",
")",
")"
] | Reads in the given GermaNet relation file and inserts its contents
into the given MongoDB database.
Arguments:
- `germanet_db`: a pymongo.database.Database object
- `gn_rels_file`: | [
"Reads",
"in",
"the",
"given",
"GermaNet",
"relation",
"file",
"and",
"inserts",
"its",
"contents",
"into",
"the",
"given",
"MongoDB",
"database",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L429-L487 | train |
wroberts/pygermanet | pygermanet/mongo_import.py | insert_paraphrase_information | def insert_paraphrase_information(germanet_db, wiktionary_files):
'''
Reads in the given GermaNet relation file and inserts its contents
into the given MongoDB database.
Arguments:
- `germanet_db`: a pymongo.database.Database object
- `wiktionary_files`:
'''
num_paraphrases = 0
# cache the lexunits while we work on them
lexunits = {}
for filename in wiktionary_files:
paraphrases = read_paraphrase_file(filename)
num_paraphrases += len(paraphrases)
for paraphrase in paraphrases:
if paraphrase['lexUnitId'] not in lexunits:
lexunits[paraphrase['lexUnitId']] = \
germanet_db.lexunits.find_one(
{'id': paraphrase['lexUnitId']})
lexunit = lexunits[paraphrase['lexUnitId']]
if 'paraphrases' not in lexunit:
lexunit['paraphrases'] = []
lexunit['paraphrases'].append(paraphrase)
for lexunit in lexunits.values():
germanet_db.lexunits.save(lexunit)
print('Inserted {0} wiktionary paraphrases.'.format(num_paraphrases)) | python | def insert_paraphrase_information(germanet_db, wiktionary_files):
'''
Reads in the given GermaNet relation file and inserts its contents
into the given MongoDB database.
Arguments:
- `germanet_db`: a pymongo.database.Database object
- `wiktionary_files`:
'''
num_paraphrases = 0
# cache the lexunits while we work on them
lexunits = {}
for filename in wiktionary_files:
paraphrases = read_paraphrase_file(filename)
num_paraphrases += len(paraphrases)
for paraphrase in paraphrases:
if paraphrase['lexUnitId'] not in lexunits:
lexunits[paraphrase['lexUnitId']] = \
germanet_db.lexunits.find_one(
{'id': paraphrase['lexUnitId']})
lexunit = lexunits[paraphrase['lexUnitId']]
if 'paraphrases' not in lexunit:
lexunit['paraphrases'] = []
lexunit['paraphrases'].append(paraphrase)
for lexunit in lexunits.values():
germanet_db.lexunits.save(lexunit)
print('Inserted {0} wiktionary paraphrases.'.format(num_paraphrases)) | [
"def",
"insert_paraphrase_information",
"(",
"germanet_db",
",",
"wiktionary_files",
")",
":",
"num_paraphrases",
"=",
"0",
"# cache the lexunits while we work on them",
"lexunits",
"=",
"{",
"}",
"for",
"filename",
"in",
"wiktionary_files",
":",
"paraphrases",
"=",
"read_paraphrase_file",
"(",
"filename",
")",
"num_paraphrases",
"+=",
"len",
"(",
"paraphrases",
")",
"for",
"paraphrase",
"in",
"paraphrases",
":",
"if",
"paraphrase",
"[",
"'lexUnitId'",
"]",
"not",
"in",
"lexunits",
":",
"lexunits",
"[",
"paraphrase",
"[",
"'lexUnitId'",
"]",
"]",
"=",
"germanet_db",
".",
"lexunits",
".",
"find_one",
"(",
"{",
"'id'",
":",
"paraphrase",
"[",
"'lexUnitId'",
"]",
"}",
")",
"lexunit",
"=",
"lexunits",
"[",
"paraphrase",
"[",
"'lexUnitId'",
"]",
"]",
"if",
"'paraphrases'",
"not",
"in",
"lexunit",
":",
"lexunit",
"[",
"'paraphrases'",
"]",
"=",
"[",
"]",
"lexunit",
"[",
"'paraphrases'",
"]",
".",
"append",
"(",
"paraphrase",
")",
"for",
"lexunit",
"in",
"lexunits",
".",
"values",
"(",
")",
":",
"germanet_db",
".",
"lexunits",
".",
"save",
"(",
"lexunit",
")",
"print",
"(",
"'Inserted {0} wiktionary paraphrases.'",
".",
"format",
"(",
"num_paraphrases",
")",
")"
] | Reads in the given GermaNet relation file and inserts its contents
into the given MongoDB database.
Arguments:
- `germanet_db`: a pymongo.database.Database object
- `wiktionary_files`: | [
"Reads",
"in",
"the",
"given",
"GermaNet",
"relation",
"file",
"and",
"inserts",
"its",
"contents",
"into",
"the",
"given",
"MongoDB",
"database",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L489-L516 | train |
wroberts/pygermanet | pygermanet/mongo_import.py | insert_lemmatisation_data | def insert_lemmatisation_data(germanet_db):
'''
Creates the lemmatiser collection in the given MongoDB instance
using the data derived from the Projekt deutscher Wortschatz.
Arguments:
- `germanet_db`: a pymongo.database.Database object
'''
# drop the database collection if it already exists
germanet_db.lemmatiser.drop()
num_lemmas = 0
input_file = gzip.open(os.path.join(os.path.dirname(__file__),
LEMMATISATION_FILE))
for line in input_file:
line = line.decode('iso-8859-1').strip().split('\t')
assert len(line) == 2
germanet_db.lemmatiser.insert(dict(list(zip(('word', 'lemma'), line))))
num_lemmas += 1
input_file.close()
# index the collection on 'word'
germanet_db.lemmatiser.create_index('word')
print('Inserted {0} lemmatiser entries.'.format(num_lemmas)) | python | def insert_lemmatisation_data(germanet_db):
'''
Creates the lemmatiser collection in the given MongoDB instance
using the data derived from the Projekt deutscher Wortschatz.
Arguments:
- `germanet_db`: a pymongo.database.Database object
'''
# drop the database collection if it already exists
germanet_db.lemmatiser.drop()
num_lemmas = 0
input_file = gzip.open(os.path.join(os.path.dirname(__file__),
LEMMATISATION_FILE))
for line in input_file:
line = line.decode('iso-8859-1').strip().split('\t')
assert len(line) == 2
germanet_db.lemmatiser.insert(dict(list(zip(('word', 'lemma'), line))))
num_lemmas += 1
input_file.close()
# index the collection on 'word'
germanet_db.lemmatiser.create_index('word')
print('Inserted {0} lemmatiser entries.'.format(num_lemmas)) | [
"def",
"insert_lemmatisation_data",
"(",
"germanet_db",
")",
":",
"# drop the database collection if it already exists",
"germanet_db",
".",
"lemmatiser",
".",
"drop",
"(",
")",
"num_lemmas",
"=",
"0",
"input_file",
"=",
"gzip",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"LEMMATISATION_FILE",
")",
")",
"for",
"line",
"in",
"input_file",
":",
"line",
"=",
"line",
".",
"decode",
"(",
"'iso-8859-1'",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
"assert",
"len",
"(",
"line",
")",
"==",
"2",
"germanet_db",
".",
"lemmatiser",
".",
"insert",
"(",
"dict",
"(",
"list",
"(",
"zip",
"(",
"(",
"'word'",
",",
"'lemma'",
")",
",",
"line",
")",
")",
")",
")",
"num_lemmas",
"+=",
"1",
"input_file",
".",
"close",
"(",
")",
"# index the collection on 'word'",
"germanet_db",
".",
"lemmatiser",
".",
"create_index",
"(",
"'word'",
")",
"print",
"(",
"'Inserted {0} lemmatiser entries.'",
".",
"format",
"(",
"num_lemmas",
")",
")"
] | Creates the lemmatiser collection in the given MongoDB instance
using the data derived from the Projekt deutscher Wortschatz.
Arguments:
- `germanet_db`: a pymongo.database.Database object | [
"Creates",
"the",
"lemmatiser",
"collection",
"in",
"the",
"given",
"MongoDB",
"instance",
"using",
"the",
"data",
"derived",
"from",
"the",
"Projekt",
"deutscher",
"Wortschatz",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L520-L542 | train |
wroberts/pygermanet | pygermanet/mongo_import.py | insert_infocontent_data | def insert_infocontent_data(germanet_db):
'''
For every synset in GermaNet, inserts count information derived
from SDEWAC.
Arguments:
- `germanet_db`: a pymongo.database.Database object
'''
gnet = germanet.GermaNet(germanet_db)
# use add one smoothing
gn_counts = defaultdict(lambda: 1.)
total_count = 1
input_file = gzip.open(os.path.join(os.path.dirname(__file__),
WORD_COUNT_FILE))
num_lines_read = 0
num_lines = 0
for line in input_file:
line = line.decode('utf-8').strip().split('\t')
num_lines += 1
if len(line) != 3:
continue
count, pos, word = line
num_lines_read += 1
count = int(count)
synsets = set(gnet.synsets(word, pos))
if not synsets:
continue
# Although Resnik (1995) suggests dividing count by the number
# of synsets, Patwardhan et al (2003) argue against doing
# this.
count = float(count) / len(synsets)
for synset in synsets:
total_count += count
paths = synset.hypernym_paths
scount = float(count) / len(paths)
for path in paths:
for ss in path:
gn_counts[ss._id] += scount
print('Read {0} of {1} lines from count file.'.format(num_lines_read,
num_lines))
print('Recorded counts for {0} synsets.'.format(len(gn_counts)))
print('Total count is {0}'.format(total_count))
input_file.close()
# update all the synset records in GermaNet
num_updates = 0
for synset in germanet_db.synsets.find():
synset['infocont'] = gn_counts[synset['_id']] / total_count
germanet_db.synsets.save(synset)
num_updates += 1
print('Updated {0} synsets.'.format(num_updates)) | python | def insert_infocontent_data(germanet_db):
'''
For every synset in GermaNet, inserts count information derived
from SDEWAC.
Arguments:
- `germanet_db`: a pymongo.database.Database object
'''
gnet = germanet.GermaNet(germanet_db)
# use add one smoothing
gn_counts = defaultdict(lambda: 1.)
total_count = 1
input_file = gzip.open(os.path.join(os.path.dirname(__file__),
WORD_COUNT_FILE))
num_lines_read = 0
num_lines = 0
for line in input_file:
line = line.decode('utf-8').strip().split('\t')
num_lines += 1
if len(line) != 3:
continue
count, pos, word = line
num_lines_read += 1
count = int(count)
synsets = set(gnet.synsets(word, pos))
if not synsets:
continue
# Although Resnik (1995) suggests dividing count by the number
# of synsets, Patwardhan et al (2003) argue against doing
# this.
count = float(count) / len(synsets)
for synset in synsets:
total_count += count
paths = synset.hypernym_paths
scount = float(count) / len(paths)
for path in paths:
for ss in path:
gn_counts[ss._id] += scount
print('Read {0} of {1} lines from count file.'.format(num_lines_read,
num_lines))
print('Recorded counts for {0} synsets.'.format(len(gn_counts)))
print('Total count is {0}'.format(total_count))
input_file.close()
# update all the synset records in GermaNet
num_updates = 0
for synset in germanet_db.synsets.find():
synset['infocont'] = gn_counts[synset['_id']] / total_count
germanet_db.synsets.save(synset)
num_updates += 1
print('Updated {0} synsets.'.format(num_updates)) | [
"def",
"insert_infocontent_data",
"(",
"germanet_db",
")",
":",
"gnet",
"=",
"germanet",
".",
"GermaNet",
"(",
"germanet_db",
")",
"# use add one smoothing",
"gn_counts",
"=",
"defaultdict",
"(",
"lambda",
":",
"1.",
")",
"total_count",
"=",
"1",
"input_file",
"=",
"gzip",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"WORD_COUNT_FILE",
")",
")",
"num_lines_read",
"=",
"0",
"num_lines",
"=",
"0",
"for",
"line",
"in",
"input_file",
":",
"line",
"=",
"line",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
"num_lines",
"+=",
"1",
"if",
"len",
"(",
"line",
")",
"!=",
"3",
":",
"continue",
"count",
",",
"pos",
",",
"word",
"=",
"line",
"num_lines_read",
"+=",
"1",
"count",
"=",
"int",
"(",
"count",
")",
"synsets",
"=",
"set",
"(",
"gnet",
".",
"synsets",
"(",
"word",
",",
"pos",
")",
")",
"if",
"not",
"synsets",
":",
"continue",
"# Although Resnik (1995) suggests dividing count by the number",
"# of synsets, Patwardhan et al (2003) argue against doing",
"# this.",
"count",
"=",
"float",
"(",
"count",
")",
"/",
"len",
"(",
"synsets",
")",
"for",
"synset",
"in",
"synsets",
":",
"total_count",
"+=",
"count",
"paths",
"=",
"synset",
".",
"hypernym_paths",
"scount",
"=",
"float",
"(",
"count",
")",
"/",
"len",
"(",
"paths",
")",
"for",
"path",
"in",
"paths",
":",
"for",
"ss",
"in",
"path",
":",
"gn_counts",
"[",
"ss",
".",
"_id",
"]",
"+=",
"scount",
"print",
"(",
"'Read {0} of {1} lines from count file.'",
".",
"format",
"(",
"num_lines_read",
",",
"num_lines",
")",
")",
"print",
"(",
"'Recorded counts for {0} synsets.'",
".",
"format",
"(",
"len",
"(",
"gn_counts",
")",
")",
")",
"print",
"(",
"'Total count is {0}'",
".",
"format",
"(",
"total_count",
")",
")",
"input_file",
".",
"close",
"(",
")",
"# update all the synset records in GermaNet",
"num_updates",
"=",
"0",
"for",
"synset",
"in",
"germanet_db",
".",
"synsets",
".",
"find",
"(",
")",
":",
"synset",
"[",
"'infocont'",
"]",
"=",
"gn_counts",
"[",
"synset",
"[",
"'_id'",
"]",
"]",
"/",
"total_count",
"germanet_db",
".",
"synsets",
".",
"save",
"(",
"synset",
")",
"num_updates",
"+=",
"1",
"print",
"(",
"'Updated {0} synsets.'",
".",
"format",
"(",
"num_updates",
")",
")"
] | For every synset in GermaNet, inserts count information derived
from SDEWAC.
Arguments:
- `germanet_db`: a pymongo.database.Database object | [
"For",
"every",
"synset",
"in",
"GermaNet",
"inserts",
"count",
"information",
"derived",
"from",
"SDEWAC",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L551-L600 | train |
wroberts/pygermanet | pygermanet/mongo_import.py | compute_max_min_depth | def compute_max_min_depth(germanet_db):
'''
For every part of speech in GermaNet, computes the maximum
min_depth in that hierarchy.
Arguments:
- `germanet_db`: a pymongo.database.Database object
'''
gnet = germanet.GermaNet(germanet_db)
max_min_depths = defaultdict(lambda: -1)
for synset in gnet.all_synsets():
min_depth = synset.min_depth
if max_min_depths[synset.category] < min_depth:
max_min_depths[synset.category] = min_depth
if germanet_db.metainfo.count() == 0:
germanet_db.metainfo.insert({})
metainfo = germanet_db.metainfo.find_one()
metainfo['max_min_depths'] = max_min_depths
germanet_db.metainfo.save(metainfo)
print('Computed maximum min_depth for all parts of speech:')
print(u', '.join(u'{0}: {1}'.format(k, v) for (k, v) in
sorted(max_min_depths.items())).encode('utf-8')) | python | def compute_max_min_depth(germanet_db):
'''
For every part of speech in GermaNet, computes the maximum
min_depth in that hierarchy.
Arguments:
- `germanet_db`: a pymongo.database.Database object
'''
gnet = germanet.GermaNet(germanet_db)
max_min_depths = defaultdict(lambda: -1)
for synset in gnet.all_synsets():
min_depth = synset.min_depth
if max_min_depths[synset.category] < min_depth:
max_min_depths[synset.category] = min_depth
if germanet_db.metainfo.count() == 0:
germanet_db.metainfo.insert({})
metainfo = germanet_db.metainfo.find_one()
metainfo['max_min_depths'] = max_min_depths
germanet_db.metainfo.save(metainfo)
print('Computed maximum min_depth for all parts of speech:')
print(u', '.join(u'{0}: {1}'.format(k, v) for (k, v) in
sorted(max_min_depths.items())).encode('utf-8')) | [
"def",
"compute_max_min_depth",
"(",
"germanet_db",
")",
":",
"gnet",
"=",
"germanet",
".",
"GermaNet",
"(",
"germanet_db",
")",
"max_min_depths",
"=",
"defaultdict",
"(",
"lambda",
":",
"-",
"1",
")",
"for",
"synset",
"in",
"gnet",
".",
"all_synsets",
"(",
")",
":",
"min_depth",
"=",
"synset",
".",
"min_depth",
"if",
"max_min_depths",
"[",
"synset",
".",
"category",
"]",
"<",
"min_depth",
":",
"max_min_depths",
"[",
"synset",
".",
"category",
"]",
"=",
"min_depth",
"if",
"germanet_db",
".",
"metainfo",
".",
"count",
"(",
")",
"==",
"0",
":",
"germanet_db",
".",
"metainfo",
".",
"insert",
"(",
"{",
"}",
")",
"metainfo",
"=",
"germanet_db",
".",
"metainfo",
".",
"find_one",
"(",
")",
"metainfo",
"[",
"'max_min_depths'",
"]",
"=",
"max_min_depths",
"germanet_db",
".",
"metainfo",
".",
"save",
"(",
"metainfo",
")",
"print",
"(",
"'Computed maximum min_depth for all parts of speech:'",
")",
"print",
"(",
"u', '",
".",
"join",
"(",
"u'{0}: {1}'",
".",
"format",
"(",
"k",
",",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"sorted",
"(",
"max_min_depths",
".",
"items",
"(",
")",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")"
] | For every part of speech in GermaNet, computes the maximum
min_depth in that hierarchy.
Arguments:
- `germanet_db`: a pymongo.database.Database object | [
"For",
"every",
"part",
"of",
"speech",
"in",
"GermaNet",
"computes",
"the",
"maximum",
"min_depth",
"in",
"that",
"hierarchy",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L602-L625 | train |
wroberts/pygermanet | pygermanet/mongo_import.py | main | def main():
'''Main function.'''
usage = ('\n\n %prog [options] XML_PATH\n\nArguments:\n\n '
'XML_PATH the directory containing the '
'GermaNet .xml files')
parser = optparse.OptionParser(usage=usage)
parser.add_option('--host', default=None,
help='hostname or IP address of the MongoDB instance '
'where the GermaNet database will be inserted '
'(default: %default)')
parser.add_option('--port', type='int', default=None,
help='port number of the MongoDB instance where the '
'GermaNet database will be inserted (default: %default)')
parser.add_option('--database', dest='database_name', default='germanet',
help='the name of the database on the MongoDB instance '
'where GermaNet will be stored (default: %default)')
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
sys.exit(1)
xml_path = args[0]
client = MongoClient(options.host, options.port)
germanet_db = client[options.database_name]
lex_files, gn_rels_file, wiktionary_files, ili_files = \
find_germanet_xml_files(xml_path)
insert_lexical_information(germanet_db, lex_files)
insert_relation_information(germanet_db, gn_rels_file)
insert_paraphrase_information(germanet_db, wiktionary_files)
insert_lemmatisation_data(germanet_db)
insert_infocontent_data(germanet_db)
compute_max_min_depth(germanet_db)
client.close() | python | def main():
'''Main function.'''
usage = ('\n\n %prog [options] XML_PATH\n\nArguments:\n\n '
'XML_PATH the directory containing the '
'GermaNet .xml files')
parser = optparse.OptionParser(usage=usage)
parser.add_option('--host', default=None,
help='hostname or IP address of the MongoDB instance '
'where the GermaNet database will be inserted '
'(default: %default)')
parser.add_option('--port', type='int', default=None,
help='port number of the MongoDB instance where the '
'GermaNet database will be inserted (default: %default)')
parser.add_option('--database', dest='database_name', default='germanet',
help='the name of the database on the MongoDB instance '
'where GermaNet will be stored (default: %default)')
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
sys.exit(1)
xml_path = args[0]
client = MongoClient(options.host, options.port)
germanet_db = client[options.database_name]
lex_files, gn_rels_file, wiktionary_files, ili_files = \
find_germanet_xml_files(xml_path)
insert_lexical_information(germanet_db, lex_files)
insert_relation_information(germanet_db, gn_rels_file)
insert_paraphrase_information(germanet_db, wiktionary_files)
insert_lemmatisation_data(germanet_db)
insert_infocontent_data(germanet_db)
compute_max_min_depth(germanet_db)
client.close() | [
"def",
"main",
"(",
")",
":",
"usage",
"=",
"(",
"'\\n\\n %prog [options] XML_PATH\\n\\nArguments:\\n\\n '",
"'XML_PATH the directory containing the '",
"'GermaNet .xml files'",
")",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"usage",
"=",
"usage",
")",
"parser",
".",
"add_option",
"(",
"'--host'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'hostname or IP address of the MongoDB instance '",
"'where the GermaNet database will be inserted '",
"'(default: %default)'",
")",
"parser",
".",
"add_option",
"(",
"'--port'",
",",
"type",
"=",
"'int'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'port number of the MongoDB instance where the '",
"'GermaNet database will be inserted (default: %default)'",
")",
"parser",
".",
"add_option",
"(",
"'--database'",
",",
"dest",
"=",
"'database_name'",
",",
"default",
"=",
"'germanet'",
",",
"help",
"=",
"'the name of the database on the MongoDB instance '",
"'where GermaNet will be stored (default: %default)'",
")",
"(",
"options",
",",
"args",
")",
"=",
"parser",
".",
"parse_args",
"(",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"parser",
".",
"error",
"(",
"\"incorrect number of arguments\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"xml_path",
"=",
"args",
"[",
"0",
"]",
"client",
"=",
"MongoClient",
"(",
"options",
".",
"host",
",",
"options",
".",
"port",
")",
"germanet_db",
"=",
"client",
"[",
"options",
".",
"database_name",
"]",
"lex_files",
",",
"gn_rels_file",
",",
"wiktionary_files",
",",
"ili_files",
"=",
"find_germanet_xml_files",
"(",
"xml_path",
")",
"insert_lexical_information",
"(",
"germanet_db",
",",
"lex_files",
")",
"insert_relation_information",
"(",
"germanet_db",
",",
"gn_rels_file",
")",
"insert_paraphrase_information",
"(",
"germanet_db",
",",
"wiktionary_files",
")",
"insert_lemmatisation_data",
"(",
"germanet_db",
")",
"insert_infocontent_data",
"(",
"germanet_db",
")",
"compute_max_min_depth",
"(",
"germanet_db",
")",
"client",
".",
"close",
"(",
")"
] | Main function. | [
"Main",
"function",
"."
] | 1818c20a7e8c431c4cfb5a570ed0d850bb6dd515 | https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L632-L669 | train |
alonho/pql | pql/matching.py | Operator.handle_In | def handle_In(self, node):
'''in'''
try:
elts = node.elts
except AttributeError:
raise ParseError('Invalid value type for `in` operator: {0}'.format(node.__class__.__name__),
col_offset=node.col_offset)
return {'$in': list(map(self.field.handle, elts))} | python | def handle_In(self, node):
'''in'''
try:
elts = node.elts
except AttributeError:
raise ParseError('Invalid value type for `in` operator: {0}'.format(node.__class__.__name__),
col_offset=node.col_offset)
return {'$in': list(map(self.field.handle, elts))} | [
"def",
"handle_In",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"elts",
"=",
"node",
".",
"elts",
"except",
"AttributeError",
":",
"raise",
"ParseError",
"(",
"'Invalid value type for `in` operator: {0}'",
".",
"format",
"(",
"node",
".",
"__class__",
".",
"__name__",
")",
",",
"col_offset",
"=",
"node",
".",
"col_offset",
")",
"return",
"{",
"'$in'",
":",
"list",
"(",
"map",
"(",
"self",
".",
"field",
".",
"handle",
",",
"elts",
")",
")",
"}"
] | in | [
"in"
] | fd8fefcb720b4325d27ab71f15a882fe5f9f77e2 | https://github.com/alonho/pql/blob/fd8fefcb720b4325d27ab71f15a882fe5f9f77e2/pql/matching.py#L302-L309 | train |
jonathanslenders/textfsm | jtextfsm.py | TextFSMValue.AssignVar | def AssignVar(self, value):
"""Assign a value to this Value."""
self.value = value
# Call OnAssignVar on options.
[option.OnAssignVar() for option in self.options] | python | def AssignVar(self, value):
"""Assign a value to this Value."""
self.value = value
# Call OnAssignVar on options.
[option.OnAssignVar() for option in self.options] | [
"def",
"AssignVar",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"value",
"=",
"value",
"# Call OnAssignVar on options.",
"[",
"option",
".",
"OnAssignVar",
"(",
")",
"for",
"option",
"in",
"self",
".",
"options",
"]"
] | Assign a value to this Value. | [
"Assign",
"a",
"value",
"to",
"this",
"Value",
"."
] | cca5084512d14bc367205aceb34c938ac1c65daf | https://github.com/jonathanslenders/textfsm/blob/cca5084512d14bc367205aceb34c938ac1c65daf/jtextfsm.py#L223-L227 | train |
jonathanslenders/textfsm | jtextfsm.py | TextFSMValue.Parse | def Parse(self, value):
"""Parse a 'Value' declaration.
Args:
value: String line from a template file, must begin with 'Value '.
Raises:
TextFSMTemplateError: Value declaration contains an error.
"""
value_line = value.split(' ')
if len(value_line) < 3:
raise TextFSMTemplateError('Expect at least 3 tokens on line.')
if not value_line[2].startswith('('):
# Options are present
options = value_line[1]
for option in options.split(','):
self._AddOption(option)
# Call option OnCreateOptions callbacks
[option.OnCreateOptions() for option in self.options]
self.name = value_line[2]
self.regex = ' '.join(value_line[3:])
else:
# There were no valid options, so there are no options.
# Treat this argument as the name.
self.name = value_line[1]
self.regex = ' '.join(value_line[2:])
if len(self.name) > self.max_name_len:
raise TextFSMTemplateError(
"Invalid Value name '%s' or name too long." % self.name)
if (not re.match(r'^\(.*\)$', self.regex) or
self.regex.count('(') != self.regex.count(')')):
raise TextFSMTemplateError(
"Value '%s' must be contained within a '()' pair." % self.regex)
self.template = re.sub(r'^\(', '(?P<%s>' % self.name, self.regex) | python | def Parse(self, value):
"""Parse a 'Value' declaration.
Args:
value: String line from a template file, must begin with 'Value '.
Raises:
TextFSMTemplateError: Value declaration contains an error.
"""
value_line = value.split(' ')
if len(value_line) < 3:
raise TextFSMTemplateError('Expect at least 3 tokens on line.')
if not value_line[2].startswith('('):
# Options are present
options = value_line[1]
for option in options.split(','):
self._AddOption(option)
# Call option OnCreateOptions callbacks
[option.OnCreateOptions() for option in self.options]
self.name = value_line[2]
self.regex = ' '.join(value_line[3:])
else:
# There were no valid options, so there are no options.
# Treat this argument as the name.
self.name = value_line[1]
self.regex = ' '.join(value_line[2:])
if len(self.name) > self.max_name_len:
raise TextFSMTemplateError(
"Invalid Value name '%s' or name too long." % self.name)
if (not re.match(r'^\(.*\)$', self.regex) or
self.regex.count('(') != self.regex.count(')')):
raise TextFSMTemplateError(
"Value '%s' must be contained within a '()' pair." % self.regex)
self.template = re.sub(r'^\(', '(?P<%s>' % self.name, self.regex) | [
"def",
"Parse",
"(",
"self",
",",
"value",
")",
":",
"value_line",
"=",
"value",
".",
"split",
"(",
"' '",
")",
"if",
"len",
"(",
"value_line",
")",
"<",
"3",
":",
"raise",
"TextFSMTemplateError",
"(",
"'Expect at least 3 tokens on line.'",
")",
"if",
"not",
"value_line",
"[",
"2",
"]",
".",
"startswith",
"(",
"'('",
")",
":",
"# Options are present",
"options",
"=",
"value_line",
"[",
"1",
"]",
"for",
"option",
"in",
"options",
".",
"split",
"(",
"','",
")",
":",
"self",
".",
"_AddOption",
"(",
"option",
")",
"# Call option OnCreateOptions callbacks",
"[",
"option",
".",
"OnCreateOptions",
"(",
")",
"for",
"option",
"in",
"self",
".",
"options",
"]",
"self",
".",
"name",
"=",
"value_line",
"[",
"2",
"]",
"self",
".",
"regex",
"=",
"' '",
".",
"join",
"(",
"value_line",
"[",
"3",
":",
"]",
")",
"else",
":",
"# There were no valid options, so there are no options.",
"# Treat this argument as the name.",
"self",
".",
"name",
"=",
"value_line",
"[",
"1",
"]",
"self",
".",
"regex",
"=",
"' '",
".",
"join",
"(",
"value_line",
"[",
"2",
":",
"]",
")",
"if",
"len",
"(",
"self",
".",
"name",
")",
">",
"self",
".",
"max_name_len",
":",
"raise",
"TextFSMTemplateError",
"(",
"\"Invalid Value name '%s' or name too long.\"",
"%",
"self",
".",
"name",
")",
"if",
"(",
"not",
"re",
".",
"match",
"(",
"r'^\\(.*\\)$'",
",",
"self",
".",
"regex",
")",
"or",
"self",
".",
"regex",
".",
"count",
"(",
"'('",
")",
"!=",
"self",
".",
"regex",
".",
"count",
"(",
"')'",
")",
")",
":",
"raise",
"TextFSMTemplateError",
"(",
"\"Value '%s' must be contained within a '()' pair.\"",
"%",
"self",
".",
"regex",
")",
"self",
".",
"template",
"=",
"re",
".",
"sub",
"(",
"r'^\\('",
",",
"'(?P<%s>'",
"%",
"self",
".",
"name",
",",
"self",
".",
"regex",
")"
] | Parse a 'Value' declaration.
Args:
value: String line from a template file, must begin with 'Value '.
Raises:
TextFSMTemplateError: Value declaration contains an error. | [
"Parse",
"a",
"Value",
"declaration",
"."
] | cca5084512d14bc367205aceb34c938ac1c65daf | https://github.com/jonathanslenders/textfsm/blob/cca5084512d14bc367205aceb34c938ac1c65daf/jtextfsm.py#L251-L291 | train |
jonathanslenders/textfsm | jtextfsm.py | TextFSM._CheckLine | def _CheckLine(self, line):
"""Passes the line through each rule until a match is made.
Args:
line: A string, the current input line.
"""
for rule in self._cur_state:
matched = self._CheckRule(rule, line)
if matched:
for value in matched.groupdict():
self._AssignVar(matched, value)
if self._Operations(rule):
# Not a Continue so check for state transition.
if rule.new_state:
if rule.new_state not in ('End', 'EOF'):
self._cur_state = self.states[rule.new_state]
self._cur_state_name = rule.new_state
break | python | def _CheckLine(self, line):
"""Passes the line through each rule until a match is made.
Args:
line: A string, the current input line.
"""
for rule in self._cur_state:
matched = self._CheckRule(rule, line)
if matched:
for value in matched.groupdict():
self._AssignVar(matched, value)
if self._Operations(rule):
# Not a Continue so check for state transition.
if rule.new_state:
if rule.new_state not in ('End', 'EOF'):
self._cur_state = self.states[rule.new_state]
self._cur_state_name = rule.new_state
break | [
"def",
"_CheckLine",
"(",
"self",
",",
"line",
")",
":",
"for",
"rule",
"in",
"self",
".",
"_cur_state",
":",
"matched",
"=",
"self",
".",
"_CheckRule",
"(",
"rule",
",",
"line",
")",
"if",
"matched",
":",
"for",
"value",
"in",
"matched",
".",
"groupdict",
"(",
")",
":",
"self",
".",
"_AssignVar",
"(",
"matched",
",",
"value",
")",
"if",
"self",
".",
"_Operations",
"(",
"rule",
")",
":",
"# Not a Continue so check for state transition.",
"if",
"rule",
".",
"new_state",
":",
"if",
"rule",
".",
"new_state",
"not",
"in",
"(",
"'End'",
",",
"'EOF'",
")",
":",
"self",
".",
"_cur_state",
"=",
"self",
".",
"states",
"[",
"rule",
".",
"new_state",
"]",
"self",
".",
"_cur_state_name",
"=",
"rule",
".",
"new_state",
"break"
] | Passes the line through each rule until a match is made.
Args:
line: A string, the current input line. | [
"Passes",
"the",
"line",
"through",
"each",
"rule",
"until",
"a",
"match",
"is",
"made",
"."
] | cca5084512d14bc367205aceb34c938ac1c65daf | https://github.com/jonathanslenders/textfsm/blob/cca5084512d14bc367205aceb34c938ac1c65daf/jtextfsm.py#L866-L884 | train |
vimeo/graphite-influxdb | graphite_influxdb.py | _make_graphite_api_points_list | def _make_graphite_api_points_list(influxdb_data):
"""Make graphite-api data points dictionary from Influxdb ResultSet data"""
_data = {}
for key in influxdb_data.keys():
_data[key[0]] = [(datetime.datetime.fromtimestamp(float(d['time'])),
d['value']) for d in influxdb_data.get_points(key[0])]
return _data | python | def _make_graphite_api_points_list(influxdb_data):
"""Make graphite-api data points dictionary from Influxdb ResultSet data"""
_data = {}
for key in influxdb_data.keys():
_data[key[0]] = [(datetime.datetime.fromtimestamp(float(d['time'])),
d['value']) for d in influxdb_data.get_points(key[0])]
return _data | [
"def",
"_make_graphite_api_points_list",
"(",
"influxdb_data",
")",
":",
"_data",
"=",
"{",
"}",
"for",
"key",
"in",
"influxdb_data",
".",
"keys",
"(",
")",
":",
"_data",
"[",
"key",
"[",
"0",
"]",
"]",
"=",
"[",
"(",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"float",
"(",
"d",
"[",
"'time'",
"]",
")",
")",
",",
"d",
"[",
"'value'",
"]",
")",
"for",
"d",
"in",
"influxdb_data",
".",
"get_points",
"(",
"key",
"[",
"0",
"]",
")",
"]",
"return",
"_data"
] | Make graphite-api data points dictionary from Influxdb ResultSet data | [
"Make",
"graphite",
"-",
"api",
"data",
"points",
"dictionary",
"from",
"Influxdb",
"ResultSet",
"data"
] | 56e4aeec57f39c90f14f3fbec57641b90d06c08b | https://github.com/vimeo/graphite-influxdb/blob/56e4aeec57f39c90f14f3fbec57641b90d06c08b/graphite_influxdb.py#L90-L96 | train |
vimeo/graphite-influxdb | graphite_influxdb.py | InfluxdbFinder._setup_logger | def _setup_logger(self, level, log_file):
"""Setup log level and log file if set"""
if logger.handlers:
return
level = getattr(logging, level.upper())
logger.setLevel(level)
formatter = logging.Formatter(
'[%(levelname)s] %(asctime)s - %(module)s.%(funcName)s() - %(message)s')
handler = logging.StreamHandler()
logger.addHandler(handler)
handler.setFormatter(formatter)
if not log_file:
return
try:
handler = TimedRotatingFileHandler(log_file)
except IOError:
logger.error("Could not write to %s, falling back to stdout",
log_file)
else:
logger.addHandler(handler)
handler.setFormatter(formatter) | python | def _setup_logger(self, level, log_file):
"""Setup log level and log file if set"""
if logger.handlers:
return
level = getattr(logging, level.upper())
logger.setLevel(level)
formatter = logging.Formatter(
'[%(levelname)s] %(asctime)s - %(module)s.%(funcName)s() - %(message)s')
handler = logging.StreamHandler()
logger.addHandler(handler)
handler.setFormatter(formatter)
if not log_file:
return
try:
handler = TimedRotatingFileHandler(log_file)
except IOError:
logger.error("Could not write to %s, falling back to stdout",
log_file)
else:
logger.addHandler(handler)
handler.setFormatter(formatter) | [
"def",
"_setup_logger",
"(",
"self",
",",
"level",
",",
"log_file",
")",
":",
"if",
"logger",
".",
"handlers",
":",
"return",
"level",
"=",
"getattr",
"(",
"logging",
",",
"level",
".",
"upper",
"(",
")",
")",
"logger",
".",
"setLevel",
"(",
"level",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'[%(levelname)s] %(asctime)s - %(module)s.%(funcName)s() - %(message)s'",
")",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"logger",
".",
"addHandler",
"(",
"handler",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"if",
"not",
"log_file",
":",
"return",
"try",
":",
"handler",
"=",
"TimedRotatingFileHandler",
"(",
"log_file",
")",
"except",
"IOError",
":",
"logger",
".",
"error",
"(",
"\"Could not write to %s, falling back to stdout\"",
",",
"log_file",
")",
"else",
":",
"logger",
".",
"addHandler",
"(",
"handler",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")"
] | Setup log level and log file if set | [
"Setup",
"log",
"level",
"and",
"log",
"file",
"if",
"set"
] | 56e4aeec57f39c90f14f3fbec57641b90d06c08b | https://github.com/vimeo/graphite-influxdb/blob/56e4aeec57f39c90f14f3fbec57641b90d06c08b/graphite_influxdb.py#L166-L186 | train |
vimeo/graphite-influxdb | graphite_influxdb.py | InfluxdbFinder.compile_regex | def compile_regex(self, fmt, query):
"""Turn glob (graphite) queries into compiled regex
* becomes .*
. becomes \.
fmt argument is so that caller can control anchoring (must contain exactly 1 {0} !"""
return re.compile(fmt.format(
query.pattern.replace('.', '\.').replace('*', '[^\.]*').replace(
'{', '(').replace(',', '|').replace('}', ')')
)) | python | def compile_regex(self, fmt, query):
"""Turn glob (graphite) queries into compiled regex
* becomes .*
. becomes \.
fmt argument is so that caller can control anchoring (must contain exactly 1 {0} !"""
return re.compile(fmt.format(
query.pattern.replace('.', '\.').replace('*', '[^\.]*').replace(
'{', '(').replace(',', '|').replace('}', ')')
)) | [
"def",
"compile_regex",
"(",
"self",
",",
"fmt",
",",
"query",
")",
":",
"return",
"re",
".",
"compile",
"(",
"fmt",
".",
"format",
"(",
"query",
".",
"pattern",
".",
"replace",
"(",
"'.'",
",",
"'\\.'",
")",
".",
"replace",
"(",
"'*'",
",",
"'[^\\.]*'",
")",
".",
"replace",
"(",
"'{'",
",",
"'('",
")",
".",
"replace",
"(",
"','",
",",
"'|'",
")",
".",
"replace",
"(",
"'}'",
",",
"')'",
")",
")",
")"
] | Turn glob (graphite) queries into compiled regex
* becomes .*
. becomes \.
fmt argument is so that caller can control anchoring (must contain exactly 1 {0} ! | [
"Turn",
"glob",
"(",
"graphite",
")",
"queries",
"into",
"compiled",
"regex",
"*",
"becomes",
".",
"*",
".",
"becomes",
"\\",
".",
"fmt",
"argument",
"is",
"so",
"that",
"caller",
"can",
"control",
"anchoring",
"(",
"must",
"contain",
"exactly",
"1",
"{",
"0",
"}",
"!"
] | 56e4aeec57f39c90f14f3fbec57641b90d06c08b | https://github.com/vimeo/graphite-influxdb/blob/56e4aeec57f39c90f14f3fbec57641b90d06c08b/graphite_influxdb.py#L230-L238 | train |
alonho/pql | pql/__init__.py | find | def find(expression, schema=None):
'''
Gets an <expression> and optional <schema>.
<expression> should be a string of python code.
<schema> should be a dictionary mapping field names to types.
'''
parser = SchemaFreeParser() if schema is None else SchemaAwareParser(schema)
return parser.parse(expression) | python | def find(expression, schema=None):
'''
Gets an <expression> and optional <schema>.
<expression> should be a string of python code.
<schema> should be a dictionary mapping field names to types.
'''
parser = SchemaFreeParser() if schema is None else SchemaAwareParser(schema)
return parser.parse(expression) | [
"def",
"find",
"(",
"expression",
",",
"schema",
"=",
"None",
")",
":",
"parser",
"=",
"SchemaFreeParser",
"(",
")",
"if",
"schema",
"is",
"None",
"else",
"SchemaAwareParser",
"(",
"schema",
")",
"return",
"parser",
".",
"parse",
"(",
"expression",
")"
] | Gets an <expression> and optional <schema>.
<expression> should be a string of python code.
<schema> should be a dictionary mapping field names to types. | [
"Gets",
"an",
"<expression",
">",
"and",
"optional",
"<schema",
">",
".",
"<expression",
">",
"should",
"be",
"a",
"string",
"of",
"python",
"code",
".",
"<schema",
">",
"should",
"be",
"a",
"dictionary",
"mapping",
"field",
"names",
"to",
"types",
"."
] | fd8fefcb720b4325d27ab71f15a882fe5f9f77e2 | https://github.com/alonho/pql/blob/fd8fefcb720b4325d27ab71f15a882fe5f9f77e2/pql/__init__.py#L7-L14 | train |
alonho/pql | pql/__init__.py | sort | def sort(fields):
'''
Gets a list of <fields> to sort by.
Also supports getting a single string for sorting by one field.
Reverse sort is supported by appending '-' to the field name.
Example: sort(['age', '-height']) will sort by ascending age and descending height.
'''
from pymongo import ASCENDING, DESCENDING
from bson import SON
if isinstance(fields, str):
fields = [fields]
if not hasattr(fields, '__iter__'):
raise ValueError("expected a list of strings or a string. not a {}".format(type(fields)))
sort = []
for field in fields:
if field.startswith('-'):
field = field[1:]
sort.append((field, DESCENDING))
continue
elif field.startswith('+'):
field = field[1:]
sort.append((field, ASCENDING))
return {'$sort': SON(sort)} | python | def sort(fields):
'''
Gets a list of <fields> to sort by.
Also supports getting a single string for sorting by one field.
Reverse sort is supported by appending '-' to the field name.
Example: sort(['age', '-height']) will sort by ascending age and descending height.
'''
from pymongo import ASCENDING, DESCENDING
from bson import SON
if isinstance(fields, str):
fields = [fields]
if not hasattr(fields, '__iter__'):
raise ValueError("expected a list of strings or a string. not a {}".format(type(fields)))
sort = []
for field in fields:
if field.startswith('-'):
field = field[1:]
sort.append((field, DESCENDING))
continue
elif field.startswith('+'):
field = field[1:]
sort.append((field, ASCENDING))
return {'$sort': SON(sort)} | [
"def",
"sort",
"(",
"fields",
")",
":",
"from",
"pymongo",
"import",
"ASCENDING",
",",
"DESCENDING",
"from",
"bson",
"import",
"SON",
"if",
"isinstance",
"(",
"fields",
",",
"str",
")",
":",
"fields",
"=",
"[",
"fields",
"]",
"if",
"not",
"hasattr",
"(",
"fields",
",",
"'__iter__'",
")",
":",
"raise",
"ValueError",
"(",
"\"expected a list of strings or a string. not a {}\"",
".",
"format",
"(",
"type",
"(",
"fields",
")",
")",
")",
"sort",
"=",
"[",
"]",
"for",
"field",
"in",
"fields",
":",
"if",
"field",
".",
"startswith",
"(",
"'-'",
")",
":",
"field",
"=",
"field",
"[",
"1",
":",
"]",
"sort",
".",
"append",
"(",
"(",
"field",
",",
"DESCENDING",
")",
")",
"continue",
"elif",
"field",
".",
"startswith",
"(",
"'+'",
")",
":",
"field",
"=",
"field",
"[",
"1",
":",
"]",
"sort",
".",
"append",
"(",
"(",
"field",
",",
"ASCENDING",
")",
")",
"return",
"{",
"'$sort'",
":",
"SON",
"(",
"sort",
")",
"}"
] | Gets a list of <fields> to sort by.
Also supports getting a single string for sorting by one field.
Reverse sort is supported by appending '-' to the field name.
Example: sort(['age', '-height']) will sort by ascending age and descending height. | [
"Gets",
"a",
"list",
"of",
"<fields",
">",
"to",
"sort",
"by",
".",
"Also",
"supports",
"getting",
"a",
"single",
"string",
"for",
"sorting",
"by",
"one",
"field",
".",
"Reverse",
"sort",
"is",
"supported",
"by",
"appending",
"-",
"to",
"the",
"field",
"name",
".",
"Example",
":",
"sort",
"(",
"[",
"age",
"-",
"height",
"]",
")",
"will",
"sort",
"by",
"ascending",
"age",
"and",
"descending",
"height",
"."
] | fd8fefcb720b4325d27ab71f15a882fe5f9f77e2 | https://github.com/alonho/pql/blob/fd8fefcb720b4325d27ab71f15a882fe5f9f77e2/pql/__init__.py#L73-L97 | train |
numberoverzero/bloop | bloop/util.py | ordered | def ordered(obj):
"""
Return sorted version of nested dicts/lists for comparing.
Modified from:
http://stackoverflow.com/a/25851972
"""
if isinstance(obj, collections.abc.Mapping):
return sorted((k, ordered(v)) for k, v in obj.items())
# Special case str since it's a collections.abc.Iterable
elif isinstance(obj, str):
return obj
elif isinstance(obj, collections.abc.Iterable):
return sorted(ordered(x) for x in obj)
else:
return obj | python | def ordered(obj):
"""
Return sorted version of nested dicts/lists for comparing.
Modified from:
http://stackoverflow.com/a/25851972
"""
if isinstance(obj, collections.abc.Mapping):
return sorted((k, ordered(v)) for k, v in obj.items())
# Special case str since it's a collections.abc.Iterable
elif isinstance(obj, str):
return obj
elif isinstance(obj, collections.abc.Iterable):
return sorted(ordered(x) for x in obj)
else:
return obj | [
"def",
"ordered",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"collections",
".",
"abc",
".",
"Mapping",
")",
":",
"return",
"sorted",
"(",
"(",
"k",
",",
"ordered",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"obj",
".",
"items",
"(",
")",
")",
"# Special case str since it's a collections.abc.Iterable",
"elif",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"return",
"obj",
"elif",
"isinstance",
"(",
"obj",
",",
"collections",
".",
"abc",
".",
"Iterable",
")",
":",
"return",
"sorted",
"(",
"ordered",
"(",
"x",
")",
"for",
"x",
"in",
"obj",
")",
"else",
":",
"return",
"obj"
] | Return sorted version of nested dicts/lists for comparing.
Modified from:
http://stackoverflow.com/a/25851972 | [
"Return",
"sorted",
"version",
"of",
"nested",
"dicts",
"/",
"lists",
"for",
"comparing",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/util.py#L65-L80 | train |
numberoverzero/bloop | bloop/util.py | walk_subclasses | def walk_subclasses(root):
"""Does not yield the input class"""
classes = [root]
visited = set()
while classes:
cls = classes.pop()
if cls is type or cls in visited:
continue
classes.extend(cls.__subclasses__())
visited.add(cls)
if cls is not root:
yield cls | python | def walk_subclasses(root):
"""Does not yield the input class"""
classes = [root]
visited = set()
while classes:
cls = classes.pop()
if cls is type or cls in visited:
continue
classes.extend(cls.__subclasses__())
visited.add(cls)
if cls is not root:
yield cls | [
"def",
"walk_subclasses",
"(",
"root",
")",
":",
"classes",
"=",
"[",
"root",
"]",
"visited",
"=",
"set",
"(",
")",
"while",
"classes",
":",
"cls",
"=",
"classes",
".",
"pop",
"(",
")",
"if",
"cls",
"is",
"type",
"or",
"cls",
"in",
"visited",
":",
"continue",
"classes",
".",
"extend",
"(",
"cls",
".",
"__subclasses__",
"(",
")",
")",
"visited",
".",
"add",
"(",
"cls",
")",
"if",
"cls",
"is",
"not",
"root",
":",
"yield",
"cls"
] | Does not yield the input class | [
"Does",
"not",
"yield",
"the",
"input",
"class"
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/util.py#L83-L94 | train |
numberoverzero/bloop | bloop/util.py | dump_key | def dump_key(engine, obj):
"""dump the hash (and range, if there is one) key(s) of an object into
a dynamo-friendly format.
returns {dynamo_name: {type: value} for dynamo_name in hash/range keys}
"""
key = {}
for key_column in obj.Meta.keys:
key_value = getattr(obj, key_column.name, missing)
if key_value is missing:
raise MissingKey("{!r} is missing {}: {!r}".format(
obj, "hash_key" if key_column.hash_key else "range_key",
key_column.name
))
# noinspection PyProtectedMember
key_value = engine._dump(key_column.typedef, key_value)
key[key_column.dynamo_name] = key_value
return key | python | def dump_key(engine, obj):
"""dump the hash (and range, if there is one) key(s) of an object into
a dynamo-friendly format.
returns {dynamo_name: {type: value} for dynamo_name in hash/range keys}
"""
key = {}
for key_column in obj.Meta.keys:
key_value = getattr(obj, key_column.name, missing)
if key_value is missing:
raise MissingKey("{!r} is missing {}: {!r}".format(
obj, "hash_key" if key_column.hash_key else "range_key",
key_column.name
))
# noinspection PyProtectedMember
key_value = engine._dump(key_column.typedef, key_value)
key[key_column.dynamo_name] = key_value
return key | [
"def",
"dump_key",
"(",
"engine",
",",
"obj",
")",
":",
"key",
"=",
"{",
"}",
"for",
"key_column",
"in",
"obj",
".",
"Meta",
".",
"keys",
":",
"key_value",
"=",
"getattr",
"(",
"obj",
",",
"key_column",
".",
"name",
",",
"missing",
")",
"if",
"key_value",
"is",
"missing",
":",
"raise",
"MissingKey",
"(",
"\"{!r} is missing {}: {!r}\"",
".",
"format",
"(",
"obj",
",",
"\"hash_key\"",
"if",
"key_column",
".",
"hash_key",
"else",
"\"range_key\"",
",",
"key_column",
".",
"name",
")",
")",
"# noinspection PyProtectedMember",
"key_value",
"=",
"engine",
".",
"_dump",
"(",
"key_column",
".",
"typedef",
",",
"key_value",
")",
"key",
"[",
"key_column",
".",
"dynamo_name",
"]",
"=",
"key_value",
"return",
"key"
] | dump the hash (and range, if there is one) key(s) of an object into
a dynamo-friendly format.
returns {dynamo_name: {type: value} for dynamo_name in hash/range keys} | [
"dump",
"the",
"hash",
"(",
"and",
"range",
"if",
"there",
"is",
"one",
")",
"key",
"(",
"s",
")",
"of",
"an",
"object",
"into",
"a",
"dynamo",
"-",
"friendly",
"format",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/util.py#L125-L142 | train |
numberoverzero/bloop | examples/mixins.py | new_expiry | def new_expiry(days=DEFAULT_PASTE_LIFETIME_DAYS):
"""Return an expiration `days` in the future"""
now = delorean.Delorean()
return now + datetime.timedelta(days=days) | python | def new_expiry(days=DEFAULT_PASTE_LIFETIME_DAYS):
"""Return an expiration `days` in the future"""
now = delorean.Delorean()
return now + datetime.timedelta(days=days) | [
"def",
"new_expiry",
"(",
"days",
"=",
"DEFAULT_PASTE_LIFETIME_DAYS",
")",
":",
"now",
"=",
"delorean",
".",
"Delorean",
"(",
")",
"return",
"now",
"+",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"days",
")"
] | Return an expiration `days` in the future | [
"Return",
"an",
"expiration",
"days",
"in",
"the",
"future"
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/examples/mixins.py#L14-L17 | train |
numberoverzero/bloop | bloop/conditions.py | sync | def sync(obj, engine):
"""Mark the object as having been persisted at least once.
Store the latest snapshot of all marked values."""
snapshot = Condition()
# Only expect values (or lack of a value) for columns that have been explicitly set
for column in sorted(_obj_tracking[obj]["marked"], key=lambda col: col.dynamo_name):
value = getattr(obj, column.name, None)
value = engine._dump(column.typedef, value)
condition = column == value
# The renderer shouldn't try to dump the value again.
# We're dumping immediately in case the value is mutable,
# such as a set or (many) custom data types.
condition.dumped = True
snapshot &= condition
_obj_tracking[obj]["snapshot"] = snapshot | python | def sync(obj, engine):
"""Mark the object as having been persisted at least once.
Store the latest snapshot of all marked values."""
snapshot = Condition()
# Only expect values (or lack of a value) for columns that have been explicitly set
for column in sorted(_obj_tracking[obj]["marked"], key=lambda col: col.dynamo_name):
value = getattr(obj, column.name, None)
value = engine._dump(column.typedef, value)
condition = column == value
# The renderer shouldn't try to dump the value again.
# We're dumping immediately in case the value is mutable,
# such as a set or (many) custom data types.
condition.dumped = True
snapshot &= condition
_obj_tracking[obj]["snapshot"] = snapshot | [
"def",
"sync",
"(",
"obj",
",",
"engine",
")",
":",
"snapshot",
"=",
"Condition",
"(",
")",
"# Only expect values (or lack of a value) for columns that have been explicitly set",
"for",
"column",
"in",
"sorted",
"(",
"_obj_tracking",
"[",
"obj",
"]",
"[",
"\"marked\"",
"]",
",",
"key",
"=",
"lambda",
"col",
":",
"col",
".",
"dynamo_name",
")",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
"column",
".",
"name",
",",
"None",
")",
"value",
"=",
"engine",
".",
"_dump",
"(",
"column",
".",
"typedef",
",",
"value",
")",
"condition",
"=",
"column",
"==",
"value",
"# The renderer shouldn't try to dump the value again.",
"# We're dumping immediately in case the value is mutable,",
"# such as a set or (many) custom data types.",
"condition",
".",
"dumped",
"=",
"True",
"snapshot",
"&=",
"condition",
"_obj_tracking",
"[",
"obj",
"]",
"[",
"\"snapshot\"",
"]",
"=",
"snapshot"
] | Mark the object as having been persisted at least once.
Store the latest snapshot of all marked values. | [
"Mark",
"the",
"object",
"as",
"having",
"been",
"persisted",
"at",
"least",
"once",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L63-L78 | train |
numberoverzero/bloop | bloop/conditions.py | printable_name | def printable_name(column, path=None):
"""Provided for debug output when rendering conditions.
User.name[3]["foo"][0]["bar"] -> name[3].foo[0].bar
"""
pieces = [column.name]
path = path or path_of(column)
for segment in path:
if isinstance(segment, str):
pieces.append(segment)
else:
pieces[-1] += "[{}]".format(segment)
return ".".join(pieces) | python | def printable_name(column, path=None):
"""Provided for debug output when rendering conditions.
User.name[3]["foo"][0]["bar"] -> name[3].foo[0].bar
"""
pieces = [column.name]
path = path or path_of(column)
for segment in path:
if isinstance(segment, str):
pieces.append(segment)
else:
pieces[-1] += "[{}]".format(segment)
return ".".join(pieces) | [
"def",
"printable_name",
"(",
"column",
",",
"path",
"=",
"None",
")",
":",
"pieces",
"=",
"[",
"column",
".",
"name",
"]",
"path",
"=",
"path",
"or",
"path_of",
"(",
"column",
")",
"for",
"segment",
"in",
"path",
":",
"if",
"isinstance",
"(",
"segment",
",",
"str",
")",
":",
"pieces",
".",
"append",
"(",
"segment",
")",
"else",
":",
"pieces",
"[",
"-",
"1",
"]",
"+=",
"\"[{}]\"",
".",
"format",
"(",
"segment",
")",
"return",
"\".\"",
".",
"join",
"(",
"pieces",
")"
] | Provided for debug output when rendering conditions.
User.name[3]["foo"][0]["bar"] -> name[3].foo[0].bar | [
"Provided",
"for",
"debug",
"output",
"when",
"rendering",
"conditions",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L887-L899 | train |
numberoverzero/bloop | bloop/conditions.py | iter_conditions | def iter_conditions(condition):
"""Yield all conditions within the given condition.
If the root condition is and/or/not, it is not yielded (unless a cyclic reference to it is found)."""
conditions = list()
visited = set()
# Has to be split out, since we don't want to visit the root (for cyclic conditions)
# but we don't want to yield it (if it's non-cyclic) because this only yields inner conditions
if condition.operation in {"and", "or"}:
conditions.extend(reversed(condition.values))
elif condition.operation == "not":
conditions.append(condition.values[0])
else:
conditions.append(condition)
while conditions:
condition = conditions.pop()
if condition in visited:
continue
visited.add(condition)
yield condition
if condition.operation in {"and", "or", "not"}:
conditions.extend(reversed(condition.values)) | python | def iter_conditions(condition):
"""Yield all conditions within the given condition.
If the root condition is and/or/not, it is not yielded (unless a cyclic reference to it is found)."""
conditions = list()
visited = set()
# Has to be split out, since we don't want to visit the root (for cyclic conditions)
# but we don't want to yield it (if it's non-cyclic) because this only yields inner conditions
if condition.operation in {"and", "or"}:
conditions.extend(reversed(condition.values))
elif condition.operation == "not":
conditions.append(condition.values[0])
else:
conditions.append(condition)
while conditions:
condition = conditions.pop()
if condition in visited:
continue
visited.add(condition)
yield condition
if condition.operation in {"and", "or", "not"}:
conditions.extend(reversed(condition.values)) | [
"def",
"iter_conditions",
"(",
"condition",
")",
":",
"conditions",
"=",
"list",
"(",
")",
"visited",
"=",
"set",
"(",
")",
"# Has to be split out, since we don't want to visit the root (for cyclic conditions)",
"# but we don't want to yield it (if it's non-cyclic) because this only yields inner conditions",
"if",
"condition",
".",
"operation",
"in",
"{",
"\"and\"",
",",
"\"or\"",
"}",
":",
"conditions",
".",
"extend",
"(",
"reversed",
"(",
"condition",
".",
"values",
")",
")",
"elif",
"condition",
".",
"operation",
"==",
"\"not\"",
":",
"conditions",
".",
"append",
"(",
"condition",
".",
"values",
"[",
"0",
"]",
")",
"else",
":",
"conditions",
".",
"append",
"(",
"condition",
")",
"while",
"conditions",
":",
"condition",
"=",
"conditions",
".",
"pop",
"(",
")",
"if",
"condition",
"in",
"visited",
":",
"continue",
"visited",
".",
"add",
"(",
"condition",
")",
"yield",
"condition",
"if",
"condition",
".",
"operation",
"in",
"{",
"\"and\"",
",",
"\"or\"",
",",
"\"not\"",
"}",
":",
"conditions",
".",
"extend",
"(",
"reversed",
"(",
"condition",
".",
"values",
")",
")"
] | Yield all conditions within the given condition.
If the root condition is and/or/not, it is not yielded (unless a cyclic reference to it is found). | [
"Yield",
"all",
"conditions",
"within",
"the",
"given",
"condition",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L914-L935 | train |
numberoverzero/bloop | bloop/conditions.py | iter_columns | def iter_columns(condition):
"""
Yield all columns in the condition or its inner conditions.
Unwraps proxies when the condition's column (or any of its values) include paths.
"""
# Like iter_conditions, this can't live in each condition without going possibly infinite on the
# recursion, or passing the visited set through every call. That makes the signature ugly, so we
# take care of it here. Luckily, it's pretty easy to leverage iter_conditions and just unpack the
# actual columns.
visited = set()
for condition in iter_conditions(condition):
if condition.operation in ("and", "or", "not"):
continue
# Non-meta conditions always have a column, and each of values has the potential to be a column.
# Comparison will only have a list of len 1, but it's simpler to just iterate values and check each
# unwrap proxies created for paths
column = proxied(condition.column)
# special case for None
# this could also have skipped on isinstance(condition, Condition)
# but this is slightly more flexible for users to create their own None-sentinel Conditions
if column is None:
continue
if column not in visited:
visited.add(column)
yield column
for value in condition.values:
if isinstance(value, ComparisonMixin):
if value not in visited:
visited.add(value)
yield value | python | def iter_columns(condition):
"""
Yield all columns in the condition or its inner conditions.
Unwraps proxies when the condition's column (or any of its values) include paths.
"""
# Like iter_conditions, this can't live in each condition without going possibly infinite on the
# recursion, or passing the visited set through every call. That makes the signature ugly, so we
# take care of it here. Luckily, it's pretty easy to leverage iter_conditions and just unpack the
# actual columns.
visited = set()
for condition in iter_conditions(condition):
if condition.operation in ("and", "or", "not"):
continue
# Non-meta conditions always have a column, and each of values has the potential to be a column.
# Comparison will only have a list of len 1, but it's simpler to just iterate values and check each
# unwrap proxies created for paths
column = proxied(condition.column)
# special case for None
# this could also have skipped on isinstance(condition, Condition)
# but this is slightly more flexible for users to create their own None-sentinel Conditions
if column is None:
continue
if column not in visited:
visited.add(column)
yield column
for value in condition.values:
if isinstance(value, ComparisonMixin):
if value not in visited:
visited.add(value)
yield value | [
"def",
"iter_columns",
"(",
"condition",
")",
":",
"# Like iter_conditions, this can't live in each condition without going possibly infinite on the",
"# recursion, or passing the visited set through every call. That makes the signature ugly, so we",
"# take care of it here. Luckily, it's pretty easy to leverage iter_conditions and just unpack the",
"# actual columns.",
"visited",
"=",
"set",
"(",
")",
"for",
"condition",
"in",
"iter_conditions",
"(",
"condition",
")",
":",
"if",
"condition",
".",
"operation",
"in",
"(",
"\"and\"",
",",
"\"or\"",
",",
"\"not\"",
")",
":",
"continue",
"# Non-meta conditions always have a column, and each of values has the potential to be a column.",
"# Comparison will only have a list of len 1, but it's simpler to just iterate values and check each",
"# unwrap proxies created for paths",
"column",
"=",
"proxied",
"(",
"condition",
".",
"column",
")",
"# special case for None",
"# this could also have skipped on isinstance(condition, Condition)",
"# but this is slightly more flexible for users to create their own None-sentinel Conditions",
"if",
"column",
"is",
"None",
":",
"continue",
"if",
"column",
"not",
"in",
"visited",
":",
"visited",
".",
"add",
"(",
"column",
")",
"yield",
"column",
"for",
"value",
"in",
"condition",
".",
"values",
":",
"if",
"isinstance",
"(",
"value",
",",
"ComparisonMixin",
")",
":",
"if",
"value",
"not",
"in",
"visited",
":",
"visited",
".",
"add",
"(",
"value",
")",
"yield",
"value"
] | Yield all columns in the condition or its inner conditions.
Unwraps proxies when the condition's column (or any of its values) include paths. | [
"Yield",
"all",
"columns",
"in",
"the",
"condition",
"or",
"its",
"inner",
"conditions",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L938-L970 | train |
numberoverzero/bloop | bloop/conditions.py | ReferenceTracker._value_ref | def _value_ref(self, column, value, *, dumped=False, inner=False):
"""inner=True uses column.typedef.inner_type instead of column.typedef"""
ref = ":v{}".format(self.next_index)
# Need to dump this value
if not dumped:
typedef = column.typedef
for segment in path_of(column):
typedef = typedef[segment]
if inner:
typedef = typedef.inner_typedef
value = self.engine._dump(typedef, value)
self.attr_values[ref] = value
self.counts[ref] += 1
return ref, value | python | def _value_ref(self, column, value, *, dumped=False, inner=False):
"""inner=True uses column.typedef.inner_type instead of column.typedef"""
ref = ":v{}".format(self.next_index)
# Need to dump this value
if not dumped:
typedef = column.typedef
for segment in path_of(column):
typedef = typedef[segment]
if inner:
typedef = typedef.inner_typedef
value = self.engine._dump(typedef, value)
self.attr_values[ref] = value
self.counts[ref] += 1
return ref, value | [
"def",
"_value_ref",
"(",
"self",
",",
"column",
",",
"value",
",",
"*",
",",
"dumped",
"=",
"False",
",",
"inner",
"=",
"False",
")",
":",
"ref",
"=",
"\":v{}\"",
".",
"format",
"(",
"self",
".",
"next_index",
")",
"# Need to dump this value",
"if",
"not",
"dumped",
":",
"typedef",
"=",
"column",
".",
"typedef",
"for",
"segment",
"in",
"path_of",
"(",
"column",
")",
":",
"typedef",
"=",
"typedef",
"[",
"segment",
"]",
"if",
"inner",
":",
"typedef",
"=",
"typedef",
".",
"inner_typedef",
"value",
"=",
"self",
".",
"engine",
".",
"_dump",
"(",
"typedef",
",",
"value",
")",
"self",
".",
"attr_values",
"[",
"ref",
"]",
"=",
"value",
"self",
".",
"counts",
"[",
"ref",
"]",
"+=",
"1",
"return",
"ref",
",",
"value"
] | inner=True uses column.typedef.inner_type instead of column.typedef | [
"inner",
"=",
"True",
"uses",
"column",
".",
"typedef",
".",
"inner_type",
"instead",
"of",
"column",
".",
"typedef"
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L166-L181 | train |
numberoverzero/bloop | bloop/conditions.py | ReferenceTracker.any_ref | def any_ref(self, *, column, value=missing, dumped=False, inner=False):
"""Returns a NamedTuple of (name, type, value) for any type of reference.
.. code-block:: python
# Name ref
>>> tracker.any_ref(column=User.email)
Reference(name='email', type='name', value=None)
# Value ref
>>> tracker.any_ref(column=User.email, value='user@domain')
Reference(name='email', type='value', value={'S': 'user@domain'})
# Passed as value ref, but value is another column
>>> tracker.any_ref(column=User.email, value=User.other_column)
Reference(name='other_column', type='name', value=None)
:param column: The column to reference. If ``value`` is None, this will render a name ref for this column.
:type column: :class:`~bloop.conditions.ComparisonMixin`
:param value: *(Optional)* If provided, this is likely a value ref. If ``value`` is also a column,
this will render a name ref for that column (not the ``column`` parameter).
:param bool dumped: *(Optional)* True if the value has already been dumped and should not be dumped
through the column's typedef again. Commonly used with atomic conditions (which store the object's dumped
representation). Default is False.
:param bool inner: *(Optional)* True if this is a value ref and it should be dumped through a collection's
inner type, and not the collection type itself. Default is False.
:return: A name or value reference
:rtype: :class:`bloop.conditions.Reference`
"""
# Can't use None since it's a legal value for comparisons (attribute_not_exists)
if value is missing:
# Simple path ref to the column.
name = self._path_ref(column=column)
ref_type = "name"
value = None
elif isinstance(value, ComparisonMixin):
# value is also a column! Also a path ref.
name = self._path_ref(column=value)
ref_type = "name"
value = None
else:
# Simple value ref.
name, value = self._value_ref(column=column, value=value, dumped=dumped, inner=inner)
ref_type = "value"
return Reference(name=name, type=ref_type, value=value) | python | def any_ref(self, *, column, value=missing, dumped=False, inner=False):
"""Returns a NamedTuple of (name, type, value) for any type of reference.
.. code-block:: python
# Name ref
>>> tracker.any_ref(column=User.email)
Reference(name='email', type='name', value=None)
# Value ref
>>> tracker.any_ref(column=User.email, value='user@domain')
Reference(name='email', type='value', value={'S': 'user@domain'})
# Passed as value ref, but value is another column
>>> tracker.any_ref(column=User.email, value=User.other_column)
Reference(name='other_column', type='name', value=None)
:param column: The column to reference. If ``value`` is None, this will render a name ref for this column.
:type column: :class:`~bloop.conditions.ComparisonMixin`
:param value: *(Optional)* If provided, this is likely a value ref. If ``value`` is also a column,
this will render a name ref for that column (not the ``column`` parameter).
:param bool dumped: *(Optional)* True if the value has already been dumped and should not be dumped
through the column's typedef again. Commonly used with atomic conditions (which store the object's dumped
representation). Default is False.
:param bool inner: *(Optional)* True if this is a value ref and it should be dumped through a collection's
inner type, and not the collection type itself. Default is False.
:return: A name or value reference
:rtype: :class:`bloop.conditions.Reference`
"""
# Can't use None since it's a legal value for comparisons (attribute_not_exists)
if value is missing:
# Simple path ref to the column.
name = self._path_ref(column=column)
ref_type = "name"
value = None
elif isinstance(value, ComparisonMixin):
# value is also a column! Also a path ref.
name = self._path_ref(column=value)
ref_type = "name"
value = None
else:
# Simple value ref.
name, value = self._value_ref(column=column, value=value, dumped=dumped, inner=inner)
ref_type = "value"
return Reference(name=name, type=ref_type, value=value) | [
"def",
"any_ref",
"(",
"self",
",",
"*",
",",
"column",
",",
"value",
"=",
"missing",
",",
"dumped",
"=",
"False",
",",
"inner",
"=",
"False",
")",
":",
"# Can't use None since it's a legal value for comparisons (attribute_not_exists)",
"if",
"value",
"is",
"missing",
":",
"# Simple path ref to the column.",
"name",
"=",
"self",
".",
"_path_ref",
"(",
"column",
"=",
"column",
")",
"ref_type",
"=",
"\"name\"",
"value",
"=",
"None",
"elif",
"isinstance",
"(",
"value",
",",
"ComparisonMixin",
")",
":",
"# value is also a column! Also a path ref.",
"name",
"=",
"self",
".",
"_path_ref",
"(",
"column",
"=",
"value",
")",
"ref_type",
"=",
"\"name\"",
"value",
"=",
"None",
"else",
":",
"# Simple value ref.",
"name",
",",
"value",
"=",
"self",
".",
"_value_ref",
"(",
"column",
"=",
"column",
",",
"value",
"=",
"value",
",",
"dumped",
"=",
"dumped",
",",
"inner",
"=",
"inner",
")",
"ref_type",
"=",
"\"value\"",
"return",
"Reference",
"(",
"name",
"=",
"name",
",",
"type",
"=",
"ref_type",
",",
"value",
"=",
"value",
")"
] | Returns a NamedTuple of (name, type, value) for any type of reference.
.. code-block:: python
# Name ref
>>> tracker.any_ref(column=User.email)
Reference(name='email', type='name', value=None)
# Value ref
>>> tracker.any_ref(column=User.email, value='user@domain')
Reference(name='email', type='value', value={'S': 'user@domain'})
# Passed as value ref, but value is another column
>>> tracker.any_ref(column=User.email, value=User.other_column)
Reference(name='other_column', type='name', value=None)
:param column: The column to reference. If ``value`` is None, this will render a name ref for this column.
:type column: :class:`~bloop.conditions.ComparisonMixin`
:param value: *(Optional)* If provided, this is likely a value ref. If ``value`` is also a column,
this will render a name ref for that column (not the ``column`` parameter).
:param bool dumped: *(Optional)* True if the value has already been dumped and should not be dumped
through the column's typedef again. Commonly used with atomic conditions (which store the object's dumped
representation). Default is False.
:param bool inner: *(Optional)* True if this is a value ref and it should be dumped through a collection's
inner type, and not the collection type itself. Default is False.
:return: A name or value reference
:rtype: :class:`bloop.conditions.Reference` | [
"Returns",
"a",
"NamedTuple",
"of",
"(",
"name",
"type",
"value",
")",
"for",
"any",
"type",
"of",
"reference",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L183-L227 | train |
numberoverzero/bloop | bloop/conditions.py | ReferenceTracker.pop_refs | def pop_refs(self, *refs):
"""Decrement the usage of each ref by 1.
If this was the last use of a ref, remove it from attr_names or attr_values.
"""
for ref in refs:
name = ref.name
count = self.counts[name]
# Not tracking this ref
if count < 1:
continue
# Someone else is using this ref
elif count > 1:
self.counts[name] -= 1
# Last reference
else:
logger.debug("popping last usage of {}".format(ref))
self.counts[name] -= 1
if ref.type == "value":
del self.attr_values[name]
else:
# Clean up both name indexes
path_segment = self.attr_names[name]
del self.attr_names[name]
del self.name_attr_index[path_segment] | python | def pop_refs(self, *refs):
"""Decrement the usage of each ref by 1.
If this was the last use of a ref, remove it from attr_names or attr_values.
"""
for ref in refs:
name = ref.name
count = self.counts[name]
# Not tracking this ref
if count < 1:
continue
# Someone else is using this ref
elif count > 1:
self.counts[name] -= 1
# Last reference
else:
logger.debug("popping last usage of {}".format(ref))
self.counts[name] -= 1
if ref.type == "value":
del self.attr_values[name]
else:
# Clean up both name indexes
path_segment = self.attr_names[name]
del self.attr_names[name]
del self.name_attr_index[path_segment] | [
"def",
"pop_refs",
"(",
"self",
",",
"*",
"refs",
")",
":",
"for",
"ref",
"in",
"refs",
":",
"name",
"=",
"ref",
".",
"name",
"count",
"=",
"self",
".",
"counts",
"[",
"name",
"]",
"# Not tracking this ref",
"if",
"count",
"<",
"1",
":",
"continue",
"# Someone else is using this ref",
"elif",
"count",
">",
"1",
":",
"self",
".",
"counts",
"[",
"name",
"]",
"-=",
"1",
"# Last reference",
"else",
":",
"logger",
".",
"debug",
"(",
"\"popping last usage of {}\"",
".",
"format",
"(",
"ref",
")",
")",
"self",
".",
"counts",
"[",
"name",
"]",
"-=",
"1",
"if",
"ref",
".",
"type",
"==",
"\"value\"",
":",
"del",
"self",
".",
"attr_values",
"[",
"name",
"]",
"else",
":",
"# Clean up both name indexes",
"path_segment",
"=",
"self",
".",
"attr_names",
"[",
"name",
"]",
"del",
"self",
".",
"attr_names",
"[",
"name",
"]",
"del",
"self",
".",
"name_attr_index",
"[",
"path_segment",
"]"
] | Decrement the usage of each ref by 1.
If this was the last use of a ref, remove it from attr_names or attr_values. | [
"Decrement",
"the",
"usage",
"of",
"each",
"ref",
"by",
"1",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L229-L253 | train |
numberoverzero/bloop | bloop/conditions.py | ConditionRenderer.render | def render(self, obj=None, condition=None, atomic=False, update=False, filter=None, projection=None, key=None):
"""Main entry point for rendering multiple expressions. All parameters are optional, except obj when
atomic or update are True.
:param obj: *(Optional)* An object to render an atomic condition or update expression for. Required if
update or atomic are true. Default is False.
:param condition: *(Optional)* Rendered as a "ConditionExpression" for a conditional operation.
If atomic is True, the two are rendered in an AND condition. Default is None.
:type condition: :class:`~bloop.conditions.BaseCondition`
:param bool atomic: *(Optional)* True if an atomic condition should be created for ``obj`` and rendered as
a "ConditionExpression". Default is False.
:param bool update: *(Optional)* True if an "UpdateExpression" should be rendered for ``obj``.
Default is False.
:param filter: *(Optional)* A filter condition for a query or scan, rendered as a "FilterExpression".
Default is None.
:type filter: :class:`~bloop.conditions.BaseCondition`
:param projection: *(Optional)* A set of Columns to include in a query or scan, redered as a
"ProjectionExpression". Default is None.
:type projection: set :class:`~bloop.models.Column`
:param key: *(Optional)* A key condition for queries, rendered as a "KeyConditionExpression". Default is None.
:type key: :class:`~bloop.conditions.BaseCondition`
"""
if (atomic or update) and not obj:
raise InvalidCondition("An object is required to render atomic conditions or updates without an object.")
if filter:
self.render_filter_expression(filter)
if projection:
self.render_projection_expression(projection)
if key:
self.render_key_expression(key)
# Condition requires a bit of work, because either one can be empty/false
condition = (condition or Condition()) & (get_snapshot(obj) if atomic else Condition())
if condition:
self.render_condition_expression(condition)
if update:
self.render_update_expression(obj) | python | def render(self, obj=None, condition=None, atomic=False, update=False, filter=None, projection=None, key=None):
"""Main entry point for rendering multiple expressions. All parameters are optional, except obj when
atomic or update are True.
:param obj: *(Optional)* An object to render an atomic condition or update expression for. Required if
update or atomic are true. Default is False.
:param condition: *(Optional)* Rendered as a "ConditionExpression" for a conditional operation.
If atomic is True, the two are rendered in an AND condition. Default is None.
:type condition: :class:`~bloop.conditions.BaseCondition`
:param bool atomic: *(Optional)* True if an atomic condition should be created for ``obj`` and rendered as
a "ConditionExpression". Default is False.
:param bool update: *(Optional)* True if an "UpdateExpression" should be rendered for ``obj``.
Default is False.
:param filter: *(Optional)* A filter condition for a query or scan, rendered as a "FilterExpression".
Default is None.
:type filter: :class:`~bloop.conditions.BaseCondition`
:param projection: *(Optional)* A set of Columns to include in a query or scan, redered as a
"ProjectionExpression". Default is None.
:type projection: set :class:`~bloop.models.Column`
:param key: *(Optional)* A key condition for queries, rendered as a "KeyConditionExpression". Default is None.
:type key: :class:`~bloop.conditions.BaseCondition`
"""
if (atomic or update) and not obj:
raise InvalidCondition("An object is required to render atomic conditions or updates without an object.")
if filter:
self.render_filter_expression(filter)
if projection:
self.render_projection_expression(projection)
if key:
self.render_key_expression(key)
# Condition requires a bit of work, because either one can be empty/false
condition = (condition or Condition()) & (get_snapshot(obj) if atomic else Condition())
if condition:
self.render_condition_expression(condition)
if update:
self.render_update_expression(obj) | [
"def",
"render",
"(",
"self",
",",
"obj",
"=",
"None",
",",
"condition",
"=",
"None",
",",
"atomic",
"=",
"False",
",",
"update",
"=",
"False",
",",
"filter",
"=",
"None",
",",
"projection",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"if",
"(",
"atomic",
"or",
"update",
")",
"and",
"not",
"obj",
":",
"raise",
"InvalidCondition",
"(",
"\"An object is required to render atomic conditions or updates without an object.\"",
")",
"if",
"filter",
":",
"self",
".",
"render_filter_expression",
"(",
"filter",
")",
"if",
"projection",
":",
"self",
".",
"render_projection_expression",
"(",
"projection",
")",
"if",
"key",
":",
"self",
".",
"render_key_expression",
"(",
"key",
")",
"# Condition requires a bit of work, because either one can be empty/false",
"condition",
"=",
"(",
"condition",
"or",
"Condition",
"(",
")",
")",
"&",
"(",
"get_snapshot",
"(",
"obj",
")",
"if",
"atomic",
"else",
"Condition",
"(",
")",
")",
"if",
"condition",
":",
"self",
".",
"render_condition_expression",
"(",
"condition",
")",
"if",
"update",
":",
"self",
".",
"render_update_expression",
"(",
"obj",
")"
] | Main entry point for rendering multiple expressions. All parameters are optional, except obj when
atomic or update are True.
:param obj: *(Optional)* An object to render an atomic condition or update expression for. Required if
update or atomic are true. Default is False.
:param condition: *(Optional)* Rendered as a "ConditionExpression" for a conditional operation.
If atomic is True, the two are rendered in an AND condition. Default is None.
:type condition: :class:`~bloop.conditions.BaseCondition`
:param bool atomic: *(Optional)* True if an atomic condition should be created for ``obj`` and rendered as
a "ConditionExpression". Default is False.
:param bool update: *(Optional)* True if an "UpdateExpression" should be rendered for ``obj``.
Default is False.
:param filter: *(Optional)* A filter condition for a query or scan, rendered as a "FilterExpression".
Default is None.
:type filter: :class:`~bloop.conditions.BaseCondition`
:param projection: *(Optional)* A set of Columns to include in a query or scan, redered as a
"ProjectionExpression". Default is None.
:type projection: set :class:`~bloop.models.Column`
:param key: *(Optional)* A key condition for queries, rendered as a "KeyConditionExpression". Default is None.
:type key: :class:`~bloop.conditions.BaseCondition` | [
"Main",
"entry",
"point",
"for",
"rendering",
"multiple",
"expressions",
".",
"All",
"parameters",
"are",
"optional",
"except",
"obj",
"when",
"atomic",
"or",
"update",
"are",
"True",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L299-L339 | train |
numberoverzero/bloop | bloop/conditions.py | ConditionRenderer.rendered | def rendered(self):
"""The rendered wire format for all conditions that have been rendered. Rendered conditions are never
cleared. A new :class:`~bloop.conditions.ConditionRenderer` should be used for each operation."""
expressions = {k: v for (k, v) in self.expressions.items() if v is not None}
if self.refs.attr_names:
expressions["ExpressionAttributeNames"] = self.refs.attr_names
if self.refs.attr_values:
expressions["ExpressionAttributeValues"] = self.refs.attr_values
return expressions | python | def rendered(self):
"""The rendered wire format for all conditions that have been rendered. Rendered conditions are never
cleared. A new :class:`~bloop.conditions.ConditionRenderer` should be used for each operation."""
expressions = {k: v for (k, v) in self.expressions.items() if v is not None}
if self.refs.attr_names:
expressions["ExpressionAttributeNames"] = self.refs.attr_names
if self.refs.attr_values:
expressions["ExpressionAttributeValues"] = self.refs.attr_values
return expressions | [
"def",
"rendered",
"(",
"self",
")",
":",
"expressions",
"=",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"self",
".",
"expressions",
".",
"items",
"(",
")",
"if",
"v",
"is",
"not",
"None",
"}",
"if",
"self",
".",
"refs",
".",
"attr_names",
":",
"expressions",
"[",
"\"ExpressionAttributeNames\"",
"]",
"=",
"self",
".",
"refs",
".",
"attr_names",
"if",
"self",
".",
"refs",
".",
"attr_values",
":",
"expressions",
"[",
"\"ExpressionAttributeValues\"",
"]",
"=",
"self",
".",
"refs",
".",
"attr_values",
"return",
"expressions"
] | The rendered wire format for all conditions that have been rendered. Rendered conditions are never
cleared. A new :class:`~bloop.conditions.ConditionRenderer` should be used for each operation. | [
"The",
"rendered",
"wire",
"format",
"for",
"all",
"conditions",
"that",
"have",
"been",
"rendered",
".",
"Rendered",
"conditions",
"are",
"never",
"cleared",
".",
"A",
"new",
":",
"class",
":",
"~bloop",
".",
"conditions",
".",
"ConditionRenderer",
"should",
"be",
"used",
"for",
"each",
"operation",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L388-L396 | train |
numberoverzero/bloop | bloop/stream/stream.py | Stream._unpack | def _unpack(self, record, key, expected):
"""Replaces the attr dict at the given key with an instance of a Model"""
attrs = record.get(key)
if attrs is None:
return
obj = unpack_from_dynamodb(
attrs=attrs,
expected=expected,
model=self.model,
engine=self.engine
)
object_loaded.send(self.engine, engine=self.engine, obj=obj)
record[key] = obj | python | def _unpack(self, record, key, expected):
"""Replaces the attr dict at the given key with an instance of a Model"""
attrs = record.get(key)
if attrs is None:
return
obj = unpack_from_dynamodb(
attrs=attrs,
expected=expected,
model=self.model,
engine=self.engine
)
object_loaded.send(self.engine, engine=self.engine, obj=obj)
record[key] = obj | [
"def",
"_unpack",
"(",
"self",
",",
"record",
",",
"key",
",",
"expected",
")",
":",
"attrs",
"=",
"record",
".",
"get",
"(",
"key",
")",
"if",
"attrs",
"is",
"None",
":",
"return",
"obj",
"=",
"unpack_from_dynamodb",
"(",
"attrs",
"=",
"attrs",
",",
"expected",
"=",
"expected",
",",
"model",
"=",
"self",
".",
"model",
",",
"engine",
"=",
"self",
".",
"engine",
")",
"object_loaded",
".",
"send",
"(",
"self",
".",
"engine",
",",
"engine",
"=",
"self",
".",
"engine",
",",
"obj",
"=",
"obj",
")",
"record",
"[",
"key",
"]",
"=",
"obj"
] | Replaces the attr dict at the given key with an instance of a Model | [
"Replaces",
"the",
"attr",
"dict",
"at",
"the",
"given",
"key",
"with",
"an",
"instance",
"of",
"a",
"Model"
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/stream.py#L79-L91 | train |
numberoverzero/bloop | bloop/stream/shard.py | reformat_record | def reformat_record(record):
"""Repack a record into a cleaner structure for consumption."""
return {
"key": record["dynamodb"].get("Keys", None),
"new": record["dynamodb"].get("NewImage", None),
"old": record["dynamodb"].get("OldImage", None),
"meta": {
"created_at": record["dynamodb"]["ApproximateCreationDateTime"],
"event": {
"id": record["eventID"],
"type": record["eventName"].lower(),
"version": record["eventVersion"]
},
"sequence_number": record["dynamodb"]["SequenceNumber"],
}
} | python | def reformat_record(record):
"""Repack a record into a cleaner structure for consumption."""
return {
"key": record["dynamodb"].get("Keys", None),
"new": record["dynamodb"].get("NewImage", None),
"old": record["dynamodb"].get("OldImage", None),
"meta": {
"created_at": record["dynamodb"]["ApproximateCreationDateTime"],
"event": {
"id": record["eventID"],
"type": record["eventName"].lower(),
"version": record["eventVersion"]
},
"sequence_number": record["dynamodb"]["SequenceNumber"],
}
} | [
"def",
"reformat_record",
"(",
"record",
")",
":",
"return",
"{",
"\"key\"",
":",
"record",
"[",
"\"dynamodb\"",
"]",
".",
"get",
"(",
"\"Keys\"",
",",
"None",
")",
",",
"\"new\"",
":",
"record",
"[",
"\"dynamodb\"",
"]",
".",
"get",
"(",
"\"NewImage\"",
",",
"None",
")",
",",
"\"old\"",
":",
"record",
"[",
"\"dynamodb\"",
"]",
".",
"get",
"(",
"\"OldImage\"",
",",
"None",
")",
",",
"\"meta\"",
":",
"{",
"\"created_at\"",
":",
"record",
"[",
"\"dynamodb\"",
"]",
"[",
"\"ApproximateCreationDateTime\"",
"]",
",",
"\"event\"",
":",
"{",
"\"id\"",
":",
"record",
"[",
"\"eventID\"",
"]",
",",
"\"type\"",
":",
"record",
"[",
"\"eventName\"",
"]",
".",
"lower",
"(",
")",
",",
"\"version\"",
":",
"record",
"[",
"\"eventVersion\"",
"]",
"}",
",",
"\"sequence_number\"",
":",
"record",
"[",
"\"dynamodb\"",
"]",
"[",
"\"SequenceNumber\"",
"]",
",",
"}",
"}"
] | Repack a record into a cleaner structure for consumption. | [
"Repack",
"a",
"record",
"into",
"a",
"cleaner",
"structure",
"for",
"consumption",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L287-L303 | train |
numberoverzero/bloop | bloop/stream/shard.py | unpack_shards | def unpack_shards(shards, stream_arn, session):
"""List[Dict] -> Dict[shard_id, Shard].
Each Shards' parent/children are hooked up with the other Shards in the list.
"""
if not shards:
return {}
# When unpacking tokens, shard id key is "shard_id"
# When unpacking DescribeStream responses, shard id key is "ShardId"
if "ShardId" in shards[0]:
shards = _translate_shards(shards)
by_id = {shard_token["shard_id"]:
Shard(stream_arn=stream_arn, shard_id=shard_token["shard_id"],
iterator_type=shard_token.get("iterator_type"), sequence_number=shard_token.get("sequence_number"),
parent=shard_token.get("parent"), session=session)
for shard_token in shards}
for shard in by_id.values():
if shard.parent:
shard.parent = by_id[shard.parent]
shard.parent.children.append(shard)
return by_id | python | def unpack_shards(shards, stream_arn, session):
"""List[Dict] -> Dict[shard_id, Shard].
Each Shards' parent/children are hooked up with the other Shards in the list.
"""
if not shards:
return {}
# When unpacking tokens, shard id key is "shard_id"
# When unpacking DescribeStream responses, shard id key is "ShardId"
if "ShardId" in shards[0]:
shards = _translate_shards(shards)
by_id = {shard_token["shard_id"]:
Shard(stream_arn=stream_arn, shard_id=shard_token["shard_id"],
iterator_type=shard_token.get("iterator_type"), sequence_number=shard_token.get("sequence_number"),
parent=shard_token.get("parent"), session=session)
for shard_token in shards}
for shard in by_id.values():
if shard.parent:
shard.parent = by_id[shard.parent]
shard.parent.children.append(shard)
return by_id | [
"def",
"unpack_shards",
"(",
"shards",
",",
"stream_arn",
",",
"session",
")",
":",
"if",
"not",
"shards",
":",
"return",
"{",
"}",
"# When unpacking tokens, shard id key is \"shard_id\"",
"# When unpacking DescribeStream responses, shard id key is \"ShardId\"",
"if",
"\"ShardId\"",
"in",
"shards",
"[",
"0",
"]",
":",
"shards",
"=",
"_translate_shards",
"(",
"shards",
")",
"by_id",
"=",
"{",
"shard_token",
"[",
"\"shard_id\"",
"]",
":",
"Shard",
"(",
"stream_arn",
"=",
"stream_arn",
",",
"shard_id",
"=",
"shard_token",
"[",
"\"shard_id\"",
"]",
",",
"iterator_type",
"=",
"shard_token",
".",
"get",
"(",
"\"iterator_type\"",
")",
",",
"sequence_number",
"=",
"shard_token",
".",
"get",
"(",
"\"sequence_number\"",
")",
",",
"parent",
"=",
"shard_token",
".",
"get",
"(",
"\"parent\"",
")",
",",
"session",
"=",
"session",
")",
"for",
"shard_token",
"in",
"shards",
"}",
"for",
"shard",
"in",
"by_id",
".",
"values",
"(",
")",
":",
"if",
"shard",
".",
"parent",
":",
"shard",
".",
"parent",
"=",
"by_id",
"[",
"shard",
".",
"parent",
"]",
"shard",
".",
"parent",
".",
"children",
".",
"append",
"(",
"shard",
")",
"return",
"by_id"
] | List[Dict] -> Dict[shard_id, Shard].
Each Shards' parent/children are hooked up with the other Shards in the list. | [
"List",
"[",
"Dict",
"]",
"-",
">",
"Dict",
"[",
"shard_id",
"Shard",
"]",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L306-L329 | train |
numberoverzero/bloop | bloop/stream/shard.py | Shard.token | def token(self):
"""JSON-serializable representation of the current Shard state.
The token is enough to rebuild the Shard as part of rebuilding a Stream.
:returns: Shard state as a json-friendly dict
:rtype: dict
"""
if self.iterator_type in RELATIVE_ITERATORS:
logger.warning("creating shard token at non-exact location \"{}\"".format(self.iterator_type))
token = {
"stream_arn": self.stream_arn,
"shard_id": self.shard_id,
"iterator_type": self.iterator_type,
"sequence_number": self.sequence_number,
}
if self.parent:
token["parent"] = self.parent.shard_id
if not self.iterator_type:
del token["iterator_type"]
if not self.sequence_number:
del token["sequence_number"]
return token | python | def token(self):
"""JSON-serializable representation of the current Shard state.
The token is enough to rebuild the Shard as part of rebuilding a Stream.
:returns: Shard state as a json-friendly dict
:rtype: dict
"""
if self.iterator_type in RELATIVE_ITERATORS:
logger.warning("creating shard token at non-exact location \"{}\"".format(self.iterator_type))
token = {
"stream_arn": self.stream_arn,
"shard_id": self.shard_id,
"iterator_type": self.iterator_type,
"sequence_number": self.sequence_number,
}
if self.parent:
token["parent"] = self.parent.shard_id
if not self.iterator_type:
del token["iterator_type"]
if not self.sequence_number:
del token["sequence_number"]
return token | [
"def",
"token",
"(",
"self",
")",
":",
"if",
"self",
".",
"iterator_type",
"in",
"RELATIVE_ITERATORS",
":",
"logger",
".",
"warning",
"(",
"\"creating shard token at non-exact location \\\"{}\\\"\"",
".",
"format",
"(",
"self",
".",
"iterator_type",
")",
")",
"token",
"=",
"{",
"\"stream_arn\"",
":",
"self",
".",
"stream_arn",
",",
"\"shard_id\"",
":",
"self",
".",
"shard_id",
",",
"\"iterator_type\"",
":",
"self",
".",
"iterator_type",
",",
"\"sequence_number\"",
":",
"self",
".",
"sequence_number",
",",
"}",
"if",
"self",
".",
"parent",
":",
"token",
"[",
"\"parent\"",
"]",
"=",
"self",
".",
"parent",
".",
"shard_id",
"if",
"not",
"self",
".",
"iterator_type",
":",
"del",
"token",
"[",
"\"iterator_type\"",
"]",
"if",
"not",
"self",
".",
"sequence_number",
":",
"del",
"token",
"[",
"\"sequence_number\"",
"]",
"return",
"token"
] | JSON-serializable representation of the current Shard state.
The token is enough to rebuild the Shard as part of rebuilding a Stream.
:returns: Shard state as a json-friendly dict
:rtype: dict | [
"JSON",
"-",
"serializable",
"representation",
"of",
"the",
"current",
"Shard",
"state",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L127-L149 | train |
numberoverzero/bloop | bloop/stream/shard.py | Shard.walk_tree | def walk_tree(self):
"""Generator that yields each :class:`~bloop.stream.shard.Shard` by walking the shard's children in order."""
shards = collections.deque([self])
while shards:
shard = shards.popleft()
yield shard
shards.extend(shard.children) | python | def walk_tree(self):
"""Generator that yields each :class:`~bloop.stream.shard.Shard` by walking the shard's children in order."""
shards = collections.deque([self])
while shards:
shard = shards.popleft()
yield shard
shards.extend(shard.children) | [
"def",
"walk_tree",
"(",
"self",
")",
":",
"shards",
"=",
"collections",
".",
"deque",
"(",
"[",
"self",
"]",
")",
"while",
"shards",
":",
"shard",
"=",
"shards",
".",
"popleft",
"(",
")",
"yield",
"shard",
"shards",
".",
"extend",
"(",
"shard",
".",
"children",
")"
] | Generator that yields each :class:`~bloop.stream.shard.Shard` by walking the shard's children in order. | [
"Generator",
"that",
"yields",
"each",
":",
"class",
":",
"~bloop",
".",
"stream",
".",
"shard",
".",
"Shard",
"by",
"walking",
"the",
"shard",
"s",
"children",
"in",
"order",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L151-L157 | train |
numberoverzero/bloop | bloop/stream/shard.py | Shard.jump_to | def jump_to(self, *, iterator_type, sequence_number=None):
"""Move to a new position in the shard using the standard parameters to GetShardIterator.
:param str iterator_type: "trim_horizon", "at_sequence", "after_sequence", "latest"
:param str sequence_number: *(Optional)* Sequence number to use with at/after sequence. Default is None.
"""
# Just a simple wrapper; let the caller handle RecordsExpired
self.iterator_id = self.session.get_shard_iterator(
stream_arn=self.stream_arn,
shard_id=self.shard_id,
iterator_type=iterator_type,
sequence_number=sequence_number)
self.iterator_type = iterator_type
self.sequence_number = sequence_number
self.empty_responses = 0 | python | def jump_to(self, *, iterator_type, sequence_number=None):
"""Move to a new position in the shard using the standard parameters to GetShardIterator.
:param str iterator_type: "trim_horizon", "at_sequence", "after_sequence", "latest"
:param str sequence_number: *(Optional)* Sequence number to use with at/after sequence. Default is None.
"""
# Just a simple wrapper; let the caller handle RecordsExpired
self.iterator_id = self.session.get_shard_iterator(
stream_arn=self.stream_arn,
shard_id=self.shard_id,
iterator_type=iterator_type,
sequence_number=sequence_number)
self.iterator_type = iterator_type
self.sequence_number = sequence_number
self.empty_responses = 0 | [
"def",
"jump_to",
"(",
"self",
",",
"*",
",",
"iterator_type",
",",
"sequence_number",
"=",
"None",
")",
":",
"# Just a simple wrapper; let the caller handle RecordsExpired",
"self",
".",
"iterator_id",
"=",
"self",
".",
"session",
".",
"get_shard_iterator",
"(",
"stream_arn",
"=",
"self",
".",
"stream_arn",
",",
"shard_id",
"=",
"self",
".",
"shard_id",
",",
"iterator_type",
"=",
"iterator_type",
",",
"sequence_number",
"=",
"sequence_number",
")",
"self",
".",
"iterator_type",
"=",
"iterator_type",
"self",
".",
"sequence_number",
"=",
"sequence_number",
"self",
".",
"empty_responses",
"=",
"0"
] | Move to a new position in the shard using the standard parameters to GetShardIterator.
:param str iterator_type: "trim_horizon", "at_sequence", "after_sequence", "latest"
:param str sequence_number: *(Optional)* Sequence number to use with at/after sequence. Default is None. | [
"Move",
"to",
"a",
"new",
"position",
"in",
"the",
"shard",
"using",
"the",
"standard",
"parameters",
"to",
"GetShardIterator",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L159-L173 | train |
numberoverzero/bloop | bloop/stream/shard.py | Shard.seek_to | def seek_to(self, position):
"""Move the Shard's iterator to the earliest record after the :class:`~datetime.datetime` time.
Returns the first records at or past ``position``. If the list is empty,
the seek failed to find records, either because the Shard is exhausted or it
reached the HEAD of an open Shard.
:param position: The position in time to move to.
:type position: :class:`~datetime.datetime`
:returns: A list of the first records found after ``position``. May be empty.
"""
# 0) We have no way to associate the date with a position,
# so we have to scan the shard from the beginning.
self.jump_to(iterator_type="trim_horizon")
position = int(position.timestamp())
while (not self.exhausted) and (self.empty_responses < CALLS_TO_REACH_HEAD):
records = self.get_records()
# We can skip the whole record set if the newest (last) record isn't new enough.
if records and records[-1]["meta"]["created_at"].timestamp() >= position:
# Looking for the first number *below* the position.
for offset, record in enumerate(reversed(records)):
if record["meta"]["created_at"].timestamp() < position:
index = len(records) - offset
return records[index:]
return records
# Either exhausted the Shard or caught up to HEAD.
return [] | python | def seek_to(self, position):
"""Move the Shard's iterator to the earliest record after the :class:`~datetime.datetime` time.
Returns the first records at or past ``position``. If the list is empty,
the seek failed to find records, either because the Shard is exhausted or it
reached the HEAD of an open Shard.
:param position: The position in time to move to.
:type position: :class:`~datetime.datetime`
:returns: A list of the first records found after ``position``. May be empty.
"""
# 0) We have no way to associate the date with a position,
# so we have to scan the shard from the beginning.
self.jump_to(iterator_type="trim_horizon")
position = int(position.timestamp())
while (not self.exhausted) and (self.empty_responses < CALLS_TO_REACH_HEAD):
records = self.get_records()
# We can skip the whole record set if the newest (last) record isn't new enough.
if records and records[-1]["meta"]["created_at"].timestamp() >= position:
# Looking for the first number *below* the position.
for offset, record in enumerate(reversed(records)):
if record["meta"]["created_at"].timestamp() < position:
index = len(records) - offset
return records[index:]
return records
# Either exhausted the Shard or caught up to HEAD.
return [] | [
"def",
"seek_to",
"(",
"self",
",",
"position",
")",
":",
"# 0) We have no way to associate the date with a position,",
"# so we have to scan the shard from the beginning.",
"self",
".",
"jump_to",
"(",
"iterator_type",
"=",
"\"trim_horizon\"",
")",
"position",
"=",
"int",
"(",
"position",
".",
"timestamp",
"(",
")",
")",
"while",
"(",
"not",
"self",
".",
"exhausted",
")",
"and",
"(",
"self",
".",
"empty_responses",
"<",
"CALLS_TO_REACH_HEAD",
")",
":",
"records",
"=",
"self",
".",
"get_records",
"(",
")",
"# We can skip the whole record set if the newest (last) record isn't new enough.",
"if",
"records",
"and",
"records",
"[",
"-",
"1",
"]",
"[",
"\"meta\"",
"]",
"[",
"\"created_at\"",
"]",
".",
"timestamp",
"(",
")",
">=",
"position",
":",
"# Looking for the first number *below* the position.",
"for",
"offset",
",",
"record",
"in",
"enumerate",
"(",
"reversed",
"(",
"records",
")",
")",
":",
"if",
"record",
"[",
"\"meta\"",
"]",
"[",
"\"created_at\"",
"]",
".",
"timestamp",
"(",
")",
"<",
"position",
":",
"index",
"=",
"len",
"(",
"records",
")",
"-",
"offset",
"return",
"records",
"[",
"index",
":",
"]",
"return",
"records",
"# Either exhausted the Shard or caught up to HEAD.",
"return",
"[",
"]"
] | Move the Shard's iterator to the earliest record after the :class:`~datetime.datetime` time.
Returns the first records at or past ``position``. If the list is empty,
the seek failed to find records, either because the Shard is exhausted or it
reached the HEAD of an open Shard.
:param position: The position in time to move to.
:type position: :class:`~datetime.datetime`
:returns: A list of the first records found after ``position``. May be empty. | [
"Move",
"the",
"Shard",
"s",
"iterator",
"to",
"the",
"earliest",
"record",
"after",
"the",
":",
"class",
":",
"~datetime",
".",
"datetime",
"time",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L175-L204 | train |
numberoverzero/bloop | bloop/stream/shard.py | Shard.load_children | def load_children(self):
"""If the Shard doesn't have any children, tries to find some from DescribeStream.
If the Shard is open this won't find any children, so an empty response doesn't
mean the Shard will **never** have children.
"""
# Child count is fixed the first time any of the following happen:
# 0 :: stream closed or throughput decreased
# 1 :: shard was open for ~4 hours
# 2 :: throughput increased
if self.children:
return self.children
# ParentShardId -> [Shard, ...]
by_parent = collections.defaultdict(list)
# ShardId -> Shard
by_id = {}
for shard in self.session.describe_stream(
stream_arn=self.stream_arn,
first_shard=self.shard_id)["Shards"]:
parent_list = by_parent[shard.get("ParentShardId")]
shard = Shard(
stream_arn=self.stream_arn,
shard_id=shard["ShardId"],
parent=shard.get("ParentShardId"),
session=self.session)
parent_list.append(shard)
by_id[shard.shard_id] = shard
# Find this shard when looking up shards by ParentShardId
by_id[self.shard_id] = self
# Insert this shard's children, then handle its child's descendants etc.
to_insert = collections.deque(by_parent[self.shard_id])
while to_insert:
shard = to_insert.popleft()
# ParentShardId -> Shard
shard.parent = by_id[shard.parent]
shard.parent.children.append(shard)
# Continue for any shards that have this shard as their parent
to_insert.extend(by_parent[shard.shard_id])
return self.children | python | def load_children(self):
"""If the Shard doesn't have any children, tries to find some from DescribeStream.
If the Shard is open this won't find any children, so an empty response doesn't
mean the Shard will **never** have children.
"""
# Child count is fixed the first time any of the following happen:
# 0 :: stream closed or throughput decreased
# 1 :: shard was open for ~4 hours
# 2 :: throughput increased
if self.children:
return self.children
# ParentShardId -> [Shard, ...]
by_parent = collections.defaultdict(list)
# ShardId -> Shard
by_id = {}
for shard in self.session.describe_stream(
stream_arn=self.stream_arn,
first_shard=self.shard_id)["Shards"]:
parent_list = by_parent[shard.get("ParentShardId")]
shard = Shard(
stream_arn=self.stream_arn,
shard_id=shard["ShardId"],
parent=shard.get("ParentShardId"),
session=self.session)
parent_list.append(shard)
by_id[shard.shard_id] = shard
# Find this shard when looking up shards by ParentShardId
by_id[self.shard_id] = self
# Insert this shard's children, then handle its child's descendants etc.
to_insert = collections.deque(by_parent[self.shard_id])
while to_insert:
shard = to_insert.popleft()
# ParentShardId -> Shard
shard.parent = by_id[shard.parent]
shard.parent.children.append(shard)
# Continue for any shards that have this shard as their parent
to_insert.extend(by_parent[shard.shard_id])
return self.children | [
"def",
"load_children",
"(",
"self",
")",
":",
"# Child count is fixed the first time any of the following happen:",
"# 0 :: stream closed or throughput decreased",
"# 1 :: shard was open for ~4 hours",
"# 2 :: throughput increased",
"if",
"self",
".",
"children",
":",
"return",
"self",
".",
"children",
"# ParentShardId -> [Shard, ...]",
"by_parent",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"# ShardId -> Shard",
"by_id",
"=",
"{",
"}",
"for",
"shard",
"in",
"self",
".",
"session",
".",
"describe_stream",
"(",
"stream_arn",
"=",
"self",
".",
"stream_arn",
",",
"first_shard",
"=",
"self",
".",
"shard_id",
")",
"[",
"\"Shards\"",
"]",
":",
"parent_list",
"=",
"by_parent",
"[",
"shard",
".",
"get",
"(",
"\"ParentShardId\"",
")",
"]",
"shard",
"=",
"Shard",
"(",
"stream_arn",
"=",
"self",
".",
"stream_arn",
",",
"shard_id",
"=",
"shard",
"[",
"\"ShardId\"",
"]",
",",
"parent",
"=",
"shard",
".",
"get",
"(",
"\"ParentShardId\"",
")",
",",
"session",
"=",
"self",
".",
"session",
")",
"parent_list",
".",
"append",
"(",
"shard",
")",
"by_id",
"[",
"shard",
".",
"shard_id",
"]",
"=",
"shard",
"# Find this shard when looking up shards by ParentShardId",
"by_id",
"[",
"self",
".",
"shard_id",
"]",
"=",
"self",
"# Insert this shard's children, then handle its child's descendants etc.",
"to_insert",
"=",
"collections",
".",
"deque",
"(",
"by_parent",
"[",
"self",
".",
"shard_id",
"]",
")",
"while",
"to_insert",
":",
"shard",
"=",
"to_insert",
".",
"popleft",
"(",
")",
"# ParentShardId -> Shard",
"shard",
".",
"parent",
"=",
"by_id",
"[",
"shard",
".",
"parent",
"]",
"shard",
".",
"parent",
".",
"children",
".",
"append",
"(",
"shard",
")",
"# Continue for any shards that have this shard as their parent",
"to_insert",
".",
"extend",
"(",
"by_parent",
"[",
"shard",
".",
"shard_id",
"]",
")",
"return",
"self",
".",
"children"
] | If the Shard doesn't have any children, tries to find some from DescribeStream.
If the Shard is open this won't find any children, so an empty response doesn't
mean the Shard will **never** have children. | [
"If",
"the",
"Shard",
"doesn",
"t",
"have",
"any",
"children",
"tries",
"to",
"find",
"some",
"from",
"DescribeStream",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L206-L250 | train |
numberoverzero/bloop | bloop/stream/shard.py | Shard.get_records | def get_records(self):
"""Get the next set of records in this shard. An empty list doesn't guarantee the shard is exhausted.
:returns: A list of reformatted records. May be empty.
"""
# Won't be able to find new records.
if self.exhausted:
return []
# Already caught up, just the one call please.
if self.empty_responses >= CALLS_TO_REACH_HEAD:
return self._apply_get_records_response(self.session.get_stream_records(self.iterator_id))
# Up to 5 calls to try and find a result
while self.empty_responses < CALLS_TO_REACH_HEAD and not self.exhausted:
records = self._apply_get_records_response(self.session.get_stream_records(self.iterator_id))
if records:
return records
return [] | python | def get_records(self):
"""Get the next set of records in this shard. An empty list doesn't guarantee the shard is exhausted.
:returns: A list of reformatted records. May be empty.
"""
# Won't be able to find new records.
if self.exhausted:
return []
# Already caught up, just the one call please.
if self.empty_responses >= CALLS_TO_REACH_HEAD:
return self._apply_get_records_response(self.session.get_stream_records(self.iterator_id))
# Up to 5 calls to try and find a result
while self.empty_responses < CALLS_TO_REACH_HEAD and not self.exhausted:
records = self._apply_get_records_response(self.session.get_stream_records(self.iterator_id))
if records:
return records
return [] | [
"def",
"get_records",
"(",
"self",
")",
":",
"# Won't be able to find new records.",
"if",
"self",
".",
"exhausted",
":",
"return",
"[",
"]",
"# Already caught up, just the one call please.",
"if",
"self",
".",
"empty_responses",
">=",
"CALLS_TO_REACH_HEAD",
":",
"return",
"self",
".",
"_apply_get_records_response",
"(",
"self",
".",
"session",
".",
"get_stream_records",
"(",
"self",
".",
"iterator_id",
")",
")",
"# Up to 5 calls to try and find a result",
"while",
"self",
".",
"empty_responses",
"<",
"CALLS_TO_REACH_HEAD",
"and",
"not",
"self",
".",
"exhausted",
":",
"records",
"=",
"self",
".",
"_apply_get_records_response",
"(",
"self",
".",
"session",
".",
"get_stream_records",
"(",
"self",
".",
"iterator_id",
")",
")",
"if",
"records",
":",
"return",
"records",
"return",
"[",
"]"
] | Get the next set of records in this shard. An empty list doesn't guarantee the shard is exhausted.
:returns: A list of reformatted records. May be empty. | [
"Get",
"the",
"next",
"set",
"of",
"records",
"in",
"this",
"shard",
".",
"An",
"empty",
"list",
"doesn",
"t",
"guarantee",
"the",
"shard",
"is",
"exhausted",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L252-L271 | train |
numberoverzero/bloop | bloop/engine.py | Engine.bind | def bind(self, model, *, skip_table_setup=False):
"""Create backing tables for a model and its non-abstract subclasses.
:param model: Base model to bind. Can be abstract.
:param skip_table_setup: Don't create or verify the table in DynamoDB. Default is False.
:raises bloop.exceptions.InvalidModel: if ``model`` is not a subclass of :class:`~bloop.models.BaseModel`.
"""
# Make sure we're looking at models
validate_is_model(model)
concrete = set(filter(lambda m: not m.Meta.abstract, walk_subclasses(model)))
if not model.Meta.abstract:
concrete.add(model)
logger.debug("binding non-abstract models {}".format(
sorted(c.__name__ for c in concrete)
))
# create_table doesn't block until ACTIVE or validate.
# It also doesn't throw when the table already exists, making it safe
# to call multiple times for the same unbound model.
if skip_table_setup:
logger.info("skip_table_setup is True; not trying to create tables or validate models during bind")
else:
self.session.clear_cache()
is_creating = {}
for model in concrete:
table_name = self._compute_table_name(model)
before_create_table.send(self, engine=self, model=model)
if not skip_table_setup:
if table_name in is_creating:
continue
creating = self.session.create_table(table_name, model)
is_creating[table_name] = creating
for model in concrete:
if not skip_table_setup:
table_name = self._compute_table_name(model)
if is_creating[table_name]:
# polls until table is active
self.session.describe_table(table_name)
if model.Meta.ttl:
self.session.enable_ttl(table_name, model)
if model.Meta.backups and model.Meta.backups["enabled"]:
self.session.enable_backups(table_name, model)
self.session.validate_table(table_name, model)
model_validated.send(self, engine=self, model=model)
model_bound.send(self, engine=self, model=model)
logger.info("successfully bound {} models to the engine".format(len(concrete))) | python | def bind(self, model, *, skip_table_setup=False):
"""Create backing tables for a model and its non-abstract subclasses.
:param model: Base model to bind. Can be abstract.
:param skip_table_setup: Don't create or verify the table in DynamoDB. Default is False.
:raises bloop.exceptions.InvalidModel: if ``model`` is not a subclass of :class:`~bloop.models.BaseModel`.
"""
# Make sure we're looking at models
validate_is_model(model)
concrete = set(filter(lambda m: not m.Meta.abstract, walk_subclasses(model)))
if not model.Meta.abstract:
concrete.add(model)
logger.debug("binding non-abstract models {}".format(
sorted(c.__name__ for c in concrete)
))
# create_table doesn't block until ACTIVE or validate.
# It also doesn't throw when the table already exists, making it safe
# to call multiple times for the same unbound model.
if skip_table_setup:
logger.info("skip_table_setup is True; not trying to create tables or validate models during bind")
else:
self.session.clear_cache()
is_creating = {}
for model in concrete:
table_name = self._compute_table_name(model)
before_create_table.send(self, engine=self, model=model)
if not skip_table_setup:
if table_name in is_creating:
continue
creating = self.session.create_table(table_name, model)
is_creating[table_name] = creating
for model in concrete:
if not skip_table_setup:
table_name = self._compute_table_name(model)
if is_creating[table_name]:
# polls until table is active
self.session.describe_table(table_name)
if model.Meta.ttl:
self.session.enable_ttl(table_name, model)
if model.Meta.backups and model.Meta.backups["enabled"]:
self.session.enable_backups(table_name, model)
self.session.validate_table(table_name, model)
model_validated.send(self, engine=self, model=model)
model_bound.send(self, engine=self, model=model)
logger.info("successfully bound {} models to the engine".format(len(concrete))) | [
"def",
"bind",
"(",
"self",
",",
"model",
",",
"*",
",",
"skip_table_setup",
"=",
"False",
")",
":",
"# Make sure we're looking at models",
"validate_is_model",
"(",
"model",
")",
"concrete",
"=",
"set",
"(",
"filter",
"(",
"lambda",
"m",
":",
"not",
"m",
".",
"Meta",
".",
"abstract",
",",
"walk_subclasses",
"(",
"model",
")",
")",
")",
"if",
"not",
"model",
".",
"Meta",
".",
"abstract",
":",
"concrete",
".",
"add",
"(",
"model",
")",
"logger",
".",
"debug",
"(",
"\"binding non-abstract models {}\"",
".",
"format",
"(",
"sorted",
"(",
"c",
".",
"__name__",
"for",
"c",
"in",
"concrete",
")",
")",
")",
"# create_table doesn't block until ACTIVE or validate.",
"# It also doesn't throw when the table already exists, making it safe",
"# to call multiple times for the same unbound model.",
"if",
"skip_table_setup",
":",
"logger",
".",
"info",
"(",
"\"skip_table_setup is True; not trying to create tables or validate models during bind\"",
")",
"else",
":",
"self",
".",
"session",
".",
"clear_cache",
"(",
")",
"is_creating",
"=",
"{",
"}",
"for",
"model",
"in",
"concrete",
":",
"table_name",
"=",
"self",
".",
"_compute_table_name",
"(",
"model",
")",
"before_create_table",
".",
"send",
"(",
"self",
",",
"engine",
"=",
"self",
",",
"model",
"=",
"model",
")",
"if",
"not",
"skip_table_setup",
":",
"if",
"table_name",
"in",
"is_creating",
":",
"continue",
"creating",
"=",
"self",
".",
"session",
".",
"create_table",
"(",
"table_name",
",",
"model",
")",
"is_creating",
"[",
"table_name",
"]",
"=",
"creating",
"for",
"model",
"in",
"concrete",
":",
"if",
"not",
"skip_table_setup",
":",
"table_name",
"=",
"self",
".",
"_compute_table_name",
"(",
"model",
")",
"if",
"is_creating",
"[",
"table_name",
"]",
":",
"# polls until table is active",
"self",
".",
"session",
".",
"describe_table",
"(",
"table_name",
")",
"if",
"model",
".",
"Meta",
".",
"ttl",
":",
"self",
".",
"session",
".",
"enable_ttl",
"(",
"table_name",
",",
"model",
")",
"if",
"model",
".",
"Meta",
".",
"backups",
"and",
"model",
".",
"Meta",
".",
"backups",
"[",
"\"enabled\"",
"]",
":",
"self",
".",
"session",
".",
"enable_backups",
"(",
"table_name",
",",
"model",
")",
"self",
".",
"session",
".",
"validate_table",
"(",
"table_name",
",",
"model",
")",
"model_validated",
".",
"send",
"(",
"self",
",",
"engine",
"=",
"self",
",",
"model",
"=",
"model",
")",
"model_bound",
".",
"send",
"(",
"self",
",",
"engine",
"=",
"self",
",",
"model",
"=",
"model",
")",
"logger",
".",
"info",
"(",
"\"successfully bound {} models to the engine\"",
".",
"format",
"(",
"len",
"(",
"concrete",
")",
")",
")"
] | Create backing tables for a model and its non-abstract subclasses.
:param model: Base model to bind. Can be abstract.
:param skip_table_setup: Don't create or verify the table in DynamoDB. Default is False.
:raises bloop.exceptions.InvalidModel: if ``model`` is not a subclass of :class:`~bloop.models.BaseModel`. | [
"Create",
"backing",
"tables",
"for",
"a",
"model",
"and",
"its",
"non",
"-",
"abstract",
"subclasses",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L115-L165 | train |
numberoverzero/bloop | bloop/engine.py | Engine.delete | def delete(self, *objs, condition=None, atomic=False):
"""Delete one or more objects.
:param objs: objects to delete.
:param condition: only perform each delete if this condition holds.
:param bool atomic: only perform each delete if the local and DynamoDB versions of the object match.
:raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met.
"""
objs = set(objs)
validate_not_abstract(*objs)
for obj in objs:
self.session.delete_item({
"TableName": self._compute_table_name(obj.__class__),
"Key": dump_key(self, obj),
**render(self, obj=obj, atomic=atomic, condition=condition)
})
object_deleted.send(self, engine=self, obj=obj)
logger.info("successfully deleted {} objects".format(len(objs))) | python | def delete(self, *objs, condition=None, atomic=False):
"""Delete one or more objects.
:param objs: objects to delete.
:param condition: only perform each delete if this condition holds.
:param bool atomic: only perform each delete if the local and DynamoDB versions of the object match.
:raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met.
"""
objs = set(objs)
validate_not_abstract(*objs)
for obj in objs:
self.session.delete_item({
"TableName": self._compute_table_name(obj.__class__),
"Key": dump_key(self, obj),
**render(self, obj=obj, atomic=atomic, condition=condition)
})
object_deleted.send(self, engine=self, obj=obj)
logger.info("successfully deleted {} objects".format(len(objs))) | [
"def",
"delete",
"(",
"self",
",",
"*",
"objs",
",",
"condition",
"=",
"None",
",",
"atomic",
"=",
"False",
")",
":",
"objs",
"=",
"set",
"(",
"objs",
")",
"validate_not_abstract",
"(",
"*",
"objs",
")",
"for",
"obj",
"in",
"objs",
":",
"self",
".",
"session",
".",
"delete_item",
"(",
"{",
"\"TableName\"",
":",
"self",
".",
"_compute_table_name",
"(",
"obj",
".",
"__class__",
")",
",",
"\"Key\"",
":",
"dump_key",
"(",
"self",
",",
"obj",
")",
",",
"*",
"*",
"render",
"(",
"self",
",",
"obj",
"=",
"obj",
",",
"atomic",
"=",
"atomic",
",",
"condition",
"=",
"condition",
")",
"}",
")",
"object_deleted",
".",
"send",
"(",
"self",
",",
"engine",
"=",
"self",
",",
"obj",
"=",
"obj",
")",
"logger",
".",
"info",
"(",
"\"successfully deleted {} objects\"",
".",
"format",
"(",
"len",
"(",
"objs",
")",
")",
")"
] | Delete one or more objects.
:param objs: objects to delete.
:param condition: only perform each delete if this condition holds.
:param bool atomic: only perform each delete if the local and DynamoDB versions of the object match.
:raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met. | [
"Delete",
"one",
"or",
"more",
"objects",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L167-L184 | train |
numberoverzero/bloop | bloop/engine.py | Engine.load | def load(self, *objs, consistent=False):
"""Populate objects from DynamoDB.
:param objs: objects to delete.
:param bool consistent: Use `strongly consistent reads`__ if True. Default is False.
:raises bloop.exceptions.MissingKey: if any object doesn't provide a value for a key column.
:raises bloop.exceptions.MissingObjects: if one or more objects aren't loaded.
__ http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html
"""
get_table_name = self._compute_table_name
objs = set(objs)
validate_not_abstract(*objs)
table_index, object_index, request = {}, {}, {}
for obj in objs:
table_name = get_table_name(obj.__class__)
key = dump_key(self, obj)
index = index_for(key)
if table_name not in object_index:
table_index[table_name] = list(sorted(key.keys()))
object_index[table_name] = {}
request[table_name] = {"Keys": [], "ConsistentRead": consistent}
if index not in object_index[table_name]:
request[table_name]["Keys"].append(key)
object_index[table_name][index] = set()
object_index[table_name][index].add(obj)
response = self.session.load_items(request)
for table_name, list_of_attrs in response.items():
for attrs in list_of_attrs:
key_shape = table_index[table_name]
key = extract_key(key_shape, attrs)
index = index_for(key)
for obj in object_index[table_name].pop(index):
unpack_from_dynamodb(
attrs=attrs, expected=obj.Meta.columns, engine=self, obj=obj)
object_loaded.send(self, engine=self, obj=obj)
if not object_index[table_name]:
object_index.pop(table_name)
if object_index:
not_loaded = set()
for index in object_index.values():
for index_set in index.values():
not_loaded.update(index_set)
logger.info("loaded {} of {} objects".format(len(objs) - len(not_loaded), len(objs)))
raise MissingObjects("Failed to load some objects.", objects=not_loaded)
logger.info("successfully loaded {} objects".format(len(objs))) | python | def load(self, *objs, consistent=False):
"""Populate objects from DynamoDB.
:param objs: objects to delete.
:param bool consistent: Use `strongly consistent reads`__ if True. Default is False.
:raises bloop.exceptions.MissingKey: if any object doesn't provide a value for a key column.
:raises bloop.exceptions.MissingObjects: if one or more objects aren't loaded.
__ http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html
"""
get_table_name = self._compute_table_name
objs = set(objs)
validate_not_abstract(*objs)
table_index, object_index, request = {}, {}, {}
for obj in objs:
table_name = get_table_name(obj.__class__)
key = dump_key(self, obj)
index = index_for(key)
if table_name not in object_index:
table_index[table_name] = list(sorted(key.keys()))
object_index[table_name] = {}
request[table_name] = {"Keys": [], "ConsistentRead": consistent}
if index not in object_index[table_name]:
request[table_name]["Keys"].append(key)
object_index[table_name][index] = set()
object_index[table_name][index].add(obj)
response = self.session.load_items(request)
for table_name, list_of_attrs in response.items():
for attrs in list_of_attrs:
key_shape = table_index[table_name]
key = extract_key(key_shape, attrs)
index = index_for(key)
for obj in object_index[table_name].pop(index):
unpack_from_dynamodb(
attrs=attrs, expected=obj.Meta.columns, engine=self, obj=obj)
object_loaded.send(self, engine=self, obj=obj)
if not object_index[table_name]:
object_index.pop(table_name)
if object_index:
not_loaded = set()
for index in object_index.values():
for index_set in index.values():
not_loaded.update(index_set)
logger.info("loaded {} of {} objects".format(len(objs) - len(not_loaded), len(objs)))
raise MissingObjects("Failed to load some objects.", objects=not_loaded)
logger.info("successfully loaded {} objects".format(len(objs))) | [
"def",
"load",
"(",
"self",
",",
"*",
"objs",
",",
"consistent",
"=",
"False",
")",
":",
"get_table_name",
"=",
"self",
".",
"_compute_table_name",
"objs",
"=",
"set",
"(",
"objs",
")",
"validate_not_abstract",
"(",
"*",
"objs",
")",
"table_index",
",",
"object_index",
",",
"request",
"=",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
"for",
"obj",
"in",
"objs",
":",
"table_name",
"=",
"get_table_name",
"(",
"obj",
".",
"__class__",
")",
"key",
"=",
"dump_key",
"(",
"self",
",",
"obj",
")",
"index",
"=",
"index_for",
"(",
"key",
")",
"if",
"table_name",
"not",
"in",
"object_index",
":",
"table_index",
"[",
"table_name",
"]",
"=",
"list",
"(",
"sorted",
"(",
"key",
".",
"keys",
"(",
")",
")",
")",
"object_index",
"[",
"table_name",
"]",
"=",
"{",
"}",
"request",
"[",
"table_name",
"]",
"=",
"{",
"\"Keys\"",
":",
"[",
"]",
",",
"\"ConsistentRead\"",
":",
"consistent",
"}",
"if",
"index",
"not",
"in",
"object_index",
"[",
"table_name",
"]",
":",
"request",
"[",
"table_name",
"]",
"[",
"\"Keys\"",
"]",
".",
"append",
"(",
"key",
")",
"object_index",
"[",
"table_name",
"]",
"[",
"index",
"]",
"=",
"set",
"(",
")",
"object_index",
"[",
"table_name",
"]",
"[",
"index",
"]",
".",
"add",
"(",
"obj",
")",
"response",
"=",
"self",
".",
"session",
".",
"load_items",
"(",
"request",
")",
"for",
"table_name",
",",
"list_of_attrs",
"in",
"response",
".",
"items",
"(",
")",
":",
"for",
"attrs",
"in",
"list_of_attrs",
":",
"key_shape",
"=",
"table_index",
"[",
"table_name",
"]",
"key",
"=",
"extract_key",
"(",
"key_shape",
",",
"attrs",
")",
"index",
"=",
"index_for",
"(",
"key",
")",
"for",
"obj",
"in",
"object_index",
"[",
"table_name",
"]",
".",
"pop",
"(",
"index",
")",
":",
"unpack_from_dynamodb",
"(",
"attrs",
"=",
"attrs",
",",
"expected",
"=",
"obj",
".",
"Meta",
".",
"columns",
",",
"engine",
"=",
"self",
",",
"obj",
"=",
"obj",
")",
"object_loaded",
".",
"send",
"(",
"self",
",",
"engine",
"=",
"self",
",",
"obj",
"=",
"obj",
")",
"if",
"not",
"object_index",
"[",
"table_name",
"]",
":",
"object_index",
".",
"pop",
"(",
"table_name",
")",
"if",
"object_index",
":",
"not_loaded",
"=",
"set",
"(",
")",
"for",
"index",
"in",
"object_index",
".",
"values",
"(",
")",
":",
"for",
"index_set",
"in",
"index",
".",
"values",
"(",
")",
":",
"not_loaded",
".",
"update",
"(",
"index_set",
")",
"logger",
".",
"info",
"(",
"\"loaded {} of {} objects\"",
".",
"format",
"(",
"len",
"(",
"objs",
")",
"-",
"len",
"(",
"not_loaded",
")",
",",
"len",
"(",
"objs",
")",
")",
")",
"raise",
"MissingObjects",
"(",
"\"Failed to load some objects.\"",
",",
"objects",
"=",
"not_loaded",
")",
"logger",
".",
"info",
"(",
"\"successfully loaded {} objects\"",
".",
"format",
"(",
"len",
"(",
"objs",
")",
")",
")"
] | Populate objects from DynamoDB.
:param objs: objects to delete.
:param bool consistent: Use `strongly consistent reads`__ if True. Default is False.
:raises bloop.exceptions.MissingKey: if any object doesn't provide a value for a key column.
:raises bloop.exceptions.MissingObjects: if one or more objects aren't loaded.
__ http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html | [
"Populate",
"objects",
"from",
"DynamoDB",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L186-L239 | train |
numberoverzero/bloop | bloop/engine.py | Engine.query | def query(self, model_or_index, key, filter=None, projection="all", consistent=False, forward=True):
"""Create a reusable :class:`~bloop.search.QueryIterator`.
:param model_or_index: A model or index to query. For example, ``User`` or ``User.by_email``.
:param key:
Key condition. This must include an equality against the hash key, and optionally one
of a restricted set of conditions on the range key.
:param filter: Filter condition. Only matching objects will be included in the results.
:param projection:
"all", "count", a list of column names, or a list of :class:`~bloop.models.Column`. When projection is
"count", you must advance the iterator to retrieve the count.
:param bool consistent: Use `strongly consistent reads`__ if True. Default is False.
:param bool forward: Query in ascending or descending order. Default is True (ascending).
:return: A reusable query iterator with helper methods.
:rtype: :class:`~bloop.search.QueryIterator`
__ http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html
"""
if isinstance(model_or_index, Index):
model, index = model_or_index.model, model_or_index
else:
model, index = model_or_index, None
validate_not_abstract(model)
q = Search(
mode="query", engine=self, model=model, index=index, key=key, filter=filter,
projection=projection, consistent=consistent, forward=forward)
return iter(q.prepare()) | python | def query(self, model_or_index, key, filter=None, projection="all", consistent=False, forward=True):
"""Create a reusable :class:`~bloop.search.QueryIterator`.
:param model_or_index: A model or index to query. For example, ``User`` or ``User.by_email``.
:param key:
Key condition. This must include an equality against the hash key, and optionally one
of a restricted set of conditions on the range key.
:param filter: Filter condition. Only matching objects will be included in the results.
:param projection:
"all", "count", a list of column names, or a list of :class:`~bloop.models.Column`. When projection is
"count", you must advance the iterator to retrieve the count.
:param bool consistent: Use `strongly consistent reads`__ if True. Default is False.
:param bool forward: Query in ascending or descending order. Default is True (ascending).
:return: A reusable query iterator with helper methods.
:rtype: :class:`~bloop.search.QueryIterator`
__ http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html
"""
if isinstance(model_or_index, Index):
model, index = model_or_index.model, model_or_index
else:
model, index = model_or_index, None
validate_not_abstract(model)
q = Search(
mode="query", engine=self, model=model, index=index, key=key, filter=filter,
projection=projection, consistent=consistent, forward=forward)
return iter(q.prepare()) | [
"def",
"query",
"(",
"self",
",",
"model_or_index",
",",
"key",
",",
"filter",
"=",
"None",
",",
"projection",
"=",
"\"all\"",
",",
"consistent",
"=",
"False",
",",
"forward",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"model_or_index",
",",
"Index",
")",
":",
"model",
",",
"index",
"=",
"model_or_index",
".",
"model",
",",
"model_or_index",
"else",
":",
"model",
",",
"index",
"=",
"model_or_index",
",",
"None",
"validate_not_abstract",
"(",
"model",
")",
"q",
"=",
"Search",
"(",
"mode",
"=",
"\"query\"",
",",
"engine",
"=",
"self",
",",
"model",
"=",
"model",
",",
"index",
"=",
"index",
",",
"key",
"=",
"key",
",",
"filter",
"=",
"filter",
",",
"projection",
"=",
"projection",
",",
"consistent",
"=",
"consistent",
",",
"forward",
"=",
"forward",
")",
"return",
"iter",
"(",
"q",
".",
"prepare",
"(",
")",
")"
] | Create a reusable :class:`~bloop.search.QueryIterator`.
:param model_or_index: A model or index to query. For example, ``User`` or ``User.by_email``.
:param key:
Key condition. This must include an equality against the hash key, and optionally one
of a restricted set of conditions on the range key.
:param filter: Filter condition. Only matching objects will be included in the results.
:param projection:
"all", "count", a list of column names, or a list of :class:`~bloop.models.Column`. When projection is
"count", you must advance the iterator to retrieve the count.
:param bool consistent: Use `strongly consistent reads`__ if True. Default is False.
:param bool forward: Query in ascending or descending order. Default is True (ascending).
:return: A reusable query iterator with helper methods.
:rtype: :class:`~bloop.search.QueryIterator`
__ http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html | [
"Create",
"a",
"reusable",
":",
"class",
":",
"~bloop",
".",
"search",
".",
"QueryIterator",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L241-L268 | train |
numberoverzero/bloop | bloop/engine.py | Engine.save | def save(self, *objs, condition=None, atomic=False):
"""Save one or more objects.
:param objs: objects to save.
:param condition: only perform each save if this condition holds.
:param bool atomic: only perform each save if the local and DynamoDB versions of the object match.
:raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met.
"""
objs = set(objs)
validate_not_abstract(*objs)
for obj in objs:
self.session.save_item({
"TableName": self._compute_table_name(obj.__class__),
"Key": dump_key(self, obj),
**render(self, obj=obj, atomic=atomic, condition=condition, update=True)
})
object_saved.send(self, engine=self, obj=obj)
logger.info("successfully saved {} objects".format(len(objs))) | python | def save(self, *objs, condition=None, atomic=False):
"""Save one or more objects.
:param objs: objects to save.
:param condition: only perform each save if this condition holds.
:param bool atomic: only perform each save if the local and DynamoDB versions of the object match.
:raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met.
"""
objs = set(objs)
validate_not_abstract(*objs)
for obj in objs:
self.session.save_item({
"TableName": self._compute_table_name(obj.__class__),
"Key": dump_key(self, obj),
**render(self, obj=obj, atomic=atomic, condition=condition, update=True)
})
object_saved.send(self, engine=self, obj=obj)
logger.info("successfully saved {} objects".format(len(objs))) | [
"def",
"save",
"(",
"self",
",",
"*",
"objs",
",",
"condition",
"=",
"None",
",",
"atomic",
"=",
"False",
")",
":",
"objs",
"=",
"set",
"(",
"objs",
")",
"validate_not_abstract",
"(",
"*",
"objs",
")",
"for",
"obj",
"in",
"objs",
":",
"self",
".",
"session",
".",
"save_item",
"(",
"{",
"\"TableName\"",
":",
"self",
".",
"_compute_table_name",
"(",
"obj",
".",
"__class__",
")",
",",
"\"Key\"",
":",
"dump_key",
"(",
"self",
",",
"obj",
")",
",",
"*",
"*",
"render",
"(",
"self",
",",
"obj",
"=",
"obj",
",",
"atomic",
"=",
"atomic",
",",
"condition",
"=",
"condition",
",",
"update",
"=",
"True",
")",
"}",
")",
"object_saved",
".",
"send",
"(",
"self",
",",
"engine",
"=",
"self",
",",
"obj",
"=",
"obj",
")",
"logger",
".",
"info",
"(",
"\"successfully saved {} objects\"",
".",
"format",
"(",
"len",
"(",
"objs",
")",
")",
")"
] | Save one or more objects.
:param objs: objects to save.
:param condition: only perform each save if this condition holds.
:param bool atomic: only perform each save if the local and DynamoDB versions of the object match.
:raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met. | [
"Save",
"one",
"or",
"more",
"objects",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L270-L287 | train |
numberoverzero/bloop | bloop/engine.py | Engine.scan | def scan(self, model_or_index, filter=None, projection="all", consistent=False, parallel=None):
"""Create a reusable :class:`~bloop.search.ScanIterator`.
:param model_or_index: A model or index to scan. For example, ``User`` or ``User.by_email``.
:param filter: Filter condition. Only matching objects will be included in the results.
:param projection:
"all", "count", a list of column names, or a list of :class:`~bloop.models.Column`. When projection is
"count", you must exhaust the iterator to retrieve the count.
:param bool consistent: Use `strongly consistent reads`__ if True. Default is False.
:param tuple parallel: Perform a `parallel scan`__. A tuple of (Segment, TotalSegments)
for this portion the scan. Default is None.
:return: A reusable scan iterator with helper methods.
:rtype: :class:`~bloop.search.ScanIterator`
__ http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html
__ http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#QueryAndScanParallelScan
"""
if isinstance(model_or_index, Index):
model, index = model_or_index.model, model_or_index
else:
model, index = model_or_index, None
validate_not_abstract(model)
s = Search(
mode="scan", engine=self, model=model, index=index, filter=filter,
projection=projection, consistent=consistent, parallel=parallel)
return iter(s.prepare()) | python | def scan(self, model_or_index, filter=None, projection="all", consistent=False, parallel=None):
"""Create a reusable :class:`~bloop.search.ScanIterator`.
:param model_or_index: A model or index to scan. For example, ``User`` or ``User.by_email``.
:param filter: Filter condition. Only matching objects will be included in the results.
:param projection:
"all", "count", a list of column names, or a list of :class:`~bloop.models.Column`. When projection is
"count", you must exhaust the iterator to retrieve the count.
:param bool consistent: Use `strongly consistent reads`__ if True. Default is False.
:param tuple parallel: Perform a `parallel scan`__. A tuple of (Segment, TotalSegments)
for this portion the scan. Default is None.
:return: A reusable scan iterator with helper methods.
:rtype: :class:`~bloop.search.ScanIterator`
__ http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html
__ http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#QueryAndScanParallelScan
"""
if isinstance(model_or_index, Index):
model, index = model_or_index.model, model_or_index
else:
model, index = model_or_index, None
validate_not_abstract(model)
s = Search(
mode="scan", engine=self, model=model, index=index, filter=filter,
projection=projection, consistent=consistent, parallel=parallel)
return iter(s.prepare()) | [
"def",
"scan",
"(",
"self",
",",
"model_or_index",
",",
"filter",
"=",
"None",
",",
"projection",
"=",
"\"all\"",
",",
"consistent",
"=",
"False",
",",
"parallel",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"model_or_index",
",",
"Index",
")",
":",
"model",
",",
"index",
"=",
"model_or_index",
".",
"model",
",",
"model_or_index",
"else",
":",
"model",
",",
"index",
"=",
"model_or_index",
",",
"None",
"validate_not_abstract",
"(",
"model",
")",
"s",
"=",
"Search",
"(",
"mode",
"=",
"\"scan\"",
",",
"engine",
"=",
"self",
",",
"model",
"=",
"model",
",",
"index",
"=",
"index",
",",
"filter",
"=",
"filter",
",",
"projection",
"=",
"projection",
",",
"consistent",
"=",
"consistent",
",",
"parallel",
"=",
"parallel",
")",
"return",
"iter",
"(",
"s",
".",
"prepare",
"(",
")",
")"
] | Create a reusable :class:`~bloop.search.ScanIterator`.
:param model_or_index: A model or index to scan. For example, ``User`` or ``User.by_email``.
:param filter: Filter condition. Only matching objects will be included in the results.
:param projection:
"all", "count", a list of column names, or a list of :class:`~bloop.models.Column`. When projection is
"count", you must exhaust the iterator to retrieve the count.
:param bool consistent: Use `strongly consistent reads`__ if True. Default is False.
:param tuple parallel: Perform a `parallel scan`__. A tuple of (Segment, TotalSegments)
for this portion the scan. Default is None.
:return: A reusable scan iterator with helper methods.
:rtype: :class:`~bloop.search.ScanIterator`
__ http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html
__ http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#QueryAndScanParallelScan | [
"Create",
"a",
"reusable",
":",
"class",
":",
"~bloop",
".",
"search",
".",
"ScanIterator",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L289-L314 | train |
numberoverzero/bloop | bloop/engine.py | Engine.stream | def stream(self, model, position):
"""Create a :class:`~bloop.stream.Stream` that provides approximate chronological ordering.
.. code-block:: pycon
# Create a user so we have a record
>>> engine = Engine()
>>> user = User(id=3, email="user@domain.com")
>>> engine.save(user)
>>> user.email = "admin@domain.com"
>>> engine.save(user)
# First record lacks an "old" value since it's an insert
>>> stream = engine.stream(User, "trim_horizon")
>>> next(stream)
{'key': None,
'old': None,
'new': User(email='user@domain.com', id=3, verified=None),
'meta': {
'created_at': datetime.datetime(2016, 10, 23, ...),
'event': {
'id': '3fe6d339b7cb19a1474b3d853972c12a',
'type': 'insert',
'version': '1.1'},
'sequence_number': '700000000007366876916'}
}
:param model: The model to stream records from.
:param position: "trim_horizon", "latest", a stream token, or a :class:`datetime.datetime`.
:return: An iterator for records in all shards.
:rtype: :class:`~bloop.stream.Stream`
:raises bloop.exceptions.InvalidStream: if the model does not have a stream.
"""
validate_not_abstract(model)
if not model.Meta.stream or not model.Meta.stream.get("arn"):
raise InvalidStream("{!r} does not have a stream arn".format(model))
stream = Stream(model=model, engine=self)
stream.move_to(position=position)
return stream | python | def stream(self, model, position):
"""Create a :class:`~bloop.stream.Stream` that provides approximate chronological ordering.
.. code-block:: pycon
# Create a user so we have a record
>>> engine = Engine()
>>> user = User(id=3, email="user@domain.com")
>>> engine.save(user)
>>> user.email = "admin@domain.com"
>>> engine.save(user)
# First record lacks an "old" value since it's an insert
>>> stream = engine.stream(User, "trim_horizon")
>>> next(stream)
{'key': None,
'old': None,
'new': User(email='user@domain.com', id=3, verified=None),
'meta': {
'created_at': datetime.datetime(2016, 10, 23, ...),
'event': {
'id': '3fe6d339b7cb19a1474b3d853972c12a',
'type': 'insert',
'version': '1.1'},
'sequence_number': '700000000007366876916'}
}
:param model: The model to stream records from.
:param position: "trim_horizon", "latest", a stream token, or a :class:`datetime.datetime`.
:return: An iterator for records in all shards.
:rtype: :class:`~bloop.stream.Stream`
:raises bloop.exceptions.InvalidStream: if the model does not have a stream.
"""
validate_not_abstract(model)
if not model.Meta.stream or not model.Meta.stream.get("arn"):
raise InvalidStream("{!r} does not have a stream arn".format(model))
stream = Stream(model=model, engine=self)
stream.move_to(position=position)
return stream | [
"def",
"stream",
"(",
"self",
",",
"model",
",",
"position",
")",
":",
"validate_not_abstract",
"(",
"model",
")",
"if",
"not",
"model",
".",
"Meta",
".",
"stream",
"or",
"not",
"model",
".",
"Meta",
".",
"stream",
".",
"get",
"(",
"\"arn\"",
")",
":",
"raise",
"InvalidStream",
"(",
"\"{!r} does not have a stream arn\"",
".",
"format",
"(",
"model",
")",
")",
"stream",
"=",
"Stream",
"(",
"model",
"=",
"model",
",",
"engine",
"=",
"self",
")",
"stream",
".",
"move_to",
"(",
"position",
"=",
"position",
")",
"return",
"stream"
] | Create a :class:`~bloop.stream.Stream` that provides approximate chronological ordering.
.. code-block:: pycon
# Create a user so we have a record
>>> engine = Engine()
>>> user = User(id=3, email="user@domain.com")
>>> engine.save(user)
>>> user.email = "admin@domain.com"
>>> engine.save(user)
# First record lacks an "old" value since it's an insert
>>> stream = engine.stream(User, "trim_horizon")
>>> next(stream)
{'key': None,
'old': None,
'new': User(email='user@domain.com', id=3, verified=None),
'meta': {
'created_at': datetime.datetime(2016, 10, 23, ...),
'event': {
'id': '3fe6d339b7cb19a1474b3d853972c12a',
'type': 'insert',
'version': '1.1'},
'sequence_number': '700000000007366876916'}
}
:param model: The model to stream records from.
:param position: "trim_horizon", "latest", a stream token, or a :class:`datetime.datetime`.
:return: An iterator for records in all shards.
:rtype: :class:`~bloop.stream.Stream`
:raises bloop.exceptions.InvalidStream: if the model does not have a stream. | [
"Create",
"a",
":",
"class",
":",
"~bloop",
".",
"stream",
".",
"Stream",
"that",
"provides",
"approximate",
"chronological",
"ordering",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L316-L355 | train |
numberoverzero/bloop | bloop/engine.py | Engine.transaction | def transaction(self, mode="w"):
"""
Create a new :class:`~bloop.transactions.ReadTransaction` or :class:`~bloop.transactions.WriteTransaction`.
As a context manager, calling commit when the block exits:
.. code-block:: pycon
>>> engine = Engine()
>>> user = User(id=3, email="user@domain.com")
>>> tweet = Tweet(id=42, data="hello, world")
>>> with engine.transaction("w") as tx:
... tx.delete(user)
... tx.save(tweet, condition=Tweet.id.is_(None))
Or manually calling prepare and commit:
.. code-block:: pycon
>>> engine = Engine()
>>> user = User(id=3, email="user@domain.com")
>>> tweet = Tweet(id=42, data="hello, world")
>>> tx = engine.transaction("w")
>>> tx.delete(user)
>>> tx.save(tweet, condition=Tweet.id.is_(None))
>>> tx.prepare().commit()
:param str mode: Either "r" or "w" to create a ReadTransaction or WriteTransaction. Default is "w"
:return: A new transaction that can be committed.
:rtype: :class:`~bloop.transactions.ReadTransaction` or :class:`~bloop.transactions.WriteTransaction`
"""
if mode == "r":
cls = ReadTransaction
elif mode == "w":
cls = WriteTransaction
else:
raise ValueError(f"unknown mode {mode}")
return cls(self) | python | def transaction(self, mode="w"):
"""
Create a new :class:`~bloop.transactions.ReadTransaction` or :class:`~bloop.transactions.WriteTransaction`.
As a context manager, calling commit when the block exits:
.. code-block:: pycon
>>> engine = Engine()
>>> user = User(id=3, email="user@domain.com")
>>> tweet = Tweet(id=42, data="hello, world")
>>> with engine.transaction("w") as tx:
... tx.delete(user)
... tx.save(tweet, condition=Tweet.id.is_(None))
Or manually calling prepare and commit:
.. code-block:: pycon
>>> engine = Engine()
>>> user = User(id=3, email="user@domain.com")
>>> tweet = Tweet(id=42, data="hello, world")
>>> tx = engine.transaction("w")
>>> tx.delete(user)
>>> tx.save(tweet, condition=Tweet.id.is_(None))
>>> tx.prepare().commit()
:param str mode: Either "r" or "w" to create a ReadTransaction or WriteTransaction. Default is "w"
:return: A new transaction that can be committed.
:rtype: :class:`~bloop.transactions.ReadTransaction` or :class:`~bloop.transactions.WriteTransaction`
"""
if mode == "r":
cls = ReadTransaction
elif mode == "w":
cls = WriteTransaction
else:
raise ValueError(f"unknown mode {mode}")
return cls(self) | [
"def",
"transaction",
"(",
"self",
",",
"mode",
"=",
"\"w\"",
")",
":",
"if",
"mode",
"==",
"\"r\"",
":",
"cls",
"=",
"ReadTransaction",
"elif",
"mode",
"==",
"\"w\"",
":",
"cls",
"=",
"WriteTransaction",
"else",
":",
"raise",
"ValueError",
"(",
"f\"unknown mode {mode}\"",
")",
"return",
"cls",
"(",
"self",
")"
] | Create a new :class:`~bloop.transactions.ReadTransaction` or :class:`~bloop.transactions.WriteTransaction`.
As a context manager, calling commit when the block exits:
.. code-block:: pycon
>>> engine = Engine()
>>> user = User(id=3, email="user@domain.com")
>>> tweet = Tweet(id=42, data="hello, world")
>>> with engine.transaction("w") as tx:
... tx.delete(user)
... tx.save(tweet, condition=Tweet.id.is_(None))
Or manually calling prepare and commit:
.. code-block:: pycon
>>> engine = Engine()
>>> user = User(id=3, email="user@domain.com")
>>> tweet = Tweet(id=42, data="hello, world")
>>> tx = engine.transaction("w")
>>> tx.delete(user)
>>> tx.save(tweet, condition=Tweet.id.is_(None))
>>> tx.prepare().commit()
:param str mode: Either "r" or "w" to create a ReadTransaction or WriteTransaction. Default is "w"
:return: A new transaction that can be committed.
:rtype: :class:`~bloop.transactions.ReadTransaction` or :class:`~bloop.transactions.WriteTransaction` | [
"Create",
"a",
"new",
":",
"class",
":",
"~bloop",
".",
"transactions",
".",
"ReadTransaction",
"or",
":",
"class",
":",
"~bloop",
".",
"transactions",
".",
"WriteTransaction",
"."
] | 4c95f5a0ff0802443a1c258bfaccecd1758363e7 | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L357-L394 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.