content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def gaussian_blur(img, kernel_size=5):
"""Applies a Gaussian Noise kernel, blurring the original image"""
return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0) | 60,600 |
def characterize(q=1,e=1,apv=1,aae=1,afp=1,ame=1,ahk="string",mhk="string",aab=1,cpp=1,ef="string",fk="string",nm="string",phf=1,pnp=1,pos="string",sk="string",sp="string",typ="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/characterize.html
------------------------------... | 60,601 |
def write_model_inputs(
scenario_directory, scenario_id, subscenarios, subproblem, stage, conn
):
"""
Get inputs from database and write out the model input
projects.tab file (to be precise, amend it).
:param scenario_directory: string, the scenario directory
:param subscenarios: SubScenarios ob... | 60,602 |
def convolve_sep2(data, hx, hy, res_g=None, sub_blocks=None):
"""convolves 2d data with kernel h = outer(hx,hy)
boundary conditions are clamping to edge.
data is either np array or a gpu buffer (OCLArray)
"""
if isinstance(data, np.ndarray):
data = np.ascontiguousarray(data)
if s... | 60,603 |
def test_gradients():
"""Test getting the default gradients property."""
value = c.gradients
assert_equal(value, "no_gradients") | 60,604 |
def print_log(info_type="", title="", info=""):
"""
:param info_type: 日志的等级
:param title: 日志的标题
:param info: 日志的信息
:return:
"""
if not os.path.exists(get_file_path("logs")):
os.mkdir(get_file_path("logs/"))
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
log = now ... | 60,605 |
def gradebook_bulk_management_enabled(course_key):
"""
Returns whether bulk management features should be specially enabled for a given course.
"""
return waffle_flags()[BULK_MANAGEMENT].is_enabled(course_key) | 60,606 |
def distclean_dir(dirname):
"""
Distclean function called in the particular case when::
top == out
:param dirname: absolute path of the folder to clean
:type dirname: string
"""
for (root, dirs, files) in os.walk(dirname):
for f in files:
if _can_distclean(f):
fname = os.path.join(root, f)
try:
... | 60,607 |
def bboxes_filter():
"""
"""
def _augment(
image,
bboxes,
classes=None
):
return image, bboxes, classes
return _augment | 60,608 |
def kl_loss_var(prior_mu, log_var_prior, post_mu, log_var_post):
"""
Analytical KLD for two gaussians, taking in log_variance instead of scale ( given variance=scale**2) for more stable gradients
For version using scale see https://github.com/pytorch/pytorch/blob/master/torch/distributions/kl.py#L398
"... | 60,609 |
def test_pid_owa1():
"""
Test idep on a generic distribution.
"""
d = bivariates['pnt. unq.']
pid = PID_SKAR_owa(d, ((0,), (1,)), (2,))
assert pid[((0,), (1,))] == pytest.approx(0.0, abs=1e-4)
assert pid[((0,),)] == pytest.approx(0.5, abs=1e-4)
assert pid[((1,),)] == pytest.approx(0.5, a... | 60,610 |
def p__shift_op_arith_exprs(p):
"""_shift_op_arith_exprs : LEFTSHIFT arith_expr
| RIGHTSHIFT arith_expr
| _shift_op_arith_exprs LEFTSHIFT arith_expr
| _shift_op_arith_exprs RIGHTSHIFT arith_expr"""
if len(p) == 3:
p[0... | 60,611 |
def get_matching_s3_keys_as_set(bucketname, suffix="") -> set:
"""
Generate the keys in an S3 bucket as set.
:param bucket: Name of the S3 bucket.
:param prefix: Only fetch keys that start with this prefix (optional).
"""
result = set()
for obj in get_matching_s3_objects(bucketname):
... | 60,612 |
def write_model_to_file(model: str, file_path: str = "model.py") -> str:
"""Write the Pydantic Model string to a Python file.
Args:
model: The Pydantic Model string.
file_path: The path must include the .py file extension.
* The file_path is relative to the Workspace Root.
Returns:
... | 60,613 |
def readSite(dir_path, file_name):
""" Read a CSS3 type .site file.
More info: ftp://ftp.pmel.noaa.gov/newport/lau/tphase/data/css_wfdisc.pdf
Arguments:
dir_path: [str] Path to the directory where the .site file is located.
file_name: [str] Name of the .site file.
"""
site_list ... | 60,614 |
def scaled_up_roi(roi, scale: int, shape=None):
"""
Compute ROI for a scaled up image.
Given a crop region in the original image compute equivalent crop in the upsampled image.
:param roi: ROI in the original image
:param scale: integer scale to get scaled up image
:return: ROI in the scaled u... | 60,615 |
def get_rotation(tracker: TrackerComponent):
"""Returns the Euler rotation of the tracker."""
# Data is [0]=side-side [1]=flat [2]=forward-back
if tracker.is_hardware:
torso_state = tracker.get_state('torso')
return torso_state.rot_euler
return (0, 0, 0) | 60,616 |
def lowpass_filtering_in_frequency_domain(
image_grad: torch.Tensor, lowpass: torch.Tensor
) -> torch.Tensor:
"""Applies lowpass filtering in the frequency domain as descibed in Walker
et al. 2019.
Args:
grad (torch.Tensor): gradient
lowpass (torch.Tensor): losspass tensor (constant)
... | 60,617 |
def del_feat(
example,
name,
):
"""Delete feature if present."""
name = _get_field_name(name)
if name and name in example.features.feature:
del example.features.feature[name] | 60,618 |
def review_detection_html(ibs, image_uuid, result_list, callback_url, callback_method='POST', include_jquery=False):
"""
Returns the detection review interface for a particular image UUID and a list of
results for that image.
Args:
image_uuid (UUID): the UUID of the image you want to review det... | 60,619 |
def traverse_conversations(driver, year=None):
"""
Remove all conversations within a specified range
"""
driver.get("https://mobile.facebook.com/messages/?pageNum=1&selectable&see_older_newer=1")
convos = get_conversations(driver)
with archiver("conversations") as archive_convo:
for c... | 60,620 |
def mask_label_image(labels: np.ndarray, bg_mask: np.ndarray, bg_label: int = 0):
"""
Mask an input label image and rearrange the label numbers so that
they form the continuous range [0, numlabel].
Note that there is not relabelling of the components, just a
renumbering.
Args:
:param labe... | 60,621 |
def _check_col_length(datasets):
"""
Ensures the length of all data columns are equal within each
dataset.
Parameters
----------
datasets: dict[]
List of datasets to validate.
Raises
------
UnevenColumnError
If the columns do not equal each other.
"""
for da... | 60,622 |
def install_mysql():
"""Install mysql"""
# First, setup root password
sudo('apt-get install -y debconf-utils')
debconf_defaults = [
"mysql-server-5.5 mysql-server/root_password_again password %s" % (config.ADMIN_PASSWORD,),
"mysql-server-5.5 mysql-server/root_password password %s" % (c... | 60,623 |
def compute_accuracy(
x: Tensor, y: Tensor, m: int, nx: int, c1: int, w: Tensor, b: Tensor
) -> float:
"""Compute accuracy using the given parameters and data.
Args:
x (Tensor): The input tensor (MNIST images)
y (Tensor): The output tensor (a column vector of zeros and ones)
m (int)... | 60,624 |
def modal(item_id):
"""
Return the information of the specified 'item_id'.
This is so that users can open the correct modal item through AJAX
"""
return jsonify({
"id": item_id,
"name": mysqlcommands.get_item(item_id)[1]
}) | 60,625 |
def get_download_url(data_product_uri):
"""(Deprecated) Get URL for downloading data product identified by data_product_uri."""
warnings.warn("Use user_storage.get_download_url instead.", DeprecationWarning)
return (reverse("django_airavata_api:download_file") + "?" +
urlencode({"data-product-ur... | 60,626 |
def get_remote_version_string():
"""
Get the current cvd string from the clamav DNS TXT entry
"""
resolver = Resolver()
resolver.timeout = 5
nameserver = CVDUPDATE_NAMESERVER
record = str(resolver.resolve(CVDUPDATE_NAMESERVER, "TXT").response.answer[0])
versions = re.search('"(.*)"', ... | 60,627 |
def lit(val):
"""Accept a single item and return the given value."""
return lambda seq: ([val], seq[1:], Status.succeed(where='lit')) | 60,628 |
def build_parser(args):
""" This method allows us to test the args.
>>> args = build_parser(['--verbose'])
>>> print(args.verbose))
True
"""
parser = argparse.ArgumentParser(usage='$ python logger.py',
description='Get the latest MTA elevator ... | 60,629 |
def average(data, axis, n):
"""
Averages data along the given axis by combining n adjacent values.
:param data: Data to average along a given axis.
:type data: numpy array
:param axis: Axis along which to average.
:type axis: int
:param n: Factor by which to average.
:type n: int
... | 60,630 |
def test_standard_levels():
"""
Проверяем, что уровни логирования из стандартной схемы устанавливаются.
"""
config.standard_levels()
assert Levels.get('DEBUG') == 10
assert Levels.get('INFO') == 20
assert Levels.get('WARNING') == 30
assert Levels.get('ERROR') == 40
assert Levels.get(... | 60,631 |
def _left_operator(func):
"""Function decorator to treat a method as the left operator."""
def inner(self, other):
"""Decorator wrapper."""
left = self.value
if isinstance(other, NumericType):
right = other.value
else:
right = other
return to_aiid... | 60,632 |
def normalize_data_values(type_string: TypeStr, data_value: Any) -> Any:
"""Decodes utf-8 bytes to strings for abi string values.
eth-abi v1 returns utf-8 bytes for string values.
This can be removed once eth-abi v2 is required.
"""
_type = parse_type_string(type_string)
if _type.base == "strin... | 60,633 |
def StringArrayToVideo(string_array):
"""Converts a N length JPEG encoded string array to NCHW video.
TODO: Allow partial decode (only some frames)
"""
nframes = string_array.shape[0]
frames = [StringArrayElementToFrame(string_array, i) for i in range(nframes)]
video = np.transpose(np.stack(fram... | 60,634 |
def update_bpt(*args):
"""update_bpt(bpt_t bpt) -> bool"""
return _idaapi.update_bpt(*args) | 60,635 |
def test_construction():
"""Simplest test that we can make a SUPERCELL object"""
instance = supercell_step.Supercell()
assert (
str(type(instance)) == "<class 'supercell_step.supercell.Supercell'>"
) | 60,636 |
def test_get_constructor_args_no_args() -> None:
""" Test get_constructor_args() on no arguments """
contract_manager = ContractManager(contracts_precompiled_path())
deploy_info: Dict = {"contracts": {contract_name: {"constructor_arguments": []}}}
assert get_constructor_args(deploy_info, contract_name, ... | 60,637 |
def generate_test_data():
"""
生成测试样本数据,来自函数y=sin(2 * pi * x)
:return: 生成的测试数据集的X向量和Y向量
"""
test_X = np.linspace(0, 1, 4 * data_number)
test_Y = np.sin(2 * np.pi * test_X)
return test_X, test_Y | 60,638 |
def test_create_slot(slotter_obj):
""" Test slotter slot creation """
with pytest.raises(SlotterException):
slot_obj = slotter_obj.create_slot(100, 10)
with pytest.raises(SlotterException):
slot_obj = slotter_obj.create_slot(1, 1)
slot_obj = slotter_obj.create_slot(100, 200)
assert slot_obj.start ==... | 60,639 |
def get_cfg_rabbitMQ(f:str)->Dict:
"""
Check if the 'rabbitMQ' config file is valid and returns the values
:param f: path to the cfg file
:return: params
"""
if path.isfile(f):
with open(f, 'r') as cfg:
par = {k.lower():v for k,v in load(cfg).items()}
if "address"... | 60,640 |
def usaf_station_to_lat_lng(station):
"""Return the latitude and longitude coordinates of the given USAF station.
Parameters
----------
station : str
String representing a USAF Weather station ID
Returns
-------
lat_lng : tuple of float
Latitude and longitude coordinates.
... | 60,641 |
def generate_kwargs(gt, m_vir_thresh, SSPs_in=None, SSP_kwargs={}, **extra_kwargs):
"""
Generate kwargs for a GAMMA run.
Example usage:
## Generate tree and SSP input to GAMMA
gt = caga.gamma_tree.load("my_gamma_tree.npy")
mvir_thresh = 1e7
SSPs_in = caga.precompute_ssps... | 60,642 |
def is_valid_attr(dicts, key, minsize=None, maxsize=None, regex=None, instance=None, required=True):
"""Valida o atributo passado
@todo: arrumar doc
@param dicts: Dicionario de dados.
@param key: key do atributo
@param minsize: Min size of the value to be validated.
@param maxsize: Max size o... | 60,643 |
def increase_vectors(vectors):
"""accelerate so that pieces move faster in earlier frames"""
new_vecs = []
for vec in vectors:
new_vecs.append((vec[0]*VEC_GROWTH, vec[1]*VEC_GROWTH))
return new_vecs | 60,644 |
def test_list_int_length_1_nistxml_sv_iv_list_int_length_2_2(mode, save_output, output_format):
"""
Type list/int is restricted by facet length with value 6.
"""
assert_bindings(
schema="nistData/list/int/Schema+Instance/NISTSchema-SV-IV-list-int-length-2.xsd",
instance="nistData/list/in... | 60,645 |
def Validate(ciffile,dic = "", diclist=[],mergemode="replace",isdic=False):
"""Validate the `ciffile` conforms to the definitions in `CifDic` object `dic`, or if `dic` is missing,
to the results of merging the `CifDic` objects in `diclist` according to `mergemode`. Flag
`isdic` indicates that `ciffile` is ... | 60,646 |
def tapis_client(x_tapis_token: str = Depends(tapis_token)) -> Tapis:
"""Returns a user Tapis client for the provided token"""
try:
client = _client(x_tapis_token)
except BaseTapyException as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="... | 60,647 |
def default_exchange():
"""Return a default :class:`kombu.Exchange` created from configuration.
Scope: function
This fixture offers a default :class:`kombu.Exchange`.
"""
return Exchange("test-exchange", type="direct") | 60,648 |
def to_geo(values):
"""Convert values to GeoArray
Parameters
----------
values : WKT, GeoJSON or Esri JSON in a list
Returns
-------
addresses : GeoArray
Examples
--------
Parse strings
>>> to_geo(['{"x" : -118.15, "y" : 33.80, "spatialReference" : {"wkid" : 4326}}'])
... | 60,649 |
def transpose(x, amount):
"""
transpose directly alters the Notes of the supplied structure.
Each Note's pitch number has amount added to it.
:param x:
:param amount:
:return:
"""
def f(xNote): xNote.pitch = xNote.pitch+amount
mMap(f, x) | 60,650 |
def fire_bullet(bulletx, bullety):
"""this function blit the image of bullet"""
global bullet_state
bullet_state = "fire"
window.blit(bullet_img, (bulletx, bullety)) | 60,651 |
def build(name, ask=True, **kwargs):
"""
Build the malicious mote to its target hardware.
:param name: experiment name (or absolute path to experiment)
:param ask: ask confirmation
:param path: expanded path of the experiment (dynamically filled in through 'command' decorator with 'expand')
:pa... | 60,652 |
def cor(y, z):
"""Compute Pearson's correlation coefficient."""
return np.corrcoef(y, z)[0, 1] | 60,653 |
def ldot(u, v, keepdim=False):
"""Lorentzian scalar product"""
uv = u * v
uv.narrow(-1, 0, 1).mul_(-1)
return torch.sum(uv, dim=-1, keepdim=keepdim) | 60,654 |
def print_qa(questions, answers_gt, answers_gt_original, answers_pred, era, similarity=dirac, path=''):
"""
In:
questions - list of questions
answers_gt - list of answers (after modifications like truncation)
answers_gt_original - list of answers (before modifications)
answers_pr... | 60,655 |
def thumbiconurl(public_path):
"""Get the URL of an icon for filename.
"""
return mimetypeurl(mimetype(public_path)) | 60,656 |
def test_pushing(reference_1, numbers_1, reference_2, numbers_2):
"""
Проверка добавления элементов
"""
s = MovingSum(window=4)
for ref, number in zip(reference_1, numbers_1):
s.push(number)
assert approx(s.sum) == ref
s.restore()
for ref, number in zip(reference_2, number... | 60,657 |
def test_depends(func):
"""Decorator to prevent a test being executed in individual mode"""
def invalid(self, test):
if self.test_individual:
test.description = "Invalid"
return test.DISABLED("This test cannot be performed individually")
else:
return func(self... | 60,658 |
def testItemChangeRegression():
"""Make sure PyQt5 handles QGraphicsItem.itemChange correctly
as there was a regression in PyQt5 v 5.6 that was fixed in v 5.7
"""
a = MyRectItemNOIC()
b = MyRectItem(a)
item_group = MyItemGroup()
assert b.parentItem() is a
assert a.childItems()[0] is b
... | 60,659 |
def orient_y_to_child(joint, invert=False):
"""
Function that orients given joint to its child (points Y axis of joint to its child)
:param joint: str
:param invert: bool
"""
aim_axis = [0, 1, 0] if not invert else [0, -1, 0]
up_axis = [0, 0, 1] if not invert else [0, 0, -1]
children = ... | 60,660 |
def codec_set_threads(codec, num_threads):
"""
Allocates worker threads for the compressor/decompressor.
This function Wraps the openjp2 library function opj_codec_set_threads.
Parameters
----------
codec
Decompressor handler
num_threads : int
Number of threads.
Raises... | 60,661 |
def load(
phono3py_yaml=None, # phono3py.yaml-like must be the first argument.
supercell_matrix=None,
primitive_matrix=None,
phonon_supercell_matrix=None,
is_nac=True,
calculator=None,
unitcell=None,
supercell=None,
nac_params=None,
unitcell_filename=None,
supercell_filename... | 60,662 |
def pluralize(
*, with_quantity: bool = True, with_indicative: bool = False, **word
) -> str:
"""Pluralize a single kwarg's name depending on the value.
``with_indicative`` must be used with ``with_quantity``.
Example
-------
>>> pluralize(object=2)
"2 objects"
>>> pluralize(object=1)... | 60,663 |
def move_bounds(box, ovl_box, padding=0, axis=None):
"""
given two boxes, return the x and y deltas needed to move the first box to avoid the second.
for simplicity, we chose only one axis, whichever is shorter. Also, only allow positive moves.
can choose axis with axis='y' or axis='x'
""... | 60,664 |
def ensure_f(func: Function) -> F:
"""wrap the given function into a F instance"""
if not isinstance(func, F):
return F(func)
return func | 60,665 |
def compiler_call(executable):
""" A predicate to decide the entry is a compiler call or not. """
compilers = [
re.compile(r'^([^/]*/)*([^-]*-)*c(c|\+\+)$'),
re.compile(r'^([^/]*/)*([^-]*-)*g(cc|\+\+)(-\d+(\.\d+){0,2})?$'),
re.compile(r'^([^/]*/)*([^-]*-)*clang(\+\+)?(-\d+(\.\d+){0,2})?$... | 60,666 |
def debye(img, fig, center=None):
"""Draw the Debye-Scherrer rings, calculates diameter and center of each
and returns the mean center for mirroring
:param fig: a dictionary with keyword arguments for ``sf.show``
or a matplotlib figure
.. note:: If you use ``sf.show`` the figure must be cr... | 60,667 |
def test_mother_is_still_young(set_up_mother):
"""
Should check if mother should be replaced
"""
# Given:
bee_mother = BeeMother.objects.all()
# When:
for mother in bee_mother:
BeeMotherService.set_mother_age(mother)
BeeMotherService.set_mother_active(mother)
# Then:
... | 60,668 |
def month_and_year(m=None, y=None):
"""Creates a string from month and year data, if available."""
if y is None:
return "present"
if m is None:
return str(y)
m = month_to_int(m)
return "{0} {1}".format(SHORT_MONTH_NAMES[m], y) | 60,669 |
def to_bool(a):
"""
a: a str or bool object
if a is string
'true', 't', 'yes', 'y', '1', 'ok' ==> True
'false', 'f', 'no', 'n', '0' ==> False
"""
if isinstance(a, bool):
return a
elif a is None:
return False
elif isinstance(a, (int, float)):
return b... | 60,670 |
def find_nova_host(address, config):
"""See if a nova instance has the supplied address."""
nova = client.Client(config['username'],
config['password'],
config['tenant_id'],
config['authurl'],
region_name=config[... | 60,671 |
def test_youyoun():
"""
Run `python -m pytest ./day-10/part-1/youyoun.py` to test the submission.
"""
assert (
YouyounSubmission().run(
"""[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{... | 60,672 |
def camera_matrix(fov=const.CAMERA_FOV, resolution=const.CAMERA_RESOLUTION, alpha=0):
"""Returns camera matrix [1] from Field-of-View, skew, and offset.
Parameters
----------
fov : float, Iterable
Field-of-View angle (degrees), if type is Iterable it will be interpreted as (fov_x, fov_y)
re... | 60,673 |
def LoadUserAgents(uafile):
"""
uafile : string
path to text file of user agents, one per line
"""
uas = []
with open(uafile, 'rb') as uaf:
for ua in uaf.readlines():
if ua:
uas.append(ua.strip()[1:-1-1])
random.shuffle(uas)
return uas | 60,674 |
def comment_threads_list(key, part, allThreadsRelatedToChannelId=None,
channelId=None, id=None, videoId=None,
maxResults=None, moderationStatus=None, order=None,
pageToken=None, searchTerms=None, textFormat=None):
"""Returns a list of commen... | 60,675 |
def generate_csv_files():
"""Generate temporary csv files"""
print("[info] Generating data")
# Make temporary directory
if not os.path.exists('r_data'): os.mkdir('r_data')
# Begin experiments
for name in DATA_SETS:
X, y = load_data(name)
# For consistency, standardize fe... | 60,676 |
def gaussianBlur(img):
"""Applies gaussian filter to a grayscale image"""
return cv2.GaussianBlur(img, (5, 5), 0) | 60,677 |
def fix_month(bib_str: str) -> str:
"""Fixes the string formatting in a bibtex entry"""
return (
bib_str.replace("{Jan}", "jan")
.replace("{jan}", "jan")
.replace("{Feb}", "feb")
.replace("{feb}", "feb")
.replace("{Mar}", "mar")
.replace("{mar}", "mar")
.r... | 60,678 |
def multipart_form_message(media, form_data={}):
"""Return a MIMEMultipart message to upload encoded media via an HTTP form POST request.
Args:
media: a list of (encoded_data, filename) tuples.
form_data: dict of name, value form fields.
"""
message = MIMEMultipart('form-data', None)
if form_data:
... | 60,679 |
def make_well2file_dict(data):
"""Create a dictionary mapping wells to image files.
Parameters
----------
data : pandas data frame
A data frame from feature computation.
Returns
-------
well2file : dictionary, {(int, string): string}
A dictionary keyed by a (plate, well) tu... | 60,680 |
def assert_none(source):
"""
assert None
"""
if source is not None:
assert False, 'expect source is None, but now is {0}'.format(source) | 60,681 |
def create_balloon(
x: units.Distance = units.Distance(m=0.0),
y: units.Distance = units.Distance(m=0.0),
center_lat: float = 0.0,
center_lng: float = 0.0,
pressure: float = 7_000.0,
power_percent: float = 0.95,
date_time: Optional[dt.datetime] = None,
time_elapsed: Optional[dt.timedelta... | 60,682 |
def _is_attribute_file(filepath):
"""
Check, if ``filepath`` points to a valid udev attribute filename.
Implementation is stolen from udev source code, ``print_all_attributes``
in ``udev/udevadm-info.c``. It excludes hidden files (starting with a
dot), the special files ``dev`` and ``uevent`` and ... | 60,683 |
def calculate_reference_sample(experiment: FCSExperiment,
exclude_samples: list) -> str:
"""
Given an FCS Experiment with multiple FCS files, calculate the optimal reference file.
This is performed as described in Li et al paper (https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5... | 60,684 |
def create_joint_at_pivot():
"""
If there is a valid selection then get the world space
position of the selection's pivot and create a joint to that
position.
"""
import pymel.core as pm # pylint: disable=import-error
meshes = pm.cmds.ls(sl=True)
# checks if there are selec... | 60,685 |
def create_plots(effects, true):
"""The function creates the figures that illustrates the behavior of each estimator of the ATE
when the correlation structure changes from 0 to 1."""
# Determine the title for each strategy plot
for strategy in ['grmpy', 'ols']:
if strategy == 'ols':
... | 60,686 |
def get_visibles(photos, user):
"""
get only photos visible for user
"""
return photos.filter(
Q(owner=user) |
Q(shared=user)
) | 60,687 |
async def changeTeam(team, member):
"""enleve tous les rôles d'un utilisateur sauf '@everyone' et '@modo' puis place le member dans la team appropriée
return 1 si le changement est effectif 0 sinon"""
team = teamName(team)
assert team
assert isinstance(member, discord.Member)
for role in member... | 60,688 |
def dataqc_spiketest(dat, acc, N=5, L=5, strict_validation=False):
"""
Description:
Data quality control algorithm testing a time series for spikes.
Returns 1 for presumably good data and 0 for data presumed bad.
The time series is divided into windows of len L (an odd integer
... | 60,689 |
def pad(text: str, width: int, align: str = '<', fill: str = ' '):
"""
pad the string with `fill` to length of `width`
:param text: text to pad
:param width: expected length
:param align: left: <, center: ^, right: >
:param fill: char to fill the padding
:return:
"""
assert align in ... | 60,690 |
def coins_to_numpy(game):
"""Game coins info to numpy array
Parameters
----------
game : camel up game
Camel up game class
Returns
-------
array
Numpy array
"""
return np.array(
[(key[0], key[1]["coins"]) for key in [*game.player_dict.items()]],
dty... | 60,691 |
def edit_mode(obj):
"""
Select the object and change to edit mode
:param obj: string, name of object
:return: bpy data object
"""
bpy.ops.object.mode_set(mode='EDIT')
o = select(obj)
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.object.mode_set(mode='EDIT')
return o | 60,692 |
async def test_cli(
aiohttp_client,
otupdate_config,
monkeypatch,
version_file_path,
mock_name_synchronizer,
):
"""
Build an app using dummy versions, then build a test client and return it
"""
app = buildroot.get_app(
name_synchronizer=mock_name_synchronizer,
system_... | 60,693 |
def check_xform(path_to_xform):
"""
Returns an array of warnings if the form is valid.
Throws an exception if it is not
"""
# provide useful error message if java is not installed
if not _java_installed():
raise EnvironmentError("pyxform odk validate dependency: java not found")
#re... | 60,694 |
def slerp(val, low, high):
"""
val, low, high: bs x frames x coordinates
if val == 0 then low
if val == 1 then high
"""
assert low.dim() == 3, low.dim()
assert val.dim() == 3, val.dim()
assert high.dim() == 3, high.dim()
low_norm = low / torch.norm(low, dim=2, keepdim=True)
... | 60,695 |
def canonical_version(versionstr, release_type='python-service'):
"""Given a version string verify it is in the canonical form."""
errors = list(validate_version(versionstr, release_type))
if errors:
raise ValueError(errors[-1])
return versionstr | 60,696 |
def CircAperture(Fin, R, x_shift = 0.0, y_shift = 0.0):
"""
*Inserts a circular aperture in the field.*
:param R: radius of the aperture
:type R: int, float
:param x_shift: shift in x direction (default = 0.0)
:param y_shift: shift in y direction (default = 0.0)
:type x_shift: int, floa... | 60,697 |
def extract_access_token(request):
"""
Get the access token using Authorization Request Header Field method.
Or try getting via GET.
See: http://tools.ietf.org/html/rfc6750#section-2.1
Return a string.
"""
auth_header = request.META.get('HTTP_AUTHORIZATION', '')
if re.compile(r'^[Bb]ea... | 60,698 |
def parse_trap_model(device_trap_models, trap_data):
"""
This function filters out trap_model from unwanted data.
Positional Arguments:
- device_trap_models -- list of all trap models for specific devices
- trap_data -- raw trap data
"""
for trap_model in device_trap_models:
filter... | 60,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.