content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def encode_selection(selection: SelectionNode, db: Database) -> EncodedSelection:
"""
Encoding is a vector of:
-------------------------------------------------------------------------------
| *col | *rel | *hist | *freq | onehot dtype | op one hot | operand encoding |
-------------... | 5,290,900 |
def dict_keys(this):
"""
Return PyIterable for Dict keys.
"""
return mkiterable(this.getvalue().keys()) | 5,290,901 |
def EMA2(df, n):
"""
线性加权移动平均 WMA
Args:
df (pandas.DataFrame): Dataframe格式的K线序列
n (int): 线性加权移动平均的周期
Returns:
pandas.DataFrame: 返回的DataFrame包含1列, 是"ema2", 代表计算出来的线性加权移动平均线
Example::
# 获取 CFFEX.IF1903 合约的线性加权移动平均线
from tqsdk import TqApi, TqSim
fro... | 5,290,902 |
def pusher(obj_scale=None,
obj_mass=None,
obj_damping=None,
object_pos=(0.45, -0.05, -0.275),
distr_scale=None,
axisangle=(0, 0, 1, 1.5),
distr_mass=None,
distr_damping=None,
goal_pos=(0.45, -0.05, -0.3230),
distractor_po... | 5,290,903 |
def inc_key_cnt(dic: dict, key):
"""指定したキーの値を1つカウントアップする。
"""
if key in dic:
dic[key] += 1
else:
dic[key] = 1 | 5,290,904 |
def reroot_list(path_list, new_path, old_path):
""" Change a path in a list of paths in a tree, and thereby change each
path the derives from, recursively. """
for index, path_string in enumerate(path_list):
if Path(path_string) == Path(old_path):
path_list[index] = new_path
elif... | 5,290,905 |
def create_from_pairs(pairs):
"""
Build graph from `pairs` of words.
Accumulate weight for the edges that appear multiple time
"""
DG = nx.DiGraph()
for (n1, n2, w) in pairs:
if DG.has_edge(n1, n2):
DG.edge[n1][n2]['weight'] = w
else:
DG.add_edge(n1, n2, {... | 5,290,906 |
def loop(env, mind, interpreter=None, n_episodes=1, max_steps=-1, policy='deterministic', name="",
debug_mode=False, render_mode=False, train_mode=True, verbose=2, callbacks=None, **kwargs):
"""Conduct series of plies.
Args:
env (Environment): Environment to take actions in.
mind (Mind... | 5,290,907 |
def get_panelist_by_id(panelist_id: int):
"""Retrieve a panelist based on their ID"""
return panelists.get_panelist_by_id(panelist_id, database_connection) | 5,290,908 |
def test_has_extract_config(clients, db, mocker, file_type, content):
"""
Test that user can download extract config for expedited file types
"""
extract_config_dir = os.path.join(
settings.BASE_DIR, "extract_configs", "templates"
)
mock_resp = mocker.patch("creator.files.views.HttpRespo... | 5,290,909 |
def main_json(config, in_metadata, out_metadata):
"""
Alternative main function
-------------
This function launches the app using configuration written in
two json files: config.json and input_metadata.json.
"""
# 1. Instantiate and launch the App
print("1. Instantiate and launch the A... | 5,290,910 |
def new_figure_manager(*args, **kwargs):
"""Create a new figure manager instance."""
_warn_if_gui_out_of_main_thread()
return _backend_mod.new_figure_manager(*args, **kwargs) | 5,290,911 |
def given(distribution: Series, **givens) -> Series:
"""
Condition the distribution on given and/or not-given values of the
variables.
:param distribution: The probability distribution to condition
e.g. P(A,B,C,D).
:param givens: Names and values of variables to condition o... | 5,290,912 |
def cosine_similiarity(vec_left, vec_right):
"""
余弦相似度
:param vec_left:
:param vec_right:
:return:
"""
num = np.dot(vec_left, vec_right)
denom = np.linalg.norm(vec_left) * np.linalg.norm(vec_right)
cos = -1 if denom == 0 else num / denom
return cos | 5,290,913 |
def albedo_diffuse_bubbly_ice(wavelengths, a, f, ni="p2016"):
"""compute diffuse albedo of pure ice without taking into account for the surface reflectance and
using the assymptotic radiative transfer theory
:param a: bubble radius (m)
:param f: is bubble fractional volume w/r to total volume (m3/m3).... | 5,290,914 |
def parse_arguments():
"""
Parse file arguments
"""
parser = argparse.ArgumentParser(description="Predict class for a given input image")
parser.add_argument('image_url', help="url for a test image")
return parser.parse_args() | 5,290,915 |
def main():
"""
Here we arrange the background and foreground accordingly to get desired results
"""
# Getting video feed through webcam
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if ret:
frame_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
... | 5,290,916 |
def reflectance(*reference):
"""Reference to a factbase resource describing reflectance.
Parameters
----------
*reference : :obj:`str`
Keys pointing to the metadata object describing the resource within the
reflectance category in the layout file of a factbase.
Returns
-------
:obj:`Cube... | 5,290,917 |
async def handler_wrapper(handler_function, stream, data, session, scope):
"""
Wrapper around handler function. Automatically closes stream and handles errors
"""
try:
handler_function(stream, data, session=session, scope=scope)
stream.close()
except SystemExit as system_exit:
... | 5,290,918 |
def get_validator_or_converter(name):
"""
Get a validator or converter by name
"""
if name == 'unicode':
return six.text_type
try:
v = get_validator(name)
return v
except UnknownValidator:
pass
raise SchemingException('validator/converter not found: %r' % name... | 5,290,919 |
def _d_sellmeier(b, c, lambda0):
"""
Calculate the first derivative (wrt wavelength) of the Sellmeier equation.
This is a private method.
Args:
b : array of three Sellmeier Coefficients [--]
c : array of three Sellmeier Coefficients [microns**2]
lambda0 : wavelength in vacuum... | 5,290,920 |
def is_running():
"""
Check JDB process state
"""
return jdb_process is not None and jdb_process.poll() is None | 5,290,921 |
def start_sai_test_container(duthost, creds, deploy_sai_test_container, request):
"""
Starts sai test container docker on DUT.
"""
logger.info("sai_test_keep_test_env {}".format(request.config.option.sai_test_keep_test_env))
logger.info("Starting sai test container {}".format(get_sai_test_contai... | 5,290,922 |
def _rename_phasediff_files(directory, cfg, idf):
""" Renames Philips "B0" files (1 phasediff / 1 magnitude) because dcm2niix
appends (or sometimes prepends) '_ph' to the filename after conversion.
"""
if not isinstance(idf, list):
idf = [idf]
b0_files = []
for this_idf in idf:
... | 5,290,923 |
def get_non_us_city(location: str) -> str:
"""
Deals with two types of non-US locations:
"New Delhi (India)" and "Perth, Western Australia (Australia)"
:param location: geo location of the person
:return city
:raises LocatorException: could not infer the city name
"""
sep_idx = location.... | 5,290,924 |
def validate():
"""Check that the database is good."""
pass | 5,290,925 |
def row_to_top(df, index):
"""Bring row to top
Parameters
----------
df: pandas.dataframe
Dataframe to copy
index: int
Index of row to bring to top
Returns
-------
df_cp: pandas.dataframe
Copy of dataframe with specified row at top
"""
df_cp = pd.concat... | 5,290,926 |
def _plot_feature_distributions(X):
"""
Plots the distribution of the features in separate plots
:param X: Feature matrix
Folder: Features/Feature_distributions/
Plot name: histogram_{feature name}.pdf
"""
print("Plotting histogram of each feature...")
f_names = f_factory.featu... | 5,290,927 |
def AddTestResource(request_id, test_resource):
"""Addes a test resource to a request.
Args:
request_id: a request ID.
test_resource: a datastore_entities.TestResource object.
"""
request_key = ndb.Key(datastore_entities.Request, request_id,
namespace=common.NAMESPACE)
resourc... | 5,290,928 |
def init_cache(cname):
"""
Wipes and initializes a cache dir for container name `cname`.
"""
cache = abspath('.tmptest/test-kraken-integration/{cname}/cache'.format(cname=cname))
if os.path.exists(cache):
subprocess.check_call(['rm', '-rf', cache])
os.makedirs(cache)
os.chmod(cache, ... | 5,290,929 |
def encodeMask(M):
"""
Encode binary mask M using run-length encoding.
:param M (bool 2D array) : binary mask to encode
:return: R (object RLE) : run-length encoding of binary mask
"""
[h, w] = M.shape
M = M.flatten(order='F')
N = len(M)
counts_list = []
pos = 0
# counts
counts_list.append(1)
diffs ... | 5,290,930 |
def flatten_model_graph(ir_model: Model):
"""
Flatten the subgraph into root graph.
"""
def _flatten(graph: Graph):
"""
flatten this graph
"""
model = graph.model
node_to_remove = []
for node in graph.hidden_nodes:
node_graph = model.graphs.ge... | 5,290,931 |
async def test_refresh_token(connection: Connection) -> None:
"""Auth refreshes token on expiration/invalidation"""
with connection.cursor() as c:
# Works fine
await c.execute("show tables")
# Invalidate the token
c._client.auth._token += "_"
# Still works fine
... | 5,290,932 |
def test_get_token_from_environ(monkeypatch):
"""Tests getting a token from the environment."""
service = 'test'
key = 'TEST_TOKEN'
token = 'test_token'
lipwig.tokens._SERVICES[service] = {'env': key}
key = lipwig.tokens._SERVICES[service]['env']
monkeypatch.setenv(key, token)
assert lip... | 5,290,933 |
def get_cache():
"""returns the cache"""
return _cache | 5,290,934 |
def parse_message(message, nodata=False):
"""Parse df message from bytearray.
@message - message data
@nodata - do not load data
@return - [binary header, metadata, binary data]
"""
header = read_machine_header(message)
h_len = __get_machine_header_length(header)
meta_raw = message[h_l... | 5,290,935 |
def reblock_array(df, nblocks, weights=None):
"""
Reblock df into nblocks new blocks
:param df: data to reblock
:type df: numpy array-like
:param nblocks: number of resulting blocks
:type nblocks: int
:param weights: weights used to average data
:type weights: array
:return: reblock... | 5,290,936 |
def B_measure(D, Cm, verbose=False):
"""
Computes the B measure for each network edge with infinite distance, thus not existing in the original Distance graph.
The formal definition is as follow:
.. math::
b_{ij} = <d_{ik}> / d_{ij}^m
b_{ji} = <d_{jk}> / d_{ij}^m
which is the average distance of all edges t... | 5,290,937 |
def get_medias() -> List[Media]:
"""
Retrieve the list of medias to be processed into folders
:return: the list of medias to process
"""
files = []
for folder in config['input']['folders']:
files += scan_folder(folder)
files.sort()
medias = []
for index, file in... | 5,290,938 |
def test_init(app):
"""Test initialisation."""
auth = OktaOAuth(app, base_url='https://sbphnk.okta-emea.com')
assert auth.app is app | 5,290,939 |
def count_paths_recursive(graph, node_val, target):
"""A more conventional recursive function (not a recursive generator)"""
if node_val >= target:
return 1
total = 0
for next_node in graph[node_val]:
total += count_paths_recursive(graph, next_node, target)
return total | 5,290,940 |
def create_dir(path):
"""
create dir if not exists
"""
if not os.path.exists(path):
os.makedirs(path) | 5,290,941 |
def set_permission(StackId=None, IamUserArn=None, AllowSsh=None, AllowSudo=None, Level=None):
"""
Specifies a user\'s permissions. For more information, see Security and Permissions .
See also: AWS API Documentation
Exceptions
:example: response = client.set_permission(
StackId='st... | 5,290,942 |
def check_valency(mol):
"""
Checks that no atoms in the mol have exceeded their possible
valency
:return: True if no valency issues, False otherwise
"""
try:
Chem.SanitizeMol(mol, sanitizeOps=Chem.SanitizeFlags.SANITIZE_PROPERTIES)
return True, None
except ValueError as e:
... | 5,290,943 |
def ensure_pod(ctx):
"""创建configmap"""
name = "kubectld-%s-u%s" % (ctx["source_cluster_id"], ctx["username_slug"])
name = name.lower()
k8s_client = K8SClient(ctx)
try:
pod = k8s_client.v1.read_namespaced_pod(name, namespace=constants.NAMESPACE)
if pod.status.phase != "Running":
... | 5,290,944 |
def lidar_to_camera(points, r_rect, velo2cam):
""" transformation from lidar coordinate to camera coordinate
:param points: non-homo coodinates [..., 3] or homogeneous coordinates [..., 4]
:param r_rect: [4, 4] camera rectification matrix
:param velo2cam: [4, 4] transformation from velo to camera
:... | 5,290,945 |
def _render(value, params):
"""Renders text, interpolating params."""
return str(jinja2.Template(value).render(params)) | 5,290,946 |
def expand (properties):
""" Given a property set which may consist of composite and implicit
properties and combined subfeature values, returns an expanded,
normalized property set with all implicit features expressed
explicitly, all subfeature values individually expressed, and all
... | 5,290,947 |
def convert_to_monophonic(seq):
"""Summary
Parameters
----------
seq : TYPE
Description
"""
note_i = 1
while note_i < len(seq.notes):
n_prev = seq.notes[note_i - 1]
n_curr = seq.notes[note_i]
if n_curr.start_time >= n_prev.start_time and \
n_c... | 5,290,948 |
def login_required(f):
"""Redirects requests to /login if the user isn't authenticated"""
@wraps(f)
def decorated_function(*args, **kwargs):
user_id = session.get('user_id', None)
if user_id:
user = User.query.filter_by(id=user_id).one_or_none()
if user is not None:
... | 5,290,949 |
def validate_namespace(value, exception=BadValueError):
"""Raises an exception if value is not a valid namespace string.
A namespace must match the regular expression `([0-9A-Za-z._-]{0,100})`.
Args:
value: string, the value to validate.
exception: exception type to raise.
Raises:
BadValueError: ... | 5,290,950 |
def ClusterSetSslCert(mvip,
username,
password,
cert,
key):
"""
Set the SSL certificate used by the cluster
Args:
mvip: the management IP of the cluster
username: the admin user of the cluste... | 5,290,951 |
def organization_daily_metrics_view(request):
"""
:param request:
:return:
"""
# admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer
authority_required = {'verified_volunteer'}
if not voter_has_authority(request, authority_required)... | 5,290,952 |
def from_gen(
generator, n_iter, width, height, range, make_xy_proportional=False, log=False
):
"""Create a 2D histogram with `width * height` bins from `generator`.
The generator should be compiled using Numba's `njit` or `jit`.
Parameters
----------
generator : generator() -> x, y
A ... | 5,290,953 |
def inWhichGrid(coord, grid_info):
"""
Specify which grid it is in for a given coordinate
:param coord: (latitude, longitude)
:param grid_info: grid_info dictionary
:return: row, column, grid ID
"""
lat, lng = coord
row = math.floor((grid_info['maxLat'] - lat) / grid_info['gridLat'])
... | 5,290,954 |
def find_executable(executable, path=None):
"""Find if 'executable' can be run. Looks for it in 'path'
(string that lists directories separated by 'os.pathsep';
defaults to os.environ['PATH']). Checks for all executable
extensions. Returns full path or None if no command is found.
"""
if path is... | 5,290,955 |
def aup():
"""Send the user to Acceptable Use Policy page"""
# Read AUP from markdown dir
domain_name = domain_name_edgecase()
with open(
brand_dir + "/" + domain_name + "/signup_content/signup_modal.md", "r"
) as file:
aup_md = file.read()
return render_template("AUP.html", aup... | 5,290,956 |
def transpose(matrix):
"""Matrix transpose
Args:
matrix: list of list
Returns:
list: list of list
"""
return list(map(list, zip(*matrix))) | 5,290,957 |
def download_metadata_file(url, outputdir, program, max_age=None):
"""
:param url:
:param outputdir:
:param program:
:param max_age:
:return:
"""
if outputdir is None:
outputdir = FELS_DEFAULT_OUTPUTDIR
zipped_index_path = os.path.join(outputdir, 'index_' + program + '.csv.g... | 5,290,958 |
def print_title(url: str):
"""Prints title of given url"""
html = requests.get(url)
bs_obj = BeautifulSoup(html.content, "html.parser")
contents = """
{}
""".format(bs_obj.title)
print(contents) | 5,290,959 |
def timestamp(s, tz=None):
"""Parse a HOBO timestamp value to Python DateTime"""
for fmt in TIME_FMTS:
try:
dt = datetime.strptime(s, fmt)
return dt.replace(tzinfo=tz) if tz else dt
except ValueError as e:
pass
raise ValueError('time data "%s" does... | 5,290,960 |
def decodeVarint32FromHttp(response):
"""Decode an 32 bit integer from a varint byte representation.
Expects an HTTP Response to read from.
"""
return _HttpDecodeVarint32(response) | 5,290,961 |
def init(name, root):
"""
Roll-out a new library.
"""
Library.create(name, root) | 5,290,962 |
def get_schema_names():
"""Return a dict of vertex and edge base names."""
names = [] # type: list
for path in _find_paths(_CONF['spec_paths']['schemas'], '*.yaml'):
names.append(_get_file_name(path))
return names | 5,290,963 |
def enumerate_any_files(source_directory, variant_directory = ""):
"""Forms a list of all files in a project directory
@param source_directory Directory containing all of the source files
@param variant_directory Variant directory to which source paths will be rewritten"""
files = []
# F... | 5,290,964 |
async def test_blazer_usb(hass):
"""Test creation of blazer_usb sensors."""
config_entry = await async_init_integration(hass, "blazer_usb")
registry = er.async_get(hass)
entry = registry.async_get("sensor.ups1_battery_charge")
assert entry
assert entry.unique_id == f"{config_entry.entry_id}_bat... | 5,290,965 |
def gen_fix_fixups(*args):
"""
gen_fix_fixups(_from, to, size)
Relocate the bytes with fixup information once more (generic
function). This function may be called from 'loader_t::move_segm()' if
it suits the goal. If 'loader_t::move_segm' is not defined then this
function will be called automatically when... | 5,290,966 |
def test_preset_n_and_ew(preset_args, clres, start_time=time.time(),
time_limit=Def.TimeOuts.test_time_limit):
"""
Test command arguments - check evaluation worker with number of workers
"""
ew_flag = ['-ew']
n_flag = ['-n', Def.Flags.enw]
p_valid_params = p_utils.valid... | 5,290,967 |
def user_setup_stub(self, *args, **kwargs):
"""
Override this function in your code, otherwise it won't customize stuff.
"""
raise NotImplementedError(
"Please overload the `user_setup` function in your class") | 5,290,968 |
def line_fit(x,y):
"""Least-squares fit intercept and slope
.. versionadded:: 1.2
:arg x: sequence of independent variable data
:arg y: sequence of dependent variable data
:rtype: a :class:`~type_b.LineFitOLS`
``y`` must be a sequence of uncertain real num... | 5,290,969 |
def test_from_source_id(testing_user):
""" Test finding the user by source ID """
# get user ID for searching from fixture
user_id = testing_user.data.id
# do search
user = User.from_source_id(Source.TEST, user_id)
assert user.exists
assert user.uid == testing_user.uid | 5,290,970 |
def parse_resolution(json):
"""
Parse a JSON response from the server into a Resolution object.
"""
frequency = Frequency.by_tag(json.get("frequency"))
timezone = pytz.timezone(json.get("timezone"))
return Resolution(frequency, timezone) | 5,290,971 |
def unbiased_ccd_image_dict(ccd, **kwargs):
"""Get the images keys by amp for a ccd
Parameters
----------
ccd : `MaskedCCD` or `ImageF`
CCD data object
Keywords
--------
bias : `str` or `None`
Method for bias subtraction
superbias_frame : `MaskedCCD` or `None`
B... | 5,290,972 |
def get_learning_rate_scheduler(optimizer, args):
"""Build the learning rate scheduler."""
# Add linear learning rate scheduler.
if args.lr_decay_iters is not None:
num_iters = args.lr_decay_iters
else:
num_iters = args.train_iters
num_iters = max(1, num_iters)
init_step = -1
... | 5,290,973 |
def plot_raster(demeter_gdf,
landclass_list,
target_year,
font_scale=1.5,
scope='conus',
resolution='0.083333',
value_to_nan=True,
nan_less_than=0.01,
nan_greater_than=None):
"""Generate a... | 5,290,974 |
def parseargs() -> argparse.ArgumentParser:
""" Parse arguments """
parser = worker.parseargs('Shadowserver ASN enrichment')
parser.add_argument(
'--country-codes',
help="Should point to file downloaded from {}".format(ISO_3166_FILE))
group = parser.add_mutually_exclusive_group(required... | 5,290,975 |
def meshgrid(*xi, **kwargs):
"""Return coordinate matrices from coordinate vectors.
Given one-dimensional coordinate arrays x1, x2, ..., xn, this function
makes N-D grids.
For one-dimensional arrays x1, x2, ..., xn with lengths ``Ni = len(xi)``,
this function returns ``(N1, N2, N3, ..., Nn)`` shap... | 5,290,976 |
def y_dot(t,y,x,nu,F):
"""y_dot(t,y,x,nu,F)
Describes the differential equation for velocity as given in CW 12.
"""
return -(nu*y)+x-(x**3)+(F*np.cos(t)) | 5,290,977 |
def write_or_cache(outvolume, vol_to_write, buffer, cache, data):
"""
Arguments:
----------
outvolume: Volume object representing the output block
vol_to_write: Volume object representing a write buffer which will write into the output block represented by outvolume
buffer: Volume... | 5,290,978 |
def split_code_into_blocks(code):
"""Split code into blocks of code, comments, and string literals."""
def is_noncode_start(code, idx=0):
"""String starts something other than source code (eg, a comment)."""
return (is_quote(code, idx) or
is_multiline_comment_start(code, idx) o... | 5,290,979 |
def lstExcel(filepath, colname):
"""
lstExcel function analyses the excel file and creates a list of the elements, that should be translated.
Parameter:
filepath:str: Path of the excel file.
colname:str: Name of the column to be translated.
Returns list.
"""
df = pd.read_... | 5,290,980 |
def try_start_browser(url):
""" Try to start the default browser """
try:
import webbrowser
webbrowser.open(url)
except:
print 'warning: unable to detect your browser' | 5,290,981 |
def get_model_json_string(model_bigg_id):
"""Get the model JSON for download."""
path = join(settings.model_dump_directory,
model_bigg_id + '.json')
try:
with open(path, 'r') as f:
data = f.read()
except IOError as e:
raise NotFoundError(e.message)
return ... | 5,290,982 |
def compute_shot(way, labels):
"""Computes the `shot` of the episode containing labels.
Args:
way: An int constant tensor. The number of classes in the episode.
labels: A Tensor of labels of shape [batch_size].
Returns:
shots: An int 1D tensor: The number of support examples per class.
"""
class... | 5,290,983 |
def new_line(string: str):
"""
Append a new line at the end of the string
Args:
string: String to make a new line on
Returns: Same string with a new line character
"""
return string + "\n" | 5,290,984 |
def git_commit_and_push(branch: str):
"""Command to git checkout, commit, and push branch"""
subprocess.run(
["git", "add", "build/"], cwd=settings.TRANSLATION_REPOSITORY_DIRECTORY
)
subprocess.run(
["git", "commit", "-m", f"{branch}"],
cwd=settings.TRANSLATION_REPOSITORY_DIRECTO... | 5,290,985 |
def create_groups(container, groups):
"""Creates system groups on docker specified by 'container'.
"""
for group in groups:
gid = str(hash(group) % 50000 + 10000)
command = ["groupadd", "-g", gid, group]
assert 0 is docker.exec_(container, command, interactive=True)
for user ... | 5,290,986 |
def convert_to_unicode(text, encoding='utf-8', errors='ignore'):
"""字符串转换为unicode格式(假设输入为utf-8格式)
"""
if isinstance(text, bytes):
text = text.decode(encoding, errors=errors)
return text | 5,290,987 |
def decaying(start, decay):
"""Return an iterator of exponentially decaying values.
The first value is ``start``. Every further value is obtained by multiplying
the last one by a factor of ``decay``.
Examples
--------
>>> from climin.schedule import decaying
>>> s = decaying(10, .9)
>... | 5,290,988 |
def associate_floating_ip(name, ip=Config.get('Openstack', 'instant_floating')):
""" Will associate a floating ip with an instance name.
Args:
name: Name of the instance to associate with
ip: Floating ip to assign, gets default from config
Returns:
None
"""
server = vm_stat... | 5,290,989 |
def chime_local_datetime(*args):
"""Create a :class:`datetime.datetime` object in Canada/Pacific timezone.
Parameters
----------
*args
Any valid arguments to the constructor of :class:`datetime.datetime`
except *tzinfo*. Local date and time at CHIME.
Returns
-------
dt : :c... | 5,290,990 |
def PrintKmlFooter(f):
"""Write KML footer."""
f.write('</Document>\n</kml>\n') | 5,290,991 |
def build_calling_regions(contigs, regions_to_include, regions_to_exclude):
"""Builds a RangeSet containing the regions we should call variants in.
This function intersects the Ranges spanning all of the contigs with those
from regions_to_include, if not empty, and removes all of the regions in
regions_to_excl... | 5,290,992 |
def _is_bound_method(the_function: object) -> bool:
"""
Returns True if fn is a bound method, regardless of whether
fn was implemented in Python or in C.
"""
if inspect.ismethod(the_function):
return True
if inspect.isbuiltin(the_function):
self = getattr(the_function, "__self__"... | 5,290,993 |
def _is_valid_output_hash(outputs):
"""Test if a set of outputs have valid hashes on the staging channel.
Parameters
----------
outputs : dict
A dictionary mapping each output to its md5 hash. The keys should be the
full names with the platform directory, version/build info, and file ex... | 5,290,994 |
def _CreateSubnetwork(messages, subnet_ref, network_ref, args,
include_alpha_logging, include_beta_logging,
include_l7_internal_load_balancing,
include_private_ipv6_access):
"""Create the subnet resource."""
subnetwork = messages.Subnetwork(
na... | 5,290,995 |
def warmup_linear(
initial_rate: float, warmup_steps: int, total_steps: int
) -> Iterable[float]:
"""Generate a series, starting from an initial rate, and then with a warmup
period, and then a linear decline. Used for learning rates.
"""
step = 0
while True:
if step < warmup_steps:
... | 5,290,996 |
def convert_video_to_numpy(filenames, width, height, n_frames_per_video, n_channels, dense_optical_flow=False):
"""Generates an ndarray from multiple video files given by filenames.
Implementation chooses frame step size automatically for a equal separation distribution of the video images.
:param filenames
:p... | 5,290,997 |
def rm_clusters(name):
"""
Requires the following pillar to be set:
- ceph-salt:execution:fsid
"""
ret = {'name': name, 'changes': {}, 'comment': '', 'result': False}
fsid = __salt__['pillar.get']('ceph-salt:execution:fsid')
__salt__['ceph_salt.begin_stage']("Remove cluster {}".format(fsid... | 5,290,998 |
def micro_averaged_auprc(df_dict, return_df=False):
"""
Compute micro-averaged area under the precision-recall curve (AUPRC)
from a dictionary of class-wise DataFrames obtained via `evaluate`.
"""
# List all unique values of thresholds across coarse categories.
thresholds = np.unique(
np... | 5,290,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.