content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def update_internal_subnets(
self,
ipv4_list: list = [
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"169.254.0.0/16",
"224.0.0.0/4",
],
ipv6_list: list = [],
segment_ipv4_list: list = [],
non_default_routes: bool = False,
) -> bool:
"""Update the l... | ce1a11f2cbdb01c81fb01a13ba3d73c7ce5d0cf6 | 3,629,200 |
def prune_outside_window(boxlist, window, scope=None):
"""Prunes bounding boxes that fall outside a given window.
This function prunes bounding boxes that even partially fall outside the given
window. See also clip_to_window which only prunes bounding boxes that fall
completely outside the window, and clips an... | 9a16f0e4e55b7588e6a59402d058eb09e3c63c2a | 3,629,201 |
from typing import Optional
def cross_section(adjacency_matrices: npt.NDArray[np.int_],
rng: Optional[np.random.Generator] = None):
"""
Parameters
----------
adjacency_matrices :
rng :
Returns
-------
"""
if rng is None:
rng = np.random.default_rng()
... | e75435a5888f89cd202b5ff8ecfce65565a58f59 | 3,629,202 |
def get_threshold_otsu(image: npt.ArrayLike, blur_sigma=5):
"""Perform Otsu's thresholding with Gaussian blur."""
skimage_gaussian = get_image_method(image, "skimage.filters.gaussian")
skimage_otsu = get_image_method(image, "skimage.filters.threshold_otsu")
image = skimage_gaussian(image, sigma=blur_sig... | 0b1ea8e0652936697a47299743d090b0e665e1f3 | 3,629,203 |
def mask(batch_tokens, total_token_num, vocab_size, CLS=1, SEP=2, MASK=3):
"""
Add mask for batch_tokens, return out, mask_label, mask_pos;
Note: mask_pos responding the batch_tokens after padded;
"""
max_len = max([len(sent) for sent in batch_tokens])
mask_label = []
mask_pos = []
prob_... | 3d0951770b9f6e13ce7e0ef6a100cdd95e331bed | 3,629,204 |
def get_lr_curves(
spark, features_df, cluster_ids, kernel_bandwidth, num_pdf_points, random_seed=None
):
""" Compute the likelihood ratio curves for clustered clients.
Work-flow followed in this function is as follows:
* Access the DataFrame including cluster numbers and features.
* Load same s... | 2d00cfe1204a814c3782344af762f5fc5b398d5f | 3,629,205 |
def orred_filter_list(prefix, subfilters):
"""Produces Q-object for a list of dicts
Each dict's (key: value) pairs are ANDed together (rows must satisfy all k:v)
List items are ORred together (satisfying any one is enough)
"""
result = Q()
for filter in subfilters:
subresult = Q()
... | 81bea3472ea975fa84431b801e11ebdb108c2b1e | 3,629,206 |
import unittest
def get_unittests():
""" Return all of the unit tests """
directory_of_tests=get_testdirectory()
basic_suite = unittest.TestLoader().discover(directory_of_tests,pattern='basic_tests_*.py')
advanced_suite = unittest.TestLoader().discover(directory_of_tests, pattern='advanced_t... | 53a613a1c9463d3a0d239267b1cfa10f8d9a5625 | 3,629,207 |
def become_mapper_(mapper_idx, map_fun, input_files, n_mappers, n_reducers,
map_begin, map_end, unit_fun, reduce_factory,
load_balancing_scheme, input_files_delimiter, record_terminator,
mapper_output_template, mapper_idx_template):
"""
become mapper
... | fbbb4fee89b5e2d69e69ee5274ff9dd6a7b504dd | 3,629,208 |
from typing import Dict
from typing import List
def execute_action(arena: ActiveArena, unit: ActiveUnit, act: Dict) -> List[Dict]:
"""
Based on the type of `act`, executes the given action.
Returns a summary of the action's effects, conforming to the action_output_schema.
Mutates the given arena and/o... | c91bed4c185d31260ededc9f84b02848929d19ba | 3,629,209 |
import copy
def has_mutation(gm, example_inputs):
"""Check if the graph module has any form of mutation"""
# TODO - moco gives bad accuracy with Aliasing. gm is getting mutated in a bad way.
new_gm = copy.deepcopy(gm)
ShapeAliasingAndMutationProp(new_gm).run(*example_inputs)
for node in new_gm.gr... | 7b1a44f3389b5335f45574e22d5c9976dc4ab653 | 3,629,210 |
def comment_remove(obj_id, analyst, date):
"""
Remove an existing comment.
:param obj_id: The top-level ObjectId to find the comment to remove.
:type obj_id: str
:param analyst: The user removing the comment.
:type analyst: str
:param date: The date of the comment to remove.
:type date:... | e3c918960e28cbca567f719f53656ef80b1fb40f | 3,629,211 |
def eul2m_vector(in11, in12, in13, k1, k2, k3):
"""eul2m_vector(ConstSpiceDouble * in11, ConstSpiceDouble * in12, ConstSpiceDouble * in13, SpiceInt k1, SpiceInt k2, SpiceInt k3)"""
return _cspyce0.eul2m_vector(in11, in12, in13, k1, k2, k3) | fd3a7527698d7df289fff683fef75668bca5fa01 | 3,629,212 |
def helicsCreateMessageFederateFromConfig(config_file: str) -> HelicsMessageFederate:
"""
Create `helics.HelicsMessageFederate` from a JSON file or JSON string or TOML file.
`helics.HelicsMessageFederate` objects can be used in all functions that take a `helics.HelicsFederate` object as an argument.
**... | 02102f97823ef2f59bb5d3b3170c6a47cc11e436 | 3,629,213 |
def chain_template_as_nx_graph(chain: ChainTemplate):
""" Convert FEDOT chain template into networkx graph object """
graph = nx.DiGraph()
node_labels = {}
for operation in chain.operation_templates:
unique_id, label = operation.operation_id, operation.operation_type
node_labels[unique_i... | 8143f0563a9fc56c8bc02559fd90c0a65f5c6bf2 | 3,629,214 |
import os
def AbsoluteCanonicalPath(*path):
"""Return the most canonical path Python can provide."""
file_path = os.path.join(*path)
return os.path.realpath(os.path.abspath(os.path.expanduser(file_path))) | 31c9a4e6a7a52b856b0f7575fc6a231f2887fba5 | 3,629,215 |
def skip_if(expr, msg=""):
"""Skip the current substep and set _output to empty. Output
will be removed if already generated."""
if expr:
raise StopInputGroup(msg=msg, keep_output=False)
return 0 | 383b0edf96f2c088b5191a952970d6cccd481d06 | 3,629,216 |
import operator
def mergeGuideInfo(seq, startDict, pamPat, otMatches, inputPos, effScores, sortBy=None, org=None):
"""
merges guide information from the sequence, the efficiency scores and the off-targets.
creates rows with too many fields. Probably needs refactoring.
for each pam in startDict, retri... | bed13fdcdb6e32af64738b6d224412b34e066699 | 3,629,217 |
def get_distribution_centers_shipments(dc_id):
"""
Retrieve all shipments originating from the specified distribution center.
:param dc_id: The distribution center's id
:return: [{
"id": "123",
"status": "SHIPPED",
"createdAt": "2015-11-05T22:00:51.692765",
"updatedAt... | 62bc07a405eb4db6bb11c29adcad0a5ab9af10f4 | 3,629,218 |
from typing import Union
from datetime import datetime
def historical_summary(date: Union[None, str, datetime] = None, filter: str = ''):
"""
https://iextrading.com/developer/docs/#historical-summary
Args:
date: fixme
filter: https://iextrading.com/developer/docs/#filter-results
Retu... | a0d2364b81dd7735dcd797f8ba9696e670224b19 | 3,629,219 |
def runIW(before, after, aoi, scl, tScl, ag):
"""
Run the complete iteratively weighted change analysis
Parameters:
before (ee.ImageCollection): images representing the reference landscape
after (ee.ImageCollection): images representing the after condition
aoi: (ee.Geometry): ar... | 67261ee476727329c0144a3f416e8fb1c40828c3 | 3,629,220 |
def normalize_text(text, norm_type="stemming", pos=False, pipeline=None):
"""
Preprocess text data
:param str text:
:param str norm_type: "stemming" or "lemmatization" of None
:param bool pos: Only for lemmatization. If True add tags to tokens like "_NOUN"
:param Pipeline pipeline: for lemm... | 8c98cd3e931ec762c3b1b128c066aa34d4fc9e74 | 3,629,221 |
def make_field(
name: str,
dimensions: FieldDimensions,
is_temporary: bool = False
) -> Field:
""" Create a Field
:param name: Name of the field
:param dimensions: dimensions of the field (use make_field_dimensions_*)
:param is_temporary: Is it a temporary field?
"""
fie... | d01f9436a563ac911ba097c0f4a2918db8e4e0d4 | 3,629,222 |
from operator import add
def expand_to_point(b1, p1):
"""
Expand bbox b1 to contain p1: [(x,y),(x,y)]
"""
for p in p1:
b1 = add(b1, (p[0], p[1], p[0], p[1]))
return b1 | 5a79646403f7f9c2397aadb4f1826d8309eb8dcb | 3,629,223 |
import collections
def get_closing_bracket(string, indice_inicio):
"""Retorna o indice da '}' correspondente a '{' no indice recebido."""
if string[indice_inicio] != '{':
raise ValueError("String invalida")
deque = collections.deque()
for atual in range(indice_inicio, len(string)):
if ... | 5a865de5f5d3589e04f1c1e50f817ec20d8e712f | 3,629,224 |
def read_matrix():
"""Returns a matrix from the input integers, spit by ', '"""
n = int(input())
matrix = []
for _ in range(n):
row = []
for x in input().split(', '):
row.append(int(x))
matrix.append(row)
return matrix | 7bd1e72fbf6c871324a02b0e11a2f10c2830bed2 | 3,629,225 |
def format_time_trigger_string(timer_instance):
"""
:param timer_instance: either instance of RepeatTimer or EventClock
:return: human-readable and editable string in one of two formats:
- 'at Day_of_Week-HH:MM, ..., Day_of_Week-HH:MM'
- 'every NNN'
"""
if isinstance(timer_instance, Repeat... | 8d2f5399f4b96b3855d18b78c809bad6b90fb5df | 3,629,226 |
import importlib
def get_class_from_string(class_string: str):
"""Get class or function instance from a string, interpreted as Python module.
:param class_string:
:return:
"""
class_name = class_string.split(".")[-1]
module = class_string.replace(f".{class_name}", "")
lib = importlib.impor... | 5ffb49c23c815b4d3511b93a97a8a9aad4e30adb | 3,629,227 |
def safe_power(a, b): # pylint: disable=invalid-name
"""a limited exponent/to-the-power-of function, for safety reasons"""
if abs(a) > MAX_POWER or abs(b) > MAX_POWER:
raise NumberTooHigh("Sorry! I don't want to evaluate {0} ** {1}".format(a, b))
return a**b | 10aa89e299b75a361b0842d9acf56cf6390ca160 | 3,629,228 |
def ConcateMatching(vec1, vec2):
"""
ConcateMatching
"""
#TODO: assert shape
return fluid.layers.concat(input=[vec1, vec2], axis=1) | e54350fd17c4dc12cbb75f8146bab4c072c9523a | 3,629,229 |
import copy
import random
def defaults( d= cli(
cohen = .3
,data = "data/weather.csv"
,far = .9
,k = 1
,m = 2
,mostrest = 3
,p = 2
,seed = 1
,train = .66
,tiny = .6
)):
"""Calling `default` will return a fresh copy of... | 47fd9146fb6256123b6281897f2a0ea802fe2da4 | 3,629,230 |
import itertools
def _racemization(compound, max_centers=3, carbon_only=True):
"""Enumerates all possible stereoisomers for unassigned chiral centers.
:param compound: A compound
:type compound: rdMol object
:param max_centers: The maximum number of unspecified stereocenters to
enumerate.... | ecba340db624c48ba3518f101e703f803fb4133a | 3,629,231 |
def stop_gradient(variables):
"""Returns `variables` but with zero gradient with respect to every other
variables.
"""
return KerasSymbol(mx.sym.BlockGrad(variables.symbol)) | 9a75aa0abccd1173005cfd3b98927a3d8b2bc3a2 | 3,629,232 |
def get_repartition_emission_pies(data):
"""
This function will create a figure with 3 pies describing the repartition per building of the emission for electricity / gas / total
"""
fig = make_subplots(
rows=1,
cols=3,
specs=[[{"type": "domain"}, {"type": "domain"}, {"type": "do... | e8210783e3df0b79c00c189f39e6f74151c3993f | 3,629,233 |
def get_next_video_id(database_session: Session):
"""Returns what the next vid id will be"""
return database_session.query(func.max(models.Video.id)).scalar() + 1 | f176cc94f2683df8e6c9cde52f53a4097a2ed2c9 | 3,629,234 |
import os
def system_supports_plotting():
"""
Check if x server is running
Returns
-------
system_supports_plotting : bool
True when on Linux and running an xserver. Returns None when
on a non-linux platform.
"""
try:
if os.environ['ALLOW_PLOTTING'].lower() == 't... | 42af0e67348df85bbe7bc32dd50faa65be95b4c5 | 3,629,235 |
def parse_args():
"""Command-line argument parser for testing."""
# New parser
parser = ArgumentParser(description='Noise2Noise adapted to X-ray microtomography')
# Parameters
parser.add_argument('-d', '--data', help='dataset root path', default='../data')
parser.add_argument('--load-ckpt', he... | eda63b9e9b90f26a02e8cf5c3c6e85d1161385a6 | 3,629,236 |
def sparse_to_dense(sparse_indices, output_shape, sparse_values, default_value=0):
"""Converts a sparse representation into a dense tensor.
Example::
- sparse_to_dense([[0, 0], [1, 1]], [2, 2], [3, 3], 0) = [[3, 0], [0, 3]]
Parameters
----------
sparse_indices : tvm.te.Tensor
A 0-D, ... | 672a4190086d2086fa9ac93cecc6a8f1f02825ce | 3,629,237 |
def os_supported():
"""Check if current OS is supported
Returns:
bool
"""
return is_os('Windows') | 8d144f884cb4ba0df9d2f27186c8bed0bca48cf1 | 3,629,238 |
def put_path_to_db(req_path: ReqPathPutTransact):
"""Put learning path to DynamoDB"""
try:
transact_items = path_input.transact_update_path(path=req_path)
# return transact_items
res = db.client.transact_write_items(
ReturnConsumedCapacity="INDEXES", TransactItems=transact_i... | a9e36870c3922362aca050abe683fc681402e7a0 | 3,629,239 |
import zlib
def get_hash(value, max_hash):
"""Calculate split hash factor"""
return zlib.adler32(str(value).encode()) % max_hash + 1 | 55a703997e4a8bc852def35d0cd418f009998f7e | 3,629,240 |
import shutil
def copy_proto_go_source(target, source, env):
"""Copy go source file generated by protobuf into go standard directory. """
shutil.copy2(str(source[0]), str(target[0]))
return None | 33a10c78ec3db952a738bed523fa333e0c60cb4e | 3,629,241 |
def add_credentials(request):
"""
Create credentials for SolarWinds integration.
"""
action_url = reverse('add_credentials')
if request.method == 'POST':
form = SolarWindsConectionForm(request.POST)
if form.is_valid():
form.save()
msg = "The SolarWinds credent... | dbf26f7b1c7cc9d9b61a1d2f164849ff93792e2e | 3,629,242 |
def parsePifKey(pif, key):
"""Parse a single pif key for single scalar values; return nan if no scalar found.
:param pif: PIF to access
:type pif: pif
:param key: key to access data
:type key: string
:returns: scalar value or np.nan
:rtype:
"""
if (key in ReadView(pif).keys()):
... | f7db7ac5b05573bf3d03b268c05d92ccf884a577 | 3,629,243 |
def check_multimetric_scoring(estimator, scoring):
"""Check the scoring parameter in cases when multiple metrics are allowed.
Parameters
----------
estimator : sklearn estimator instance
The estimator for which the scoring will be applied.
scoring : list, tuple or dict
A single str... | 8ca3e82e63631d3e8642cf88e5a0c5d4faa9f522 | 3,629,244 |
def dummy_workflow():
"""Return dummy Snakemake workflow object"""
mock_workflow = MagicMock()
return mock_workflow | 8400c6fbd1851e666676945e84413735090371c0 | 3,629,245 |
from distributed import MultiLock
import contextlib
def get_multi_lock_or_null_context(multi_lock_context, *args, **kwargs):
"""Return either a MultiLock or a NULL context
Parameters
----------
multi_lock_context: bool
If True return MultiLock context else return a NULL context that
d... | 962f612367158c3f27364b5ec9cd4460c208d248 | 3,629,246 |
import os
def load_cme_scenarios():
"""
Load in the CME scenarios from their HDF5 file and return them in a dictionary.
"""
project_dirs = get_project_dirs()
datafile_path = os.path.join(project_dirs['out_data'], 'CME_scenarios.hdf5')
datafile = h5py.File(datafile_path, 'r')
cme_scena... | 7081870b8bfcc28e5132a1a5e1bbdff4f36752c3 | 3,629,247 |
def argument_decorator(f):
"""Decorates a function to create an annotation for adding parameters
to qualify another.
.. literalinclude:: /../examples/argdeco.py
:lines: 5-25
"""
return parser.use_mixin(
DecoratedArgumentParameter, kwargs={'decorator': f}) | 2ce86145d605cbf211d9fc7170b6721311b8c146 | 3,629,248 |
async def get_open_api_endpoint(api_key: APIKey = Depends(get_api_key)):
"""To check if my authorisation process was succesfull"""
return "Certification is accepted" | ecfb36f6f9262425dc06f005569e927c5e7803fd | 3,629,249 |
def ReadMaleResp2015():
"""Reads respondent data from NSFG Cycle 9.
returns: DataFrame
"""
usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw',
'evrmarry', 'wgt2013_2015',
'marend01', 'rmarital', 'fmarno', 'mar1diss']
df = ReadResp('2013_2015_MaleSetup.dct... | 47b89995c8064126af9ff3d91d8f303dd8145628 | 3,629,250 |
def keyword_list(request):
"""
This is a view that will show all the keywords.
This view should also show the number of datasets for each keyword.
Maybe that is a template problem.
"""
k = Keyword.objects.all()
if "q" in request.GET:
q = request.GET["q"]
keyword_list = k.fil... | 0548dec3226c20b69157780701ccb72782615f4f | 3,629,251 |
import dateutil
def parse_date(datestr):
""" Parses an ISO 8601 formatted date from Gophish """
return dateutil.parser.parse(datestr) | 6063266dae4264b1c889d0570f23c1a4cf6cd26c | 3,629,252 |
def block_resnet152(pretrained=False, progress=True, device='cpu', **kwargs):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _block_resnet(... | 8a2c4c8f4d579729432b81412eceae8295c12aad | 3,629,253 |
def encode_categorical_features(dataframe, categorical_features):
"""Encode categorical features and add to the column of the dataframe."""
transformations = []
# Ordinal encoding
ordinal_encoded_output_cols = ["ordinal_indexed_"+categorical_feature for categorical_feature in categorical_features]
indexer = Stri... | 4a80a2d75f3f44a08e2fcb463385d1c775e84e46 | 3,629,254 |
def gen_nondeferred_mock(return_value=_sentinel, func_dict=None, spec=None, name='NDMock',
side_effect=_sentinel):
"""
Get a mock which cannot be mistaken for a Deferred
@param return_value : A return value, passed directly to the Mock constructor if set
@param func_dict: A dic... | 2efe00e3bf0d24d12b506d67515633883cf88b3b | 3,629,255 |
import os
def npm_localfile(package, version):
"""Get the local filename of a npm package"""
return os.path.join("npm2", npm_filename(package, version)) | 35edec7ef271425d5211cd546a246dd8f5ddbcb0 | 3,629,256 |
import re
def url2domain(url):
""" extract domain from url
"""
parsed_uri = urlparse.urlparse(url)
domain = '{uri.netloc}'.format(uri=parsed_uri)
domain = re.sub("^.+@", "", domain)
domain = re.sub(":.+$", "", domain)
return domain | 193521f9beded8ad22999f42dd2e8c1476cc1534 | 3,629,257 |
def rhythm_track(file_path: PathType) -> dict:
"""Perform rhythm track analysis of given audio file.
Args:
file_path: Path to audio file.
Returns:
Rhythm track parameters and data.
"""
snd = load_audio(file_path)
onsets = FluxOnsetDetector(snd.data, snd.fps)
segs = segment... | c7ed8e9ed1af3584da781ecb122f71eec3ba9b63 | 3,629,258 |
import os
def get_package_dbpath():
"""Return the default database path"""
return os.path.join(os.path.abspath(os.path.dirname(__file__)), DBNAME) | 04641c162e66c1e50f1638493257ded893925910 | 3,629,259 |
def repo(request, repo_id):
"""Show repo page and handle POST request to decrypt repo.
"""
repo = get_repo(repo_id)
if not repo:
raise Http404
if request.method == 'GET':
return render_repo(request, repo)
elif request.method == 'POST':
form = RepoPassowrdForm(reques... | 8adac803f4bf7785e5c79db56447824ecd2c6a2e | 3,629,260 |
def plot_predicted_treatment_effect(cf, figsize, npoints, num_workers):
"""Plot the predicted treatment effect from a Causal Forest.
Args:
cf (CausalForest): Fitted Causal Forest.
figsize (tuple): The figure size.
npoints (int): Number of points for meshgrid.
num_workers (int): ... | b36ef7359bd4d899c6b8b65330684659d6627758 | 3,629,261 |
import sys
def create_progress_bar(total, desc, **kwargs):
"""Helper creating a progress bar instance for a given parameters set.
The bar should be closed by calling close() method.
"""
return ProgressBar(
total=total,
desc=desc,
# XXX: click.get_text_stream or click.get_binar... | eaf49d5644f59cbce5c8ffb433c71602f3c6433d | 3,629,262 |
def central_angle_names(zma):
""" distance coordinate names
"""
return vmat.central_angle_names(vmatrix(zma)) | 1fbb687e01e77489af822d9533bd784b8035300a | 3,629,263 |
def cylinder_circles(nodeA, nodeB, radius, element_number=10):
"""
Return list of two circles with defined parameters.
"""
vector = (np.array(nodeA) - np.array(nodeB)).tolist()
ptsA = circle(nodeA, vector, radius, element_number)
ptsB = circle(nodeB, vector, radius, element_number)
return ... | a5d60cc5f1db67f8c9afef0ecc6d504734e65cfd | 3,629,264 |
def get_at_index(obj, index):
"""Возвращает объект списка с определенным индексом.
Индексация списка 1...n
"""
try:
return obj[index - 1]
except IndexError:
return None | 8a70a6b7cff6bcaff173a5ebd258d74d271964ca | 3,629,265 |
def mass_distance_matrix(ts, query, w):
"""
Computes a distance matrix using mass that is used in mpdist_vector
algorithm.
Parameters
----------
ts : array_like
The time series to compute the matrix for.
query : array_like
The time series to compare against.
w : int
... | e301f3a28ac08893623fff5034c2d319705c6844 | 3,629,266 |
def create_tube(inner_radius=0.5, outer_radius=1.0, height=1.0, slices=64, stacks=64):
"""generates the vertices, normals, and indices for a tube mesh
:param inner_radius: tube inner radius
:type inner_radius: float
:param outer_radius: tube outer radius
:type outer_radius: float
:param height:... | ebf1f125e1e060fb0082351e3958316059408d86 | 3,629,267 |
import requests
import json
def get_room_id(room_name):
"""
This function will find the Spark room id based on the {room_name}
Call to Spark - /rooms
:param room_name: The Spark room name
:return: the Spark room Id
"""
payload = {'title': room_name}
room_number = None
url = SPARK_... | f859212e994ae39612a0510adf86735269b69992 | 3,629,268 |
def openstack_ceilometer(today, **kwargs):
"""
Pricing plugin for openstack ceilometer.
"""
clear_ceilometer_stats(today)
new = total = 0
for site in settings.OPENSTACK_CEILOMETER:
logger.info(
"Processing OpenStack ceilometer {}".format(site['WAREHOUSE'])
)
t... | e3eed79b8231f8d718f5e51d824eb93e565fb7c2 | 3,629,269 |
def spkezp_vector(k1, in11, str1, str2, k2):
"""spkezp_vector(SpiceInt k1, ConstSpiceDouble * in11, ConstSpiceChar * str1, ConstSpiceChar * str2, SpiceInt k2)"""
return _cspyce0.spkezp_vector(k1, in11, str1, str2, k2) | 5d044d5c9cc8cc329dd2d8d7ad5352898c963469 | 3,629,270 |
import math
def rowSpacing(beta, sazm, lat, lng, tz, hour, minute):
"""
This method determines the horizontal distance D between rows of PV panels
(in PV module/panel slope lengths) for no shading on December 21 (north
hemisphere) June 21 (south hemisphere) for a module tilt angle beta and
surface... | 3df45c808e6ba99a10a743f30f0eea37d46bcaa6 | 3,629,271 |
def _check_buildopts_arches(mmd, arches):
"""
Returns buildopts arches if valid, or otherwise the arches provided.
:param mmd: Module MetaData
:param arches: list of architectures
:return: list of architectures
"""
buildopts = mmd.get_buildopts()
if not buildopts:
return arches
... | 79a27005bbae82378cf4307ec6c6dcd58007ecdb | 3,629,272 |
def hopwise_qry_encoder(qry_seq_emb,
qry_input_ids,
qry_input_mask,
is_training,
bert_config,
qa_config,
suffix="",
project=True,
project_dim=No... | 1923129f58d31b96cf985731785f96280cf0d814 | 3,629,273 |
def construct_acyclic_matching_along_gradients(morse_complex,
delta=np.inf):
""" Finds an acyclic matching in filtration order along gradients
Inspired by [MN13] p. 344 MorseReduce
:param morse_complex: A morse complex
:param delta: Only construct matches... | d6a98b49a9d2e10d5c3d349c6ecf0bbea0baf845 | 3,629,274 |
def r2tth(x,dist):
"""Convert a numpy array of azimuthal radii to 2 theta"""
return np.arctan(x/dist)*180/np.pi | 2d500e8543507de561994d92ea8ed0a03ad28186 | 3,629,275 |
def is_notebook():
"""
code from https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook
"""
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
... | 1db42ba465db00b0cf3f633b389bb251a5f99363 | 3,629,276 |
def crypto_lettre(dico: dict, lettre: str) -> str:
"""
Fonction qui renvoie une lettre cryptée d'après le dictionnaire associé
:param ASCIIrandom:
:param lettre: lettre MAJUSCULE
:return: la lettre cryptée en MAJUSCULE
"""
return dico[lettre] | af46af6e3221587731b1c522bf50b8b75563835b | 3,629,277 |
def read_tusc(path):
"""Helper function to read in the Tuscany shapefile"""
path_shapefiles, regions, provinces, territories, municipalities, crs = read_files.read_shapefile_data(path, 'shape_files_path.json')
df_reg_tus = read_files.read_shapefiles_in(True, path_shapefiles, regions, crs)
return df... | e4d3bc257e545eb8b1246b2b10685fe6d7f00fbd | 3,629,278 |
def train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image,
correct_label, keep_prob, learning_rate):
"""
Train neural network and print out the loss during training.
:param sess: TF Session
:param epochs: Number of epochs
:param batch_size: Batch s... | 6ddaa1826fd84e6280cf50c41d1dc9277f79122b | 3,629,279 |
import warnings
def preprocess_config(config, path, all_cols=True, model_cols=None, modify_config=None):
"""Preprocess the config
Args:
* config: original config
* path: path to load column names
Returns:
* config: preprocess config.
If design_all_cols is true, then read col_na... | 9f23547ffdc685f971877635fd12bcb7d72ad8dc | 3,629,280 |
def monoscale(array, color=MONOSCALE_SHADOWLEVEL, as_type=None, slice_size=SLICE_SIZE):
"""
Converts a grayscale array into a monoscale array.
This deletes shadow level 1 and sets the other shadow values to a uniform value.
The Poisson spot markings remain unchanged.
Note: After conversion, the opt... | de92f24ba539b35f60abaa9c2e09b59fb2198d52 | 3,629,281 |
def _mergeChannels(st):
"""
function to find longest continuous data chunck and discard the rest
"""
st1 = st.copy()
st1.merge(fill_value=0.0)
start = max([x.stats.starttime for x in st1])
end = min([x.stats.endtime for x in st1])
try:
st1.trim(starttime=start, endtime=end)
e... | c656417eca68a97c8e4f152fb0b82b23ab61d48c | 3,629,282 |
from typing import List
import re
def create_pattern(templates: List[str], input_str: str, pretty: bool = False):
"""
create all patterns based on list of input templates using the input string.
Args:
templates: list of templates/stencils
input_str: string to apply templates on to create... | 8ac0af7d5a55291804a3c98ec7d3176667cc729c | 3,629,283 |
import numpy
def dehaze(
image: xpArray,
size: int = 21,
downscale: int = 4,
minimal_zero_level: float = 0,
correct_max_level: bool = True,
in_place: bool = True,
internal_dtype=None,
):
"""
Dehazes an image by means of a non-linear low-pass rejection filter.
Parameters
--... | 14b8624ce88c6b4efac4b20ef98bd4d2a12eece1 | 3,629,284 |
from datetime import datetime
import requests
def token_price_chart_arken(token, symbol):
"""Lookup for prices via Arken API and return price chart image"""
timeframe = get_timeframe(INTERVAL) * 50 # Number of candlesticks
end_time = datetime.now()
# Convert datetime to Unix time
start_time = in... | c3a69a52099ec793e19e19d87f16dcec82181ec9 | 3,629,285 |
def code_info(x, version, is_pypy=False):
"""Formatted details of methods, functions, or code."""
return format_code_info(get_code_object(x), version, is_pypy=is_pypy) | b9f1d6343e15eabfc2903f933d59d670c7bf7dc8 | 3,629,286 |
def substrings(a, b, n):
"""Return substrings of length n in both a and b"""
substrings = []
a_substrings = get_substrings(a, n)
b_substrings = get_substrings(b, n)
# For every substring in list of substrings a:
for a_substring in a_substrings:
# For every substring in list of substrings... | cfe89690ce518b55ed3662153c69890a1fdf79c1 | 3,629,287 |
import sys
def all_ids(conn, protein=False, verbose=False):
"""
Get all the available IDs in the database
:param conn: the database connection
:param protein: Whether the object refers to protein (True) or DNA (False). Default=DNA
:param verbose: More output
:param verbose: More output
:re... | 7bf0d4ef30a75d281bf70cfa2a2cc2159ae8a88c | 3,629,288 |
import torch
def mc_control_epsilon_greedy(env, gamma, n_episode, epsilon):
"""
Obtain the optimal policy with on-policy MC control with epsilon_greedy
@param env: OpenAI Gym environment
@param gamma: discount factor
@param n_episode: number of episodes
@param epsilon: the trade-off between ex... | 5706961696f23c961906ce52125dcee5d6c0e0a7 | 3,629,289 |
import logging
import os
def v_slide(params):
"""
"""
paths = Paths()
try:
try:
scn_file = OpenSlide(paths.slice_80)
except OpenSlideUnsupportedFormatError:
logging.error("OpenSlideUnsupportedFormatError!")
return
except OpenSlideError:
... | 470b0cbcae0f92f78e9666e9754685a98f1c6d3b | 3,629,290 |
def svn_wc_maybe_set_repos_root(*args):
"""
svn_wc_maybe_set_repos_root(svn_wc_adm_access_t adm_access, char path, char repos,
apr_pool_t pool) -> svn_error_t
"""
return _wc.svn_wc_maybe_set_repos_root(*args) | 10d4e3d3fe55279d32982ab1921640787b1cdf48 | 3,629,291 |
def graph_semantics(g):
"""Convert a networkx.DiGraph to compounds and reactions for grid_land."""
compounds = {}
reactions = {}
for node, attributes in g.nodes.items():
if attributes.get("reaction"):
reactants = [e[0] for e in g.in_edges(node)]
products = [e[1] for e in ... | 34508120a21992b3260001e795a27fec7f22025e | 3,629,292 |
def fetching_latest_quiz_statistics(request_ctx, course_id, quiz_id, all_versions, **request_kwargs):
"""
This endpoint provides statistics for all quiz versions, or for a specific
quiz version, in which case the output is guaranteed to represent the
_latest_ and most current version of the quiz.
... | 60be2d9b0eacc6b9d9f6863c86f9ee569cc9fa59 | 3,629,293 |
import os
def make_api_key(size=32):
"""Generate a random API key, should be as random as possible
(not predictable)
:param size: the size in byte to generate
note that it will be encoded in base58 manner,
the length will be longer than the aksed size
"""
# TODO: os.urandom collec... | 0d847406ee56b52194d99341aab5b974dc252172 | 3,629,294 |
def relocate_estimates_data(ws):
"""
"""
### Country group
ws = relocate(ws, 'B', 7, 11, 'B', 34)
ws = relocate(ws, 'D', 7, 11, 'C', 34)
ws = format_numbers(ws, ['C'], (34,40), 'Comma [0]', 3)
ws = relocate(ws, 'B', 7, 11, 'E', 34)
ws = relocate(ws, 'E', 7, 11, 'F', 34)
ws = format... | 0f36e12275250b8642f117a03a6018425cdb72d6 | 3,629,295 |
def replace_channel_in_key(meta,new_band_id):
"""
Replace the band id in the CX header key.
Parameters
----------
meta : str
CX line header.
new_band_id : int
id for the new (zoom) band.
Returns
-------
new_meta : str
new CX line header.
... | 3d6e365b83985262690a5482c44a8d7afe5cda2f | 3,629,296 |
def check_cells_fit(cell_no, min_cell_distance, space_range=[[0,10],[0,10],None]):
""" given the number of cells (cell_no), and the minimal distance
between the cells and the space_ranges (x,y,z) it returns True if the
cells can fit within this range and False if not. If any of the
dimensions does not... | b2fa2cd1d7d84d6ef74a408c10293e88299987cf | 3,629,297 |
import argparse
import os
def parse_args() -> argparse.Namespace:
"""Parse CLI arguments.
:return: Namespace object holding parsed arguments as attributes.
This object may be directly used by garminexport/garminbackup.py.
"""
parser = argparse.ArgumentParser(
prog="garminbackup",
... | 383e75d019eb0d744041b66db981374c15c30a71 | 3,629,298 |
import io
def _read_sub_atoms(atom: tuple) -> list:
"""
A special method for parsing a stream that isn't from the
original file.
:param atom: a tuple containing atom data
:return: a set of sub atoms
"""
byte_stream = io.BytesIO(atom[2])
atoms = _read_atoms(byte_stream, atom[0] - 8)
... | 36faa5ae07f52671b2b9f407b690feb074321cdf | 3,629,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.