content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def gate_settle(gate):
""" Return gate settle times """
return 0 | f452a343550c4f7be2133119c89dc386665921c4 | 3,652,086 |
def fov_gc(lons, lats):
"""Field of view great circle.
Properties
----------
lons: [float]
Field of view longitudes (degE).
lats: [float]
Field of view latitudes (degN).
Return
------
geojson.Feature
GeoJSON field of view polygon.
"""
return geo_polygon... | 3013648c04e5626c51995288afd6e441d3afef30 | 3,652,088 |
import ietf.sync.rfceditor
from ietf.doc.templatetags.mail_filters import std_level_prompt
def request_publication(request, name):
"""Request publication by RFC Editor for a document which hasn't
been through the IESG ballot process."""
class PublicationForm(forms.Form):
subject = forms.CharField... | d6377b08c5eae6740e98a154d991ba268ed37815 | 3,652,090 |
def strip_trailing_characters(unstripped_string, tail):
"""
Strip the tail from a string.
:param unstripped_string: The string to strip. Ex: "leading"
:param tail: The trail to remove. Ex: "ing"
:return: The stripped string. Ex: "lead"
"""
if unstripped_string.endswith(str(tail)):
... | dbd09fe9a58b0fb3072a680a9c7ac701257ebfcd | 3,652,091 |
def is_prime(x):
""" Prove if number is prime """
if x == 0 or x == 1:
return 0
for i in range(2, x//2 +1):
if x % i == 0:
return 0
return 1 | 63980c49b9ea05458ecafe874073805df50ce1d0 | 3,652,092 |
import pickle
def obj_to_str(obj, encoding='utf8') -> str:
"""
Examples:
>>> d = dict(a=1, b=2)
>>> assert isinstance(obj_to_str(d), str)
"""
b = pickle.dumps(obj)
return bytes_to_str(b, encoding=encoding) | 76c87052596aefcbd15a5135379ff2a3512bed77 | 3,652,093 |
def sample_ellipsoid(p0, covmat, size=1):
"""
Produce an ellipsoid of walkers around an initial parameter value,
according to a covariance matrix.
:param p0: The initial parameter value.
:param covmat:
The covariance matrix. Must be symmetric-positive definite or
it will raise the ... | a09448f29920a7758a549ede80608c8c4dd9892a | 3,652,095 |
def avg_pool_2d(x, size=(2, 2), stride=(2, 2), name='avg_pooling', padding='VALID'):
"""
Average pooling 2D Wrapper
:param x: (tf.tensor) The input to the layer (N,H,W,C).
:param size: (tuple) This specifies the size of the filter as well as the stride.
:param name: (string) Scope na... | b39dfed959f43346c48d13b7e41601999c1b7f8b | 3,652,096 |
from django.contrib.auth import get_user_model
def get_username_field() -> str:
"""Get custom username field.
Returns:
str: username field.
"""
user_model = get_user_model()
return getattr(user_model, "USERNAME_FIELD", "username") | 45dfe6888d8c69e012b98a0edd1b639b7bf56af7 | 3,652,098 |
def get_header(yaml_dict):
"""
Header merely comprises the access token
:return:
"""
headers = {"Authorization": "Bearer {}".format(get_access_token(yaml_dict)),
"Content-Type": "application/json"}
return headers | fb93b304cdb960f1eec7396a92262fde94699126 | 3,652,100 |
def change_filename_extension(filename: str, old_ext: str, new_ext: str) -> str:
"""
Change extension of a filename (e.g. "data.csv" to "data.json").
:param filename: the old filename (including extension)
:param old_ext: the extension of the old filename
:param new_ext: the extension to replace th... | acf9d75383fafaeaf6bf42e46ef8d01080661172 | 3,652,101 |
def parseArgPairToBoundaryArray(pair, mesh):
"""
Parse boundary related pair argument to create a list of
[ :gimliapi:`GIMLI::Boundary`, value|callable ].
Parameters
----------
pair: tuple
- [marker, arg]
- [marker, [callable, *kwargs]]
- [marker, [arg_x, arg_y, arg_z]]
... | e4827117dfa3b1b6683f2af51ed90bd6f2edf170 | 3,652,102 |
def get_niter(outcarfile):
"""
Get the number of ionic steps that were run
Args:
outcarfile (string): full path to OUTCAR file
Returns:
niter (int): number of ionic iterations
"""
with open(outcarfile,'r') as rf:
for line in rf:
if '- Iteration' in line:
niter = line.split('(')[0].split('n')[-1].... | c64a5cc399cabc41a0fc7ca6fee35970c3db0444 | 3,652,103 |
def bucket_contvar(ex, ctrl, num_buckets):
"""
Given ex, which contains a continuous value for a particular control variable,
return the bucketed version of that control value.
Inputs:
ex: message dictionary. Assume it has key ctrl, mapping to the value.
ctrl: string. The name of the CT con... | 182f9bd01ec81a18b0555afebc40183982d997e9 | 3,652,104 |
def handle_exception(error):
"""
Flask error handler for Exception
Parameters
----------
error : Exception
An Exception error
Returns
-------
string
A JSON string of the Exception error response
"""
response = create_error_response(error)
return response, 50... | 6827d310804a65ff26d6abc036ec60ff94ae4ab7 | 3,652,105 |
import re
def isphone(value, locale='en-US'):
"""
Return whether or not given value is valid mobile number according to given locale. Default locale is 'en-US'.
If the value is valid mobile number, this function returns ``True``, otherwise ``False``.
Supported locales are: ``ar-DZ``, ``ar-SY``, ``ar-S... | 2e3de8fb6aad000c21ea560521f81c4e9bf2e090 | 3,652,106 |
def _darken(color):
"""
Takes a hexidecimal color and makes it a shade darker
:param color: The hexidecimal color to darken
:return: A darkened version of the hexidecimal color
"""
# Get the edge color
darker = "#"
hex1 = color[1:3]
hex2 = color[3:5]
hex3 = color[5:7]
for val... | 5b43785572f9685906e73f4bf856cf4d693f6411 | 3,652,107 |
from datetime import datetime
def commit_datetime(author_time: str, author_tz: str):
"""
Convert a commit's timestamp to an aware datetime object.
Args:
author_time: Unix timestamp string
author_tz: string in the format +hhmm
Returns:
datetime.datetime object with tzinfo
... | d44f7a693ad3c3a6efe97be3707d14b5514bf65e | 3,652,108 |
def flatten_acfg_list(acfg_list):
"""
Returns a new config where subconfig params are prefixed by subconfig keys
"""
flat_acfg_list = []
for acfg in acfg_list:
flat_dict = {
prefix + '_' + key: val
for prefix, subdict in acfg.items()
for key, val in subdic... | ae586bc49ee31db022f388492acbbf5e8d02b09d | 3,652,109 |
def happy_birthday(name: hug.types.text, age: hug.types.number):
"""Says happy birthday to a user"""
return "Happy {0} Birthday {1}!".format(name, age) | 84cf051205db60566bd4fcd07c0d8f31f01c65cb | 3,652,110 |
def _format_d10_singlecell(row):
"""
Format the D10 input data for a single cell (corresponds to a single row
in the input csv file).
"""
nlayers = int(row['nlayer'])
if nlayers == 0:
# This means this cell cannot be run in HELP.
return None
try:
title = str(int(row['... | 567fa7e8582174d6aa1b3ce77441039ecae8c6cf | 3,652,111 |
def logical_and(x, y, out=None, name=None):
"""
:alias_main: paddle.logical_and
:alias: paddle.logical_and,paddle.tensor.logical_and,paddle.tensor.logic.logical_and
:old_api: paddle.fluid.layers.logical_and
logical_and Operator
It operates element-wise on X and Y, and returns the Out. X, Y and Out a... | df0f111f7acb6aafa47cf2a99e6bc45c91e77e08 | 3,652,112 |
def _create_tileZeros():
""" Create a function mapping to the Scala implementation."""
def _(cols, rows, cellType = 'float64'):
jfcn = RFContext.active().lookup('tile_zeros')
return Column(jfcn(cols, rows, cellType))
_.__name__ = 'tile_zeros'
_.__doc__ = "Create column of constant tiles ... | 94dc69bddf1359a2c4645e17a2546920f0c05925 | 3,652,113 |
import pkgutil
def load_modules():
"""
Dynamically loads all the modules in the modules folder and sorts
them by the PRIORITY key. If no PRIORITY is defined for a given
module, a priority of 0 is assumed.
"""
# logger = logging.getLogger(__name__)
locations = [marvin.support.p... | b8232e1663da6b062750cc1261bac229ea945539 | 3,652,114 |
def property_fragment():
"""Builds and returns a random Property init fragment."""
return _build_property_fragment() | 0db4483c98f2495ad6826818759e54f32a8778c4 | 3,652,116 |
def create_person_node(author):
"""
Parameters
----------
author : dict
author field of JSON file.
Returns
-------
ID : str
Document _id from 'Person' collection.
"""
given = author.get('given', '')
family = author.get('family', '')
ID = search_person(given, f... | bfb7f8f0061ad337257c9e43b5907520b79eb59b | 3,652,117 |
def create_date_list(startDt='2020-11-01', endDt='2020-12-01'):
"""
Create a date list ranging from start to end dates. Date output format = yyyy_mm
:startDt = beginning date for the range
:endDt = end date for the range
To run the current method requires a minimum one month difference between dates... | 34b4105876e4e1977716bb307cd9536eb37482fb | 3,652,118 |
import torch
def batch_distance_metrics_from_coords(coords, mask):
"""
Given coordinates of neighboring atoms, compute bond
distances and 2-hop distances in local neighborhood
"""
d_mat_mask = mask.unsqueeze(1) * mask.unsqueeze(2)
if coords.dim() == 4:
two_dop_d_mat = torch.square(coo... | e8322310806debbdb4d2f3699eca4355cc9e3ed6 | 3,652,120 |
def ComputeHash256(buf: bytes) -> bytes:
"""ComputeHash256 Compute a cryptographically strong 256 bit hash of the input byte slice."""
return ComputeHash256Array(buf) | 1597d4ea67a4e74970576a1336a8687640aaca25 | 3,652,121 |
def acf_std(x, maxlag=None, periodogram=True,
confidence=0.6826895, simplified=True, acf_cached=None):
"""Computes the approximate standard deviation of the autocorrelation
coefficients.
Parameters
----------
x : ndarray
Input data.
maxlag : {None, int} optional
Maximum lag bey... | 7720f0f07f901cb3dfbb59a9fdc01afcfb7caf6d | 3,652,122 |
def traverse_map(map, x_step, y_step):
"""
iterates over a "map" (array of strings) starting at the top left until reaching the
bottom of the map. every iteration advances position by <x_step,y_step> and checks if
a tree is hit
returns: the total number of Trees hit
rtype: int
"""
trees... | 42a21c070d25bfc962fa76f94a90417238057986 | 3,652,123 |
from typing import Optional
def q_to_res(Q: float) -> Optional[float]:
"""
:param Q: Q factor
:return: res, or None if Q < 0.25
"""
res = 1 - 1.25 / (Q + 1)
if res < 0.0:
return None
return res | 98380be0c8fbd3bfd694d7851f35488d74cdd862 | 3,652,124 |
import logging
def list_document_classifier():
"""[Lists Document Classifiers for Text Classification on AWS]
Raises:
error: [description]
Returns:
[list]: [List of Document Classifiers]
"""
try:
logging.info(f"List Document Classifiers")
return client.list_docume... | 4efb390fa3ebcd4b1f163db5afdad66d8fdc2cf4 | 3,652,125 |
def id_str_to_bytes(id_str: str) -> bytes:
"""Convert a 40 characters hash into a byte array.
The conversion results in 160 bits of information (20-bytes array). Notice
that this operation is reversible (using `id_bytes_to_str`).
Args:
id_str: Hash string containing 40 characters.
Returns... | cd6a702343f1267e17710305f9aed70613feacb3 | 3,652,126 |
def transform(data):
"""Transform words and tags to ids
"""
new_data = []
unknown_word_count = 0
total_word_count = 0
for words, tags in data:
word_ids = [word_to_ix.get(w, word_to_ix[UNK]) for w in words]
tag_ids = [tag_to_ix.get(t) for t in tags]
new_data.append((word_i... | 6a9f99521bfe157a16ad9dd4d933a46e25878205 | 3,652,127 |
from typing import Optional
def textarea():
""" Returns a textarea parser.
Example::
...[5]
The number defines the number of rows.
"""
rows = number_enclosed_in('[]')('rows')
textarea = Suppress('...') + Optional(rows)
textarea.setParseAction(tag(type='textarea'))
return... | 915d1da239c11a35674ac0f05581afd2fecbd92d | 3,652,128 |
from typing import Optional
def get_agent(agent_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAgentResult:
"""
This data source provides details about a specific Agent resource in Oracle Cloud Infrastructure Database Migration service.
Display the ODM... | 5c364a4572811e46e8ade0c210ce6f7a3d4a025f | 3,652,129 |
def darknet():
"""Darknet-53 classifier.
"""
inputs = Input(shape=(416, 416, 3))
x = darknet_base(inputs)
x = GlobalAveragePooling2D()(x)
x = Dense(1000, activation='softmax')(x)
model = Model(inputs, x)
return model | fd4dc9d0b5e5f6dba1939084669d09f13456133f | 3,652,130 |
def create_process_chain_entry(input_object, python_file_url,
udf_runtime, udf_version, output_object):
"""Create a Actinia command of the process chain that uses t.rast.udf
:param strds_name: The name of the strds
:param python_file_url: The URL to the python file that defin... | 78a76275a2f1dba30627f1a52acd88d2ce851ccc | 3,652,131 |
import requests
def add_user_to_authorization_domain(auth_domain_name, email, permission):
"""Add group with given permissions to authorization domain."""
# request URL for addUserToGroup
uri = f"https://api.firecloud.org/api/groups/{auth_domain_name}/{permission}/{email}"
# Get access token and and... | ac774e5d065c5dd5bb1994333c8893290c129162 | 3,652,132 |
import re
def error_032_link_two_pipes(text):
"""Fix some cases and return (new_text, replacements_count) tuple."""
(text, ignored) = ignore(text, r"\[\[\s*:?\s*{}.*?\]\]".format(IMAGE))
(text, count1) = re.subn(r"\[\[([^|\[\]\n]+)\|\|([^|\[\]\n]+)\]\]", "[[\\1|\\2]]", text)
(text, count2) = re.subn(r... | 071a56e8f87fcbbbd423f9754c16b57dd7a90b01 | 3,652,133 |
import random
def define_answer(defined_answer):
"""
ランダムに「正解」を生成する
1桁ずつ、0~15までの乱数を引いて決めていく
count桁目の乱数(digit_kari)を引いた時、count-1桁目までの数字と重複がないかをチェック。
重複がなければ、引いた乱数(digit_kari)をans_list[count]に保存。
重複してたらその桁の乱数を引き直す。
"""
global ans_str #,ans_list
if type(defined_answer) == st... | fa19b2e28864d4c09458582d6dea80b81b3426f6 | 3,652,134 |
def truncate_dataset_position(filename, joint_type="w", threshold=0.01, directory="./2_smoothed/"):
"""
Truncates dataset **with raw position data** from last zero value before maximum velocity to following zero value.
:param filename: Input filename of position dataset
:param joint_type: Chooses which... | 266a02a35f6f07e488629513f7252e16007d38cb | 3,652,136 |
def quadric_errors_representative(bucket):
"""
Quadric errors representative function.
:param bucket: bucket to calculate representative from.
:type bucket: Bucket
:return: bucket's representative vertex coordinates
:rtype: tuple(float, float, float)
"""
A = np.zeros((3, 3))
b = np.... | d613c8cdf7acb5add81d879e52a3c127d3731980 | 3,652,137 |
import time
def getMonthTicks(start, end, increment, offset=0):
"""
Create a set of matplotlib compatible ticks and tick labels
for every `increment` month in the range [start, end],
beginning at the month of start + `offset` months.
"""
xLabels = []
xTicks = []
y, m, d = helpers.yearm... | 398c8542b5cce3614b1efd9306b05c6ce1f6f185 | 3,652,138 |
def entropy_layer(inp, theta, num_samples, sample_init, sample_const, train_vect):
""" Entropy PersLay
WARNING: this function assumes that padding values are zero
"""
bp_inp = tf.einsum("ijk,kl->ijl", inp, tf.constant(np.array([[1.,-1.],[0.,1.]], dtype=np.float32)))
sp = tf.get_variable("s", shape=[... | d9f1155e576f382abfc467ed8704219a5017260d | 3,652,139 |
def set_version_code(data):
"""
Utility function to set new versionCode
"""
match = version_code_pattern.search(data)
if not match:
raise ValueError('Version code not found')
version_code = int(match.group('value'))
next_version_code = '\g<key> {}'.format(version_code + 1)
return... | f94392a06cbb4cda852ad83c8afcd3bae0603b52 | 3,652,140 |
import logging
from datetime import datetime
def add_resource(label, device_type, address, userid, password, rackid='', rack_location='',
ssh_key=None, offline=False):
""" Add device to the list of devices in the configuration managed
Args:
label: label for device
device_type:... | b94dc65fdf864e4f5226d6793702355a9cbe1e46 | 3,652,141 |
def kegg_df_to_smiles(kegg_df, column_name):
"""
Args:
kegg_df : pandas dataframe with SID numbers in the third column
Returns:
kegg_df : modified with a fourth column containing CID and fifth column containing SMILES
unsuccessful_list : list of SIDs for which no CID or SMILES were ... | 09c4f3af98bb287348c20fe0fe7e3ce0eb63e6fa | 3,652,142 |
import sqlite3
async def get_user(user_id: int) -> User:
"""Gets user settings.
Returns
-------
User object
Raises
------
sqlite3.Error if something happened within the database.
exceptions.NoDataFoundError if no user was found.
LookupError if something goes wrong reading the dic... | e754113b0d2b4791c6660f9b4e7122144f1638b6 | 3,652,143 |
def _valid_optimizer_args(cfg_user, logger):
"""
Validates the "optimizer" parameters of a json configuration file used for training.
The function returns False if an error has occurred and True if all settings have passed the check.
:param cfg_user: EasyDict, json configuration file imported as dicti... | 126d66cc04d7bafc5ef91a9d365cdca34d0fd36a | 3,652,144 |
def delete_host_network(host_id, host_network_id):
"""Delete host network."""
data = _get_request_data()
return utils.make_json_response(
200,
host_api.del_host_network(
host_id, host_network_id, user=current_user, **data
)
) | 047ffb411e8dfbde1a818ba31874280dfa113aa0 | 3,652,145 |
def rrms_error(y: np.array, y_hat: np.array) -> float:
"""
Computes the RRMS error of an estimation.
:param y: true parameters as numpy array
:param y_hat: estimated parameters as numpy array
:return: Frobenius norm of the relative estimation error, as percentage
"""
return fro_error(y, y_h... | 0b534c5b8047bd77a1873a604f3896eb597d7267 | 3,652,146 |
import locale
def create():
"""Creates new quiz and stores information about it in database."""
if request.method == "GET":
return render_template("quizzes/create.html")
error = None
questions = []
quiz_name = None
if isinstance(request.json, dict):
for quiz in request.json:
... | 002915c6e8c766053623bf70ab66225ddfdc0883 | 3,652,147 |
from typing import Dict
def get_teams_from_account(client: FrameioClient) -> Dict:
"""
Builds a list of teams for the account. Note: the API offers two strategies to fetch an account's teams,
`'get_teams`` and `get_all_teams`. Using `get_teams`, we'll pull only the teams owned by the account_id,
dis... | ebbc73e2aad3f6a0833dad469a8b952cc8eef21b | 3,652,148 |
def verify_mfib_vrf_hardware_rate(
device, vrf, num_of_igmp_groups, var, rate_pps, max_time=60, check_interval=10):
"""Verify mfib vrf hardware rate
Args:
device ('obj'): Device object
neighbors (`list`): neighbors to be verified
max_time (`int`, optional): Max time, defa... | 402c178acff9d58fec01e96efc08d205a5ff9c5e | 3,652,149 |
import math
def sieve(n):
"""
Returns a list with all prime numbers up to n.
>>> sieve(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> sieve(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> sieve(10)
[2, 3, 5, 7]
>>> sieve(9)
[2, 3, 5, 7]
>>> sieve(2)
[2]
... | f6c930c604839ba1872bd3168c76b353606ee8ee | 3,652,150 |
def is_trueish(expression: str) -> bool:
"""True if string and "True", "Yes", "On" (ignorecase), False otherwise"""
expression = str(expression).strip().lower()
return expression in {'true', 'yes', 'on'} | 7d958c068281deb68de7665dc1eeb07acf5e941f | 3,652,151 |
def u_onequbit_h(qc: qiskit.QuantumCircuit, thetas, wire: int):
"""Return a simple series of 1 qubit - gate which is measured in X-basis
Args:
- qc (QuantumCircuit): Init circuit
- thetas (Numpy array): Parameters
- wire (Int): position that the gate carries on
Returns:
... | 3bcb5e9bb61abe8eb0d150ba539f2b21d4089589 | 3,652,152 |
def get_manager() -> ArchiveManager:
"""
Returns the object storage manager for the archive subsys
:return:
"""
global _manager_singleton
if _manager_singleton is None:
raise Exception("Not initialized. Call init_archive_manager")
return _manager_singleton | c43edc20af5b3e9a18442cfbb4bdefa7e7442d1d | 3,652,153 |
def require_password_and_profile_via_email(
strategy, backend, user=None, flow=None, current_partial=None, *args, **kwargs
): # pylint: disable=unused-argument
"""
Sets a new user's password and profile
Args:
strategy (social_django.strategy.DjangoStrategy): the strategy used to authenticate
... | 63d7d6e61696e5a48d297b8911f1b48cc5c82e5e | 3,652,154 |
import copy
def plot_feat_barplot(feat_data: pd.DataFrame,
top_x_feats: int = 15,
plot_features: dict = None
):
"""Plots local feature explanations
Parameters
----------
feat_data: pd.DataFrame
Feature explanations
top_x_f... | 4fd976f4846163a97690143da18a8e235d1b940c | 3,652,155 |
async def post_ir_remote_key(device_id: str, remote_id: str, payload: dict) -> dict:
# fmt: off
"""
Trigger key / code on the remote bound to IR device. There are 2 types of keys on Tuya IR
devices:
* native - out of the box keys, provided with remotes for different brands
* custom - DIY... | 9c0fb945076c49564fa65f48971e0df0b2131794 | 3,652,156 |
import requests
import traceback
def login():
"""
The function for the front-end client to log in.
Use the following command to test:
$ curl -d '{"custom_id":"id"}' -H "Content-Type: application/json" -X POST http://0.0.0.0:5000/login/
Parameters
----------
google_id_token : str
... | a8de77d1f9f2c64fca6927c2d5fd29fa4133b31b | 3,652,157 |
def listThingTypes():
"""
Return a list of C{unicode} strings each of which gives the name of a type
which can be created with the create command.
"""
return sorted([type.type for type in getPlugins(IThingType, imaginary.plugins)]) | 31a98e58d2fd70cc7a1449e2e50946decbf98244 | 3,652,158 |
import json
def _parse_boolean(value):
"""
:param value: The string to parse
:type value: str
:returns: The parsed value
:rtype: bool
"""
try:
boolean = json.loads(value)
if boolean is None or isinstance(boolean, bool):
return boolean
else:
... | 60dcd4ed8663823fdf4df5c27e032c6693a11cc8 | 3,652,159 |
import torch
import time
def train(args, model, train_data_loader, dev_data_loader, accuracy, device):
"""
Train the current model
Keyword arguments:
args: arguments
model: model to be trained
train_data_loader: pytorch build-in data loader output for training examples
dev_data_loader: p... | fa5953bc4fc8554b1d0164eae96c1fd9ce949068 | 3,652,160 |
def get_category_embeddings(word_table, embeds):
"""Calculate embeddings from word labels for each category."""
category_words = read_categories_as_json()
word_ids = word_table.lookup(tf.constant(category_words))
glove_embeds = tf.nn.embedding_lookup(embeds, word_ids)
# Calculate category embedding by summin... | 23fbb867ec1390c49b0a217968d44f2abe189e57 | 3,652,161 |
import re
import requests
def find_download_links(soup, title, language):
"""Examine all download links per law document and create respective filepaths."""
vbfile = soup.find("div", "vbFile")
fulltext = soup.find("div", "fulltext")
# check if file attachment elements exist
if vbfile is not None... | 22c017c20ab2a3cfa9cfeb1e43ec2a24e9ff0cc7 | 3,652,162 |
import random
def fake_feature_date(days=365):
"""Generate fake feature_date."""
start_date = date.today()
random_number_of_days = random.randrange(days)
_date = start_date + timedelta(days=random_number_of_days)
return _date.strftime("%Y-%m-%d") | f9706d353eef0f531ab74b585cf966349faf4003 | 3,652,163 |
def export_graph(checkpoint_path, output_nodes):
"""
Export a graph stored in a checkpoint as a *.pb file.
:param checkpoint_path: The checkpoint path which should be frozen.
:param output_nodes: The output nodes you care about as a list of strings (their names).
:return:
"""
if not tf.gfile... | b83b832c0b0bea9afc0e84843061bd8091e63fc8 | 3,652,165 |
def GetTrackingBranch(git_repo, branch=None, for_checkout=True, fallback=True,
manifest=None, for_push=False):
"""Gets the appropriate push branch for the specified directory.
This function works on both repo projects and regular git checkouts.
Assumptions:
1. We assume the manifest def... | 0bb9bb99e03cebc800a0f60f89a8de5178fdffdc | 3,652,166 |
def inception_crop(image, **kw):
"""Perform an "inception crop", without resize."""
begin, size, _ = tf.image.sample_distorted_bounding_box(
tf.shape(image), tf.zeros([0, 0, 4], tf.float32),
use_image_if_no_bounding_boxes=True, **kw)
crop = tf.slice(image, begin, size)
# Unfortunately, the above ope... | c5d8dd420055ad82e64bc61204fb6218c7621489 | 3,652,167 |
import json
import logging
def _clear_port_access_clients_limit_v1(port_name, **kwargs):
"""
Perform GET and PUT calls to clear a port's limit of maximum allowed number of authorized clients.
:param port_name: Alphanumeric name of Port
:param kwargs:
keyword s: requests.session object with lo... | 46827c7a7ac70dba971e6fc04e9d101a8ca9e8b6 | 3,652,168 |
from typing import cast
def cvGetHistValue_1D(hist, i1):
"""Returns pointer to histogram bin"""
return cast(cvPtr1D(hist.bins, i1), c_float_p) | 6b1a453696d8d1fbeda54900c1319e56a9133118 | 3,652,169 |
import re
def contains_order_by(query):
"""Returns true of the query contains an 'order by' clause"""
return re.search( r'order\s+by\b', query, re.M|re.I) is not None | 4f4eebadfd5dc4cb1121378db4ef5f68d27bf787 | 3,652,170 |
def detach(l):
"""\
Set a layer as detached, excluding it from gradient computation.
:param l: layer or list of layers to detach
:return: detached layer(s)
"""
# core module has multiple overloads for this:
# 1. detach(l) where l is a Layer and the return value is a Layer
# 2. detach... | d4ea7c1496bbcc918ad55c32c852332d4f892e31 | 3,652,171 |
import re
def __shorten_floats(source):
""" Use short float notation whenever possible
:param source: The source GLSL string
:return: The GLSL string with short float notation applied
"""
# Strip redundant leading digits
source = re.sub(re.compile(r'(?<=[^\d.])0(?=\.)'), '', source)
# St... | 538645cde50e6c9a4ed3960cf6bbd177c5583381 | 3,652,172 |
def cnn_model(logits=False, input_ph=None, img_rows=28, img_cols=28,
channels=1, nb_filters=64, nb_classes=10):
"""
Defines a CNN model using Keras sequential model
:param logits: If set to False, returns a Keras model, otherwise will also
return logits tensor
:param in... | 488b307f394f9184d094aeb0a71d75442534d4c7 | 3,652,173 |
def _mvnormal_halton(sample_shape,
mean,
randomized,
seed=None,
covariance_matrix=None,
scale_matrix=None,
validate_args=False,
dtype=None,
**kwargs):
... | f3795f4c40e809b461c60b43f118a57b1bb18ba3 | 3,652,174 |
def get_meals(bouts_sec: np.ndarray, max_gap_sec: float = 60.0, min_overlap: float = 0.25):
"""
Computes a sequence of meal intervals from a sequence of chewing-bout intervals.
:param bouts_sec: The sequence of chewing-bout intervals (see ``get_bouts`` output)
:param max_gap_sec: Maximum gap-duration t... | aa4d66d71614825a71daddbb169994e8d3c4aac7 | 3,652,175 |
def setPerformanceLevel(source, level):
"""Sets a given performance level for the GPU Core and Memory.
Args:
source: string containing word "core" or "mem"
level: an integer between 0-7 for core and 0-3 memory
Returns:
True - if action is sucessful.
False - not possible to ... | ef13376acf51de0acb3491efcca731cdc3e569b3 | 3,652,176 |
from typing import OrderedDict
def elem_props_template_init(templates, template_type):
"""
Init a writing template of given type, for *one* element's properties.
"""
ret = OrderedDict()
tmpl = templates.get(template_type)
if tmpl is not None:
written = tmpl.written[0]
props = t... | c31d5ca8224763701f44471f23f00454c4365240 | 3,652,177 |
def to_density(x, bins=5, bounds=None):
""""Turn into density based nb of bins"""
p_x = np.histogram(x, bins=bins, density=True, range=bounds)[0]
p_x = p_x / np.sum(p_x)
return p_x | ce4af24ef57ca466a0f5d4b96ffff13ee45ddddb | 3,652,178 |
from datetime import datetime
def pro_bar(ts_code='', api=None, start_date='', end_date='', freq='D', asset='E',
exchange='',
adj = None,
ma = [],
factors = None,
adjfactor = False,
contract_type = '',
retry_count = 3):
"""
BAR数据
... | 8df29ce9ac89acabfb5109954f2deee515d707ca | 3,652,179 |
def ticket_qr_code(request, ticket_id):
""" Generates a qr code data url to validate a ticket with the id passed """
return segno.make(
validate_ticket_url(request, ticket_id),
micro=False
).svg_data_uri(scale=2) | 249b25d5d96651175e881284d31938fe56fe06dc | 3,652,181 |
def _iou(box_a, box_b):
"""
:param box_a: [c, A, 4]
:param box_b: [c, B, 4]
:return: [c, A, B] 两两之间的iou
"""
# 变成左上角坐标、右下角坐标
boxes1 = tf.concat([box_a[..., :2] - box_a[..., 2:] * 0.5,
box_a[..., :2] + box_a[..., 2:] * 0.5], axis=-1)
boxes2 = tf.concat([box... | f385b2a4ddfd6dfcae7b6cc3067e229c3dff768b | 3,652,182 |
import torch
def subsequent_mask(size, device=device):
"""
Mask out subsequent positions. upper diagonal elements should be zero
:param size:
:return: mask where positions are filled with zero for subsequent positions
"""
# upper diagonal elements are 1s, lower diagonal and the main diagonal a... | 5c642e8f73ee33307b54193db2a15ec80518e673 | 3,652,183 |
from typing import Optional
import google
def read_gcs_file_if_exists(gcs_client: storage.Client,
gsurl: str) -> Optional[str]:
"""return string of gcs object contents or None if the object does not exist
"""
try:
return read_gcs_file(gcs_client, gsurl)
except googl... | 1354d319dd20193fa097e4f2c6e7cce8edbda98b | 3,652,184 |
from typing import Union
from typing import List
from typing import Tuple
from typing import Dict
def collapse_multigraph_to_nx(
graph: Union[gr.MultiDiGraph, gr.OrderedMultiDiGraph]) -> nx.DiGraph:
""" Collapses a directed multigraph into a networkx directed graph.
In the output directed graph, ... | 1239393366071371116c5ebbb28209fa753b3db8 | 3,652,185 |
def get_encoder_type(encoder_name):
""" gets the class of the encoer of the given name """
if encoder_name == 'Dense':
return DenseEncoder
elif encoder_name == 'CNN':
return CNNEncoder
else:
raise ValueError(encoder_name) | 31fbce2fb26ebdaf2d3701d36d0d977039b03e42 | 3,652,186 |
def stateless_truncated_normal(shape,
seed,
mean=0.0,
stddev=1.0,
dtype=dtypes.float32,
name=None):
"""Outputs deterministic pseudorandom values, truncated normall... | b0b967cc6d8e489cb4f914f7306ef5d5376977b0 | 3,652,187 |
def mean(l):
"""
Returns the mean value of the given list
"""
sum = 0
for x in l:
sum = sum + x
return sum / float(len(l)) | 74926c9aaafd2362ce8821d7040afcba1f569400 | 3,652,188 |
from bettermoments.quadratic import quadratic
def collapse_quadratic(velax, data, rms):
"""
Collapse the cube using the quadratic method presented in `Teague &
Foreman-Mackey (2018)`_. Will return the line center, ``v0``, and the
uncertainty on this, ``dv0``, as well as the line peak, ``Fnu``, and the... | b19b6ee4b75c246e505fc5a4a47eac736c40599a | 3,652,190 |
def get_module_version(module_name: str) -> str:
"""Check module version. Raise exception when not found."""
version = None
if module_name == "onnxrt":
module_name = "onnxruntime"
command = [
"python",
"-c",
f"import {module_name} as module; print(module.__version__)",
... | 32c608491e012bd0b77d0e52aa206332877d889b | 3,652,191 |
import requests
def _post(url, data):
"""RESTful API post (insert to database)
Parameters
----------
url: str
Address for the conftrak server
data: dict
Entries to be inserted to database
"""
r = requests.post(url,
data=ujson.dumps(data))
r.raise... | 6cbf8700360e6eff868eef91125a692dfef5af47 | 3,652,192 |
import inspect
import functools
def curry(arity_or_fn=None, ignore_kwargs=False, evaluator=None, *args, **kw):
"""
Creates a function that accepts one or more arguments of a function and
either invokes func returning its result if at least arity number of
arguments have been provided, or returns a fun... | 225f9295894538046f3dc5390964416c2ef6a7d1 | 3,652,193 |
def fin_forecast(ratio1, ratio2, sp_df):
"""used to forecast 3 years of financial forecast/projection
"""
print("print test line 6")
forecast = MCSimulation(
portfolio_data = sp_df,
weights = [ratio1, ratio2],
num_simulation = 500,
num_trading_days = 252*3
)
print... | 7d081d58bf9ec779fe6a68818e0f245c9c634db8 | 3,652,195 |
def implied_volatility(price, S, K, t, r, q, flag):
"""Calculate the Black-Scholes-Merton implied volatility.
:param S: underlying asset price
:type S: float
:param K: strike price
:type K: float
:param sigma: annualized standard deviation, or volatility
:type sigma: float
:param t: tim... | d3db13c24cf491df519d286e25da2e0a33448615 | 3,652,197 |
import re
def clean_hotel_maxpersons(string):
"""
"""
if string is not None:
r = int(re.findall('\d+', string)[0])
else:
r = 0
return r | d20d9db1da49eea1a4057e43b9f43f2960dbd27a | 3,652,198 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.