content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_function(client: Client) -> str:
"""
Performs test connectivity by valid http response
:param client: client object which is used to get response from api
:return: raise ValueError if any error occurred during connection
"""
client.http_request(method='GET', url_suffix=URL_SUFFIX['TEST... | 5,339,400 |
def _close_output(out_file: TextIOWrapper):
"""
Closes the output. Does not close stdout.
:param out_file: File object to close
"""
if out_file is not sys.stdout:
out_file.close() | 5,339,401 |
def load_tests(loader, tests, ignore):
"""Create tests from all docstrings by walking the package hierarchy."""
modules = pkgutil.walk_packages(rowan.__path__, rowan.__name__ + ".")
for _, module_name, _ in modules:
tests.addTests(doctest.DocTestSuite(module_name, globs={"rowan": rowan}))
return... | 5,339,402 |
def k_hot_array_from_string_list(context,
typename,
entity_names):
"""Create a numpy array encoding a k-hot set.
Args:
context: a NeuralExpressionContext
typename: type of entity_names
entity_names: list of names of type typename
Retu... | 5,339,403 |
def get_validation_data_iter(data_loader: RawParallelDatasetLoader,
validation_sources: List[str],
validation_target: str,
buckets: List[Tuple[int, int]],
bucket_batch_sizes: List[BucketBatchSize],
... | 5,339,404 |
def _serialize_property(
target_expr: str, value_expr: str, a_property: mapry.Property,
auto_id: _AutoID, cpp: mapry.Cpp) -> str:
"""
Generate the code to serialize the property.
The value as the property is given as ``value_expr`` and serialized
into the ``target_expr``.
:param ta... | 5,339,405 |
def read_raw_data(pattern):
""":return X"""
if isinstance(pattern, basestring):
fpaths = glob.glob(pattern)
elif isinstance(pattern, list):
fpaths = pattern
X = []
for fpath in fpaths:
print 'loading file {} ... ' . format(fpath)
X.extend(loadtxt(fpath))
return X | 5,339,406 |
def warp_affine_rio(src: np.ndarray,
dst: np.ndarray,
A: Affine,
resampling: Resampling,
src_nodata: Nodata = None,
dst_nodata: Nodata = None,
**kwargs) -> np.ndarray:
"""
Perform Affine warp ... | 5,339,407 |
def encode_integer_leb128(value: int) -> bytes:
"""Encode an integer with signed LEB128 encoding.
:param int value: The value to encode.
:return: ``value`` encoded as a variable-length integer in LEB128 format.
:rtype: bytes
"""
if value == 0:
return b"\0"
# Calculate the number o... | 5,339,408 |
def test_MS2DeepScoreMonteCarlo_score_pair(average_type):
"""Test score calculation using *.pair* method."""
spectrums, _, similarity_measure = get_test_ms2_deep_score_instance(n_ensembles=5,
average_type=average_type)
score = similarit... | 5,339,409 |
def google_sen_new(text_content):
"""
Analyzing Entity Sentiment in a String
Args:
text_content The text content to analyze
"""
# text_content = 'Grapes are good. Bananas are bad.' Available types: PLAIN_TEXT, HTML
client = language_v1.LanguageServiceClient()
type_ = enums.Document.Ty... | 5,339,410 |
def _create_ip_config_data():
"""
This loads into a map the result of IPCONFIG command.
"""
map_ipconfigs = dict()
curr_itf = ""
proc = subprocess.Popen(['ipconfig', '/all'], stdout=subprocess.PIPE)
for curr_line in proc.stdout.readlines():
curr_line = curr_line.decode("utf-8").r... | 5,339,411 |
def simplify_polygon_by(points, is_higher, should_stop, refresh_node):
"""
Simplify the given polygon by greedily removing vertices using a given priority.
This is generalized from Visvalingam's algorithm, which is described well here:
http://bost.ocks.org/mike/simplify/
is_higher = functio... | 5,339,412 |
def main(argv):
"""Main entry for Dataflow python job launcher.
expected input args are as follows:
project - Required. The project of which the resource will be launched.
Location - Required. The region of which the resource will be launched.
python_module_path - The gcs path to the python file or folder to... | 5,339,413 |
def get_builder(slug):
"""
Get the Builder object for a given slug name.
Args:
slug - The slug name of the installable software
"""
for builder in Index().index:
if builder.slug == slug:
return builder
return False | 5,339,414 |
def preprocess_normscale(patient_data, result, index, augment=True,
metadata=None,
normscale_resize_and_augment_function=normscale_resize_and_augment,
testaug=False):
"""Normalizes scale and augments the data.
Args:
patie... | 5,339,415 |
def get_contact_lookup_list():
"""get contact lookup list"""
try:
return jsonify(Contact.get_contact_choices())
except Exception as e:
return e.message | 5,339,416 |
def argmax(X, axis=None):
"""
Return tuple (values, indices) of the maximum entries of matrix
:param:`X` along axis :param:`axis`. Row major order.
:param X: Target matrix.
:type X: :class:`scipy.sparse` of format csr, csc, coo, bsr, dok, lil,
dia or :class:`numpy.matrix`
:param axis: Speci... | 5,339,417 |
def show_new_high_score():
""" If a new high score is achieved, the score and winning player is displayed """
print("new_high_score")
myfont = pygame.font.SysFont("Comic Sans MS", 30)
winner = "left" if cfg.l_score > cfg.r_score else "right"
score = str(cfg.new_high_score)
print(score)
text... | 5,339,418 |
def plot_pdn(Px, Tx, pdi_nCO_v, pdi_mu_v, Tmin, Tmax, Pmin, Pmax, iso_names):
"""Generate plots for a size n"""
# extract the dimensions of the simulations
pdi_nCO_v = pdi_nCO_v.copy()
pdi_mu_v = pdi_mu_v.copy()
if len(pdi_nCO_v.shape) == 2: # add one more dimension if only two provided
... | 5,339,419 |
def test_verify_sub_value_NotOK_wrong_sub():
"""
arg=None
"""
_info = setup_conv()
conv = _info['conv']
# Need an IdToken and an AuthorizationRequest with a claims request
ar = {
'scope': 'openid',
'redirect_uri': 'https://example.com/cb',
'client_id': 'client',
... | 5,339,420 |
def posts():
"""
Function accessed by AJAX to handle a Series of Posts
"""
try:
series_id = request.args[0]
except:
raise HTTP(400)
try:
recent = request.args[1]
except:
recent = 5
table = s3db.cms_post
# List of Posts in this Series
query ... | 5,339,421 |
def resolve_game_object_y_collision(moving, static):
"""Resolves a collision by moving an object along the y axis.
Args:
moving (:obj:`engine.game_object.PhysicalGameObject`):
The object to move along the y axis.
static (:obj:`engine.game_object.PhysicalGameObject`):
The... | 5,339,422 |
def update():
"""The program starts here"""
global current_level
# Initialization (only runs on start/restart)
# player = Player()
dino = DinoSprite()
group = pg.sprite.Group(dino)
sp = spritesheet("tileset48.png")
wall, wall_floor, floor = sp.images_at(
[(48, y, 16*3, 16*3... | 5,339,423 |
def filter_all(fn, *l):
"""
Runs the filter function on all items in a list of lists
:param fn: Filter function
:param l: list of lists to filter
:return: list of filtered lists
>>> filter_all(lambda x: x != "", ['a'], ['b'], [""], ["d"])
[['a'], ['b'], [], ['d']]
"""
return [filter... | 5,339,424 |
async def reply_on_message(message: types.Message):
"""Replies on user message."""
payload, url = _get_server_payload_for_user(message)
async with aiohttp.ClientSession(auth=AUTH) as session:
async with session.post(url, data=payload, headers=HEADERS) as server_response:
await reply_usin... | 5,339,425 |
def get_test_runners(args):
""" Get Test Runners """
res = list()
qitest_jsons = args.qitest_jsons or list()
# first case: qitest.json in current working directory
test_runner = get_test_runner(args)
if test_runner:
res.append(test_runner)
# second case: qitest.json specified with --... | 5,339,426 |
def test_decorator_return_val():
""" Tests tha the decorator returns value. """
returned = on_completed()
assert returned == "It works!" | 5,339,427 |
def test_build_package_name(tmp_path, monkeypatch):
"""The zip file name comes from the metadata."""
to_be_zipped_dir = tmp_path / BUILD_DIRNAME
to_be_zipped_dir.mkdir()
# the metadata
metadata_data = {'name': 'name-from-metadata'}
metadata_file = tmp_path / 'metadata.yaml'
with metadata_fi... | 5,339,428 |
def save_image(image, path):
"""Save an image as a png file."""
min_val = image.min()
if min_val < 0:
image = image + min_val
scipy.misc.imsave(path, image)
print('[#] Image saved {}.'.format(path)) | 5,339,429 |
def get_preselected_facets(params, all_categories):
""" Resolve all facets that have been determined by the GET parameters.
Args:
params: Contains the categories/facets
all_categories:
Returns:
dict: Contains all sorted facets
"""
ret_arr = {}
iso_cat = params.get("isoC... | 5,339,430 |
def has_joined(*args: list, **kwargs) -> str:
"""
Validates the user's joining the channel after being required to join.
:param args: *[0] -> first name
:param kwargs:
:return: Generated validation message
"""
first_name = args[0]
text = f"{_star_struck}{_smiling_face_with_heart} بسیار خ... | 5,339,431 |
def depth_residual_regresssion_subnet(x, flg, regular, subnet_num):
"""Build a U-Net architecture"""
""" Args: x is the input, 4-D tensor (BxHxWxC)
flg represent weather add the BN
regular represent the regularizer number
Return: output is 4-D Tensor (BxHxWxC)
"""
... | 5,339,432 |
def dist2(x, c):
"""
Calculates squared distance between two sets of points.
Parameters
----------
x: numpy.ndarray
Data of shape `(ndata, dimx)`
c: numpy.ndarray
Centers of shape `(ncenters, dimc)`
Returns
-------
n2: numpy.ndarray
Squared distances between... | 5,339,433 |
def process_name(i: int, of: int) -> str:
"""Return e.g. '| | 2 |': an n-track name with track `i` (here i=2) marked.
This makes it easy to follow each process's log messages, because you just
go down the line until you encounter the same number again.
Example: The interleaved log of four processes th... | 5,339,434 |
def cards_db(db):
"""
CardsDB object that's empty.
"""
db.delete_all()
return db | 5,339,435 |
def _geo_connected(geo, rxn):
""" Assess if geometry is connected. Right now only works for
minima
"""
# Determine connectivity (only for minima)
if rxn is not None:
gra = automol.geom.graph(geo)
conns = automol.graph.connected_components(gra)
lconns = len(conns)
els... | 5,339,436 |
def scale_to_range(image, dest_range=(0,1)):
""" Scale an image to the given range.
"""
return np.interp(image, xp=(image.min(), image.max()), fp=dest_range) | 5,339,437 |
def files():
"""Hypothesis strategy for generating objects pyswagger can use as file
handles to populate `file` format parameters.
Generated values take the format: `dict('data': <file object>)`"""
return file_objects().map(lambda x: {"data": x}) | 5,339,438 |
def get_histograms(
query: Optional[str] = None, delta: Optional[bool] = None
) -> Generator[dict, dict, list[Histogram]]:
"""Get Chrome histograms.
Parameters
----------
query: Optional[str]
Requested substring in name. Only histograms which have query as a
substring in the... | 5,339,439 |
def energy_decay_curve_chu_lundeby(
data,
sampling_rate,
freq='broadband',
noise_level='auto',
is_energy=False,
time_shift=True,
channel_independent=False,
normalize=True,
plot=False):
""" This function combines Chu's and Lundeby's methods:
... | 5,339,440 |
def sinkhorn(
p, q, metric="euclidean",
):
"""
Returns the earth mover's distance between two point clouds
Parameters
----------
cloud1 : 2-D array
First point cloud
cloud2 : 2-D array
Second point cloud
Returns
-------
distance : float
The distance betwee... | 5,339,441 |
def generate_s3_events(cluster_name, cluster_dict, config):
"""Add the S3 Events module to the Terraform cluster dict.
Args:
cluster_name (str): The name of the currently generating cluster
cluster_dict (defaultdict): The dict containing all Terraform config for a given cluster.
config ... | 5,339,442 |
def _check_predictor_matrix(
predictor_matrix, allow_nan=False, min_num_dimensions=3,
max_num_dimensions=5):
"""Checks predictor matrix for errors.
:param predictor_matrix: numpy array of predictor images. Dimensions may be
E x M x N, E x M x N x C, or E x M x N x T x C.
:param all... | 5,339,443 |
def cluster_seg(bt, seg_list, radius):
"""
Fetch segments which align themself for a given tolerance.
"""
cluster, seen_ix = [], set()
for i, seg in enumerate(seg_list):
if i not in seen_ix:
sim_seg_ix = list(bt.query_radius([seg], radius)[0])
seen_ix |= set(sim_se... | 5,339,444 |
def stage_grid(
Dstg,
A,
dx_c,
tte,
min_Rins=None,
recamber=None,
stag=None,
resolution=1.
):
"""Generate an H-mesh for a turbine stage."""
# Change scaling factor on grid points
# Distribute the spacings between stator and rotor
dx_c = np.array([[dx_c[0], dx_c[1] / 2.... | 5,339,445 |
def get_best_trial(trial_list, metric):
"""Retrieve the best trial."""
return max(trial_list, key=lambda trial: trial.last_result.get(metric, 0)) | 5,339,446 |
def connect_signals(**kwargs):
"""
Listens to the ``initializing`` signal and tells other modules to
connect their signals. This is done so as to guarantee that django
is loaded first.
"""
from reviewboard.notifications import email, webhooks
email.connect_signals()
webhooks.connect_sig... | 5,339,447 |
def director_score():
"""
use .agg() operation to pass .count() and .sum()
counts the number of movies for each director.
sum the IMDB score of the movies from each director.
renames columns, sort the values in descending order.
calculates average score and create a new column.
"""
gb_di... | 5,339,448 |
def plot_confusion_matrix(cm, xticks, yticks, normalize=False, ignore_main_diagonal=False,
cmap=plt.cm.binary):
"""
plots a confusion matrix using matplotlib
Parameters
----------
cm : (tensor or numpy array)
confusion matrix
e.g. from tf.math.confusion_ma... | 5,339,449 |
def processMultiplierSegment(segment, source_dir_band, wind_prj, bear_prj, dst_band):
"""
Calculates local wind multiplier data by image segments
and writes to corresponding segment of output file
:param segment: image segment specified by [x_offset, y_offset,
width, height, segment... | 5,339,450 |
def make_registry_metaclass(registry_store):
"""Return a new Registry metaclass."""
if not isinstance(registry_store, dict):
raise TypeError("'registry_store' argument must be a dict")
class Registry(type):
"""A metaclass that stores a reference to all registered classes."""
def _... | 5,339,451 |
def test_chairman_info(
session: Session, id: int, true_title: str, true_firstname: str, true_lastname: str
) -> None:
"""Test that chairman info is correctly parsed."""
[element] = session.xml_transcript.xpath(f"(. //*[local-name() = 'Toimenpide'])[{id}]")
title, firstname, lastname = session.get_chair... | 5,339,452 |
def bind11(reactant, max_helix = True):
"""
Returns a list of reaction pathways which can be produced by 1-1 binding
reactions of the argument complex. The 1-1 binding reaction is the
hybridization of two complementary unpaired domains within a single complex
to produce a single unpseudoknotted prod... | 5,339,453 |
def test_three_code_wars():
"""Test function that emulates test.assert_equals(nth_even(3), 4)."""
from get_nth_even_number import nth_even
assert nth_even(3) == 4 | 5,339,454 |
def benchmark():
"""
Some basic performance benchmarks. You are encouraged to implement
your own 'next' function!
"""
sg = SudokuGames(end=24)
iter_, recu_ = Sudoku.solve_iterative, Sudoku.solve_recursive
# tuple of pairs that define the solver function. First element picks the
# flavou... | 5,339,455 |
def main(url, owner, repo, outdir=None, suffix=None):
"""Route request."""
token, api_url = parse_url(url)
dl_assets = get_latest_assets(api_url, owner, repo, token, suffix)
if outdir is not None and not os.path.isdir(outdir):
os.makedirs(outdir)
for pkg_name, pkg_url in dl_assets:
... | 5,339,456 |
def main():
"""
Creates a knowledge resource from triplets file: first step,
receives the entire triplets file and saves the following files:
'_path_to_id.db', '_id_to_path.db', '_term_to_id.db', '_id_to_term.db'
"""
# Get the arguments
args = docopt("""Creates a knowledge resource from tri... | 5,339,457 |
def get_all_movie_props(movies_set: pd.DataFrame, flag: int, file_path: str):
"""
Function that returns the data frame of all movie properties from dbpedia
:param movies_set: data set of movies with columns movie id and movie dbpedia uri
:param flag: 1 to generate the data frame from scratch and 0 to re... | 5,339,458 |
def convert_to_clocks(duration, f_sampling=200e6, rounding_period=None):
"""
convert a duration in seconds to an integer number of clocks
f_sampling: 200e6 is the CBox sampling frequency
"""
if rounding_period is not None:
duration = max(duration//rounding_period, 1)*rounding_period
... | 5,339,459 |
def _add_supplemental_plot_info(infos_copy, item, common_data):
"""Add supplemental info to plot description"""
suppl_info = []
if item.get('dpSupplementalMessage'):
# Short information about future release of tv show season or other
suppl_info.append(item['dpSupplementalMessage'])
# The... | 5,339,460 |
def account_approved(f):
"""Checks whether user account has been approved, raises a 401 error
otherwise .
"""
def decorator(*args, **kwargs):
if not current_user:
abort(401, {'message': 'Invalid user account.'})
elif not current_user.is_approved:
abort(401, {'mess... | 5,339,461 |
def multiply(x):
"""Multiply operator.
>>> multiply(2)(1)
2
"""
def multiply(y):
return y * x
return multiply | 5,339,462 |
def tally_transactions(address, txs):
"""Calculate the net value of all deposits, withdrawals and fees
:param address: Address of the account
:param txs: Transactions JSON for the address
:returns: The total net value of all deposits, withdrawals and fees
"""
send_total = 0
for it... | 5,339,463 |
def test_fft3d():
"""Test 3d fft core function."""
arr3d_f = fourier.fft3d(arr3d, mode="forward")
assert arr3d_f.shape == (n_pixels, n_pixels, n_pixels)
arr3d_r = fourier.fft3d(arr3d_f, mode="inverse")
assert arr3d_r.shape == (n_pixels, n_pixels, n_pixels) | 5,339,464 |
def expose(policy):
"""
Annotate a method to permit access to contexts matching an authorization
policy. The annotation may be specified multiple times. Methods lacking any
authorization policy are not accessible.
::
@mitogen.service.expose(policy=mitogen.service.AllowParents())
de... | 5,339,465 |
def _bytes_feature(value):
"""Creates a bytes feature from the passed value.
Args:
value: An numpy array.
Returns:
A TensorFlow feature.
"""
return tf.train.Feature(
bytes_list=tf.train.BytesList(
value=[value.astype(np.float32).tostring()])) | 5,339,466 |
def get_cell_phase(
adata: anndata.AnnData,
layer: str = None,
gene_list: Union[OrderedDict, None] = None,
refine: bool = True,
threshold: Union[float, None] = 0.3,
) -> pd.DataFrame:
"""Compute cell cycle phase scores for cells in the population
Arguments
---------
adata: :clas... | 5,339,467 |
def pm_callback(sender, **kwargs):
"""
Post Migrate callbghack Re/load sql files and move models to schemas
"""
load_sql_files(sender)
move_models_to_schemas(sender) | 5,339,468 |
def variational_lower_bound(prediction):
"""
This is the variational lower bound derived in
Auto-Encoding Variational Bayes, Kingma & Welling, 2014
:param [posterior_means, posterior_logvar,
data_means, data_logvar, originals]
posterior_means: predicted means for the posterior
... | 5,339,469 |
def didGen(vk, method="dad"):
"""
didGen accepts an EdDSA (Ed25519) key in the form of a byte string and returns a DID.
:param vk: 32 byte verifier/public key from EdDSA (Ed25519) key
:param method: W3C did method string. Defaults to "dad".
:return: W3C DID string
"""
if vk is None:
... | 5,339,470 |
def part_1( pwd_data ):
"""
For each line in pwd_data:
* element 0 contains the min/max counts. It is stored as <str>-<str> it will
need to be split and each of the 2 new elements cast to ints.
* element 1 contains the character to count in the provided password string.
It will have a trail... | 5,339,471 |
def load_dataset(datapath):
"""Extract class label info """
with open(datapath + "/experiment_dataset.dat", "rb") as f:
data_dict = pickle.load(f)
return data_dict | 5,339,472 |
def deleteupload():
"""Deletes an upload.
An uploads_id is given and that entry is then removed from the uploads table
in the database.
"""
uploads_id = request.args.get('uploads_id')
if not uploads.exists(uploads_id=uploads_id):
return bad_json_response(
'BIG OOPS: Somethi... | 5,339,473 |
def read(fn, offset, length, hdfs=None):
""" Read a block of bytes from a particular file """
with hdfs.open(fn, 'r') as f:
f.seek(offset)
bytes = f.read(length)
logger.debug("Read %d bytes from %s:%d", len(bytes), fn, offset)
return bytes | 5,339,474 |
def load_json(filename: str) -> Dict:
"""Read JSON file from metadata folder
Args:
filename: Name of metadata file
Returns:
dict: Dictionary of data
"""
filepath = (
Path(__file__).resolve().parent.parent.joinpath("metadata").joinpath(filename)
)
metadata: Dict = js... | 5,339,475 |
def assert_db_got_replaced(rotkehlchen_instance: Rotkehlchen, username: str):
"""For environment setup with setup_starting_environment make sure DB is replaced"""
# At this point pulling data from rotkehlchen server should have worked
# and our database should have been replaced. The new data have different... | 5,339,476 |
def main():
"""Given a dashboard title, get the ids of all dashboards with matching titles
and move them to trash.
$ python soft_delete_dashboard.py "An Unused Dashboard"
"""
dashboard_title = sys.argv[1] if len(sys.argv) > 1 else ""
if not dashboard_title:
raise sdk_exceptions.Argume... | 5,339,477 |
def get_riemann_sum(x, delta_x):
"""
Returns the riemann `sum` given a `function` and
the input `x` and `delta_x`
Parameters
----------
x : list
List of numbers returned by `np.linspace` given a lower
and upper bound, and the number of intervals
delta_x :
The inter... | 5,339,478 |
def initialize_library(verbose):
""" Sets the native library verbosity
Args:
verbose: Set to 1 for redirecting native library logs to stderr. For full debug
information, compile the RQRMI library with DEBUG flag.
"""
global _library_initialzied
if _library_init... | 5,339,479 |
def MPO_rand(n, bond_dim, phys_dim=2, normalize=True, cyclic=False,
herm=False, dtype=float, **mpo_opts):
"""Generate a random matrix product state.
Parameters
----------
n : int
The number of sites.
bond_dim : int
The bond dimension.
phys_dim : int, optional
... | 5,339,480 |
def test_api_exception(symbol='invalid'):
"""Test API response Exception"""
with pytest.raises(CryptowatchAPIException):
client.get_assets(symbol) | 5,339,481 |
def get_short_size(size_bytes):
"""
Get a file size string in short format.
This function returns:
"B" size (e.g. 2) when size_bytes < 1KiB
"KiB" size (e.g. 345.6K) when size_bytes >= 1KiB and size_bytes < 1MiB
"MiB" size (e.g. 7.8M) when size_bytes >= 1MiB
size_bytes: File siz... | 5,339,482 |
def stop_evennia():
"""
This instructs the Portal to stop the Server and then itself.
"""
def _portal_stopped(*args):
print("... Portal stopped.\nEvennia shut down.")
_reactor_stop()
def _server_stopped(*args):
print("... Server stopped.\nStopping Portal ...")
send... | 5,339,483 |
def pair_setup(
auth_type: AuthenticationType, connection: HttpConnection
) -> PairSetupProcedure:
"""Return procedure object used for Pair-Setup."""
_LOGGER.debug("Setting up new AirPlay Pair-Setup procedure with type %s", auth_type)
if auth_type == AuthenticationType.Legacy:
srp = LegacySRPAu... | 5,339,484 |
def score_from_srl(srl_path, truth_path, freq, verbose=False):
"""
Given source list output by PyBDSF and training truth catalogue,
calculate the official score for the sources identified in the srl.
Args:
srl_path (`str`): Path to source list (.srl file)
truth_path (`str`): Path to tra... | 5,339,485 |
def get_feature_read(key, max_num_bbs=None):
"""Choose the right feature function for the given key to parse TFRecords
Args:
key: the feature name
max_num_bbs: Max number of bounding boxes (used for `bounding_boxes` and `classes`)
max_num_groups: Number of pre-defined groups (used f... | 5,339,486 |
def kernel(cc, eris, t1=None, t2=None, max_cycle=50, tol=1e-8, tolnormt=1e-6,
verbose=logger.INFO):
"""Exactly the same as pyscf.cc.ccsd.kernel, which calls a
*local* energy() function."""
if isinstance(verbose, logger.Logger):
log = verbose
else:
log = logger.Logger(cc.stdout... | 5,339,487 |
def test_generate_import_code_2():
"""Assert that generate_import_code() returns the correct set of dependancies and dependancies are importable."""
pipeline_string = (
'KNeighborsClassifier(CombineDFs('
'DecisionTreeClassifier(input_matrix, DecisionTreeClassifier__criterion=gini, '
'De... | 5,339,488 |
def on_session_started(session_started_request, session):
""" Called when the session starts
Can be used to initialize values if used across intents.
"""
print("on_session_started requestId=" + session_started_request['requestId']
+ ", sessionId=" + session['sessionId']) | 5,339,489 |
def get_arguments():
"""parse provided command line arguments"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--server",
help="Where to send the output - use https URL to POST "
"to the dognews server API, or a file name to save locally as json",
required=True)
... | 5,339,490 |
async def getAllDestinyIDs():
"""Returns a list with all discord members destiny ids"""
select_sql = """
SELECT
destinyID
FROM
"discordGuardiansToken";"""
async with (await get_connection_pool()).acquire(timeout=timeout) as connection:
result = await conne... | 5,339,491 |
def login():
"""Handles login for Gello."""
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is not None and user.verify_password(form.password.data):
login_user(user, form.remember_me.data)
return red... | 5,339,492 |
def create_loss_functions(interconnector_coefficients, demand_coefficients, demand):
"""Creates a loss function for each interconnector.
Transforms the dynamic demand dependendent interconnector loss functions into functions that only depend on
interconnector flow. i.e takes the function f and creates g by... | 5,339,493 |
def num2proto(pnum):
"""Protocol number to name"""
# Look for the common ones first
if pnum == 6:
return "tcp"
elif pnum == 17:
return "udp"
elif pnum == 1:
return "icmp"
elif pnum == 58:
# Use the short form of icmp-ipv6 when appropriate
return "icmpv6"
... | 5,339,494 |
def get_problem_size(problem_size, params):
"""compute current problem size"""
if callable(problem_size):
problem_size = problem_size(params)
if isinstance(problem_size, (str, int, np.integer)):
problem_size = (problem_size, )
current_problem_size = [1, 1, 1]
for i, s in enumerate(pr... | 5,339,495 |
def zip_dir(path):
"""
Create a zip archive containing all files and dirs rooted in path.
The archive is created in memory and a file handler is returned by the function.
Args:
path: directory containing the resources to archive.
Return:
file_out: file handler pointing to the compre... | 5,339,496 |
def interpolate(x,
size=None,
scale_factor=None,
mode='nearest',
align_corners=False,
align_mode=0,
data_format='NCHW',
name=None):
"""
This op resizes a batch of images.
The input must be a 3-D ... | 5,339,497 |
def encode_auth_token(user_id):
"""
Generates the Auth Token
:return: string
"""
try:
payload = {
'exp': datetime.datetime.utcnow() + datetime.timedelta(days=90),
'iat': datetime.datetime.utcnow(),
'sub': user_id
}
return jwt.encode(
... | 5,339,498 |
def count_weighted_pairs_3d_cuda_fix(
x1, y1, z1, w1, x2, y2, z2, w2, rbins_squared, result):
"""Naively count Npairs(<r), the total number of pairs that are separated
by a distance less than r, for each r**2 in the input rbins_squared.
"""
start = cuda.grid(1)
stride = cuda.gridsize(1)
... | 5,339,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.