content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def normalize_image_min_max(image, min_image, max_image):
"""normalizes an image (from [min_image;max_image] to [0;1])
Args:
image (numpy.ndarray): input image
min_image (float): input image manual min value (all values below will be set to 0)
max_image (float): input image manu... | d314ef09feed7342b5229ce95c8815b3d4da7a6d | 58,478 |
def setup_es(endpoint, dataset, production,
drop_and_recreate=False, increment_version=False):
"""Retrieve the ES connection, ES config and setup the index
if required.
Args:
endpoint (str): Name of the AWS ES endpoint.
dataset (str): Name of the dataset for the ES mapping.
... | cc8a2731c3d09dfcf64454b7d7c65adb119494bf | 58,479 |
import numbers
import math
def _sd_of_runs(stats, mean, key='runs'):
"""Obtain the standard deviation of stats.
Args:
stats: dict; A set of stats, structured as above.
mean: dict; Mean for each key in stats.
key: str; Optional key to determine where list of runs is found in stats
... | 3736fa81b782e2ef45fe1acc7a300047f215ce1d | 58,480 |
from typing import Optional
import re
def get_biolink_element(name) -> Optional[Element]:
"""
Get Biolink element for a given name, where name can be a class, slot, or relation.
Parameters
----------
name: str
The name
Returns
-------
Optional[biolinkml.meta.Element]
... | c5cfe635dee723590d762e41f37ef22ac4221a4d | 58,481 |
def make_path(index, bits):
"""
Given a size of a node to add get the binary path to reach it.
"""
mask = 2**np.arange(bits-1, -1, -1)
x = np.bitwise_and(np.array(index+1).ravel(), mask) != 0
def path(c, a):
x = a + 2 * c
x = np.minimum(x, index+1)
return x, x
_, x =... | 6e0cb999eb52fe5af708af43e85d0977bf3a94c7 | 58,482 |
import stat
def _get_type_by_stat(st_mode):
"""Match special filesystem objects to Mimetypes."""
if stat.S_ISDIR(st_mode): return inode_dir
elif stat.S_ISCHR(st_mode): return inode_char
elif stat.S_ISBLK(st_mode): return inode_block
elif stat.S_ISFIFO(st_mode): return inode_fifo
elif stat.S_IS... | 7e202a31013b32098d9929052fba2ef04e65af38 | 58,483 |
def sm_to_pandas(sm):
"""
Convert a score matrix that is the result of sciunit TestSuite
to a regular pandas dataframe.
"""
n_rows, n_cols = sm.shape
arr = np.empty(shape=(n_rows, n_cols), dtype=np.float64)
for i in range(n_rows):
for j in range(n_cols):
arr[i, j] = sm.ia... | 2143cf69d00175fbd008f54b7572fb8d7f7c1ca4 | 58,485 |
def is_in_group(user, group_name):
"""
Check if a user in a group named ``group_name``.
:param user User:
The auth.User object
:param group_name str:
The name of the group
:returns: bool
"""
return user.groups.filter(name__exact=group_name).exists() | 25e51e483b0c18c03f8e897725f07e9e63cc160a | 58,486 |
import csv
def read_pairs_from_csv(filename, skip_first=False):
"""Read numbers from file in format ROMAN;DECIMAL.
This will return a list of (roman_numeral: string, decimal: int) tuples.
The Roman numerals will have square brackets removed.
"""
with open(filename) as csvfile:
if skip_fir... | f0a7e80a8860f0b26d78cceffd454c4b5ed64235 | 58,487 |
from datetime import datetime
def create(task):
"""
This function creates a new task in the tasks structure
based on the passed in task data
:param task: task to create in tasks structure
:return: 201 on success, 406 on task exists
"""
title = task.get("title")
duedate = task.... | 575a027be2892e649de250fc47283ea186cd78d4 | 58,488 |
def MakeReverseCompoMapping(font):
"""Return a dict that maps glyph names to lists containing tuples
of the form:
(clientGlyphName, componentIndex)
"""
font = unwrapFont(font)
reverseCompoMapping = {}
for g in font.glyphs:
for i, c in zip(range(len(g.components)), g.components):
base = font[c.index].name... | 416466c4a0f9d1e8e13bb883e275e5a69b174d86 | 58,489 |
def get_anno_bbox(img_id, scale_factor_row, scale_factor_col):
"""
根据xml文件获取标注的整体bbox
"""
xml_fname = id_to_xml(img_id)
tree = ET.parse(xml_fname)
root = tree.getroot()
annotations = root[0]
minx, miny, maxx, maxy = 1e10, 1e10, 0, 0
for each_annotation in annotations:
for eac... | 26105abb70db6ae2722ccddcdbd8aebef700308f | 58,491 |
def label_colormap(n_label=256, value=None):
"""Label colormap.
Parameters
----------
n_labels: int
Number of labels (default: 256).
value: float or int
Value scale or value of label color in HSV space.
Returns
-------
cmap: numpy.ndarray, (N, 3), numpy.uint8
La... | d16c149e294fdbb7e14895061cf1ad7148b51e76 | 58,492 |
def create_group_transition_probs(states, assort_by, params, model_name):
"""Create a transition matrix for groups.
Args:
states (pandas.DataFrame): The states.
assort_by (list): List of variables that influence matching probabilities.
params (pandas.DataFrame): The parameters.
... | ff288bcdeb0d928c6f79127987af115f86773868 | 58,493 |
def _cached_to(attr_name):
"""
Оборачивает простые методы (без аргументов) и property getters,
с целью закэшировать первый полученный результат
"""
def wrapper(fn):
@wraps(fn)
def inner(self):
if hasattr(self, attr_name):
result = getattr(self, attr_name)
... | 098d72ad164f6794492747f0dbefa752f0c92028 | 58,494 |
def pickArgs(local_state, global_state, node_name, argument_specs, operation,predecessors):
"""
:param local_state:
:param global_state:
:param argument_specs:
:param operation:
:param predecessors:
:return:
@type operation : Operation
@type predecessors: List[str]
"""
startT... | 6b9f6f06ae6fd9489be72e5cbf57bfad3bc830b3 | 58,495 |
def imshow(image, ax=None, title=None, normalize=True):
"""Imshow for Tensor."""
if ax is None:
fig, ax = plt.subplots()
image = image.numpy().transpose((1, 2, 0))
if normalize:
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
image = std * im... | 35fe7c6e945c978a3e7082aad7e36b87d6dc9ac6 | 58,496 |
def calc_bic(eprofile, bi2014):
"""
Calculates the Bayesian Information Criterion
See: https://www.immagic.com/eLibrary/ARCHIVES/GENERAL/WIKIPEDI/W120607B.pdf
Parameters
----------
eprofile
bi2014
Returns
-------
"""
err_var = crr_error_variance(eprofile, bi2014.crr_m7p5)... | 0827bc54a235f157fa6ceb5ba6db56158993d62e | 58,498 |
def _derive_entity_label_matrix(train_full_results, entities):
"""
Derive entity feature matrix for chi2 anaylsis using entity annotations from message api
:param train_full_results: pandas data frame outputed by inference
:param entities: list of entities that is defined in the workspace
:return en... | ce806a97ce83d50226b1a68b09e986c0225ec955 | 58,499 |
import random
def example_3() -> Body_System:
"""
Example 3: Random system with many bodies.
No doctest provided since this function does not have a return value.
"""
bodies = []
for i in range(10):
velocity_x = random.uniform(-0.5, 0.5)
velocity_y = random.uniform(-0.5, 0.5)
... | 1034578080f3a450bda0248897fa5d18133ef21c | 58,500 |
import scipy
def distribution1d(X, Y, title='', figshape=(1, 1), scatter=False, mean=False,
median=True, range=True, range_alpha=0.3, convolve=False,
xlog=False, ylog=True, labels=[]):
""" X,Y: lists of x,y data """
n_subplots = len(Y)
cols, rows = figshape
assert... | 40c4cc1833c25f2fd7a60d05efc22bbfdf1bac97 | 58,501 |
def get_dfs(object_ids):
"""Retrieve dataframes from the object store given their object IDs."""
buffers = client.get_buffers(object_ids)
return [pa.RecordBatchStreamReader(buf).read_next_batch().to_pandas()
for buf in buffers] | 770bcc4d2d56c3d7656a6f55ce320137b238ac78 | 58,502 |
import torch
def ce_loss(logits, targets):
"""
logits: (torch.float32) shape (N, C, H, W)
targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1}
"""
targets = targets.type(torch.int64)
ce_loss = F.cross_entropy(logits, targets)
return ce_loss | 9c5a5ebcd5f285cf39236e0c1926fbc291ba9b62 | 58,503 |
from typing import Callable
import tqdm
import time
def experiment(method: str, step_size: float, num_steps: int, num_samples: int, proposal: Callable, randomize_steps: bool):
"""Experiment to examine the use of different integrators for sampling from
Neal's funnel distribution. Given a proposal operator, att... | f547dbeabd6fb0b16c5fae11784c140f92b95f6a | 58,504 |
def get_pars(ts, coors, mode='qp',
equations=None, term=None, problem=None, **kwargs):
"""
The material nonlinearity function - the Lamé coefficient `mu`
depends on the strain.
"""
if mode != 'qp': return
val = nm.empty(coors.shape[0], dtype=nm.float64)
val.fill(1e0)
order... | 4ca313924c86f20f51943f2584279236b274758a | 58,505 |
def get_day_02():
"""Returns the ``Day02`` for the puzzle data."""
return Day02(
read_lines_of_datafile('day_02_data.txt')
) | fa97835d7af954f6028d0ad5a7e699fa8fe5ceed | 58,506 |
def post_process_tree(G):
"""
Given a networkx graph in the form of a tree, assign sample identities to character states.
:param graph: Networkx Graph as a tree
:return: postprocessed tree as a Networkx object
"""
new_nodes = []
new_edges = []
for n in G.nodes:
spl = n.split("... | aba4654d174e3bf5e8706ca3e8a8d2bae8461129 | 58,507 |
def init_db():
"""
Establishing the connection with MongoDB
"""
connection = MongoClient(cons.ip_port_initial_db)
connection.sampledb.authenticate(cons.mongoUserName, cons.mongoPasswd)
db = connection.sampledb
return db | fa135ddf1166cab5ad7588dbc6fd6ac9900e9c25 | 58,508 |
def select(text: str, cases: list, default: int = None, case_sensitive: bool = False):
"""
Let user select one of the cases.
Args:
text (str): Text.
cases (list[tuple]): Cases, should be list of tuples. Each tuple is in form `('display text', 'user's input')`.
For ex... | 0875134cd5f4f824a10ab4c51a6bd4f834830250 | 58,509 |
def _preprocess_data(lulc_lookup_dict, lulc_snapshot_list):
"""Preprocess data.
Args:
lulc_lookup_dict (dict): dictionary of lookup values
lulc_snapshot_list (list): list of raster paths
Returns:
transition_matrix_dict (dict): dictionary of transitions for transition
ma... | c287c16db0aa3e335e28931c8b48572ceb4a0e05 | 58,510 |
def k_means_cluster(colors):
"""
Color recovery has errors.
Hence, look at colors, cluster them, and pick an average color per cluster.
:param colors: Colors to cluster.
:return: Clustered colors.
"""
global kmeans_num_clusters
flattened = colors.reshape([-1, colors.shape[-1]])
km... | 359dce1267ddd114786a39ff6d3d537b495f3b83 | 58,511 |
def cluster_hyperbola(npts, fac=3.0):
"""Return a hyperbolic tangent clustering function."""
xhat = np.linspace(-1.0, 1.0, npts)
return np.tanh(fac * xhat) / 2.0 / np.tanh(fac) + 0.5 | 3f13e6076381cd9a3da8187e77536a111fa9cf02 | 58,512 |
def remote_db_val_from_raw_val(grpc_address: str) -> bytes:
"""Format a remote db value from it's grpc address string
Parameters
----------
grpc_address : str
IP:PORT where the grpc server can be accessed
Returns
-------
bytes
formated representation of the grpc address sui... | 4e4386391faf25e06bbf859fddd06812a0ce9c4c | 58,513 |
def list_snapshots(session, verbose):
# type: (Session, bool) -> Union[List[str], List[Dict[str,str]]]
"""List the snapshots in the current network."""
if not session.network:
raise ValueError("Network must be set to list snapshots")
url_tail = "/{}/{}/{}".format(
CoordConstsV2.RSC_NETWO... | d8e42ff7f97c9041b5234bf58bc81dc775f2a9cb | 58,514 |
def __data_suppression(indicator_dataframe):
"""Helper function to reduce data used by the large indicator dataframe"""
# Couple columns we just don't need
indicator_dataframe.drop(columns = {'SpatialDimType','TimeDimType','DataSourceDimType',
'Date','TimeDimensionValue','TimeD... | fa9d205c2d5b9ae8a668247fc32abc76c562a9e7 | 58,516 |
def strip_email(s: str) -> str:
"""
Filter which extracts the first part of an email to make an shorthand
for user.
:param s: Input email (or any string).
:type s: str
:return: A shorthand extracted.
:rtype: str
"""
return s.split('@', 1)[0] | 36ea94b9eb12e0e64b78965c66233578790e6a13 | 58,517 |
def flat_node_and_edge(nodes, eids, weights=None):
"""flatten the sub-lists to one list"""
nodes = list(set(traverse(nodes)))
eids = list(traverse(eids))
if weights is not None:
weights = list(traverse(weights))
return nodes, eids, weights | f6103c00c374cca58884093de4ada3a319709f21 | 58,518 |
def name_item_info(mosaic_info, item_info):
"""
Generate the name for a mosaic metadata file in Azure Blob Storage.
This follows the pattern `metadata/quad/{mosaic-id}/{item-id}.json`.
"""
return f"metadata/quad/{mosaic_info['id']}/{item_info['id']}.json" | db78eb175f6530ace2037ed89cb090591c82147f | 58,519 |
import itertools
import pandas as pd
def get_all_locations_from_jobs(jobs, start_time, end_time):
"""Return a list of Location objects collected from each job in jobs.
Pulls Location objects from each Job's associated Shift
Location list is sorted by timestamp.
Args:
jobs ([Job]): List of J... | b709cf141e6e432cc41f5c390059b40d5de31d3b | 58,521 |
from pathlib import Path
def load_sheets(t_list=None):
"""Load mapping for given sheets.
Loads a lsit of .xlsx files from disk as named in `t_list`. Generates a
nested dict through which individual codes can be accessed and decoded to
a human-readable format.
Parameters
----------
t_list... | 072cd5a782580e2ee5e5cedd035b947c85e4e143 | 58,522 |
def get_D_matrix_for_angle(angle, j, cached=True):
"""
Interface to *D_matrix_conj()*
:param angle: Dict of angle data {"alpha","beta","gamma"}
:param j: Integer :math:`2j` in the formula
:param cached: Haven't been used???
:return: Array of the conjugated D-matrices. Same length as the angle d... | df3ce7046b12c328087278d92dda1721ad6ca5c8 | 58,523 |
def ptfhost(testbed_devices):
"""
Shortcut fixture for getting PTF host
"""
return testbed_devices["ptf"] | 25fdbc9520c4cda9719887ff213ccb2b88918dcc | 58,524 |
from datetime import datetime
def add_current_time_to_state(state):
"""Annotate state with the latest server time"""
state['currentTime'] = datetime.now().timestamp()
return state | f61fa2d7b127fbebb22fc277e16f2f79cdd4acd3 | 58,525 |
def volCube(edge: float) -> float:
"""Finds volume of a cube"""
volume: float = edge * edge * edge
return volume | 34d42c35b04d73fb1a925076fcaab47a932ee394 | 58,526 |
import time
def delay(fn):
"""Decorator function to delay the execution of a function.
The function that use this decorator must have delay as a keyword
argument.
"""
def wrapper(*args, **kwargs):
seconds = kwargs.get('delay', 0)
time.sleep(seconds)
return fn(*args, **kwa... | 459fe2741af565225b1d9aee4e8841460d1bff4e | 58,527 |
import re
def normalize_rgb_colors_to_hex(css):
"""Convert `rgb(51,102,153)` to `#336699`."""
regex = re.compile(r"rgb\s*\(\s*([0-9,\s]+)\s*\)")
match = regex.search(css)
while match:
colors = map(lambda s: s.strip(), match.group(1).split(","))
hexcolor = '#%.2x%.2x%.2x' % tuple(m... | e3650f525d1d9c1e7bbf7d5b4161712a7439b529 | 58,528 |
def validate_input_for_delete_role(role_for_the_profile_list) -> int:
"""ロール削除時のユーザー入力を validate"""
prompt_str = INPUT_No
min_menu_num = 1
max_menu_num = len(role_for_the_profile_list)
return ask_for_selection(prompt_str, min_menu_num, max_menu_num) | e9ec9856230da818c5a25ecd9c60f3c9476b9dc1 | 58,529 |
def replay():
"""
Function that asks the player if they want to play again and
returns a boolean True if they do want to play again.
:return:
"""
return input('Do you want to play again? \nEnter Yes or No: ').lower().startswith('y') | b95119baf68cf056a5abd9b5cb17036da8aa775a | 58,530 |
def _marble_of_player(player: Player) -> Marble:
"""Returns the corresponding `abalone_engine.enums.Marble` for a given `abalone_engine.enums.Player`.
Args:
player: The `abalone_engine.enums.Player` whose `abalone_engine.enums.Marble` is wanted.
Returns:
The `abalone_engine.enums.Marble` w... | 9860409c67625ff3ceefd4b006a1d3a22ddf30e5 | 58,532 |
def breadth_first_search(adjacency: sparse.csr_matrix, source: int, return_predecessors: bool = True):
"""Breadth-first ordering starting with specified node.
* Graphs
* Digraphs
Based on SciPy (scipy.sparse.csgraph.breadth_first_order)
Parameters
----------
adjacency :
The adjace... | 24a33f15d51191da38d33b054410894bbdd76cb2 | 58,533 |
def bessel2(order, x):
"""Evaluate `Bessel function of the second kind <https://en.wikipedia.org/wiki/Bessel_function>`_."""
if order == 0:
return y0(x)
if order == 1:
return y1(x)
return yv(order, x) | 4b565d85629749353eb9e5d02ef9bbb286148af9 | 58,534 |
from typing import Union
from typing import List
from typing import Dict
from typing import Tuple
from typing import Optional
def rdm_comparison_scatterplot(rdms,
show_marginal_distributions: bool = True,
show_identity_line: bool = True,
... | 2adac1b20660a174febc5cef4bdef9918318a010 | 58,535 |
def start_end_temp_stats():
"""When given the start and the end date, calculate the TMIN, TAVG, and TMAX for dates between the start and end date inclusive."""
return jsonify() | 30a79b2c90a40a1822a1ff52515deb0209584c59 | 58,537 |
def bernoulli(X):
"""
If x1,x2,...xn ~iid~ BER(p), then the MLE, p-hat, is X-bar
Parameters
----------
X : array_like
Returns:
----------
bernoulli_mle : MLE calculation for p-hat for Bernoulli distribution
References
----------
[1] Casella, G., ... | 1891c179b5b4bbe0785234a8a10bb6da08ebf66f | 58,538 |
def fetch(station: str) -> str:
"""
Returns TAF report string or raises an error
Maintains backwards compatability but uses the new Service object.
It is recommended to use the Service class directly instead of this function
"""
return service.get_service(station)('taf').fetch(station) | 37acb01cb90aeee7d79f22a2dc1ed8308524f3cd | 58,539 |
def run(command, parser, known_args, unknown_args):
""" run command """
release_file = utils.get_heron_release_file()
with open(release_file) as release_info:
for line in release_info:
print line,
return True | 5e427e83ddaede4b7cb065212dcc6641c46f4099 | 58,540 |
def trial(df_train, test_data):
"""
Test 1: 1s followed by 3s
"""
my_test_data = test_data.drop(['avg_stand'], axis=1)
y = df_train['state'].values
X = df_train.drop(['avg_stand', 'stand', 'state', 'index'], axis=1)
if X.isnull().values.any() == False:
rf = RandomForestClassifier(b... | 08ad0fc14df736e21088e4eb6433bda6d4a30949 | 58,541 |
def dilated_residual_conv_block(dim, kernel, stride, dilation):
"""
Use dilated convs to enlarge the receptive field
"""
return pax.Sequential(
pax.Conv1D(dim, dim, kernel, stride, dilation, "VALID", with_bias=False),
pax.LayerNorm(dim, -1, True, True),
ReLU(),
pax.Conv1D... | 6ed7da173f612dac4ca475d601034971dd47f686 | 58,542 |
import typing
import concurrent
import tqdm
def get_sparse_matrix(documents: np.ndarray, words: dict, workers: int, weighting: typing.Any=weight) -> typing.Tuple[dok.dok_matrix, np.ndarray]:
"""
Parallelize Sparse Matrix Calculation
:documents: list of document strings
:words: dictionary of word freq... | e62737e74b03ca1031d2ce4d9e0b0085212d8604 | 58,543 |
def method_codes_to_geomagia(magic_method_codes,geomagia_table):
"""
Looks at the MagIC method code list and returns the correct GEOMAGIA code number depending
on the method code list and the GEOMAGIA table specified. Returns O, GEOMAGIA's "Not specified" value, if no match.
When mutiple codes are mat... | 7939704ba51f8e199b79ddf89611ec63c6ead703 | 58,544 |
import torch
def bbures_distance(Σ1, Σ2, sqrtΣ1=None, inv_sqrtΣ1=None,
diagonal_cov=False, commute=False, squared=True, sqrt_method='spectral',
sqrt_niters=20):
""" Bures distance between PDF. Batched version. """
if sqrtΣ1 is None and not diagonal_cov:
sqrtΣ1 =... | 6f07c0489f319d95775d2f4a116a4f9fe310bb3d | 58,545 |
def async(f):
"""
异步执行函数.
"""
@wraps(f)
def wrapper(*args, **kwargs):
thr = Thread(target=f, args=args, kwargs=kwargs)
# https://docs.python.org/2/library/threading.html#threading.Thread.daemon
# 重启Flask服务器时中止正在执行的异步线程
thr.setDaemon(True)
thr.start()
ret... | cef8b1a5b7665d37d6caa277b5f7d5c18ba8f755 | 58,547 |
import torch
import math
def decode_μ_law(x: torch.Tensor, μ: int = 255) -> torch.Tensor:
"""
Applies the element-wise inverse μ-law encoding to the tensor.
Args:
x: input tensor
μ: size of the encoding (number of possible classes)
Returns:
the decoded tensor
"""
x = ... | 84b991fdb80b845796ec751756ae56140dfc2f45 | 58,548 |
def _get_histogram_data(tracking_data):
"""Returns the histogram data for the plot.
Currently we return the bins and values of the last iteration tracked before
this plot.
Args:
tracking_data (pandas.DataFrame): DataFrame holding the tracking data.
Returns:
list: Bins of the histo... | 18afd4fc320ae67c25beb635144da76a0ca81b5f | 58,549 |
def get_linear_solver(solver_type: SparseSolver = preferred_type):
"""
Privide the chosen linear solver_type function pointer to solver_type linear systems of the type A x = b, with x = f(A,b)
:param solver_type: SparseSolver option
:return: function pointer f(A, b)
"""
if solver_type == SparseS... | 4e843c4a1ae56f21557a577c91b3e2b30ed05ff6 | 58,550 |
def quick_kld(p_eval, q_eval, dx=0.01):
"""
Calculates the Kullback-Leibler Divergence between two evaluations of PDFs.
Parameters
----------
p_eval: numpy.ndarray, float
evaluations of probability distribution whose distance _from_ `q` will be calculated
q_eval: numpy.ndarray, float
... | 28d324ec5e81fd3f039747c43618264d71066097 | 58,552 |
import yaml
def dump_rendered_config_file(config):
"""Write config to file"""
return yaml.dump(config, default_flow_style=False) | 3efb499a8af1604e67906bc4c86e32c9441bd1a7 | 58,553 |
async def get_image_text(url: str, headers: dict, data) -> str:
"""
Request to a remote server for the text recognition function.
:param url: request url
:param headers: settings
:param data: data for OCR
:return: result
"""
async with ClientSession() as session:
async with sessi... | 0d82421c324948bb6224e9b0454964267ed79a67 | 58,554 |
def general_poly (L):
""" L, a list of numbers (n0, n1, n2, ... nk)
Returns a function, which when applied to a value x, returns the value
n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """
def f(x):
total = 0
fact = len(L) - 1
for num in L:
print(num)
... | 724def67b2bca32d6cfa27ef83bb3b4eff009a73 | 58,557 |
import tqdm
def polymerize_cell(mol, n, m, terminate=None, terminate2=None, cell=None, density=0.1,
ff=None, opt='rdkit', retry=50, dist_min=0.7, threshold=2.0, work_dir=None, omp=1, mpi=1, gpu=0):
"""
poly.polymerize_cell
*** DEPRECATION ***
Unit cell generator of a homopolymer b... | 934e39fa105515abc62bfadb501372fe0e18c8fc | 58,558 |
def constant_array(context, builder, ty, pyval):
"""
Create a constant array (mechanism is target-dependent).
"""
return context.make_constant_array(builder, ty, pyval) | eefd69b2f8f355e2af61f7636a586dd87a0e0419 | 58,559 |
def shape_to_spacing(region, shape, pixel_register=False):
"""
Calculate the spacing of a grid given region and shape.
Parameters
----------
region : list = [W, E, S, N]
The boundaries of a given region in Cartesian or geographic
coordinates.
shape : tuple = (n_north, n_east) or... | bc943f55330c17295bdb078d732c6ebc9f8cecfe | 58,560 |
import math
def choose_grid_size(train_inputs, ratio=1.0, kronecker_structure=True):
"""
Given some training inputs, determine a good grid size for KISS-GP.
:param x: the input data
:type x: torch.Tensor (... x n x d)
:param ratio: Amount of grid points per data point (default: 1.)
:type rati... | 1d3e30a6b7b419a1e2fcdc245830aa00d1ba493d | 58,561 |
def ldamodel_top_word_topics(topic_word_distrib, vocab, top_n=10, val_fmt=None, topic_labels=DEFAULT_TOPIC_NAME_FMT,
col_labels=None, index_name='token'):
"""
Retrieve the top (i.e. most probable) `top_n` topics for each word in the topic-word distribution
`topic_word_distrib` a... | ad6c8c0f778473e4f83a73a0e35e92ef0537e76d | 58,562 |
def convert_to_location_dictionary(array, locations=REGIONS):
"""Convert array of values ``array`` with order ``locations`` to a dictionary:
{
'place name': value
}
Assumes that the first axis of the array matches the locations."""
size = array.shape[0]
if len(array.shape) ... | e2457311bd301d04cd48ac5741d0b2d714b22cec | 58,563 |
def multihead_attention_vars(
mesh, heads, io_channels, kv_channels, activation_dtype):
"""Create Parameters for Multihead Attention.
Args:
mesh: a Mesh
heads: a Dimension
io_channels: a Dimension
kv_channels: a Dimension
activation_dtype: a tf.dtype
Returns:
q_var: a Tensor with sha... | a245b7292529d56571e3144b9b550ab24ee14fd2 | 58,564 |
import math
def vertical_angle(img, p1, p2, p3, draw=False):
"""
Calculate the angle between segment(A,B) and vertical axe
"""
x1, y1 = p1[0], p1[1]
x2, y2 = p2[0], p2[1]
x3, y3 = p3[0], p3[1]
# Calculate the Angle
radius = math.atan2(y3 - y2, x3 - x2) - math.atan2(y1 - y2, x1 - x2)
angle = math.degrees(rad... | 2566989cbe24c4d3e690efffa7caceac2d83d09c | 58,565 |
import math
def factors_convert_fract2cartes(cif_data):
"""
Edge vectors (a, b, c) in fractional coordinate –> (x, y, z) in Cartesian coordinate
cos(alpha) = b*c/(|b||c|)
cos(beta) = a*c/(|a||c|)
cos(gamma) = a*b/(|a||b|)
a = (a, 0, 0)
b = (bcos(gamma), bsin(gamma), 0)
c = (cx, cy, c... | b60afbbed466efd0f2016e771323d3d56c3ffaf8 | 58,566 |
import scipy
def get_mvgcca_latents_space(X, W, model):
""" Return a list containing the common latent space Z and all the views latent space Z_m.
- X : [np.array(n x d1),...,np.array(n x dM)] multivews features ; n number of instances; dm dimension of views m ; M number of views
- W : ... | d513d54a3ec3dc2baed01c8dd04816f75753ad6e | 58,567 |
import transformers
def load_pipeline(**kwargs):
"""Load text generation pipeline."""
logger.info("Loading the pipeline...")
return transformers.pipeline("text-generation", **kwargs) | 6065791c6e89c7028ba123a4bc1df542ad786aad | 58,568 |
def get_table_column(tags, hdulist, idx=None):
""" Find a column in a FITS binary table
Used to return flux/error/wave values from a binary FITS table
from a list of tags.
Parameters
----------
tags : list
List of string tag names
hdulist : fits header data unit list
idx : int, op... | 7c8982ea56cf5ac7a5807317bd3d6c5a5f454391 | 58,571 |
def new_weights(shapes, names, random_types='truncated_normal', dtypes=tf.float32):
"""[Create a new trainable tensor as weight]
Arguments:
shapes {[Array of int]} -- [- example (convolution), [filter height, filter width, input channels, output channels]
- examp... | 50774aaf6c91c6ad5f586880bc2371db2fda7c18 | 58,572 |
from madrona.common import default_mimetypes as mimetypes
from madrona.common.jsonutils import get_properties_json, get_feature_json, srid_to_urn, srid_to_proj
from madrona.features.models import FeatureCollection
import json
def geojson_link(request, instances):
"""
Generic view for GeoJSON representation of... | a84357d44c114423eca391906995bed5a8f45530 | 58,574 |
import requests
def get(path, params=None, filename=None, keyfile='api-key.txt'):
"""
Query Illustris API
Args:
path (str): API query path
params: ...
filename (str): filename and directory to save content.
"""
with open('api-key.txt', 'r') as myfile:
key=myfile.read()
... | b2f1226bd66325a012872d3d07d5c10648aa8680 | 58,575 |
def DistributedPushSumOptimizer(optimizer, model,
num_steps_per_communication=1):
"""
An distributed optimizer that wraps another torch.optim.Optimizer through
win_accumulate ops to implement the gradient push algorithm.
Returned optimizer has two extra parameters `self_... | 8fccd6edddd5f8268517d20ffa51d5f700fbff90 | 58,576 |
def compute_ngrams (sentence, n): # OK
"""la fonction qui renvoie la liste de ngrams à partir d'une phrase"""
sentence = sentence.lower()
ngrams = zip(*[sentence.split()[i:] for i in range(n)])
return [" ".join(ngram) for ngram in ngrams] | 495505f4183d56a5a76339826f8306186191c6b1 | 58,577 |
import requests
def get_nof_instances(marathon_url, app_id):
"""
Get number of running instances given an app_id.
marathon_url : [string] the URL of the marathon service
app_id : [string] ID of the running marathon app
Method : GET
"""
api_endpoint = '/v2/apps/'
headers = {'Content-Ty... | e7abad86dc46f9ced379c2fa8b0eeafac6edd657 | 58,578 |
import pandas
def cell_id_count(dataframe: pandas.DataFrame, col_name: str) -> pandas.DataFrame:
"""
Count/tally the unique cell ID's to generate coverage density.
In general this could work for any field
and was initi.
"""
counts = dataframe.groupby([col_name])[col_name].agg("count").to_frame... | 2d6e47efc181e00e102ae51adc85c674a2bf53f4 | 58,579 |
def parameter_tuple_parser(parameter_tuple, code_list, relative_base):
"""
Accepts parameter_tuple, code_list, and relative_base. Returns parameter for use in intcode operation.
"""
if parameter_tuple[0] == 0:
return code_list[parameter_tuple[1]]
elif parameter_tuple[0] == 1:
retur... | f869240666f2adca0551a3620644023b88930a5a | 58,580 |
def navbar_tutorial_categories():
"""Navbar categories template-tag"""
categories = (
Category.objects.select_related("parent_category")
.order_by("parent_category")
.active_categories()
)
return {"categories": categories} | 20758b3521b7c9e5f4b771d3df756a7cf3ab9073 | 58,581 |
def sum_of_factorial_pure_recursion(number: int) -> int:
"""
>>> sum_of_factorial_pure_recursion(0)
0
>>> sum_of_factorial_pure_recursion(1)
1
>>> sum_of_factorial_pure_recursion(2)
3
>>> sum_of_factorial_pure_recursion(5)
153
"""
if number == 1 or number == 0:
return... | 12ca71c011535bcff990f49cf8716aca3ecc5226 | 58,582 |
from typing import List
from typing import Dict
from typing import Optional
def noisy_copy(
value: Outcome, probability: float = 0.9, domain: List[Outcome] = None
) -> Dict[Outcome, Optional[float]]:
"""specify a variable's CPD as copying the value of some other variable with a certain probability."""
dis... | 2a01b30edfa22fbf63baf033dbfabf6910853af5 | 58,583 |
from typing import Dict
def _serialize_issued_currency_amount(value: Dict[str, str]) -> bytes:
"""Serializes an issued currency amount.
Args:
value: A dictionary representing an issued currency amount
Returns:
The bytes representing the serialized issued currency amount.
"""
amo... | 17d1c5042038a380e0b3508acebafbf9bd7bc7b9 | 58,584 |
def get_historical_price(crypto, fiat, date):
"""
Only one service is defined for geting historical price, so no fetching modes
are needed.
"""
return HistoricalPrice().action(crypto, fiat, date) | c54c320cfd918e66e013d2d56c5c86551bdaee3b | 58,587 |
def _compute_padding_to_prevent_task_description_from_moving(unfinished_tasks):
"""Compute the padding to have task descriptions with the same length.
Some task names are longer than others. The tqdm progress bar would be constantly
adjusting if more space is available. Instead, we compute the length of th... | 82a2fffa0a35036901affe11fdf98d875445ffea | 58,588 |
def mcity_to_lab(dim):
"""
Converts real-world dimension to model.
"""
return dim / scale | b8105e43e0bb7115e0106a4a902df85567d29836 | 58,589 |
from typing import List
def predict(model: SpacyModel, X: List[str]) -> List[str]:
"""
Predict the label for each text.
Parameters
-----------
- **model**: the model to use.
- **X**: the texts inputs.
Return
----------
A List containing the label of each text.
"""
predic... | 08ce3abf80f0aa47f1e2dd5bfe1462b74b908a42 | 58,590 |
import math
def float_in_range(value: float, lower: float, upper: float) -> bool:
"""Checks if a float is within a range.
In addition to checking if lower < value < upper, checks if value is close to the end points;
if so, returns True. This is to account for the vageries of floating point precision.
... | e971c082e8019f545c9ccc1024f37d3bab61b64e | 58,591 |
def view(request, acronym):
"""
View IETF Group details
**Templates:**
* ``groups/view.html``
**Template Variables:**
* group
"""
group = get_object_or_404(Group, acronym=acronym)
add_legacy_fields(group)
return render(request, 'groups/view.html', { 'group': group } ) | f6a39f05526977582f33edd069e111da10bfffae | 58,592 |
def to_header(axes):
"""
Converts the axes describing the rows/columns of a CIFTI-2 vector/matrix to a Cifti2Header
Parameters
----------
axes : iterable of :py:class:`Axis` objects
one or more axes describing each dimension in turn
Returns
-------
header : :class:`.cifti2.Cift... | 5e9c12bc9e76c79e9da8b4122f461b962d49f028 | 58,593 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.