content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def path_graph(n, create_using=None):
"""Returns the Path graph `P_n` of linearly connected nodes.
Parameters
----------
n : int or iterable
If an integer, node labels are 0 to n with center 0.
If an iterable of nodes, the center is the first.
create_using : NetworkX graph construct... | 53eabfd815b3c37f6b7e8e8e54e1a0357c0fcca9 | 31,113 |
def numpy_shift(array: np.ndarray, periods: int, axis: int, fill_value=np.nan) -> np.ndarray:
"""
numpy implementation for validation
"""
assert axis in range(-array.ndim, array.ndim)
copy_src_indices = [slice(None)] * array.ndim
copy_dst_indices = [slice(None)] * array.ndim
fill_indices = ... | 3ffc61a61abc5bdc3547822c0715a81efb9d0b4d | 31,114 |
def draw_rect(im, cords, color = None):
"""Draw the rectangle on the image
Parameters
----------
im : numpy.ndarray
numpy image
cords: numpy.ndarray
Numpy array containing bounding boxes of shape `N X 4` where N is the
number of bounding boxes and the boundin... | 02c52166f0f9c25d9f9ad61f7083d7ee733759aa | 31,115 |
from typing import List
def _setup_entities(hass, dev_ids: List[str]):
"""Set up CAME light device."""
manager = hass.data[DOMAIN][CONF_MANAGER] # type: CameManager
entities = []
for dev_id in dev_ids:
device = manager.get_device_by_id(dev_id)
if device is None:
continue
... | 5c9deb213b5df197aaf075f62a68c1472951a3e0 | 31,116 |
def check_doa(geometry, doa, online=False):
"""
Check value of the DoA
"""
if not online:
doas = [doa]
else:
doas = doa
for doa in doas:
if doa < 0:
return False
if geometry == "linear" and doa > 180:
return False
if geometry == "ci... | ae2be5c478968358a9edf6e7da63e586af39eed8 | 31,118 |
def _trim_orderbook_list(arr: list, ascending: bool, limit_len: int = 50) -> list:
"""trims prices up to 4 digits precision"""
first_price = arr[0][0]
if first_price < 0.1:
unit = 1e-5
elif first_price < 1:
unit = 1e-4
elif first_price < 10:
unit = 1e-3
elif first_price <... | 557dceab9b11836b2f884ebc40d1e66769f5eb4c | 31,121 |
from corpkit.process import make_name_to_query_dict
def process_piece(piece, op='=', quant=False, **kwargs):
"""
Make a single search obj and value
"""
if op not in piece:
return False, False
translator = make_name_to_query_dict()
target, criteria = piece.split(op, 1)
criteria = c... | 2d79455fcc27e0b3b9a81209cdc28089a7b73f5a | 31,122 |
import random
def normal220(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2,bb1,bb2,bb3,aa1,aa2):
"""
for source and destination id generation
"""
"""
for type of banking work,label of fraud and type of fraud
"""
idvariz=random.choice(bb1)... | d83408e8d5ec18d0a6de2aee62ca12aa5f1561b8 | 31,123 |
def sigma_voigt(dgm_sigmaD,dgm_gammaL):
"""compute sigma of the Voigt profile
Args:
dgm_sigmaD: DIT grid matrix for sigmaD
dgm_gammaL: DIT grid matrix for gammaL
Returns:
sigma
"""
fac=2.*np.sqrt(2.*np.log(2.0))
fdgm_gammaL=jnp.min(dgm_gammaL,axis=1)*2.0
fdgm_sigm... | 27581dc61e04d2f5b1411cb64093e03378bb8297 | 31,124 |
def zigzag2(i, curr=.45, upper=.48, lower=.13):
"""
Generalized version of the zig-zag function.
Returns points oscillating between two bounds
linearly.
"""
if abs(i) <= (upper-curr):
return curr + i
else:
i = i - (upper-curr)
i = i%(2*(upper-lower))
if i < (u... | a51624af520121eb7285b2a8a5b4dc5ffa552147 | 31,125 |
def get_len_of_range(start, stop, step):
"""Get the length of a (start, stop, step) range."""
n = 0
if start < stop:
n = ((stop - start - 1) // step + 1);
return n | 4c43f502efe7ad0e20a9bc7624e6d47e208a94a7 | 31,126 |
def generate_tap(laygen, objectname_pfix, placement_grid, routing_grid_m1m2_thick, devname_tap_boundary, devname_tap_body,
m=1, origin=np.array([0,0]), transform='R0'):
"""generate a tap primitive"""
pg = placement_grid
rg_m1m2_thick = routing_grid_m1m2_thick
# placement
itapbl0 = ... | 59f3ceeee74e8b99690e86b671cbd1e503fe4121 | 31,127 |
from typing import Union
from typing import Optional
def multiply(
x1: Union[ivy.Array, ivy.NativeArray],
x2: Union[ivy.Array, ivy.NativeArray],
out: Optional[Union[ivy.Array, ivy.NativeArray]] = None,
) -> ivy.Array:
"""Calculates the product for each element ``x1_i`` of the input array ``x1`` with
... | 53ce0b715933b59b40abd7f51d7bb104874e54db | 31,128 |
def discriminateEvents(events, threshold):
"""
Discriminate triggers when different kind of events are on the same channel.
A time threshold is used to determine if two events are from the same trial.
Parameters
----------
events : instance of pandas.core.DataFrame
Dataframe containing ... | 0078548ea463c01d88b574185b3dcb5632e5cd13 | 31,129 |
def whiten(sig, win):
"""Whiten signal, modified from MSNoise."""
npts = len(sig)
nfreq = int(npts // 2 + 1)
assert (len(win) == nfreq)
# fsr = npts / sr
fsig = fft(sig)
# hl = nfreq // 2
half = fsig[: nfreq]
half = win * phase(half)
fsig[: nfreq] = half
fsig[-nfreq + 1:] ... | 0c6e4300d7bebc466039ee447c7f6507d211be1c | 31,130 |
def create_slice(request):
"""
Create a slice based on a pattern. User has to be the "production_request" owner. Steps should contain dictionary of step
names which should be copied from the pattern slice as well as modified fields, e.g. {'Simul':{'container_name':'some.container.name'}}
:param produ... | c01f15b6b369d9159b02c06ce6e2bc9c63dac50e | 31,131 |
def get_reverse_charge_recoverable_total(filters):
"""Returns the sum of the total of each Purchase invoice made with recoverable reverse charge."""
query_filters = get_filters(filters)
query_filters.append(['reverse_charge', '=', 'Y'])
query_filters.append(['recoverable_reverse_charge', '>', '0'])
query_filters.a... | 95b24a90230675ffda80760d073705f5da823bc8 | 31,132 |
import hashlib
def load_data(url_bam):
"""Load ``MetaData`` from the given ``url_bam``."""
if url_bam.scheme != "file":
raise ExcovisException("Can only load file resources at the moment")
with pysam.AlignmentFile(url_bam.path, "rb") as samfile:
read_groups = samfile.header.as_dict().get("... | e5c17b6ad236ebcbd4222bbe5e3cbdb923965325 | 31,133 |
import random
import string
def generate_room_number():
"""
Generates a room number composed of 10 digits.
"""
return "".join(random.sample(string.digits, 10)) | 133e7463106df89fb68de6a7dfa7c718bc1bc5ba | 31,134 |
def is_noiseless(model: Model) -> bool:
"""Check if a given (single-task) botorch model is noiseless"""
if isinstance(model, ModelListGP):
raise ModelError(
"Checking for noisless models only applies to sub-models of ModelListGP"
)
return model.__class__ in NOISELESS_MODELS | d1b5cfee5713cc44d40a7d0d98542d0d2147a9a3 | 31,135 |
def random_sampling_normalized_variance(sampling_percentages, indepvars, depvars, depvar_names,
n_sample_iterations=1, verbose=True, npts_bandwidth=25, min_bandwidth=None,
max_bandwidth=None, bandwidth_values=None, scale_unit_box=True, n_th... | a340659a363760c01d38dd21b2a439b346751a23 | 31,136 |
def classify_data(X_train, Y_train, X_test):
"""Develop and train your very own variational quantum classifier.
Use the provided training data to train your classifier. The code you write
for this challenge should be completely contained within this function
between the # QHACK # comment markers. The nu... | 7af9c56490a782fb32f289042a23871bfb5f0a85 | 31,137 |
def preprocess_embedding(z):
"""Pre-process embedding.
Center and scale embedding to be between -.5, and .5.
Arguments:
z: A 2D NumPy array.
shape=(n_concept, n_dim)
Returns:
z_p: A pre-processed embedding.
"""
# Center embedding.
z_p = z - np.mean(z, axis=0, ... | 6927e606ec61b0504e91b5b19e84a819d3e86274 | 31,138 |
def T_from_Ts(Ts,P,qt,es_formula=es_default):
""" Given theta_e solves implicitly for the temperature at some other pressure,
so that theta_e(T,P,qt) = Te
>>> T_from_Tl(282.75436951,90000,20.e-3)
290.00
"""
def zero(T,Ts,P,qt):
return np.abs(Ts-get_theta_s(T,P,qt,es_formula))
return optim... | ae2431127a3d0924da4b1e45d98c72a2c42b7a6c | 31,140 |
from typing import Tuple
def find_global_peaks_integral(
cms: tf.Tensor, crop_size: int = 5, threshold: float = 0.2
) -> Tuple[tf.Tensor, tf.Tensor]:
"""Find local peaks with integral refinement.
Integral regression refinement will be computed by taking the weighted average of
the local neighborhood ... | 22529379fdf1e685b33319e0432a95ee51973575 | 31,142 |
def test_data(test_data_info, pytestconfig):
"""Fixture provides test data loaded from files automatically."""
data_pattern = pytestconfig.getoption(constants.OPT_DATA_PATTERN)
if test_data_info.subdirs:
return list(
list(loader.each_data_under_dir(
test_data_info.datadi... | 639c9b16b9f6e1a4bbb5422d0ce29850535a267b | 31,143 |
def load_maggic_data():
"""Load MAGGIC data.
Returns:
orig_data: Original data in pandas dataframe
"""
# Read csv files
file_name = 'data/Maggic.csv'
orig_data = pd.read_csv(file_name, sep=',')
# Remove NA
orig_data = orig_data.dropna(axis=0, how='any')
# Remove labels
orig_data = o... | b4d1c219ef892c9218fd45aba22c859c96954853 | 31,144 |
def create_res_hessian_computing_tf_graph(input_shape, layer_kernel, layer_stride):
"""
This function create the TensorFlow graph for computing hessian matrix for res layer.
Step 1: It first extract image patches using tf.extract_image_patches.
Step 2: Then calculate the hessian matrix by outer product... | aaf5f52b32f1f8f67d54d70c10c706dc26b91a75 | 31,145 |
def loadUiType(uiFile):
"""
Pyside lacks the "loadUiType" command, so we have to convert the ui file to py code in-memory first
and then execute it in a special frame to retrieve the form_class.
http://tech-artists.org/forum/showthread.php?3035-PySide-in-Maya-2013
"""
parsed = xml.parse(ui... | 2b5bfcdefb0d1c0fb361a4d080eea0b0cc927599 | 31,146 |
def ldns_native2rdf_int8(*args):
"""LDNS buffer."""
return _ldns.ldns_native2rdf_int8(*args) | 21e295dcd9a67018bd673dc5ff605e80707d9736 | 31,147 |
import re
def _ListProcesses(args, req_vars): # pylint: disable=W0613
"""Lists processes and their CPU / mem stats.
The response is formatted according to the Google Charts DataTable format.
"""
device = _GetDevice(args)
if not device:
return _HTTP_GONE, [], 'Device not found'
resp = {
'cols':... | 636f91e3dcf6b236081787096c12eadf956c9024 | 31,148 |
def _runForRunnerUser(resourceDB: ResourceDB, user: User) -> TaskRun:
"""Returns the task run accessible to the given user.
Raises AccessDenied if the user does not represent a Task Runner
or the Task Runner is not running any task.
"""
# Get Task Runner.
if not isinstance(user, TokenUser):
... | e3b89ed95bea8c50be885ef56578e23919a7a25c | 31,149 |
def narrow(lon='auto',lat='auto',ax=None,lfactor=1,**kwargs):
"""
Plot north arrow.
Parameters:
lon: Starting longitude (decimal degrees) for arrow
lat: Starting latitude (ecimal degrees) for arrow
ax: Axes on which to plot arrow
lfactor: Length factor to increase/decrea... | 8d3162ab05366472b607ff953811caf2796c1e3e | 31,150 |
from typing import List
from pathlib import Path
def dump_content_descriptor(artifact_manager: ArtifactsManager) -> ArtifactsReport:
""" Dumping content/content_descriptor.json into:
1. content_test
2. content_new
3. content_all
Args:
artifact_manager: Artifacts ma... | e39bc38c72cd3f7b555d410d037ef1df3c747933 | 31,151 |
def parse_movie(line, sep='::'):
"""
Parses a movie line
Returns: tuple of (movie_id, title)
"""
fields = line.strip().split(sep)
movie_id = int(fields[0]) # convert movie_id to int
title = fields[1]
return movie_id, title | 9d7a13ca3ddf823ff22582f648434d4b6df00207 | 31,152 |
def make_plot(dataset, plot_label, xlabel, ylabel, legend):
"""
Generates a MatPlotLib plot from the specified dataset and with the specified labeling features.
make_plot(dataset, plot_label, xlabel, ylabel, legend) -> plt
@type dataset: list of list
@param dataset: formatted dataset.
... | 0e5ff583c65dcd3751354a416d9940a12871e37d | 31,153 |
def flatten_list(in_list: typ.List) -> typ.List:
"""Flattens list"""
result = []
for item in in_list:
if isinstance(item, list):
result.extend(flatten_list(item))
else:
result.append(item)
return result | 9d847fea7f1eb30ecbd51dd1d001c8661a502a0d | 31,154 |
import logging
def formatMessage(data):
"""
Format incoming message before passing to Discord
"""
logging.info("Formatting message payload...")
time = (data.occurredAt).split("T")
message = [":alarm_clock: __**Meraki Alert**__ :alarm_clock: "]
message.append(f"**Device:** {data.deviceName}... | 21d7a50951aeecb6917479622f4131b7ddcfda00 | 31,155 |
def _convert_nearest_neighbors(operator, container, k=None, radius=None):
"""
Common parts to regressor and classifier. Let's denote
*N* as the number of observations, *k*
the number of neighbours. It returns
the following intermediate results:
top_indices: [N, k] (int64), best indices for
... | c328d2f78467df05ddcfd83186e0704e234eabd8 | 31,156 |
import click
def interface_alias_to_name(config_db, interface_alias):
"""Return default interface name if alias name is given as argument
"""
vlan_id = ""
sub_intf_sep_idx = -1
if interface_alias is not None:
sub_intf_sep_idx = interface_alias.find(VLAN_SUB_INTERFACE_SEPARATOR)
if ... | 6cac69be850a65dda505999616e4d21d0a8c9438 | 31,157 |
import time
def twait(phrase, tn, tout=-1, logging='off', rcontent=False, screenprint=False):
""" telnetlib wait with optional timeout and optional logging"""
# Adding code to allow lists for phrase
finalcontent = ' '
#This is the time of the epoch
startTime = int(time.time())
while True:
... | 9c4308e873321fd556d8eec2668981fc2843ae87 | 31,158 |
def process_ob(obs : dict) -> dict:
""" Processes an individual post
:param obs: video observation metadata
:returns: processed post metadata based on tags in posts_titles
"""
metadata = {tag: obs[tag] for tag in obs_tags}
metadata.update(process_obs(obs["children"], obs["history"]))
metad... | e5200443d6ba6e69d49fb56d377f4a9992f157bb | 31,159 |
from beta import calc_beta_eta
def calc_detectable_frac(gen, model, args, gen2=None, swap_h0_and_h1=False, verbose=0):
"""
:param gen: sample generator
:param model: NN model
:param args: parameters object (should contain alpha and beta attributes)
:param gen2: if gen2 is not None gen output is u... | 6844abc148cee69453eb3136e018a40eccb40334 | 31,160 |
import numpy as np
from typing import Tuple
def similarity_std(
buffer: NumpyNDArray, wav_file: WavFile, rate: int, threshold: float
) -> Tuple[bool, float, float]:
"""Check the similarity of a recorded sound buffer and a given wav_file.
Use a correlation check using the standard deviation."""
_, ... | 8900495860f59b39be3f5f3808bb321e0275bc81 | 31,161 |
def grdtrack(points, grid, newcolname=None, outfile=None, **kwargs):
"""
Sample grids at specified (x,y) locations.
Grdtrack reads one or more grid files and a table with (x,y) [or (lon,lat)]
positions in the first two columns (more columns may be present). It
interpolates the grid(s) at the positi... | ed6a09c4f925321520c99e2a941602e82852bec3 | 31,162 |
def add(x, y):
"""add two number"""
return x+y | 9c5fe5867e0c345bd3e7439b8fc76c21b20b2c35 | 31,163 |
def is_exponential(character: str) -> bool:
"""
Whether an IPA character is written above the base line
and to the right of the previous character,
like how exponents of a power are written
in mathematical notation.
"""
return character in exponentials | 0d263a0969454ad9d8e7a3a53e393b55b5c8d45c | 31,164 |
def _union_items(baselist, comparelist):
"""Combine two lists, removing duplicates."""
return list(set(baselist) | set(comparelist)) | 782f325960db2482afc75e63dbc8a51fea24c8d0 | 31,165 |
def broadcast_state(state=current_state, ip=ip_osc, port=port_client):
"""
Broadcasts state
"""
print("Called Broadcast State Function")
#client = udp_client.UDPClient(ip, port,1)
#builder = osc_message_builder.OscMessageBuilder(address='/status')
#for k,v in state.items():
# builde... | be8b391cbd033b7271796ec47529b8ca78f85bd5 | 31,167 |
def make_gaussian(shape, var):
"""returns 2d gaussian of given shape and variance"""
h,w = shape
x = np.arange(w, dtype=float)
y = np.arange(h, dtype=float)[:,np.newaxis]
x0 = w // 2
y0 = h // 2
mat = np.exp(-0.5 * (pow(x-x0, 2) + pow(y-y0, 2)) / var)
normalized_img = np.zeros((h, w))
... | 88500f08c43b446ea073fef322f2007ea4032875 | 31,168 |
def analysis_iou_on_miyazakidata(result_path, pattern="GT_o"):
"""对最终4张图片统合的结果进行测试"""
ious = []
pattern1, pattern2 = pattern.strip().split("_")
pattern1 = pattern_dict[pattern1]
pattern2 = pattern_dict[pattern2]
for i in range(1, 21):
image1 = get_image(result_path, i, pattern1)
... | 5099cde71284c0badae64e701a2362b30f87ad4c | 31,170 |
def min_max_rdist(node_data, x: FloatArray):
"""Compute the minimum and maximum distance between a point and a node"""
lower_bounds = node_data[0]
upper_bounds = node_data[1]
min_dist = 0.0
max_dist = 0.0
for j in range(x.size):
d_lo = lower_bounds[j] - x[j]
d_hi = x[j] - upper_... | 03f80210ada3530c692ce24db3bb92f0156a2d6f | 31,171 |
def strip_newlines(s, nleading=0, ntrailing=0):
"""strip at most nleading and ntrailing newlines from s"""
for _ in range(nleading):
if s.lstrip(' \t')[0] == '\n':
s = s.lstrip(' \t')[1:]
elif s.lstrip(' \t')[0] == '\r\n':
s = s.lstrip(' \t')[2:]
for _ in range(ntrai... | cd9c55d4ac7828d9506567d879277a463d896c46 | 31,172 |
def xyz_to_lab(x_val, y_val, z_val):
"""
Convert XYZ color to CIE-Lab color.
:arg float x_val: XYZ value of X.
:arg float y_val: XYZ value of Y.
:arg float z_val: XYZ value of Z.
:returns: Tuple (L, a, b) representing CIE-Lab color
:rtype: tuple
D65/2° standard illuminant
"""
x... | c2478772659a5d925c4db0b6ba68ce98b6537a59 | 31,173 |
def get_core_v1_api():
"""
:return: api client
"""
config.load_kube_config()
core_api = client.CoreV1Api()
return core_api | 2169b3dfe7a603c1d870c0100d96640f4688023c | 31,174 |
def ssbm(n: int, k: int, p: float, q: float, directed=False):
"""
Generate a graph from the symmetric stochastic block model.
Generates a graph with n vertices and k clusters. Every cluster will have floor(n/k) vertices. The probability of
each edge inside a cluster is given by p. The probability of an... | f849bb41afe617e6d66e043280b4606e1d5390c4 | 31,175 |
def std_normal_dist_cumulative(lower, upper):
"""
Find the area under the standard normal distribution between
the lower and upper bounds.
Bounds that aren't specified are taken at infinity.
"""
return find_distribution_area(stats.norm, lower, upper) | 210a16d29d8e07949dbe67c7486e9fea1656ce76 | 31,177 |
def ann_pharm_variant(dataframe, genome, knowledgebase, variant_type):
"""query with chr, start, stop, ref, alt, genome assembly version. Returns all the drugs
targeting the observed variant. """
all_direct_targets = {}
rows = get_variant_list(dataframe)
for r in rows:
direct_target_list = ... | cf1b8be54bf5ccb1bfa29afbe2af5020246ac7ea | 31,178 |
from typing import List
from typing import Tuple
def to_pier_settlement(
config: Config,
points: List[Point],
responses_array: List[List[float]],
response_type: ResponseType,
pier_settlement: List[Tuple[PierSettlement, PierSettlement]],
) -> List[List[float]]:
"""Time series of responses to pi... | 48879533d392f89cb39e7bea4b6565b8ff172279 | 31,179 |
def subtract_something(a, b):
"""
Substracts something from something else.
a: add-able
First thing
b: add-able
Second thing.
Returns:
--------
Result of adding the two.
"""
return a - b | e090d09fc3fd35b080b12584d663519b39ed24c9 | 31,180 |
from pathlib import Path
def last_rådata(datafil, track=None):
"""Last inn rådata fra en gpx-fil eller en GPSLogger csv-fil.
"""
datafil = Path(datafil)
if datafil.suffix == '.gpx':
sjekk_at_gpxpy_er_installert()
return last_rådata_gpx(datafil, track=track)
elif datafil.suffix == '... | c0e7d638c858ef97cde7c8c0ce2ea9796ff4c7de | 31,181 |
from datetime import datetime
def getAverageStay(date1, date2, hop):
"""
The average number of days a patient stays at a hospital (from admission to discharge)
if hop is None it calculates the stat system wide
"""
count = 0
num = 0
for visit in Appointment.objects.all():
doc = Doct... | 9044d415d6231e51ee4eecb5e00e3a531fb209fb | 31,182 |
def classify(inputTree,featLabels,testVec):
"""
决策树分类函数
"""
firstSides = list(myTree.keys())
firstStr = firstSides[0]
secondDict = inputTree[firstStr]
featIndex = featLabels.index(firstStr)
for key in secondDict.keys():
if testVec[featIndex]==key:
if type(secondDict[k... | 3daee2b72332c14eab41fd00bf781f00b4e1e633 | 31,183 |
def update(sql, *args):
"""
执行update语句,返回update的行数
:param sql:
:param args:
:return:
"""
return _update(sql, *args) | 700a155dbdcc77d824ce14eb95b7f041a0dda261 | 31,184 |
def videoSize():
"""
videoSize() -> (width, height)
Get the camera resolution.
Returns: A map with two integer values, i.e. width and height.
Parameters: This method does not have any parameter.
Usage: width, heigh = SIGBTools.videoSize()
size = SIGBTools.videoSize()
"""
ret... | 58757851dbbde75a1e1fef201d3ed2decee8cd06 | 31,185 |
import hashlib
def generate_md5_token_from_dict(input_params):
""" Generate distinct md5 token from a dictionary.
初衷是为了将输入一个函数的输入参数内容编码为独一无二的md5编码, 方便在其变动的时候进行检测.
Parameters
----------
input_params : dict
Dictionary to be encoded.
Returns
-------
str
Encoded md5 token... | 2faf66679a72c6fd4f2e02f3ddef728b3bab687e | 31,186 |
import re
def create_range(range_, arrayTest, headers_suppresed = True):
"""
Creates a range string from a start and end value
'A1','A4' becomes 'A1,A2,A3,A4'
"""
result_string = []
first_cell = range_.split(':')[0]
last_cell = range_.split(':')[1]
column_start = re.search(r'[a-zA-Z]+'... | 5aff1450946ee12ab943a24491a9947e6d2fa830 | 31,187 |
def find_largest_helper(n, maximum):
"""
:param n: int, the number to find the largest digit
:param maximum: int, the largest digit
:return: int, the largest digit
"""
if n % 10 > maximum:
maximum = n % 10
if n / 10 == 0:
return maximum
else:
return find_largest_helper(n // 10, maximum) | ddd49839be6a3ab6ece7cabde41f3978df1ba6f3 | 31,188 |
def global_align(seq1_1hot, seq2_1hot):
"""Align two 1-hot encoded sequences."""
align_opts = {'gap_open_penalty':10, 'gap_extend_penalty':1, 'match_score':5, 'mismatch_score':-4}
seq1_dna = DNA(dna_io.hot1_dna(seq1_1hot))
seq2_dna = DNA(dna_io.hot1_dna(seq2_1hot))
# seq_align = global_pairwise_align_nucleo... | 35cc261f43c116a96fbec9e409875b8131ff76a3 | 31,189 |
import math
def get_points_dist(pt1, pt2):
"""
Returns the distance between a pair of points.
get_points_dist(Point, Point) -> number
Parameters
----------
pt1 : a point
pt2 : the other point
Attributes
----------
Examples
--------
>>> get_points_dist(Point((4, 4)),... | c517833dec161585c336289149a8c56461fe7642 | 31,190 |
def get_source_type(*, db_session: Session = Depends(get_db), source_type_id: PrimaryKey):
"""Given its unique ID, retrieve details about a single source type."""
source_type = get(db_session=db_session, source_type_id=source_type_id)
if not source_type:
raise HTTPException(
status_code=... | 31eeda78aa3dff35618cc2e57092449e47645702 | 31,191 |
def load_data(messages_filepath, categories_filepath):
""" Get the messages and categories from CSV files. """
messages = pd.read_csv(messages_filepath)
categories = pd.read_csv(categories_filepath)
return messages.merge(categories, on='id', how='left') | 7efafc6a51b1e3dd02e3df8926fbf4ea92f8cb39 | 31,193 |
def apply_meth(dna, meth):
"""Transforms DNA sequence to methylated DNA sequence
Input:
dna (np.array): array of DNA sequence
meth (np.array): Methylation labels (len == len(dna))
Output:
dna_meth (np.array): array of methylated DNA sequence
"""
dna_meth = dna.copy()
img ... | e835047651970dd3add0a463a235209b772411fd | 31,194 |
def apply_affine_3D(coords_3d, affine_matrix):
"""
Apply an affine transformation to all coordinates.
Parameters
----------
coords_3d: numpy 2D array
The source coordinates, given as a 2D numpy array with shape (n, 3). Each of the n rows represents a point in space, given by its x, y and z ... | 2b06901c4428075800e919579ab07c7577c6d9a0 | 31,195 |
def weighted_degree_kernel_pos_inv(x1, x2, K=4, var=8, beacon=None, bin=None):
"""
Weighted degree kernel with positional invariance
:param x1:
Sequence of characters.
:param x2:
Sequence of characters.
:param K:
K-mers to be scanned.
:param beacon:
Beacon sequen... | 01403c7ca780c272b7b6ea37d291d79f2515edb6 | 31,196 |
import ast
def is_valid_block_variable_definition(node: _VarDefinition) -> bool:
"""Is used to check either block variables are correctly defined."""
if isinstance(node, ast.Tuple):
return all(
_is_valid_single(var_definition)
for var_definition in node.elts
)
retur... | 9be2e583353bed1910b2dfe70bba2dfd9fe96328 | 31,197 |
def julian_day_to_gregorian(julian_day):
"""Converts a Julian Day number to its (proleptic) Gregorian calendar equivalent
Adapted from: https://en.wikipedia.org/wiki/Julian_day#Julian_or_Gregorian_calendar_from_Julian_day_number
Note that the algorithm is only valid for Julian Day numbers greater than or
... | 1544f6cd5abee1f5cef3b5befbf24f82c8d26e44 | 31,198 |
def isnotebook():
"""Identify shell environment."""
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
if shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
... | 4620d8275c10f5aeb8e13406c897b5b93313de97 | 31,199 |
def erratic_leveling(target_level: int) -> int:
"""
Non-trivial calculation of experience to next level for an erratic leveling curve.
Args:
target_level (int): the level to reach.
Returns:
The amount of experience to reach this level from the ground up (from experience 0),
acc... | 0841aed503226932ebd49a66cdd42665eee265b2 | 31,200 |
import re
def get_puppetfile_tags(puppetfile):
"""
obtain tags from Puppetfile
:return: tuple(list, list)
"""
regex_vcs = re.compile(r"^:(git|svn)\s+=>\s+['\"](.+)['\"]\,", re.I)
regex_tag = re.compile(r"^:(ref|tag|commit|branch)\s+=>\s+['\"](.+)['\"]\,?", re.I)
vcss = []
tags = []
... | 6beec37d4c8a3a3b9a2c845cea0f5e12e18af620 | 31,201 |
def inf_is_wide_high_byte_first(*args):
"""
inf_is_wide_high_byte_first() -> bool
"""
return _ida_ida.inf_is_wide_high_byte_first(*args) | 13f30f49823e792ec83fb4b50266c72ceeed942c | 31,202 |
def rewrite_and_sanitize_link(link_header):
"""Sanitize and then rewrite a link header."""
return rewrite_links(sanitize_link(link_header)) | 907cc1492be7162611408200ad660e1a49dd5e14 | 31,203 |
def user_info():
"""
用户个人中心页面显示
:return:
"""
user = g.user
if not user:
return redirect("/")
data = {
"user": user.to_dict()
}
return render_template("news/user.html", data=data) | 2cbe80c6086bffbb5e147ee756b7b393b546da99 | 31,204 |
def cartesian2polar(state: CartesianState, state_goal : CartesianState) -> PolarState:
"""
rho is the distance between the robot and the goal position
: \sqrt((x*-x)^2 + (y*-y)^2)
alpha is the heading of the robot relative the angle to the goal
: theta - atan2((y*-y),(x*-x))
beta is the goal pos... | 92eea79a8ac8f7c83e78d9aaaff3d6af500b9876 | 31,205 |
def organize_array_by_rows(unformatted_array, num_cols):
"""Take unformatted array and make grid array"""
num_rows = int(len(unformatted_array) / num_cols)
array = []
for row in range(num_rows):
array.append(unformatted_array[row * num_cols:(row + 1) * num_cols])
return array | 8a7d74ea593bfcc5c4d3a92d1c192b2bf628f641 | 31,206 |
from typing import Union
from typing import Literal
from typing import Sequence
def group_abundance(
adata: AnnData,
groupby: str,
target_col: str = "has_ir",
*,
fraction: Union[None, str, bool] = None,
sort: Union[Literal["count", "alphabetical"], Sequence[str]] = "count",
) -> pd.DataFrame:
... | adfc5047349ec5fcffdc05de0ae2ecdfbf9b8b6c | 31,207 |
def infer(model, text_sequences, input_lengths):
"""
An inference hook for pretrained synthesizers
Arguments
---------
model: Tacotron2
the tacotron model
text_sequences: torch.Tensor
encoded text sequences
input_lengths: torch.Tensor
input lengths
Returns
-... | e7937395956e2dcd35dd86bc23599fbb63417c22 | 31,208 |
def build_info(image, spack_version):
"""Returns the name of the build image and its tag.
Args:
image (str): image to be used at run-time. Should be of the form
<image_name>:<image_tag> e.g. "ubuntu:18.04"
spack_version (str): version of Spack that we want to use to build
Retur... | bb09a530e2fdf50b78225647df1238ae08fe5b3d | 31,209 |
def _get_data_attr(data, attr):
"""Get data object field."""
if isinstance(data, dict):
# `Data` object's id is hydrated as `__id` in expression engine
data = data["__id"]
data_obj = Data.objects.get(id=data)
return getattr(data_obj, attr) | bdc90d01172655f77680f0c373ed609b4100e874 | 31,210 |
def get_user_project(user, dds_project_id):
"""
Get a single Duke DS Project for a user
:param user: User who has DukeDS credentials
:param dds_project_id: str: duke data service project id
:return: DDSProject: project details
"""
try:
remote_store = get_remote_store(user)
pr... | 71649da2b092954d8f7d65059edd75fc18a8e750 | 31,211 |
def _event_split(elist):
"""Split event list into dictionary of event keywords
"""
eventdict = dict()
dictkeys = (roxar.EventType.WLIMRATE,
roxar.EventType.WLIMPRES,
roxar.EventType.WLIMRATIO,
roxar.EventType.WHISTRATE,
roxar.EventType.WHIS... | 8097fdee8b36881b0c5a4851165ac57f70482415 | 31,212 |
import random
import re
def generate_reply(utt, dais):
"""Generate a reply task for the given utterance and DAIs list."""
ret = DataLine(dat='reply', abstr_utt=utt, abstr_da='&'.join([unicode(dai) for dai in dais]))
utt, dais = deabstract(utt, dais)
# offer a ride (meeting the specifications in dai... | 9a9d1a7271b03e01e492be830e29725399f61387 | 31,214 |
def create_concept_graphs(example_indices, grakn_session):
"""
Builds an in-memory graph for each example, with an example_id as an anchor for each example subgraph.
Args:
example_indices: The values used to anchor the subgraph queries within the entire knowledge graph
grakn_session: Grakn S... | 66d5d13fad865e6d6437eb29d20e611e509ad7f7 | 31,215 |
def GetChange(host, change):
"""Queries a Gerrit server for information about a single change."""
path = 'changes/%s' % change
return _SendGerritJsonRequest(host, path) | 3f4c7c3554fdbba0cc6bc0c8c513823859d22d61 | 31,216 |
def block_shape(f):
"""
find the block shape (nxb, nyb, nzb) given the hdf5 file f
returns
dimension, (nxb, nyb, nzb)
"""
if 'integer scalars' in f.root:
params = f.getNode(f.root, 'integer scalars').read()
p_dict = dict((name.rstrip(), val) for name, val in params)
... | ce7e3f58400185fa76855dc809f78867905915bc | 31,218 |
def model_init(rng_key, batch, encoder_sizes=(1000, 500, 250, 30)):
"""Initialize the standard autoencoder."""
x_size = batch.shape[-1]
decoder_sizes = encoder_sizes[len(encoder_sizes) - 2::-1]
sizes = (x_size,) + encoder_sizes + decoder_sizes + (x_size,)
keys = jax.random.split(rng_key, len(sizes) - 1)
par... | 937aa19a7bac1fd1e90e6ef7d7027dcb3822dcc8 | 31,219 |
def _make_rotation_matrix(vector_1,vector_2):
"""" Generates the rotation matrix from vector_1 to vector_2"""
# Use formula for rotation matrix: R = I + A + A^2 * b
# https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d
v = np.cross(vector_1,vecto... | 17c24c4c4e6c8378b65076686f4d80736d6ccf3e | 31,221 |
def get_models(models='all'):
"""
Returns model names as a list
Parameters
----------
models: str
OPTIONAL. Default value is 'all' in which case all keys in defaule_models are returned.
If 'mixed' is passed, only the MixedFluid model names are returned.
"""
if models == 'all':
return list(default_models.ke... | dcf0a00946f3146e5511825d875947bb5278be6a | 31,222 |
def other_language_code():
"""Language code used for testing, currently not set by user."""
return 'de-DE' | 2cbac23cd7a13e71991be6516a3a38dee19ae690 | 31,223 |
import numpy
def do_novelty_detection(
baseline_image_matrix, test_image_matrix, image_normalization_dict,
predictor_names, cnn_model_object, cnn_feature_layer_name,
ucn_model_object, num_novel_test_images,
percent_svd_variance_to_keep=97.5):
"""Does novelty detection.
Specifi... | 69181690b81a987b45dcdbea5b0febe8928b365b | 31,224 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.