content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def expand_basic(state):
"""
Simple function which returns child states by appending an available move to
current state.
"""
assert(len(state) < 9)
# Calculte set difference to get remaining moves.
n = tuple(set(range(9)) - set(state))
# Create tuple of available new states and return... | 0889a21b043f6f675d133fed6e3c825eb69f4a82 | 33,644 |
def schedule_conv2d_winograd_nnpack_weight_transform(attrs, outs, target):
"""Schedule conv2d_winograd_nnpack_weight_transform"""
with target:
return topi.generic.schedule_conv2d_winograd_nnpack_weight_transform(outs) | 24882fd6b578fd34f806970c44991dec023e150e | 33,645 |
def bce_loss(input, target):
"""
Numerically stable version of the binary cross-entropy loss function.
As per https://github.com/pytorch/pytorch/issues/751
See the TensorFlow docs for a derivation of this formula:
https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits
... | 9f9c722fbc8a9be4ed436084097af40241d2a7ee | 33,646 |
from typing import List
def query_normalised_list(x: str or None,
ref: List[NormalisedName]) -> str:
"""
Internal method for querying a channel/marker against a reference list of
NormalisedName's
Parameters
----------
x: str or None
channel/marker to query
... | a52e0aba0c67be4d82ba2b9d42e5415d0c738263 | 33,648 |
def get_reachable_observed_variables_for_inferred_variables(model, observed=set()):
"""
After performing inference on a BayesianModel, get the labels of observed variables
("reachable observed variables") that influenced the beliefs of variables inferred
to be in a definite state.
Args
mode... | a693d6c57969b38b357a4a57fe2e868650b514b6 | 33,649 |
from typing import Dict
import logging
def load_bias(dataset_name, filtered=False) -> Dict[str, np.ndarray]:
"""Loads the output of our bias-only model
Note that since this produces per-token output, it is only valid on data with the
same tokenization as our annotated data.
"""
if filtered:
bias_ids = ... | 4cbfa171ac998c7d114f6df04a1ffe14457a98b0 | 33,650 |
def isbuildin(name: str) -> bool:
"""[summary]
Checks if name is a keyword or build-in function
[description]
Arguments:
name {str} -- name to be checked
Returns:
bool -- true if it is a build-in
"""
blacklist = ["abs", "delattr", "hash", "memoryview", "set", "all", "dict"... | 42ac527e1bbc2a50f0fe065fa27c9560eb062448 | 33,651 |
def find_dip(pulls):
"""Find the longest sequence of significant observations in the data"""
significant = pulls > 3.
if np.sum(significant) == 0:
return 0, 0
# Find indices of start and end of each significant sequence
changes = np.diff(np.hstack(([False], significant, [False])))
sign... | 0f6a7bd33092605cf851b8b10fbb151a9854cb02 | 33,652 |
def clip_weights(model, weight_constraint):
"""
Clip weights of a keras model to be bounded by given constraints.
Parameters
----------
model: keras model object
model for which weights need to be clipped
weight_constraint:
Returns
-------
model: keras model object
... | 9b6fd73b0f04a9889c96a6d823260ce008cab50d | 33,653 |
def scatter_wrapper(
self, func, *args,
s=None, size=None, markersize=None,
c=None, color=None, markercolor=None,
smin=None, smax=None,
cmap=None, cmap_kw=None, vmin=None, vmax=None, norm=None, norm_kw=None,
lw=None, linewidth=None, linewidths=None,
markeredgewidth=None, markeredgewidths=Non... | 093172b28492864c4462cfc5a8a1e90c89abe1b1 | 33,654 |
from datetime import datetime
def _coerce_loc_index(divisions, o):
"""Transform values to be comparable against divisions
This is particularly valuable to use with pandas datetimes
"""
if divisions and isinstance(divisions[0], datetime):
return pd.Timestamp(o)
if divisions and isinstance(... | 818504516d60c3822ac8f2c0e8fda38a2664ea2e | 33,655 |
def triplet_loss(anchor_vector, positive_vector, negative_vector, metric='cosine_dist', margin=0.009):
"""Computes the triplet loss with semi-hard negative mining.
The loss encourages the positive distances (between a pair of embeddings with
the same labels) to be smaller than the minimum negative distance ... | 6120f3b2ddd581b6dbde427c66643a8d0cc3f6e4 | 33,656 |
import hashlib
def get_file_hash(filepath: str, blocksize: int = 2**20) -> str:
"""Return the hash of the given file, with a default blocksize of 1MiB."""
_hash = hashlib.md5()
if not isfile(filepath):
return _hash
with open(filepath, "rb") as f:
while True:
buffer = f.re... | d1ed17e5d1eb1c38b44b313b245a9244a787014d | 33,657 |
def get_stopwords():
"""common stopwords to skip when checking for article names (derived from nltk)
"""
return [
"i",
"me",
"my",
"myself",
"we",
"our",
"out",
"ours",
"ourselves",
"you",
"your",
"he",
"... | 861037bad40204961f205f03399b4b6bbe0e6b2d | 33,658 |
def test_io_dataset_to_in_dataset(fixture_lookup, io_dataset_fixture):
"""test_io_dataset_to_in_dataset"""
args, func, data_func = fixture_lookup(io_dataset_fixture)
def f(v):
dataset = tf.data.Dataset.range(1000)
dataset = dataset.batch(15)
dataset = dataset.map(tf.strings.as_string)
dataset = d... | f15bfe02e1c89c73c45b36a54800d941c8317172 | 33,659 |
def convert_operation_to_task(operation):
"""Converts an Operation to a legacy Task."""
result = _convert_dict(
operation['metadata'], {
'createTime': ('creation_timestamp_ms', _convert_timestamp_to_msec),
'updateTime': ('update_timestamp_ms', _convert_timestamp_to_msec),
'startT... | 886cb37a29b8d4de5fc15e9a98946d0a7c3ddebb | 33,660 |
def augment_with_derivatives(V=None, theta=None, M=None, tol=1E-8, symm=True, deflate=True):
"""
Make a linear basis containing the subspace spanned by V and a third order tensor theta
e.g. from modal derivatives by deflation.
Parameters
----------
V : ndarray
linear basis
theta : n... | caa1639f7c0b8c3ae24d633ff3d89bceffccfc2e | 33,661 |
from typing import Union
def fomc_statement(
dates: Union[str, list[str], None] = None,
asDict: bool = False,
) -> Union[pd.DataFrame, dict]:
"""
Get FOMC statements for given date or dates.
`dates`: YYYY-MM-DD, or 'current', or 'previous'.
`asDict`: True or False, will return as dictionary i... | 356416dee9e68eaed036fcbdeb971f22518e70b0 | 33,662 |
def lambda_handler(event, context):
""" This is the entry point for the lambda. It will call the main handler, which is within a
try/catch so that we can efficiently log any unhandled exceptions to Cloudwatch/Splunk.
Args:
event (dictionary): contains event data passed in by AWS Lambda ... | dc03440c4bc54a9142cff726d26ae802ed659c2e | 33,663 |
from textwrap import dedent
def get_device_number(connection_str):
"""Return the integer device number from the connection string or raise ValueError
if the connection string is not in the format "device <n>" with positive n."""
try:
prefix, num = connection_str.split(' ')
num = int(num)
... | 396a13d4449166e0d63e830b17b07b3b22a208e7 | 33,664 |
from click.testing import CliRunner
def runner():
"""Returns a ```click.testing.CliRunner()`` instance."""
return CliRunner() | 8bd6dcdfef85e5afa30ea412a7b7c85b243aac17 | 33,665 |
def bent_plume_ic(profile, particles, Qj, A, D, X, phi_0, theta_0, Tj, Sj,
Pj, rho_j, cj, chem_names, tracers, p):
"""
Build the Lagragian plume state space given the initial conditions
Constructs the initial state space for a Lagrangian plume element from
the initial values for... | 24fdf411c69f06c766fe5a7cc59fb64d83dd7992 | 33,667 |
def GetMatrixBase(dim, val = 0):
"""Return matrix base, with a single sand grain in the middle"""
m = np.ones(dim) * val
SandFalling(m, 1)
return m | f22c025d64c532a86c88e0604847f2c1ca79645b | 33,668 |
def are_resize_confirm_logs_created(logs, instance, guest_hb=False):
"""
Check if resize-confirm logs have been created
"""
expected_logs = [{'event_log_id': fm_constants.FM_LOG_ID_VM_RESIZE_CONFIRM,
'severity': fm_constants.FM_ALARM_SEVERITY_CRITICAL},
{'event... | 4254ae1175efefa4244544961a638b3d11fe822a | 33,669 |
def find_second_largest2(root_node):
"""
Time: O(h)
Space: O(h)
h: height of the tree (O(lg n)); n: # of nodes
"""
def find_largest(node):
if node is None:
raise ValueError('Tree must have at least 1 node')
if node.right is not None:
return find_largest(... | 6d012a7fce306cc89f63603462991ac9441d0e57 | 33,670 |
from bs4 import BeautifulSoup
import html
def parse_team_totals(page):
"""
gets only the totals for a team from the box score of a game
(i.e. the last row)
"""
soup = BeautifulSoup(page, features='lxml')
scorebox = soup.find('div', {'class':'scorebox'})
teams = [TEAM_NAME_TO_TEAM(item.text... | 311eb570a74dc628e504a92b3282be8e6fbec613 | 33,671 |
def ball(p, radius, mass=-1):
"""Creates a ball that reacts to gravity.
:param p: The center point of the ball
:type p: (int, int)
:param radius: The radius of the ball
:type radius: int
:param mass: The mass of the shape (defaults to 1)
:type mass: int
:rtype: shape
"""
return... | 8f0da0982ea6f5622a857e96d47c1ba45731437d | 33,672 |
import torch
from typing import List
from typing import Any
def decode_actions(
node_logits: torch.Tensor,
parent_label_logits: torch.Tensor,
new_label_logits: torch.Tensor,
label_vocab: List[Label],
) -> List[Any]:
"""
Decode the most likely actions from action logits for the attach-juxtapose... | 5ef9f875c3e283c935bf50dfec96211737d5e75d | 33,675 |
def timetz_pack(timetup_tz, dl_pack = dl_pack, mktime = mktime):
"""
Pack a time; offset from beginning of the day and timezone offset.
Given a pair, ((seconds, microseconds), timezone_offset), pack it into its
serialized form: "!dl".
"""
(timetup, tz_offset) = timetup_tz
return dl_pack((mktime(timetup), tz_off... | 5dc027656c8b5f474ac48c9391fcdcce981c1228 | 33,676 |
import inspect
def authentication_exempt(handler):
"""Mark the endpoint handler as not requiring authentication.
Note:
This only applies when the authentication_required_middleware is
being used.
"""
# Can't set attributes directly on a bound method so we need to
# wrap it in a fu... | 2e817d2adcf4ae1a08c21de4588c796155851470 | 33,677 |
def make_scan(headers, light_ROI=[0, np.inf, 0, np.inf],
curvature=np.array([0., 0., 0.]), bins=1,
ADU_per_photon=1, detector='rixscam_centroids',
min_threshold=-np.inf, max_threshold=np.inf,
background=None):
"""
Make 4D array of RIXS spectra with structu... | 0a855a8cfe4102d2299e02d0233f07230ba8d6b6 | 33,678 |
import functools
def print_args(function):
"""Decorate the given function to print out it's arguments and return val if not None
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
bound_arguments = bind_args(function, *args, **kwargs)
print("{name}({call})".format(
... | ffccb7d3fe73167927b8328bf56f150321ef288c | 33,679 |
def load_data(cutoff: float) -> DataFrame:
"""
Loads descriptors and binding data for given cutoff.
"""
# Load ECIF
ecif = pd.read_csv(f'Descriptors/ECIF_{cutoff}.csv')
# Load ligand descriptors
ligand_descriptors = pd.read_csv("Descriptors/RDKit_Descriptors.csv")
# Load binding affinity... | 80a9709f1034abe7f1b3af1f41bdab06a840e68f | 33,680 |
def phys2digital(mvolts):
"""
Obtains the digital difference value in the signal that corresponds to
a certain physical magnitude variation.
"""
return mvolts * ADCGain | 523c06eea2ce23d4ba18e709e185ebb8bae09428 | 33,681 |
from typing import Any
def resolve_mock_target(target: Any) -> str:
"""
`mock.patch` uses a str-representation of an object to find it, but this doesn't play well with
refactors and renames. This method extracts the str-representation of an object.
This method will not handle _all_ kinds of objects, ... | 4c7520d2b17daaf79d1de2d9eca4f615e401fb12 | 33,682 |
import math
import heapq
def a_star_dist(start_state: frozenset, end_state: frozenset):
"""A* algorithm to calculate minimum energy needed to traverse the given states."""
start_node = Node(0, start_state)
open_pq = [start_node]
g_scores = defaultdict(lambda: math.inf)
g_scores[start_state] = 0
... | b55160bd50e245a0d8236f7c7c402933c8bc665a | 33,683 |
def get_calc_data(stock_code, s, e, fq='qfq',
drop_columns=['code', 'preclose', 'adj'],
scaler=['amount', 'volume'],
scaler_func=sklearn.preprocessing.MinMaxScaler):
"""获取计算用数据源
Args:
fq: 是否采用复权数据。默认使用前复权。如果不需要复权则传''即可。
stock_code:
s... | d8d382ff1523cfdc95753dcc2f73c758301a416c | 33,684 |
def encode_add_validator_and_reconfigure_script(
sliding_nonce: st.uint64, validator_name: bytes, validator_address: AccountAddress
) -> Script:
"""# Summary
Adds a validator account to the validator set, and triggers a
reconfiguration of the system to admit the account to the validator set for the syst... | 6a19907eaa0b1e94ec8339f783540f01555bd599 | 33,685 |
import numpy
def get_microphone():
"""Return raw data from microphone as Numpy array
Default format will be 16-bit signed mono. Format will match
audio playback. You must call tick() every frame to update the
results from this function.
"""
glock.acquire()
d = gmicdata
glock.releas... | 755072e394603f22282328b553a3ada5c101bd1e | 33,686 |
from typing import OrderedDict
from typing import ChainMap
def _expand_arrays(raw_variables, old_variables={}, compat='identical'):
"""Expand a dictionary of variables.
Returns a dictionary of Variable objects suitable for inserting into a
Dataset._arrays dictionary.
This includes converting tuples ... | 04ce236b447d26e7d7c748dd155c16f83d2b526e | 33,687 |
import logging
def redundant_peaks(usrdata):
"""Remove redundant, often ambiguous peaks by keeping the peak
with the highest ion score"""
peaks = usrdata.sort_values(by="IonScore", ascending=False).drop_duplicates(
subset=["SpectrumFile", "SequenceModi", "Charge", "PrecursorArea"]
)
peaks[... | da3413e4239c68168e1c4cd08feafd0320fcb8d5 | 33,689 |
import importlib
def getattr_in_module(module_name: str, func_name: str):
""" 在某个模块中获取属性
Args:
module_name: 模块名
func_name: 属性名
Returns:
属性
"""
m = importlib.import_module(module_name)
return getattr(m, func_name) | e0ceec50c063cea8350c04a4f048ca53d75ab5f6 | 33,690 |
def codeblock(request):
"""Parametrized fixture of each convention codeblock."""
return request.param | 52209ca4c84c873a33d9b6b3dc4ba044ebcd9513 | 33,691 |
import numpy
def cp_ls_cholesky_factor_objective(beta_gamma, norb, nthc, cholesky_factor, calcgrad=False):
"""cholesky_factor is reshaped into (norb, norb, num_cholesky)
Cholesky factor B_{ab,x}
Least squares fit objective ||B_{ab,x} - \sum_{r}beta_{a,x}beta_{b,x}gamma_{ab,x}||
This function provid... | cfa02ca214c0d0638243f916afdbfa052dbc9efe | 33,692 |
def volumes(jukebox_name, slot_id=[], as_object=False, p5_connection=None):
"""
Syntax: Jukebox <name> volumes
Description: Returns a list of all volumes currently loaded in the <name>
jukebox. To update the list of the volumes in the jukebox, use the
inventory method.
Return Values:
-On Suc... | 8c43a598a8d3ec55bcc3fd07b4b0f0ad1c585bcb | 33,693 |
def calculate_psi(cube, cfg):
"""Calculate temperature variability metric psi for a given cube."""
window_length = cfg.get('window_length', 55)
lag = cfg.get('lag', 1)
psi_years = []
psis = []
# Moving average
for yr_idx in range(cube.shape[0] - window_length):
slc = slice(yr_idx, y... | 641b55232dc4c845332aac5f28aef78c26783c43 | 33,694 |
import torch
def _get_product_features(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""
Get outer product of 2 tensors along the last dimension.
All dimensions except last are preserved. The last dimension is replaced
with flattened outer products of last-dimension-vectors from input tensors... | cf438a799b749563ea9509184cf117f4075730ab | 33,695 |
def resume_job(args, wording):
"""
used by fg and bg to resume a job either in the foreground or in the background.
"""
_clear_dead_jobs()
if len(tasks) == 0:
return "", "There are currently no suspended jobs"
if len(args) == 0:
tid = tasks[0] # take the last manipulated task b... | 235db36f3d4c59071b53f61777c908eccd86aa5c | 33,696 |
def drop_me(message):
"""This function removes user/chat id into a database.
Parameters
----------
message : telebot.types.Message
The message object.
Returns
-------
msg : str
User/Chat alert list addition/removal.
"""
helpers.start_connection().query("""
DELETE FROM
`mooncake-304003.misc.ps5-broa... | dd6c44b42e1809ff887ca6a99d8d3d4ecc63e882 | 33,697 |
def cmpd_to_pt(cmpd, els):
"""
Args:
cmpd (str) - chemical formula
els (list) - ordered list of elements (str) in triangle (right, top, left)
Returns:
(x, y) for compound
"""
tri = [CompAnalyzer(cmpd).fractional_amt_of_el(el) for el in els]
return triangle_to_square(... | aafc4d1a1821ee2a5e41f1540f114f8899a8485a | 33,698 |
def si_unit_lookup_table(units=UNITS):
"""
Creates a lookup table from all possible input unit names and symbols to
their corresponding SI unit.
"""
return {
**{ u.name: (u.si_equivalent, u.coefficient) for u in units
if u.name is not None},
**{ u.symbol: (u.si_equivalent... | a859dc78dca4cd31728fdda226609d67fccff7b1 | 33,699 |
def image_get_all(client, filters=None, marker=None, limit=None,
sort_key='created_at', sort_dir='desc',
member_status='accepted', is_public=None,
admin_as_user=False):
"""
Get all images that match zero or more filters.
:param filters: dict of filter k... | 1176b22dac3a45c3cd2ba3a33d52acb77710dfe0 | 33,700 |
import urllib
import json
def handleDBS(reqmgrOutDsets, cmswebUrl):
"""
Get total number of lumi sections in each dataset
"""
if 'testbed' in cmswebUrl:
dbsUrl = cmswebUrl + "/dbs/int/global/DBSReader/"
else:
dbsUrl = cmswebUrl + "/dbs/prod/global/DBSReader/"
dbsOutput = {}
... | 89dc385828ac042431fffb02c8c4201b5223ed4d | 33,701 |
def get_sub_folders(session, ds_browser, ds_path):
"""Return a set of subfolders for a path on a datastore.
If the path does not exist then an empty set is returned.
"""
search_task = session._call_method(
session._get_vim(),
"SearchDatastore_Task",
ds_browser,
... | e240973e4569208904ec6fcd3b7563ee213ca9e9 | 33,702 |
import requests
def stock_board_concept_cons_em(symbol: str = "车联网") -> pd.DataFrame:
"""
东方财富-沪深板块-概念板块-板块成份
http://quote.eastmoney.com/center/boardlist.html#boards-BK06551
:param symbol: 板块名称
:type symbol: str
:return: 板块成份
:rtype: pandas.DataFrame
"""
stock_board_concept_em_map ... | a3789c92a483b61504f4e98c0200d358e66a64b0 | 33,703 |
import torch
def jittered_center_crop(frames, box_extract, box_gt, search_area_factor, output_sz, masks=None):
""" For each frame in frames, extracts a square crop centered at box_extract, of area search_area_factor^2
times box_extract area. The extracted crops are then resized to output_sz. Further, the co-o... | 477bde7a6b1697ddf6fe2d1a3e2858b9cbdcd84b | 33,704 |
def bayesquad(fun, fun0, bounds, nevals=None, type="vanilla", **kwargs):
"""
One-dimensional Bayesian quadrature.
Parameters
----------
fun : function
Function to be integrated.
fun0 : RandomProcess
Stochastic process modelling the function to be integrated.
bounds : ndarray... | cd084d0ff8c34de5aadc98e56a4535e6d7d49f72 | 33,705 |
def track():
""" RESTful CRUD controller """
if deployment_settings.get_security_map() and not shn_has_role("MapAdmin"):
unauthorised()
resource = request.function
table = module + "_" + resource
# Model options
# used in multiple controllers, so defined in model
# CRUD Strings
... | 321f4cc50a4f8a08f1c49450f2269fd85113d83c | 33,706 |
def slice_or_index(index):
"""Return index or slice the array [:]."""
return slice(None) if index is None else index | 7bdf34a0667cfcc387c41bfcfc000d0881c3f6cd | 33,708 |
def get_driver():
"""Returns current driver."""
return _driver | 291543a22af57aa757641c7b77554dd3b1480e5b | 33,709 |
import torch
def transform_points(trans_01, points_1):
"""
Function that applies transformations to a set of points.
"""
if not (trans_01.device == points_1.device and trans_01.dtype == points_1.dtype):
raise TypeError(
"Tensor must be in the same device and dtype. "
... | 739881cb0080cc69a53caf6a821dbf354319dec0 | 33,711 |
def insert(*entities, **options):
"""
bulk inserts the given entities.
note that entities must be from the same type.
:param BaseEntity entities: entities to be inserted.
:keyword int chunk_size: chunk size to insert values.
after each chunk, store will be committed.
... | 9ce71916232175be5878237e95263834edd6878c | 33,712 |
def batch_resample(X, new_dim, mode="bilinear"):
"""
Resample each image (or similar grid-based 2D signal) in a batch to
`new_dim` using the specified resampling strategy.
Parameters
----------
X : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, in_rows, in_cols, in_channels)`
An i... | ef8dc6c2c8d062b6da5254b770fe930f0fe33024 | 33,713 |
def register(request):
"""
Sets a session variable and redirects users to register for BCeID
"""
if settings.DEPLOYMENT_TYPE == 'localdev':
return render(request, 'localdev/register.html')
request.session['went_to_register'] = True
return redirect(settings.REGISTER_BCEID_URL) | 3d5487b9d6018079b1f6b9bd97050cb03164912c | 33,714 |
def get_bits(byte_size, number):
"""Returns last byte_size*8 bits from number."""
res = []
for i in range(byte_size * 8):
res.append(str(number % 2))
number //= 2
res.reverse()
return res | ad41d3c9f1192b2f7026caa0f42a084ea39c82fa | 33,715 |
import copy
def greedy_find_path(entrance, exits, corridors):
""" Find ANY path connecting input and output, """
print("corridors at start: ", corridors)
#max_flow = float("inf")
# Not the case.
#if entrance in exits:
# return 1/0
cur_pos = entrance
path = [entrance]
... | c47065d2d9e6913009cb4e41daf0730c7a04c3ef | 33,716 |
import time
def blacklist_chat(chat_id: int, reason: str):
"""
BLACKLIST A CHAT
"""
c.execute(
"""
UPDATE chats
SET blacklisted = 1
WHERE chat_id=?
""",
(chat_id,),
)
c.execute(
"""
INSERT
INTO reas... | 5c327c99787d52d8576a82f6deb3509525826759 | 33,717 |
from pathlib import Path
def load_artefacts_from_file(file_path: Path) -> Artefacts:
"""
Load an artefacts file.
Args:
file_path: path to the artefacts file
Returns:
the artefacts created from the given file
"""
documents = load_yaml(file_path)
version_header = VersionHea... | 699f5f980ebf8f61c02b53b1b9f10b2d29a782a7 | 33,718 |
def date(date):
"""Return a date object representing the ISO 8601 date.
:param date: The ISO 8601 date.
:return: boolean
"""
return runner(date, r.dates) | 15805363f017cfa3ab90ce4b6dab4ba38f7f1423 | 33,719 |
from typing import Optional
def get_mean_var(
array: np.ndarray,
axis: Optional[int] = None,
weights: Optional[np.ndarray] = None,
):
"""Calculate average and variance of an array."""
average = np.average(array, axis=axis, weights=weights)
variance = np.average((array - average) ** 2, axis=axi... | 8e023f09de922475d3acca51edf61947767047f5 | 33,720 |
import json
from networkx.readwrite import json_graph
def write_nxgraph_to_json(g, output):
"""
Write a networkx graph as JSON to the specified output
Args:
g (networkx.Graph): graph to write as JSON
output (filelike): output to write to
"""
jsond = json_graph.node_link_data(g)
... | a909fd3f4e8c87bb3fe059b310819570758c553e | 33,721 |
import random
def heterogeneous_length(chromosome, generator, probability):
"""Return a mutant made through point mutation that may grow or shrink.
In this scheme, mutated alleles will be replaced with a value provided by
calling ``generator``. It is suitable for use with list encoding. Be warned
tha... | f14a3ce8f3af5be674553a93bb60841766315cbd | 33,722 |
from typing import Optional
from typing import List
def clean_eisenhower(raw_eisen: Optional[List[str]]) -> List[str]:
"""Clean the raw Eisenhower values from Notion."""
if raw_eisen is None:
return []
return [e for e in raw_eisen if e != ''] | a8dd48a307455f20b8dd7afbf5b5aec1835c7a2d | 33,723 |
import struct
def binary(num):
"""
calculate R, G, B components from bytes number
:param num: int
:return: list
"""
packed = struct.pack('!f', num)
integers = [ord(c) for c in packed]
return integers | 02a98dea32ed4270c90d4c1377726b4f59b5136e | 33,724 |
def giou_loss(pred, target, eps=1e-6):
"""IoU loss.
Computing the IoU loss between a set of predicted bboxes and target bboxes.
The loss is calculated as negative log of IoU.
Args:
pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2),
shape (n, 4).
target (Tensor): Co... | a5432f9b7924887e0baca111f9a2ae8d1a92fd93 | 33,725 |
def raw(text):
"""Returns a raw string representation of text"""
new_string=''
for char in text:
try: new_string+=escape_dict[char]
except KeyError: new_string+=char
return new_string | b8cd0ad183f1fd1e38bff446feb3b89f3acceeab | 33,726 |
def queries_to_retract_from_unioned_dataset(project_id, dataset_id, sandbox_dataset_id, pid_table_id):
"""
Get list of queries to remove all records in all tables associated with supplied ids
:param project_id: identifies associated project
:param dataset_id: identifies associated dataset
:param sa... | 30f41725098a98cf1e8875d5769064e7c3183cbc | 33,727 |
def get_instance_type(entity_name, instance_dict=None):
"""
:param entity_name: name of an entity;
:param instance_dict: dictionary that contains the instance type of each entity;
:return: the instance type of the provided entity;
Get the instance type of a given entity, as specified by the ins... | 0fead313271ee8b2b0d7be0d8048d506657b4944 | 33,730 |
def file_keyword(request):
"""Return multiple possible styles for the bumpsemver:file keyword."""
return request.param | 86700f811786a99b290557e9498bba03b800618d | 33,732 |
def get_compound(name):
"""Get a workspace compound by name as a dictionary"""
return get_object(name) | 390985cb25fe705b056788acd00b3519aa8ee2f4 | 33,733 |
import dateutil
def parse_iso_date(date):
"""
Parses and returns a human-readable date from a ISO datetime.
Args:
date (string): ISO datetime.
Returns:
The date in a more human-readable format.
"""
if date is None:
return "an unknown time"
parsed = dateutil.parse... | 4647192d9db9bf21ffc102fe5e0d950ec1d6667b | 33,735 |
def deconvolve_tf(y: np.ndarray, x: np.ndarray,
C: np.ndarray,
kernel: np.ndarray, lam: float, gam: float,
n_iters: int = 200, k: int = 3,
natural: bool = True,
clip: bool = False) -> np.ndarray:
"""
Perform deconvolut... | 0515672baf18d497d64b7ace195ea308a3621b7d | 33,736 |
from typing import Tuple
def get_bounds(features: list) -> Tuple[np.array, np.array]:
"""Given a list of feature names, generate a numpy array
with the bounds for the optimization and the variable types.
Args:
features (list): List of feature names, following the convention
from the L... | 5e86095f4beb46d12e10d1f78fa9a39627498e4d | 33,737 |
def findNeighbors(g, r, c):
"""
Check all neighbors of cell at row r, column c in grid g to find the count
of all living neighbor cells
"""
nAlive = checkArray(g, r-1, c-1) + checkArray(g, r-1, c) + \
checkArray(g, r-1, c+1) + checkArray(g, r+1, c-1) + \
checkArray(g, r+1, c) + check... | 012f64900f165b98f93095828141b1e8b1a994d2 | 33,738 |
def summarize_results(warmup_rewards, rewards):
"""
Print a summary of running a Bandit algorithm for a number of runs
"""
warmup_reward = warmup_rewards.sum()
rewards = rewards.sum(axis=-1)
r_mean = rewards.mean()
r_std = rewards.std()
r_total = r_mean + warmup_reward
print(f"Expec... | 2a3b786fdc835d312fe826600f46f4ab7a7ccaa7 | 33,739 |
def extract_zone(zone_url):
"""Given zone URL (as in instance['zone']) returns zone name."""
zone = zone_url[zone_url.rfind('/')+1:]
assert is_valid_zone(zone), zone
return zone | 446a723edb9f1aba9a4f9273c8172b192b2d05d5 | 33,740 |
def forward_transfer_metrics(*, experience=False, stream=False):
"""
Helper method that can be used to obtain the desired set of
plugin metrics.
:param experience: If True, will return a metric able to log
the forward transfer on each evaluation experience.
:param stream: If True, will retu... | afd53bf92bc16775685369ec971322a9a72b1b70 | 33,741 |
def tail(f, lines=10):
""" Get the n last lines from file f """
if lines == 0:
return ""
BUFSIZ = 1024
f.seek(0, 2)
bytes = f.tell()
size = lines + 1
block = -1
data = []
while size > 0 and bytes > 0:
if bytes - BUFSIZ > 0:
# Seek back one whole BUFSIZ
... | edd84be7bfa87cf3d21c785f08cbfaaee4eb029e | 33,742 |
def get_traffic_matrix(n, scale: float = 100, fixed_total: float = None) -> np.ndarray:
"""
Creates a traffic matrix of size n x n using the gravity model with independent exponential distributed weight vectors
:param n: size of network (# communication nodes)
:param scale: used for generating the expon... | 7de387a7b2d5ce4acb5d22d37240ec93c37a7bb6 | 33,743 |
def rectMask(size, corner=[0,0], dimensions=[0,0], channels=3):
"""
Create a mask in the shape of a (non-rotated) rectangle, in which the inside
of the rectangle is the desired region.
Parameters
----------
size : [int, int] or [int, int, int]
The size of the mask to be created (height... | cbeefbf45bc93d5c9de64a9fcc71be6189da828b | 33,744 |
def getCoursebycourseCredit(courseCredit):
"""
根据学分查询课程
"""
return generalGet('course', 0, 'courseCredit = \'{}\''.format(courseCredit)) | 4d8fb0f1c8f8bb7f0d70af1370b07783dd862f67 | 33,745 |
def main(brute_force=False, grid_width=3, sample_size=10000):
"""
:param brute_force: boolean - if True then grid width must be less than or equal to 3
:param grid_width: One dimension of a square grid - e.g. value of 3 = grid of 3x3
:param sample_size: sample size if using sampling - number of uni... | 25a67273e6a1982f93f15e004484a89c270414ce | 33,746 |
def get_E_beta_3(parameter, fid, did, N_data, N_flow):
"""
Predict the expected response for a set of combinations between different models and datasets
Parameters
----------
parameter: numpy.ndarray
The estimated parameters for the Beta-3 IRT model.
fid: numpy.ndarray
A (n_tes... | f6b2c5c7089b5df96f50f05fc24704b1c5d66780 | 33,747 |
import torch
def l1_gradient(x: torch.Tensor,
*,
zero_tol: float = 0.,
subgradient_samples: np.ndarray = None) -> torch.Tensor:
"""
Compute all the possible gradient of the 1-norm |x|₁
Notice that when x(i)=0, the 1-norm is non-differentiable. We consider
... | b7685dc9c5541e3e4286e6e6719220990f1f205f | 33,748 |
from datetime import datetime
from typing import cast
def _is_visible_with_salt(ra: Quantity, dec: Quantity, t: datetime) -> bool:
"""
Checks whether a target is visible by SALT.
Parameters
----------
ra: Quantity
Right ascension.
dec: Quantity
Declination.
t: datetime
... | 5148cfec973f0d76cbfe859263c4bcad61bcbc30 | 33,749 |
def sorted_date_list(df, col_collect: str):
"""
Builds a sorted list of every value for a date column in a given DataFrame
:param df: data to analyze
:param col_collect: column to analyze
:return: list
"""
try:
logger.info("Order Date List")
return sorted([x.operation_date fo... | d335b2979cf11101b362a1855a0b8bf09939a31b | 33,750 |
def get_tags(blog_id, username, password):
"""
wp.getTags(blog_id, username, password)
=> tag structure[]
"""
authenticate(username, password)
return [tag_structure(tag)
for tag in Tag.objects.usage_for_queryset(
Post.is_publish.all(), counts=True)] | 50445cc6014db2c4b600ae44a0292b569313d377 | 33,751 |
def add_scalebar(
ax, left, right, label, fontsize=15,
ax_y=-0.01,
):
"""
"""
ax.hlines(ax_y, left, right, color='k', linewidth=3,
transform=ax.get_xaxis_transform(),
clip_on=False,
)
ax.text(right, ax_y-0.01, label,
va='top', ha='rig... | 077d8a095c548085e1544050f1144bcb51f307b9 | 33,752 |
from functools import partial
from multiprocessing import pool
def mol_wt_from_smiles(smiles, workers=1):
"""
Calculate molecular weights for molecules represented by SMILES strings.
Args:
smiles (list or str): List of SMILES strings.
workers (int): Number of parallel threads to use for ... | 5017566a79a401262450f2032035014a52e87d8c | 33,753 |
def PolyArea(x, y):
"""Calculate area of polygon given (x,y) coordinates (Shoelace formula)
:param x: np.ndarray(N, )
:param y: np.ndarray(N, )
:return: area
"""
return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) | 23d17edc863cb2551fdf41cba96d71aa839ce073 | 33,755 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.