content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def linkCount(tupleOfLists, listNumber, lowerBound, upperBound):
"""Counts the number of links in one of the lists passed.
This function is a speciality function to aid in calculating
statistics involving the number of links that lie in a given
range. It is primarily intended as a private helper functi... | 25,600 |
def field_groups(pairs, aligned_fields):
"""
Yield lists of (marker, value) pairs where all pairs in the list
are aligned. Unaligned fields will be returned as the only pair in
the list, and repeating groups (e.g. where they are wrapped) will
be returned separately.
"""
group = []
seen =... | 25,601 |
def encode_md5(plain_text):
"""
Encode the plain text by md5
:param plain_text:
:return: cipher text
"""
plain_text = plain_text + EXT_STRING
encoder = md5()
encoder.update(plain_text.encode('utf-8'))
return encoder.hexdigest() | 25,602 |
def delta(x, y, assume_normal=True, percentiles=[2.5, 97.5],
min_observations=20, nruns=10000, relative=False, x_weights=1, y_weights=1):
"""
Calculates the difference of means between the samples (x-y) in a
statistical sense, i.e. with confidence intervals.
NaNs are ignored: treated as if th... | 25,603 |
def CircleCircumference(curve_id, segment_index=-1):
"""Returns the circumference of a circle curve object
Parameters:
curve_id = identifier of a curve object
segment_index [opt] = identifies the curve segment if
curve_id identifies a polycurve
Returns:
The circumference of th... | 25,604 |
def set_authentication(application, authentication):
"""Set the wether API needs to be authenticated or not."""
if not isinstance(authentication, bool):
raise TypeError("Authentication flag must be of type <bool>")
def handler(sender, **kwargs):
g.authentication_ = authentication
with a... | 25,605 |
def generate_handshake(info_hash, peer_id):
"""
The handshake is a required message and must be the first message
transmitted by the client. It is (49+len(pstr)) bytes long in the form:
<pstrlen><pstr><reserved><info_hash><peer_id>
Where:
pstrlen: string length of <pstr>, as a single raw byte
... | 25,606 |
def tokenizer_decorator(func, **kwargs):
"""
This decorator wraps around a tokenizer function.
It adds the token to the info dict and removes the found token from the given name.
"""
if not callable(func):
raise TypeError(f"func {func} not callable")
@wraps(func)
def wrapper(name, i... | 25,607 |
def reverse_complement( seq ):
"""
Biological reverse complementation. Case in sequences are retained, and
IUPAC codes are supported. Code modified from:
http://shootout.alioth.debian.org/u32/program.php?test=revcomp&lang=python3&id=4
"""
return seq.translate(_nt_comp_table)[::-1] | 25,608 |
def maybe_extract_from_zipfile(zip_file):
"""
Extract files needed for Promtimer to run if necessary. Files needed by Promtimer are:
* everything under the stats_snapshot directory; nothing is extracted if the
stats_snapshot directory is already present
* couchbase.log: extracted if not present
... | 25,609 |
def computeLPS(s, n):
"""
Sol with better comle
"""
prev = 0 # length of the previous longest prefix suffix
lps = [0]*(n)
i = 1
# the loop calculates lps[i] for i = 1 to n-1
while i < n:
if s[i] == s[prev]:
prev += 1
lps[i] = prev
i += 1
... | 25,610 |
def roundedCorner(pc, p1, p2, r):
"""
Based on Stackoverflow C# rounded corner post
https://stackoverflow.com/questions/24771828/algorithm-for-creating-rounded-corners-in-a-polygon
"""
def GetProportionPoint(pt, segment, L, dx, dy):
factor = float(segment) / L if L != 0 else segment
... | 25,611 |
def depth_first_search(starting_nodes, visitor, outedges_func = node.outward):
"""
depth_first_search
go through all starting points and DFV on each of them
if they haven't been seen before
"""
colours = defaultdict(int) # defaults to WHITE
if len(starting_nodes):
for start ... | 25,612 |
def synthetic_data(n_points=1000, noise=0.05,
random_state=None, kind="unit_cube",
n_classes=None, n_occur=1, legacy_labels=False, **kwargs):
"""Make a synthetic dataset
A sample dataset generators in the style of sklearn's
`sample_generators`. This adds other function... | 25,613 |
def parse_args():
"""
Argument Parser
"""
parser = argparse.ArgumentParser(description="Wiki Text Extractor")
parser.add_argument("-i", "--input_dir", dest="input_dir", type=str, metavar="PATH",
default="./extracted",help="Input directory path ")
parser.add_argu... | 25,614 |
def _load_default_profiles():
# type: () -> Dict[str, Any]
"""Load all the profiles installed on the system."""
profiles = {}
for path in _iter_default_profile_file_paths():
name = _get_profile_name(path)
if _is_abstract_profile(name):
continue
definition = _read_p... | 25,615 |
async def reload(ctx, cog: str = None):
""" Reload cogs """
async def reload_cog(ctx, cog):
""" Reloads a cog """
try:
bot.reload_extension(f"cogs.{cog}")
await ctx.send(f"Reloaded {cog}")
except Exception as e:
await ctx.send(f"Couldn't reload {cog},... | 25,616 |
def train_model(model, train_loader, valid_loader, learning_rate, device,
epochs):
"""Trains a model with train_loader and validates it with valid_loader
Arguments:
model -- Model to train
train_loader -- Data to train
valid_loader -- Data to validate the training
... | 25,617 |
def get_weapon_techs(fighter=None):
"""If fighter is None, return list of all weapon techs.
If fighter is given, return list of weapon techs fighter has."""
if fighter is None:
return weapon_tech_names
else:
return [t for t in fighter.techs if get_tech_obj(t).is_weapon_tech] | 25,618 |
def read_csv(
_0: str,
/,
*,
_: None,
cache_dates: bool,
chunksize: None,
comment: None,
compression: Literal["infer"],
converters: None,
date_parser: None,
dayfirst: bool,
decimal: Literal["."],
delim_whitespace: bool,
delimiter: None,
dialect: None,
doub... | 25,619 |
def xml_to_values(l):
"""
Return a list of values from a list of XML data potentially including null values.
"""
new = []
for element in l:
if isinstance(element, dict):
new.append(None)
else:
new.append(to_float(element))
return new | 25,620 |
def _get_options(raw_options, apply_config):
"""Return parsed options."""
if not raw_options:
return parse_args([''], apply_config=apply_config)
if isinstance(raw_options, dict):
options = parse_args([''], apply_config=apply_config)
for name, value in raw_options.items():
... | 25,621 |
def csvdir_equities(tframes=None, csvdir=None):
"""
Generate an ingest function for custom data bundle
This function can be used in ~/.zipline/extension.py
to register bundle with custom parameters, e.g. with
a custom trading calendar.
Parameters
----------
tframes: tuple, optional
... | 25,622 |
def reverse_readline(filename, buf_size=8192):
"""a generator that returns the lines of a file in reverse order"""
with open(filename) as fh:
segment = None
offset = 0
fh.seek(0, os.SEEK_END)
file_size = remaining_size = fh.tell()
while remaining_size > 0:
off... | 25,623 |
def normalize_skeleton(joints):
"""Normalizes joint positions (NxMx2 or NxMx3, where M is 14 or 16) from parent to child order. Each vector from parent to child is normalized with respect to it's length.
:param joints: Position of joints (NxMx2) or (NxMx3)
:type joints: numpy.ndarray
:retur... | 25,624 |
def parseAreas(area):
"""Parse the strings into address. This function is highly customized and demonstrates the general steps for transforming raw covid cases data to a list of address searchable in Google Map.
Arguments:
area: raw data downloaded from a news app
Return:
l: a list of human-readabl... | 25,625 |
def is_valid_instruction(instr: int, cpu: Cpu = Cpu.M68000) -> bool:
"""Check if an instruction is valid for the specified CPU type"""
return bool(lib.m68k_is_valid_instruction(instr, cpu.value)) | 25,626 |
def wrap_text(translations, linewrap=0):
"""Pretty print translations.
If linewrap is set to 0 disble line wrapping.
Parameters
----------
translations : list
List of word translations.
linewrap : int
Maximum line length before wrapping.
"""
# pylint: disable=too-many-l... | 25,627 |
def test_list_qname_max_length_nistxml_sv_iv_list_qname_max_length_1_3(mode, save_output, output_format):
"""
Type list/QName is restricted by facet maxLength with value 5.
"""
assert_bindings(
schema="nistData/list/QName/Schema+Instance/NISTSchema-SV-IV-list-QName-maxLength-1.xsd",
inst... | 25,628 |
def docker_available():
"""Check if Docker can be run."""
returncode = run.run(["docker", "images"], return_code=True)
return returncode == 0 | 25,629 |
def is_bc(symbol):
"""
判断是否背驰
:param symbol:
:return:
"""
bars = get_kline(symbol, freq="30min", end_date=datetime.now(), count=1000)
c = CZSC(bars, get_signals=get_selector_signals)
factor_ = Factor(
name="背驰选股",
signals_any=[
Signal("30分钟_倒1笔_三笔形态_向下盘背_任意_任... | 25,630 |
def IEEE2030_5Time(dt_obj, local=False):
""" Return a proper IEEE2030_5 TimeType object for the dt_obj passed in.
From IEEE 2030.5 spec:
TimeType Object (Int64)
Time is a signed 64 bit value representing the number of seconds
since 0 hours, 0 minutes, 0 seconds, ... | 25,631 |
def learning_rate_schedule(params, global_step):
"""Handles learning rate scaling, linear warmup, and learning rate decay.
Args:
params: A dictionary that defines hyperparameters of model.
global_step: A tensor representing current global step.
Returns:
A tensor representing current learning rate.
... | 25,632 |
def generate_async(seq_name, count):
"""Generates sequence numbers.
Supports up to 5 QPS. If we need more, we will need to implement something
more advanced.
Args:
name: name of the sequence.
count: number of sequence numbers to allocate.
Returns:
The generated number. For a returned number i, ... | 25,633 |
def deadNode(uid):
"""
Remove a node from the neighbors.
"""
global universe
try:
lookupNode(uid).destroyTCPConnection()
neighborStrategy.removeNeighbor(uid)
del universe[uid]
deadMessage = message.DeadNodeMessage(uid)
deadMessage.send()
finally:
k... | 25,634 |
def run(
command,
cwd=None,
capture_output=False,
input=None,
check=True,
**subprocess_run_kwargs
):
""" Wrapper for subprocess.run() that sets some sane defaults """
logging.info("Running {} in {}".format(" ".join(command), cwd or os.getcwd()))
if isinstance(input, str):
inp... | 25,635 |
def test_is_zip_file(zipfile):
"""Verify is_repo_url works."""
assert is_zip_file(zipfile) is True | 25,636 |
def profile(step):
"""
Profiles a Pipeline step and save the results as HTML file in the project output
directory.
Usage:
@profile
def step(self):
pass
"""
@wraps(step)
def wrapper(*arg, **kwargs):
pipeline_instance = arg[0]
project = pipeline_in... | 25,637 |
def make_dataframe_wrapper(DataFrame):
"""
Prepares a "delivering wrapper" proxy class for DataFrame.
It makes DF.loc, DF.groupby() and other methods listed below deliver their
arguments to remote end by value.
"""
from modin.pandas.series import Series
conn = get_connection()
class O... | 25,638 |
def download_cmems_ts(lats, lons, t0, tf, variables, fn=None):
"""Subset CMEMS output using OpenDAP
:params:
lats = [south, north] limits of bbox
lons = [west, east] limits of bbox
t0 = datetime for start of time series
tf = datetime for end of time series
variables = li... | 25,639 |
def construct_gpu_info(statuses):
""" util for unit test case """
m = {}
for status in statuses:
m[status.minor] = status
m[status.uuid] = status
return m | 25,640 |
def load_data_time_machine(batch_size, num_steps, use_random_iter=False,
max_tokens=10000):
"""Return the iterator and the vocabulary of the time machine dataset."""
data_iter = SeqDataLoader(batch_size, num_steps, use_random_iter,
max_tokens)
return ... | 25,641 |
def scan_paths(paths, only_detect, recursive, module_filter):
"""
Scans paths for known bots and dumps information from them
@rtype : dict
@param paths: list of paths to check for files
@param only_detect: only detect known bots, don't process configuration information
@param recursive: recursi... | 25,642 |
def decode_shift(s: str):
"""
takes as input string encoded with encode_shift function. Returns decoded string.
Example solution:
# line 1
decoded_str = ''
# line 2
for ch in s:
# line 3
v = (ord(ch) - 5 - ord('a'))
# line 4
v = (v + ord('a'))
# l... | 25,643 |
def gather_guids (env):
"""
Returns and array of guids
"""
#ProjectGUID="{F4B0B7E4-A405-4EB1-A74F-0765181FE3BC}"
guidpattern = re.compile ("\"{(\S+-\S+-\S+-\S+-\S+)}\"")
namepattern = re.compile ("Name=\"(\S+)\"")
ret = ""; vcproj_dir = env["vcproj_dir"]; guids = {}
for file in os.listdir(vcproj_dir):
... | 25,644 |
def generate_masks(input_size, output_size=1, observed=None):
"""
Generates some basic input and output masks.
If C{input_size} is an integer, the number of columns of the mask will be
that integer. If C{input_size} is a list or tuple, a mask with multiple channels
is created, which can be used with RGB images, f... | 25,645 |
def parse_config_file(config):
"""
Load config file (primarily for endpoints)
"""
fail = False
with open(config, 'r') as fp:
content = yaml.load(fp.read())
if 'endpoints' not in content.keys():
return
for title, items in content['endpoints'].items():
if not 'url' in i... | 25,646 |
def average(time_array,height_array,data_array,height_bin_size=100,time_bin_size=3600):
"""
average: function that averages the radar signal by height and time
Args:
time_array: numpy 1d array with timestamps
height_array: numpy 1d array with height range
data_array: numpy ... | 25,647 |
def mkdir_if_not_exist(dir_name):
"""
make directory if not exist
:param dir_name:
:return:
"""
if not os.path.exists(dir_name):
os.makedirs(dir_name) | 25,648 |
def daily_report(api, space_name, charts, num_days=1, end_time=None):
"""Get a report of SLO Compliance for the previous day(s)
Returns: list of dicts of threshold breaches. Example Dict format:
{u'measure_time': 1478462400, u'value': 115.58158333333334}
:param api: An instance of sloc_report.LibratoA... | 25,649 |
def download_paris_dataset(root: str):
"""
Download the Paris dataset archive and expand it in the folder provided as parameter
"""
images_url = "https://www.robots.ox.ac.uk/~vgg/data/parisbuildings/paris_1.tgz"
download_and_extract_archive(images_url, root)
images_url = "https://www.robots.ox.... | 25,650 |
def new_pitch():
"""
route to new pitch form
:return:
"""
form = PitchForm()
if form.validate_on_submit():
title = form.title.data
pitch = form.pitch.data
category = form.category.data
fresh_pitch = Pitch(title=title, pitch_actual=pitch, category=category, user_... | 25,651 |
def get_entity_bios(seq,id2label):
"""Gets entities from sequence.
note: BIOS
Args:
seq (list): sequence of labels.
Returns:
list: list of (chunk_type, chunk_start, chunk_end).
Example:
# >>> seq = ['B-PER', 'I-PER', 'O', 'S-LOC']
# >>> get_entity_bios(seq)
[[... | 25,652 |
def early_stopping_train(model, X, Y_, x_test, y_test, param_niter=20001, param_delta=0.1):
"""Arguments:
- X: model inputs [NxD], type: torch.Tensor
- Y_: ground truth [Nx1], type: torch.Tensor
- param_niter: number of training iterations
- param_delta: learning rate
"""
best_model, bes... | 25,653 |
def my_vtk_grid_props(vtk_reader):
"""
Get grid properties from vtk_reader instance.
Parameters
----------
vtk_reader: vtk Reader instance
vtk Reader containing information about a vtk-file.
Returns
----------
step_x : float
For regular grid, stepsize in x-direction.
... | 25,654 |
def _set_jit_fusion_options():
"""Set PyTorch JIT layer fusion options."""
TORCH_MAJOR = int(torch.__version__.split(".")[0])
TORCH_MINOR = int(torch.__version__.split(".")[1])
if (TORCH_MAJOR > 1) or (TORCH_MAJOR == 1 and TORCH_MINOR >= 10):
# nv fuser
torch._C._jit_set_profiling_execu... | 25,655 |
def make_env(stack=True, scale_rew=True):
"""
Create an environment with some standard wrappers.
"""
env = grc.RemoteEnv('tmp/sock')
env = SonicDiscretizer(env)
if scale_rew:
env = RewardScaler(env)
env = WarpFrame(env)
if stack:
env = FrameStack(env, 4)
return env | 25,656 |
def plot_distr_cumsum(result, measure="degree", scale=['log', 'log'], figures=[], prefix="", show_std=True, show_figs=True, mode="safe", colors=('r', 'b')):
""" plots the cummulative distribution functions
special care has to be taken because averaging these is not trivial in comparison to e.g. degree
"""
... | 25,657 |
def recvall(sock, n, silent=False):
"""Helper function for recv_msg()."""
data = b''
while len(data) < n:
try:
packet = sock.recv(n - len(data))
if not packet:
return None
data += packet
except (socket.error, OSError) as e:
if n... | 25,658 |
def install_jenkins(dest_folder=".", fLOG=print, install=True, version=None):
"""
install `Jenkins <http://jenkins-ci.org/>`_ (only on Windows)
@param dest_folder where to download the setup
@param fLOG logging function
@param install install (other... | 25,659 |
def main():
"""Runs the program.
"""
# If the first flag is a -y, call the install main function directly.
# When the install is run with user and root installs, the calling script is re-run with -y in the beginning.
if len(sys.argv) >= 2 and sys.argv[1].lower() == "-y":
installMain()
... | 25,660 |
def state_space_model(A, z_t_minus_1, B, u_t_minus_1):
"""
Calculates the state at time t given the state at time t-1 and
the control inputs applied at time t-1
"""
state_estimate_t = (A @ z_t_minus_1) + (B @ u_t_minus_1)
return state_estimate_t | 25,661 |
def write_object_info(session, obj_type, id, outfile, path=os.getcwd()):
"""
Write all data for an object to a file as JSON.
Args:
session: SQLAlchemy session object.
obj_type (string): Class of the object to write.
Options are "gateware", "devicedb", "project", "sequence", "mea... | 25,662 |
def get_post(id , check_author=True):
"""Get a post and its author by id.
Checks that the id exists and optionally that the current user is
the author.
:param id: id of post to get
:param check_author: require the current user to be the author
:return: the post with author information
:rai... | 25,663 |
def hexdump(data, address=0, width=16):
""" Hexdump of the given bytes.
"""
hex_chars_width = width * 3 - 1 + ((width - 1) // 8)
for piece in chunks(data, chunk_size=width):
hex_chars = []
for part8 in chunks(piece, chunk_size=8):
hex_chars.append(
' '.join(he... | 25,664 |
def get_pixel(x, y):
"""Get the RGB value of a single pixel.
:param x: Horizontal position from 0 to 7
:param y: Veritcal position from 0 to 7
"""
global _pixel_map
return _pixel_map[y][x] | 25,665 |
def check_for_NAs(func: Callable) -> Callable:
"""
This decorator function checks whether the input string qualifies as an
NA. If it does it will return True immediately. Otherwise it will run
the function it decorates.
"""
def inner(string: str, *args, **kwargs) -> bool:
if re.fullmatc... | 25,666 |
def integrateEP_w0_ode( w_init: np.ndarray, w0: Union[ Callable, np.ndarray ], w0prime: Union[ Callable, np.ndarray ],
B: np.ndarray, s: np.ndarray, s0: float = 0, ds: float = None,
R_init: np.ndarray = np.eye( 3 ), Binv: np.ndarray = None, arg_check: bool = True,
... | 25,667 |
def change_coordinate_frame(keypoints, window, scope=None):
"""Changes coordinate frame of the keypoints to be relative to window's frame.
Given a window of the form [y_min, x_min, y_max, x_max], changes keypoint
coordinates from keypoints of shape [num_instances, num_keypoints, 2]
to be relative to this ... | 25,668 |
def eval_log_type(env_var_name):
"""get the log type from environment variable"""
ls_log = os.environ.get(env_var_name, '').lower().strip()
return ls_log if ls_log in LOG_LEVELS else False | 25,669 |
def _get_name(filename: str) -> str:
"""
Function returns a random name (first or last)
from the filename given as the argument.
Internal function. Not to be imported.
"""
LINE_WIDTH: int = 20 + 1 # 1 for \n
with open(filename) as names:
try:
total_names = int(next(... | 25,670 |
def map_to_udm_section_associations(enrollments_df: DataFrame) -> DataFrame:
"""
Maps a DataFrame containing Canvas enrollments into the Ed-Fi LMS Unified Data
Model (UDM) format.
Parameters
----------
enrollments_df: DataFrame
Pandas DataFrame containing all Canvas enrollments
Ret... | 25,671 |
def ngrammer(tokens, length=4):
"""
Generates n-grams from the given tokens
:param tokens: list of tokens in the text
:param length: n-grams of up to this length
:return: n-grams as tuples
"""
for n in range(1, min(len(tokens) + 1, length+1)):
for gram in ngrams(tokens, n):
... | 25,672 |
def plot_electrodes(mris, grid, values=None, ref_label=None, functional=None):
"""
"""
surf = mris.get('pial', None)
if surf is None:
surf = mris.get('dura', None)
pos = grid['pos'].reshape(-1, 3)
norm = grid['norm'].reshape(-1, 3)
labels = grid['label'].reshape(-1)
right_or_le... | 25,673 |
def _get_laplace_matrix(bcs: Boundaries) -> Tuple[np.ndarray, np.ndarray]:
"""get sparse matrix for laplace operator on a 1d Cartesian grid
Args:
bcs (:class:`~pde.grids.boundaries.axes.Boundaries`):
{ARG_BOUNDARIES_INSTANCE}
Returns:
tuple: A sparse matrix and a sparse vector ... | 25,674 |
def column_or_1d(y, warn=False):
""" Ravel column or 1d numpy array, else raises an error
Parameters
----------
y : array-like
warn : boolean, default False
To control display of warnings.
Returns
-------
y : array
"""
shape = np.shape(y)
if len(shape) == 1:
... | 25,675 |
def deplacer_pion(event,fenetre,grille,can):
"""
deplace un pion
:param event: evenement tkinter
:type event: evenement tkinter
:param fenetre: fenetre tkinter
:type fenetre: fenetre tkinter
:param can: canvas tkinter
:type can: objet tkinter
:param grille: grille du plateau
:type gr... | 25,676 |
def conv_tower(
inputs,
filters_init,
filters_end=None,
filters_mult=None,
divisible_by=1,
repeat=1,
**kwargs
):
"""Construct a reducing convolution block.
Args:
inputs: [batch_size, seq_length, features] input sequence
filters_init: Initial Conv1D filters
... | 25,677 |
def transcribe(args: argparse.Namespace):
"""Do speech to text on one more WAV files."""
# Load transcriber
args.model_dir = Path(args.model_dir)
if args.graph_dir:
args.graph_dir = Path(args.graph_dir)
else:
args.graph_dir = args.model_dir / "graph"
transcriber = KaldiCommandL... | 25,678 |
def edit_coach(request, coach_id):
""" Edit a coach's information """
if not request.user.is_superuser:
messages.error(request, 'Sorry, only the owners can do that.')
return redirect(reverse('home'))
coach = get_object_or_404(Coach, pk=coach_id)
if request.method == 'POST':
for... | 25,679 |
def estimate_translation(S,
joints_2d,
focal_length=5000.,
img_size=224.,
use_all_joints=False,
rotation=None):
"""Find camera translation that brings 3D joints S closest to 2D the correspond... | 25,680 |
def find_ladders_pretty(left_word: str, right_word: str, exact_depth: Optional[int] = None, max_depth: int = 10, use_heuristic: bool = True):
""" Print unique word ladders (see find_ladders)
See Also:
ladder: Find adjacent words
find_ladders: Find all ladders between two words
find_ladd... | 25,681 |
def create_midterm_data(all_students):
"""
Create the midterm data set
Ten questions, two from each topic, a percentage of students did not
show up, use it as an example of merge
Rules:
- International students have a 10% drop out rate
- Performance changes by PROGRAM!
:param all_stu... | 25,682 |
def identify_outliers(x_vals, y_vals, obj_func, outlier_fraction=0.1):
"""Finds the indices of outliers in the provided data to prune for subsequent curve fitting
Args:
x_vals (np.array): the x values of the data being analyzed
y_vals (np.array): the y values of the data being analyzed
... | 25,683 |
def GetTypeMapperFlag(messages):
"""Helper to get a choice flag from the commitment type enum."""
return arg_utils.ChoiceEnumMapper(
'--type',
messages.Commitment.TypeValueValuesEnum,
help_str=(
'Type of commitment. `memory-optimized` indicates that the '
'commitment is for mem... | 25,684 |
def gaussian_2Dclusters(n_clusters: int,
n_points: int,
means: List[float],
cov_matrices: List[float]):
"""
Creates a set of clustered data points, where the distribution within each
cluster is Gaussian.
Parameters
----------
... | 25,685 |
def test_dependent_get_define(mock_code_version, mock_dep_code):
"""Test task dependent function get_define."""
project_name = "test-dep-project"
process_definition_name = "test-dep-definition"
dependent_task_name = "test-dep-task"
dep_operator = And(
Or(
# test dependence with a... | 25,686 |
def prepare_concepts_index(create=False):
"""
Creates the settings and mappings in Elasticsearch to support term search
"""
index_settings = {
"settings": {"analysis": {"analyzer": {"folding": {"tokenizer": "standard", "filter": ["lowercase", "asciifolding"]}}}},
"mappings": {
... | 25,687 |
def test_to_graph_should_return_has_part_as_uri() -> None:
"""It returns a information model graph isomorphic to spec."""
"""It returns an has_part graph isomorphic to spec."""
informationmodel = InformationModel()
informationmodel.identifier = "http://example.com/informationmodels/1"
has_part: Li... | 25,688 |
def pack_wrapper(module, att_feats, att_masks):
"""
for batch computation, pack sequences with different lenghth with explicit setting the batch size at each time step
"""
if att_masks is not None:
packed, inv_ix = sort_pack_padded_sequence(att_feats, att_masks.data.long().sum(1))
return... | 25,689 |
async def test_form_invalid_auth(opp):
"""Test we handle invalid auth."""
result = await opp.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"pylitterbot.Account.connect",
side_effect=LitterRobotLoginException,
):
... | 25,690 |
def cd(directory):
"""A context manager for switching the current working directory when
using the local() function. Not thread safe.
"""
global GLOBAL_PWD
GLOBAL_PWD.append(directory)
yield
if len(GLOBAL_PWD) > 1:
GLOBAL_PWD.pop() | 25,691 |
def processor(preprocessed_data_id, param_id, param_constructor):
"""Dispatch the processor work"""
preprocessed_data = PreprocessedData(preprocessed_data_id)
params = param_constructor(param_id)
sp = StudyProcessor()
try:
process_out = sp(preprocessed_data, params)
except Exception as ... | 25,692 |
def recommendation_inspiredby(film: str, limit: int=20) -> list:
"""Movie recommandations from the same inspiration with selected movie
Args:
film (str): URI of the selected movie
limit (int, optional): Maximum number of results to return. Defaults to 20.
Returns:
list: matching mo... | 25,693 |
def str2twixt(move):
""" Converts one move string to a twixt backend class move.
Handles both T1-style coordinates (e.g.: 'd5', 'f18'') as well as tsgf-
style coordinates (e.g.: 'fg', 'bi') as well as special strings
('swap' and 'resign'). It can handle letter in upper as well as lowercase.
Args:
... | 25,694 |
def celery_health_view(request):
"""Admin view that displays the celery configuration and health."""
if request.method == 'POST':
celery_health_task.delay(datetime.now())
messages.success(request, 'Health task created.')
return HttpResponseRedirect(request.path)
capital = re.compile... | 25,695 |
def get_n_runs(slurm_array_file):
"""Reads the run.sh file to figure out how many conformers or rotors were meant to run
"""
with open(slurm_array_file, 'r') as f:
for line in f:
if 'SBATCH --array=' in line:
token = line.split('-')[-1]
n_runs = 1 + int(to... | 25,696 |
def consume(pipeline, data, cleanup=None, **node_contexts):
"""Handles node contexts before/after calling pipeline.consume()
Note
----
It would have been better to subclass Pipeline and implement this logic
right before/after the core consume() call, but there is a bug in pickle
that prevents t... | 25,697 |
def notify(hours):
"""
This Function notifies when it's an hour, two hours or more.
"""
present = it_is_time_for_notify()
if hours == 1:
Notification("It's an Hour!!", present).send()
else:
ptr = f"It's {hours} Hours"
Notification(ptr, present).send()
Timer(3600, fu... | 25,698 |
def get_field_attribute(field):
"""
Format and return a whole attribute string
consists of attribute name in snake case and field type
"""
field_name = get_field_name(field.name.value)
field_type = get_field_type(field)
strawberry_type = get_strawberry_type(
field_name, field.descrip... | 25,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.