content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def convert_to_azimuth(angle):
"""Converts Near 180 to -180 angles to Azimuth Angles. Will also normalize any number to 0-360 .
@param: angle - angle denoted in terms of 180 to -180 degrees
@returns angle - angle 0 to 360"""
if angle <= 180 and angle > 90:
azimuth_angles = 360.0 - (angle - 90)
... | cb2fa989297642d9089812426559dbf994096821 | 668,661 |
def get_clearance(context, box, collapsed_margin=0):
"""Return None if there is no clearance, otherwise the clearance value."""
clearance = None
hypothetical_position = box.position_y + collapsed_margin
# Hypothetical position is the position of the top border edge
for excluded_shape in context.excl... | cb84dda15fac306ce5731fda3a57b42aa418a0c5 | 668,663 |
import ast
def ast_expr_from_module(node):
"""
Get the `ast.Expr` node out of a `ast.Module` node.
Can be useful when calling `ast.parse` in `'exec'` mode.
"""
assert isinstance(node, ast.Module)
assert len(node.body) == 1
assert isinstance(node.body[0], ast.Expr)
return node.body[0].... | 0536c6cae807ce92ca423de067b016a8ff555e49 | 668,664 |
def _get_params(model):
"""Get number of params in a model."""
return model.coefs.shape[0] | 4ec4603a4004f25980e5332705fdbbeb8e48af45 | 668,666 |
import math
def dInd_calc(TNR, TPR):
"""
Calculate dInd (Distance index).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: dInd as float
"""
try:
result = math.sqrt((... | 20134d302553f65de081876a501a9bb16a697cd6 | 668,667 |
def uninitialized(hist, verif, verif_dates, lead):
"""Uninitialized forecast uses a simulation without any initialization (assimilation/nudging). Also called historical in some communities."""
lforecast = hist.sel(time=verif_dates[lead])
lverif = verif.sel(time=verif_dates[lead])
return lforecast, lveri... | 18e929ccdd5c7ec24874517a91b3619d016d70ac | 668,668 |
import unicodedata
def normalize_unicode(text):
"""
Normalizes a string by converting Unicode characters to their simple
form when possible. This is done by using Normal Form KC of a string.
For example, the non-breaking space character (xa0) will be converted
to a simple space character.
Refe... | 3e197fb5489e5623612bb2c062b6bc13aebddc22 | 668,669 |
import math
def wgs_to_tile( latitude, longitude, zoom):
"""Get google-style tile cooridinate from geographical coordinate
Note:
Note that this will return a tile coordinate. and a tile coordinate
is located at (0,0) or origin of a tile.
all tiles are 256x256. there are as many gps locations in... | a9908049ce74259b1141af00e849779cbdee01f6 | 668,670 |
def mils(value):
"""Returns number in millions of dollars"""
try:
value = float(value) / 1000000
except (ValueError, TypeError, UnicodeEncodeError):
return ''
return '${0:,}M'.format(value) | 2dcbcb3b4a731c2b76ff348a398e469b0f493174 | 668,671 |
def drawSensorAsMarker(ax, data):
"""Draw Sensor marker, these marker are pickable."""
elecsX = []
elecsY = []
for i in range(len(data.sensorPositions())):
elecsX.append(data.sensorPositions()[i][0])
elecsY.append(data.sensorPositions()[i][1])
electrodeMarker, = ax.plot(elecsX, ele... | fb078908e115681e18ad1d831b0b92729e5ca9e0 | 668,673 |
import sys
def load_text_and_convert(text_file, lex):
""" convert unicode text to single character graphemic representation """
utt_ids = []
text = []
with open(text_file, "r", encoding="utf-8") as fpr:
for line in fpr:
line_str = ""
words = line.strip().split()
... | fe0f84a65b8c60d69def0437813782376b026b54 | 668,674 |
def get_integer(prompt):
"""
Get an integer from standard input (stdin).
The function keep looping and prompting until a valid
`int` is entered.
:param prompt: The string user will see
when prompted for input
:return: the `int` user has entered
"""
while True:
temp = in... | 83f10689655846c6ee364dd1c25c7ffca0ef132f | 668,675 |
def dashboard(request):
"""Logged in user landing page."""
return {} | 3cbce58961b9cce10b14c8775a9308d8c09f907a | 668,676 |
import argparse
def parse_args():
"""Parse arguments from the command line."""
parser = argparse.ArgumentParser("Test latest Aurora model Aurora "
"Testing in simulator.")
parser.add_argument('--save-dir', type=str, default="",
help="direcotry t... | d47c0836bf27bf473ba5b23c9f9aca0683780eab | 668,677 |
import os
def get_pio_asset(asset):
"""
Searches for a PIO-compiled utility and compiles it
if it is not available.
"""
asset_filepath = f".pio/build/{asset}/program"
if not os.path.exists(asset_filepath):
print(f"Compiling PlatformIO target {asset}.")
os.system(f"pio run -e ... | 1e2224d02e91c957fb61c39f5918a9be4c876b8f | 668,679 |
from typing import List
from typing import Dict
def dedup(l: List[str], suffix: str = "__", case_sensitive: bool = True) -> List[str]:
"""De-duplicates a list of string by suffixing a counter
Always returns the same number of entries as provided, and always returns
unique values. Case sensitive compariso... | 7c7e7ce2ca6446cf0b76df34a9ec66df255ba9eb | 668,680 |
def render_sync_enum_value_op(autogen_context, op):
""" """
return "op.sync_enum_values(%r, %r, %r, %r)" % (
op.schema,
op.name,
sorted(op.old_values),
sorted(op.new_values),
) | e665cd196613e85d0c6e10ca2ecf7c9fca0fb4d2 | 668,681 |
import csv
def read_from_csv(csv_file):
""" Reads data from a CSV file. """
print("Reading from CSV file...")
data = []
reader = csv.reader(csv_file, delimiter=',')
for row in reader:
try:
data.append((float(row[0]) if row[0] != '-' else None, float(row[1]) if row[1] != '-' e... | b1d40ec028729c314cea3c2ff592498b89b134fa | 668,682 |
import re
def word_tokenize(text):
"""Split on whitespace and punctuation."""
return re.findall(r'\w+|[^\w\s]', text, re.UNICODE), None | 10c96869da8268c1464750e72256e8e69f350a58 | 668,683 |
def cm2inch(*tupl):
"""
Convert a value or tuple of values from cm
to inches.
Source: https://stackoverflow.com/a/22787457
Input
---
tupl : float, int or tuple of arbitrary size
Values to convert
Returns
---
Converted values in inches.
"""
inch = 2.54
if is... | 8563bc70c8a63e3e7791e045134cbb0ac2707835 | 668,684 |
import os
import shutil
def fncDir(tmpDir):
"""A temporary folder for a single test function."""
fncDir = os.path.join(tmpDir, "f_temp")
if os.path.isdir(fncDir):
shutil.rmtree(fncDir)
if not os.path.isdir(fncDir):
os.mkdir(fncDir)
return fncDir | 7646a1c01f42d0b01f582421016aa082e7c15f21 | 668,685 |
def my_partition_id():
"""Return the short ID (not UUID) of the current partition, as an int."""
with open('/proc/ppc64/lparcfg') as lparcfg:
for line in lparcfg:
if line.startswith('partition_id='):
return int(line.split('=')[1].rstrip()) | 65c268c3bac577f79b59f137e7bb2d67bd80b5ad | 668,686 |
def SplitBlobName(layer_name, blob_name, blob_idx, split_idx):
"""
Used for caffe parser.
"""
return "_".join([layer_name, blob_name, str(blob_idx), "split", str(split_idx)]) | c13d07107f7e8b41ba4c6a054871640598f2d3a6 | 668,687 |
import torch
def directional_derivatives(lin_op, directions, device):
"""``lin_op`` represents a curvature matrix (either ``GGNLinearOperator`` or
``HessianLinearOperator`` from ``vivit.hessianfree``). ``directions`` is a
``D x nof_directions`` matrix, where ``nof_directions`` directions are stored
co... | b91f1f09159d1f09933f007b3b1b4cec1da3513d | 668,688 |
def square_root(a):
"""returns an estimate of the square root of a"""
x = a - 1
if x > 0:
while True:
y = (x + a/x) / 2
if y == x:
break
x = y
return x | 6955d6e3b6b0c870e9f4033c2eddf478645b0956 | 668,689 |
def apply_ant_t_delay(scan_rad):
"""Accounts for antenna time delay by extending the scan rad
Gets the "true" antenna radius used during a scan. Assumes ant_rad
is measured from the black-line radius on the plastic antenna stand.
Uses formula described in the M.Sc. thesis of Diego
Rodriguez-Herrera... | e6a79999a2eb000d7436e6a56f45b87663bdd71c | 668,691 |
import math
def compute_mcc(tp, fp, tn, fn):
"""
Compute the Matthew correlation coefficient.
Regarded as a good measure of quality in case of unbalanced classes.
Returns a value between -1 and +1. +1 represents perfect prediction, 0 random, and -1 total disagreement
between prediction and observa... | 254bb7df12fe1059f07605f67089906ae2ffb8ff | 668,693 |
def clean_text(text, patterns):
"""
Applies the given patterns to the input text. Ensures lower-casing of all text.
"""
txt = text
for pattern in patterns:
txt = pattern[0].sub(pattern[1], txt)
txt = ''.join([letter for letter in txt if (letter.isalnum() or letter.isspace())])
retur... | 78f221a35549f40b2a2b81596901a63c528cae20 | 668,694 |
def device(site_client, attributes):
"""Return a Device object."""
return site_client.sites(site_client.default_site).devices.post(
{
'hostname': 'foo-bar1',
'attributes': {
'foo': 'test_device'
},
}
) | a969559e1bb9e4bfb01e3150a012d7c013252b98 | 668,695 |
import numpy
def note_density(eventList, time_resolution=0.005, duration=False):
"""Returns note density (number of simultaneous notes) statistics
Returns:
(mean, std, min, max)
If duration is set to True, then these statistics will be weighted acording
to their time.
The time resolution is... | 6f7b8c76c7dc52e76e5c53eecd0c6ae213a3544c | 668,696 |
def rk4_step(f, y, t, dt, params):
""" Returns the fourth order runge-kutta approximation of the change in `y` over the
timestep `dt`
Parameters
----------
f (callable): accepts `y`, `t` and all of the parameters in `params`
y (ndarray or float): current system stat... | d761bc43a0a2bf47aba0ab68b2c11be9ec33d9ba | 668,698 |
def validate_grid_staggering(umf, gs_valid):
"""
Check that a :class:`UMFile` object has an accepted grid staggering.
Args:
* umf:
A :class:`UMFile` subclass instance.
* gs_valid:
A tuple containing valid values of the grid staggering
to be checked agains... | 89a689a21e235f6b248689bf4553dda2441169d2 | 668,699 |
def get_incremental_iteration_dets(for_el):
"""
Look for the pattern:
pets = ['cat', 'dog']
for i in range(len(pets)):
print(f"My {pets[i]}")
For/target/Name id = i
iter/Call/func/Name id = range
args/Call/func/Name id = len
args/Name i... | e3076d311cc1b7492a8905bde4fb15278130d917 | 668,700 |
def re_escape(string: str) -> str:
"""
Escape literal backslashes for use with :mod:`re`.
.. seealso:: :func:`re.escape`, which escapes all characters treated specially be :mod:`re`.
:param string:
"""
return string.replace('\\', "\\\\") | 504befa074bbe977805c64d0eecc27c647e05f90 | 668,701 |
def make_taskdescription(run):
"""This is only place I can think of where we can put information about
performance and acquisition"""
s = []
FIELDS = [
'task_description',
'performance',
'acquisition',
]
for f in FIELDS:
value = getattr(run, f)
if va... | ff95153e3c1782e5eeb6dce4ef24482da920b763 | 668,702 |
import re
def sanitizeFilename(path):
"""Replace all non-printable and space chars with underscores.
"""
r = path.replace("a\xcc\x88", "ae")
r = path.replace("o\xcc\x88", "oe")
r = path.replace("u\xcc\x88", "ue")
r = path.replace("A\xcc\x88", "Ae")
r = path.replace("O\xcc\x88", "Oe")
r... | d648835e4f4ab3dbfee0f148f1c04a4c0a5af286 | 668,703 |
from typing import Optional
from typing import Tuple
import re
def _parse_addr(addr: str, allow_wildcard: bool = False) -> Optional[Tuple[str, str]]:
"""Safely parse an email, returning first component and domain."""
m = re.match(
(
r'([a-zA-Z0-9\-_\+\.]+)' +
('?' if allow_wild... | ab62e2a99b9ad460163f08997e5c9bd9d6096bac | 668,704 |
def prepare_standard_scaler(X, overlap=False, indices=None):
"""Compute mean and standard deviation for each channel.
Parameters
----------
X : np.ndarray
Full features array of shape `(n_samples, n_channels, lookback, n_assets)`.
overlap : bool
If False, then only using the most r... | 8dbce4fed5a2bd1772f9b042d4dacdb0501b2462 | 668,705 |
import csv
def read_lines():
"""
Output:
samples: array of each line within the csv file.
Reads each line of the driving_log.csv file.
"""
samples = []
# Opens the csv file.
with open('./data/driving_log.csv') as csvfile:
reader = csv.reader(csvfile)
# Loops through... | 6abdad99676ef044d1cf0bfa460d99dc5308795d | 668,706 |
from typing import List
import glob
import os
def get_missing_names(path: str, names: str) -> List[str]:
"""
:param path: path to files
:param names: list of names
:return: list of any names without a corresponding file in the path
"""
file_names = [os.path.basename(file_path) for file_... | 4479bb17a4fa3b88d84b22f17a81cd46c706be0a | 668,707 |
def binaryalert_yara_match(rec):
"""
author: Austin Byers (Airbnb CSIRT)
description: BinaryAlert found a binary matching a YARA rule
reference: https://binaryalert.io
"""
return rec['NumMatchedRules'] > 0 | a75b8fafbe19bb4a3b95b1da3693933d5d6d1b5b | 668,708 |
def reasonable(n):
"""Is N small enough that 1/N can be represented?
>>> reasonable(100)
True
>>> reasonable(0)
True
>>> reasonable(-100)
True
>>> reasonable(10 ** 1000)
False
"""
return n == 0 or 1/n != 0.0 | e05599d12e1a332cac523ddb794882151bb848eb | 668,709 |
import yaml
import os
def get_post_details(ad_file, api=None):
"""
Extract ad data from inf file
"""
with open(ad_file, 'r') as f:
data = yaml.load(f, Loader=yaml.FullLoader)
files = [open(os.path.join(os.path.dirname(ad_file), picture),
'rb').read() for picture in data[... | 3d8c9af5d576816f18b918405f3636bad1f4d4b3 | 668,710 |
import os
def maybe_resolve_path_conflict(path):
"""creates a unique filename incase `path` already exists"""
base_dir, filename = os.path.split(path)
sep = filename.index('.')
name, ext = filename[:sep], filename[sep:]
while os.path.exists(path):
if "_" in name:
name_split = name.split("_")
... | 975b074007cdedd9bcec41777329b88f8fee2cf9 | 668,711 |
import re
def bs_preprocess(html):
"""remove distracting whitespaces and newline characters"""
pat = re.compile('(^[\s]+)|([\s]+$)', re.MULTILINE)
html = re.sub(pat, '', html) # remove leading and trailing whitespaces
html = re.sub('\n', ' ', html) # convert newlines to spaces
# this pre... | 802d00233a5acb42dd7e80fd04ccdf3aea79438f | 668,712 |
import os
def add_path(file_path, file_name):
"""Sets the path for a file
"""
return os.path.join(file_path, file_name) | d0e31a113e2f8cb535285245dabc85a0bb9f9b87 | 668,713 |
import os
import pathlib
def get_absolute_path(file):
"""
get the absolute path of a pathlib.Path() object
"""
absolute_path = os.path.abspath(os.path.expanduser(str(file)))
return pathlib.Path(absolute_path) | 5a4fc3fa378681276531548563dbbfce42a1cc29 | 668,714 |
def _list_intersection(list1, list2):
"""Compute the list of all elements present in both list1 and list2.
Duplicates are allowed. Assumes both lists are sorted."""
intersection = []
pos1 = 0
pos2 = 0
while pos1 < len(list1) and pos2 < len(list2):
val1 = list1[pos1]
val2 = list... | 4e1eb7c7051b54aade8be0c11247cafc65ac27c1 | 668,715 |
import io
def read_input(input_file):
""" Read OpenAssessIt .md file """
if input_file:
if type(input_file) is str:
with io.open(input_file, encoding='utf-8') as stream:
return stream.read() | b9811ab89d5fa45b6b0f56851f9c7d7e9bbbdf74 | 668,716 |
def caesar(shift, data, shift_ranges=('az', 'AZ')):
"""
Apply a caesar cipher to a string.
The caesar cipher is a substition cipher where each letter in the given
alphabet is replaced by a letter some fixed number down the alphabet.
If ``shift`` is ``1``, *A* will become *B*, *B* will become *C*, ... | c4bf5bd7fc878599e737e107c8311549a02f6a95 | 668,717 |
import six
def format_range(value):
"""Formats a range header tuple per the HTTP spec.
Args:
value: ``tuple`` passed to `req.range`
"""
# PERF(kgriffs): % was found to be faster than str.format(),
# string concatenation, and str.join() in this case.
if len(value) == 4:
resul... | 54172fd48083def7bfa73c24d599fd69a4f45bb3 | 668,718 |
def parse_room_config(config):
"""
This method provides backwards compatibility with the previous room
list as dict format by transforming dicts like `{"main": "#myroom:matrix.org"}` into
`{"main": {"alias": "#myroom:matrix.org"}}`.
"""
new_rooms = {}
for name, room in config["rooms"].items(... | 07e4138e400fb118f1c1b232fae8178724697874 | 668,719 |
from typing import Optional
def get_src(src: Optional[str], curie: str):
"""Get prefix of subject/object in the MappingSetDataFrame.
:param src: Source
:param curie: CURIE
:return: Source
"""
if src is None:
return curie.split(":")[0]
else:
return src | 9b04c3182549abbdadd60546c30c52dc05bce376 | 668,720 |
import numpy
def snell(theta_inc, n):
"""Snell law.
INPUT
theta_inc = angle of incidence.
n = 1D numpy.array of refractive indices.
OUTPUT
theta = 1D numpy.array.
"""
theta = numpy.zeros_like(n)
theta[0] = theta_inc
for i in range(1, n.size):
theta[i] = numpy.arcsin(... | 6268ff38332d031c452414028d632e02ad54dd5b | 668,721 |
import numpy
def reorder_counterclockwise(cells: numpy.ndarray):
"""
Reorder cell topology so that V0->V1->V2->V3->V0
forms a closed path and the resulting quadrilateral
doest not have self-intersections.
"""
perm = numpy.array([0, 1, 3, 2], dtype=numpy.int32)
new_cell_order = cells[:, per... | 66dc3f4662eedde6ad9de3f6c43b35e98eb8d3d4 | 668,722 |
from pathlib import Path
def read_key(location: Path) -> str:
"""
reads a key from a text file containing one line
parameters:
location: Path
the location of the file to read from
"""
with location.open() as file:
return file.read().strip() | c044caa2ccedf795326df996244cee71501e1b1f | 668,723 |
def get_value(node):
"""
Get the value of a node.
"""
if len(node.children) == 0:
return sum(node.metadata)
else:
total = 0
for index in node.metadata:
try:
total += get_value(node.children[index-1])
except IndexError:
p... | 0404dadf2253f039a83bbeaa1c2b3626097a1aa0 | 668,724 |
def DES3500(v):
"""
DES-3500-series
:param v:
:return:
"""
return v["platform"].startswith("DES-35") | ecd8452aa26ae512fb00df0705d330fe3e261e11 | 668,725 |
def version_str(version):
"""Convert a version tuple or string to a string.
Should be returned in the form: major.minor.release
"""
if isinstance(version, str):
return version
elif isinstance(version, tuple):
return '.'.join([str(int(x)) for x in version])
else:
raise Va... | c548a7c781fa3dc21ab4144ee12342802648bf7a | 668,726 |
import re
def _defaultColor(text):
""" Returns a stripped version of a text that can be used as color
>>> p = PaletteBase()
>>> p.colorize("numbers 1 2 3 12 inside, also with 0.5 decimal points")
'numbers inside, also with decimal points'
"""
# Any number
colorized = re.sub( '-?[0-9]+\.?... | dd97e1c00be316c6f3f9d48c311e2f5fdebdf9dc | 668,727 |
def readGmtFile(gmtPath):
"""
Read GMT file. In GMT file each line consists of term ID, term name and genes,
all tab separated, no header.
:param str gmtPath: Path of the GMT file
:return: **geneSetsDict** (*dict*) – Dictionary mapping term IDs to set of genes.
:return: **gsIDToGsNameDict** (*dict*) – Dictionary... | 45c3bce208ec479e8454fbb7a4d6b3cd83c29324 | 668,728 |
def get_priority_points(priority):
"""
Normal = 2
Low = 1
High = 3
Urgent = 4
Immediate = 5
"""
points = 0
for i in priority:
if i == 'Low':
points += priority[1]
elif i == 'Normal':
points += priority[i] * 2
elif i == 'High':
... | 320d228b7ce38c638114beaabc57bcbbb2f3cda6 | 668,729 |
def second(seq):
"""Returns the second element in a sequence.
>>> second('ABC')
'B'
"""
seq = iter(seq)
next(seq)
return next(seq) | 491004d1e74eda99c8ba49e5b28ec6c9de809fb0 | 668,730 |
def modelform_with_extras(form_cls, **extra_kwargs):
"""
Wrap a ModelForm in a class that creates the ModelForm-instance with
extra paramaters to the constructor.
This function is ment to to be returned by ModelAdmin.get_form in order
to easily supply extra parameters to admin forms.
"""
cl... | a0b221a0097d46ca46bf7ee4594e0b632e3faa73 | 668,731 |
def listens_to_mentions(regex):
"""
Decorator to add function and rule to routing table
Returns Line that triggered the function.
"""
def decorator(func):
func.route_rule = ('mentions', regex)
return func
return decorator | 4e0ebfc0e68ab423fba9cd318ed82a3bfd329307 | 668,732 |
def _message_from_pods_dict(errors_dict):
"""Form a message string from a 'pod kind': [pod name...] dict.
Args:
- errors_dict: a dict with keys pod kinds as string and values
names of pods of that kind
Returns: a string message
"""
msg_list = [
"{0}: {1}".format(k... | 51c87b1744fea7ca2540c35648c3305ea08e52a2 | 668,733 |
import pickle
def pickle_load(fname):
"""
Load data from file using pickle.
"""
# load the model
loaded_object = pickle.load(open(fname, 'rb'))
return loaded_object | c2281dac1eb7daca831780ec86fbc9bef9e3fc23 | 668,734 |
import os
def CheckIfBisectDepotExists(opts):
"""Checks if the bisect directory already exists.
Args:
opts: The options parsed from the command line through parse_args().
Returns:
Returns True if it exists.
"""
path_to_dir = os.path.join(opts.working_directory, 'bisect', 'src')
return os.path.ex... | 9518fad27f5db8f9c49846f96ad39855fac02c14 | 668,735 |
def sum_values_in_dict(list_of_dicts, key_name):
"""
# sum values in dictionary
# ex.
example_list = [
{'points': 400, 'gold': 80},
{'points': 100, 'gold': 10},
{'points': 100, 'gold': 10},
{'points': 100, 'gold': 10}
]
then
sum(item['gold'] for item in m... | c2a71fbb9a94207965ce0406f0561ddb890257ed | 668,737 |
def ari(b3, b5):
"""
Anthocyanin Reflectance Index (Gitelson, Chivkunova and Merzlyak, 2009).
.. math:: ARI = (1/b3) - (1/b5)
:param b3: Green.
:type b3: numpy.ndarray or float
:param b5: Red-edge 1.
:type b5: numpy.ndarray or float
:returns ARI: Index value
.. Tip::
Kar... | 1c763aa7da5faa45342035cc36de0cffd11bf58e | 668,738 |
def colorAsFloatValues(color):
""" convert color values """
return color[0] / 255., color[1] / 255., color[2] / 255. | b1f316c363c0440b8067d04f7bc0c2cb46e77d60 | 668,739 |
import math
def angle_normalize(z):
""" convenience function to map an angle to the range [-pi,pi] """
return math.atan2(math.sin(z), math.cos(z)) | b64f1ef7b79c2302909a74ab6e50602fc5a99c40 | 668,740 |
import os
def file_exists(path):
"""Check if file exists and is readable
Args:
path (str)
Returns:
bool
Raises:
IOError
"""
exists = False
if os.path.isfile(path):
if os.access(path, os.R_OK):
exists = True
else:
raise I... | a0738136aa51140b054e7c285eaa42a67b6af27a | 668,741 |
def calculate_entropy_tuning_loss(policy, log_pi):
"""Calculates the loss for the entropy temperature parameter. This is only relevant if self.automatic_entropy_tuning
is True."""
alpha_loss = -(policy.log_alpha * (log_pi.detach() + policy.target_entropy)).mean()
return alpha_loss | 53a2481ec6bd1c37b4ef18aa28df363349d103eb | 668,742 |
import os
def _CheckPedalsHistograms(input_api, output_api):
"""Check that no `OmniboxPedalId` values were added without also
changing enums.xml"""
results = []
header = next((f for f in input_api.AffectedFiles()
if os.path.basename(f.LocalPath()) ==
"omnibox_pedal_concepts.h... | 1c890129ca04aef1595c83b56f61fdd36c4bf99b | 668,744 |
def get_key_from_rot(rotation):
""" Yeah I know it's ugly code... """
if rotation < -67.5:
return -90
elif rotation < -22.5:
return -45
elif rotation < 22.5:
return 0
elif rotation < 67.5:
return 45
else:
return 90 | dcdb27bfff7d5d5f37c28ab4beffd307935a20d4 | 668,745 |
import re
def filterBadLibraries(infiles, bad_samples):
"""
Takes a list of infiles, removes those files that match any pattern in list
of bad_samples, returns the filtered list of outfiles
"""
bad_samples = [re.compile(x) for x in bad_samples]
to_remove = []
for inf in infiles:
fo... | a033ab50500f17a587ac655b521d89bd6c8bdbae | 668,746 |
def lines(fetched):
"""Iterable list of lines from Ilmanet"""
return [line.decode('utf-8').rstrip() for line in fetched.readlines()] | c62398a16b2d4ce48a522272a36a69c35aaf8815 | 668,747 |
from functools import reduce
from operator import getitem
def _get_by_path(tree, keys):
"""
Access a nested object in tree by sequence keys.
"""
return reduce(getitem, keys, tree) | 79edeae0cd5aa85a508ce20562f34ebbe46eba0d | 668,748 |
def analytical_domain(request):
"""
Adds the analytical_domain context variable to the context (used by
django-analytical).
"""
return {'analytical_domain': request.get_host()} | 2d1f32ada6524cdc14075596a7b61de3d82d2ea1 | 668,749 |
def crc_check(input_bitstring, polynomial_bitstring, check_value):
"""Calculate the CRC check of a string of bits using a chosen polynomial."""
polynomial_bitstring = polynomial_bitstring.lstrip('0')
len_input = len(input_bitstring)
initial_padding = check_value
input_padded_array = list(input_bitst... | cc4c7891875057709e460da830f97e8d699a92e1 | 668,750 |
import re
def _match_duration(value):
"""Return the durations (by minute) in value, None if no trainID."""
mat = re.search(r"(\d{1,2} minutes)", value)
if mat is not None and len(mat.groups()) > 0:
return mat.groups()[0]
return None | 4b3e9e54cbfcafc9813b04c56bc5cc32cf808adc | 668,751 |
import argparse as ap
def read_cli():
"""
read command line arguments
"""
# lets read in some command-line arguments
p = ap.ArgumentParser(description="Generate boundary condition"
" data as specified on the command line.",
formatter_class=ap.Ar... | 862f507400e28028b8f2c2c54d2b60ea8a4e09ed | 668,752 |
import argparse
def parse_options(cli_options, valid_groups, valid_types):
"""Main arguments processing for the CLI
:param cli_options: CLI args Supplied by user
:type cli_options: `dict`
:param valid_groups: Plugin groups to chose from
:type valid_groups: `list`
:param valid_types: Plugin ty... | b06b69fafc39219a15862820ed6393f108a90cea | 668,753 |
def get_start_middle_end_point(line):
"""
Ger three point on line
Transform it to DB.Curve
:param line: Line
:type line: DB.Line
:return: Start, middle and end point of line
:rtype: [DB.XYZ, DB.XYZ, DB.XYZ]
"""
curve = line.GeometryCurve
start = curve.GetEndPoint(0)
end = cu... | b6b4f578cd8ce44663a3c7ebb0c6b7dff3ab18d8 | 668,754 |
def eps(machine):
"""Return numeric tolerance for machine"""
return 1e-5 if machine == "x86" else 1e-8 | 95d6d59ab05a757255529b9ca75e727496fa8369 | 668,755 |
def set_some_elements_to(config_dict: dict, keys: list, boolean: bool) -> dict:
"""
Function which uses the global parameters Default_False and Default_True to adjust
the config file by custom parameters.
IMPORTANT: Parameters should only be modified but not deleted.
"""
for key in keys:
... | 129b8512f90edf5ea1aa31ca5eb28776637b2801 | 668,756 |
def check_if_last_row(array, row_number):
"""Loop through row for get_num_rows_cols."""
for cell in enumerate(array[row_number]):
if array[row_number][cell] != '':
if array[row_number + 1][cell] != '':
return False
return True | f9e93a02ee8571b6180a6955055c13f06d423a73 | 668,757 |
import argparse
def parse_arguments():
"""
Basic argument parsing using python's argparse
return: void
"""
parser = argparse.ArgumentParser(description="Script to convert RNAcentral sequence metadata to Rfamseq")
parser.add_argument("--rnac-csv",
help="A valid csv fi... | a1c70973acf4f44b7f1a6bc846171716f9020e2f | 668,758 |
def toint(x):
"""Convert x to interger type"""
try: return int(x)
except: return 0 | 2b31eebc52e9b5774b5562b65c27dd3f62171163 | 668,759 |
def _normalize_string_values(field_values):
"""Normalize string values for passed parameters.
Normalizes parameters to ensure that they are consistent across queries where
factors such as case are should not change the output, and therefore not
require additional Telescope queries.
Args:
f... | d475d89f38dc924e631353be1d814c9cd0b6227c | 668,761 |
import os
def preparing_path(ref_path):
"""
This function prepares path for working
"""
last_char = ref_path[len(ref_path)-1]
if not last_char == os.sep:
ref_path += os.sep
return ref_path | d47820bf158a26aade28b81bfcf2725c5bbfeef6 | 668,762 |
def read_seqfile(filename):
"""Read seq files in ??? format and strip metadata."""
with open(filename) as inp:
seqs = inp.read().split('\n')
seqs = [seq for seq in seqs if not '>' in seq]
seqs = [seq for seq in seqs if seq != '']
return seqs | 137a117764f36cdd8a4e750c0e80b2360cf7f31b | 668,763 |
def cmd(required_params, *, needs_reply=False):
"""Create the internal structure describing a command
:param required_params: A list of parameters that must be included with the command.
:param needs_reply: The message needs to be replied to (and must have a uuid)."""
return required_params, needs_repl... | 0e9bc63ce3547a8b2856de8af8804fbee3f2bb3d | 668,765 |
import torch
def _chop_model(model, remove=1):
"""
Removes the last layer from the model.
"""
model = torch.nn.Sequential(*(list(model.children())[:-remove]))
return model | 73eca910e3068311c97ea76d6e398697d04c6a2e | 668,766 |
def clean(str):
"""
Goes through the string and ensures that every char is a known character.
Keyword arguments:
str -- the string to be cleaned up.
Returns:
This function returns a clean String with bad characters removed
"""
outStr = ""
for i in range(len(str)):
if(str[i] in "abcdefghijklmnopqrstuvwxyzAB... | 58779fd3e3af0c626726a60ce96b8a127198a246 | 668,767 |
def SanityCheckCatalog(catalog):
"""Ensures any given service name appears only once within the catalog."""
known_services = set()
def has_no_dupes(root):
if "name" in root:
name = root["name"]
if name in known_services:
raise ValueError("Duplicate catalog entry found for service: %s" % n... | 0fdee6bdde12071c393678dd193fca779dfc4b09 | 668,768 |
import json
def json_response(func):
""" Translates results of 'func' into a JSON response. """
def wrap(*a, **kw):
(code, data) = func(*a, **kw)
json_data = json.dumps(data)
return (code, { 'Content-type': 'application/json',
'Content-Length': len(json_data) },... | 968a2e3cf8ffedbbc96cc9eee45038115dd80e26 | 668,770 |
import networkx
def get_superterms(term, hpo_g):
"""
Get all HPO terms upstream of a query term
"""
if hpo_g.nodes.get(term, None) is not None:
superterms = networkx.descendants(hpo_g, term)
superterms = [s for s in superterms if s is not None]
else:
superterms = []
r... | f966d0f0f56db36a163b59fa68d599723091b573 | 668,771 |
import sys
import platform
import os
from pathlib import Path
import warnings
def task_prepare_build():
"""Build a standalone windows executable."""
python_path = sys.executable.split(os.sep)
venv_path = str(Path(os.sep.join(python_path[:-2])))
def get_dst_path():
print(f"Going on with {ve... | 67a8e3284578f67b1b32f04341c3e6e998fff31a | 668,772 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.