content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Type
def _get_func_def_ret_type(semanal: SemanticAnalyzerPluginInterface, funcdef: FuncDef) -> Type:
"""
Given a `FuncDef`, return its return-type (or `Any`)
"""
ret_type = None
type_ = funcdef.type
if isinstance(type_, CallableType):
ret_type = type_.ret_type
... | cb5d22aa5ebf5988c24f322281c3bd8e3ddb757c | 3,633,200 |
def setup(hass, config):
"""Mock a successful setup."""
return True | fd2977534aa8a165b49c4fbddc513c8f77b0588d | 3,633,201 |
def generate_breadcrumbs(text):
"""
It expects a string with format `name=url, name=url, ...' and it will automatically convert that into a list of
dictionaries `[{name: url}, {name: url}, ...]`.
"""
entries = text.split(',')
values = {}
for entry in entries:
entry = entry.split('='... | 4b647e14ba28c25769d6c2d288cc115558ccc331 | 3,633,202 |
def _compile_docker_commands(app_name, assembled_specs, port_spec):
""" This is used to compile the command that will be run when the docker container starts
up. This command has to install any libs that the app uses, run the `always` command, and
run the `once` command if the container is being launched fo... | 6b3e359e0b773acfbee7250e5bc1933a42eefdd2 | 3,633,203 |
def equation_expow3(x, a, b, c, d, e):
"""Equation form for expow3 """
return exp(a + b*x + x*c/2) | 0e77c3537c37ce22d6cea00b373e98523335c205 | 3,633,204 |
def _process_cosmos_qa(example):
"""Process cosmos_qa dataset example."""
label = tf.cast(example['label'], tf.int32)
one_hot = tf.one_hot(label, 4)
options = tf.stack([
example['answer0'],
example['answer1'],
example['answer2'],
example['answer3'],
])
return {
'context': examp... | 42776f9958c57eb332f3130db996d1943094e6ab | 3,633,205 |
def resolve_collisions(rlist, newr, collision):
"""Adjust region list rlist to avoid overlaps with newr"""
updated = []
for i in range(len(rlist)):
if collision[i]:
updated.extend(split(rlist[i], newr))
else:
updated.append(rlist[i])
return updated | e9ecebc31348eb00bfa543890870b0155b050da9 | 3,633,206 |
from typing import Sequence
from typing import Optional
from typing import List
import os
def create_source_list(paths: Sequence[str], options: Options,
fscache: Optional[FileSystemCache] = None,
allow_empty_dir: bool = False) -> List[BuildSource]:
"""From a list of s... | e34b37abfe82b1f25a493b0e6fa773eae9b59eef | 3,633,207 |
def beale(xy):
"""
The Beale function, as a set of residuals (cost = sum(residuals**2))
The standard Beale's function is with data as [1.5, 2.25, 2.625],
and has a global minima at (3, 0.5). Beale's function is a coupled
model, linear in x and quartic in y. Its data-space dimension (3) is
great... | 222600a1ff08791e07d85e04cc481b879fa73d42 | 3,633,208 |
def ks_twosamp(data1, data2, alternative="two-sided"):
"""
Computes the Kolmogorov-Smirnov test on two samples.
Missing values are discarded.
Parameters
----------
data1 : array_like
First data set
data2 : array_like
Second data set
alternative : {'two-sided', 'less', '... | c2fbca3ed32e666407f20976cffe56e4457c0e39 | 3,633,209 |
def getIdFromVpcArn(resources):
""" given a vpc arn, strip off all but the id """
vpcStr = 'vpc/'
ids = []
for resource in resources:
if vpcStr in resource:
index = resource.rfind(vpcStr)
id = resource[index+len(vpcStr):]
ids.append(id)
return ids | c1c5e5aef145ee8d3a2072604a1f531ad9198385 | 3,633,210 |
def input_output_mapping():
"""Build a mapping dictionary from pfb input to output numbers."""
# the polyphase filter bank maps inputs to outputs, which the MWA
# correlator then records as the antenna indices.
# the following is taken from mwa_build_lfiles/mwac_utils.c
# inputs are mapped to output... | 1c88c7aba95218a4ce4ae792b2001e4f912da178 | 3,633,211 |
def get_testmeta_min_max_count(leaf, x_axis):
"""
This function expects all x label titles to be numeric value
so we can calculate the minimum and maximum of them.
"""
testcases = get_testcases(leaf)
# logaritmic, we need to calculate the position
minval = None
maxval = None
for tit... | 4a84a5ccdf9aa61cfee9c0f37fe5bdb56e3d32a2 | 3,633,212 |
def xplus(x, v):
"""
Adds two 3DOF states with an arbitrary number of parameters.
"""
xv = np.add(x, v)
xv[2] = unwrap(xv[2])
return xv | 2861807c7288b4a7b1abf58098160215f4cd8e2c | 3,633,213 |
import subprocess
def rexec(cmd):
""" executes shell command cmd with the output
returned as a string when the command has
finished.
"""
try:
output = subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as exc:
return exc.... | 79a7441c9798c53c2a9f064cec15d38adbe1dd6b | 3,633,214 |
import requests
import json
import time
import sys
def get_value(symbol, amount, compare=args.c):
"""
Convert some amount of some coin, into the currency specified by -c
"""
if symbol.upper() == compare.upper():
return amount
#sometimes the API does not respond so this loop tri
num_att... | 90958c6e65e684ddeeff91c99af5f014d8575d27 | 3,633,215 |
def list_times(service):
"""
Lists the times from the selected calendar in ascending order.
:param service: a google 'service' object
:return: busy is a sorted list of busy times and free is a sorted list of
free times for the selected calendar(s)
"""
app.logger.debug('Entering list_times')
... | 7d87714bb29cc2e298a64a285b2ef72205cb6e4a | 3,633,216 |
import logging
def process(utim, data):
"""
Run process
:param Utim utim: Utim instance
:param list data: Data to process [source, destination, status, body]
:return list: [from, to, status, body]
"""
source = data[SubprocessorIndex.source.value]
destination = data[SubprocessorIndex.... | 5774ecf399274fa19513d866cf8a29d6d698a70d | 3,633,217 |
def get_event_list_current_file(df, fname):
"""
Get list of events for a given filename
:param df: pd.DataFrame, the dataframe to search on
:param fname: the filename to extract the value from the dataframe
:return: list of events (dictionaries) for the given filename
"""
event_file = df[df[... | 4fc56e23e57f021a5c84d5650d2c9586ed86b19e | 3,633,218 |
def get_dealer_reviews_from_cf(url, **kwargs):
""" Get Reviews"""
results = []
json_result = get_request(url)
if json_result:
reviews = json_result["entries"]
for review in reviews:
dealer_review = DealerReview(id=review["id"],
name=re... | 08f16863e1f05d5fe45d7e6bec0cceded41994af | 3,633,219 |
def fused_normalize(x: th.Tensor, mean: th.Tensor, std: th.Tensor, eps: float = 1e-8):
"""Normalize or standardize."""
return (x - mean) / (std + eps) | 971e061da3d55642fc32729132a647cdf63d6d42 | 3,633,220 |
def get_attachment_file_upload_to(instance, filename):
""" Returns a valid upload path for the file of an attachment. """
return instance.get_file_upload_to(filename) | e38c51a2ca947bebe1ed274c4265081c6b9e7c41 | 3,633,221 |
def temp_ann(S_SHSTA_0, S_SHSTA_1, S_SHSTA_2, S_SHSTA_3, I_SHSTA_0, I_SHSTA_1,
I_SHSTA_2, I_SHSTA_3, C_KSWCK_0, C_KSWCK_1, C_KSWCK_2, C_KSWCK_3):
"""
Notes
-----
Where t = 0, provide the current time step. Where t = 1, provide the
1-month prior time step value. Repeat this pattern for a... | cddc9ac237fcc446daff7f2f4ffd99783a9faab5 | 3,633,222 |
def slice(Matrix, a, b):
"""Slice a matrix properly- like Octave.
Addresses the confounding inconsistency that `M[a,b]` acts differently if
`a` and `b` are the same length or different lengths.
Parameters
----------
Matrix : float array
Arbitrary array
a, b : int lists or arrays
... | a66dbdca7bbaf1ecf556e4cdd340d10dca28be02 | 3,633,223 |
import _functools
def completing(rf, cf=identity):
"""Returns a wrapper around `rf` that calls `cf` when invoked with one argument.
Args:
rf: A :any:`reducing function`.
cf: An optional function that accepts a single argument. Used as the
completion arity for the returned :any:`re... | 9efc81357d65871871a335d1e66fe687127568aa | 3,633,224 |
def build_feet(
filter1, # type: pymunk.ShapeFilter
normal_rect, # type: pygame.Rect
pymunk_objects, # type: List[Any]
body_body, # type: pymunk.Body
seat_body, # type: pymunk.Body
):
# type: (...) -> Tuple[pymunk.Body, pygame.Sprite]
"""
Builds our unicycle cat... | f903b89feedab4bf80cf34b2b6c0fd6e296330d3 | 3,633,225 |
def zone_distances(zones):
"""
:param zones
GeoDataFrame [*index, zone, geometry]
Must be in a CRS of unit: metre
"""
for ax in zones.crs.axis_info:
assert ax.unit_name == 'metre'
print("Calculating distances between zones...")
distances_meters = pairwise_distances(
list... | 74538d679e7efa3e4a2dfa031548e7e2062053cb | 3,633,226 |
import re
import base64
def decode_base64(data, altchars=b'+/'):
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
data = re.sub(rb'[^a-zA-Z0-9%s]+' % altchars,
b'', data.encode())
missing_paddi... | c99f4c832e8e990611ad8413d4b508a697504218 | 3,633,227 |
from operator import ge
def _run_after(a, b):
"""Force operation a to run after b. Do not add control dependencies
to ops that already run after. Returns 0 if no dependencies were added,
1 otherwise."""
already_after = (b in a.control_inputs) or (b in [i.op for i in a.inputs])
if already_after:
return... | 36489af41d4671a952dd62c4dd5d68618606a361 | 3,633,228 |
def handle_negations(tweet_tokens, lexicon_scores):
"""
Handling of negations occuring in tweets -> shifts meaning of words
-> if a negation was found the polarity of the following words will change
Parameters
----------
tweet_tokens : List
list of tweet tokens that were already prepocessed (... | cca56e5fa1b611aa6adb2e74ab580fed49b923ee | 3,633,229 |
def build_keras(hyperparams_fn, freeze_batchnorm, inplace_batchnorm_update,
num_predictions_per_location_list, box_predictor_config,
is_training, num_classes, add_background_class=True):
"""Builds a Keras-based box predictor based on the configuration.
Builds Keras-based box predict... | 9b5247042bb1a47715c0f64f19011c5634c4aff3 | 3,633,230 |
def log_level(non_prod_value: str, prod_value: str) -> str:
"""
Helper function for setting an appropriate log level in prod.
"""
return prod_value | 86f098cfe9137519da1d160c22dfc1f43303c546 | 3,633,231 |
import os
def partitioning_df(stats_df,plus_and_minus,tmp_dir,chunk_size = 1000):
""" the first state for large files is very large. We split the first state in a separate file.
Then all the other states are splitted into several files.
"""
# stats_df.to_csv('stats_df.csv', index=False, header=True... | 3a62c7abe0ac67b095351ea69bad642b3479a36e | 3,633,232 |
def add(x, y):
""" Add two numbers and return their sum"""
return x+y | 5afb9194e696fe87f9f29f8893fd2f0e90673a1b | 3,633,233 |
from typing import Any
from typing import Optional
from typing import Union
def default_resolve_type_fn(
value: Any,
info: GraphQLResolveInfo,
abstract_type: GraphQLAbstractType
) -> MaybeAwaitable[Optional[Union[GraphQLObjectType, str]]]:
"""Default type resolver function.
If... | d1266fc358bbce50c226d7e40f95f6930261a121 | 3,633,234 |
def svn_repos_parse_fns2_invoke_close_node(*args):
"""svn_repos_parse_fns2_invoke_close_node(svn_repos_parse_fns2_t _obj, void * node_baton) -> svn_error_t"""
return _repos.svn_repos_parse_fns2_invoke_close_node(*args) | 996ebf6c153a659361d429ae6cbb977dc4202f3a | 3,633,235 |
def sample_dball(dimension: int, amount: int, radius: float = 1) -> np.ndarray:
"""
**Sample from a d-ball by drop of coordinates.**
Similar to the sphere, values are randomly assigned to each dimension dimension from a certain interval
evenly distributed. Since the radius can be determined... | a1bbf552ea05dad5b1d11fa397ae8c2ce98c77a5 | 3,633,236 |
def distinguishable_paths(path1, path2):
"""
Checks if two model paths are distinguishable in a deterministic way, without looking forward
or backtracking. The arguments are lists containing paths from the base group of the model to
a couple of leaf elements. Returns `True` if there is a deterministic s... | 140f8f18f030df233490ef242504649f175f62c7 | 3,633,237 |
def _correct_rotation(img: np.ndarray) -> np.ndarray:
"""if image is rotated correct for this and return it"""
edges = cv2.Canny(img, 50, 150, apertureSize=3)
lines = cv2.HoughLinesP(
edges, 1, np.pi / 180, 100, minLineLength=100, maxLineGap=10
)
avg_slope = 0
cnt = 0
try:
fo... | d2a3760ceb4a73260f8013a9aeafcfd21cfd6a07 | 3,633,238 |
def get_xyz_coords(illuminant, observer):
"""Get the XYZ coordinates of the given illuminant and observer [1]_.
Parameters
----------
illuminant : {"A", "D50", "D55", "D65", "D75", "E"}, optional
The name of the illuminant (the function is NOT case sensitive).
observer : {"2", "10"}, optiona... | bca3f1e4a195fc2dcfc0dd9d440a84336573d34f | 3,633,239 |
import sys
def get_progname():
"""Get program name."""
return PurePath(sys.argv[0]).name | 50d49770479f4fb72711745a22ba2fbf3b0b0cf6 | 3,633,240 |
async def document_analyze(*, db:AsyncIOMotorClient = Depends(get_database), payload: NoteSchema):
"""[summary]
View inserts item in the document string.
[description]
Endpoint to retrieve an specific item.
"""
analyze = await gensim.result(db, payload)
return fix_item_id(analyze) | a7dc75306a40c2cc89016f7cf632e558e50fef7e | 3,633,241 |
import os
import shutil
import tempfile
import re
def run_gfail(args):
"""Runs ground failure.
Args:
args: dictionary or argument parser Namespace output by bin/gfail
program.
Returns:
list: Names of created files.
"""
# TODO: ADD CONFIG VALIDATION STEP THAT MAKES SU... | 9ec18779d7742d08702a441ff192c51c899774af | 3,633,242 |
def create_example_concept_description() -> model.ConceptDescription:
"""
Creates an example :class:`~aas.model.concept.ConceptDescription`
:return: example concept description
"""
concept_description = model.ConceptDescription(
identification=model.Identifier(id_='https://acplt.org/Test_Co... | 72c60aca03bd85fc66a5600675888a10542c1c96 | 3,633,243 |
def to_int(x):
"""
Try to convert a string to int
:param x: str
:return: int or np.nan
"""
try:
return int(x)
except:
return np.nan | 6d488258d49fc0cb396d48e1dd74c8bd9ed9fbea | 3,633,244 |
import progressbar
import gc
def train_single_batch_agent(agent, train_batch, val_batch, acc_tolerance=1.0, train_loss_tolerance=0.01):
"""
Train untils the accuracy on the specified batch has perfect interpolation in loss and accuracy.
It also prints and tb logs every iteration.
todo - compare with... | f35d143f7d39802e35246705ddf317b7f066986a | 3,633,245 |
def residuals(pars, data):
"""Returns data - model for given values of parameters
Parameters
----------
pars : array-like
[alpha, beta, gamma] parameters.
data : Data object (string)
Data to be compared with model.
"""
alpha, beta, gamma = pars
mod = model(data.x, alp... | ee69bb681c003041de62ea9bb7774b51f9de5600 | 3,633,246 |
def plot_psth_photostim_effect(units, condition_name_kw=['both_alm'], axs=None):
"""
For the specified `units`, plot PSTH comparison between stim vs. no-stim with left/right trial instruction
The stim location (or other appropriate search keywords) can be specified in `condition_name_kw` (default: bilateral... | d416207f19cf640faac1da6ab2e97c6a3fad251e | 3,633,247 |
import configparser
def load_versions(versions):
"""
parses 'jc221,jc221' etc.
returns the supported versions and orders them
from newest to oldest
"""
props = configparser.ConfigParser()
props.read(LIB_DIR / "sdkversions.properties")
known = list(props["SUPPORTED_VERSIONS"])
filt... | 28bd0e7f080fb75707f716117c0c6b9ed6d05d77 | 3,633,248 |
import click
def market_search_formatter(search_results):
""" Formats the search results into a tabular paginated format
Args:
search_results (list): a list of results in dict format returned from the REST API
Returs:
str: formatted results in tabular format
"""
headers = ["id", ... | 24942024599ddd5117a604cbd4e4890a8ccb5bf6 | 3,633,249 |
from typing import Optional
from pathlib import Path
def get_run_dir(run_number: Optional[int] = None) -> Path:
"""
Returns the directory corresponding to a given run number as a Path.
If no run number is provided, return the current run directory.
"""
if run_number is None:
run_number = o... | 513c913effeadbf1267e63e1948e7ff9cb2fe753 | 3,633,250 |
def read_to_ulens_in_intvls(read, intvls):
"""Extract units within `intvls` from `read.units`."""
return [unit.length for unit in read.units
if unit.length in intvls] | 11159bea8bbf0cb68f0e9a7355c82e93b430065d | 3,633,251 |
def org_identities_edit(self) -> bool:
"""
### NOT IMPLEMENTED ###
Edit an existing Organizational Identity.
:param self:
:return
501 Server Error: Not Implemented for url: mock://not_implemented_501.local:
"""
url = self._MOCK_501_URL
resp = self._mock_session.get(
url=... | bb08be8788812b396776c41f195ccce91c36a071 | 3,633,252 |
import secrets
def makePrimes(bits):
"""
Generates the prime numbers p and q.
Param bits: int -- the bit length of each prime
Returns a tuple of prime numbers.
"""
p = None
q = None
for _ in range(500):
p = secrets.randbits(bits)
q = secrets.randbits(bits)
... | f14c31c1ef6bbf151a743b2468db7d545ea7feb3 | 3,633,253 |
from beakerx import TableDisplay
import ipywidgets
def _in_splice_compatible_env():
"""
Determines if a user is using the Splice Machine managed notebooks or not
:return: Boolean if the user is using the Splice Environment
"""
try:
except ImportError:
return False
return get_ipyth... | 8088e1526daa33c86a88acd08a14c77b3de5fc8d | 3,633,254 |
import torch
def make_split(dataset, holdout_fraction, seed=0, sort=False):
""" Split a Torch TensorDataset into (1-holdout_fraction) / holdout_fraction.
Args:
dataset (TensorDataset): Tensor dataset that has 2 tensors -> data, targets
holdout_fraction (float): Fraction of the dataset that is... | 148f0569320329c1737d2d585d9502db2215e9a4 | 3,633,255 |
from typing import Callable
def singleton(instance: str = 'name') -> Callable:
"""
Wrap injector decorator.
:param instance: name of instance to inject
:type instance: str
:return: injector decorator
:rtype: Callable
"""
def save_to_storage(factory_method):
"""
Decora... | d8e9b63d81f95c18663edf00d0fb462a44805c0e | 3,633,256 |
def fillNaToNone(data):
"""Iterates through NA values and changes them to None
Parameters:
dataset (pd.Dataset): Both datasets
Returns:
data (pd.Dataset): Dataset with any NA values in the columns listed changed to None
"""
columns = ["PoolQC", "MiscFeature", "Alley", "Fence", "FireplaceQu... | 2a6fc8008447abefd9f993b01606c1afc5aa5a8a | 3,633,257 |
import re
def is_ld_block_defn_line(mdfl):
"""
Parse GFM link definition lines of the form...
[10]: https://www.google.com
[11]: https://www.google.com "Title Info"
[1a]: https://www.google.com "Title Info {}"
[2b]: https://www.google.com "Title Info {biblio info}"
Ret... | 0ebd01c0c05634ee33a320fa4c280ad575ee9b25 | 3,633,258 |
def return_data_frame_deaths_vs_cases(dict_corona_virus: dict, data_frame_countries: pd.DataFrame) -> pd.DataFrame:
"""
This method will return a data_coronavirus frame with the fields we need to create our map with circles:
In this map, the circles will represent the ratio between deaths and number of case... | c7b1cf4456f2495de1302eb75c0617cef1c965ae | 3,633,259 |
def vn_islowercase(char):
"""Check is lowercase for a vn character
:param char: a unicode character
:return:
"""
if char in _DIGIT or char in _ADDITIONAL_CHARACTERS:
return True
return char in VN_LOWERCASE | 2393de33155a940f260d91f7304f7f3c35ce3e4e | 3,633,260 |
def shared_template(testconfig):
"""Shared template for hyperfoil test"""
shared_template = testconfig.get('hyperfoil', {}).get('shared_template', {})
return shared_template.to_dict() | 160daa08699ae973d5cbbfe28b75f08ff3eb2f52 | 3,633,261 |
def doubleSlit_interaction(psi, j0, j1, i0, i1, i2, i3):
"""
Function responsible of the interaction of the psi wave function with the
double slit in the case of rigid walls.
The indices j0, j1, i0, i1, i2, i3 define the extent of the double slit.
slit.
Input parameters:
... | 99fe70f564a72ff84d2de09bc93b3c9dada3c4a0 | 3,633,262 |
import random
def gnp_from_data(sizes, densities, directed = True):#, p_disconnect_node = None):
"""
Given a set of graph sizes (number of nodes) and densities, generate a new gnp (Bernoulli/Erdos-Renyi) random graph with size selected from the given graph sizes. Density is estimated based on a linear model o... | e63cea7d705eacb77b6fdc97654d049967a4de4a | 3,633,263 |
def greedy_tsp(G, weight="weight", source=None):
"""Return a low cost cycle starting at `source` and its cost.
This approximates a solution to the traveling salesman problem.
It finds a cycle of all the nodes that a salesman can visit in order
to visit many nodes while minimizing total distance.
It... | e9dbb0c2bb4b1b41545fd5e47d03e022bdfd5ca9 | 3,633,264 |
def get_sector(sector_id):
"""
GET: Gets all Entities on the required sector.
https://meinformoapi.herokuapp.com/entities/sectors/Ejecutivo
"""
sector_id = str(sector_id)
output = tools.filter_dict(current_entities,"sector", [sector_id])
return Response(dumps(output), mimetype='application/j... | 4df0d454e1f592173e8c43d26254a00e054fd721 | 3,633,265 |
def map_get_by_key_range(bin_name, key_range_start,
key_range_end, return_type, inverted=False):
"""Creates a map_get_by_key_range operation to be used with operate or operate_ordered
The operation returns items with keys between key_range_start(inclusive) and
key_range_end(exclusi... | 4a2ffac60203e88520a46fb28d4fc31715c16369 | 3,633,266 |
def output(input_text : str = ""):
"""
It will take input as a string and return the output of the given input mathematics problem
"""
cal_object = Calculator(input_text)
return cal_object.result | 3393216343c4c2aa7a4b5e8fd73494b65f2c652f | 3,633,267 |
import torch
from typing import Sequence
def to_tensor(X, use_cuda):
"""Turn to torch Variable.
Handles the cases:
* Variable
* PackedSequence
* numpy array
* torch Tensor
* list or tuple of one of the former
* dict of one of the former
"""
to_tensor_ = partial(to... | 51eaec2cdd4b64ca2a1922f36221305992d78d2b | 3,633,268 |
def get_regularization_losses(scope=None):
"""Gets the list of regularization losses.
Args:
scope: An optional scope name for filtering the losses to return.
Returns:
A list of regularization losses as Tensors.
"""
return ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES, scope) | 442d47f32e1d4be11072d0731c58bac795cce1ff | 3,633,269 |
def get_output_tracking_error_message(ulog: ULog) -> str:
"""
return the name of the message containing the output_tracking_error
:param ulog:
:return: str
"""
for elem in ulog.data_list:
if elem.name == "ekf2_innovations":
return "ekf2_innovations"
if elem.name == "e... | 55445033308ca476b31e06a4374ad098e74f0c92 | 3,633,270 |
def getBpms():
"""
return a list of bpms object.
this calls :func:`~aphla.lattice.Lattice.getGroupMembers` of current
lattice and take a "union".
"""
return machine._lat.getGroupMembers('BPM', op='union') | 44ad3256074be5f5d521892ed48379cc6539f9d3 | 3,633,271 |
import os
import subprocess
def get_test_disk(node=1):
"""获取可测试使用的磁盘
Args:
node (int, optional): 节点号. Defaults to 1.
Returns:
[str]: 磁盘名称
"""
if os.environ.get("NODE" + str(node) + "LOCALTION") == "local":
used_disk = subprocess.getoutput(
"lsblk -l | grep -e ... | c7e7e40e0ea8a6ca939cdd0b81b426475d9ebbdc | 3,633,272 |
def get_single_label(label_id):
"""Get an ID as a single element.
Args:
label_id: Single ID or sequence of IDs.
Returns:
The first elements if ``label_id`` is a sequence, or the
``label_id`` itself if not.
"""
if libmag.is_seq(label_id) and len(label_id) > 0:
... | b97b6dbaf5fbb56204acef637f358ec35a331db7 | 3,633,273 |
from sentinelsat import SentinelAPI
import pyproj
import numpy as np
import shapely.geometry as sg
from shapely.wkt import loads
from astropy.time import Time, TimeDelta
from tqdm import tqdm
import sys
def search_sentinels(platform_name, df, aoi, dt=2, user=None, pwd=None,
proj_string='+init=EPS... | ff7585bd66a60c1ba0ce6d09c535b19378dadcd9 | 3,633,274 |
import unittest
def not_implemented(cls):
"""Decorator for TestCase classes to indicate that the tests have not been written (yet)."""
msg = "%s: tests have not been implemented" % cls.__name__
_NOT_IMPLEMENTED.append(msg)
return unittest.skip(msg)(cls) | 0454ffeb08e4367dbb70c90f40748a32c5cec05d | 3,633,275 |
def get_default_container_image_for_current_sdk(job_type):
"""For internal use only; no backwards-compatibility guarantees.
Args:
job_type (str): BEAM job type.
Returns:
str: Google Cloud Dataflow container image for remote execution.
"""
# TODO(tvalentyn): Use enumerated type instead of strings for... | a27fa86cd8bb6dd5ea7fec5b3597521d969f4b30 | 3,633,276 |
from pymatgen.io.cif import CifParser
def get_structure_tuple(fileobject, fileformat, extra_data=None):
"""
Given a file-like object (using StringIO or open()), and a string
identifying the file format, return a structure tuple as accepted
by seekpath.
:param fileobject: a file-like object contai... | ada7d694b0d9ec60f6b1e40dd21487650c637207 | 3,633,277 |
def find_merge_commit_in_prs(needle, prs):
"""Find the merge commit `needle` in the list of `prs`
If found, returns the pr the merge commit comes from. If not found, return
None
"""
for pr in prs[::-1]:
if pr['merge_commit'] is not None:
if pr['merge_commit']['hash'] == needle[1... | 42320473aff84985e35cdf9024a64a18fe6f14f1 | 3,633,278 |
def date_breaks(width):
"""
Regularly spaced dates
Parameters
----------
width:
an interval specification. must be one of [minute, hour, day, week, month, year]
Examples
--------
>>> date_breaks(width = '1 year')
>>> date_breaks(width = '6 weeks')
>>> date_breaks('month... | a1808ccb7c09fcc3f2d0367f64cd3533eb63a33d | 3,633,279 |
def create_valid_url(url: str) -> str:
"""
Generate a video direct play url.
"""
return url | a04a22ec64b346be83b020745aeb33f74ca90b74 | 3,633,280 |
import numpy
def circular_weight(angle):
"""This function utilizes the precomputed circular bezier function
with a fit to a 10th order curve created by the following code block:
.. code-block:: python
x = numpy.arange(.5, 180, 0.5)
y = []
for i in x:
y.append(bezier.f... | 4341173c3e3584fcddbe04c60f7dd43fe859ac89 | 3,633,281 |
def parse_single_example(serialized, # pylint: disable=invalid-name
names=None,
sparse_keys=None,
sparse_types=None,
dense_keys=None,
dense_types=None,
dense_defaults=No... | aa2a7774a5b03e0b89b6a55c13a13ed45c1e700d | 3,633,282 |
def delta_date_feature(dates):
"""
Given a 2d array containing dates (in any format recognized by
pd.to_datetime), it returns the delta in days between each date and the
most recent date in its column
"""
date_sanitized = pd.DataFrame(dates).apply(pd.to_datetime)
return (date_sanitized
... | bfdde9fe12ffabb336d2f92b9bd3875782a9f8ff | 3,633,283 |
import torch
import timeit
def benchmark_training(model, opts):
"""Benchmarks training phase.
:param obj model: A model to benchmark
:param dict opts: A dictionary of parameters.
:rtype: tuple:
:return: A tuple of (model_name, list of batch times)
"""
def _reduce_tensor(tensor):
r... | 45f9328949e3385c1001db3dc2097d7a814455a4 | 3,633,284 |
import subprocess
def runprog(*args):
"""Runs specified program and args, returns (exitcode, stdout, stderr)."""
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return (p.returncode, out, err) | 2146d967c961f4c9ed1f62288436a82cc7a62189 | 3,633,285 |
def inhib_kin_query(inhib_pubchem_cid):
"""
Query to pull targeted kinases using inhib CID
:param inhib_pubchem_cid: string inhib CID
:return: Flask_Table Kinase object
"""
session = create_sqlsession()
q = session.query(Inhibitor).filter_by(inhib_pubchem_cid= inhib_pubchem_cid)
inh = q.... | cf06cd79e057e4bd7f6c8abc8db115a94cc51a0f | 3,633,286 |
from typing import Set
def abstract_methods_of(cls) -> Set[str]:
"""
Gets the abstract methods of a class.
:param cls: The class to get the abstract methods from.
:return:
"""
return getattr(cls, ABSTRACT_CLASS_ATTRIBUTE, set()) | 0cf9fa46433230e535bb01daaa27109ccb246aef | 3,633,287 |
from optparse import OptionParser
import os
def parse_cmd_line_args():
"""
Parse command line parameters
"""
parser = OptionParser()
parser.add_option("-m", "--model", dest="model", default='standard_glm',
help="Type of model to use. See model_factory.py for available types.... | 22f0eb365914f9fa915f3352152f29809db70944 | 3,633,288 |
def parameterized_qubit_qnode():
"""A parametrized qubit ciruit."""
def qfunc(a, b, c, angles):
qml.RX(a, wires=0)
qml.RX(b, wires=1)
qml.PauliZ(1)
qml.CNOT(wires=[0, 1]).inv()
qml.CRY(b, wires=[3, 1])
qml.RX(angles[0], wires=0)
qml.RX(4 * angles[1], wire... | e82a93b3f3c9c7d9a7c63c5f22c80e2248c1bdf4 | 3,633,289 |
import yaml
def fem_context( filename, comm=MPI.COMM_WORLD ):
"""
Create tensor-product spline space and mapping from geometry input file
in HDF5 format (single-patch only).
Parameters
----------
filename : str
Name of HDF5 input file.
comm : mpi4py.Comm
MPI communicator.
... | f5016a4df27699814622f9843706f5096052d92d | 3,633,290 |
def get_indicators_from_fred(start=start, end=end):
"""
Fetch quarterly data on 6 leading indicators from time period start:end
"""
# yield curve, unemployment, change in inventory, new private housing permits
yc_unemp_inv_permit = (
web.DataReader(["T10Y2Y", "UNRATE", "CBIC1",
... | 8ed26654d64ca8c5a08c74ecc48e326396ecb311 | 3,633,291 |
def permission_denied_exception_handler(exc, context):
"""If the object exist but the user does not have permission for it, change the status code and message."""
# Call REST framework's default exception handler first to get the standard error response.
response = exception_handler(exc, context)
if co... | c3abfb58419a9cd2e07d29b3340ba3042db93506 | 3,633,292 |
from typing import Optional
import ray
def get_current_placement_group() -> Optional[PlacementGroup]:
"""Get the current placement group which a task or actor is using.
It returns None if there's no current placement group for the worker.
For example, if you call this method in your driver, it returns No... | 5a7fd8cad03adaad2479bdb33cf2182c050dedf4 | 3,633,293 |
def _GenerateManifest(args, service_account_key_data, image_pull_secret_data,
upgrade, membership_ref, release_track=None):
"""Generate the manifest for connect agent from API.
Args:
args: arguments of the command.
service_account_key_data: The contents of a Google IAM service account... | af3553a3cbdc7c8bd75cafe5c48cfa06a72ec347 | 3,633,294 |
import uuid
import os
import io
def save_image(img_type, elem):
"""
Save post cover or user avatar to local filesystem in dev or to S3 in prod
:param img_type: 'avatars' or 'covers'
:param elem: post or user obj on which to save the image
:return: name of the file to be saved
"""
image = r... | 4a346963490c4b2f41542b19b7f537bbbb30438e | 3,633,295 |
import re
def check_conjunctions(sentence: str) -> list or None:
"""
Returns the list of messages about a punctuation error
with conjunctions if there is one.
"""
sentence = sentence.lower()
conjunctions = {'а', 'але', 'однак', 'проте', 'зате', 'хоч', 'хоча'}
errors = []
for word in co... | 9bbf6e72e431cf652cdac659e8e0a4da7b7a9b3c | 3,633,296 |
import numpy
def decompose(poly: PolyLike) -> ndpoly:
"""
Decompose a polynomial to component form.
In array missing values are padded with 0 to make decomposition compatible
with ``chaospy.sum(output, 0)``.
Args:
poly:
Polynomial to decompose.
Returns:
Decompose... | d2817904fb6a2f1977d92a99c75d640b5b869fca | 3,633,297 |
def letter_to_vec(letter):
"""returns one-hot representation of given letter
"""
index = ALL_LETTERS.find(letter)
return _one_hot(index, NUM_LETTERS) | 490aa2f3c5a9ddf7bf950c309f30c7753ea6628d | 3,633,298 |
def Hellinger2D(dist1, dist2, x_low=-np.inf, x_high=np.inf, y_low=None,
y_high=None):
""" Computes the Hellinger distance between two bivariate probability
distributions, dist1 and dist2.
inputs:
dist1: a function that returns the probability of x, y
dist2: a function... | 0541e44529d9c04916ee8ab88f2eaf4295b77256 | 3,633,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.