content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def residual_block(filters, repetitions,kernel_size=(3,3),strides=(2,2), is_first_layer=False):
"""Builds a residual block with repeating bottleneck blocks.
"""
def f(input):
for i in range(repetitions):
init_strides = (1, 1)
if i == 0 and not is_first_layer:
... | d3771289e034c4cd06f38caa715c925d7b947ab1 | 9,500 |
def vpg_omega(X,Y,Gamma=1, sigma=1, polarIn=False):
"""
Vorticity distribution for 2D Gaussian vortex patch
"""
if polarIn:
r = X
else:
r = np.sqrt(X ** 2 + Y ** 2)
omega_z = Gamma/(np.pi*sigma) * (np.exp(- r**2/sigma**2))
return omega_z | d7964152c9d21defc395e2a31d8709fe9c5d94c8 | 9,501 |
from typing import Tuple
def get_outgroup(tree: CassiopeiaTree, triplet: Tuple[str, str, str]) -> str:
"""Infers the outgroup of a triplet from a CassioepiaTree.
Finds the outgroup based on the depth of the latest-common-ancestors
of each pair of items. The pair with the deepest LCA is the
ingroup a... | c48e7121a8622876b6fb1269f881da4afe9cd8da | 9,502 |
from unittest.mock import call
def delete_host(resource_root, host_id):
"""
Delete a host by id
@param resource_root: The root Resource object.
@param host_id: Host id
@return: The deleted ApiHost object
"""
return call(resource_root.delete, "%s/%s" % (HOSTS_PATH, host_id), ApiHost) | 8d4349c0722517e0f4f8d74ea74b2d74bbc08227 | 9,503 |
from typing import Union
from typing import Tuple
from typing import List
def get_preds(model: nn.Module, image: Union[np.array, str], **kwargs) -> Tuple[List]:
"""
Generated predictions for the given `image` using `model`.
"""
logger = _get_logger(name=__name__)
# load in the image if string is ... | 8778f43fd65bccca8fc9372454aba2a7cd2544d5 | 9,504 |
async def unblock_func(func_name:object,
func_args,
logger=None,
default_res=None,
is_new_loop=False,):
"""
异步函数非阻塞
:param func_name: def 函数对象名
:param func_args: 请求参数可迭代对象(必须遵循元素入参顺序!)
:param logger:
:par... | a8f0a6f4f1171f01df4b637ca002c30efc8954e0 | 9,505 |
from typing import Dict
from typing import Tuple
import re
def replace_if_has_wiki_link(line: str, folder_dict: Dict) -> Tuple[str, int]:
""" ^title
:return: (string with all wikis replaced, replacement count)
"""
embed_rule = re.compile(re_md_reference)
wiki_partial_rule = re.compile(re_md_wiki_... | 5e7a1111685e5543a6624756809da59ae4b37f47 | 9,506 |
def init_w(w, n):
"""
:purpose:
Initialize a weight array consistent of 1s if none is given
This is called at the start of each function containing a w param
:params:
w : a weight vector, if one was given to the initial function, else None
NOTE: w MUST be an array of np.float6... | 2157f12410c2a909a32f37b9fcae4a489361fb6e | 9,507 |
def _ensure_min_resources(progs, cores, memory, min_memory):
"""Ensure setting match minimum resources required for used programs.
"""
for p in progs:
if p in min_memory:
if not memory or cores * memory < min_memory[p]:
memory = float(min_memory[p]) / cores
return cor... | f311259242a73a7bc527e3601765c95153a08748 | 9,508 |
import ctypes
def ctypes_pointer(name):
"""Create a ctypes type representing a C pointer to a custom data type ``name``."""
return type("c_%s_p" % name, (ctypes.c_void_p,), {}) | d87f10ac06391379a24f166272fd42fa938e3676 | 9,509 |
def generate_linear_data(n, betas, sigma):
"""Generate pandas df with x and y variables related by a linear equation.
Export data as csv.
:param n: Number of observations.
:param betas: beta parameters.
:param sigma: standard deviation
:return: None
"""
x = np.linspace(start=0.0, stop=1.... | 2f8b99a3c11ecf75afee51bd5df31f22efaddf58 | 9,510 |
def entry(
text,
*,
foreground: str = "",
background: str = "",
sgr: str = "",
jump_line: str = "\n> ",
) -> str:
"""
This function is derived from the input, but with the option of
coloring it and some different formatting.
Note: If you use Windows, the coloring opti... | c0bbbf5bfc675407088a3d820e3a543d9ad167c9 | 9,511 |
def vrotate_3D(vec: np.ndarray,
ref: np.ndarray) -> np.ndarray:
"""Rotates a vector in a 3D space.
Returns the rotation matrix for `vec` to match the orientation of a
reference vector `ref`.
https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-... | 4cea9d84d8fba2dd5bd9399b83ca9f1aca79b830 | 9,512 |
def asymptotic_decay(learning_rate, t, max_iter):
"""Decay function of the learning process.
Parameters
----------
learning_rate : float
current learning rate.
t : int
current iteration.
max_iter : int
maximum number of iterations for the training.
"""
return le... | 7cc699caed4ddcbde67f5d6e4199fc8479364585 | 9,513 |
def get_cell_content(browser, author):
"""
get novel cells
return [cell, cell, cell]
"""
content = list()
cells = browser.find_all(class_='t t2')
for cell in cells:
if cell.find(class_='r_two').b.string != author:
continue
for cell_content in cell.find(class_=['tp... | eb498d937b8ffd51ef7805a30940833e09571ed5 | 9,514 |
def triangle_area(a, h):
"""Given length of a side and high return area for a triangle.
>>> triangle_area(5, 3)
7.5
"""
#[SOLUTION]
return a * h / 2.0 | 9890d5e8332e667fab6dd672f62ca852f6f8f8c0 | 9,515 |
from nicos.core import ConfigurationError
import urllib
import logging
def create_mongo_handler(config):
"""
:param config: configuration dictionary
:return: [MongoLogHandler, ] if 'mongo_logger' is in options, else []
"""
if hasattr(config, 'mongo_logger'):
url = urllib.parse.urlparse(c... | c7ac39574a21c44519ae57c6fb40b8f6ca679311 | 9,516 |
def split_and_load(data, ctx_list, batch_axis=0, even_split=True):
"""Splits an NDArray into `len(ctx_list)` slices along `batch_axis` and loads
each slice to one context in `ctx_list`.
Parameters
----------
data : NDArray
A batch of data.
ctx_list : list of Context
A list of Co... | 4b8f0d1b6b256895da3e37fbb4b1be0cd0da5c46 | 9,517 |
def _get_scoped_outputs(comp, g, explicit_outs):
"""Return a list of output varnames scoped to the given name."""
cnamedot = comp.name + '.'
outputs = set()
if explicit_outs is None:
explicit_outs = ()
for u,v in g.list_connections():
if u.startswith(cnamedot):
outputs.a... | 8ff2cfe49dc3d892c4ed4adaeb9300e9395c790b | 9,518 |
def judge_1d100_with_6_ver(target: int, dice: int):
"""
Judge 1d100 dice result, and return text and color for message.
Result is critical, success, failure or fumble.
Arguments:
target {int} -- target value (ex. skill value)
dice {int} -- dice value
Returns:
message {string}... | f870f6ffee3bb90046eb2f1660e827b899c59f04 | 9,519 |
def get_normals(self, indices=None, loc="center"):
"""Return the array of the normals coordinates.
Parameters
----------
self : MeshVTK
a MeshVTK object
indices : list
list of the points to extract (optional)
loc : str
localization of the normals ("center" or "point")
... | 5d08247f70e1012eef7d525ae63f7aebe294e700 | 9,520 |
def string_to_weld_literal(s):
"""
Converts a string to a UTF-8 encoded Weld literal byte-vector.
Examples
--------
>>> string_to_weld_literal('hello')
'[104c,101c,108c,108c,111c]'
"""
return "[" + ",".join([str(b) + 'c' for b in list(s.encode('utf-8'))]) + "]" | d85b016091988c9307cbed56aafdd5766c3c9be5 | 9,521 |
def verify_model_licensed(class_name : str, model_path:str):
"""
Load a licensed model from HDD
"""
try :
m = eval(class_name).load(model_path)
return m
except:
print(f"Could not load Annotator class={class_name} located in {model_path}. Try updaing spark-nlp-jsl") | 057987d838982a85925f70c93ff2f4166b038cec | 9,522 |
def examine_api(api):
"""Find all style issues in the given parsed API."""
global failures
failures = {}
for key in sorted(api.keys()):
examine_clazz(api[key])
return failures | c94efa9a2be66e30597c63b376adf74bd2ef6462 | 9,523 |
from logging.handlers import RotatingFileHandler
import sys
from pathlib import Path
import logging
def enable_logging_app_factory(log_file: Path, level) -> logging.Logger:
"""
Enable logging for the system.
:param level: Logging Level
:param log_file: Log File path
:return:
"""
logge... | 827b99db1980c826bdebd0cfe0c559d6d1647ce8 | 9,524 |
def launch():
""" Initialize the module. """
return BinCounterWorker(BinCounter, PT_STATS_RESPONSE, STATS_RESPONSE) | 07bfc99731088a8572616aa1cbfbd0be74db5492 | 9,525 |
def make_map(source):
"""Creates a Bokeh figure displaying the source data on a map
Args:
source: A GeoJSONDataSource object containing bike data
Returns: A Bokeh figure with a map displaying the data
"""
tile_provider = get_provider(Vendors.STAMEN_TERRAIN_RETINA)
TOOLTIPS = [
... | 51578186a1fabd071e31e46b20568c23c79bc693 | 9,526 |
import os
def save_all_pages(pages, root='.'):
"""Save picture references in pages on the form:
pages = {
urn1 : [page1, page2, ..., pageN],
urn2: [page1, ..., pageM]},
...
urnK: [page1, ..., pageL]
}
Each page reference is a URL.
"""
# In case urn is an ... | 5472be4a2d6f84eef9a256eb114e9d3ce17a5375 | 9,527 |
def rotate_images(images, rot90_scalars=(0, 1, 2, 3)):
"""Return the input image and its 90, 180, and 270 degree rotations."""
images_rotated = [
images, # 0 degree
tf.image.flip_up_down(tf.image.transpose_image(images)), # 90 degrees
tf.image.flip_left_right(tf.image.flip_up_down(images)), # 1... | dd151b83918eba9b62a91b499273772e66af6ba9 | 9,528 |
def csv(args:[str])->str:
"""create a string of comma-separated values"""
return ','.join(args) | 1e48583c236940f2af10f8e050af8ad70ace51f6 | 9,529 |
import types
def _update_class(oldclass, newclass):
"""Update a class object."""
# XXX What about __slots__?
olddict = oldclass.__dict__
newdict = newclass.__dict__
# PDF changed to remove use of set as not in Jython 2.2
for name in olddict.keys():
if name not in newdict:
d... | 123eb4eadf7bf6ee65ae5df6ae9ed6df444c25d3 | 9,530 |
import google
def update_signature():
"""Create and update signature in gmail.
Returns:Draft object, including updated signature.
Load pre-authorized user credentials from the environment.
TODO(developer) - See https://developers.google.com/identity
for guides on implementing OAuth2 for the appli... | 77e9a9aef4b1ab1471cf147f57008874497d28e3 | 9,531 |
def generate_block(constraints, p, rng=None):
"""Generated a balanced set of trials, might be only part of a run."""
if rng is None:
rng = np.random.RandomState()
n_trials = constraints.trials_per_run
# --- Assign trial components
# Assign the target to a side
gen_dist = np.repeat([0... | 3c712f94e6fc4e7b5317f13a733afd1c13d7a723 | 9,532 |
def mean_by_weekday(day, val):
"""
Returns a list that contain weekday, mean of beginning and end of presence.
"""
return [day_abbr[day], mean(val['start']), mean(val['end'])] | 8aa7ac3dde83db88b44d2178ba19c5b731af683c | 9,533 |
def parse_metrics(match, key):
"""Gets the metrics out of the parsed logger stream"""
elements = match.split(' ')[1:]
elements = filter(lambda x: len(x) > 2, elements)
elements = [float(e) for e in elements]
metrics = dict(zip(['key', 'precision', 'recall', 'f1'], [key] + elements))
return m... | 70de1ad16edfe827e0a851c719d902695696700f | 9,534 |
def minecraftify(clip: vs.VideoNode, div: float = 64.0, mod: int | None = None) -> vs.VideoNode:
"""
Function that transforms your clip into a Minecraft.
Idea from Meme-Maji's Kobayashi memery (love you varde).
:param clip: Input clip
:param div: How much to divide the clip's resolution with... | 4f8338cfe2df8bff8d4f2c7571fa38688e39496c | 9,535 |
def processGOTerm(goTerm):
"""
In an object representing a GO term, replace single-element lists with
their only member.
Returns the modified object as a dictionary.
"""
ret = dict(goTerm) #Input is a defaultdict, might express unexpected behaviour
for key, value in ret.items():
if l... | 541916a0060726bbc972b784f9a011541e7c8128 | 9,536 |
import urllib
def searchxapian_show(request):
""" zeigt den Inhalt eines Dokumentes """
SORT_BY = { -1: _(u'Relevanz'),
0: _(u'URL'),
1: _(u'Überschrift/Titel'),
2: _(u'Datum der letzten Änderung') }
if request.path.find('index.html') < 0:
my_path = request.pa... | bd1f252107bfcf2aa02cf58ef6d1a302d71edbd8 | 9,537 |
import re
def html2plaintext(html, body_id=None, encoding='utf-8'):
""" From an HTML text, convert the HTML to plain text.
If @param body_id is provided then this is the tag where the
body (not necessarily <body>) starts.
"""
## (c) Fry-IT, www.fry-it.com, 2007
## <peter@fry-it.com>
## dow... | 70a7af7e557b6cffac05e33a7a394fdccbf7bc84 | 9,538 |
def _create_regularization_of_grad(param, grad, regularization=None):
""" Create and add backward regularization Operators
Function helper of append_regularization_ops.
"""
# If no gradient or no regularization is specified, then we don't need to do anything
if grad is None or (param.regularizer i... | c3c027bc72cf2a0ced45ca2ed686301303582588 | 9,539 |
def MooreSpace(q):
"""
Triangulation of the mod `q` Moore space.
INPUT:
- ``q`` -0 integer, at least 2
This is a simplicial complex with simplices of dimension 0, 1,
and 2, such that its reduced homology is isomorphic to
`\\ZZ/q\\ZZ` in dimension 1, zero otherwise.
If `q=2`, this is... | 448e948782d530f6b1ee0909fae02b66606da94d | 9,540 |
def show(tournament_name, params=[], filter_response=True):
"""Retrieve a single tournament record by `tournament name`"""
utils._validate_query_params(params=params, valid_params=VALID_PARAMS, route_type='tournament')
uri = TOURNAMENT_PREFIX + tournament_name
response = api.get(uri, params)
if fi... | d854c97e312a0bd6860a5c7fa7cbd36cd79d4ffd | 9,541 |
def auto_run_api_pk(**kwargs):
"""run api by pk and config
"""
id = kwargs['id']
env = kwargs['config']
config_name = 'rig_prod' if env == 1 else 'rig_test'
api = models.API.objects.get(id=id)
config = eval(models.Config.objects.get(name=config_name, project=api.project).body)
test_case ... | ba0e424d7ccbc3d1a6d3f8f0ec58892f4172d215 | 9,542 |
from typing import Optional
from datetime import datetime
def create(arxiv_id: ArXivID,
arxiv_ver: int,
resource_type: str,
resource_id: str,
description: str,
creator: Optional[str]) -> Relation:
"""
Create a new relation for an e-print.
Parameters
... | e1cbe374bba359b66d8564134ee27ac777c4a16e | 9,543 |
def p_contain_resist(D, t, f_y, f_u=None):
"""Pressure containment resistance in accordance with DNVGL-ST-F101.
(press_contain_resis)
Reference:
DNVGL-ST-F101 (2017-12)
sec:5.4.2.2 eq:5.8 p:94 $p_{b}(t)$
"""
if f_u is None:
f_cb = f_y
else:
f_cb = np.minimum(f_y, ... | 1c771eebf2ed43115b8ae32405172cd8576d66a2 | 9,544 |
def revalue(request):
"""其它设备参数修改"""
value = request.GET.get('value')
name = request.GET.get('name')
others = Machines().filter_machines(OtherMachineInfo, pk=request.GET.get('dID'))[0]
if name == 'remark':
others.remark = value
elif name == 'machine_name':
others.machine_name = v... | 0a7ab179932466e171a119c87871e04e2a3ae252 | 9,545 |
import authl.handlers.indieauth
import json
def indieauth_endpoint():
""" IndieAuth token endpoint """
if 'me' in flask.request.args:
# A ticket request is being made
me_url = flask.request.args['me']
try:
endpoint, _ = authl.handlers.indieauth.find_endpoint(me_url,
... | 29809af2c243a08b675738b0169bdc794965c934 | 9,546 |
def policy_simulation_c(model,var,ages):
""" policy simulation for couples"""
if var == 'd':
return {'hs': lifecycle_c(model,var=var,MA=[0],ST_w=[1,3],ages=ages,calc='sum')['y'][0] +
lifecycle_c(model,var=var,MA=[1],ST_h=[1,3],ages=ages,calc='sum')['y'][0],
... | d81ddd950eafb23b8cb219638b358a65084ae08d | 9,547 |
def emit_obj_db_entry(target, source, env):
"""Emitter for object files. We add each object file
built into a global variable for later use"""
for t in target:
if str(t) is None:
continue
OBJ_DB.append(t)
return target, source | e02c2b4e3f3b1aad15097c6b4701407ef1902b77 | 9,548 |
def listtimes(list, c):
"""multiplies the elements in the list by the given scalar value c"""
ret = []
for i in range(0, len(list)):
ret.extend([list[i]]*c);
return ret; | 8aef63677a1a926f355644187d58b47e437e152c | 9,549 |
import os
import stat
import traceback
import sys
def get(request):
"""Given a Request, return a Resource object (with caching).
We need the request because it carries media_type_default.
"""
# XXX This is not thread-safe. It used to be, but then I simplified it
# when I switched to diesel. Now... | dcc573fff237fde0b444dc5a655865a6593a27b1 | 9,550 |
def split_audio_ixs(n_samples, rate=STEP_SIZE_EM, min_coverage=0.75):
"""
Create audio,mel slice indices for the audio clip
Args:
Returns:
"""
assert 0 < min_coverage <= 1
# Compute how many frames separate two partial utterances
samples_per_frame = int((SAMPLING_RATE * WINDOW_STEP_... | d3a71082c9f551dffb5a0457ba79fc3318f6df6a | 9,551 |
def new(w: int, h: int, fmt: str, bg: int) -> 'Image':
"""
Creates new image by given size and format
and fills it with bg color
"""
if fmt not in ('RGB', 'RGBA', 'L', 'LA'):
raise ValueError('invalid format')
c = len(fmt)
image = Image()
image.im = _new_image(w, h, c)
lib.im... | c570eab9d62def584a2a12b8a228b30c57cfed76 | 9,552 |
def eval_f(f, xs):
"""Takes a function f = f(x) and a list xs of values that should be used as arguments for f.
The function eval_f should apply the function f subsequently to every value x in xs, and
return a list fs of function values. I.e. for an input argument xs=[x0, x1, x2,..., xn] the
function e... | 00c6ed7fc59b213a3ec9fec9feeb3d91b1522061 | 9,553 |
def cie94_loss(x1: Tensor, x2: Tensor, squared: bool = False, **kwargs) -> Tensor:
"""
Computes the L2-norm over all pixels of the CIEDE2000 Color-Difference for two RGB inputs.
Parameters
----------
x1 : Tensor:
First input.
x2 : Tensor:
Second input (of size matching x1).
... | 1044585ce4cf8158caa3b969a8b94001681815db | 9,554 |
def get_current_user_id() -> str:
"""
This functions gets the id of the current user that is signed in to the Azure CLI.
In order to get this information, it looks like there are two different services,
"Microsoft Graph" (developer.microsoft.com/graph) and "Azure AD Graph"
(graph.windows.net), the ... | 79a557762c9c4c2a6546370f492f879f3f046f67 | 9,555 |
def scale_labels(subject_labels):
"""Saves two lines of code by wrapping up the fitting and transform methods of the LabelEncoder
Parameters
:param subject_labels: ndarray
Label array to be scaled
:return: ndarray
Scaled label array
"""
encoder = preprocessing.LabelEncoder()
... | e7c4e4c01f7bc7b43519f1eaf97ff9ce0fda9bbd | 9,556 |
def _get_basemap(grid_metadata_dict):
"""Creates basemap.
M = number of rows in grid
M = number of columns in grid
:param grid_metadata_dict: Dictionary created by
`grids.create_equidistant_grid`.
:return: basemap_object: Basemap handle (instance of
`mpl_toolkits.basemap.Basemap`).... | caeac576f5a6345378c71e8e0e690f9bafda0995 | 9,557 |
import types
def unary_math_intr(fn, intrcode):
"""
Implement the math function *fn* using the LLVM intrinsic *intrcode*.
"""
@lower(fn, types.Float)
def float_impl(context, builder, sig, args):
res = call_fp_intrinsic(builder, intrcode, args)
return impl_ret_untracked(context, bui... | cd3a4c22dab5ea1776987a717c32fbbc71d75da7 | 9,558 |
def is_is_int(a):
"""Return `True` if `a` is an expression of the form IsInt(b).
>>> x = Real('x')
>>> is_is_int(IsInt(x))
True
>>> is_is_int(x)
False
"""
return is_app_of(a, Kind.IS_INTEGER) | d7565102a228119ba3157e9569495c5531ea5d74 | 9,559 |
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" ... | 8ea94ad556dd77d28d5abdb2034b51858c996042 | 9,560 |
import torch
def normalize_channel_wise(tensor: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torch.Tensor:
"""Normalizes given tensor channel-wise
Parameters
----------
tensor: torch.Tensor
Tensor to be normalized
mean: torch.tensor
Mean to be subtracted
std: torch.... | 862a5497d9c4379a974e8e2543acc0c1282faea5 | 9,561 |
import tqdm
def load_images(shot_paths):
"""
images = {
shot1: {
frame_id1: PIL image1,
...
},
...
}
"""
images = list(tqdm(map(load_image, shot_paths), total=len(shot_paths), desc='loading images'))
images = {k: v for k, v in images}
retur... | 4916c68e1b4255d066bc624284cde77036764dd6 | 9,562 |
import numpy
def rmSingles(fluxcomponent, targetstring='target'):
"""
Filter out targets in fluxcomponent that have only one ALMA source.
"""
nindiv = len(fluxcomponent)
flagger = numpy.zeros(nindiv)
for icomp in range(nindiv):
target = fluxcomponent[targetstring][icomp]
... | 013d5f3169fd1dcb277733627ecd5b0135bc33fb | 9,563 |
import os
import json
def discover_guids(file_path, keys):
"""
"""
# Now we revise the files
if isinstance(file_path, list):
discovered_files = file_path
else:
discovered_files = [os.path.join(file_path, f) for f in os.listdir(file_path)]
known_guids = set()
for f in disco... | a858024d7d93ab65607e41f6f8b392b28b2baab4 | 9,564 |
def gray():
"""Convert image to gray scale."""
form = ImageForm(meta={'csrf': False})
current_app.logger.debug(f"request: {request.form}")
if form.validate():
service_info = cv_services["gray"]
json_format = request.args.get("json", False)
# Image Processing
image = servi... | 93ad57e1d66b65ea4af351c942aa6defe5ee4e60 | 9,565 |
import torch
def compute_accuracy(outputs, targets, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = targets.size(0)
_, preds = outputs.topk(maxk, 1, True, True)
preds = preds.t(... | 6cfcc9e43aaaed09baae567f9cc27818c555fe5f | 9,566 |
import io
def unpack_text_io_wrapper(fp, encoding):
"""
If *fp* is a #io.TextIOWrapper object, this function returns the underlying
binary stream and the encoding of the IO-wrapper object. If *encoding* is not
None and does not match with the encoding specified in the IO-wrapper, a
#RuntimeError is raised.
... | f2c93babab4bff1f08e6fe5c04fbd97dd1ee8a84 | 9,567 |
def dummy_blob(size_arr=(9, 9, 9), pixdim=(1, 1, 1), coordvox=None):
"""
Create an image with a non-null voxels at coordinates specified by coordvox.
:param size_arr:
:param pixdim:
:param coordvox: If None: will create a single voxel in the middle of the FOV.
If tuple: (x,y,z): Create single ... | 2426ca5cddfa3da660bd5e7436f8093b1d7fa109 | 9,568 |
import torch
def poly_edges(P, T):
"""
Returns the ordered edges from the given polygons
Parameters
----------
P : Tensor
a (N, D,) points set tensor
T : LongTensor
a (M, T,) topology tensor
Returns
-------
tuple
a tuple containing the edges of the given p... | c8d838bf1ada319cebc5c08719f66846959ce2c2 | 9,569 |
def make_list(v):
"""
If the object is not a list already, it converts it to one
Examples:
[1, 2, 3] -> [1, 2, 3]
[1] -> [1]
1 -> [1]
"""
if not jsoncfg.node_is_array(v):
if jsoncfg.node_is_scalar(v):
location = jsoncfg.node_location(v)
line = location.lin... | c5288cc726d103667e5f51055bc4e8cd4a90816e | 9,570 |
def score_game(game_core):
"""Запускаем игру 1000 раз, чтобы узнать, как быстро игра угадывает число"""
count_ls = []
np.random.seed(1) # фиксируем RANDOM SEED, чтобы ваш эксперимент был воспроизводим!
random_array = np.random.randint(1, 101, 1000)
for number in random_array:
count_ls.appen... | 74a8c4b44ff2caec31f38f136c3fc2336909759f | 9,571 |
def add_plot(
lon, lat, kind=None, props=None, ax=None, break_on_change=False, transform=identity
):
"""Add a plot with different props for different 'kind' values to an existing map
Parameters
----------
lon : sequence of float
lat : sequence of float
kind : sequence of hashable, optional
... | c5d6b5234fe560e9d954d4ea8d0a7aef0e810f89 | 9,572 |
def can_review_faults(user):
"""
users can review faults if one of the the following applies:
a) No fault review groups exist and they have can_review permissions
b) Fault review groups exist, they are a member of one, and they have
review permissions
"""
can_review = user.h... | c66f022b6f52144d8e9fde6865f0a8a263819813 | 9,573 |
import requests
def create_freshservice_object(obj_type, data):
"""Use the Freshservice v2 API to create an object.
Accepts an object name (string) and a dict of key values.
"""
url = '{}/{}'.format(settings.FRESHSERVICE_ENDPOINT, obj_type)
resp = requests.post(url, auth=FRESHSERVICE_AUTH, json=da... | 597348b744d6193beb12dcf2a3a4958808f09d24 | 9,574 |
def print_begin(*args, sep=' ', end='\n', file=None, ret_value='') -> str:
"""Print the function name and start."""
print(_prefix('begin'), *args, sep=sep, end=end, file=file, flush=True)
return ret_value | 8e9ac418d161a0d2b5b7c0c9de7b81da42ea5017 | 9,575 |
def scale_bounding_box(bounding_box,scale):
"""Scales bounding box coords (in dict from {x1,y1,x2,y2}) by x and y given by sclae in dict form {x,y}"""
scaled_bounding_box = {
"x1" : int(round(bounding_box["x1"]*scale["x"]))
,"y1" : int(round(bounding_box["y1"]*scale["y"]))
,"x2" : int(ro... | 8aa374537ed2ae3ae2324bd8a4819e981f281b71 | 9,576 |
import click
def is_command(obj) -> bool:
"""
Return whether ``obj`` is a click command.
:param obj:
"""
return isinstance(obj, click.Command) | 8159aea42baca70b3218a0b82e2f4dc3f34278aa | 9,577 |
def GetContigs(orthologs):
"""get map of contigs to orthologs.
An ortholog can be part of only one contig, but the same ortholog_id can
be part of several contigs.
"""
contigs = {}
for id, oo in orthologs.items():
for o in oo:
if o.contig not in contigs:
con... | 0c449a31e60f1a149317de815d630c4d8a817ca1 | 9,578 |
import logging
import json
def _save_training_results(
mltk_model:MltkModel,
keras_model:KerasModel,
training_history,
logger: logging.Logger,
show:bool = False
) -> TrainingResults:
"""Save the training history as .json and .png"""
results = TrainingResults(mltk_model, keras_model, tra... | fbc8cdb44dcada27df4c47dfdc394dc1900eeb9f | 9,579 |
def set_backwards_pass(op, backwards):
"""
Returns new operation which behaves like `op` in the forward pass but
like `backwards` in the backwards pass.
"""
return backwards + tf.stop_gradient(op - backwards) | 13287ac73c52ac01808c41c81ba5311bc3f49b91 | 9,580 |
def remove_hydrogens(list_of_lines):
"""
Removes hydrogen from the pdb file.
To add back the hydrogens, run the reduce program on the file.
"""
return (line for line in list_of_lines if line['element']!=" H") | 164ac79171cf6b3632fe7909ace91ffe75192b61 | 9,581 |
def crash_random_instance(org: str, space: str, appname: str, configuration: Configuration, count: int = 1):
"""
Crash one or more random application instances.
:param org: String; Cloud Foundry organization containing the application.
:param space: String; Cloud Foundry space containing the application... | 652ab95038d405b6a193809804aae7f3bc15978f | 9,582 |
def spc_dict_from_spc_info(spc_info: dict, resonance: bool = True) -> dict:
"""
Generate a species dictionary from species info.
Args:
spc_info (dict): Species info contains the label and species geom info.
resonance (bool): Whether generate resonance geom in the species dictionary.
Re... | 0a291f2fd50134b1c1259adc36b5637e30e21118 | 9,583 |
import torch
def label_smooth_loss(log_prob, label, confidence=0.9):
"""
:param log_prob: log probability
:param label: one hot encoded
:param confidence: we replace one (in the one hot) with confidence. 0 <= confidence <= 1.
:return:
"""
N = log_prob.size(0)
C = log_prob.size(1)
s... | f1164d1a41d2c275ae4e406e2a46a0d50a2d240d | 9,584 |
def update(self, using=None, **kwargs):
"""
Updates specified attributes on the current instance.
"""
assert self.pk, "Cannot update an instance that has not yet been created."
using = using or router.db_for_write(self.__class__, instance=self)
for field in self._meta.fields:
if getatt... | b3400f43c0a744de17225ee6c029fc41465b784d | 9,585 |
def differential_privacy_with_risk( dfg_freq, dfg_time, delta, precision, aggregate_type=AggregateType.SUM):
"""
This method adds the differential privacy to the DFG of both time and frequencies.
* It calculates the epsilon using the guessing advantage technique.
* It adds laplace noise to the D... | a85035b8786bb6bf9a5cc0af88433a490faac77f | 9,586 |
from typing import Iterable
from typing import Counter
def get_all_values(string: str) -> Iterable[int]:
"""Return all kinds of candidates, with ordering: Dec, Hex, Oct, Bin."""
if string.startswith('0x'):
return filter(bool, [parse_hex(string[2:])]) # type: ignore[list-item]
if string.startswith... | d9e12290339cbf31dc572c9e3d49ec503949250d | 9,587 |
def svn_auth_get_simple_provider(*args):
"""svn_auth_get_simple_provider(apr_pool_t pool)"""
return _core.svn_auth_get_simple_provider(*args) | e91c2198f5ee214fb1db9e8969711a806caf19c6 | 9,588 |
def preferred_language():
""" It just returns first language from acceptable
"""
return acceptable_languages()[0] | 6e5c2b069f84c5a6601b579616858457598f2cf4 | 9,589 |
def get_frequencies(trial = 1):
"""
get frequency lists
"""
if trial =="run_fast_publish":
lb_targ, ub_targ, obs_hz = 340, 350, 10
elif trial == 1:
lb_targ, ub_targ, obs_hz = 210, 560, int(320 / 2)
elif trial == 2:
lb_targ, ub_targ, obs_hz = 340, 640, 280
elif trial == 3:
lb_... | e6c7f33865ffd76532a19426f0748d4dd22e37f8 | 9,590 |
from sys import path
def load_csv(file_path: str = None, clean: bool = True) -> pd.DataFrame:
"""Load the dataset CSV file.
Args:
file_path (str, optional): Path to CSV file. Can be omitted, to load the default dataset. Defaults to None.
drop (list[str], optional): Optionally supply a list of... | 8afa250f4d91b349193682b5bb7bd9c8b1d4eec4 | 9,591 |
import re
def parse_field_pubblicazione(field):
"""
Extracts year, place and publisher from the field `pubblicazione` by applying a cascade of regexps.
"""
exp2 = r'^(?P<place>\D+)(?:\s?\W\s?)(?P<publisher>.*?)\D{1}?(?P<year>\d+)?$'
exp1 = r'^(?P<place>.*?)(?::)(?P<publisher>.*?)\D{1}?(?P<year>\d+)?$'
exp3 = r'... | 91aee4dabf62b3ec5bccff2a07d664312226448c | 9,592 |
def test_api_calendar():
"""Return a test calendar object used in API responses."""
return TEST_API_CALENDAR | 1c73e63bf19cef92dbbe328825c2ae4e867c1e84 | 9,593 |
def apply_custom_colormap(image_gray, cmap=plt.get_cmap("seismic")):
"""
Implementation of applyColorMap in OpenCV using colormaps in Matplotlib.
"""
assert image_gray.dtype == np.uint8, "must be np.uint8 image"
if image_gray.ndim == 3:
image_gray = image_gray.squeeze(-1)
# Initialize ... | e2f3c9a8900f47c0e7183f4ebe72f41a7f6d26b9 | 9,594 |
from typing import Callable
def _cond_with_per_branch_args(pred,
true_operand, true_fun: Callable,
false_operand, false_fun: Callable):
"""Conditionally apply ``true_fun`` or ``false_fun``.
Has equivalent semantics to this Python implementation::
... | e942124beafebb69fed80e3175164a34f088cb9e | 9,595 |
import urllib
def msgSet(key, notUsed, queryString, body):
"""no treatment on the body (we send exactly the body like we received it)"""
dict = urllib.parse.parse_qs(body.decode('utf-8'))
#sendSMS.writeRawMsg(body)
user = dict['user'][0]
print(dict)
sendSMS.writeMsgUser(dict['msg'][0], user)
... | b67663f516f54af9a7dbbece67933ee1d04ee7a2 | 9,596 |
import re
def _strip_build_number(api_version):
"""Removes the build number component from a full api version string."""
match = re.match(r"^([A-Z]+-)?([0-9]+)(\.[0-9]+){2}$", api_version)
if match:
return api_version[:match.start(3)]
# if there aren't exactly 3 version number components, just leave it un... | 20d8023281f05dfcb8c9fdd021b77796c72e1001 | 9,597 |
def get_me():
"""サインインしている自分自身の情報を取得"""
jia_user_id = get_user_id_from_session()
return {"jia_user_id": jia_user_id} | c31f6a1a8c794e4a2aa70779f9c8b2559baccd84 | 9,598 |
def dec_file(name, out=None, **kwargs):
"""
This is a helper function to decrypt a file and return its contents.
You can provide an optional output file using `out`
`name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc.
CLI Examples:
.. code-bloc... | 3ff74b9300fa8b441a22daf65d546f329e414447 | 9,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.