content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def onnx_rename_weights(onx):
"""
Renames ONNX initialiers to make sure their name
follows the alphabetical order. The model is
modified inplace. This function calls
:func:`onnx_rename_names
<mlprodict.onnx_tools.onnx_manipulations.onnx_rename_names>`.
:param onx: ONNX model
... | 7452011b7adc723af4262818ba369e349f66bcaf | 70,069 |
def dp_make_weight(egg_weights, target_weight, memo={}):
"""
Find number of eggs to bring back, using the smallest number of eggs. Assumes there is
an infinite supply of eggs of each weight, and there is always a egg of value 1.
Parameters:
egg_weights - tuple of integers, available egg weights sor... | 8546ab2dd0394d2864c23a47ea14614df83ec2f7 | 70,070 |
def switch_player (who_play):
"""
Function for switch the player
@type whoPlay: TypeOfPlayers
@param whoPlay: The current player
@rtype: TypeOfPlayers
@return: Return the new user who play
"""
if (who_play == TypeOfPlayers.PLAYER):
who_play = TypeOfPlayers.COMPUTER
else:
who_play ... | df8d87f8b13f4a8bcb79281b6d94ac2bb22c3c6f | 70,071 |
def get_impact_dates(previous_model, updated_model, impact_date=None,
start=None, end=None, periods=None):
"""
Compute start/end periods and an index, often for impacts of data updates
Parameters
----------
previous_model : MLEModel
Model used to compute default start/e... | b2e6966e0fe2213e504e913d8cd64dbe84fa815b | 70,072 |
def FindMinCover(points, L, S, format='slash'):
"""
Find minimal binary interval cover which covers all points, under the constraints given by L and S
:param points: collection of IPv4 IPs in string notation e.g. 10.0.0.1
:param L: maximum number of binary intervals
:param S: maximum length of a bin... | bca3e1ae12dfc6da516dca123891f03bc5ea6dbb | 70,073 |
from typing import Dict
from typing import List
def create_event_search(
p: Process,
search_data: Dict = {},
criteria: Dict = {},
fields: List = ["*"],
query: str = None,
time_range: Dict = {},
rows=1000,
start: int = 0,
) -> Dict:
"""Perform an event search.
Without anything ... | 9256b5bb7dae24809b0820e88eed406ee8c14ce1 | 70,074 |
def sinh(x):
"""
Hyperbolic sine
"""
if isinstance(x, UncertainFunction):
mcpts = np.sinh(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.sinh(x) | f3d1f1ec78420b90f8fcc5298547d0c8230e4d74 | 70,075 |
def unwrap_value(metadata, attr, default=None):
"""Gets a value like dict.get() with unwrapping it."""
data = metadata.get(attr)
if data is None:
return default
return data[0] | fee5f12f0fba86e221fe722b5829a50706ccd5dc | 70,076 |
def lookup_A_dns_record_for_ip(sought_ip):
"""search all DNS records in all domains for an A entry for the IP address"""
# IP must match by exact string
domains = get_list_of_domains()
for domain in domains:
records = get_domain_record_list(domain["id"])
for record in records:
... | 47501e87a0f6936c5cd177b79b3fbef96014a8d3 | 70,077 |
def _get_requirements(requirements_file): # pylint: disable=g-doc-args
"""Returns a list of dependencies for setup() from requirements.txt.
Currently a requirements.txt is being used to specify dependencies. In order
to avoid specifying it in two places, we're going to use that file as the
source of truth.
... | b1c78333ac42f577c98e3d99c05bf491eb6a888e | 70,078 |
def format_replication_collection(body: Json) -> Json:
"""Format replication collection data.
:param body: Input body.
:type body: dict
:return: Formatted body.
:rtype: dict
"""
result: Json = {}
if "planVersion" in body:
result["plan_version"] = body["planVersion"]
if "isRe... | f9f0f05541bb653b262305ec9d8ba875325551f7 | 70,079 |
def CreateSQLiteObject(dbname):
"""
创建SQLite
:param dbname:
:return:
"""
if _SQLInstance.instance:
_SQLInstance.instance.close()
_SQLInstance.instance = SQLiteMgr(dbname)
return _SQLInstance.instance | 3375468237007b6d4f4ae899486e6a8829cf5899 | 70,080 |
def tap_imol_inv_time(ref):
"""tap imol inverse
tapping for imol inverse model
Args:
- ref(ModelBlock2): reference to ModelBlock2 containing all info
Returns:
- tapping(tuple): tuple consisting of predict and fit tappings
"""
if ref.mdl['inv']['recurrent']:
tap_pre_inv = tappi... | 8c99c7664b78e3c657cc4df5515600df4e0cabdc | 70,083 |
async def async_restore_arrangement(connection, name, window_id=None):
"""
Restore a window arrangement.
"""
request = _alloc_request()
request.saved_arrangement_request.name = name
request.saved_arrangement_request.action = iterm2.api_pb2.SavedArrangementRequest.Action.Value(
"RESTORE")... | ec638717bff8560028be641b45c94efd5b2ea843 | 70,084 |
def _expected_rule_table(sorted_rules):
"""Build a table of the expected ACLSwitch output.
:param sorted_rules: List of time enforced ACL rules sorted by time.
:return: The formatted table.
"""
table = PrettyTable(["Rule ID", "Rule Time"])
for entry in sorted_rules:
table.add_row([entry... | 263b8b7413e7447be5bb7d990a90d6efe97ecedc | 70,085 |
def production_env_KO_eval(input_file, model, universal, output_optknock, output_cons_prod):
"""
Do production envelope analysis on mutants with reaction knockouts
Given the output of Optknock analysis, it evaluate the solutions
by calculating the production envelope of the model variant with
the r... | 8a4f39211d2a8ae9c742c519a8c37b8f75ad62a0 | 70,086 |
def df_from(url, extension=None):
"""Load data from URL"""
if extension is None:
extension = url.split(".")[-1]
if extension not in "csv tsv xls xlsx msgpack".split():
extension = "csv"
if url.startswith("http:") or url.startswith("https:") or url.startswith("ftp:"):
f = ... | 2023a9cdc54e1484537b63f6f97fa7b335468472 | 70,087 |
def plot_behavioral_index_as_frac_of_courtship(
exp,
bnames,
colors,
show_points=True
):
"""
Parameters
----------
bnames : list of string
Should always be in the following order ['tap', 'ori', 'sci']
"""
fig, ax = plt.subplots()
num_behaviors = len(bnames)
n... | 4584cc2ba4c3c22949d4c39eb4ef6789a7a5290b | 70,088 |
def tonemapping_operator_simple(RGB):
"""
Performs given *RGB* array tonemapping using the simple method:
:math:`\\cfrac{RGB}{RGB + 1}`.
Parameters
----------
RGB : array_like
*RGB* array to perform tonemapping onto.
Returns
-------
ndarray
Tonemapped *RGB* array.
... | 0e35769eeb1d52661d20977eb458c9c63eccbf88 | 70,089 |
def generate_hmackey(i, r, sr):
"""
生成 hMac 密钥
:param i
:param r
:param sr
:return:
"""
hmac_key = sha256_encrypt(i)[8: 12] + sha256_encrypt(r)[8: 16] + sha256_encrypt(sr)[8:12]
return hmac_key | fa95c01ba36a4d06b8df5fb4e70ccc44e7a383ea | 70,090 |
def get_frames(cmds):
"""
添加命令列表中的粒子坐标到时序列
:param cmds: 命令列表
:return: 时序列
"""
frame_list = []
seq_duration = get_max_frame(cmds)
dx = seq_duration - len(frame_list)
if dx >= 0:
for i in range(0, dx + 1):
frame_list.append([])
for cmd in cmds:
index = ... | e251f285ea6739540251d6d74959b37e00f235ee | 70,091 |
def getTimestamp(self):
"""Get timestamp (sec)"""
return self.seconds + self.picoseconds*1e-12 | 0c913fdcd9a3ce07e31a416208a8488bd41cea81 | 70,093 |
def lazymap(func, seq):
"""
Lazy equivalent for the map builtin function.
lazymap returns a LazyTuple whose contents are computed on demand
by applying *func* to seq[i], where i is the index that's being accessed.
"""
if isinstance(seq, LazySequence):
if seq.isTerminating():
... | 9ea778644800d6684b7f43f6983804870b509c98 | 70,094 |
from typing import List
from typing import Optional
def TcxTrackList(filename: str) -> List[tp.TrackPoint]:
"""Create a List[tp.TrackPoint] which maybe empty if no trkpt's found"""
# Create a list of TrackPoints
track: List[tp.TrackPoint] = []
elem: et.Element
tree = et.parse(filename)
root: ... | e90c6fb2341a16953017c2200e2e611f126cc784 | 70,095 |
import torch
def logsumexp(tensor: torch.Tensor,
dim: int = -1,
keepdim: bool = False) -> torch.Tensor:
"""
A numerically stable computation of logsumexp. This is mathematically equivalent to
`tensor.exp().sum(dim, keep=keepdim).log()`. This function is typically used for summing lo... | bd32459f6db3bcb38e9be3874478c2775271456c | 70,096 |
def get_offers_formset():
"""Helper method that returns a Django formset for a dynamic amount of FruitOffers."""
return modelformset_factory(FruitOffer, form=OfferForm, extra=1) | 405e87956b2d65e03855a6eb6e99bb7c05713201 | 70,097 |
from pathlib import Path
from typing import Optional
def choose_file(root_dir: Path) -> Optional[Path]:
"""
Interactive loop to choose a file
"""
def _format(root_dir: Path, entry: str) -> str:
f = root_dir / entry
if f.is_dir():
return entry
return f'{entry}\t({hum... | e0f77829053d7dcba5ea348d6c33e5cd2a13819e | 70,098 |
def variable(name, shape, init= 'rand', initializers=
{ 'zero': tf.initializers.zeros()
, 'unit': tf.initializers.ones()
, 'rand': tf.glorot_uniform_initializer()
}):
"""wraps `tf.get_variable` to provide initializer based on usage"""
return tf.get_variable... | 2094cf7240045c4da9953b8732265a278eee10aa | 70,099 |
import json
def insert_workspace(cursor, specification):
"""workspace情報登録
Args:
cursor (mysql.connector.cursor): カーソル
specification (Dict)): ワークスペース情報のJson形式
Returns:
int: ワークスペースID
"""
# insert実行
cursor.execute('INSERT INTO workspace ( organization_id, speci... | 1dcc08af71e133bc9a34d3bc1a23f641ba253ec0 | 70,100 |
import xarray as xr
from aux_gps import save_ncfile
def produce_final_dsea_pwv(ims_station=None, savepath=None, use_pressure=True):
"""use ims_station='SEDOM' to get close ts, pressure"""
if ims_station is not None:
ts = xr.open_dataset(ims_path/'IMS_TD_israeli_10mins.nc')[ims_station]
pres = ... | 5a172a9b940307fe6d6d8786ab1666d4b77d4a40 | 70,101 |
import urllib
def url_encode(params):
"""Wrapper for urllib.urlencode which doesn't handle UTF-8 encoded characters"""
for key, value in params.items():
if isinstance(value, str):
params[key] = value.encode('utf-8')
return urllib.parse.urlencode(params, doseq=True) | 4d6313a1624228e786e9ebdce1a0c2e8055391fa | 70,102 |
def f_classification (dataset):
"""
ANOVA: avalia afirmações através das médias das populações.
A análise permite verificar se exite ou não diferença significativa entre as
médias e se os fatores têm influência nas variáveis dependentes.
"""
X = dataset.X
y = dataset.y
aa = []
for... | 47c88588e37e5ffb34a92f8c63bb92d81a0198cb | 70,103 |
from typing import Union
from typing import Callable
def get_source(object_: Union[type, Callable, ModuleType]) -> str:
"""
Get the source code which defined an object.
"""
object_source: str = getattr(object_, "_source", "")
if not object_source:
object_source = getsource(object_)
ret... | 00bf59045495fd8fd3d15fb205e6edf9f4f8f385 | 70,104 |
def get_read_params(stmt):
"""Get the feature map parameters from a read loop nest.
Parameters
----------
stmt : tvm.tir.AttrStmt
The outermost attribute statement of a read loop nest.
Returns
-------
SerialFeatureMap
The serializable feature map.
input_pointer : tvm.ti... | bcdab9cbc5ebd73fb3bf30fdccd8e56a12a43410 | 70,105 |
def asRawURL(url):
"""
rawURL is just the name followed by the claim_id, without channel info, like
blog#4fa3e1b8c62e9b41e6cf4a3eb9faafe3778f1445
"""
l = fixedAPI()
res = l.resolveOrNone(url)
if not res: return None
permalink = ""
claimID = recGetter(res, 'claim', 'claim_id')
i... | ce2240c0a27712672dcbe665f503356140ddc67a | 70,106 |
def cellbasis(angles, edges):
"""
For the unit cell with given angles and edge lengths calculate the
basis transformation (vectors) as a 4x4 matrix
"""
rad = np.deg2rad(angles)
basis = np.identity(4)
basis[0][1] = np.cos(rad[2])
basis[1][1] = np.sin(rad[2])
basis[0][2] = np.cos(rad[1... | ec67067039c67c78df3d5b1300928e545a9b8f59 | 70,107 |
from typing import Any
from typing import Tuple
from typing import Union
from typing import List
import signal
def peak_detector(
filtered_magnetic_signal: NDArray[(2, Any), int],
twitches_point_up: bool = True,
start_time: float = 0,
end_time: float = np.inf,
prominence_factors: Tuple[Union[int, ... | 83efbcd6fc6aa5933f7626a81017730c45b983ad | 70,108 |
def point_in_polygon(points, x, y):
""" Ray casting algorithm.
Determines how many times a horizontal ray starting from the point
intersects with the sides of the polygon.
If it is an even number of times, the point is outside, if odd, inside.
The algorithm does not always report c... | 26ab72c6b545f94d41b0d1228dd312d590ad208b | 70,109 |
def task3(ob):
"""
Function that take an object as input and prints its docs (__doc__) every sentence in one line.
Input: name of object (e.g. int)
Output: string ready to write.
"""
return ob.__doc__ | 859996692629a61664acf39309741020192f3da5 | 70,111 |
def word_count(sentence,method):
"""
切割字符后计算词的出现频率
:param sentence:
:return:
"""
res = {}
word_list = CUT_METHODS.get(method)(sentence)
for word in word_list:
if len(word) > 1:
res[word] = sentence.count(word)
return res | bac9fc45c1cbe84d0afd5c0e3aad988d34ede75d | 70,112 |
def validate_integer(value, name, min_value=None, max_value=None):
"""Make sure that value is a valid integer, potentially within range."""
try:
value = int(str(value))
except (ValueError, UnicodeEncodeError):
msg = _('%(value_name)s must be an integer')
raise exception.InvalidInput... | b14230ddd0835b3a2c206472baa6a6e6dc6f59d0 | 70,113 |
def create_cost(bounds_true, bounds_pred):
"""
create_cost(bounds_true, bounds_pred)
Parameters
----------
bounds_true : 2d ndarray (rows = seizrs, columns = start,stop), ground truth
bounds_pred : 2d ndarray (rows = seizrs, columns = start,stop), predicted
Returns
-------
cost : F... | 3e38cccae0f03c986fb3079c072d55b404aeb48a | 70,115 |
def mrr_ng_to_fsr(lambda0, n_g, radius):
"""
description: Calculate the free-spectral range (FSR) based on the central resonance wavelength, group index and MRR radius.
(Bogaerts et al., Silicon microring resonators, Laser and Photonics Review 2011, Eq.(9))\\
lambda0 {float} Resonance wavelength (unit: ... | b4b74f1ed8bff28cfceb4ebbbf8bc42a92eec05c | 70,116 |
def _indexed_tags(tags):
"""Returns a list of tags that must be indexed.
The order of returned tags is from more selective to less selective.
"""
if not tags:
return []
return sorted(set(
t for t in tags
if t.startswith(('buildset:', 'build_address:'))
)) | 0a85c2f88e452c4898cc3a77d9cf5ebc9a90b8f6 | 70,117 |
def set_default_blockchain(blockchain: Blockchain):
"""
Δ(β) \n
\t Makes privacychain adopt β as the default blockchain:
\t 1: "HYPERLEDGER" \n
\t 2: "ETHEREUM (default)" \n
\t 3: "BITCOIN" \n
"""
blockchain = {
1: "HYPERLEDGER",
2: "ETHE... | 8e6ebe455595e0bf0baa5e766bdb82df9abc3281 | 70,118 |
def test_sequential():
"""call `set_seed` just before generating random variables"""
def build():
set_seed(200)
layers = [
tf.keras.layers.Conv2D(4, 3, input_shape=(16, 16, 3)),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Activation("relu"),
... | d2b547e7a69d580f6316429801f9e09d5262a85e | 70,119 |
from typing import Callable
from datetime import datetime
def gogetcisdata(startyear: int = STARTYEAR, startmonth: int = STARTMONTH, startday: int = STARTDAY,
storefunc: Callable[[str, str], None] = None):
""" manage getting CIS data, uses multiple sessions to avoid throttling """
thisyear = ... | b20222a23cc506977d9aa3a9c9fa93028183657a | 70,120 |
def render_figure(code, code_dir, language, output_dir, output_base, config=None):
"""
Run a GMT code and save the images in *output_dir* with file names
derived from *output_base*.
"""
# pylint: disable=too-many-arguments
if language == "bash":
figname = eval_bash(code, code_dir, output... | 59741e88b00568298535f57fa0a6c8b3a80f3f17 | 70,121 |
def add_server_subparser(subparsers):
"""
Create the subparser for 'shorts serve'
"""
server_parser = subparsers.add_parser('serve',
help="serve this site")
server_parser.set_defaults(func=shortstack.server.start)
server_parser.add_argument('--port', '... | 788972926bdd63b14f92d8613140aa8ec061aee4 | 70,122 |
from functools import reduce
def ensure_latest_source_from_artifacts(
source, name, destination=None, host=None, port=22, only_cache=False
):
"""
Ensure a repository is checked out and the latest version in the name directory
in the INSTALL DIR on the specified machine. Caches the repository in artifa... | 1cef445e7029d87c9b179d44e9972bb748b4b535 | 70,123 |
from datetime import datetime
def plot_forecast(
fig,
ax,
y,
f,
samples,
dates,
linewidth=1,
linecolor="b",
credible_interval=95,
**kwargs,
):
"""
Plot observations along with sequential forecasts and credible intervals.
"""
ax.scatter(dates, y, color="k")
... | 63be9c6fc5099d6114efdff8dacb5dfaf013414f | 70,124 |
def update_user(user_id):
"""
Update a user's atat role.
PUT /users/<user id>
{
atat_role: <name of an atat role>
}
Returns the updated user.
"""
try:
atat_role_name = request.json["atat_role"]
except (KeyError, TypeError):
abort(400)
try:
upda... | cc3de44ee393d37e6911c38aa07cf4f8dc1e66bd | 70,126 |
def get_finger_joint_limit_state(x,m):
"""Gets the joint limit state of the finger from a hybrid state"""
return m[3:6] | 90fa8e3dce6c9f9dc08e3e7c2fd9e447690202c1 | 70,127 |
def test_id(id):
"""Convert a test id in JSON into an immutable object that
can be used as a dictionary key"""
if isinstance(id, list):
return tuple(id)
else:
return id | 11e18a57648cb09f680751d1596193020523e5e1 | 70,128 |
import re
def MakeHeaderToken(filename):
"""Generates a header guard token.
Args:
filename: the name of the header file
Returns:
the generated header guard token.
"""
return re.sub('[^A-Z0-9_]', '_', filename.upper()) + '__' | d29f756e30c3214aac174302175c52ca28cad6cb | 70,129 |
def interpret_met_auxsens_code(auxsenscode):
"""interpret integer code for the availability of auxiliary sensors in MET files, return dict of contents vars"""
auxsenscode_int8 = np.uint8(auxsenscode)
auxsensbits = np.unpackbits(auxsenscode_int8, bitorder='little')
if auxsensbits is None:
out = {... | 2d030b2a212a9555af6867a3b73f3971fbff01af | 70,130 |
def admin_board_delete():
"""
This function is used for logged in admin to delete a board
:return: json information
if the deletion is successful it will return status 1 otherwise it will return error message
"""
Bid = request.form.get("Bid")
if not Bid or not Bid.isnumeric():
return... | bb12323c1e9e8e0f7586e850566d4094d4d52d81 | 70,131 |
def check_byte(b):
"""
Clamp the supplied value to an integer between 0 and 255 inclusive
:param b:
A number
:return:
Integer representation of the number, limited to be between 0 and 255
"""
i = int(b)
if i < 0:
i = 0
elif i > 255:
i = 255
return i | 374e0ffbe1d0baa80c56cafd3650fba8441c5ea0 | 70,132 |
from typing import List
def apply_over_under_sampling(
X_train: DataFrame, y_train: Series, target_balance: str
) -> List:
"""
Apply over or under sampling to adjust class balance
in imbalanced data
"""
if target_balance in ["under_sampled", "over_sampled"]:
if target_balance == "under... | f7bd51d8c9ed69549881cfc7a185ccaf8e918d28 | 70,133 |
from typing import Dict
def get_piece_value(piece: Piece, color: bool) -> int:
"""
Helper function for piece value herustic, values each individual piece
:param piece: the current piece
:param color: color of the player
:return: piece value
"""
if piece is None:
return 0
piece... | 4c39dd5847710bc9c6f31725f24ee417f40f8afb | 70,134 |
def run():
"""Requirements for Task 1B"""
# Build list of stations
stations = build_station_list(False)
#run inconsistency check
inconsistent_stations = inconsistent_typical_range_stations(stations)
#Function to sort the list of inconsistent stations
def inconsistent_stations_details(... | 69f390abc6a7bbd39c6631461daa3b04e3b71206 | 70,135 |
def observations():
"""Example observation list for testing."""
datastore = DataStore.from_dir("$GAMMAPY_DATA/cta-1dc/index/gps")
return datastore.get_observations([111630]) | d23949f5c6b1a439a723b52275ddf7cb261675ad | 70,137 |
def getCIDsFromAID(AID, usepost=True):
"""
Return a list of pubchem cids that correspond to an AID.
@param AID The AID to search on.
@param usepost Boolean value indicating whether post or get should be used.
"""
if usepost:
url = PROLOG + "/assay/aid/cids/TXT"
payload = {'aid':AID}
response =... | 4c3642b7048b7525f62f79434745fe6697bddd0a | 70,138 |
def check_worker_lookup_response(response, operator, value):
"""
This function will verifies the worker lookup response
"""
if env['proxy_mode']:
if operator(response[0], value):
err_cd = 0
else:
err_cd = 1
else:
if operator(response["result"]["totalCo... | 37e64cb71c5d0ab51d787db94619f048491c83b8 | 70,139 |
def create_unsubscription_list(correls, options):
""" unsubscribe list including correlations """
subscriptions = blpapi.SubscriptionList()
for ticker, correlid in correls.items():
subscriptions.add(ticker, options.fields, options.options, correlid)
return subscriptions | 66083db52f0c54c17e10d897ccacf351a32421d5 | 70,140 |
def connect():
"""
:return:
"""
return psycopg2.connect("dbname=forum") | 35674dd904cab4539d0bd0089b55e8935986b95a | 70,141 |
import numpy
def get_signal_to_fluctuation_noise_ratio(signal_array, tfn_array,
roi_size=10):
""" The SFNR image is is obtained by dividing, voxel by voxel,
the mean fMRI signal image by the temporal fluctuation image.
A 21 x 21 voxel ROI, placed in the center of... | 4240adee5062b7a1302f010c92b91ed272287df7 | 70,144 |
def insert(rcd, insert_at_junctions, genotype):
"""
Given the genotype (ie the junction that was chosen), returns the corresponding insert
"""
junctions = ["x", "y", "z"]
if genotype[1] != "-":
j = junctions.index(genotype[1])
return insert_at_junctions[j]
else:
return "-... | 1bf3d7e8bb84659c3992e55fc51490c19701cff0 | 70,145 |
def checkout(skus: str) -> int:
"""
Arguments:
--------------
skus: str
A string of all skus in the basket
Returns:
--------------
@return: int
total value of all items in the basket.
It will be an int and not a float since the price of every item is a whole number
... | 91eb966990534f46d9e72b51695da1b7587021ab | 70,146 |
def nc_domegazetadzeta(Surfs, Surfs_star):
"""
Produces a list of derivative matrix d(omaga x zeta)/dzeta, where omega is
the rotation speed of the A FoR,
ASSUMING constant panel norm.
Each list is such that:
- the ii-th element is associated to the ii-th bound surface collocation
point, an... | d979d8418e02195339c67a25fd7a126901e8b3d2 | 70,147 |
import torch
def fp16_compress_hook(process_group: object, bucket: dist._GradBucket):
"""
This DDP communication hook implements a simple gradient compression
approach that converts ``GradBucket`` tensors whose type is assumed to be
``torch.float32`` to half-precision floating point format... | 5e2ad4afaff402cc97d9604effac6229dc6985bb | 70,148 |
def clone_model(model, **kwargs):
"""Clone an arbitrary sqlalchemy model object without its primary key values."""
table = model.__table__
non_pk_columns = [k for k in table.columns.keys() if k not in table.primary_key]
data = {c: getattr(model, c) for c in non_pk_columns}
data.update(kwargs)
... | 5aa3efe0d508390a7f4ec6f22c0d4ffbfe3f04b5 | 70,149 |
import networkx as nx
def nodes_class(graph, nodeslist):
""" Classify nodes in the graph network with reference to nodeslist.
From the list of nodes in arg nodelist, verify if these nods are part of
the network in arg graph. If they are, and attribute "type" is set as
"internal". Otherwise, the attr... | aa1380116cf9b6b6ed457429099a9946ac1d35fb | 70,150 |
def redistribute_data(
old_dist, new_dist, shared_manager, detdata_manager, intervals_manager, times=None
):
"""Helper function to redistribute data in an observation.
Given the old and new data distributions, redistribute all objects in the
shared, detdata, and intervals manager objects. The input ma... | 0bcd67f9f9ff85b63f11b34e99c4357b60df6568 | 70,151 |
def Search(request):
"""
Searching for phones or by manufacturer name is handled via post requests sent to this view.
"""
searchString = request.POST["searchString"].lower()
if "manufacture" in request.POST.keys():
if searchString:
return redirect(Manufacturer, manufacturer = searchString)
else:
return... | e26334f8f2cd2a7700fcb421e9ba789fcf5ce3e7 | 70,155 |
def within_discussion_comment_and_user_anonymization(comment_gen,
extract_comment_name,
extract_user_name,
anonymous_coward_name):
"""
Reads all distinct... | a3ccdaff147a14ce966d942ca958ecfe9723a131 | 70,156 |
def all_conditionals(results,prior_correct):
"""For each class, prob of results given that class."""
cond_probs = [prob_results_given_c(results,c,prior_correct) for c in range(len(results))]
assert np.sum(cond_probs) < 1.01
return np.array(cond_probs) | cd7ac1ba2ce05c175a255cb24e7fbf0a08d4b662 | 70,157 |
from typing import Tuple
def restart_seek(
point: Tuple[float, float], world_state: Tuple[rc.WorldState]
) -> float:
"""
func to find a point to move to
robot "most open" @ point found by optimizer
"""
cost = 0
pt = np.array(point)
ball_pos = world_state.ball.pos
# hard constraint ... | 4eeb4ca9975fe58549c8ceee520ae4a53e3a2f2e | 70,158 |
def resize(file_paths):
"""
Resize the list of images in the file_path
:param file_paths: a file_path with the .jpeg images
:return: np array of resized images
"""
image_list = []
for image in file_paths:
image_list.append(cv2.resize(cv2.imread(image), (128, 128)))
return np.arra... | 7648ead15a61b1ab48b0b8b29086751c3597d216 | 70,159 |
def __process_sample(nbins, i):
"""
A helper function for the multiprocessing of kappamode.out files
Args:
nbins (int):
Number of bins used in the GPUMD simulation
i (int):
The current sample from a run to analyze
Returns:
np.ndarray: A 2D array of each... | 022dac2231115d3738c6e7ceef8df313b5620127 | 70,160 |
def autoclose_stream(f):
"""Decorator to close gRPC stream.
Args:
f (func): The function to decorate
Returns:
wrapper: wrapper of the decorator
"""
def wrapper(*args):
"""Wrapper function, checks context state to close stream.
Args:
*args (list): All a... | 3f5dda42f4d9c1467c3d84e0adf18112d9a261a7 | 70,161 |
def maskPeaks(df, peaks, width):
"""df is the dataframe to mask rows
peaks are the row indices
width is the extent to mask around each row in peaks"""
e = extendMaskArray(peaks, width)
# make sure no values are outside the row count (although pandas would not care
f = pd.Series(e.values[(e>=0) &... | 401af9594f3756284ffad5a967a9512acbd75e07 | 70,162 |
def _convert_labels_for_svm(y):
"""
Convert labels from {0, 1} to {-1, 1}
"""
return 2.*y - 1.0 | eca685bea6fd991245a299999fcbe31cd3b1a9ad | 70,163 |
def test_xlabel(dash_threaded):
"""Test that xlabel displays as set via UI."""
def assert_callback(p_value, nclicks, input_value):
answer = ''
if nclicks is not None:
if input_value == p_value:
answer = 'PASSED'
return answer
template_test_python_compone... | eb1d8451852ccf3537858203a7ba27594df7a852 | 70,164 |
def get_rasterio_crs_object(crs_string: str) -> rs.crs.CRS:
""" Returns a valid rasterio CRS object from given EPSG, ESRI, PROJ4,
or WKT string """
err_string = (f'Rasterio: {crs_string} is an invalid crs!\n'
'Choose a valid EPSG, ESRI, PROJ4, or WKT string')
try:
proj_crs = CR... | 825c7b2d1f6716b53c7ab3130b28e684618ad432 | 70,165 |
def E_from_ElectricDipoleWholeSpace(XYZ, srcLoc, sig, t, current=1., length=1., orientation='X', kappa=0., epsr=1.):
"""
Computing the analytic electric fields (E) from an electrical dipole in a wholespace
- You have the option of computing E for multiple times at a single reciever location
... | f8d4581aacc62556c7cfd7581a394eaad751c0cb | 70,166 |
from typing import List
def not_statement(args: List, node):
"""Evaluate (< a b) as {a < b}"""
if len(args) != 1:
evaluator.error("(special_forms.control_statements.not) 1 parameter expected, {} given".format(len(args)), node)
return evaluator.evaluate_node(args[0]) in FALSE_STATEMENTS | 6cfedca03846d53a215d40a644595b3f3bd51367 | 70,167 |
def scrabble_word(word: str) -> str:
"""
Randomly reorders all but the first and the last letters in a word
Parameters:
word(str): the word to scrabble
Returns:
str: the word with randomly reordered all but the first and the last letters
Examples:
>>... | 8bb025c29b361419ec8bb68c5a308510bd5d155b | 70,169 |
def DFS(graph, start, end, path=None, paths=None):
"""
Depth first traversal from start to end node
"""
counter = 0
if path is None:
path = [start]
paths = []
counter += 1
else:
path = path + [start]
counter += 1
if start == end:
paths.appen... | 2d2120d426643d1f5328229056d8340ad63d8a48 | 70,170 |
def cate_query(keyword):
"""Return a list of business Information based on categorical keywords."""
results = session.query(*sel_all).filter(Basic_data_model.categories.ilike('%'+keyword+'%')).all()
jsondata_list = []
results_list = build_metadata_list(jsondata_list,results)
return jsoni... | ac5a1d200a5e8c07d371f0620a3928e6dc17338d | 70,171 |
import numpy
def rgb2hslv(r:numpy.ndarray, g:numpy.ndarray, b:numpy.ndarray):
"""
Convert RGB to HSLV values
Parameters
----------
r, g, b : ndarray
Arrays with red, green, blue channel values (any dims, must match!)
Returns
-------
(h, sl, l, sv, v) : tuple
Hue, ... | f25148f97139315cc7e6d49fa4eacdef286c05b2 | 70,172 |
def plot_parametric(*args, **kwargs):
"""
Plots a 2D parametric plot.
The plotting uses an adaptive algorithm which samples recursively to
accurately plot the plot. The adaptive algorithm uses a random point near
the midpoint of two points that has to be further sampled. Hence the same
plots ca... | 92beb2ea21d331ada16b1d07115d30ba1b2df61e | 70,173 |
def user():
"""
exposes:
http://..../[app]/default/user/login
http://..../[app]/default/user/logout
http://..../[app]/default/user/register
http://..../[app]/default/user/profile
http://..../[app]/default/user/retrieve_password
http://..../[app]/default/user/change_password
http://..... | 8419712bfeabdf18f10209158814a6fa57641b4d | 70,174 |
def ilr( data_frame, voxmats, ilr_formula, verbose = False ):
"""
Image-based linear regression.
This function simplifies calculating p-values from linear models
in which there is a similar formula that is applied many times
with a change in image-based predictors. Image-based variables
are st... | aaa5abd2ae3d072842f6764bc5bcf5ed9b5c9159 | 70,175 |
import math
def chunks(l, n):
"""Divide l into n approximately-even chunks."""
chunksize = int(math.ceil(len(l) / n))
return [l[i:i + chunksize] for i in range(0, len(l), chunksize)] | c7b395dec7939b863097b3da9cdd49fbe2a47740 | 70,177 |
from typing import Callable
from typing import Any
from typing import Tuple
from typing import Mapping
import logging
import collections
import time
def _run_training(training_fn: computation_base.Computation,
client_selection_fn: Callable[[int], Any], state: Any,
round_num: int) -... | 8ff9c15efc117c3d9fb25bdd88ecc7702bd1ed8e | 70,178 |
def camp_sweeps_by_time(request):
"""
Number of camp sweeps by time. Optional query parameters are:
Query params: timeframe
options: 'month', 'week'
default: 'week'
"""
timeframe = request.query_params.get('timeframe', 'week').lower()
if timeframe not in ('week', 'month'):
msg ... | b1fc73333bb528ab58ebb01c867211e7fc9d673c | 70,179 |
import torch
def vec_ans_index_buffered_encoder(symbols, indices, cdf, cdf_length, cdf_offset, precision,
coding_shape, overflow_width=OVERFLOW_WIDTH, **kwargs):
"""
Vectorized version of `ans_index_encoder`. Incurs constant bit overhead,
but is faster.
ANS-encodes unbounded integer data using ... | 4aef22a40a612b037fed7c4acd92f5c546349b4b | 70,182 |
def file_picker():
"""shows a file picker for selecting a postQC.tsv file. Returns None on Cancel."""
chooser = sg.Window('Choose file', [
[sg.Text('Filename')],
[sg.Input(), sg.FileBrowse(key='-FILE-', file_types=(('PostQC TSV files', '*.postQC.tsv'),))],
[sg.OK(), sg.Cancel()]], icon=i... | 5e052974ac775cd0dcd622df419040a8561ceeca | 70,183 |
def slide_selection(request, course_id):
"""
Teacher form for adding slide(s) to a course
"""
course = get_object_or_404(Course, id=course_id)
slidesInCourse = [slide for slide in course.slide.all()]
# Filter slides by tags
filteredSlides = Slide.objects.all()
organs = request.GET.getl... | b836bc3b43d3c3ca47d14ac81522b4516cb5eb5d | 70,184 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.