content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import random
def new_match(request, cmd_args):
"""
Return a slack message with a link to a new match
"""
# Could potentially add arguments to allow game configuration here
serializer = LiveMatchSerializer(data={"config": cmd_args})
if serializer.is_valid():
live_match = serializer.sa... | fe5a1f57a23188eaf000c32623eb5ce4386e4dc0 | 20,902 |
def head(feats, anchors, num_classes):
"""Convert final layer features to bounding box parameters.
Parameters
----------
feats : tensor
Final convolutional layer features.
anchors : array-like
Anchor box widths and heights.
num_classes : int
Number of target classes.
... | d05f47f199d500bb8938396ef9052abfe6815a1f | 20,903 |
def socfaker_azurevmtopology_get():
"""
None
"""
if validate_request(request):
return jsonify(str(socfaker.products.azure.vm.topology)) | c4041c2cb3d124b1ed3a2b124292b669caba3595 | 20,904 |
import json
def read_json_file(filename):
"""Load json object from a file."""
with open(filename, 'r') as f:
content = json.load(f)
return content | b575891ac4b5a5484c9dcf7966e63a7cd9ca748c | 20,905 |
import copy
def createVectorisedTargValObjFunction(functTypeStr:str, averageMethod="mean",catchOverflow=True, errorRetVal=1e30, normToErrorRetVal=False, greaterThanIsOk=False, lessThanIsOk=False, useAbsVals=False,
divideErrorsByNormFactor=None):
""" Creates a comparison function that operators on (iterA,iterB) and r... | 1e9f0da8ce87c40f1dd461fd052a7c9de69ce86f | 20,906 |
def get_nonoverlap_ra_dataset_conf(dataset_conf):
"""extract segments by shifting segment length"""
if dataset_conf["if_rand"]:
info("disabled dataset_conf if_rand")
dataset_conf["if_rand"] = False
if dataset_conf["seg_rand"]:
info("disabled dataset_conf seg_rand")
dataset_co... | 8aba162200d2f020e72a29d9d9c5676792ae0405 | 20,907 |
def _f_model_snaive_wday(a_x, a_date, params, is_mult=False, df_actuals=None):
"""Naive model - takes last valid weekly sample"""
if df_actuals is None:
raise ValueError('model_snaive_wday requires a df_actuals argument')
# df_actuals_model - table with actuals samples,
# adding y_out column w... | f7668b6e73f1e985304198f1996f3374994e10cf | 20,908 |
def union_exprs(La, Lb):
"""
Union two lists of Exprs.
"""
b_strs = set([node.unique_str() for node in Lb])
a_extra_nodes = [node for node in La if node.unique_str() not in b_strs]
return a_extra_nodes + Lb | 2bd634a22b27314f6d03c8e52c0b09f7f4b692db | 20,910 |
def programs_reload():
"""Reload programs from config file
Parameters (default):
- do_create (True)
- do_update (True)
- do_pause (False)
"""
try:
result = dar.reload_programs(**request.args)
except TypeError as e:
log.info("Caught TypeError: %s" % (str(e)))
... | 06beff9b2f67bb7978ddd31ff338accb90d259bf | 20,911 |
import requests
def generate_urls():
"""Gathers clinical trials from clinicaltrials.gov for search term
defined in build_url() function and downloads to specified file format.
"""
api_call = build_url(expr='Cancer', max_rnk=1, fmt='json')
r = requests.get(api_call)
data = r.json()
... | 7de042ff2031d1b49e4fc02535f151d5e1dda913 | 20,912 |
def xyz2luv(xyz, illuminant="D65", observer="2"):
"""XYZ to CIE-Luv color space conversion.
Parameters
----------
xyz : (M, N, [P,] 3) array_like
The 3 or 4 dimensional image in XYZ format. Final dimension denotes
channels.
illuminant : {"A", "D50", "D55", "D65", "D75", "E"}, option... | 194f0e76c35257fb1d87fd58f507cc11da45eab4 | 20,913 |
def today():
"""
Today Page:
Displays all the notifications like the word of the day, news highlights or friends who added you or shared a
note with you
"""
return render_template('main/today.html', username=session['username']) | ada12c04456967bba1e506ca0fe27d3efe252307 | 20,915 |
import re
import itertools
def compile_read_regex(read_tags, file_extension):
"""Generate regular expressions to disern direction in paired-end reads."""
read_regex = [re.compile(r'{}\.{}$'.format(x, y))\
for x, y in itertools.product(read_tags, [file_extension])]
return read_regex | e677b8ff622eb31ea5f77bc662845ba0aef91770 | 20,916 |
def filter(start=None, stop=None, **kwargs):
"""
Get commands with ``start`` <= date < ``stop``. Additional ``key=val`` pairs
can be supplied to further filter the results. Both ``key`` and ``val``
are case insensitive. In addition to the any of the command parameters
such as TLMSID, MSID, SCS, S... | 95471d3a69f7566b7e079e04e38fc21324425e90 | 20,917 |
def _get_energy_at_time(masses, pos, vel, time_idx):
"""
Internal function used to calculate kinetic energy and potential energy at
a give time index using a vectorized direct sum approach. This function is
necessary to facilitate the parallelization of the energy calculation
across multiple CPU cor... | 76c72be399cb31e949024123c635ee76e9f4ab3a | 20,918 |
def get_root_url_for_date(date):
"""
Returns the root URL of the TMCDB web I/F for the given date.
The argument date should be an ISO-8601 date string (YYYY-MM-DD).
The returned URL already contains the date.
"""
year = date[:4]
mm = date[5:7]
hostname = get_host_name()
return "%s/i... | 32a223d672e4878dfb4766ac9fc86a581826701b | 20,919 |
def dummy_annotation_txt_one_segment(tmpdir_factory):
"""Create empty TXT annotations."""
content = ("# MNE-Annotations\n"
"# onset, duration, description\n"
"3.14, 42, AA")
fname = tmpdir_factory.mktemp('data').join('one-annotations.txt')
fname.write(content)
return fn... | 4e127391b3f43fe8db7cceca54c5001697483fc9 | 20,920 |
def article_title_meets_posting_requirements(website, article_title):
"""
Validates that the article title meets all requirements to post the list to Reddit.
The validations below check if:
(1) The article contains a number
(2) The article title doesn't contain certain pre-defined keywords
... | c1a36592eff9144ab2dc9703cfdf669294dac229 | 20,921 |
import json
import csv
def about():
""" returns about page """
counter = json.load(open(r'filter/OXAs_dict/counter.txt'))
ids = [*counter]
r = csv.reader(open(r'Training_data/Training_data_IC.csv'))
df = pd.DataFrame(data=list(r))
svm_table = df.to_html(index=False, header=False)
return re... | 5565fdd2616df38e223fa4e3dbc6d8963fcf285d | 20,922 |
from typing import List
def phys_mem_regions_from_elf(elf: ElfFile, alignment: int) -> List[MemoryRegion]:
"""Determine the physical memory regions for an ELF file with a given
alignment.
The returned region shall be extended (if necessary) so that the start
and end are congruent with the specified a... | 611b5b5d89c999ee5136f98bf5555d9c71e14048 | 20,923 |
def force_float_to_int_in_any_way(x):
"""This force a float to be converted to an int.
Any float is fine. The result is truncated.
Like PHP, if the input float is greater than 2**63, then the result
is 0, even if intmask(int(f)) would return some bits."""
# magic values coming from pypy.rlib.rarith... | 7ad932c213f4c4c3f4195383d87268ba803cc533 | 20,924 |
from typing import Union
def where(condition : pdarray, A : Union[Union[int,float], pdarray],
B : Union[Union[int,float], pdarray]) -> pdarray:
"""
Returns an array with elements chosen from A and B based upon a
conditioning array. As is the case with numpy.where, the return arra... | 26f42d3e45d81108b5fa2cdeed018f509432854e | 20,925 |
def pre_training_configs(m):
"""
Before training the model, configure it
"""
ordering = range(m.n_visible)
np.random.shuffle(ordering)
trainer = Optimization.MomentumSGD(m.nade, m.nade.__getattribute__(m.loss_function))
trainer.set_datasets([m.training_dataset, m.masks_dataset])
trainer... | 9e726f8b9b136d0ee8f8015b533111f30e6447ce | 20,926 |
import torch
def loadClusterModule(pathCheckpoint):
"""
Load CPC Clustering Module from Clustering checkpoint file.
"""
state_dict = torch.load(pathCheckpoint, map_location=torch.device('cpu'))
clusterModule = kMeanCluster(torch.zeros(1, state_dict["n_clusters"], state_dict["dim"]))
clusterMod... | e6e950c651e890a60b356b97266f3198f7e0a07d | 20,928 |
import base64
def bash_inline_create_file(name, contents):
"""
Turns a file into bash command.
Parameters
----------
name : str
File name.
contents : bytes
File contents.
Returns
-------
result : str
The resulting command that creates this file.
"""
... | 6ecabcb9a35dd760d762f3c4b7e1a15502ae5637 | 20,929 |
import html
def rtf_encode(unicode_string):
"""
Converts HTML encoding and Unicode encoding to RTF.
Be sure that autoescaping is off in the template. Autoescaping converts <, >, ", ', &
The unescape function used here is helpful for catching additional escape sequences used for special
characters,... | bd9cc1b8b9d736c4746a381ae6ab547af30452af | 20,930 |
def get_P(A):
"""
Markov matrix.
P = D^{-1}*A
"""
D = get_D(A)
return np.linalg.inv(D).dot(A) | bea5a3f10a5e6f6d592fd6df651ce09f5f4d4939 | 20,931 |
def get_movie_and_zmw_from_name(name):
"""Given a string of pacbio zmw name or read name, return movie and zmw"""
try:
fs = name.strip().split(' ')[0].split('/')
movie, zmw = fs[0], fs[1]
return movie, int(zmw)
except ValueError:
raise ValueError("Read %r is not a PacBio read... | 8dfb5e8d85b9e4a8a5ecfc0115416ce7c23bb6db | 20,932 |
def create_sp_history_copy(sp):
"""
Create a history copy of SP, with end_at value and new pk
return: created service provider object
"""
admins = sp.admins.all()
admin_groups = sp.admin_groups.all()
nameidformat = sp.nameidformat.all()
grant_types = sp.grant_types.all()
response_ty... | 0508a1763c46e7f57c34647af2d5b00c2dd0f9cf | 20,933 |
def onehot(arr, num_classes=None, safe=True):
"""
Function to take in a 1D label array and returns the one hot encoded
transformation.
"""
arr = exactly_1d(arr)
if num_classes is None:
num_classes = np.unique(arr).shape[0]
if safe:
if num_classes != np.unique(arr).shape[0]:
... | ddeba80964712d85a8933c748fc973577a8fe4a5 | 20,934 |
def scale_relative_sea_level_rise_rate(mmyr: float, If: float = 1) -> float:
"""Scale a relative sea level rise rate to model time.
This function scales any relative sea level rise rate (RSLR) (e.g., sea
level rise, subsidence) to a rate appropriate for the model time. This is
helpful, because most dis... | 2150f1e0e9aa5f7f7c0c4c5b1d876676b6556d08 | 20,935 |
def get_covalent1_radius(Z):
"""
Converts array of nuclear charges to array of corresponding valence.
Args:
Z (numpy ndarray): array with nuclear charges
Returns:
numpy ndarray: array of the same size as Z with the valence of the corresponding atom
"""
global _elements
if _elements is None:
_elem... | c655a5253a088379abdf171383ea8a2dedd52aa7 | 20,936 |
from typing import List
def get_bank_sizes(num_constraints: int,
beam_size: int,
candidate_counts: List[int]) -> List[int]:
"""
Evenly distributes the beam across the banks, where each bank is a portion of the beam devoted
to hypotheses having met the same number of c... | 7a515b1e7762d01b7f7a1405a943f03babe26520 | 20,937 |
def ssh_connect(openstack_properties):
"""Create a connection to a server via SSH.
Args:
openstack_properties (dict): OpenStack facts and variables from Ansible
which can be used to manipulate OpenStack objects.
Returns:
def: A factory function object.
"""
connections ... | 03d05c78d8ed516f581f01b4c093b05bc1ddcc1c | 20,938 |
def prepare(args: dict, overwriting: bool):
"""Load config and key file,create output directories and setup log files.
Args:
args (dict): argparser dictionary
Returns:
Path: output directory path
"""
output_dir = make_dir(args, "results_tmp", "activity_formatting", overwriting)
... | 0da7d1e98cd1a518fd8aa33b53204dce8de63fde | 20,939 |
import ast
def parse_data(data):
"""Takes a string from a repr(WSGIRequest) and transliterates it
This is incredibly gross "parsing" code that takes the WSGIRequest
string from an error email and turns it into something that
vaguely resembles the original WSGIRequest so that we can send
it throug... | 63470f1a935ef6218c239f99228eaf7919b9f09c | 20,940 |
from typing import List
def create_slack_context_block(elements: List[SlackBlock]) -> dict:
"""
Creates a "context block" as described in the slack documentation here:
https://api.slack.com/reference/messaging/blocks#context
"""
return {
'type': 'context',
'elements': [element.get_... | c2d4400f910cdc6756ec94bcd14661d76bc3dfa1 | 20,941 |
def sample_bar_report(request):
"""
Demonstrates a basic horizontal bar chart report.
"""
profile = request.get_user_profile()
if not profile.super_admin:
raise PermissionDenied('Only super admins can view this report.')
# Run your custom report logic to build the following lists:
#... | ae4fcf560ca3d1ebac149b6ae3a65ea8f7db2190 | 20,943 |
def _is_ref_path(path_elements):
"""
Determine whether the given object path, expressed as an element list
(see _element_list_to_object_path()), ends with a reference and is
therefore eligible for continuation through the reference. The given
object path is assumed to be "completed" down to a singl... | da8bc8eb7611ce7b5361209873e871f2a4656a03 | 20,944 |
import numpy
def apply_along_axis(func1d, axis, arr, *args, **kwargs):
"""Apply the harmonic analysis to 1-D slices along the given axis."""
arr = dask.array.core.asarray(arr)
# Validate and normalize axis.
arr.shape[axis]
axis = len(arr.shape[:axis])
# Rechunk so that analyze is applied ove... | 09e08b00c9df157e1cf3122f34413e2c4d8e3cb3 | 20,945 |
import pytz
from datetime import datetime
def current_time_utc(conf):
""" Get time in UTC """
UTC = pytz.utc
curr_time = datetime.now(UTC)
return curr_time | e4d4a76cbf04ff059b6913d632d3e2636cfa2b17 | 20,946 |
def CORe50(root=expanduser("~") + "/.avalanche/data/core50/",
scenario="nicv2_391",
run=0,
train_transform=None,
eval_transform=None):
"""
Creates a CL scenario for CORe50.
If the dataset is not present in the computer, this method will
automatically download... | 16e1772d7b9d627fdec34657041570b7f4ccfe49 | 20,947 |
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
res = []
for ele in line:
res.append(ele)
for num in res:
if num == 0:
res = shift(res,res.index(num))
for inde in range(len(res)-1):
if res[inde] == res[inde+1]:
res... | 55418ab717333060455c4f9f41eeafd10e0a9940 | 20,948 |
import PIL
def image_to_bytes(image: "PIL.Image.Image") -> bytes:
"""Convert a PIL Image object to bytes using native compression if possible, otherwise use PNG compression."""
buffer = BytesIO()
format = image.format if image.format in list_image_compression_formats() else "PNG"
image.save(buffer, fo... | aa05f41967dd02dbb544e6d503f555d491d6891e | 20,949 |
def add_transform(transform_type, transform_tag=None, priority=0, status=TransformStatus.New, locking=TransformLocking.Idle,
retries=0, expired_at=None, transform_metadata=None, workprogress_id=None, session=None):
"""
Add a transform.
:param transform_type: Transform type.
:param tra... | ec6bfe98cecf14b80be5c8c08b86c3ee196b4255 | 20,950 |
import joblib
def load_memmap(path):
"""load_memmap方法用于读取共享数据
Parameters
----------
path : str
文件路径
Returns
----------
"""
memmap_data = joblib.load(path, mmap_mode='r+')
return memmap_data | f17120650ecc232be6f4fd8962c8a5a97dd59e1f | 20,951 |
from typing import Tuple
import enum
from typing import Optional
def _classical_routine_on_result(
N: int, t: int, x: int, measurement
) -> Tuple[enum.Enum, Optional[Tuple[int, ...]]]:
"""Try to find factors, given x,N,t and the result of a single quantum measurement.
:param N: number to factorise
:p... | c9a7c9fedfc95cffc766fee0814e43487bb374ad | 20,952 |
def get_rst_cls_file_header(collection_name, class_name):
"""produce the rst content to begin an attribute-level *.rst file"""
# use :doc:`class_name<index>` syntax to create reference back to the index.rst file
title = ":doc:`%s<../index>` %s" % (collection_name.capitalize(), class_name)
return get_rs... | e914ed9d18c2f248e928f2e6482eee6e0461cfd5 | 20,953 |
def is_leap(year):
"""
Simply returns true or false depending on if it's leap or not.
"""
return not year%400 or not (year%4 and year%100) | 5cb40664b2e8aa9aea647a356b63708f00891a2c | 20,954 |
def ForwardDynamics(thetalist, dthetalist, taulist, g, Ftip, Mlist, \
Glist, Slist):
"""Computes forward dynamics in the space frame for an open chain robot
:param thetalist: A list of joint variables
:param dthetalist: A list of joint rates
:param taulist: An n-vector of joint force... | 3b6e23e301db5c81ed6b19109c203f177d2a3f82 | 20,955 |
def union(dataframe1, dataframe2) -> pd.DataFrame:
"""The set union between dataframe1 (S) and dataframe2 (T), i.e. it returns the elements that are both in dataframe1
and dataframe2. Formally S ∩ T = {s|s ∈ S and s ∈ T}.
If duplicates exists in either dataframe they are dropped and a UserWarning is issued... | 8f0f9a86bcb75efdc31615f2e1a9e568c58af3ee | 20,956 |
def get_axis_periodic(self, Nper, is_antiperiod=False):
"""Returns the vector 'axis' taking symmetries into account.
Parameters
----------
self: Data1D
a Data1D object
Nper: int
number of periods
is_antiperiod: bool
return values on a semi period (only for antiperiodic si... | aa9c9b14cbe27b2f3b64ca2a1c3fe606ba921686 | 20,957 |
def knapsack_fractional(weights,values,capacity):
""" takes weights and values of items and capacity of knapsack as input
and returns the maximum profit possible for the given capacity of knapsack
using the fractional knapsack algorithm"""
#initialisaing the value of max_profit variable
max_profit=... | 8cb05c199baf65c24512fa97882085e7bb66a98d | 20,958 |
def invert(values: np.array, inversion: int) -> np.array:
"""Return the specified musical inversion of the values."""
if np.abs(inversion) > (len(values) - 1):
raise ValueError("Inversion out of range")
return np.hstack([values[inversion:], values[:inversion]]).astype(int) | 625d60633efdb44b99c93194f5bdc6dd159df9e7 | 20,959 |
from typing import Any
def engine_factory(database_url: str) -> Engine:
"""Construct database connection pool."""
url = make_url(database_url)
engine_kwargs: dict[str, Any] = {}
if url.host == "localhost":
engine_kwargs = {
**engine_kwargs,
"connect_args": {"connect_tim... | e2eec7c7cfa20426708d02429aee565b070df760 | 20,961 |
import torch
def _shear_x(video: torch.Tensor, factor: float, **kwargs):
"""
Shear the video along the horizontal axis.
Args:
video (torch.Tensor): Video tensor with shape (T, C, H, W).
factor (float): How much to shear along the horizontal axis using the affine
matrix.
""... | e09d539bd8f8481bff3376f7b6dd5a21849fb6cd | 20,962 |
from typing import Optional
from typing import Sequence
def get_smtp_credentials(filters: Optional[Sequence[pulumi.InputType['GetSmtpCredentialsFilterArgs']]] = None,
user_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSmtpCreden... | 3ce0fbd2ce03d072d1b0903018901ef30f360b1f | 20,963 |
def coord(row, col):
""" returns coordinate values of specific cell within Sudoku Puzzle"""
return row*9+col | 14cda1489215a2b36d61ac6eac56c14981290b16 | 20,964 |
def post_authn_parse(request, client_id, endpoint_context, **kwargs):
"""
:param request:
:param client_id:
:param endpoint_context:
:param kwargs:
:return:
"""
if endpoint_context.args["pkce"]["essential"] is True:
if not "code_challenge" in request:
raise ValueErro... | 6e9e00a5d073a57cf0245b2506abfd822b5f6ff5 | 20,965 |
import torch
def token2hot(seq, max_length, n_features):
"""
takes in tokenized sequences and returns 1-hot encoded
[1 2 2] -> [1 0 0 0], [0 1 0 0 ], [0 1 0 0]
"""
N = max_length - len(seq)
x = np.pad(seq, (0, N), 'constant')
x = F.one_hot(torch.tensor(x),num_classes=n_features)
retur... | 8a662703448b4cf8f4e1fddc853436c9677cc664 | 20,967 |
import re
def is_repo_on_known_branch(path):
"""Check if we're on the most recent commit in a well known branch, 'master' or
a version branch."""
remote = find_upstream_remote(None, path)
branches = execute_git(
None,
path,
[
"for-each-ref",
"--format=... | 34f96c625c4864d303be84ec6c78f1c3b45761a0 | 20,968 |
def make_key(ns_sep, namespace, *names):
"""Make a redis namespaced key.
>>> make_key(":", "YOO:HOO", "a", "b", "c") == "YOO:HOO:a:b:c"
True
"""
return ns_sep.join(chain((namespace,), names)) | 2b73b00819f888c31c4b21a7ba21536b98a9ab26 | 20,971 |
from typing import Counter
def directly_follows(logs_traces, all_activs, noise_threshold=0):
"""
Gets the allowed directly-follows relations given the traces of the log
Parameters
-------------
logs_traces
Traces of the log
all_activs
All the activities
noise_threshold
... | 6b0922113f0774eb7ac074ce65fd29b81ecf946f | 20,973 |
def hfc(x, framesize=1024, hopsize=512, fs=44100):
"""
Calculate HFC (High Frequency Content)
Parameters:
inData: ndarray
input signal
framesize: int
framesize
hopsize: int
hopsize
fs: int
samplingrate
Returns:
result: ndarray
... | dc28cfd8376b585bf26d85ceaf12777c0f81c471 | 20,975 |
from functools import reduce
def acronym_buster(message):
"""
Find the first group of words that is in all caps
check if it is in the ACRONYMS dict
if it is, return the first occurrence of the acronym
else return [acronym] is an acronym. I do not like acronyms. Please remove them from your email.
... | 0867462af314be01d68e4764f2d4462f12ec1c1f | 20,976 |
import logging
def get_backup_temp_2():
"""
This is the third way to get the temperature
"""
try:
temp = RFM69.temperature
logging.warning("Got second backup temperature")
return temp
except RuntimeError:
logging.error("RFM69 not connected")
return 2222
... | cc22a21cf319d30330e32cb70ff54b9117be87b6 | 20,977 |
def constructed(function):
"""A decorator function for calling when a class is constructed."""
def store_constructed(class_reference):
"""Store the key map."""
setattr(class_reference, "__deserialize_constructed__", function)
return class_reference
return store_constructed | 29101fe6deb1112b5e69291377a3d8ab12082268 | 20,978 |
def generate_functions(
function,
parameters,
name,
name_func,
tag_dict,
tag_func,
docstring_func,
summarize,
num_passing,
num_failing,
key_combs_limit,
execution_group,
timeout,
):
"""
Generate test cases using the given parameter context, use the name_func
... | 16c8dbabb94e377b034445213a18e379f3bc58ea | 20,979 |
from typing import List
def post_multi_tag_datapoints(timeseries_with_datapoints: List[TimeseriesWithDatapoints], **kwargs):
"""Insert data into multiple timeseries.
Args:
timeseries_with_datapoints (List[v04.dto.TimeseriesWithDatapoints]): The timeseries with data to insert.
Keyword Args:
... | 6bb73c3896fbad250574dfd5c5ea5c74f6059521 | 20,981 |
def get_version(pname: str, url: str) -> str:
"""Extract the package version from the url returned by `get_url`."""
match = search(r"/(\d+\.\d+\.\d+)/(\w+(?:-\w+)?)-(\d+\.\d+\.\d+)\.tar\.gz$", url)
# Assert that the package name matches.
assert match[2] == pname
# As a sanity check, also assert that... | dc51ad64f4c47f35b5e6944754ccf4225829047f | 20,982 |
import numpy
def SmoothMu(trimset, smoothing):
""" Smooth mu or P(mu>thresh). """
Stot = trimset[0]
newmu = trimset[1]
maxflux = Stot.max()
xfine = numpy.exp(numpy.linspace(0, numpy.log(maxflux), 300))
#tck = interpolate.splrep(Stot, newmu, s=1, k=5)
#yfine = interpolate.splev(xfine, tc... | 47dfdcb6b2db607fec65708f03cecaf56b6e3836 | 20,983 |
def spdiags(data, diags, m, n, format=None):
"""
Return a sparse matrix from diagonals.
Parameters
----------
data : array_like
matrix diagonals stored row-wise
diags : diagonals to set
- k = 0 the main diagonal
- k > 0 the k-th upper diagonal
- k < 0 the k... | ba0301389ab8ca2ef85cdf32aca7851464386ff7 | 20,984 |
def precision_with_fixed_recall(y_true, y_pred_proba, fixed_recall):
""" Compute precision with a fixed recall, for class 1. The chosen threshold for this couple precision is also returned.
Parameters
----------
y_true : 1d array-like, or label indicator array / sparse matrix
Ground truth (corr... | 8ff70df3a01a2403735ce68e1158d700b5dd3e6f | 20,987 |
def sample_kollege(user, name='Miguel', crm='222'):
"""Create and return a sample tag"""
return Kollege.objects.create(user=user, name=name, crm=crm) | 6d663e06a33ec576d9d2d96e29abb1522629f11b | 20,988 |
from course_lib.Base.Evaluation.metrics import average_precision, precision, recall
def get_singular_user_metrics(URM_test, recommender_object: BaseRecommender, cutoff=10):
"""
Return a pandas.DataFrame containing the precision, recall and average precision of all the users
:param URM_test: URM to be tes... | ed2e4c8cfa79967b6423f2af214aac4d0b817dd9 | 20,989 |
def detect_license(document, cleaned=False):
"""
Finds a license that is most similar to the provided `document`.
/
:document: a license, whose name should be identified
:type document: string
/
:cleaned: shows whether a `document` is prepared for vectorization.
/
Returns the name of... | 66ae25e7d1d29ed2d0541e7e8136aa9c6d53f6a6 | 20,990 |
from models import Participant
def user_profile(request):
"""
Puts user_profile into context if available.
"""
profile = None
if request.user.is_authenticated():
try:
profile = Participant.objects.get(user__id=request.user.id)
except ObjectDoesNotExist:
pass
return {'user_profile': profile} | 3ffdd2a851caebc865901fa118b19c813b4bffed | 20,991 |
import torch
def get_reduced_model(model: torch.nn.Module, x_sample: torch.Tensor,
bias: bool = True, activation: bool = True) -> torch.nn.Module:
"""
Get 1-layer model corresponding to the firing path of the model for a specific sample.
:param model: pytorch model
:param x_samp... | d46c4d6194b77b689618f3980d56ec459247f033 | 20,992 |
def cosine_sim(a: np.ndarray, b: np.ndarray) -> float:
"""
Computes the cosine similarity between two vectors
Parameters
----------
a: np.ndarray
the first vector
b: np.ndarray
the second vector
Returns
-------
float: the cosine similarity of the two vectors
"""... | bc8bd6c156f11e3ea16fb3ad20e1a4740ad2e22d | 20,993 |
def datetime_to_hours(dt):
"""Converts datetime.timedelta to hours
Parameters:
-----------
dt: datetime.timedelta
Returns:
--------
float
"""
return dt.days * 24 + dt.seconds / 3600 | e7373cbb49e21340fef1590a655059fd39c6ce88 | 20,994 |
def create_data_element(ds: "Dataset") -> "DataElement":
"""Return a ``gdcm.DataElement`` for the *Pixel Data*.
Parameters
----------
ds : dataset.Dataset
The :class:`~pydicom.dataset.Dataset` containing the *Pixel
Data*.
Returns
-------
gdcm.DataElement
The convert... | c45370201de36b7a5ea41613bc1387185ce80567 | 20,995 |
def thermo_paths(spc_dct, spc_locs_dct, spc_mods, run_prefix):
""" Set up the path for saving the pf input and output.
Placed in a MESSPF, NASA dirs high in run filesys.
"""
thm_path_dct = {}
for spc_name in spc_locs_dct:
spc_thm_path_dct = {}
spc_info = sinfo.from_dct(spc_dct[s... | 43e7746e38cd7617c0f4168afa59fe557d67316e | 20,996 |
def create_da_model_std(filename, eta_rho=10, xi_rho=10, s_rho=1,
reftime=default_epoch, clobber=False,
cdl=None, title="My Model STD"):
"""
Create an time varying model standard deviation file
Parameters
----------
filename : string
name and ... | c22f3c023d266a5b53cff2f64afe10975c08464d | 20,997 |
from rmgpy.chemkin import writeThermoEntry
def thermoEntry(request, section, subsection, index):
"""
A view for showing an entry in a thermodynamics database.
"""
# Load the thermo database if necessary
loadDatabase('thermo', section)
# Determine the entry we wish to view
try:
da... | a13fb8236ef9778b65d29358452234a32ba53a14 | 20,998 |
import io
def read_template(filename):
"""[summary]
This function is for reading a template from a file
[description]
Arguments:
filename {[type]} -- [description]
Returns:
[type] -- [description]
"""
with io.open(filename, encoding = 'utf-8') as template_file:
content = template_file.read()
return ... | f4eceb6d2b9075d0cf61d31842b754d6f3c01ce4 | 21,000 |
def S(a):
"""
Return the 3x3 cross product matrix
such that S(a)*b = a x b.
"""
assert a.shape == (3,) , "Input vector is not a numpy array of size (3,)"
S = np.asarray([[ 0.0 ,-a[2], a[1] ],
[ a[2], 0.0 ,-a[0] ],
[-a[1], a[0], 0.0 ]])
return S | b71f2529ccdafcc2b27f28c030ec2e3be9bf43ea | 21,001 |
from typing import Collection
from typing import Mapping
from typing import Any
from typing import Set
from typing import Dict
from typing import List
import itertools
def bulk_get_subscriber_user_ids(
stream_dicts: Collection[Mapping[str, Any]],
user_profile: UserProfile,
subscribed_stream_ids: Set[int],... | 49c6fc717340523ef4bdc1d66de111c4c86ce777 | 21,002 |
def adjust_learning_rate(optimizer, step):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
if step == 500000:
for param_group in optimizer.param_groups:
param_group['lr'] = 0.0005
elif step == 1000000:
for param_group in optimizer.param_groups:
... | 729c6650eb9b88102b68ba5e8d356e1cfa8b6632 | 21,003 |
def get_menu_permissions(obj):
"""
接收request中user对象的id
:param obj:
:return: 通过表级联得到user或者user所属group对应的菜单信息
"""
menu_obj = Menu.objects # 菜单对象
umids = [x.id for x in UserMenu.objects.get(user=obj).menu.all()]
isgroups = [x.id for x in User.objects.get(id=obj).groups.all()] # 用户所属组
... | 45b68b8f39b5507aa1aa1a58c3cc16eb5a1a983a | 21,004 |
import typing
def process_package(
package_path: str,
include_patterns: typing.Optional[typing.List[str]] = None,
exclude_patterns: typing.Optional[typing.List[str]] = None,
) -> SchemaMap:
"""
Recursively process a package source folder and return all json schemas from the top level functions it ... | f0297d8d93161dc481f8d2aca81a4618ced603fe | 21,005 |
def remove_suffix(input_string, suffix):
"""From the python docs, earlier versions of python does not have this."""
if suffix and input_string.endswith(suffix):
return input_string[: -len(suffix)]
return input_string | af4af2442f42121540de00dfaece13831a27cc57 | 21,008 |
def ais_TranslatePointToBound(*args):
"""
:param aPoint:
:type aPoint: gp_Pnt
:param aDir:
:type aDir: gp_Dir
:param aBndBox:
:type aBndBox: Bnd_Box &
:rtype: gp_Pnt
"""
return _AIS.ais_TranslatePointToBound(*args) | a45701c8a35fdd07e870ec850467a49145acd644 | 21,009 |
def unet_deepflash2(pretrained=None, **kwargs):
"""
U-Net model optimized for deepflash2
pretrained (str): specifies the dataset for pretrained weights
"""
model = _unet_deepflash2(pretrained=pretrained, **kwargs)
return model | 40b11641e3e2c418458c7e1d7e6180d4015ab2b9 | 21,010 |
import requests
def get_bga_game_list():
"""Gets a geeklist containing all games currently on Board Game Arena."""
result = requests.get("https://www.boardgamegeek.com/xmlapi2/geeklist/252354")
return result.text | 61418d5c0e0ad12c3f7af8a7831d02f94153ac84 | 21,011 |
def artifact(name: str, path: str):
"""Decorate a step to create a KFP HTML artifact.
Apply this decorator to a step to create a Kubeflow Pipelines artifact
(https://www.kubeflow.org/docs/pipelines/sdk/output-viewer/).
In case the path does not point to a valid file, the step will fail with
an erro... | b5033a66612d0f2aa5b138b368ca0f1acb7c2b21 | 21,012 |
import http
def build_status(code: int) -> str:
"""
Builds a string with HTTP status code and reason for given code.
:param code: integer HTTP code
:return: string with code and reason
"""
status = http.HTTPStatus(code)
def _process_word(_word: str) -> str:
if _word == "OK":
... | 9730abf472ddc3d5e852181c9d60f8c42fee687d | 21,013 |
def pretty_picks_players(picks):
"""Formats a table of players picked for the gameweek, with live score information"""
fields = ["Team", "Position", "Player", "Gameweek score", "Chance of playing next game",
"Player news", "Sub position", "Id"]
table = PrettyTable(field_names=fields)
table... | f4269fedad07b3302f724ba38f3afc1d8d9afc9f | 21,014 |
def open_path(request):
"""
handles paths authors/
"""
if(request.method == "POST"):
json_data = request.data
new_author = Author(is_active=False)
# Creating new user login information
if "password" in json_data:
password = json_data["password"]
... | 3c6a8d8fa6ac03a0bdd2b805fa348c43cf088f35 | 21,015 |
def encode_task(task):
""" Encodes a syllogistic task.
Parameters
----------
task : list(list(str))
List representation of the syllogism (e.g., [['All', 'A', 'B'], ['Some', 'B', 'C']]).
Returns
-------
str
Syllogistic task encoding (e.g., 'AI1').
"""
return Syllog... | b05b9e691d045bcc4877e1d9b9875902b9201bf7 | 21,016 |
def resize_small(image, resolution):
"""Shrink an image to the given resolution."""
h, w = image.shape[0], image.shape[1]
ratio = resolution / min(h, w)
h = tf.round(h * ratio, tf.int32)
w = tf.round(w * ratio, tf.int32)
return tf.image.resize(image, [h, w], antialias=True) | c44f615c788f300c62eef617f47b81c761ce63bc | 21,017 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.