Datasets:

function_name
stringlengths
1
63
docstring
stringlengths
50
5.89k
masked_code
stringlengths
50
882k
implementation
stringlengths
169
12.9k
start_line
int32
1
14.6k
end_line
int32
16
14.6k
file_content
stringlengths
274
882k
__init__
Initializes Diagnostic with neccessary attributes. Args: intro: A message to introduce the objectives and tasks of the diagnostic. title: The name of the diagnostic. checklist: An iterable of checkbase.Check objects to be run by the diagnostic.
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
def __init__(self, intro, title, checklist): """Initializes Diagnostic with neccessary attributes. Args: intro: A message to introduce the objectives and tasks of the diagnostic. title: The name of the diagnostic. checklist: An iterable of checkbase.Check objects to be run by the d...
34
45
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
RunChecks
Runs one or more checks, tries fixes, and outputs results. Returns: True if the diagnostic ultimately passed.
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
def RunChecks(self): """Runs one or more checks, tries fixes, and outputs results. Returns: True if the diagnostic ultimately passed. """ self._Print(self.intro) num_checks_passed = 0 for check in self.checklist: result, fixer = self._RunCheck(check) if properties.VALUES.c...
47
85
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
_assert_proper_exception_context
assert that any exception we're catching does not have a __context__ without a __cause__, and that __suppress_context__ is never set. Python 3 will report nested as exceptions as "during the handling of error X, error Y occurred". That's not what we want to do. we want these exceptions in a cause chain.
# testing/assertions.py # Copyright (C) 2005-2021 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from __future__ import absolute_import import contextlib import re import sys...
def _assert_proper_exception_context(exception): """assert that any exception we're catching does not have a __context__ without a __cause__, and that __suppress_context__ is never set. Python 3 will report nested as exceptions as "during the handling of error X, error Y occurred". That's not what we w...
288
309
# testing/assertions.py # Copyright (C) 2005-2021 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from __future__ import absolute_import import contextlib import re import sys...
dict_scrape
Scrapes a dictionary for a given part of speech. POS tags in POS_tags. POS(str), dictionaryfile(str-of-filename) -> list-of-strings
import sys ##print ("This is the name of the script: ", sys.argv[0]) ##print ("Number of arguments: ", len(sys.argv)) ##print ("The arguments are: " , str(sys.argv)) lemmas = [] lemmas_cleaned = [] nums = ['1','2','3','4','5','6','7','8','9','0'] alphabet = ['a','b','c','d','e','f','g','h','i','j','k','k','l','m','n',...
def dict_scrape(POS, dictionaryfile='as_freq.txt'): """Scrapes a dictionary for a given part of speech. POS tags in POS_tags. POS(str), dictionaryfile(str-of-filename) -> list-of-strings """ if POS in POS_tags: with open(dictionaryfile) as to_scrape: for line in to_scrape: ...
22
42
import sys ##print ("This is the name of the script: ", sys.argv[0]) ##print ("Number of arguments: ", len(sys.argv)) ##print ("The arguments are: " , str(sys.argv)) lemmas = [] lemmas_cleaned = [] nums = ['1','2','3','4','5','6','7','8','9','0'] alphabet = ['a','b','c','d','e','f','g','h','i','j','k','k','l','m','n',...
gcor
Compute the :abbr:`GCOR (global correlation)`. :param numpy.ndarray func: input fMRI dataset, after motion correction :param numpy.ndarray mask: 3D brain mask :return: the computed GCOR value
#!/usr/bin/env python # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # pylint: disable=no-member # # @Author: oesteban # @Date: 2016-02-23 19:25:39 # @Email: code@oscaresteban.es # @Last Modified by: oesteban # @Last Modifie...
def gcor(func, mask): """ Compute the :abbr:`GCOR (global correlation)`. :param numpy.ndarray func: input fMRI dataset, after motion correction :param numpy.ndarray mask: 3D brain mask :return: the computed GCOR value """ # Remove zero-variance voxels across time axis tv_mask = zero_va...
246
260
#!/usr/bin/env python # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # pylint: disable=no-member # # @Author: oesteban # @Date: 2016-02-23 19:25:39 # @Email: code@oscaresteban.es # @Last Modified by: oesteban # @Last Modifie...
get
Wait until task is ready, and return its result. .. warning:: Waiting for tasks within a task may lead to deadlocks. Please read :ref:`task-synchronous-subtasks`. :keyword timeout: How long to wait, in seconds, before the operation times out. :keyword propagate: Re-raise exception if the task...
# -*- coding: utf-8 -*- """ celery.result ~~~~~~~~~~~~~ Task results/state and groups of results. """ from __future__ import absolute_import import time import warnings from collections import deque from contextlib import contextmanager from copy import copy from kombu.utils import cached_property from...
def get(self, timeout=None, propagate=True, interval=0.5, no_ack=True, follow_parents=True, EXCEPTION_STATES=states.EXCEPTION_STATES, PROPAGATE_STATES=states.PROPAGATE_STATES): """Wait until task is ready, and return its result. .. warning:: Waiting f...
123
176
# -*- coding: utf-8 -*- """ celery.result ~~~~~~~~~~~~~ Task results/state and groups of results. """ from __future__ import absolute_import import time import warnings from collections import deque from contextlib import contextmanager from copy import copy from kombu.utils import cached_property from...
iter_native
Backend optimized version of :meth:`iterate`. .. versionadded:: 2.2 Note that this does not support collecting the results for different task types using different backends. This is currently only supported by the amqp, Redis and cache result backends.
# -*- coding: utf-8 -*- """ celery.result ~~~~~~~~~~~~~ Task results/state and groups of results. """ from __future__ import absolute_import import time import warnings from collections import deque from contextlib import contextmanager from copy import copy from kombu.utils import cached_property from...
def iter_native(self, timeout=None, interval=0.5, no_ack=True): """Backend optimized version of :meth:`iterate`. .. versionadded:: 2.2 Note that this does not support collecting the results for different task types using different backends. This is currently only supported...
650
668
# -*- coding: utf-8 -*- """ celery.result ~~~~~~~~~~~~~ Task results/state and groups of results. """ from __future__ import absolute_import import time import warnings from collections import deque from contextlib import contextmanager from copy import copy from kombu.utils import cached_property from...
get_prepared_model
Function creates ANN model and compile. Args: stage ([str]): stage of experiment no_classes ([INT]): No of classes for classification input_shape ([int, int]): Input shape for model's input layer loss ([str]): Loss function for model optimizer ([str]): Optimizer for model metrics ([str]): Metric...
import tensorflow as tf from tensorflow.keras.models import Model import pandas as pd import matplotlib.pyplot as plt import os import logging from .common import create_directories # MASKED: get_prepared_model function (lines 12-80) def save_model(model_dir: str, model: Model, model_suffix: str) -> None: """...
def get_prepared_model(stage: str, no_classes: int, input_shape: list, loss: str, optimizer: str, metrics: list) -> \ Model: """Function creates ANN model and compile. Args: stage ([str]): stage of experiment no_classes ([INT]): No of classes for classification input_shape ([int,...
12
80
import tensorflow as tf from tensorflow.keras.models import Model import pandas as pd import matplotlib.pyplot as plt import os import logging from .common import create_directories def get_prepared_model(stage: str, no_classes: int, input_shape: list, loss: str, optimizer: str, metrics: list) -> \ Model: ...
save_model
args: model_dir: directory to save the model model: model object to save model_suffix: Suffix to save the model
import tensorflow as tf from tensorflow.keras.models import Model import pandas as pd import matplotlib.pyplot as plt import os import logging from .common import create_directories def get_prepared_model(stage: str, no_classes: int, input_shape: list, loss: str, optimizer: str, metrics: list) -> \ Model: ...
def save_model(model_dir: str, model: Model, model_suffix: str) -> None: """ args: model_dir: directory to save the model model: model object to save model_suffix: Suffix to save the model """ create_directories([model_dir]) model_file = os.path.join(model_dir, f"{model_suffi...
83
93
import tensorflow as tf from tensorflow.keras.models import Model import pandas as pd import matplotlib.pyplot as plt import os import logging from .common import create_directories def get_prepared_model(stage: str, no_classes: int, input_shape: list, loss: str, optimizer: str, metrics: list) -> \ Model: ...
save_history_plot
Args: history: History object for plotting loss/accuracy curves plot_dir: Directory to save plot files stage: Stage name for training
import tensorflow as tf from tensorflow.keras.models import Model import pandas as pd import matplotlib.pyplot as plt import os import logging from .common import create_directories def get_prepared_model(stage: str, no_classes: int, input_shape: list, loss: str, optimizer: str, metrics: list) -> \ Model: ...
def save_history_plot(history, plot_dir: str, stage: str) -> None: """ Args: history: History object for plotting loss/accuracy curves plot_dir: Directory to save plot files stage: Stage name for training """ pd.DataFrame(history.history).plot(figsize=(10, 8)) plt.grid(True) ...
96
108
import tensorflow as tf from tensorflow.keras.models import Model import pandas as pd import matplotlib.pyplot as plt import os import logging from .common import create_directories def get_prepared_model(stage: str, no_classes: int, input_shape: list, loss: str, optimizer: str, metrics: list) -> \ Model: ...
get_callbacks
Args: checkpoint_dir: Directory to save the model at checkpoint tensorboard_logs: Directory to save tensorboard logs stage: Stage name for training Returns: callback_list: List of created callbacks
import tensorflow as tf from tensorflow.keras.models import Model import pandas as pd import matplotlib.pyplot as plt import os import logging from .common import create_directories def get_prepared_model(stage: str, no_classes: int, input_shape: list, loss: str, optimizer: str, metrics: list) -> \ Model: ...
def get_callbacks(checkpoint_dir: str, tensorboard_logs: str, stage: str) -> list: """ Args: checkpoint_dir: Directory to save the model at checkpoint tensorboard_logs: Directory to save tensorboard logs stage: Stage name for training Returns: callback_list: List of created c...
111
128
import tensorflow as tf from tensorflow.keras.models import Model import pandas as pd import matplotlib.pyplot as plt import os import logging from .common import create_directories def get_prepared_model(stage: str, no_classes: int, input_shape: list, loss: str, optimizer: str, metrics: list) -> \ Model: ...
create_order
Create an order. Args: symbol: Trade target action: Trade direction, `BUY` or `SELL`. price: Price of each contract. quantity: The buying or selling quantity. order_type: Order type, `MARKET` or `LIMIT`. Returns: order_no: Order ID if created successfully, otherwise it's None. error: Error...
# -*- coding:utf-8 -*- """ FTX Trade module. https://docs.ftx.com/ Project: alphahunter Author: HJQuant Description: Asynchronous driven quantitative trading framework """ import time import zlib import json import copy import hmac import base64 from urllib.parse import urljoin from collections import defaultdict, d...
async def create_order(self, symbol, action, price, quantity, order_type=ORDER_TYPE_LIMIT, *args, **kwargs): """ Create an order. Args: symbol: Trade target action: Trade direction, `BUY` or `SELL`. price: Price of each contract. quantity: The buying ...
231
273
# -*- coding:utf-8 -*- """ FTX Trade module. https://docs.ftx.com/ Project: alphahunter Author: HJQuant Description: Asynchronous driven quantitative trading framework """ import time import zlib import json import copy import hmac import base64 from urllib.parse import urljoin from collections import defaultdict, d...
revoke_order
Revoke (an) order(s). Args: symbol: Trade target order_nos: Order id list, you can set this param to 0 or multiple items. If you set 0 param, you can cancel all orders for this symbol. If you set 1 or multiple param, you can cancel an or multiple order. Returns: 删除全部订单情况: 成功=(True, None), 失败=(False, ...
# -*- coding:utf-8 -*- """ FTX Trade module. https://docs.ftx.com/ Project: alphahunter Author: HJQuant Description: Asynchronous driven quantitative trading framework """ import time import zlib import json import copy import hmac import base64 from urllib.parse import urljoin from collections import defaultdict, d...
async def revoke_order(self, symbol, *order_nos): """ Revoke (an) order(s). Args: symbol: Trade target order_nos: Order id list, you can set this param to 0 or multiple items. If you set 0 param, you can cancel all orders for this symbol. If you set 1 or multipl...
275
304
# -*- coding:utf-8 -*- """ FTX Trade module. https://docs.ftx.com/ Project: alphahunter Author: HJQuant Description: Asynchronous driven quantitative trading framework """ import time import zlib import json import copy import hmac import base64 from urllib.parse import urljoin from collections import defaultdict, d...
get_assets
获取交易账户资产信息 Args: None Returns: assets: Asset if successfully, otherwise it's None. error: Error information, otherwise it's None.
# -*- coding:utf-8 -*- """ FTX Trade module. https://docs.ftx.com/ Project: alphahunter Author: HJQuant Description: Asynchronous driven quantitative trading framework """ import time import zlib import json import copy import hmac import base64 from urllib.parse import urljoin from collections import defaultdict, d...
async def get_assets(self): """ 获取交易账户资产信息 Args: None Returns: assets: Asset if successfully, otherwise it's None. error: Error information, otherwise it's None. """ #{"result": {"backstopProvider": false, "collateral": 110.09426...
306
346
# -*- coding:utf-8 -*- """ FTX Trade module. https://docs.ftx.com/ Project: alphahunter Author: HJQuant Description: Asynchronous driven quantitative trading framework """ import time import zlib import json import copy import hmac import base64 from urllib.parse import urljoin from collections import defaultdict, d...
get_orders
获取当前挂单列表 Args: symbol: Trade target Returns: orders: Order list if successfully, otherwise it's None. error: Error information, otherwise it's None.
# -*- coding:utf-8 -*- """ FTX Trade module. https://docs.ftx.com/ Project: alphahunter Author: HJQuant Description: Asynchronous driven quantitative trading framework """ import time import zlib import json import copy import hmac import base64 from urllib.parse import urljoin from collections import defaultdict, d...
async def get_orders(self, symbol): """ 获取当前挂单列表 Args: symbol: Trade target Returns: orders: Order list if successfully, otherwise it's None. error: Error information, otherwise it's None. """ #{"result": [{"avgFillPrice": null, ...
389
418
# -*- coding:utf-8 -*- """ FTX Trade module. https://docs.ftx.com/ Project: alphahunter Author: HJQuant Description: Asynchronous driven quantitative trading framework """ import time import zlib import json import copy import hmac import base64 from urllib.parse import urljoin from collections import defaultdict, d...
get_position
获取当前持仓 Args: symbol: Trade target Returns: position: Position if successfully, otherwise it's None. error: Error information, otherwise it's None.
# -*- coding:utf-8 -*- """ FTX Trade module. https://docs.ftx.com/ Project: alphahunter Author: HJQuant Description: Asynchronous driven quantitative trading framework """ import time import zlib import json import copy import hmac import base64 from urllib.parse import urljoin from collections import defaultdict, d...
async def get_position(self, symbol): """ 获取当前持仓 Args: symbol: Trade target Returns: position: Position if successfully, otherwise it's None. error: Error information, otherwise it's None. """ #{"result": [{"collateralUsed": 0.35...
420
485
# -*- coding:utf-8 -*- """ FTX Trade module. https://docs.ftx.com/ Project: alphahunter Author: HJQuant Description: Asynchronous driven quantitative trading framework """ import time import zlib import json import copy import hmac import base64 from urllib.parse import urljoin from collections import defaultdict, d...
get_symbol_info
获取指定符号相关信息 Args: symbol: Trade target Returns: symbol_info: SymbolInfo if successfully, otherwise it's None. error: Error information, otherwise it's None.
# -*- coding:utf-8 -*- """ FTX Trade module. https://docs.ftx.com/ Project: alphahunter Author: HJQuant Description: Asynchronous driven quantitative trading framework """ import time import zlib import json import copy import hmac import base64 from urllib.parse import urljoin from collections import defaultdict, d...
async def get_symbol_info(self, symbol): """ 获取指定符号相关信息 Args: symbol: Trade target Returns: symbol_info: SymbolInfo if successfully, otherwise it's None. error: Error information, otherwise it's None. """ """ { "success": ...
487
537
# -*- coding:utf-8 -*- """ FTX Trade module. https://docs.ftx.com/ Project: alphahunter Author: HJQuant Description: Asynchronous driven quantitative trading framework """ import time import zlib import json import copy import hmac import base64 from urllib.parse import urljoin from collections import defaultdict, d...
_RleCompress
Compresses mask using Run-length encoding provided by pycocotools. Args: masks: uint8 numpy array of shape [mask_height, mask_width] with values in {0, 1}. Returns: A pycocotools Run-length encoding of the mask.
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def _RleCompress(masks): """Compresses mask using Run-length encoding provided by pycocotools. Args: masks: uint8 numpy array of shape [mask_height, mask_width] with values in {0, 1}. Returns: A pycocotools Run-length encoding of the mask. """ rle = mask.encode(np.asfortranarray(masks)) rle['c...
347
359
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ExportGroundtruthToCOCO
Export groundtruth detection annotations in numpy arrays to COCO API. This function converts a set of groundtruth detection annotations represented as numpy arrays to dictionaries that can be ingested by the COCO API. Inputs to this function are three lists: image ids for each groundtruth image, groundtruth boxes for ...
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def ExportGroundtruthToCOCO(image_ids, groundtruth_boxes, groundtruth_classes, categories, output_path=None): """Export groundtruth detection annotations in numpy arrays to COCO API. This function conver...
484
556
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ExportSingleImageDetectionBoxesToCoco
Export detections of a single image to COCO format. This function converts detections represented as numpy arrays to dictionaries that can be ingested by the COCO evaluation API. Note that the image_ids provided here must match the ones given to the ExporSingleImageDetectionBoxesToCoco. We assume that boxes, and class...
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def ExportSingleImageDetectionBoxesToCoco(image_id, category_id_set, detection_boxes, detection_scores, detection_classes, ...
559
650
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ExportSingleImageDetectionMasksToCoco
Export detection masks of a single image to COCO format. This function converts detections represented as numpy arrays to dictionaries that can be ingested by the COCO evaluation API. We assume that detection_masks, detection_scores, and detection_classes are in correspondence - that is: detection_masks[i, :], detecti...
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def ExportSingleImageDetectionMasksToCoco(image_id, category_id_set, detection_masks, detection_scores, detection_classes): """Export detection masks ...
653
708
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
__init__
COCOEvalWrapper constructor. Note that for the area-based metrics to be meaningful, detection and groundtruth boxes must be in image coordinates measured in pixels. Args: groundtruth: a coco.COCO (or coco_tools.COCOWrapper) object holding groundtruth annotations detections: a coco.COCO (or coco_tools.COCOWrap...
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def __init__(self, groundtruth=None, detections=None, agnostic_mode=False, iou_type='bbox', oks_sigmas=None): """COCOEvalWrapper constructor. Note that for the area-based metrics to be meaningful, detection and groundtruth boxes must be in image coordinates measured in pixels. Args: ...
160
183
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
validate
Validate the configuration dialog fields. For any field that is not valid set the style sheet to the INVALID_STYLE_SHEET. Return the outcome of the overall validity of the configuration.
import os from PySide2 import QtWidgets from mapclientplugins.filechooserstep.ui_configuredialog import Ui_ConfigureDialog INVALID_STYLE_SHEET = 'background-color: rgba(239, 0, 0, 50)' DEFAULT_STYLE_SHEET = '' class ConfigureDialog(QtWidgets.QDialog): """ Configure dialog to present the user with the optio...
def validate(self): """ Validate the configuration dialog fields. For any field that is not valid set the style sheet to the INVALID_STYLE_SHEET. Return the outcome of the overall validity of the configuration. """ # Determine if the current identifier is unique thr...
81
101
import os from PySide2 import QtWidgets from mapclientplugins.filechooserstep.ui_configuredialog import Ui_ConfigureDialog INVALID_STYLE_SHEET = 'background-color: rgba(239, 0, 0, 50)' DEFAULT_STYLE_SHEET = '' class ConfigureDialog(QtWidgets.QDialog): """ Configure dialog to present the user with the optio...
split_section
Split a pipfile or a lockfile section out by section name and test function :param dict input_file: A dictionary containing either a pipfile or lockfile :param str section_suffix: A string of the name of the section :param func test_function: A test function to test against the value in the key/value pair ...
# -*- coding: utf-8 -*- import errno import os import re import hashlib import tempfile import sys import shutil import logging import click import crayons import delegator import parse import requests import six import stat import warnings try: from weakref import finalize except ImportError: try: fro...
def split_section(input_file, section_suffix, test_function): """ Split a pipfile or a lockfile section out by section name and test function :param dict input_file: A dictionary containing either a pipfile or lockfile :param str section_suffix: A string of the name of the section :para...
898
942
# -*- coding: utf-8 -*- import errno import os import re import hashlib import tempfile import sys import shutil import logging import click import crayons import delegator import parse import requests import six import stat import warnings try: from weakref import finalize except ImportError: try: fro...
normalize_drive
Normalize drive in path so they stay consistent. This currently only affects local drives on Windows, which can be identified with either upper or lower cased drive names. The case is always converted to uppercase because it seems to be preferred. See: <https://github.com/pypa/pipenv/issues/1218>
# -*- coding: utf-8 -*- import errno import os import re import hashlib import tempfile import sys import shutil import logging import click import crayons import delegator import parse import requests import six import stat import warnings try: from weakref import finalize except ImportError: try: fro...
def normalize_drive(path): """Normalize drive in path so they stay consistent. This currently only affects local drives on Windows, which can be identified with either upper or lower cased drive names. The case is always converted to uppercase because it seems to be preferred. See: <https://github...
1,164
1,181
# -*- coding: utf-8 -*- import errno import os import re import hashlib import tempfile import sys import shutil import logging import click import crayons import delegator import parse import requests import six import stat import warnings try: from weakref import finalize except ImportError: try: fro...
is_readonly_path
Check if a provided path exists and is readonly. Permissions check is `bool(path.stat & stat.S_IREAD)` or `not os.access(path, os.W_OK)`
# -*- coding: utf-8 -*- import errno import os import re import hashlib import tempfile import sys import shutil import logging import click import crayons import delegator import parse import requests import six import stat import warnings try: from weakref import finalize except ImportError: try: fro...
def is_readonly_path(fn): """Check if a provided path exists and is readonly. Permissions check is `bool(path.stat & stat.S_IREAD)` or `not os.access(path, os.W_OK)` """ if os.path.exists(fn): return (os.stat(fn).st_mode & stat.S_IREAD) or not os.access( fn, os.W_OK ) r...
1,184
1,194
# -*- coding: utf-8 -*- import errno import os import re import hashlib import tempfile import sys import shutil import logging import click import crayons import delegator import parse import requests import six import stat import warnings try: from weakref import finalize except ImportError: try: fro...
download_progress_hook
A hook to report the progress of a download. This is mostly intended for users with slow internet connections. Reports every 5% change in download progress.
import os import sys import tarfile from six.moves.urllib.request import urlretrieve url = 'https://commondatastorage.googleapis.com/books1000/' last_percent_reported = None data_root = '.' # Change me to store data elsewhere # MASKED: download_progress_hook function (lines 11-26) def maybe_download(filename, exp...
def download_progress_hook(count, blockSize, totalSize): """A hook to report the progress of a download. This is mostly intended for users with slow internet connections. Reports every 5% change in download progress. """ global last_percent_reported percent = int(count * blockSize * 100 / totalSize)...
11
26
import os import sys import tarfile from six.moves.urllib.request import urlretrieve url = 'https://commondatastorage.googleapis.com/books1000/' last_percent_reported = None data_root = '.' # Change me to store data elsewhere def download_progress_hook(count, blockSize, totalSize): """A hook to report the progr...
main
The entry point for the console script xbmcswift2. The 'xbcmswift2' script is command bassed, so the second argument is always the command to execute. Each command has its own parser options and usages. If no command is provided or the -h flag is used without any other commands, the general help message is shown.
''' xbmcswift2.cli.cli ------------------ The main entry point for the xbmcswift2 console script. CLI commands can be registered in this module. :copyright: (c) 2012 by Jonathan Beluch :license: GPLv3, see LICENSE for more details. ''' import sys from optparse import OptionParser from xbmcswi...
def main(): '''The entry point for the console script xbmcswift2. The 'xbcmswift2' script is command bassed, so the second argument is always the command to execute. Each command has its own parser options and usages. If no command is provided or the -h flag is used without any other commands, the ...
40
76
''' xbmcswift2.cli.cli ------------------ The main entry point for the xbmcswift2 console script. CLI commands can be registered in this module. :copyright: (c) 2012 by Jonathan Beluch :license: GPLv3, see LICENSE for more details. ''' import sys from optparse import OptionParser ...
compute_benchmark
Compute the scores of a synthesizer over a list of datasets. The results are returned in a raw format as a ``pandas.DataFrame`` containing: - One row for each dataset+scoring method (for example, a classifier) - One column for each computed metric - The columns: - dataset - distance ...
import logging import os import types from datetime import datetime import pandas as pd from sdgym.data import load_dataset from sdgym.evaluate import compute_scores from sdgym.synthesizers import BaseSynthesizer LOGGER = logging.getLogger(__name__) BASE_DIR = os.path.dirname(__file__) LEADERBOARD_PATH = os.path.jo...
def compute_benchmark(synthesizer, datasets=DEFAULT_DATASETS, iterations=3): """Compute the scores of a synthesizer over a list of datasets. The results are returned in a raw format as a ``pandas.DataFrame`` containing: - One row for each dataset+scoring method (for example, a classifier) - One...
36
79
import logging import os import types from datetime import datetime import pandas as pd from sdgym.data import load_dataset from sdgym.evaluate import compute_scores from sdgym.synthesizers import BaseSynthesizer LOGGER = logging.getLogger(__name__) BASE_DIR = os.path.dirname(__file__) LEADERBOARD_PATH = os.path.jo...
_summarize_scores
Computes a summary of the scores obtained by a synthesizer. The raw scores returned by the ``compute_benchmark`` function are summarized by grouping them by dataset and computing the average. The results are then put in a ``pandas.Series`` object with one value per dataset and metric. As an example, the summary of a...
import logging import os import types from datetime import datetime import pandas as pd from sdgym.data import load_dataset from sdgym.evaluate import compute_scores from sdgym.synthesizers import BaseSynthesizer LOGGER = logging.getLogger(__name__) BASE_DIR = os.path.dirname(__file__) LEADERBOARD_PATH = os.path.jo...
def _summarize_scores(scores): """Computes a summary of the scores obtained by a synthesizer. The raw scores returned by the ``compute_benchmark`` function are summarized by grouping them by dataset and computing the average. The results are then put in a ``pandas.Series`` object with one value per ...
90
126
import logging import os import types from datetime import datetime import pandas as pd from sdgym.data import load_dataset from sdgym.evaluate import compute_scores from sdgym.synthesizers import BaseSynthesizer LOGGER = logging.getLogger(__name__) BASE_DIR = os.path.dirname(__file__) LEADERBOARD_PATH = os.path.jo...
_get_synthesizer_name
Get the name of the synthesizer function or class. If the given synthesizer is a function, return its name. If it is a method, return the name of the class to which the method belongs. Args: synthesizer (function or method): The synthesizer function or method. Returns: str: Name of the functi...
import logging import os import types from datetime import datetime import pandas as pd from sdgym.data import load_dataset from sdgym.evaluate import compute_scores from sdgym.synthesizers import BaseSynthesizer LOGGER = logging.getLogger(__name__) BASE_DIR = os.path.dirname(__file__) LEADERBOARD_PATH = os.path.jo...
def _get_synthesizer_name(synthesizer): """Get the name of the synthesizer function or class. If the given synthesizer is a function, return its name. If it is a method, return the name of the class to which the method belongs. Args: synthesizer (function or method): The synthe...
129
149
import logging import os import types from datetime import datetime import pandas as pd from sdgym.data import load_dataset from sdgym.evaluate import compute_scores from sdgym.synthesizers import BaseSynthesizer LOGGER = logging.getLogger(__name__) BASE_DIR = os.path.dirname(__file__) LEADERBOARD_PATH = os.path.jo...
scope_guard
Change the global/default scope instance by Python `with` statement. All variable in runtime will assigned to the new scope. Args: scope: The new global/default scope. Examples: .. code-block:: python import paddle.fluid as fluid import numpy new_scope = fluid.Scope() with fl...
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
@signature_safe_contextmanager def scope_guard(scope): """ Change the global/default scope instance by Python `with` statement. All variable in runtime will assigned to the new scope. Args: scope: The new global/default scope. Examples: .. code-block:: python import pa...
64
87
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
as_numpy
Convert a Tensor to a numpy.ndarray, its only support Tensor without LoD information. For higher dimensional sequence data, please use LoDTensor directly. Examples: .. code-block:: python import paddle.fluid as fluid import numpy new_scope = fluid.Scope() with fluid.scope_guard(new_scope)...
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def as_numpy(tensor): """ Convert a Tensor to a numpy.ndarray, its only support Tensor without LoD information. For higher dimensional sequence data, please use LoDTensor directly. Examples: .. code-block:: python import paddle.fluid as fluid import numpy new_sco...
90
127
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
has_feed_operators
Check whether the block already has feed operators. Return false if the block does not have any feed operators. If some feed operators have been prepended to the block, check that the info contained in these feed operators matches the feed_targets and feed_holder_name. Raise exception when any mismatch is found. Retur...
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def has_feed_operators(block, feed_targets, feed_holder_name): """ Check whether the block already has feed operators. Return false if the block does not have any feed operators. If some feed operators have been prepended to the block, check that the info contained in these feed operators matches the f...
130
165
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
has_fetch_operators
Check whether the block already has fetch operators. Return false if the block does not have any fetch operators. If some fetch operators have been appended to the block, check that the info contained in these fetch operators matches the fetch_targets and fetch_holder_name. Raise exception when any mismatch is found. ...
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def has_fetch_operators(block, fetch_targets, fetch_holder_name): """ Check whether the block already has fetch operators. Return false if the block does not have any fetch operators. If some fetch operators have been appended to the block, check that the info contained in these fetch operators matches...
168
205
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
__init__
Construct Exponential distribution with parameter `rate`. Args: rate: Floating point tensor, equivalent to `1 / mean`. Must contain only positive values. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime perfor...
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def __init__(self, rate, validate_args=False, allow_nan_stats=True, name="Exponential"): """Construct Exponential distribution with parameter `rate`. Args: rate: Floating point tensor, equivalent to `1 / mean`. Must contain only positi...
73
110
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
create
Create each navigation componet, storing the layout. Then parent class to create application. Args: kwargs: keyword arguments passed to `self.create`
"""Classes for more complex applications that have tabbed or paged navigation.""" from collections import OrderedDict from copy import deepcopy import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from implements import implements from .utils_app import AppBa...
def create(self, **kwargs): """Create each navigation componet, storing the layout. Then parent class to create application. Args: kwargs: keyword arguments passed to `self.create` """ # Initialize the lookup for each tab then configure each tab self.nav_lookup ...
59
77
"""Classes for more complex applications that have tabbed or paged navigation.""" from collections import OrderedDict from copy import deepcopy import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from implements import implements from .utils_app import AppBa...
verify_app_initialization
Check that the app was properly initialized. Raises: RuntimeError: if child class has not called `self.register_uniq_ids`
"""Classes for more complex applications that have tabbed or paged navigation.""" from collections import OrderedDict from copy import deepcopy import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from implements import implements from .utils_app import AppBa...
def verify_app_initialization(self): """Check that the app was properly initialized. Raises: RuntimeError: if child class has not called `self.register_uniq_ids` """ super().verify_app_initialization() allowed_locations = ('left', 'top', 'bottom', 'right') ...
169
179
"""Classes for more complex applications that have tabbed or paged navigation.""" from collections import OrderedDict from copy import deepcopy import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from implements import implements from .utils_app import AppBa...
tab_menu
Return the HTML elements for the tab menu. Returns: dict: Dash HTML object
"""Classes for more complex applications that have tabbed or paged navigation.""" from collections import OrderedDict from copy import deepcopy import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from implements import implements from .utils_app import AppBa...
def tab_menu(self): """Return the HTML elements for the tab menu. Returns: dict: Dash HTML object """ tab_kwargs, tabs_kwargs, tabs_style = self.generate_tab_kwargs() tabs = [dcc.Tab(label=name, value=name, **tab_kwargs) for name, tab in self.nav_lookup.items()]...
249
265
"""Classes for more complex applications that have tabbed or paged navigation.""" from collections import OrderedDict from copy import deepcopy import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from implements import implements from .utils_app import AppBa...
nav_bar
Return the HTML elements for the navigation menu. Returns: dict: Dash HTML object
"""Classes for more complex applications that have tabbed or paged navigation.""" from collections import OrderedDict from copy import deepcopy import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from implements import implements from .utils_app import AppBa...
def nav_bar(self): """Return the HTML elements for the navigation menu. Returns: dict: Dash HTML object """ # Create brand icon and name where icon in optional brand = [] if self.logo: brand.append(dbc.Col(html.Img(src=self.logo, height='25px...
304
365
"""Classes for more complex applications that have tabbed or paged navigation.""" from collections import OrderedDict from copy import deepcopy import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from implements import implements from .utils_app import AppBa...
analyze_correctness
For each training sample, determine whether the activation clustering method was correct. :param assigned_clean_by_class: Result of clustering. :param is_clean_by_class: is clean separated by class. :return: Two variables are returned: 1) all_errors_by_class[i]: an array indicating the correctness of each ass...
# MIT License # # Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018 # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation the # r...
def analyze_correctness( self, assigned_clean_by_class: Union[np.ndarray, List[np.ndarray]], is_clean_by_class: list ) -> Tuple[np.ndarray, str]: """ For each training sample, determine whether the activation clustering method was correct. :param assigned_clean_by_class: Result ...
42
101
# MIT License # # Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018 # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation the # r...
get_confusion_matrix
Computes and returns a json object that contains the confusion matrix for each class. :param values: Array indicating the correctness of each assignment in the ith class. :return: Json object with confusion matrix per-class.
# MIT License # # Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018 # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation the # r...
def get_confusion_matrix(self, values: np.ndarray) -> dict: """ Computes and returns a json object that contains the confusion matrix for each class. :param values: Array indicating the correctness of each assignment in the ith class. :return: Json object with confusion matrix per-c...
103
174
# MIT License # # Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018 # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation the # r...
template_2a_1
Returns: QuantumCircuit: template as a quantum circuit.
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
def template_2a_1(): """ Returns: QuantumCircuit: template as a quantum circuit. """ qc = QuantumCircuit(1) qc.x(0) qc.x(0) return qc
26
34
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
adjust_bbox
Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned.
""" This module is to support *bbox_inches* option in savefig command. """ import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D # MASKED: adjust_bbox function (lines 10-56) def adjust_bbox_png(fig, bbox_inches): """ adjust_bbox for png (Agg) format """ tr = fig.dpi_sc...
def adjust_bbox(fig, format, bbox_inches): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A ...
10
56
""" This module is to support *bbox_inches* option in savefig command. """ import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, format, bbox_inches): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifi...
process_figure_for_rasterizing
This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi.
""" This module is to support *bbox_inches* option in savefig command. """ import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, format, bbox_inches): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifi...
def process_figure_for_rasterizing(figure, bbox_inches_restore, mode): """ This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inch...
114
128
""" This module is to support *bbox_inches* option in savefig command. """ import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, format, bbox_inches): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifi...
validate_authorization_request
The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI using the "application/x-www-form-urlencoded" format. Per `Section 4.2.1`_. response_type REQUIRED. Value MUST be set to "token". client_id REQUIRED. The client identifier as d...
import logging from authlib.common.urls import add_params_to_uri from .base import BaseGrant, AuthorizationEndpointMixin from ..errors import ( OAuth2Error, UnauthorizedClientError, AccessDeniedError, ) log = logging.getLogger(__name__) class ImplicitGrant(BaseGrant, AuthorizationEndpointMixin): """T...
def validate_authorization_request(self): """The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI using the "application/x-www-form-urlencoded" format. Per `Section 4.2.1`_. response_type ...
78
147
import logging from authlib.common.urls import add_params_to_uri from .base import BaseGrant, AuthorizationEndpointMixin from ..errors import ( OAuth2Error, UnauthorizedClientError, AccessDeniedError, ) log = logging.getLogger(__name__) class ImplicitGrant(BaseGrant, AuthorizationEndpointMixin): """T...
cdsem_straight
Returns straight waveguide lines width sweep. Args: widths: for the sweep length: for the line cross_section: for the lines text: optional text for labels spacing: edge to edge spacing
"""CD SEM structures.""" from functools import partial from typing import Optional, Tuple from gdsfactory.cell import cell from gdsfactory.component import Component from gdsfactory.components.straight import straight as straight_function from gdsfactory.components.text_rectangular import text_rectangular from gdsfact...
@cell def cdsem_straight( widths: Tuple[float, ...] = (0.4, 0.45, 0.5, 0.6, 0.8, 1.0), length: float = LINE_LENGTH, cross_section: CrossSectionFactory = strip, text: Optional[ComponentFactory] = text_rectangular_mini, spacing: float = 3, ) -> Component: """Returns straight waveguide lines width ...
18
47
"""CD SEM structures.""" from functools import partial from typing import Optional, Tuple from gdsfactory.cell import cell from gdsfactory.component import Component from gdsfactory.components.straight import straight as straight_function from gdsfactory.components.text_rectangular import text_rectangular from gdsfact...
_teacher_action
Extract teacher actions into variable. :param obs: The observation. :param ended: Whether the action seq is ended :return:
import json import os import sys import numpy as np import random import math import time from tqdm import tqdm import torch import torch.nn as nn from torch.autograd import Variable from torch import optim import torch.nn.functional as F from env import R2RBatch from utils import padding_idx, add_idx, Tokenizer imp...
def _teacher_action(self, obs, ended): """ Extract teacher actions into variable. :param obs: The observation. :param ended: Whether the action seq is ended :return: """ a = np.zeros(len(obs), dtype=np.int64) for i, ob in enumerate(obs): if...
169
188
import json import os import sys import numpy as np import random import math import time from tqdm import tqdm import torch import torch.nn as nn from torch.autograd import Variable from torch import optim import torch.nn.functional as F from env import R2RBatch from utils import padding_idx, add_idx, Tokenizer imp...
type_from_ast
Given an AST node representing an annotation, return a :class:`Value <pyanalyze.value.Value>`. :param ast_node: AST node to evaluate. :param visitor: Visitor class to use. This is used in the default :class:`Context` to resolve names and show errors. This is ignored if `ctx` is given. ...
""" Code for understanding type annotations. This file contains functions that turn various representations of Python type annotations into :class:`pyanalyze.value.Value` objects. There are three major functions: - :func:`type_from_runtime` takes a runtime Python object, for example ``type_from_value(int)`` -> ``...
@used # part of an API def type_from_ast( ast_node: ast.AST, visitor: Optional["NameCheckVisitor"] = None, ctx: Optional[Context] = None, ) -> Value: """Given an AST node representing an annotation, return a :class:`Value <pyanalyze.value.Value>`. :param ast_node: AST node to evaluate. :p...
227
247
""" Code for understanding type annotations. This file contains functions that turn various representations of Python type annotations into :class:`pyanalyze.value.Value` objects. There are three major functions: - :func:`type_from_runtime` takes a runtime Python object, for example ``type_from_value(int)`` -> ``...
test_compiled_js_dir_validation
Test that build.COMPILED_JS_DIR is validated correctly with outDir in build.TSCONFIG_FILEPATH.
# coding: utf-8 # # Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
def test_compiled_js_dir_validation(self): """Test that build.COMPILED_JS_DIR is validated correctly with outDir in build.TSCONFIG_FILEPATH. """ build.require_compiled_js_dir_to_be_valid() out_dir = '' with open(build.TSCONFIG_FILEPATH) as f: config_data ...
658
675
# coding: utf-8 # # Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
_encode_image
encodes an (numpy) image array to string. Args: image_array: (numpy) image array fmt: image format to use Returns: encoded image string
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def _encode_image(image_array, fmt='PNG'): """encodes an (numpy) image array to string. Args: image_array: (numpy) image array fmt: image format to use Returns: encoded image string """ pil_image = Image.fromarray(image_array) image_io = io.BytesIO() pil_image.save(image_io, format=fmt) re...
261
274
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
write_warmup_requests
Writes warmup requests for inference into a tfrecord file. Args: savedmodel_dir: string, the file to the exported model folder. model_name: string, a model name used inside the model server. image_size: int, size of image, assuming image height and width. batch_sizes: list, a list of batch sizes to create diff...
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def write_warmup_requests(savedmodel_dir, model_name, image_size, batch_sizes=None, num_requests=8): """Writes warmup requests for inference into a tfrecord file. Args: savedmodel_dir: string, the file to th...
277
311
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
add_text
Return component inside a new component with text geometry. Args: component: text: text string. text_offset: relative to component anchor. Defaults to center (cc). text_anchor: relative to component (ce cw nc ne nw sc se sw center cc). text_factory: function to add text labels.
"""All functions return a Component so you can easily pipe or compose them. There are two types of functions: - decorators: return the original component - containers: return a new component """ from functools import lru_cache import numpy as np from omegaconf import OmegaConf from pydantic import validate_argument...
@cell def add_text( component: ComponentOrFactory, text: str = "", text_offset: Float2 = (0, 0), text_anchor: Anchor = "cc", text_factory: ComponentFactory = text_rectangular_multi_layer, ) -> Component: """Return component inside a new component with text geometry. Args: component:...
41
68
"""All functions return a Component so you can easily pipe or compose them. There are two types of functions: - decorators: return the original component - containers: return a new component """ from functools import lru_cache import numpy as np from omegaconf import OmegaConf from pydantic import validate_argument...
rotate
Return rotated component inside a new component. Most times you just need to place a reference and rotate it. This rotate function just encapsulates the rotated reference into a new component. Args: component: angle: in degrees
"""All functions return a Component so you can easily pipe or compose them. There are two types of functions: - decorators: return the original component - containers: return a new component """ from functools import lru_cache import numpy as np from omegaconf import OmegaConf from pydantic import validate_argument...
@cell def rotate( component: ComponentOrFactory, angle: float = 90, ) -> Component: """Return rotated component inside a new component. Most times you just need to place a reference and rotate it. This rotate function just encapsulates the rotated reference into a new component. Args: ...
95
116
"""All functions return a Component so you can easily pipe or compose them. There are two types of functions: - decorators: return the original component - containers: return a new component """ from functools import lru_cache import numpy as np from omegaconf import OmegaConf from pydantic import validate_argument...
mirror
Return new Component with a mirrored reference. Args: p1: first point to define mirror axis p2: second point to define mirror axis
"""All functions return a Component so you can easily pipe or compose them. There are two types of functions: - decorators: return the original component - containers: return a new component """ from functools import lru_cache import numpy as np from omegaconf import OmegaConf from pydantic import validate_argument...
@cell def mirror(component: Component, p1: Float2 = (0, 1), p2: Float2 = (0, 0)) -> Component: """Return new Component with a mirrored reference. Args: p1: first point to define mirror axis p2: second point to define mirror axis """ component_new = Component() component_new.componen...
124
138
"""All functions return a Component so you can easily pipe or compose them. There are two types of functions: - decorators: return the original component - containers: return a new component """ from functools import lru_cache import numpy as np from omegaconf import OmegaConf from pydantic import validate_argument...
move
Return new Component with a moved reference to the original component. Args: origin: of component destination: axis: x or y axis
"""All functions return a Component so you can easily pipe or compose them. There are two types of functions: - decorators: return the original component - containers: return a new component """ from functools import lru_cache import numpy as np from omegaconf import OmegaConf from pydantic import validate_argument...
@cell def move( component: Component, origin=(0, 0), destination=None, axis: Optional[Axis] = None, ) -> Component: """Return new Component with a moved reference to the original component. Args: origin: of component destination: axis: x or y axis """ component_n...
141
161
"""All functions return a Component so you can easily pipe or compose them. There are two types of functions: - decorators: return the original component - containers: return a new component """ from functools import lru_cache import numpy as np from omegaconf import OmegaConf from pydantic import validate_argument...
add_settings_label
Add a settings label to a component. Args: component: layer_label: settings: tuple or list of settings. if None, adds all changed settings
"""All functions return a Component so you can easily pipe or compose them. There are two types of functions: - decorators: return the original component - containers: return a new component """ from functools import lru_cache import numpy as np from omegaconf import OmegaConf from pydantic import validate_argument...
@validate_arguments def add_settings_label( component: Component, layer_label: Layer = (66, 0), settings: Optional[Strs] = None ) -> Component: """Add a settings label to a component. Args: component: layer_label: settings: tuple or list of settings. if None, adds all changed settin...
181
200
"""All functions return a Component so you can easily pipe or compose them. There are two types of functions: - decorators: return the original component - containers: return a new component """ from functools import lru_cache import numpy as np from omegaconf import OmegaConf from pydantic import validate_argument...
write_fiducials
Write fiducials to a fiff file Parameters ---------- fname : str Destination file name. pts : iterator of dict Iterator through digitizer points. Each point is a dictionary with the keys 'kind', 'ident' and 'r'. coord_frame : int The coordinate frame of the points (one of mne.fiff.FIFF.FIFFV_COORD_...
# Authors: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu> # Matti Hamalainen <msh@nmr.mgh.harvard.edu> # # License: BSD (3-clause) from warnings import warn from copy import deepcopy import os.path as op import numpy as np from scipy import linalg from ..externals.six import BytesIO from datetime import da...
def write_fiducials(fname, pts, coord_frame=0): """Write fiducials to a fiff file Parameters ---------- fname : str Destination file name. pts : iterator of dict Iterator through digitizer points. Each point is a dictionary with the keys 'kind', 'ident' and 'r'. coord_fr...
119
147
# Authors: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu> # Matti Hamalainen <msh@nmr.mgh.harvard.edu> # # License: BSD (3-clause) from warnings import warn from copy import deepcopy import os.path as op import numpy as np from scipy import linalg from ..externals.six import BytesIO from datetime import da...
write_info
Write measurement info in fif file. Parameters ---------- fname : str The name of the file. Should end by -info.fif. info : instance of mne.fiff.meas_info.Info The measurement info structure data_type : int The data_type in case it is necessary. Should be 4 (FIFFT_FLOAT), 5 (FIFFT_DOUBLE), or 16 (mne.f...
# Authors: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu> # Matti Hamalainen <msh@nmr.mgh.harvard.edu> # # License: BSD (3-clause) from warnings import warn from copy import deepcopy import os.path as op import numpy as np from scipy import linalg from ..externals.six import BytesIO from datetime import da...
def write_info(fname, info, data_type=None, reset_range=True): """Write measurement info in fif file. Parameters ---------- fname : str The name of the file. Should end by -info.fif. info : instance of mne.fiff.meas_info.Info The measurement info structure data_type : int ...
595
615
# Authors: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu> # Matti Hamalainen <msh@nmr.mgh.harvard.edu> # # License: BSD (3-clause) from warnings import warn from copy import deepcopy import os.path as op import numpy as np from scipy import linalg from ..externals.six import BytesIO from datetime import da...
loss_fn_kd
Compute the knowledge-distillation (KD) loss given outputs, labels. "Hyperparameters": temperature and alpha NOTE: the KL Divergence for PyTorch comparing the softmaxs of teacher and student expects the input tensor to be log probabilities! See Issue #2
""" Baseline CNN, losss function and metrics Also customizes knowledge distillation (KD) loss function here """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), -1) """ This is t...
def loss_fn_kd(outputs, labels, teacher_outputs, params): """ Compute the knowledge-distillation (KD) loss given outputs, labels. "Hyperparameters": temperature and alpha NOTE: the KL Divergence for PyTorch comparing the softmaxs of teacher and student expects the input tensor to be log probabiliti...
119
133
""" Baseline CNN, losss function and metrics Also customizes knowledge distillation (KD) loss function here """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), -1) """ This is t...
forward
This function defines how we use the components of our network to operate on an input batch. Args: s: (Variable) contains a batch of images, of dimension batch_size x 3 x 32 x 32 . Returns: out: (Variable) dimension batch_size x 6 with the log probabilities for the labels of each image. Note: the dimensions ...
""" Baseline CNN, losss function and metrics Also customizes knowledge distillation (KD) loss function here """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), -1) """ This is t...
def forward(self, s): """ This function defines how we use the components of our network to operate on an input batch. Args: s: (Variable) contains a batch of images, of dimension batch_size x 3 x 32 x 32 . Returns: out: (Variable) dimension batch_size x 6 w...
62
99
""" Baseline CNN, losss function and metrics Also customizes knowledge distillation (KD) loss function here """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), -1) """ This is t...
build_model
Build model. Arguments: n_stimuli: Integer indicating the number of stimuli in the embedding. n_dim: Integer indicating the dimensionality of the embedding. Returns: model: A TensorFlow Keras model.
# -*- coding: utf-8 -*- # Copyright 2020 The PsiZ Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
def build_model(n_stimuli, n_dim, n_group): """Build model. Arguments: n_stimuli: Integer indicating the number of stimuli in the embedding. n_dim: Integer indicating the dimensionality of the embedding. Returns: model: A TensorFlow Keras model. """ stimuli = t...
259
293
# -*- coding: utf-8 -*- # Copyright 2020 The PsiZ Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
send_single_ans
Send a single message to specific id with a specific name. :params ID: User quiz id. :type ID: int :params name: Name you want on the message. :type name: str
import requests import json class BuddyAPI(): ''' An API of buddymojo.com :returns: An API ''' def __init__(self): self.payload = {'type': 'friend', 'action': 'finish'} self.payloadf = {'userQuizId': 1, 'type': 'friend', ...
def send_single_ans(self, ID, name: str): ''' Send a single message to specific id with a specific name. :params ID: User quiz id. :type ID: int :params name: Name you want on the message. :type name: str ''' self.data = {'userFullName': name, ...
22
50
import requests import json class BuddyAPI(): ''' An API of buddymojo.com :returns: An API ''' def __init__(self): self.payload = {'type': 'friend', 'action': 'finish'} self.payloadf = {'userQuizId': 1, 'type': 'friend', ...
lazy_property
Allows to avoid recomputing a property over and over. The result gets stored in a local var. Computation of the property will happen once, on the first call of the property. All succeeding calls will use the value stored in the private property.
import asyncio import functools import importlib import inspect import logging from typing import Text, Dict, Optional, Any, List, Callable, Collection, Type from rasa.shared.exceptions import RasaException logger = logging.getLogger(__name__) def class_from_module_path( module_path: Text, lookup_path: Optional...
def lazy_property(function: Callable) -> Any: """Allows to avoid recomputing a property over and over. The result gets stored in a local var. Computation of the property will happen once, on the first call of the property. All succeeding calls will use the value stored in the private property.""" ...
73
88
import asyncio import functools import importlib import inspect import logging from typing import Text, Dict, Optional, Any, List, Callable, Collection, Type from rasa.shared.exceptions import RasaException logger = logging.getLogger(__name__) def class_from_module_path( module_path: Text, lookup_path: Optional...
cached_method
Caches method calls based on the call's `args` and `kwargs`. Works for `async` and `sync` methods. Don't apply this to functions. Args: f: The decorated method whose return value should be cached. Returns: The return value which the method gives for the first call with the given arguments.
import asyncio import functools import importlib import inspect import logging from typing import Text, Dict, Optional, Any, List, Callable, Collection, Type from rasa.shared.exceptions import RasaException logger = logging.getLogger(__name__) def class_from_module_path( module_path: Text, lookup_path: Optional...
def cached_method(f: Callable[..., Any]) -> Callable[..., Any]: """Caches method calls based on the call's `args` and `kwargs`. Works for `async` and `sync` methods. Don't apply this to functions. Args: f: The decorated method whose return value should be cached. Returns: The return v...
91
150
import asyncio import functools import importlib import inspect import logging from typing import Text, Dict, Optional, Any, List, Callable, Collection, Type from rasa.shared.exceptions import RasaException logger = logging.getLogger(__name__) def class_from_module_path( module_path: Text, lookup_path: Optional...
prepare_roidb
Enrich the imdb's roidb by adding some derived quantities that are useful for training. This function precomputes the maximum overlap, taken over ground-truth boxes, between each ROI and each ground-truth box. The class with maximum overlap is also recorded.
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Transform a roidb into a trainable roidb by adding a bunch of metada...
def prepare_roidb(imdb): """Enrich the imdb's roidb by adding some derived quantities that are useful for training. This function precomputes the maximum overlap, taken over ground-truth boxes, between each ROI and each ground-truth box. The class with maximum overlap is also recorded. """ r...
14
38
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Transform a roidb into a trainable roidb by adding a bunch of metada...
create_game
Configure and create a game. Creates a game with base settings equivalent to one of the default presets. Allows user to customize the settings before starting the game. Parameters ---------- gm : int Game type to replicate: 0: Normal mode. 1: Advanced mode. Returns ------- BattleshipGame Game...
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
def create_game(gm): """ Configure and create a game. Creates a game with base settings equivalent to one of the default presets. Allows user to customize the settings before starting the game. Parameters ---------- gm : int Game type to replicate: 0: Normal mode. ...
1,152
1,237
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
box_string
Place a string into an ASCII box. The result is placed inside of a ASCII box consisting of '+' characters for the corners and '-' characters for the edges. Parameters ---------- string : str String to be boxed. min_width : int, optional Specifies that the box be of a certain minimum width. Defaults to input s...
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
@staticmethod def box_string(string, min_width=-1, print_string=False): """ Place a string into an ASCII box. The result is placed inside of a ASCII box consisting of '+' characters for the corners and '-' characters for the edges. Parameters ---------- string :...
27
62
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
string_input
Take string-based user input. The input question will be repeated until valid input is given, determined by the condition regex. Parameters ---------- question : str String to be displayed as the input question. Will be boxed with Utils#box_string before printing. condition : r-string, optional Regex to test ...
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
@staticmethod def string_input(question, condition=r'.+'): """ Take string-based user input. The input question will be repeated until valid input is given, determined by the condition regex. Parameters ---------- question : str String to be displaye...
110
140
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
print_settings
Pretty-print a settings dictionary. Parameters ---------- settings : dict The settings dictionary to pretty-print. Returns ------- None
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
@staticmethod def print_settings(settings): """ Pretty-print a settings dictionary. Parameters ---------- settings : dict The settings dictionary to pretty-print. Returns ------- None """ Utils.box_string('Current ...
142
175
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
grid_pos_input
Take user-input in coordinate form. The input question will be repeated until valid input is given. The input must be a valid coordinate in battleship form (r'[A-Z]\d+'). The input coordinate must be inside of the grid defined by height and width. Parameters ---------- height : int Specifies the height of the gri...
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
@staticmethod def grid_pos_input(height, width, question='Enter a Position:'): """ Take user-input in coordinate form. The input question will be repeated until valid input is given. The input must be a valid coordinate in battleship form (r'[A-Z]\d+'). The input coordin...
177
218
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
print_board
Pretty-print the current boards of a player. Prints both boards for a player, along with coordinate references, titles, and boxes around the grids. Parameters ---------- player : int Determines which player's grids to print. Zero-indexed. Returns ------- str Same as the string that is printed.
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
def print_board(self, player): """ Pretty-print the current boards of a player. Prints both boards for a player, along with coordinate references, titles, and boxes around the grids. Parameters ---------- player : int Determines which player's grids to p...
335
383
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
setup_ship
Create a ship. Creates a ship dictionary based on positional, directional, player, and size data and tests if placement is legal. Parameters ---------- pos : tuple (y,x) coordinate pair of top-left corner of the ship. direction : int Determines the direction of the ship: 0: Horizontal. 1: Vert...
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
def setup_ship(self, pos, direction, player, count, size): """ Create a ship. Creates a ship dictionary based on positional, directional, player, and size data and tests if placement is legal. Parameters ---------- pos : tuple (y,x) coordinate pair of to...
385
443
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
start_game
Start a new game. Starts a game with the settings provided in the constructor. All game code is contained here, with relevant helper methods also called here. Every game has two stages: Setup and Play. Returns ------- int Winning player's number. Zero-indexed.
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
def start_game(self): """ Start a new game. Starts a game with the settings provided in the constructor. All game code is contained here, with relevant helper methods also called here. Every game has two stages: Setup and Play. Returns ------- int ...
1,046
1,149
#!/usr/bin/env python3 from string import ascii_uppercase from re import fullmatch from time import sleep from random import Random # Default game presets. testing_preset = {'height': 10, 'width': 10, '5_ships': 0, '4_ships': 0, '3_ships': 0, '2_ships': 2, '1_ships': 0, 'allow_mines': True, 'allow_moves': True, 'mine...
get_application_gateway
Application gateway resource. :param str application_gateway_name: The name of the application gateway. :param str resource_group_name: The name of the resource group.
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
def get_application_gateway(application_gateway_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetApplicationGatewayResult: """ Application gateway resource. :param str ...
490
547
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
f_regression_block
runs f_regression for each block separately (saves memory). ------------------------- fun : method that returns statistics,pval X : {array-like, sparse matrix} shape = (n_samples, n_features) The set of regressors that will tested sequentially. y : array of shape(n_samples). The data matrix block...
import numpy as np import logging import unittest import os import scipy.linalg as LA import time from sklearn.utils import safe_sqr, check_array from scipy import stats from pysnptools.snpreader import Bed,Pheno from pysnptools.snpreader import SnpData,SnpReader from pysnptools.kernelreader import KernelNpz from pysn...
def f_regression_block(fun,X,y,blocksize=None,**args): """ runs f_regression for each block separately (saves memory). ------------------------- fun : method that returns statistics,pval X : {array-like, sparse matrix} shape = (n_samples, n_features) The set of regressors that will tested...
286
315
import numpy as np import logging import unittest import os import scipy.linalg as LA import time from sklearn.utils import safe_sqr, check_array from scipy import stats from pysnptools.snpreader import Bed,Pheno from pysnptools.snpreader import SnpData,SnpReader from pysnptools.kernelreader import KernelNp...
f_regression_cov_alt
Implementation as derived in tex document See pg 12 of following document for definition of F-statistic http://www-stat.stanford.edu/~jtaylo/courses/stats191/notes/simple_diagnostics.pdf Parameters ---------- X : {array-like, sparse matrix} shape = (n_samples, n_features) The set of regressors that will tested s...
import numpy as np import logging import unittest import os import scipy.linalg as LA import time from sklearn.utils import safe_sqr, check_array from scipy import stats from pysnptools.snpreader import Bed,Pheno from pysnptools.snpreader import SnpData,SnpReader from pysnptools.kernelreader import KernelNpz from pysn...
def f_regression_cov_alt(X, y, C): """ Implementation as derived in tex document See pg 12 of following document for definition of F-statistic http://www-stat.stanford.edu/~jtaylo/courses/stats191/notes/simple_diagnostics.pdf Parameters ---------- X : {array-like, sparse matrix} shape = (...
318
387
import numpy as np import logging import unittest import os import scipy.linalg as LA import time from sklearn.utils import safe_sqr, check_array from scipy import stats from pysnptools.snpreader import Bed,Pheno from pysnptools.snpreader import SnpData,SnpReader from pysnptools.kernelreader import KernelNp...
f_regression_cov
Univariate linear regression tests Quick linear model for testing the effect of a single regressor, sequentially for many regressors. This is done in 3 steps: 1. the regressor of interest and the data are orthogonalized wrt constant regressors 2. the cross correlation between data and regressors is computed 3. it is ...
import numpy as np import logging import unittest import os import scipy.linalg as LA import time from sklearn.utils import safe_sqr, check_array from scipy import stats from pysnptools.snpreader import Bed,Pheno from pysnptools.snpreader import SnpData,SnpReader from pysnptools.kernelreader import KernelNpz from pysn...
def f_regression_cov(X, y, C): """Univariate linear regression tests Quick linear model for testing the effect of a single regressor, sequentially for many regressors. This is done in 3 steps: 1. the regressor of interest and the data are orthogonalized wrt constant regressors 2. the cross...
390
442
import numpy as np import logging import unittest import os import scipy.linalg as LA import time from sklearn.utils import safe_sqr, check_array from scipy import stats from pysnptools.snpreader import Bed,Pheno from pysnptools.snpreader import SnpData,SnpReader from pysnptools.kernelreader import KernelNp...
description_of
Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str
#!/usr/bin/env python """ Script which takes one or more file paths and reports on their detected encodings Example:: % chardetect somefile someotherfile somefile: windows-1252 with confidence 0.5 someotherfile: ascii with confidence 1.0 If no paths are provided, it takes its input from stdin. """ # C...
def description_of(lines, name='stdin'): """ Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str """ u = Univers...
29
54
#!/usr/bin/env python """ Script which takes one or more file paths and reports on their detected encodings Example:: % chardetect somefile someotherfile somefile: windows-1252 with confidence 0.5 someotherfile: ascii with confidence 1.0 If no paths are provided, it takes its input from stdin. """ # C...
main
Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str
#!/usr/bin/env python """ Script which takes one or more file paths and reports on their detected encodings Example:: % chardetect somefile someotherfile somefile: windows-1252 with confidence 0.5 someotherfile: ascii with confidence 1.0 If no paths are provided, it takes its input from stdin. """ # C...
def main(argv=None): """ Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str """ # Get command line arguments parser = argparse.Argume...
57
84
#!/usr/bin/env python """ Script which takes one or more file paths and reports on their detected encodings Example:: % chardetect somefile someotherfile somefile: windows-1252 with confidence 0.5 someotherfile: ascii with confidence 1.0 If no paths are provided, it takes its input from stdin. """ # C...
get
Get an existing ActionGroup resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'ActionGroup': """ Get an existing ActionGroup resource's state with the given name, id, and optional extra properties used to qualify the lookup. ...
100
128
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
_area_tables_binning_parallel
Construct area allocation and source-target correspondence tables using a parallel spatial indexing approach ... NOTE: currently, the largest df is chunked and the other one is shipped in full to each core; within each process, the spatial index is built for the largest set of geometries, and the other one used for `q...
""" Area Weighted Interpolation """ import numpy as np import geopandas as gpd from ._vectorized_raster_interpolation import _fast_append_profile_in_gdf import warnings from scipy.sparse import dok_matrix, diags, coo_matrix import pandas as pd import os from tobler.util.util import _check_crs, _nan_check, _inf_check...
def _area_tables_binning_parallel(source_df, target_df, n_jobs=-1): """Construct area allocation and source-target correspondence tables using a parallel spatial indexing approach ... NOTE: currently, the largest df is chunked and the other one is shipped in full to each core; within each process, ...
60
137
""" Area Weighted Interpolation """ import numpy as np import geopandas as gpd from ._vectorized_raster_interpolation import _fast_append_profile_in_gdf import warnings from scipy.sparse import dok_matrix, diags, coo_matrix import pandas as pd import os from tobler.util.util import _check_crs, _nan_check, _inf_check...
build_model
Build and return a Sequential model with Dense layers given by the layers argument. Arguments model (keras.Sequential) model to which layers will be added input_dim (int) dimension of input layers (tuple) sequence of 2-ples, one per layer, such as ((64, 'relu'), (64, 'relu'), (1, 'sigmoid')) Ret...
""" Training and validation method for arbitrary models. """ import io import os import sys import time from keras import Sequential from keras.layers import Dense, Dropout, BatchNormalization from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt import matplotlib.ticker as ticker impo...
def build_model(layers, model=None, input_dim=None): """ Build and return a Sequential model with Dense layers given by the layers argument. Arguments model (keras.Sequential) model to which layers will be added input_dim (int) dimension of input layers (tuple) sequence of...
123
155
""" Training and validation method for arbitrary models. """ import io import os import sys import time from keras import Sequential from keras.layers import Dense, Dropout, BatchNormalization from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt import matplotlib.ticker as ticker impo...
to_datetime
Based on what type when is, converts when to a Python DateTime object. Type: - int: returns now.plusMillis(when) - openHAB number type: returns now.plusMillis(when.intValue()) - ISO8601 string: DateTime(when) - Duration definition: see parse_duration_to_datetime - java ZonedDateTime For python m...
""" Copyright June 25, 2020 Richard Koshak Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,...
def to_datetime(when, log=logging.getLogger("{}.time_utils".format(LOG_PREFIX)), output = 'Java'): """Based on what type when is, converts when to a Python DateTime object. Type: - int: returns now.plusMillis(when) - openHAB number type: returns now.plusMillis(when.intValue()) - ISO8601 ...
117
201
""" Copyright June 25, 2020 Richard Koshak Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,...
draw_what_sheet
Draw a calendar page for a WHAT display. Args: image: The image to be drawn on to
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Display a calendar populated from google calendar data on an inky display.""" from PIL import Image, ImageDraw # type: ignore # from typing import Tuple # import time # MASKED: draw_what_sheet function (lines 12-25) if __name__ == "__main__": palette = 3 * [...
def draw_what_sheet(image: Image.Image) -> None: """Draw a calendar page for a WHAT display. Args: image: The image to be drawn on to """ draw = ImageDraw.Draw(image) # draw.rectangle([(7, 3), (392, 296)], outline=1) draw.line([(7, 3), (392, 3)], fill=1) for line in range(8): ...
12
25
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Display a calendar populated from google calendar data on an inky display.""" from PIL import Image, ImageDraw # type: ignore # from typing import Tuple # import time def draw_what_sheet(image: Image.Image) -> None: """Draw a calendar page for a WHAT display. ...
get_shape
Return shape of the input tensor without batch size. Parameters ---------- tensor : tf.Tensor dynamic : bool If True, returns tensor which represents shape. If False, returns list of ints and/or Nones. Returns ------- shape : tf.Tensor or list
""" Utility functions. """ import tensorflow as tf # MASKED: get_shape function (lines 6-24) def get_num_dims(tensor): """ Return a number of semantic dimensions (i.e. excluding batch and channels axis)""" shape = get_shape(tensor) dim = len(shape) return max(1, dim - 2) def get_channels_axis(data...
def get_shape(tensor, dynamic=False): """ Return shape of the input tensor without batch size. Parameters ---------- tensor : tf.Tensor dynamic : bool If True, returns tensor which represents shape. If False, returns list of ints and/or Nones. Returns ------- shape : tf.Tensor...
6
24
""" Utility functions. """ import tensorflow as tf def get_shape(tensor, dynamic=False): """ Return shape of the input tensor without batch size. Parameters ---------- tensor : tf.Tensor dynamic : bool If True, returns tensor which represents shape. If False, returns list of ints and/or...
get_num_channels
Return number of channels in the input tensor. Parameters ---------- tensor : tf.Tensor Returns ------- shape : tuple of ints
""" Utility functions. """ import tensorflow as tf def get_shape(tensor, dynamic=False): """ Return shape of the input tensor without batch size. Parameters ---------- tensor : tf.Tensor dynamic : bool If True, returns tensor which represents shape. If False, returns list of ints and/or...
def get_num_channels(tensor, data_format='channels_last'): """ Return number of channels in the input tensor. Parameters ---------- tensor : tf.Tensor Returns ------- shape : tuple of ints """ shape = tensor.get_shape().as_list() axis = get_channels_axis(data_format) return...
37
50
""" Utility functions. """ import tensorflow as tf def get_shape(tensor, dynamic=False): """ Return shape of the input tensor without batch size. Parameters ---------- tensor : tf.Tensor dynamic : bool If True, returns tensor which represents shape. If False, returns list of ints and/or...
get_batch_size
Return batch size (the length of the first dimension) of the input tensor. Parameters ---------- tensor : tf.Tensor Returns ------- batch size : int or None
""" Utility functions. """ import tensorflow as tf def get_shape(tensor, dynamic=False): """ Return shape of the input tensor without batch size. Parameters ---------- tensor : tf.Tensor dynamic : bool If True, returns tensor which represents shape. If False, returns list of ints and/or...
def get_batch_size(tensor, dynamic=False): """ Return batch size (the length of the first dimension) of the input tensor. Parameters ---------- tensor : tf.Tensor Returns ------- batch size : int or None """ if dynamic: return tf.shape(tensor)[0] return tensor.get_shape...
53
66
""" Utility functions. """ import tensorflow as tf def get_shape(tensor, dynamic=False): """ Return shape of the input tensor without batch size. Parameters ---------- tensor : tf.Tensor dynamic : bool If True, returns tensor which represents shape. If False, returns list of ints and/or...
get_spatial_shape
Return the tensor spatial shape (without batch and channels dimensions). Parameters ---------- tensor : tf.Tensor dynamic : bool If True, returns tensor which represents shape. If False, returns list of ints and/or Nones. Returns ------- shape : tf.Tensor or list
""" Utility functions. """ import tensorflow as tf def get_shape(tensor, dynamic=False): """ Return shape of the input tensor without batch size. Parameters ---------- tensor : tf.Tensor dynamic : bool If True, returns tensor which represents shape. If False, returns list of ints and/or...
def get_spatial_shape(tensor, data_format='channels_last', dynamic=False): """ Return the tensor spatial shape (without batch and channels dimensions). Parameters ---------- tensor : tf.Tensor dynamic : bool If True, returns tensor which represents shape. If False, returns list of ints and...
82
101
""" Utility functions. """ import tensorflow as tf def get_shape(tensor, dynamic=False): """ Return shape of the input tensor without batch size. Parameters ---------- tensor : tf.Tensor dynamic : bool If True, returns tensor which represents shape. If False, returns list of ints and/or...
call_function
Call a function after properly setting up its arguments and return address. Args: addr : function address args : a sequence of arguments to pass to the function; may be empty ret : return address; may be None
#!/usr/bin/env python3 # # Cross Platform and Multi Architecture Advanced Binary Emulation Framework # from typing import Sequence from pefile import PE from qiling.const import QL_ARCH from qiling.exception import QlErrorArch, QlMemoryMappedError from qiling.loader.loader import QlLoader from qiling.os.memory import...
def call_function(self, addr: int, args: Sequence[int], ret: int): """Call a function after properly setting up its arguments and return address. Args: addr : function address args : a sequence of arguments to pass to the function; may be empty ret : return addr...
141
162
#!/usr/bin/env python3 # # Cross Platform and Multi Architecture Advanced Binary Emulation Framework # from typing import Sequence from pefile import PE from qiling.const import QL_ARCH from qiling.exception import QlErrorArch, QlMemoryMappedError from qiling.loader.loader import QlLoader from qiling.os.memory import...
validate_required_primitive_elements_594
https://www.hl7.org/fhir/extensibility.html#Special-Case In some cases, implementers might find that they do not have appropriate data for an element with minimum cardinality = 1. In this case, the element must be present, but unless the resource or a profile on it has made the actual value of the primitive data type m...
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/Task Release: R4 Version: 4.0.1 Build ID: 9346c8cc45 Last updated: 2019-11-01T09:29:23.356+11:00 """ import typing from pydantic import Field, root_validator from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.erro...
@root_validator(pre=True, allow_reuse=True) def validate_required_primitive_elements_594( cls, values: typing.Dict[str, typing.Any] ) -> typing.Dict[str, typing.Any]: """https://www.hl7.org/fhir/extensibility.html#Special-Case In some cases, implementers might find that they do not h...
452
509
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/Task Release: R4 Version: 4.0.1 Build ID: 9346c8cc45 Last updated: 2019-11-01T09:29:23.356+11:00 """ import typing from pydantic import Field, root_validator from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.erro...
run_decider_state
Runs the decider state of the barrier concurrency state. The decider state decides on which outcome the barrier concurrency is left. :param decider_state: the decider state of the barrier concurrency state :param child_errors: error of the concurrent branches :param final_outcomes_dict: dictionary of all outcomes of t...
# Copyright (C) 2014-2018 DLR # # All rights reserved. This program and the accompanying materials are made # available under the terms of the Eclipse Public License v1.0 which # accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Annika Wollschlaeger <anni...
def run_decider_state(self, decider_state, child_errors, final_outcomes_dict): """ Runs the decider state of the barrier concurrency state. The decider state decides on which outcome the barrier concurrency is left. :param decider_state: the decider state of the barrier concurrency state ...
183
208
# Copyright (C) 2014-2018 DLR # # All rights reserved. This program and the accompanying materials are made # available under the terms of the Eclipse Public License v1.0 which # accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Annika Wollschlaeger <anni...
states
Overwrite the setter of the container state base class as special handling for the decider state is needed. :param states: the dictionary of new states :raises exceptions.TypeError: if the states parameter is not of type dict
# Copyright (C) 2014-2018 DLR # # All rights reserved. This program and the accompanying materials are made # available under the terms of the Eclipse Public License v1.0 which # accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Annika Wollschlaeger <anni...
@ContainerState.states.setter @lock_state_machine @Observable.observed def states(self, states): """ Overwrite the setter of the container state base class as special handling for the decider state is needed. :param states: the dictionary of new states :raises exceptions.TypeErr...
260
285
# Copyright (C) 2014-2018 DLR # # All rights reserved. This program and the accompanying materials are made # available under the terms of the Eclipse Public License v1.0 which # accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Annika Wollschlaeger <anni...
get_outcome_for_state_name
Returns the final outcome of the child state specified by name. Note: This is utility function that is used by the programmer to make a decision based on the final outcome of its child states. A state is not uniquely specified by the name, but as the programmer normally does not want to use state-ids in his code this ...
# Copyright (C) 2014-2018 DLR # # All rights reserved. This program and the accompanying materials are made # available under the terms of the Eclipse Public License v1.0 which # accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Annika Wollschlaeger <anni...
def get_outcome_for_state_name(self, name): """ Returns the final outcome of the child state specified by name. Note: This is utility function that is used by the programmer to make a decision based on the final outcome of its child states. A state is not uniquely specified by the name, but...
352
367
# Copyright (C) 2014-2018 DLR # # All rights reserved. This program and the accompanying materials are made # available under the terms of the Eclipse Public License v1.0 which # accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Annika Wollschlaeger <anni...
get_errors_for_state_name
Returns the error message of the child state specified by name. Note: This is utility function that is used by the programmer to make a decision based on the final outcome of its child states. A state is not uniquely specified by the name, but as the programmer normally does not want to use state-ids in his code this ...
# Copyright (C) 2014-2018 DLR # # All rights reserved. This program and the accompanying materials are made # available under the terms of the Eclipse Public License v1.0 which # accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Annika Wollschlaeger <anni...
def get_errors_for_state_name(self, name): """ Returns the error message of the child state specified by name. Note: This is utility function that is used by the programmer to make a decision based on the final outcome of its child states. A state is not uniquely specified by the name, but ...
382
397
# Copyright (C) 2014-2018 DLR # # All rights reserved. This program and the accompanying materials are made # available under the terms of the Eclipse Public License v1.0 which # accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Annika Wollschlaeger <anni...
tag_instances_on_cluster
Adds project tag to untagged instances in a given cluster. Parameters ---------- cluster_name : str The name of the AWS ECS cluster in which running instances should be tagged. project : str The name of the project to tag instances with.
from __future__ import absolute_import, print_function, unicode_literals import pickle from builtins import dict, str import os import re import boto3 import logging import botocore.session from time import sleep import matplotlib as mpl from numpy import median, arange, array from indra.tools.reading.util.reporter ...
def tag_instances_on_cluster(cluster_name, project='cwc'): """Adds project tag to untagged instances in a given cluster. Parameters ---------- cluster_name : str The name of the AWS ECS cluster in which running instances should be tagged. project : str The name of the projec...
319
345
from __future__ import absolute_import, print_function, unicode_literals import pickle from builtins import dict, str import os import re import boto3 import logging import botocore.session from time import sleep import matplotlib as mpl from numpy import median, arange, array from indra.tools.reading.util.reporter ...
submit_reading
Submit an old-style pmid-centered no-database s3 only reading job. This function is provided for the sake of backward compatibility. It is preferred that you use the object-oriented PmidSubmitter and the submit_reading job going forward.
from __future__ import absolute_import, print_function, unicode_literals import pickle from builtins import dict, str import os import re import boto3 import logging import botocore.session from time import sleep import matplotlib as mpl from numpy import median, arange, array from indra.tools.reading.util.reporter ...
def submit_reading(basename, pmid_list_filename, readers, start_ix=None, end_ix=None, pmids_per_job=3000, num_tries=2, force_read=False, force_fulltext=False, project_name=None): """Submit an old-style pmid-centered no-database s3 only reading job. This function is provide...
536
549
from __future__ import absolute_import, print_function, unicode_literals import pickle from builtins import dict, str import os import re import boto3 import logging import botocore.session from time import sleep import matplotlib as mpl from numpy import median, arange, array from indra.tools.reading.util.reporter ...
submit_combine
Submit a batch job to combine the outputs of a reading job. This function is provided for backwards compatibility. You should use the PmidSubmitter and submit_combine methods.
from __future__ import absolute_import, print_function, unicode_literals import pickle from builtins import dict, str import os import re import boto3 import logging import botocore.session from time import sleep import matplotlib as mpl from numpy import median, arange, array from indra.tools.reading.util.reporter ...
def submit_combine(basename, readers, job_ids=None, project_name=None): """Submit a batch job to combine the outputs of a reading job. This function is provided for backwards compatibility. You should use the PmidSubmitter and submit_combine methods. """ sub = PmidSubmitter(basename, readers, proje...
552
561
from __future__ import absolute_import, print_function, unicode_literals import pickle from builtins import dict, str import os import re import boto3 import logging import botocore.session from time import sleep import matplotlib as mpl from numpy import median, arange, array from indra.tools.reading.util.reporter ...
get_ticket_multiline_description_sale
Compute a multiline description of this ticket, in the context of sales. It will often be used as the default description of a sales order line referencing this ticket. 1. the first line is the ticket name 2. the second line is the event name (if it exists, which should be the case with a normal workflow) or the p...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError, UserError from odoo.addons import decimal_precision as dp from odoo.tools import float_is_zero class EventType(models.Model): _i...
def get_ticket_multiline_description_sale(self): """ Compute a multiline description of this ticket, in the context of sales. It will often be used as the default description of a sales order line referencing this ticket. 1. the first line is the ticket name 2. the second line i...
163
181
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError, UserError from odoo.addons import decimal_precision as dp from odoo.tools import float_is_zero class EventType(models.Model): _i...
add_pusher
Creates a new pusher and adds it to the pool Returns: The newly created pusher.
# Copyright 2015, 2016 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
async def add_pusher( self, user_id: str, access_token: Optional[int], kind: str, app_id: str, app_display_name: str, device_display_name: str, pushkey: str, lang: Optional[str], data: JsonDict, profile_tag: str = "", ) -> O...
97
169
# Copyright 2015, 2016 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...