code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
parsed = self.download_parsed(days=days)
return parsed.account.statement | def statement(self, days=60) | Download the :py:class:`ofxparse.Statement` given the time range
:param days: Number of days to look back at
:type days: integer
:rtype: :py:class:`ofxparser.Statement` | 19.381643 | 13.455626 | 1.440412 |
data = {
'local_id': self.local_id(),
'institution': self.institution.serialize(),
'number': self.number,
'description': self.description
}
if hasattr(self, 'broker_id'):
data['broker_id'] = self.broker_id
elif hasattr(... | def serialize(self) | Serialize predictably for use in configuration storage.
Output look like this::
{
'local_id': 'string',
'number': 'account num',
'description': 'descr',
'broker_id': 'may be missing - type dependent',
'routing_number':... | 2.884085 | 2.000792 | 1.441472 |
from ofxclient.institution import Institution
institution = Institution.deserialize(raw['institution'])
del raw['institution']
del raw['local_id']
if 'broker_id' in raw:
a = BrokerageAccount(institution=institution, **raw)
elif 'routing_number' in r... | def deserialize(raw) | Instantiate :py:class:`ofxclient.Account` subclass from dictionary
:param raw: serilized Account
:param type: dict as given by :py:meth:`~ofxclient.Account.serialize`
:rtype: subclass of :py:class:`ofxclient.Account` | 3.860161 | 3.506489 | 1.100862 |
description = data.desc if hasattr(data, 'desc') else None
if data.type == AccountType.Bank:
return BankAccount(
institution=institution,
number=data.account_id,
routing_number=data.routing_number,
account_type=data.ac... | def from_ofxparse(data, institution) | Instantiate :py:class:`ofxclient.Account` subclass from ofxparse
module
:param data: an ofxparse account
:type data: An :py:class:`ofxparse.Account` object
:param institution: The parent institution of the account
:type institution: :py:class:`ofxclient.Institution` object | 2.247069 | 2.30091 | 0.9766 |
c = self.institution.client()
q = c.brokerage_account_query(
number=self.number, date=as_of, broker_id=self.broker_id)
return q | def _download_query(self, as_of) | Formulate the specific query needed for download
Not intended to be called by developers directly.
:param as_of: Date in 'YYYYMMDD' format
:type as_of: string | 9.34608 | 9.382393 | 0.99613 |
c = self.institution.client()
q = c.bank_account_query(
number=self.number,
date=as_of,
account_type=self.account_type,
bank_id=self.routing_number)
return q | def _download_query(self, as_of) | Formulate the specific query needed for download
Not intended to be called by developers directly.
:param as_of: Date in 'YYYYMMDD' format
:type as_of: string | 6.724686 | 6.738343 | 0.997973 |
c = self.institution.client()
q = c.credit_card_account_query(number=self.number, date=as_of)
return q | def _download_query(self, as_of) | Formulate the specific query needed for download
Not intended to be called by developers directly.
:param as_of: Date in 'YYYYMMDD' format
:type as_of: string | 12.833717 | 12.518276 | 1.025198 |
client = Client(institution=None)
out_file = StringIO()
out_file.write(client.header())
out_file.write('<OFX>')
for a in accounts:
ofx = a.download(days=days).read()
stripped = ofx.partition('<OFX>')[2].partition('</OFX>')[0]
out_file.write(stripped)
out_file.writ... | def combined_download(accounts, days=60) | Download OFX files and combine them into one
It expects an 'accounts' list of ofxclient.Account objects
as well as an optional 'days' specifier which defaults to 60 | 3.672906 | 3.255335 | 1.128273 |
u = username or self.institution.username
p = password or self.institution.password
contents = ['OFX', self._signOn(username=u, password=p)]
if with_message:
contents.append(with_message)
return LINE_ENDING.join([self.header(), _tag(*contents)]) | def authenticated_query(
self,
with_message=None,
username=None,
password=None
) | Authenticated query
If you pass a 'with_messages' array those queries will be passed along
otherwise this will just be an authentication probe query only. | 8.743397 | 8.837606 | 0.98934 |
return self.authenticated_query(
self._bareq(number, date, account_type, bank_id)
) | def bank_account_query(self, number, date, account_type, bank_id) | Bank account statement request | 9.179267 | 10.237205 | 0.896658 |
return self.authenticated_query(self._ccreq(number, date)) | def credit_card_account_query(self, number, date) | CC Statement request | 21.163551 | 20.642334 | 1.02525 |
res, response = self._do_post(query)
cookies = res.getheader('Set-Cookie', None)
if len(response) == 0 and cookies is not None and res.status == 200:
logging.debug('Got 0-length 200 response with Set-Cookies header; '
'retrying request with cookies'... | def post(self, query) | Wrapper around ``_do_post()`` to handle accounts that require
sending back session cookies (``self.set_cookies`` True). | 4.813127 | 4.399481 | 1.094021 |
i = self.institution
logging.debug('posting data to %s' % i.url)
garbage, path = splittype(i.url)
host, selector = splithost(path)
h = HTTPSConnection(host, timeout=60)
# Discover requires a particular ordering of headers, so send the
# request step by st... | def _do_post(self, query, extra_headers=[]) | Do a POST to the Institution.
:param query: Body content to POST (OFX Query)
:type query: str
:param extra_headers: Extra headers to send with the request, as a list
of (Name, Value) header 2-tuples.
:type extra_headers: list
:return: 2-tuple of (HTTPResponse, str resp... | 3.18171 | 2.871487 | 1.108035 |
raw_headers = []
for k, v in headers.items():
raw_headers.append((k.encode('utf8'), v.encode('utf8')))
return tuple(raw_headers) | def _build_raw_headers(self, headers: Dict) -> Tuple | Convert a dict of headers to a tuple of tuples
Mimics the format of ClientResponse. | 2.401368 | 2.214988 | 1.084145 |
url = normalize_url(merge_params(url, kwargs.get('params')))
url_str = str(url)
for prefix in self._passthrough:
if url_str.startswith(prefix):
return (await self.patcher.temp_original(
orig_self, method, url, *args, **kwargs
... | async def _request_mock(self, orig_self: ClientSession,
method: str, url: 'Union[URL, str]',
*args: Tuple,
**kwargs: Dict) -> 'ClientResponse' | Return mocked response object or raise connection error. | 4.081458 | 4.100137 | 0.995444 |
url = URL(url)
return url.with_query(urlencode(sorted(parse_qsl(url.query_string)))) | def normalize_url(url: 'Union[URL, str]') -> 'URL' | Normalize url to make comparisons. | 5.31702 | 4.844633 | 1.097507 |
case = Case(title=title, description=description, **kwargs)
response = self._thehive.create_case(case)
# Check for failed authentication
if response.status_code == requests.codes.unauthorized:
raise TheHiveException("Authentication failed")
if self.status_o... | def create(self, title, description, **kwargs) | Create an instance of the Case class.
:param title: Case title.
:param description: Case description.
:param kwargs: Additional arguments.
:return: The created instance. | 4.184309 | 4.087798 | 1.02361 |
response = self._thehive.do_patch("/api/case/{}".format(case_id), **attributes)
if response.status_code == requests.codes.unauthorized:
raise TheHiveException("Authentication failed")
if self.status_ok(response.status_code):
return self(response.json()['id'])
... | def update(self, case_id, **attributes) | Update a case.
:param case_id: The ID of the case to update
:param attributes: key=value pairs of case attributes to update (field=new_value)
:return: The created instance. | 4.179743 | 4.086085 | 1.022921 |
req = self.url + find_url
# Add range and sort parameters
params = {
"range": attributes.get("range", "all"),
"sort": attributes.get("sort", [])
}
# Add body
data = {
"query": attributes.get("query", {})
}
tr... | def __find_rows(self, find_url, **attributes) | :param find_url: URL of the find api
:type find_url: string
:return: The Response returned by requests including the list of documents based on find_url
:rtype: Response object | 3.467861 | 3.409859 | 1.01701 |
req = self.url + "/api/case"
data = case.jsonify()
try:
return requests.post(req, headers={'Content-Type': 'application/json'}, data=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise Ca... | def create_case(self, case) | :param case: The case details
:type case: Case defined in models.py
:return: TheHive case
:rtype: json | 3.373746 | 3.453436 | 0.976924 |
req = self.url + "/api/case/{}".format(case.id)
# Choose which attributes to send
update_keys = [
'title', 'description', 'severity', 'startDate', 'owner', 'flag', 'tlp', 'tags', 'status', 'resolutionStatus',
'impactStatus', 'summary', 'endDate', 'metrics', 'cus... | def update_case(self, case, fields=[]) | Update a case.
:param case: The case to update. The case's `id` determines which case to update.
:param fields: Optional parameter, an array of fields names, the ones we want to update
:return: | 3.900077 | 4.089692 | 0.953636 |
req = self.url + "/api/case/{}/task".format(case_id)
data = case_task.jsonify()
try:
return requests.post(req, headers={'Content-Type': 'application/json'}, data=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestExcept... | def create_case_task(self, case_id, case_task) | :param case_id: Case identifier
:param case_task: TheHive task
:type case_task: CaseTask defined in models.py
:return: TheHive task
:rtype: json | 3.030594 | 3.196902 | 0.947978 |
req = self.url + "/api/case/task/{}".format(task.id)
# Choose which attributes to send
update_keys = [
'title', 'description', 'status', 'order', 'user', 'owner', 'flag', 'endDate'
]
data = {k: v for k, v in task.__dict__.items() if k in update_keys}
... | def update_case_task(self, task) | :Updates TheHive Task
:param case: The task to update. The task's `id` determines which Task to update.
:return: | 3.60858 | 3.815563 | 0.945753 |
req = self.url + "/api/case/task/{}/log".format(task_id)
data = {'_json': json.dumps({"message":case_task_log.message})}
if case_task_log.file:
f = {'attachment': (os.path.basename(case_task_log.file), open(case_task_log.file, 'rb'), magic.Magic(mime=True).from_file(case_... | def create_task_log(self, task_id, case_task_log) | :param task_id: Task identifier
:param case_task_log: TheHive log
:type case_task_log: CaseTaskLog defined in models.py
:return: TheHive log
:rtype: json | 2.124512 | 2.170583 | 0.978775 |
req = self.url + "/api/case/{}/artifact".format(case_id)
if case_observable.dataType == 'file':
try:
mesg = json.dumps({ "dataType": case_observable.dataType,
"message": case_observable.message,
"tlp": case_observable.tlp,
... | def create_case_observable(self, case_id, case_observable) | :param case_id: Case identifier
:param case_observable: TheHive observable
:type case_observable: CaseObservable defined in models.py
:return: TheHive observable
:rtype: json | 2.651867 | 2.716405 | 0.976241 |
req = self.url + "/api/case/{}/links".format(case_id)
try:
return requests.get(req, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseException("Linked cases fetch error: {}".format(e)) | def get_linked_cases(self, case_id) | :param case_id: Case identifier
:return: TheHive case(s)
:rtype: json | 3.874538 | 4.092735 | 0.946687 |
req = self.url + "/api/case/template/_search"
data = {
"query": And(Eq("name", name), Eq("status", "Ok"))
}
try:
response = requests.post(req, json=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
json_response = response.json(... | def get_case_template(self, name) | :param name: Case template name
:return: TheHive case template
:rtype: json | 3.075448 | 3.17199 | 0.969564 |
req = self.url + "/api/case/task/{}/log".format(taskId)
try:
return requests.get(req, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseTaskException("Case task logs search error: {}".format(e)) | def get_task_logs(self, taskId) | :param taskId: Task identifier
:type caseTaskLog: CaseTaskLog defined in models.py
:return: TheHive logs
:rtype: json | 4.265142 | 3.982129 | 1.071071 |
req = self.url + "/api/alert"
data = alert.jsonify()
try:
return requests.post(req, headers={'Content-Type': 'application/json'}, data=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise ... | def create_alert(self, alert) | :param alert: TheHive alert
:type alert: Alert defined in models.py
:return: TheHive alert
:rtype: json | 3.18874 | 3.346525 | 0.952851 |
req = self.url + "/api/alert/{}/markAsRead".format(alert_id)
try:
return requests.post(req, headers={'Content-Type': 'application/json'}, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException:
raise AlertException("M... | def mark_alert_as_read(self, alert_id) | Mark an alert as read.
:param alert_id: The ID of the alert to mark as read.
:return: | 3.463047 | 3.947988 | 0.877167 |
req = self.url + "/api/alert/{}".format(alert_id)
# update only the alert attributes that are not read-only
update_keys = ['tlp', 'severity', 'tags', 'caseTemplate', 'title', 'description']
data = {k: v for k, v in alert.__dict__.items() if
(len(fields) > 0 and... | def update_alert(self, alert_id, alert, fields=[]) | Update an alert.
:param alert_id: The ID of the alert to update.
:param data: The alert to update.
:param fields: Optional parameter, an array of fields names, the ones we want to update
:return: | 3.591426 | 3.843248 | 0.934477 |
req = self.url + "/api/alert/{}".format(alert_id)
try:
return requests.get(req, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise AlertException("Alert fetch error: {}".format(e)) | def get_alert(self, alert_id) | :param alert_id: Alert identifier
:return: TheHive Alert
:rtype: json | 3.296924 | 3.61532 | 0.911931 |
req = self.url + "/api/alert/{}/createCase".format(alert_id)
try:
return requests.post(req, headers={'Content-Type': 'application/json'},
proxies=self.proxies, auth=self.auth,
verify=self.cert, data=json.dumps({}))
... | def promote_alert_to_case(self, alert_id) | This uses the TheHiveAPI to promote an alert to a case
:param alert_id: Alert identifier
:return: TheHive Case
:rtype: json | 3.836169 | 3.827634 | 1.00223 |
req = self.url + "/api/connector/cortex/job"
try:
data = json.dumps({ "cortexId": cortex_id,
"artifactId": artifact_id,
"analyzerId": analyzer_id
})
return requests.post(req, headers={'Content-Type': 'application/json'},... | def run_analyzer(self, cortex_id, artifact_id, analyzer_id) | :param cortex_id: identifier of the Cortex server
:param artifact_id: identifier of the artifact as found with an artifact search
:param analyzer_id: name of the analyzer used by the job
:rtype: json | 3.369132 | 3.581812 | 0.940622 |
return self.transport.forward_request(
method='GET', path='/', headers=headers) | def info(self, headers=None) | Retrieves information of the node being connected to via the
root endpoint ``'/'``.
Args:
headers (dict): Optional headers to pass to the request.
Returns:
dict: Details of the node that this instance is connected
to. Some information that may be interesting... | 11.970894 | 15.483246 | 0.773151 |
return self.transport.forward_request(
method='GET',
path=self.api_prefix,
headers=headers,
) | def api_info(self, headers=None) | Retrieves information provided by the API root endpoint
``'/api/v1'``.
Args:
headers (dict): Optional headers to pass to the request.
Returns:
dict: Details of the HTTP API provided by the BigchainDB
server. | 7.72451 | 9.12994 | 0.846064 |
return prepare_transaction(
operation=operation,
signers=signers,
recipients=recipients,
asset=asset,
metadata=metadata,
inputs=inputs,
) | def prepare(*, operation='CREATE', signers=None,
recipients=None, asset=None, metadata=None, inputs=None) | Prepares a transaction payload, ready to be fulfilled.
Args:
operation (str): The operation to perform. Must be ``'CREATE'``
or ``'TRANSFER'``. Case insensitive. Defaults to ``'CREATE'``.
signers (:obj:`list` | :obj:`tuple` | :obj:`str`, optional):
One or... | 2.122493 | 3.326246 | 0.638105 |
return self.transport.forward_request(
method='GET',
path=self.path,
params={'asset_id': asset_id, 'operation': operation},
headers=headers,
) | def get(self, *, asset_id, operation=None, headers=None) | Given an asset id, get its list of transactions (and
optionally filter for only ``'CREATE'`` or ``'TRANSFER'``
transactions).
Args:
asset_id (str): Id of the asset.
operation (str): The type of operation the transaction
should be. Either ``'CREATE'`` or `... | 3.876838 | 4.810462 | 0.805918 |
return self.transport.forward_request(
method='POST',
path=self.path,
json=transaction,
params={'mode': 'async'},
headers=headers) | def send_async(self, transaction, headers=None) | Submit a transaction to the Federation with the mode `async`.
Args:
transaction (dict): the transaction to be sent
to the Federation node(s).
headers (dict): Optional headers to pass to the request.
Returns:
dict: The transaction sent to the Federati... | 6.633468 | 5.375552 | 1.234007 |
path = self.path + txid
return self.transport.forward_request(
method='GET', path=path, headers=None) | def retrieve(self, txid, headers=None) | Retrieves the transaction with the given id.
Args:
txid (str): Id of the transaction to retrieve.
headers (dict): Optional headers to pass to the request.
Returns:
dict: The transaction with the given id. | 7.931345 | 11.269026 | 0.703818 |
return self.transport.forward_request(
method='GET',
path=self.path,
params={'public_key': public_key, 'spent': spent},
headers=headers,
) | def get(self, public_key, spent=None, headers=None) | Get transaction outputs by public key. The public_key parameter
must be a base58 encoded ed25519 public key associated with
transaction output ownership.
Args:
public_key (str): Public key for which unfulfilled
conditions are sought.
spent (bool): Indicat... | 3.518342 | 5.640317 | 0.623784 |
block_list = self.transport.forward_request(
method='GET',
path=self.path,
params={'transaction_id': txid},
headers=headers,
)
return block_list[0] if len(block_list) else None | def get(self, *, txid, headers=None) | Get the block that contains the given transaction id (``txid``)
else return ``None``
Args:
txid (str): Transaction id.
headers (dict): Optional headers to pass to the request.
Returns:
:obj:`list` of :obj:`int`: List of block heights. | 4.369015 | 4.753367 | 0.919141 |
path = self.path + block_height
return self.transport.forward_request(
method='GET', path=path, headers=None) | def retrieve(self, block_height, headers=None) | Retrieves the block with the given ``block_height``.
Args:
block_height (str): height of the block to retrieve.
headers (dict): Optional headers to pass to the request.
Returns:
dict: The block with the given ``block_height``. | 9.02853 | 11.851788 | 0.761786 |
return self.transport.forward_request(
method='GET',
path=self.path,
params={'search': search, 'limit': limit},
headers=headers
) | def get(self, *, search, limit=0, headers=None) | Retrieves the assets that match a given text search string.
Args:
search (str): Text search string.
limit (int): Limit the number of returned documents. Defaults to
zero meaning that it returns all the matching assets.
headers (dict): Optional headers to pass... | 4.137309 | 5.397295 | 0.766552 |
operation = _normalize_operation(operation)
return _prepare_transaction(
operation,
signers=signers,
recipients=recipients,
asset=asset,
metadata=metadata,
inputs=inputs,
) | def prepare_transaction(*, operation='CREATE', signers=None,
recipients=None, asset=None, metadata=None,
inputs=None) | Prepares a transaction payload, ready to be fulfilled. Depending on
the value of ``operation``, simply dispatches to either
:func:`~.prepare_create_transaction` or
:func:`~.prepare_transfer_transaction`.
Args:
operation (str): The operation to perform. Must be ``'CREATE'``
or ``'TRA... | 2.614086 | 3.658768 | 0.714472 |
if not isinstance(signers, (list, tuple)):
signers = [signers]
# NOTE: Needed for the time being. See
# https://github.com/bigchaindb/bigchaindb/issues/797
elif isinstance(signers, tuple):
signers = list(signers)
if not recipients:
recipients = [(signers, 1)]
elif n... | def prepare_create_transaction(*,
signers,
recipients=None,
asset=None,
metadata=None) | Prepares a ``"CREATE"`` transaction payload, ready to be
fulfilled.
Args:
signers (:obj:`list` | :obj:`tuple` | :obj:`str`): One
or more public keys representing the issuer(s) of the asset
being created.
recipients (:obj:`list` | :obj:`tuple` | :obj:`str`, optional):
... | 2.348346 | 2.392156 | 0.981686 |
if not isinstance(private_keys, (list, tuple)):
private_keys = [private_keys]
# NOTE: Needed for the time being. See
# https://github.com/bigchaindb/bigchaindb/issues/797
if isinstance(private_keys, tuple):
private_keys = list(private_keys)
transaction_obj = Transaction.from_d... | def fulfill_transaction(transaction, *, private_keys) | Fulfills the given transaction.
Args:
transaction (dict): The transaction to be fulfilled.
private_keys (:obj:`str` | :obj:`list` | :obj:`tuple`): One or
more private keys to be used for fulfilling the
transaction.
Returns:
dict: The fulfilled transaction payloa... | 3.182621 | 2.886733 | 1.102499 |
try:
operation = operation.upper()
except AttributeError:
pass
try:
operation = ops_map[operation]()
except KeyError:
pass
return operation | def _normalize_operation(operation) | Normalizes the given operation string. For now, this simply means
converting the given string to uppercase, looking it up in
:attr:`~.ops_map`, and returning the corresponding class if
present.
Args:
operation (str): The operation string to convert.
Returns:
The class corresponding... | 4.146572 | 3.395866 | 1.221065 |
if not node:
node = DEFAULT_NODE
elif '://' not in node:
node = '//{}'.format(node)
parts = urlparse(node, scheme='http', allow_fragments=False)
port = parts.port if parts.port else _get_default_port(parts.scheme)
netloc = '{}:{}'.format(parts.hostname, port)
return urlunpar... | def normalize_url(node) | Normalizes the given node url | 2.401195 | 2.439099 | 0.98446 |
headers = {} if headers is None else headers
if isinstance(node, str):
url = normalize_url(node)
return {'endpoint': url, 'headers': headers}
url = normalize_url(node['endpoint'])
node_headers = node.get('headers', {})
return {'endpoint': url, 'headers': {**headers, **node_head... | def normalize_node(node, headers=None) | Normalizes given node as str or dict with headers | 2.462664 | 2.280366 | 1.079942 |
if not nodes:
return (normalize_node(DEFAULT_NODE, headers),)
normalized_nodes = ()
for node in nodes:
normalized_nodes += (normalize_node(node, headers),)
return normalized_nodes | def normalize_nodes(*nodes, headers=None) | Normalizes given dict or array of driver nodes | 3.284498 | 3.348733 | 0.980818 |
backoff_timedelta = self.get_backoff_timedelta()
if timeout is not None and timeout < backoff_timedelta:
raise TimeoutError
if backoff_timedelta > 0:
time.sleep(backoff_timedelta)
connExc = None
timeout = timeout if timeout is None else timeout... | def request(self, method, *, path=None, json=None,
params=None, headers=None, timeout=None,
backoff_cap=None, **kwargs) | Performs an HTTP request with the given parameters.
Implements exponential backoff.
If `ConnectionError` occurs, a timestamp equal to now +
the default delay (`BACKOFF_DELAY`) is assigned to the object.
The timestamp is in UTC. Next time the function is called, it either
... | 3.10321 | 3.168085 | 0.979522 |
if len(connections) == 1:
return connections[0]
def key(conn):
return (datetime.min
if conn.backoff_time is None
else conn.backoff_time)
return min(*connections, key=key) | def pick(self, connections) | Picks a connection with the earliest backoff time.
As a result, the first connection is picked
for as long as it has no backoff time.
Otherwise, the connections are tried in a round robin fashion.
Args:
connections (:obj:list): List of
:class:`~bigc... | 4.700172 | 3.951192 | 1.189558 |
error_trace = []
timeout = self.timeout
backoff_cap = NO_TIMEOUT_BACKOFF_CAP if timeout is None \
else timeout / 2
while timeout is None or timeout > 0:
connection = self.connection_pool.get_connection()
start = time()
try:
... | def forward_request(self, method, path=None,
json=None, params=None, headers=None) | Makes HTTP requests to the configured nodes.
Retries connection errors
(e.g. DNS failures, refused connection, etc).
A user may choose to retry other errors
by catching the corresponding
exceptions and retrying `forward_request`.
Exponential backoff is... | 2.964531 | 3.229153 | 0.918052 |
for key, value in obj.items():
validation_fun(obj_name, key)
if isinstance(value, dict):
validate_all_keys(obj_name, value, validation_fun) | def validate_all_keys(obj_name, obj, validation_fun) | Validate all (nested) keys in `obj` by using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
validation_fun (function): function used to validate the value
of `key`.
Returns:
None: indica... | 1.858907 | 2.556607 | 0.727099 |
for vkey, value in obj.items():
if vkey == key:
validation_fun(value)
elif isinstance(value, dict):
validate_all_values_for_key(value, key, validation_fun) | def validate_all_values_for_key(obj, key, validation_fun) | Validate value for all (nested) occurrence of `key` in `obj`
using `validation_fun`.
Args:
obj (dict): dictionary object.
key (str): key whose value is to be validated.
validation_fun (function): function used to validate the value
of `key`.
Rais... | 1.991806 | 2.606729 | 0.764102 |
if self.operation == Transaction.CREATE:
self._asset_id = self._id
elif self.operation == Transaction.TRANSFER:
self._asset_id = self.asset['id']
return (UnspentOutput(
transaction_id=self._id,
output_index=output_index,
amount... | def unspent_outputs(self) | UnspentOutput: The outputs of this transaction, in a data
structure containing relevant information for storing them in
a UTXO set, and performing validation. | 3.567407 | 3.399639 | 1.049349 |
if not isinstance(inputs, list):
raise TypeError('`inputs` must be a list instance')
if len(inputs) == 0:
raise ValueError('`inputs` must contain at least one item')
if not isinstance(recipients, list):
raise TypeError('`recipients` must be a list ins... | def transfer(cls, inputs, recipients, asset_id, metadata=None) | A simple way to generate a `TRANSFER` transaction.
Note:
Different cases for threshold conditions:
Combining multiple `inputs` with an arbitrary number of
`recipients` can yield interesting cases for the creation of
threshold conditions we'd ... | 2.461699 | 2.358459 | 1.043774 |
if self.operation == Transaction.CREATE:
# NOTE: Since in the case of a `CREATE`-transaction we do not have
# to check for outputs, we're just submitting dummy
# values to the actual method. This simplifies it's logic
# greatly, as we do... | def inputs_valid(self, outputs=None) | Validates the Inputs in the Transaction against given
Outputs.
Note:
Given a `CREATE` Transaction is passed,
dummy values for Outputs are submitted for validation that
evaluate parts of the validation-checks to `True`.
Args:
... | 6.830989 | 5.517805 | 1.23799 |
ccffill = input_.fulfillment
try:
parsed_ffill = Fulfillment.from_uri(ccffill.serialize_uri())
except (TypeError, ValueError,
ParsingError, ASN1DecodeError, ASN1EncodeError):
return False
if operation == Transaction.CREATE:
# ... | def _input_valid(input_, operation, message, output_condition_uri=None) | Validates a single Input against a single Output.
Note:
In case of a `CREATE` Transaction, this method
does not validate against `output_condition_uri`.
Args:
input_ (:class:`~bigchaindb.common.transaction.
Input`) The Input t... | 7.503 | 6.28827 | 1.193174 |
# NOTE: Remove reference to avoid side effects
tx_body = deepcopy(tx_body)
try:
proposed_tx_id = tx_body['id']
except KeyError:
raise InvalidHash('No transaction id found!')
tx_body['id'] = None
tx_body_serialized = Transaction._to_str(t... | def validate_id(tx_body) | Validate the transaction ID of a transaction
Args:
tx_body (dict): The Transaction to be transformed. | 3.980195 | 4.052019 | 0.982275 |
inputs = [Input.from_dict(input_) for input_ in tx['inputs']]
outputs = [Output.from_dict(output) for output in tx['outputs']]
return cls(tx['operation'], tx['asset'], inputs, outputs,
tx['metadata'], tx['version'], hash_id=tx['id']) | def from_dict(cls, tx) | Transforms a Python dictionary to a Transaction object.
Args:
tx_body (dict): The Transaction to be transformed.
Returns:
:class:`~bigchaindb.common.transaction.Transaction` | 3.495541 | 3.793565 | 0.921439 |
query = []
encoders = {dict: _dictionary_encoder}
for k, v in dictionary.iteritems():
if v.__class__ in encoders:
nested_query = encoders[v.__class__](k, v)
query += nested_query
else:
key = to_utf8(k)
value = to_utf8(v)
query.... | def dict2query(dictionary) | We want post vars of form:
{'foo': 'bar', 'nested': {'a': 'b', 'c': 'd'}}
to become:
foo=bar&nested[a]=b&nested[c]=d | 3.230972 | 2.966619 | 1.089109 |
self.found_visible = False
is_multi_quote_header = self.MULTI_QUOTE_HDR_REGEX_MULTILINE.search(self.text)
if is_multi_quote_header:
self.text = self.MULTI_QUOTE_HDR_REGEX.sub(is_multi_quote_header.groups()[0].replace('\n', ''), self.text)
# Fix any outlook style r... | def read(self) | Creates new fragment for each line
and labels as a signature, quote, or hidden.
Returns EmailMessage instance | 5.951473 | 5.442143 | 1.09359 |
reply = []
for f in self.fragments:
if not (f.hidden or f.quoted):
reply.append(f.content)
return '\n'.join(reply) | def reply(self) | Captures reply message within email | 5.039784 | 5.047954 | 0.998382 |
is_quote_header = self.QUOTE_HDR_REGEX.match(line) is not None
is_quoted = self.QUOTED_REGEX.match(line) is not None
is_header = is_quote_header or self.HEADER_REGEX.match(line) is not None
if self.fragment and len(line.strip()) == 0:
if self.SIG_REGEX.match(self.fr... | def _scan_line(self, line) | Reviews each line in email message and determines fragment type
line - a row of text from an email message | 3.240917 | 3.080254 | 1.052159 |
if self.fragment:
self.fragment.finish()
if self.fragment.headers:
# Regardless of what's been seen to this point, if we encounter a headers fragment,
# all the previous fragments should be marked hidden and found_visible set to False.
... | def _finish_fragment(self) | Creates fragment | 4.879507 | 4.712088 | 1.03553 |
self.lines.reverse()
self._content = '\n'.join(self.lines)
self.lines = None | def finish(self) | Creates block of content with lines
belonging to fragment. | 6.237521 | 4.464978 | 1.396988 |
if not src_tstamp_str:
return False
res = src_tstamp_str
if src_format and dst_format:
try:
# dt_value needs to be a datetime.datetime object\
# (so notime.struct_time or mx.DateTime.DateTime here!)
dt_value = datetime.datetime.strptime(src_tstamp_str... | def _offset_format_timestamp1(src_tstamp_str, src_format, dst_format,
ignore_unparsable_time=True, context=None) | Convert a source timeStamp string into a destination timeStamp string,
attempting to apply the correct offset if both the server and local
timeZone are recognized,or no offset at all if they aren't or if
tz_offset is false (i.e. assuming they are both in the same TZ).
@param src_tstamp_str: the STR val... | 3.373677 | 3.444784 | 0.979358 |
'''
Based on isroom, status will be updated.
----------------------------------------
@param self: object pointer
'''
if self.isroom is False:
self.status = 'occupied'
if self.isroom is True:
self.status = 'available' | def isroom_change(self) | Based on isroom, status will be updated.
----------------------------------------
@param self: object pointer | 6.723926 | 2.529268 | 2.658447 |
if 'isroom' in vals and vals['isroom'] is False:
vals.update({'color': 2, 'status': 'occupied'})
if 'isroom'in vals and vals['isroom'] is True:
vals.update({'color': 5, 'status': 'available'})
ret_val = super(HotelRoom, self).write(vals)
return ret_val | def write(self, vals) | Overrides orm write method.
@param self: The object pointer
@param vals: dictionary of fields value. | 3.92313 | 3.790363 | 1.035028 |
'''
This method is used to validate the room_lines.
------------------------------------------------
@param self: object pointer
@return: raise warning depending on the validation
'''
folio_rooms = []
for room in self[0].room_lines:
if room.pro... | def folio_room_lines(self) | This method is used to validate the room_lines.
------------------------------------------------
@param self: object pointer
@return: raise warning depending on the validation | 6.811605 | 3.524737 | 1.932515 |
'''
This method gives the duration between check in and checkout
if customer will leave only for some hour it would be considers
as a whole day.If customer will check in checkout for more or equal
hours, which configured in company as additional hours than it would
be con... | def onchange_dates(self) | This method gives the duration between check in and checkout
if customer will leave only for some hour it would be considers
as a whole day.If customer will check in checkout for more or equal
hours, which configured in company as additional hours than it would
be consider as full days
... | 5.967069 | 2.849905 | 2.093778 |
if not 'service_lines' and 'folio_id' in vals:
tmp_room_lines = vals.get('room_lines', [])
vals['order_policy'] = vals.get('hotel_policy', 'manual')
vals.update({'room_lines': []})
folio_id = super(HotelFolio, self).create(vals)
for line in (t... | def create(self, vals, check=True) | Overrides orm create method.
@param self: The object pointer
@param vals: dictionary of fields value.
@return: new record set for hotel folio. | 2.447994 | 2.333352 | 1.049132 |
product_obj = self.env['product.product']
h_room_obj = self.env['hotel.room']
folio_room_line_obj = self.env['folio.room.line']
room_lst = []
room_lst1 = []
for rec in self:
for res in rec.room_lines:
room_lst1.append(res.product_id.id... | def write(self, vals) | Overrides orm write method.
@param self: The object pointer
@param vals: dictionary of fields value. | 2.431879 | 2.435675 | 0.998442 |
'''
When you change partner_id it will update the partner_invoice_id,
partner_shipping_id and pricelist_id of the hotel folio as well
---------------------------------------------------------------
@param self: object pointer
'''
if self.partner_id:
pa... | def onchange_partner_id(self) | When you change partner_id it will update the partner_invoice_id,
partner_shipping_id and pricelist_id of the hotel folio as well
---------------------------------------------------------------
@param self: object pointer | 2.962501 | 1.906669 | 1.553758 |
'''
This method is used to validate the checkin_date and checkout_date.
-------------------------------------------------------------------
@param self: object pointer
@return: raise warning depending on the validation
'''
if self.checkin_date >= self.checkout_dat... | def check_dates(self) | This method is used to validate the checkin_date and checkout_date.
-------------------------------------------------------------------
@param self: object pointer
@return: raise warning depending on the validation | 6.182559 | 3.686477 | 1.677091 |
sale_line_obj = self.env['sale.order.line']
fr_obj = self.env['folio.room.line']
for line in self:
if line.order_line_id:
sale_unlink_obj = (sale_line_obj.browse
([line.order_line_id.id]))
for rec in sale_unl... | def unlink(self) | Overrides orm unlink method.
@param self: The object pointer
@return: True/False. | 3.856467 | 4.009447 | 0.961845 |
'''
- @param self: object pointer
- '''
context = dict(self._context)
if not context:
context = {}
if context.get('folio', False):
if self.product_id and self.folio_id.partner_id:
self.name = self.product_id.name
sel... | def product_id_change(self) | - @param self: object pointer
- | 2.875836 | 2.677563 | 1.07405 |
'''
When you change checkin_date or checkout_date it will checked it
and update the qty of hotel folio line
-----------------------------------------------------------------
@param self: object pointer
'''
configured_addition_hours = 0
fwhouse_id = self.fo... | def on_change_checkout(self) | When you change checkin_date or checkout_date it will checked it
and update the qty of hotel folio line
-----------------------------------------------------------------
@param self: object pointer | 3.07836 | 2.560023 | 1.202474 |
if 'folio_id' in vals:
folio = self.env['hotel.folio'].browse(vals['folio_id'])
vals.update({'order_id': folio.order_id.id})
return super(HotelServiceLine, self).create(vals) | def create(self, vals, check=True) | Overrides orm create method.
@param self: The object pointer
@param vals: dictionary of fields value.
@return: new record set for hotel service line. | 3.620851 | 3.044405 | 1.189346 |
s_line_obj = self.env['sale.order.line']
for line in self:
if line.service_line_id:
sale_unlink_obj = s_line_obj.browse([line.service_line_id.id])
sale_unlink_obj.unlink()
return super(HotelServiceLine, self).unlink() | def unlink(self) | Overrides orm unlink method.
@param self: The object pointer
@return: True/False. | 4.562912 | 4.640032 | 0.983379 |
'''
When you change checkin_date or checkout_date it will checked it
and update the qty of hotel service line
-----------------------------------------------------------------
@param self: object pointer
'''
if not self.ser_checkin_date:
time_a = time.... | def on_change_checkout(self) | When you change checkin_date or checkout_date it will checked it
and update the qty of hotel service line
-----------------------------------------------------------------
@param self: object pointer | 3.509807 | 2.256855 | 1.555176 |
reservation_line_obj = self.env['hotel.room.reservation.line']
room_obj = self.env['hotel.room']
prod_id = vals.get('product_id') or self.product_id.id
chkin = vals.get('checkin_date') or self.checkin_date
chkout = vals.get('checkout_date') or self.checkout_date
... | def write(self, vals) | Overrides orm write method.
@param self: The object pointer
@param vals: dictionary of fields value.
Update Hotel Room Reservation line history | 2.539919 | 2.35719 | 1.07752 |
for reserv_rec in self:
if reserv_rec.state != 'draft':
raise ValidationError(_('You cannot delete Reservation in %s\
state.') % (reserv_rec.state))
return super(HotelReservation, self).unlink() | def unlink(self) | Overrides orm unlink method.
@param self: The object pointer
@return: True/False. | 5.883389 | 6.532341 | 0.900656 |
'''
This method is used to validate the reservation_line.
-----------------------------------------------------
@param self: object pointer
@return: raise a warning depending on the validation
'''
ctx = dict(self._context) or {}
for reservation in self:
... | def check_reservation_rooms(self) | This method is used to validate the reservation_line.
-----------------------------------------------------
@param self: object pointer
@return: raise a warning depending on the validation | 5.948163 | 4.226774 | 1.407258 |
if self.checkout and self.checkin:
if self.checkin < self.date_order:
raise ValidationError(_('Check-in date should be greater than \
the current date.'))
if self.checkout < self.checkin:
raise ValidationEr... | def check_in_out_dates(self) | When date_order is less then check-in date or
Checkout date should be greater than the check-in date. | 3.363086 | 2.523886 | 1.332503 |
'''
When you change checkout or checkin update dummy field
-----------------------------------------------------------
@param self: object pointer
@return: raise warning depending on the validation
'''
checkout_date = time.strftime(dt)
checkin_date = time.... | def on_change_checkout(self) | When you change checkout or checkin update dummy field
-----------------------------------------------------------
@param self: object pointer
@return: raise warning depending on the validation | 9.020914 | 3.997936 | 2.256393 |
'''
When you change partner_id it will update the partner_invoice_id,
partner_shipping_id and pricelist_id of the hotel reservation as well
---------------------------------------------------------------------
@param self: object pointer
'''
if not self.partner_id... | def onchange_partner_id(self) | When you change partner_id it will update the partner_invoice_id,
partner_shipping_id and pricelist_id of the hotel reservation as well
---------------------------------------------------------------------
@param self: object pointer | 3.205991 | 1.914947 | 1.674193 |
if not vals:
vals = {}
vals['reservation_no'] = self.env['ir.sequence'].\
next_by_code('hotel.reservation') or 'New'
return super(HotelReservation, self).create(vals) | def create(self, vals) | Overrides orm create method.
@param self: The object pointer
@param vals: dictionary of fields value. | 4.151074 | 4.839298 | 0.857784 |
reservation_line_obj = self.env['hotel.room.reservation.line']
vals = {}
for reservation in self:
reserv_checkin = datetime.strptime(reservation.checkin, dt)
reserv_checkout = datetime.strptime(reservation.checkout, dt)
room_bool = False
f... | def confirmed_reservation(self) | This method create a new record set for hotel room reservation line
-------------------------------------------------------------------
@param self: The object pointer
@return: new record set for hotel room reservation line. | 2.191356 | 2.170888 | 1.009428 |
room_res_line_obj = self.env['hotel.room.reservation.line']
hotel_res_line_obj = self.env['hotel_reservation.line']
self.state = 'cancel'
room_reservation_line = room_res_line_obj.search([('reservation_id',
'in', self.id... | def cancel_reservation(self) | This method cancel record set for hotel room reservation line
------------------------------------------------------------------
@param self: The object pointer
@return: cancel record set for hotel room reservation line. | 3.719143 | 3.563574 | 1.043655 |
'''
This function opens a window to compose an email,
template message loaded by default.
@param self: object pointer
'''
assert len(self._ids) == 1, 'This is for a single id at a time.'
ir_model_data = self.env['ir.model.data']
try:
template_i... | def send_reservation_maill(self) | This function opens a window to compose an email,
template message loaded by default.
@param self: object pointer | 2.461405 | 2.000889 | 1.230155 |
now_str = time.strftime(dt)
now_date = datetime.strptime(now_str, dt)
ir_model_data = self.env['ir.model.data']
template_id = (ir_model_data.get_object_reference
('hotel_reservation',
'mail_template_reservation_reminder_24hrs')[1])
... | def reservation_reminder_24hrs(self) | This method is for scheduler
every 1day scheduler will call this method to
find all tomorrow's reservations.
----------------------------------------------
@param self: The object pointer
@return: send a mail | 3.433583 | 3.411105 | 1.00659 |
hotel_folio_obj = self.env['hotel.folio']
room_obj = self.env['hotel.room']
for reservation in self:
folio_lines = []
checkin_date = reservation['checkin']
checkout_date = reservation['checkout']
if not self.checkin < self.checkout:
... | def create_folio(self) | This method is for create new hotel folio.
-----------------------------------------
@param self: The object pointer
@return: new record set for hotel folio. | 2.907565 | 2.873461 | 1.011869 |
'''
This method gives the duration between check in checkout if
customer will leave only for some hour it would be considers
as a whole day. If customer will checkin checkout for more or equal
hours, which configured in company as additional hours than it would
be conside... | def onchange_check_dates(self, checkin_date=False, checkout_date=False,
duration=False) | This method gives the duration between check in checkout if
customer will leave only for some hour it would be considers
as a whole day. If customer will checkin checkout for more or equal
hours, which configured in company as additional hours than it would
be consider as full days
... | 6.713411 | 2.566217 | 2.616073 |
'''
When you change categ_id it check checkin and checkout are
filled or not if not then raise warning
-----------------------------------------------------------
@param self: object pointer
'''
hotel_room_obj = self.env['hotel.room']
hotel_room_ids = hote... | def on_change_categ(self) | When you change categ_id it check checkin and checkout are
filled or not if not then raise warning
-----------------------------------------------------------
@param self: object pointer | 2.483078 | 2.00445 | 1.238783 |
hotel_room_reserv_line_obj = self.env['hotel.room.reservation.line']
for reserv_rec in self:
for rec in reserv_rec.reserve:
hres_arg = [('room_id', '=', rec.id),
('reservation_id', '=', reserv_rec.line_id.id)]
myobj = hotel... | def unlink(self) | Overrides orm unlink method.
@param self: The object pointer
@return: True/False. | 4.793241 | 4.821029 | 0.994236 |
for room in self:
for reserv_line in room.room_reservation_line_ids:
if reserv_line.status == 'confirm':
raise ValidationError(_('User is not able to delete the \
room after the room in %s state \
... | def unlink(self) | Overrides orm unlink method.
@param self: The object pointer
@return: True/False. | 8.007172 | 8.429746 | 0.949871 |
reservation_line_obj = self.env['hotel.room.reservation.line']
folio_room_line_obj = self.env['folio.room.line']
now = datetime.now()
curr_date = now.strftime(dt)
for room in self.search([]):
reserv_line_ids = [reservation_line.id for
... | def cron_room_line(self) | This method is for scheduler
every 1min scheduler will call this method and check Status of
room is occupied or available
--------------------------------------------------------------
@param self: The object pointer
@return: update status of hotel room reservation line | 2.770008 | 2.704651 | 1.024165 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.