content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _construct_request_parameters(args: dict, keys: list, params={}):
"""A helper function to add the keys arguments to the dict parameters"""
parameters = {}
if params is not None:
for p in params:
parameters[p] = params[p]
for (arg_field, filter_field) in keys:
value = ar... | a268ddf8612014a4a4012eab8cfae50d1437be1e | 53,673 |
from typing import Optional
def __run_query_table(context, client, sql: String) -> Optional[DataFrame]:
"""
Execute an SQL
:param context: execution context
:param sql: the SQL select query to execute
:return: panda DataFrame or None
:rtype: panda.DataFrame
"""
df = None
close_dow... | ff4f342d0b620d0d2a9b03b12164e39b84e18fb2 | 53,674 |
import six
import uuid
def add_parts_json(ibs, annot_uuid_list, part_bbox_list, part_theta_list, **kwargs):
"""
REST:
Method: POST
URL: /api/part/json/
Ignore:
sudo pip install boto
Args:
annot_uuid_list (list of str) : list of annot UUIDs to be used in IBEIS IA
... | 7b158f6cade44f2610d7b97b1425b6eeeb999170 | 53,675 |
def single_re_sub_empty_test():
"""A function without arguments, needed for timeit.
NB: uses global variable text to solve the argument problem"""
return single_re_sub_empty(text, repl_chars) | a5921a88012f9ebccdaac0baa5de4a166c8f0e79 | 53,676 |
def create_templates(filename):
"""Create templates with the service."""
data_to_use = _load_json(filename)
service = current_records_marc21.templates_service
templates = []
for data in data_to_use:
template = service.create(data=data["values"], name=data["name"])
templates.append(t... | ab788770dd6c58b156bf84dee7f1bdfe86ec8130 | 53,678 |
def coherence_limit(nQ=2, T1_list=None, T2_list=None,
gatelen=0.1):
"""
The error per gate (1-average_gate_fidelity) given by the T1,T2 limit.
Args:
nQ: number of qubits (1 and 2 supported).
T1_list: list of T1's (Q1,...,Qn).
T2_list: list of T2's (as measured, ... | 5860ecfbc883fc74acdb838d975b9de2fdba2158 | 53,679 |
from typing import Sequence
import warnings
def connection_from_list_slice(
list_slice: Sequence,
args: ConnectionArguments = None,
connection_type: ConnectionConstructor = Connection,
edge_type: EdgeConstructor = Edge,
pageinfo_type: PageInfoConstructor = PageInfo,
slice_start=0,
list_len... | f318dab2e5fa7b422813a3f61ba92c95c01bba1e | 53,680 |
def logp_model(residuals, params_nodes, Pk, Variance, distribution_parameters):
"""returns -2log p of residuals"""
Pk_double = np.concatenate((Pk, Pk))
return 2*np.sum(np.square(params_nodes) / Pk_double) + negative_2loglikelihood(residuals, Variance, distribution_parameters) | 0ecaed2b7a06747ca27cb4d4b67855bed29a0837 | 53,681 |
def _loadParamFromFile(config, section, paramName):
"""
read param from file
validate it
and load to to global conf dict
"""
# Get paramName from answer file
value = config.get(section, paramName)
# Validate param value using its validation func
param = controller.getParamByName(pa... | a656e32b1273bab63708fd91acdbcaec9dc97fa4 | 53,682 |
def nonConv(wSpace, pts, val= -100, vis= False, img_name= 'img'):
"""This function takes in list of convex shapes with there points list for each shape
and the union of these shapes will give us the desired nonConvex shape"""
convPts = []
ctr=0
for conv in pts:
ctr+=1
wSpace1 = convPolygon(wSpace, conv, vis=... | f545e2a7ab87e1833cf8d41e3734054852ee9ad5 | 53,683 |
from typing import Dict
from typing import List
from typing import Tuple
def votes_per_month(values: Dict[str, List[str] | Tuple[str]]) -> Dict[str, Dict[str, int]]:
"""
:param values: a dictionary formatted like: {month: list of votes}
:returns: dictionary every person for every month
"""
all_per... | acff0d2aaff68b12430c7d28f7f7f7b0f08aaa3c | 53,685 |
import array
def CalculationElement(curr_doc, elementlist):
"""
:param elementlist: list of all elements
:return:
all_functions: [[functions of elements 1][functions of element 2]...[functions of element n]]
--> order of functions: N, u, Q, M, w, phi
x: Symbol to plot over
... | 0b351ecf8c82cd0bd2750711eb41e2e9d1e97e8d | 53,686 |
def adjacency2digraph(
adj_matrix: np.ndarray,
similar_this_dgraph: nx.DiGraph = None) -> nx.DiGraph:
"""Converts the adjacency matrix to directed graph.
If similar_this_graph is given, then the final directed graph has the same
node labeling as the given graph has.
Using dgraph2adjacen... | b82a08bd669a4d5c6629713c2a869250356b8bd1 | 53,687 |
def move_cursor(move):
"""Return move value for cursor."""
return {
'left': -1,
'right': 1,
}[move] | 333c3b6b0a8b3e936250f47b16019420da2a3670 | 53,688 |
def accuracy(output, target):
"""Computes the precision@k for the specified values of k"""
topk = (1,4)
maxk = max(topk)
batch_size = target.size(0)
# 上位何件のデータを参照するかターゲットデータのラベル数を参照
label_count = np.count_nonzero(target == 1, axis = 1)
# one-hot配列からクラス番号を取得
class_index_array, class_num... | b33a612ff6ae883eabe6e0f15d1e2ddffc4ff79a | 53,689 |
def unsubscribe_from_basket_action(newsletter):
"""Unsubscribe from Basket action."""
def unsubscribe_from_basket(modeladmin, request, queryset):
"""Unsubscribe from Basket."""
ts = [(mozillians.users.tasks.unsubscribe_from_basket_task
.subtask(args=[userprofile.user.email, userp... | 8514a17decf1c47dd3718da781c03b880e2aae3e | 53,690 |
def find_possible_pt2262_device(device_id):
"""Look for the device which id matches the given device_id parameter."""
for dev_id, device in RFX_DEVICES.items():
if hasattr(device, 'is_lighting4') and len(dev_id) == len(device_id):
size = None
for i, (char1, char2) in enumerate(zi... | 037e3bf24811ba545ebe1b8327056239fca2f59c | 53,692 |
import math
def gcd(*nums):
"""
Find the greatest common divisor (GCD) of a list of numbers.
Args:
*nums (tuple[int]): The input numbers.
Returns:
gcd_val (int): The value of the greatest common divisor (GCD).
Examples:
>>> gcd(12, 24, 18)
6
>>> gcd(12, 2... | ea3b2f55ab1db530a2c0e5d472c053b9e538f3e0 | 53,693 |
def exposure_compensation(img,
illuminant_lux, # ambient illumination strength in lux
luminance_target=300, # will compensate for this luminance, in cd/m2
luminance_display=300, # the luminance of the display cd/m2
... | d6a0d740a0578fcf7860c5bff98a719b4e9ed8f2 | 53,695 |
from typing import Callable
from pathlib import Path
from typing import Tuple
from typing import Type
def template_and_parser(
template_file: Callable[[str, str], Path]
) -> Callable[[str, str], Tuple[Path, Type[AbstractParser]]]:
"""
Retrieve the parser and test template for a particular
supported fi... | ae24f243a88aa109f42494caef13f79188b21410 | 53,697 |
def sum_2(strg):
"""Sums last 3 digits"""
sum = 0
for i in strg[3:]:
sum += int(i)
if sum == 0:
sum = 1
return sum | 0b49ae9eb3f390b855d43030a5a163f594e78652 | 53,698 |
def URLs(integration: bool):
"""
summary: return URLs dict (funName:url)
arguments: (integration: bool [test type])
"""
URLs = {
"get_access_token": "/token",
"GetMe": "/users/me/",
"ListUsers": "/users",
"GetAdmins": "/users/admins",
"CreateUser": "/user",
... | 6a89eaa5ff2b0280fa82b15182edbef6dfd06154 | 53,699 |
def preprocess_cv(vec_idx_patient, cfg):
"""
Cross validation mode of the preprocessing function
:param vec_idx_patient: list containing start and end indices of the patients
:param cfg: object holding all the training parameters
:return:
"""
# Exception detection
if not cfg.binary_cla... | 73b12b155eb4329d39d3c625826af02339cf2584 | 53,700 |
def is_happy(n: int) -> bool:
"""
is_happy
:param n:
:return:
"""
global happy_flag
happy_flag = False
total, counter = n, 0
while True:
num_list, total= list(str(total)), 0
for i in num_list:
total += pow(int(i), 2)
counter += 1
if total... | 091ca74fcfd50c01197cd9a38a24cf1ae951f769 | 53,701 |
import cmath
def rotate_points(points, phase_shift):
"""
Rotate a point about the origin.
Arguments:
points: iterable(complex)
Points to rotate in the complex plane.
phase_shift:
Magnitude of rotation in radians.
Returns:
rotated_points: list(complex)
... | e9ae43774bc8f5ac770413f6e758d41223fb3c00 | 53,702 |
import tkinter
def add_choice(path, choices, default=None, *, var=None, **kwargs):
"""Add an action for choosing one from a list of choices.
:source:`The menubar plugin <porcupine/plugins/menubar.py>` displays
these actions as submenus that contain radio button items.
If given, *default* should be a... | 6a629a0860791d9d9241c5cbeceeabab893b8376 | 53,703 |
def get_bprop_max_pool_grad_grad(self):
"""Grad definition for `MaxPoolGrad` operation."""
maxpool_grad_grad = G.MaxPoolGradGrad(
kernel_size=self.kernel_size,
strides=self.strides,
pad_mode=self.pad_mode)
def bprop(x1, x2, grad, out, dout):
dx1 = zeros_like(x1)
dx2 ... | 79b3ced82ac660e4ad03e8b0834f61d0f8eea9d8 | 53,704 |
def line_style(
type=None,
line_width=1,
line_opacity=1,
line_curve=0,
line_type="solid",
line_color=None,
**kwargs
):
"""
带线图形的线的风格选项
:param type:
图形类型
:param line_width:
线的宽度,默认为 1
:param line_opacity:
线的透明度,0 为完全透明,1 为完全不透明。默认为 1
:param lin... | f816bd30e9bda9d21f6607e8dc21e010982e0f07 | 53,705 |
def generate_scale(scale, note, mode=1, r_type="list", octaves=True): # scale, start, type
"""
Generate a scale
scale (string): major, melodic_minor, harmonic_minor, chromatic, major_pentatonic
note: start note
"""
if scale in SCALE_STEPS:
steps = _get_mode(SCALE_STEPS[scale], mode)
... | 18ee2df974f5b8e70589341860885af07d90a049 | 53,706 |
def _serialize_slot_variables(checkpointable_objects, path_to_root,
non_slot_variables, object_graph_proto):
"""Name slot variables and add them to `object_graph_proto`."""
named_slot_variables = {}
for optimizer_checkpoint_id, checkpointable_ref in enumerate(
checkpointable_ob... | 83439dbc483c4269b6ac71596f2017f981823593 | 53,707 |
def tupleize(func):
"""A decorator that tuple-ize the result of a function. This is useful
when the evaluation function returns a single value.
"""
def wrapper(*args, **kargs):
return func(*args, **kargs),
return wrapper | 2a2a9d709177868bd47571f86ae026d666b2593b | 53,708 |
def _gen_capture_chain_fo(nt_names, fname=None):
"""
Given a list of NT names, generate a function object (function_object_t)
that calls corresponding xed3 NT capturing functions.
Each such function captures everything that xed2 decode graph would
capture for a given pattern with NTs (nt_names) in i... | 86deb3222c5d09c081ff604cce1e65a22a14ebb5 | 53,710 |
import scipy.signal as sig
def weight2fun(grid_rowcol):
"""Make a function from a SICD data structure description of a complex image weighting
Input:
grid_rowcol Either the Grid.Row or Grid.Col SICD field depending on
which direction is being processed. Should have ei... | aa4c7ddf609e1a57573dff2433dbb9b34c97f007 | 53,711 |
def public_point(private_key, curve='secp256k1'):
"""Retrieve the public key as a point object"""
try:
curve_obj = KNOWN_CURVES[curve.lower()][0]
except KeyError:
raise ValueError("Unknown curve name {}".format(repr(curve)))
return curve_obj.public_point(key) | 5263a932a6c49a08fa587605633184639f84c283 | 53,712 |
def get_five_landmarks_from_net(landmarks):
"""
Return 5 landmarks needed in face alignment
"""
num_lmks = landmarks.shape[0]
if num_lmks == 5:
left_eye = landmarks[0]
right_eye = landmarks[1]
nose = landmarks[2]
mouse_left = landmarks[3]
mouse_right = landma... | e0e856d2b32e62bb1a0eacb5a51e55b2a065b8ea | 53,713 |
def det_vectors(h=1.0,v=1.0,nu=0.0,delta=0.0):
"""
Compute detector apperature vectors in lab frame
Parameters:
-----------
* h = detector horz width (total slit width in lab-z,
or the horizontal scattering plane)
* v = detector vert hieght (total slit width in lab-x,
or the vertica... | b4556d580d33a544565842a8a7a01535e7769918 | 53,714 |
def TopOpeBRepBuild_Tools_FindStateThroughVertex(*args):
"""
:param aShape:
:type aShape: TopoDS_Shape &
:param aShapeClassifier:
:type aShapeClassifier: TopOpeBRepTool_ShapeClassifier &
:param aMapOfShapeWithState:
:type aMapOfShapeWithState: TopOpeBRepDS_IndexedDataMapOfShapeWithState &
... | dcbc68393122f73e8c78971b0c0db0b9055066bb | 53,715 |
from typing import List
def remove_registered_at(input_list: List[dict]) -> List[dict]:
"""
Removes the field 'registered_at' frm a list of connection results, for comparing two results without
considering the time.
"""
node_to_remove = 'registered_at'
output_list = deepcopy(input_list)
fo... | f99a21853411e0247fc4aa0ce1bdfdbbb0bb3353 | 53,716 |
def vocabulary(word_counts):
"""
:param word_counts: dictionary of each word count
:return: list of vocabulary
"""
vocabulary = list(map(lambda x: x[0], sorted(word_counts.items(), key=lambda x: -x[1])))
return vocabulary | 2e7b77fe8e69ba4dd6c9136c3e80b16f02a56d49 | 53,718 |
def new_scaled_crossentropy(index=2, scaling=1.0):
"""
Returns masked crossentropy with extra scaling:
Scales the loss for given stop_index by stop_scaling
"""
def masked_crossentropy(targets: tf.Tensor, logits: tf.Tensor) -> tf.Tensor:
crossentropy = tf.keras.losses.SparseCategoricalCr... | 4d932dc663e3bb13436f7efe96b112b06d5051a3 | 53,720 |
def version():
"""
Report the version of this module
"""
return __version__ | 2ca61a973d7dfb2f2cee3dcca21d535c8c6f22ff | 53,721 |
import torch
def rejoin(chunked, initial_shape):
"""
Rejoins chunked tensor, removing the padding as necessary
>>> eq = lambda a, b: torch.all(torch.lt(torch.abs(torch.add(a, -b)), 1e-12))
>>> x = torch.arange(end=4) + 3
>>> y = torch.arange(end=15) + 2
>>> mesh = x.view(-1, 1) @ y.view(1, -1... | 6bcf5bf07b813b79245b50c72e67a98e575df5f9 | 53,722 |
def single() -> dict:
""" 1x1 block """
temp = {
0 : {
0 : Conway(Position(0,0),True)
}
}
return temp | 531495b6d5236ea41d6646490b0de0e293d8ad4a | 53,723 |
def h4(content, accesskey:str ="", class_: str ="", contenteditable: str ="",
data_key: str="", data_value: str="", dir_: str="", draggable: str="",
hidden: str="", id_: str="", lang: str="", spellcheck: str="",
style: str="", tabindex: str="", title: str="", translate... | dca57db0ad6a21d85743fd7fc111c0db35ae29f0 | 53,724 |
def svn_wc_delete2(*args):
"""
svn_wc_delete2(char path, svn_wc_adm_access_t adm_access, svn_cancel_func_t cancel_func,
svn_wc_notify_func2_t notify_func,
apr_pool_t pool) -> svn_error_t
"""
return _wc.svn_wc_delete2(*args) | 504a22b3591a5fea7db280a0a7e8d70d145c0886 | 53,725 |
def tile(address, tile_x, tile_y, tile_z, tilesize=256, **kwargs):
"""
Create mercator tile from any images.
Attributes
----------
address : str
file url.
tile_x : int
Mercator tile X index.
tile_y : int
Mercator tile Y index.
tile_z : int
Mercator tile Z... | 1b879ca79d2d8ae4dbb5cd46c6aac09a069406c7 | 53,726 |
import json
def JsonError(error_text):
"""Constructs a JSON response from an error."""
response = make_response(json.dumps({'error': error_text}, indent=4))
response.headers['Content-Type'] = 'application/json'
return response | 8de3b48da09420806094f042b3dfb795dde956d8 | 53,727 |
def calc_b_stress_xx( x, y = 0, z = 1, Fv = 1, mu = 1, lamb = 1 ):
"""
Boussonesq solution for stresses acting on x in the x direction,
from Liu and Zoback 1992 JGR (equation 68)
"""
r = get_r( x, y, z)
term1 = Fv / (2 * np.pi)
term2 = 3 * x **2 * z / r **5
term3 = mu * ( y **2 + z *... | 31ca419ecebbe4a8fe84e49f1d29818a8fe0ac3a | 53,728 |
def stress_from_momentum_budget(H, dhdx, dSxxdx, dpdx, taub, rhow):
"""Returns the stress estimate from momentum budget components."""
return rhow * GRAV * H * dhdx + H * dpdx + dSxxdx - taub | 68001cd3296ef510f4e9b1ab9f82091f93ddb2f2 | 53,729 |
def transient_provider(func):
"""
Decorator to mark a provider as transient
"""
func.transient = True
return func | 2f540fc3099c3fc71ac49ce44dbd69a042b9e39f | 53,730 |
def getObsPETs(mat, binSize=5000):
"""
Get the number of PETs in bins.
@param mat: [[x,y]]
@param binSize:int, contact matrix bin size
"""
minC = np.min(mat)
a = (mat[:, 0] - minC) / binSize
b = (mat[:, 1] - minC) / binSize
a = a.astype(int)
b = b.astype(int)
ss = {}
for ... | c4cc020f9ea32f0912cd6f5df585a7063680336b | 53,731 |
from operator import concat
def crf1d(cost, xs, ys, reduce='mean'):
"""Calculates negative log-likelihood of linear-chain CRF.
It takes a transition cost matrix, a sequence of costs, and a sequence of
labels. Let :math:`c_{st}` be a transition cost from a label :math:`s` to
a label :math:`t`, :math:`... | 86a0b9e963db1cb27cff6b0a8bf418489608defa | 53,733 |
import re
def abs_date_from_phrase(text):
"""
Identify the first absolute date in text
Returns ((month, day), start, end) or None
Doesn't currently support British dates (e.g. '28 February')
"""
dates = set()
months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august... | 8306469ce9b1a1098a9d6fb406994375820eb7ad | 53,734 |
def _read_CD_Chirascan( infile, outfile=None ):
"""CD read method for the Chirascan output format.
.. seealso::
:func:`.read_CD`
"""
def reshape(row):
df = ru.add_column(pd.DataFrame(row.iloc[1:]).reset_index(), 'w', row.iloc[0])
df = df.assign(bin=range(1, df.shape[0] + 1))
... | 7a38fcb1f1140ef69ab7f5241069cddf248f7dc6 | 53,736 |
def new(key, *args, **kwargs):
"""Create a new XOR cipher
:Parameters:
key : byte string
The secret key to use in the symmetric cipher.
Its length may vary from 1 to 32 bytes.
:Return: an `XORCipher` object
"""
return XORCipher(key, *args, **kwargs) | 8ba3567e30a032bd74069c766877f50898e5cc2a | 53,737 |
def _quadsum1(x0, a, n, ind):
"""
sum_i (yi-x0)^2/(ai*ai) = 1 with i in ind
Args:
x0(array):
a(array):
n(int): number of dimensions
ind(list(int)): number of dimensions involved
Returns:
array: n+1 x n+1
"""
x0 = np.asarray(x0)
a = np.asarray(a)
... | 52ffed9c680dbd28274b68522c86dd6b5401009c | 53,738 |
def remove_indicator(request, _id):
"""
Remove an Indicator from CRITs.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param _id: The ObjectId of the indicator to remove.
:type _id: str
:returns: :class:`django.http.HttpResponse`,
... | 6039ba42e009142ac1e5799fbd389ea7b1de9887 | 53,739 |
def zharkov_panh(v, temp, v0, a0, m, n, z, t_ref=300.,
three_r=3. * constants.R):
"""
calculate pressure from anharmonicity for Zharkov equation
the equation is from Dorogokupets 2015
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param v0: unit-cell volume in... | f975153dad4da627e31280ec1e1f5bd5568731e0 | 53,740 |
from typing import Tuple
def nearest_edge(energy: float)-> Tuple[str, str]:
"""Return nearest x-ray edge for a given energy.
Parameters
----------
energy
X-ray energy in eV.
Returns
-------
:
Absorption element.
:
Absorption edge.
Raises
------
Va... | bdcca15904c0ef937a3fb35ca591d3efa168619f | 53,741 |
def rect_break_or_contact_box(rect: Rect, box: Rect):
"""
Determine if the `rect` breaks the `box` or it contacts the border of `box`
@param rect The Rect of the target rectangle
@param box The target box
"""
return (
rect.left <= box.left or
rect.right >= box.right or
r... | 2e9652c7333c31bf8eb9cb135bcdb7c920a837ba | 53,742 |
def validate_keep(keep):
"""validates the value of the keep parameter
If it's not coercable to an int or equal to the special string values,
raise a ValueError. Otherwise, return `keep`.
:param keep: value to validate
:type keep: int or str
:return: the validated value of keep
:rtype: eith... | 5a1d03140eeab9bef1f3ae417c3d3fc77b8499bd | 53,743 |
def __get_instruments(currency: str, kind: str, expired: bool):
"""
Create a message to get all positions for a given currency on delta.
:param currency: String symbol (e.g. 'BTC' or 'ETH')
:param kind: Type of contract (either 'future' or 'option')
:return: Message (dict)
"""
# Sanitize in... | ae084e7b6452bb16b7849425f605d46d41a25bd1 | 53,745 |
import hashlib
def sha256_file(fname):
"""
Return sha256 of a given filename
Copied from https://stackoverflow.com/a/3431838
"""
hash_sha256 = hashlib.sha256()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_sha256.update(chunk)
return h... | 5c4b571922b1a2a4eaebe3bcd1436e7f7d85583f | 53,747 |
def _calculate_vm_load(vm_list):
"""
Given a list of VMs,
Calculate the sum of the load.
"""
load = 0
for server in vm_list:
pos = server.rfind('-')
if pos < 0:
pos = len(server)-1
load += weight(server[:pos])
return load | 254a3a07134517cee1b3e81636d3f16539b9636c | 53,749 |
from typing import Type
import types
def build_ufunc_wrapper(library, context, fname, signature, objmode, cres):
"""
Wrap the scalar function with a loop that iterates over the arguments
"""
assert isinstance(fname, str)
byte_t = Type.int(8)
byte_ptr_t = Type.pointer(byte_t)
byte_ptr_ptr_t... | 4a9e29f412302c17fa47afa4eae729af6d0d1299 | 53,751 |
def levensthein_dist(input_command: str, candidate: str) -> int:
"""
Implement the Levenshtein distance algorithm to determine, in case of a non-existing handle,
if theres a very similar command to suggest.
:param input_command: The non-existing handle the user gave as input
:param candidate: The (... | 02506be8655f97a60665a507cfa62cb9703590ef | 53,753 |
def find_multiset_union(role1, role2, normalize=False, parameters=None):
"""
Finds the union of a multiset
Parameters
-------------
role1
First role originators
role2
Second role originators
normalize
Do the normalization of the roles
parameters
Parameter... | fa19df40ad1b351b93dbe069edb2409260dc48cd | 53,754 |
def Cijkl(C):
"""
Populates 4D elastic tensor from 6x6 elastic tensor
:param C: 6x6 elastic constants tensor
:return: 3x3x3x3 elastic Cijkl tensor
"""
c=np.zeros(shape=(3,3,3,3))
CC=np.zeros(shape=(9,9))
CC[0:6,0:6]=C[0:6,0:6]
CC[6:9,6:9]=C[3:6,3:6]
CC[0:6,6:9]=C[0:6,3:6]
CC[6:9,0:6]=C[3:6,0:6]
c[0,0,0,0]=... | 7378c88fbdaf86472166fd317d95974129561b05 | 53,755 |
def batch_reduce(x: Tensor):
"""return x.view(x.size(0), -1).sum(1)"""
return flatten(x).sum(1) | aa1477ac16bdc1aee5a251b14d60c0eff69b891a | 53,756 |
from typing import List
from typing import Dict
import torch
def _merge_flat_fsdp_opt_state(shards_to_load: List[Dict]) -> Dict:
"""Logic described here: https://tinyurl.com/2p86zffr"""
result = shards_to_load[0][OPT_KEY]
pad_info = _get_pad_info(shards_to_load[-1])
world_size = dist_utils.get_data_pa... | 6a8a89999e08f2b39e7bb0dd4214029f45e3eb96 | 53,757 |
def split_heads_2d(x, num_heads):
"""Split channels (dimension 4) into multiple heads (becomes dimension 1).
Args:
x: a Tensor with shape [batch, height, width, channels]
num_heads: an integer
Returns:
a Tensor with shape [batch, num_heads, height, width, channels / num_heads]
"""
return tf.transp... | 5cd4694188108ccf5b9814cb9dea1f3efb56f8e2 | 53,758 |
def read_df(df, metric):
"""
You can use `read_df(df,metric)` to load data from a `<class 'pandas.core.frame.DataFrame'>` object. It will return two objects.
1. a `DataFrame` with all hyperparameters' value and the value of metric you choose
2. a `list` of all hyperparameters' name
"""
p... | 1dfd7312bf98319effa2903097abce09f549a4f3 | 53,759 |
from typing import Sequence
from typing import Optional
def solve_fast_diag(v: Sequence[AlignedArray],
grid: grids.Grid,
q0: Optional[AlignedArray] = None,
implementation: Optional[str] = None) -> AlignedArray:
"""Solve for pressure using the fast diagonal... | 04d2003db5a551334ccd25e509c3fd62087c8722 | 53,760 |
from bs4 import BeautifulSoup
def extract_data():
"""Extract data from HTML file downloaded from AEIR website."""
cards = []
# HTML scraping
soup = BeautifulSoup(open(HTML_FILE), features="html.parser")
# Informations are in the recto of the card. The verso part is not relevant
divs = soup.... | 46f52f4efafe0b7a7211cc3119e245695a10657b | 53,761 |
def read_halos(path):
"""
Reads a list of halos with columns:
rho_s (Msun/kpc^3), r_s (kpc), v (km/s)
"""
data = np.loadtxt(path)
if data.shape[1] > 2:
return data[:,0], data[:,1], data[:,2]
else:
return data[:,0], data[:,1], None | 9e1c0edb69fd18918eb7630d61b1feafcb75c675 | 53,762 |
def simpleMultivariateNormalPdf(z, detFactorSigma):
""" Assuming z has been transformed to a mean of zero and an identity matrix of covariances.
Needs to provide the determinant of the factorized (real) covariance matrix. """
dim = len(z)
return exp(-0.5 * dot(z, z)) / (power(2.0 * pi, dim / 2.) * detFa... | b41c59489c8c228486b348a6c4c1c69bffcdda0b | 53,763 |
def _get_change_extent(str1, str2):
"""
Determines the extent of differences between two strings. Returns a tuple
containing the offset at which the changes start, and the negative offset
at which the changes end. If the two strings have neither a common prefix
nor a common suffix, (0, 0) is returne... | 5530ddb5aedda9aff5953ae7d5401e20e743b705 | 53,764 |
def FilterByLength(max_length, min_length=0, # pylint: disable=invalid-name
length_keys=None, length_axis=0):
"""Returns a function that filters out examples by length.
Args:
max_length: int. If not None, indicates maximum length.
min_length: int. If not None, indicates minimum length.
... | a714ed9447d27f90049f334ff54dd416a28d4f61 | 53,766 |
def set_attr(obj, path, value):
"""
SAME AS object.__setattr__(), BUT USES DOT-DELIMITED path
RETURN OLD VALUE
"""
try:
return _set_attr(obj, split_field(path), value)
except Exception as e:
Log = get_logger()
if PATH_NOT_FOUND in e:
Log.warning(PATH_NOT_FOUND... | 9a327e71b00accbd63744ecf52d56bad00f7f216 | 53,767 |
import logging
def get_res_dataframe_as_dict(which_results_table :str, sharelist :str, ov_audit_cols, suppression_spec :str = ''):
""" extract share dataframe from HDFStore """
data_store = None
data_store_key = None
# if ov_audit_cols has content, we're going to have to grab an Ov
ov_df = None
... | 0e30b1ec930e2603bcb195c8fa2845715d2c1d00 | 53,768 |
def brac(
transitions=None,
# Common settings
discount_factor=0.99,
# Adam optimizer settings
lr_q=1e-3,
lr_pi=1e-3,
# Training settings
bc_iters=5000,
minibatch_size=100,
polyak_rate=0.005,
alpha=0.1
):
"""
Bootstrapping er... | 928003ea7980573c4422ef7831f3e9e6fb8d77c5 | 53,769 |
def stddev(e):
"""
:rtype: Column
"""
return col(StddevSamp(column=parse(e))) | 2ec79721ab63c843de993c7ac0ac58dce2a0b123 | 53,770 |
from datetime import datetime
def _is_start_date_before_end_date(start: datetime, end: datetime) -> bool:
"""Whether the start date is before the end date.
Args:
start: The start date of an event.
end: The end date of an event.
Returns:
True if valid, otherwise returns False.
... | 4a296d6673f6beb704b590893088c50a97184764 | 53,772 |
import torch
def sens_expand(x: torch.Tensor, sens_maps: torch.Tensor) -> torch.Tensor:
"""
Expand a single image into num_coils individual coil images using estimates of the sensitivity maps.
This is the inverse of sens_reduce.
Args:
x: An image of shape (H, W, 2).
sens_maps: Sen... | e2929417792032f3ffda59df5b31b988b429122b | 53,773 |
def parseWithBioPython(path, props, chains_filter=None):
"""
Parse values from file that can be parsed using BioPython library
@return a dict containing the properties that were processed
"""
pdb = './pdb'
full_path = os.path.abspath(os.path.join(pdb, path))
chains = props['chains']
... | d2a2f935f0ffdd753eac0155f666f0f885afed05 | 53,774 |
def structure(self: Client) -> StructureProxy:
"""Delegates to a
:py:class:`mcipc.rcon.be.commands.structure.StructureProxy`
"""
return StructureProxy(self, 'structure') | a7c679a2873864c36cdf1e7f987dbc6359bbb635 | 53,775 |
def _points_from_xy(x, y, z=None):
"""
Generate list of shapely Point geometries from x, y(, z) coordinates.
Parameters
----------
x, y, z : iterable
Returns
-------
list : list
"""
if not len(x) == len(y):
raise ValueError("x and y arrays must be equal length.")
if... | f5f4eb0bc4d499a86a328d9e763c3707a12ecac6 | 53,777 |
def box(width,depth,height,center=None,R=None,t=None,world=None,name=None,mass=float('inf'),type='TriangleMesh'):
"""Makes a box with dimensions width x depth x height. The box is centered
at (0,0,0) by default.
Args:
width,depth,height (float): x,y,z dimensions of the box
center (list of ... | 7af433c5ca2e61f30891652f48fe9720508e5a68 | 53,778 |
def get_disabled_container_list(duthost):
"""Gets the container/service names which are disabled.
Args:
duthost: Host DUT.
Return:
A list includes the names of disabled containers/services
"""
disabled_containers = []
container_status, succeeded = duthost.get_feature_status()
... | e5057c723cf0836be3144950c56d18242f3c8007 | 53,779 |
def _SignedVarintDecoder(mask):
"""Like _VarintDecoder() but decodes signed values."""
local_ord = ord
def DecodeVarint(buffer, pos):
result = 0
shift = 0
while 1:
if pos > len(buffer) - 1:
raise NotEnoughDataExcption("Not enough data to decode varint")
... | 6269d12970b4abbb7ef9290d5f1a254b77aefc2b | 53,780 |
def ConvertIndexListToSet(index_list):
"""Creates a set containing the indices of all '1' entries in the index
list
"""
return set(i + 1 for i, j in enumerate(index_list) if j == 1) | 78d0769de4b22aabd0d0ea2f906958a929da5299 | 53,781 |
from typing import Tuple
def decrypt(text_enc: Tuple[int, int]) -> str:
"""Function that decrypt the tuple of tokens
and re-convert them into string.
:param text_enc: the tuple of the text encrypted
:return: the text decrypted
"""
encrypted = text_enc[0] ^ text_enc[1]
decrypted = encrypte... | 0496d90818ef310b885341dad2d91823eadf97e2 | 53,782 |
def hypersphere_point(Gr, agent_pos):
"""
For each agent determines a random point inside the hypersphere (Gr,|Gr-X|),
where Gr is its center, |Gr-X| is its radius, and X is the agent position.
"""
nPop, nVar = agent_pos.shape
# Hypersphere radius of each agent
r_max = np.linalg.norm(Gr - a... | 278b993fc0394d9f32ffe334d4d56b24503342fa | 53,783 |
def iterable_validator(schema):
"""Return a validator for casting part of schema."""
return SchemaValidator(
Draft7Validator(
schema['definitions']['iterable'],
format_checker=draft7_format_checker,
),
) | 138318797dce715dc1fbcd03c08574d7c6ede33e | 53,784 |
def remove_suffix_ness(word: str):
"""Remove the suffix from the word while keeping spelling in mind.
:param word: str - of word to remove suffix from.
:return: str - of word with suffix removed & spelling adjusted.
For example: "heaviness" becomes "heavy", but "sadness" becomes "sad".
"""
suf... | 102afe196281adf27cf446443f4bc74a478b06f7 | 53,785 |
def train_nonsegmented(language_model, dataset_fnames, segment_filtering=False):
"""
Trains a classifier that maps document similarity to relevance labels.
The non-segmented version disregards segmentation and computes similarity directly between
documents.
If segment_filtering is n... | 645ff65a78ded8f22a12cb393321c16b2ee7ddca | 53,786 |
def count_words(text):
"""
this function counts words
param sentence: string containing words
"""
if not isinstance(text, str):
raise TypeError("word counter accepts only strings")
normal_word_splits = text.split(" ")
new_words = []
for asplit in normal_word_splits:
if "\... | 773d07a4092298b292601d19bba596f1e8e9bcc2 | 53,787 |
from datetime import datetime
def edit_food(id):
"""Update a food entry if the current user is the creator"""
db = get_db()
food_entry = get_food_entry(id)
old_food_name = food_entry['food_name']
old_food_code = food_entry['food_code']
if request.method == 'POST':
if request.form['act... | 1d69c684bdaec523d627a06e8fa6496d8660120c | 53,788 |
import operator
def run_simulation(sim_object, forest_dimension):
"""
Run a single simulation with RBF and report the filter accuracy.
:param sim_object: LatticeForest simulation object.
:param forest_dimension: int representing the size of one side of the square LatticeForest.
:return: tuple of ... | 966dd5438479331c448c6473a6e01daa2edd5227 | 53,789 |
def lisser(chaine):
"""Retourne la chaîne lisser.
On lisse une chaîne en remplaçant certains schémas comme
" de le " par " du ".
"""
schemas = (
(" le a", " l'a"),
(" le e", " l'e"),
(" le hom", " l'hom"),
(" le hum", " l'hum"),
(" le i", " l'i"),
("... | 39e6c406b3708e1f5c4fd6e9845fb3e860761ef4 | 53,790 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.