content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import glob
def wav16khz2mfcc(dir_name):
"""
Loads all *.wav files from directory dir_name (must be 16kHz), converts them into MFCC
features (13 coefficients) and stores them into a dictionary. Keys are the file names
and values and 2D numpy arrays of MFCC features.
"""
features = {}
for ... | 6eae15a7ac999cd42c1e3161221356cf720d54c0 | 3,636,927 |
def add_metadata(infile, outfile, sample_metadata):
"""Add sample-level metadata to a biom file. Sample-level metadata
should be in a format akin to
http://qiime.org/tutorials/tutorial.html#mapping-file-tab-delimited-txt
:param infile: String; name of the biom file to which metadata
... | e779f876159741de60e99002a90906b151dc7530 | 3,636,928 |
def multinomial(n):
"""Finds the multinomial coefficient for a given array of numbers.
Args:
n (list): the interegs to be used.
"""
binomials = [[np.sum(n),n[0]]]
for i in range(1,len(n)):
new_sum = binomials[i-1][0]-binomials[i-1][1]
binomials.append([new_sum,n[i]])
... | 6f38656d295a4d5ecf32a01a238cdad701e6e530 | 3,636,929 |
def get_qc_data(sample_prj, p_con, s_con, fc_id=None):
"""Get qc data for a project, possibly subset by flowcell.
:param sample_prj: project identifier
:param p_con: object of type <ProjectSummaryConnection>
:param s_con: object of type <SampleRunMetricsConnection>
:returns: dictionary of qc resul... | f267148f48f86151852e12fa3be8d5f8aefc6b11 | 3,636,930 |
def sql_sanitize(sql_name):
"""
Return a SQL name (table or column) cleaned of problematic characters.
ex. punctuation )(][; whitespace
Don't use with values, which can be properly escaped with parameterization.
Ideally retaining only alphanumeric char.
Credits: Donald Miner, Source: StackOverfl... | 9ce9e0e8bed2348079fb23f2d27c53880fa1c795 | 3,636,931 |
def exists(name):
"""
`True` if a category named `name` exists;
`False` otherwise.
"""
return db.cursor().execute('SELECT COUNT(*) FROM categories WHERE name = ?', (name,)).fetchone()[0] != 0 | e15f5d961a4420ef6bd00fa393ab9af440e5f983 | 3,636,933 |
def ESMP_MeshGetOwnedElementCount(mesh):
"""
Preconditions: An ESMP_Mesh has been created.\n
Postconditions: The owned elementCount for 'mesh' has been
returned.\n
Arguments:\n
:RETURN: integer :: elementCount\n
ESMP_Mesh :: mesh\n
"""
lec = ct.c_int(0)... | 067411ba3b2fbc4f862375e2a3699d617999b6ed | 3,636,934 |
def remove_control_chars_author(input):
"""
:param input:
:return:
"""
return CONTROL_CHAR_RE.sub('', input) | 632bb20de05f3461156fa7ed311b9a04459de60f | 3,636,935 |
def run():
"""Default Run Method"""
return problem51(8) | 3357bb4e6461f8142f93fc394f3b5aba0fba7ceb | 3,636,936 |
def calc_c(e, a, b, u=1): # Check units
"""
calculate the z components of 4 partial waves in medium
e: dielectric tensor
a,b: components of wavevector in direction of x and y direction
return a list containting 4 roots for the z components of the partial waves
"""
# assign names
x = ... | 46a1ae481c9525ecc7ae1e5e3b119b8d3983ca16 | 3,636,937 |
from typing import Sequence
from typing import Tuple
def _jax_decode(
compressed_message: ndarray,
tail_limit: int,
message_len: int,
message_shape: Sequence[int],
codec: CrayCodec,
cdf_state: Sequence[ndarray],
) -> Tuple[Tuple[ndarray, int], ndarray, Sequence[ndarray]]:
"""
JAX rANS ... | 648cb4af4ddaaec01e5d5997e8698aad6acd4c01 | 3,636,938 |
def subtask1_eval(_answers, _ref):
"""
子任务1的评分函数。
:param _answers: 答卷答案。
:param _ref: 参考答案。
:return: 统计数据对象。
"""
_map = {
'11': 'TP',
'00': 'TN',
'10': 'FN',
'01': 'FP',
}
_st = {
'TP': 0,
'TN': 0,
'FN': 0,
'FP': 0,
... | 7249992f70b67928a99e96c7877e5ef4be261429 | 3,636,939 |
def render_horizontal_fields(*fields_to_render, **kwargs):
"""Render given fields with optional labels"""
labels = kwargs.get('labels', True)
media = kwargs.get('media')
hidden_fields = []
visible_fields = []
for bound_field in fields_to_render:
if bound_field.field.widget.is_hidden:
... | 22ac9c05b602c0f65ab2fc348ab9399855780bc3 | 3,636,940 |
def get_darwin_memory():
""" Use system-call to extract total memory on macOS """
system_output = sabnzbd.newsunpack.run_simple(["sysctl", "hw.memsize"])
return float(system_output.split()[1]) | 1458881c61cdb5b765c4c56fa494ff7c6f06c49b | 3,636,941 |
from datetime import datetime
def parseTextModeTimeStr(timeStr):
""" Parses the specified SMS text mode time string
The time stamp format is "yy/MM/dd,hh:mm:ss±zz"
(yy = year, MM = month, dd = day, hh = hour, mm = minute, ss = second, zz = time zone
[Note: the unit of time zone is a quarter of an... | 52a45116a2b0153595161f94fda38129ddd59b3a | 3,636,942 |
import torch
def angle_to_rotation_matrix(angle) -> Tensor:
"""
Creates a rotation matrix out of angles in degrees
Args:
angle: (Tensor): tensor of angles in degrees, any shape.
Returns:
Tensor: tensor of *x2x2 rotation matrices.
Shape:
- Input: :math:`(*)`
- Outp... | 9b88eaa0277d0c3ad672e94e4d41ec45ebe0b272 | 3,636,943 |
def extract_text():
"""Extracts text from an HTML document."""
html = request.form['html']
article = Article(html)
try:
return article.text
except AttributeError as e:
log.warn(e)
# NOTE: When a parsing error occurs, an AttributeError is raised.
# We'll deal with this... | 8efc10539462ab51715b54b17a018e5f296496eb | 3,636,944 |
import json
import time
def get_new_account_id(event):
"""Return account id for new account events."""
create_account_status_id = (
event["detail"]
.get("responseElements", {})
.get("createAccountStatus", {})["id"] # fmt: no
)
log.info("createAccountStatus = %s", create_accoun... | 4433b080b24d1a7ad276541103e55acf7bbfa137 | 3,636,945 |
from typing import List
def lag_indexes(tf_stat)-> List[pd.Series]:
"""
Calculates indexes for 3, 6, 9, 12 months backward lag for the given date range
:param begin: start of date range
:param end: end of date range
:return: List of 4 Series, one for each lag. For each Series, index is date in ran... | de8d355d213146013eb4720860dd844d22ccab45 | 3,636,946 |
def weather_outfit(req):
"""Returns a string containing text with a response to the user
with a indication if the outfit provided is appropriate for the
current weather or a prompt for more information
Takes a city, outfit and (optional) dates
uses the template responses found in weather_responses.... | ee5b3cd3ed10062155bbce532343ef51f9a83177 | 3,636,947 |
from sentence_splitter import SentenceSplitter
def parse_paragraphs(record):
"""
parse paragraphs into sentences, returns list
"""
splitter = SentenceSplitter(language='en')
sentences=splitter.split(record['value'])
article_id = remove_prefix(record['key'],'paragraphs:')
pre = 'sentence:' ... | 9a8cce4692af5e61b9f01becd8dafa9234c08f17 | 3,636,948 |
def get_stage_environment() -> str:
"""
Indicates whether the source is running as PRD or DEV. Accounts for the
user preference via TEST_WORKING_STAGE.
:return: One of the STAGE_* constants.
"""
return TEST_WORKING_STAGE | 1c2e14132af1760a13aae268b5179e70c79f5df5 | 3,636,949 |
def get_all_table_acls(conn, schema=None):
"""Get privileges for all tables, views, materialized views, and foreign
tables.
Specify `schema` to limit the results to that schema.
Returns:
List of :class:`~.types.SchemaRelationInfo` objects.
"""
stmt = _table_stmt(schema=schema)
retu... | 9067a614197d19c3256828b2a8dbb491bede0fe6 | 3,636,950 |
def add_atom_map(molecule, **kwargs):
"""
Add canonical ordered atom map to molecule
Parameters
----------
molecule :
`oechem.OEMOl` or `rdkit.Chem.Mol`
Returns
-------
molecule with map indices
"""
toolkit = _set_toolkit(molecule)
return toolkit.add_atom_map(molecu... | 584324aae018f211fc31c9f727687e9a6971822d | 3,636,951 |
from typing import Any
def build_put_dictionary_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest:
"""Put External Resource as a Dictionary.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:keyword jso... | 045c00835d592d777a155696bda76a5ecb12aa6f | 3,636,952 |
def midpoint(rooms):
"""
Helper function to help find the midpoint between the two rooms.
Args:
rooms: list of rooms
Returns:
int: Midpoint
"""
return rooms[0] + (rooms[0] + rooms[2]) // 2, rooms[1] + (rooms[1] + rooms[3]) // 2 | 60b3ba53fb15154ff97ab9c6fa3cf1b726bc2df1 | 3,636,953 |
def secondSolution( fixed, c1, c2, c3 ):
"""
If given four tangent circles, calculate the other one that is tangent
to the last three.
@param fixed: The fixed circle touches the other three, but not
the one to be calculated.
@param c1, c2, c3: Three circles to which the other tangent c... | a5f7545a3c4600e29bfdb9c516ede6ba244894c3 | 3,636,954 |
import random
def generate_concept_chain(concept_desc, sequential):
"""
Given a list of availiable concepts, generate a dict with (start, id) pairs
giving the start of each concept.
Parameters
----------
sequential: bool
If true, concept transitions are
determined by ID witho... | fcfeb345d92d627684d04da4c1d445120554bf15 | 3,636,955 |
def get_inputs(input_queue,
num_classes,
merge_multiple_label_boxes=False,
use_multiclass_scores=False):
"""Dequeues batch and constructs inputs to object detection model.
Args:
input_queue: BatchQueue object holding enqueued tensor_dicts.
num_classes: Number of... | 96185efe5e1b6ee3064136e052387da0bfb1ddaa | 3,636,956 |
def doFilter(pTable, proxyService):
"""
filter candidates by column header candidates
- column headers are kept, if they support at least (minSupport * #rows) many cells
- only filter for columns that are part of the targets (if activated)
subsequently remove:
- CTA candidates with less support... | 8b28f945e94e37302b2086e23f695c40c08b8d7c | 3,636,957 |
def int_or_float(x):
"""Convert `x` to either `int` or `float`, preferring `int`.
Raises:
ValueError : If `x` is not convertible to either `int` or `float`
"""
try:
return int(x)
except ValueError:
return float(x) | d0a4def320f88655e494f89b7239e47e1ee70d0d | 3,636,958 |
def request_factory():
"""Pytest setup for factory."""
return RequestFactory() | d6b5710dd42da06f6bb10e23fe3826a6a754228a | 3,636,959 |
def is_onehotencoded(x):
"""If input is a one-hot encoded representation of some set of values.
Parameters
----------
x : array-like
Returns
-------
bool
Whether `x` is a one-hot encoded / categorical representation.
"""
if x.ndim != 2:
return False
fractional,... | 21a023afeec886512ef806c76ade5523817ef350 | 3,636,960 |
def sequence_of_words(fname_doc, dictionary):
"""
Compute Sequence-of-Words from word list and dictionary
"""
txtdata = loadtxt(fname_doc)
words = extract_keyword(txtdata, "all")
SOW = []
for i,word in enumerate(words):
print(word)
if word in dictionary.keys():
S... | 92aeb61ce91b7149143bfb67905793caee83d3be | 3,636,961 |
def shd(B_est, B_true):
"""Compute various accuracy metrics for B_est.
true positive = predicted association exists in condition in correct direction
reverse = predicted association exists in condition in opposite direction
false positive = predicted association does not exist in condition
Args:
B_true (np.nda... | 04c1fb44025ae1a3cfd86bc877c68e93027b75fe | 3,636,962 |
def nohighlight(nick):
"""add a ZWNJ to nick to prevent highlight"""
return nick[0] + "\u200c" + nick[1:] | 1b8d0cafc5df4a442daafdece59af1675ab1de33 | 3,636,964 |
def _get_r_val(z, omega_m, omega_l):
"""Returns the comoving distance at for one z value.
Parameters
----------
z : float
Redshift.
omega_m : float
Present matter density.
omega_l : float
Present dark energy density.
"""
r, err = integrate.quad(_get_r_integrand, ... | 4f33eccdf4485c640f5c71808485fbf96a5f7614 | 3,636,965 |
def user_response_controller(bank_request, user_response):
"""
processes user's response for bank's request sent
: bank_request --> what is user currently requesting for
: user_response --> what a user wants to actually do amongst the options in the
above bank_requests
"""
user_re... | 3d959fac84a8460e7ab228127d9b6f0b9cc1a21c | 3,636,966 |
from datetime import datetime
def create_features(datestrs):
"""
Find the features associated with a set of dates.
These will include:
weekday / weekend
day of week
season
month of year
Parameters
----------
datestrs: list of strings
Date strings of the... | 75a72a54396150ed73ea43b3390994b1a41d2cf5 | 3,636,967 |
import inspect
def obj_src(py_obj, escape_docstring=True):
"""Get the source for the python object that gets passed in
Parameters
----------
py_obj : callable
Any python object
escape_doc_string : bool
If true, prepend the escape character to the docstring triple quotes
Retu... | 8ce0c7cc7672de5005b5a1c60e6b6cf5fa9ee050 | 3,636,968 |
def get_back_button_handler(current_panel: "GenericPanel") -> CallbackQueryHandler:
"""
returns a Handler for BACK_PATTERN that returns the user to current_panel
:param GenericPanel current_panel: the destination panel
:return: a CallbackQueryHandler for BACK_PATTERN that returns the user to current_pa... | 365e37b3d362afa31d231613180070be69ac7972 | 3,636,969 |
from typing import Optional
def openocd_prog_path(request: FixtureRequest) -> Optional[str]:
"""Enable parametrization for the same cli option"""
return _request_param_or_config_option_or_default(request, 'openocd_prog_path', None) | f3628427bde73d7e26e5ed30e103d4ba36df7c1b | 3,636,970 |
def reindexMatrix(iss, jss, A):
"""iss and jss are lists of indices of equal size, representing
a permuation: iss[i] is replaced with jss[i]. all other indices which are
not in the lists left unchanged.
"""
n = len(A)
B = np.zeros_like(A)
tss = [i for i in range(n)]
for i in range(len(is... | 9c36802d7e5f35ca6789d49e47d8124bc4f74c57 | 3,636,971 |
def createInfoMatix(character_id):
"""初始化创建的角色的阵法
"""
petlist = getCharacterPetList(character_id)
sql = "INSERT INTO `tb_character_matrix`(`characterId`,`eyes_4`,`eyes_5`,`eyes_6`) \
VALUES(%d,%d,%d,%d);"%(character_id,petlist[0],petlist[1],petlist[2])
conn = dbpool.connection()
cursor = co... | 7392f899ed8b46fd35ed360601edd8621aace7ac | 3,636,972 |
def help():
"""<b>Print available functions as json.<br>"""
func_list = {}
for rule in app.url_map.iter_rules():
if rule.endpoint != 'static':
func_list[rule.rule] = app.view_functions[rule.endpoint].__doc__
return jsonify(func_list) | 2ef2193aaa9d882b238a7681cb3e868690a58398 | 3,636,973 |
def version():
"""
Returns the name, version and api_version of the application when
a HTTP GET request is made.
"""
return jsonify(
name='openshift-python-flask-sample',
version=VERSION
) | 70686195978cf9d26e2d4cd954c81fc216d7bd4d | 3,636,975 |
import json
def search_quotes(request, currency):
""" Consulta a API procurando por ações que contenham o campo 'currency' no nome """
# verifica se a barra de pesquisa foi preenchida ou se está vazia
if currency:
conn.request("GET", "/auto-complete?q="+currency+"®ion=BR", headers=headers)
... | 926f29d802a7bb6a9681b3b90fd46966894a0604 | 3,636,976 |
def destroy(N, dtype=tf.complex64):
"""Returns a destruction (lowering) operator in the Fock basis.
Args:
N (int): Dimension of Hilbert space
dtype (tf.dtypes.DType, optional): Returned dtype. Defaults to c64.
Returns:
Tensor([N, N], dtype): NxN creation operator
"""
a = diag... | a92ef2cc5aa9b7bbe2c0cf109282c5fde56d4603 | 3,636,977 |
from typing import Optional
from typing import Any
def get_nearest_operation(
db: Redis[bytes], address: hash_t, subdag: Optional[str] = None
) -> Optional[Operation]:
"""Return the operation at address or the operation generating address."""
root = "root"
art = None
try:
node = Operation.... | a402ed795d60f321cd362517e9350994be836cdd | 3,636,978 |
def load_CIFAR_batch(file_path):
""" load single batch of cifar """
data_dict = load_pickle(file_path)
data = data_dict['data']
labels = data_dict['labels']
data = data.reshape(10000, 3, 32, 32).astype("float")
labels = np.array(labels)
return data, labels | 0164293fb2f31e7361da5a817c64899db96c6156 | 3,636,979 |
def _disposable_and_async_gen_from_obs(obs: Observable):
"""
Compatability layer for legacy Observable to async generator
This should be removed and subscription resolvers changed to
return async generators after removal of flask & gevent based dagit.
"""
queue: Queue = Queue()
disposable ... | ed0620b3615a36e82c20789f6a3b40aa6ae61410 | 3,636,980 |
def interesting_pattern(x: float, y: float) -> float:
"""This function is interesting in x and y in range -10..10, returning
a float value in range 0..1
"""
z = 0.5 + (np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)) / 2
return z | 432e13324b1834cbdd62259f0ac0b59751008f90 | 3,636,981 |
def interp_road(d,croad,roads,intersections,normD = False):
""" Get the position of a point along a road """
start_int = roads[croad]['start_int']
start_pos = intersections[start_int]['position']
end_int = roads[croad]['end_int']
end_pos = intersections[end_int]['position']
if not normD:
... | f6406dbb586ba2870d95f627f18085ec12c3b64b | 3,636,983 |
def zero_pad2d(inputs, padding=0, output_dtype="float32", requires_grad=False):
"""
Zero padding for 2d tensor
Args:
-----------------------------
inputs : Tensor
shape [batch, channel, height, width]
padding: (optional:0) int or tuple
expected: (h_pad_up, h_pad_down, w_pad_up, ... | 77ae8065f6e1c3b181a6bb49bd84ae4951848d7b | 3,636,984 |
def gtfs_admin(request):
"""admin page for adding new review categories (and potentially other features down the road)"""
return render(request, 'admin/gtfs_admin.html') | 14fccf4c1a8758fa223133f6e191860b6aee01a9 | 3,636,985 |
def get_file_path():
"""
Get current file's directory.
Return `None` if there is no file path available.
"""
try:
file_path = sublime.active_window().extract_variables()['file_path']
except KeyError:
return None
else:
return file_path | 0f991da4edf82435260aad443a4b506d1e2a5453 | 3,636,986 |
import random
def mutate_word(word):
"""Introduce a random change into the word: delete, swap, repeat, and add
stray character. This may raise a ValueError. """
word = list(word)
choice = random.randrange(4)
if choice == 0: # Delete a character
word.pop(random.randrange(len(word)))
... | f3b45f36893a7541131710ada5f1343387f06797 | 3,636,987 |
def data_layer_property_from_dict(data_layer_property_dictionary: dict,
client: cl.Client = None):
"""
The method converts a dictionary of DataLayerProperty to a DataLayerProperty object.
:param data_layer_property_dict: A dictionary that contains the keys of a Data... | ab579c1d6527abb176cd05c81d89fb1a74af50b0 | 3,636,988 |
def pcc_vector(v1, v2):
"""Pearson Correlation Coefficient for 2 vectors
"""
len1 = len(v1)
len2 = len(v2)
if len1 != len2:
return None
else:
length = len1
avg1 = 1.0 * sum(v1) / len(v1)
avg2 = 1.0 * sum(v2) / len(v2)
dxy = [(v1[i] - avg1) * (v2[i] - avg2) for i in ra... | 98e5f3cc304a5d844be479d65ab7eeb760a34ba3 | 3,636,989 |
from io import StringIO
def cypher_repr(obj):
""" Generate the Cypher representation of an object.
"""
string = StringIO()
writer = CypherWriter(string)
writer.write(obj)
return string.getvalue() | eae9e848076a4626a001e70b9cd925734864b3ae | 3,636,990 |
def firstlastmile_pipeline(**kwargs):
"""The first and last mile pipeline attaches any unattached elements to ensure a fully-connected graph"""
tags = ['flmile']
firstmile_nodes = [
node(
firstmile_edge,
['sjoin_oilfields_data','sjoin_edges_pipelines_oilfields','sjoin_po... | 545fda88458fb0266b0f4f98791de83759ba96f5 | 3,636,991 |
def photo_new(request, cast: Cast):
"""
Add a new Photo to a cast
"""
if request.method == 'POST':
form = CastPhotoForm(request.POST, request.FILES)
if form.is_valid():
photo = form.save(commit=False)
photo.cast = cast
photo.save()
messages... | cf9aac5f0ea49e48e571d89227c69f8ff382162a | 3,636,992 |
def decode(argument: str) -> tuple[list[int], ...]:
"""Decode argument string from command line
:param argument: argument string
:return: pair of list of digits
"""
char_lists = map(list, argument.split('-'))
range_ = tuple(list(map(int, clist)) for clist in char_lists)
return range_ | d3805396cab52fc09896ca9553f1ac3450f27e99 | 3,636,993 |
def get_search_apps():
"""Gets all registered search apps."""
return tuple(_load_search_apps().values()) | 5287abce0a31e9eb2165aafb8a6cfbaabda85e48 | 3,636,995 |
def volume_tetrahedron(
point_a: array_like, point_b: array_like, point_c: array_like, point_d: array_like
) -> np.float64:
"""
Return the volume of a tetrahedron defined by four points.
The points are the vertices of the tetrahedron. They must be 3D or less.
Parameters
----------
point_a,... | 3369044cfe53762c9bbbf8363da5d385b14b51ba | 3,636,996 |
def lemmatizer(word):
"""Returns: lemmatized word if word >= length 5
"""
if len(word)<4:
return word
return wnl.lemmatize(wnl.lemmatize(word, "n"), "v") | f8e5020b85638464b261e1ec066a141ba4a202a0 | 3,636,997 |
def kolmogn(n, x, cdf=True):
"""Computes the CDF for the two-sided Kolmogorov-Smirnov distribution.
The two-sided Kolmogorov-Smirnov distribution has as its CDF Pr(D_n <= x),
for a sample of size n drawn from a distribution with CDF F(t), where
D_n &= sup_t |F_n(t) - F(t)|, and
F_n(t) is the Empiri... | 132672a1bf45bb0b675c3ce503d47ed4f740184b | 3,636,998 |
from typing import Tuple
def watermark_pdf(input_file: str, wm_text: str, pages: Tuple = None):
"""
Adds watermark to a pdf file.
"""
result, wm_buffer = create_watermark(wm_text)
if result:
wm_reader = PdfFileReader(wm_buffer)
pdf_reader = PdfFileReader(open(input_file, 'rb'), str... | 3fb4d51a88db9c509842ee76b7fee22af30a358d | 3,637,000 |
def wrapper_configuration_get(): # noqa: E501
"""gets configuration details on the current wrapper configuration
# noqa: E501
:rtype: object
"""
return 'do some magic!' | 85ac6abbf09f93a08295584d7051aad2e8cad8d6 | 3,637,001 |
def update_qgs():
"""Generate QGIS project files."""
try:
# create ConfigGenerator
generator = config_generator()
qgs_writer_log = generator.write_qgs()
return {
'message': "Finished writing QGIS project files",
'log': qgs_writer_log
}
except ... | 1cb7f6f844fc40b611dc49b8f2b5a8de795e04e0 | 3,637,002 |
from typing import Tuple
from typing import List
import warnings
def time_evolution_derivatives(
hamiltonian: pyquil.paulis.PauliSum,
time: float,
method: str = "Trotter",
trotter_order: int = 1,
) -> Tuple[List[circuits.Circuit], List[float]]:
"""Generates derivative circuits for the time evoluti... | fe793657d9fa199df174a288f59a390c7787598c | 3,637,003 |
def had_cells_strength(strmfunc, min_plev=None, max_plev=None, lat_str=LAT_STR,
lev_str=LEV_STR):
"""Location and signed magnitude of both Hadley cell centers."""
lat = strmfunc[lat_str]
# Sometimes the winter Ferrel cell is stronger than the summer Hadley cell.
# So find the glo... | ba8b4840a3e7e851a7156cd6aed1e3969e362692 | 3,637,004 |
def d_enter_waste_cooler(W_mass, rho_waste, w_drift):
"""
Calculates the tube's diameter of enter waste to waste cooler.
Parameters
----------
W_mass : float
The mass flow rate of waste, [kg/s]
rho_waste : float
The density of liquid at boilling temperature, [kg/m**3]
w_drift... | 651c1adc0b90a286c2c8685c389268bc8834ad73 | 3,637,005 |
async def finalize_round(request, persistence):
"""Finalize an owned round."""
game_id = request.match_info['game_id']
round_name = request.match_info['round_name']
user_session = await get_session(request)
if not client_owns_game(game_id, user_session, persistence):
return json_response({'... | 21c07b35eb366d1ca78a90940bfb85772469683f | 3,637,006 |
def _arrs_to_ds(arrs, names=None):
"""Combine DataArrays into a single Dataset."""
if names is None:
names = [str(n) for n in range(len(arrs))]
return xr.Dataset(data_vars=dict(zip(names, arrs))) | 5672ba30c43d646a637d1db5735df23f916f012b | 3,637,007 |
from datetime import datetime
import time
def formatTimeFromNow(secs=0):
""" Properly Format Time that is `x` seconds in the future
:param int secs: Seconds to go in the future (`x>0`) or the
past (`x<0`)
:return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`)
... | b36e68466c05eb33f178d2568b3c2ff21bc9c707 | 3,637,008 |
def exitFlow(x, n_classes):
""" Create the exit flow section
x : input to the exit flow section
n_classes : number of output classes
"""
def classifier(x, n_classes):
""" The output classifier
x : input to the classifier
n_classes : number of o... | 95ac0696e03cb6e3320cebd20790e2f07c69d4ee | 3,637,009 |
from typing import Optional
def SingleChannelDDR4_2400(size: Optional[str] = "1024MB") -> SingleChannel:
"""
A single channel DDR3_2400.
:param size: The size of the memory system. Default value of 1024MB.
"""
return SingleChannel("DDR4_4Gb_x8_2400", size) | 10a83cd74b55f5ec93812fd1d52c8d753d9024d4 | 3,637,011 |
def convert_Pa_to_dBSPL(pa):
""" Converts units of Pa to dB re 20e-6 Pa (dB SPL) """
return 20. * np.log10(pa / 20e-6) | a14991c7923b7ceb46f279a95b3ef64ff648ae57 | 3,637,012 |
def isPalindromic(seq):
"""
is a sequence palindromic?
returns True or False
"""
if rc_expanded(seq.lower()) == seq.lower():
return(True)
return(False) | bbe011e0b599f8df417ffc10eef0ace0d8f08d37 | 3,637,013 |
import numpy
import random
def randomPairsMatch(n_records_A: int, n_records_B: int, sample_size: int) -> IndicesIterator:
"""
Return random combinations of indices for record list A and B
"""
n: int = n_records_A * n_records_B
if not sample_size:
return iter([])
elif sample_size >= n:... | 2cd6f905933149b4f23f656e9db44f57830e1eb9 | 3,637,015 |
import logging
def GetScaffoldLengths(genome_fna_fp):
""" This function gets the lengths of the scaffolds, returns a dict
Args:
genome_fna_fp: (str) Path to genome fna file (FASTA)
Returns:
Scaffold_To_Length: (dict)
scaffold_name: (str) -> length (int)
"""
Scaffold... | cee4c6a3d9171dc86563e5f74dae6fbdfcb0556a | 3,637,016 |
def flip_mesh(mesh):
"""
It flips the mesh of a shape.
----------------------------
Args:
mesh (obj: 'base.Trimesh'): The mesh of a shape
Returns:
mesh (obj: 'base.Trimesh'): The flipped mesh of the shape
"""
triangles = np.zeros((3, len(mesh.faces)))
for i, index in en... | a527b47a4f1c184a97d4ee7005d05be7926e0258 | 3,637,018 |
def leaky_twice_relu6(x, alpha_low=0.2, alpha_high=0.2, name="leaky_relu6"):
""":func:`leaky_twice_relu6` can be used through its shortcut: :func:`:func:`tl.act.ltrelu6`.
This activation function is a modified version :func:`leaky_relu` introduced by the following paper:
`Rectifier Nonlinearities Improve N... | 17c4fce9bd8803cda254fb28cde72e5401760c3d | 3,637,019 |
def fully_connected(inputs,
num_outputs,
scope,
use_xavier=True,
stddev=1e-3,
weight_decay=0.0,
activation_fn=tf.nn.relu,
bn=False,
bn_decay=None,
... | 01646dd4d18a210b298c313b13a03274c69fd127 | 3,637,020 |
def _x_orientation_rep_dict(x_orientation):
""""Helper function to create replacement dict based on x_orientation"""
if x_orientation.lower() == 'east' or x_orientation.lower() == 'e':
return {'x': 'e', 'y': 'n'}
elif x_orientation.lower() == 'north' or x_orientation.lower() == 'n':
return {... | 83434a8aef7003146a19c470b831e8e9cfa85f19 | 3,637,021 |
def move_at_objc_to_access_note(access_notes_file, arg, offset, access_note_name):
"""Write an @objc attribute into an access notes file, then return the
string that will replace the attribute and trailing comment."""
access_notes_file.write(u"""
- Name: '{}'
ObjC: true""".format(access_note_name))
... | 6037b6db15188ce43771d47f01518994f562d409 | 3,637,022 |
def test_idempotent_lambda_with_validator_util(
config_without_jmespath: IdempotencyConfig,
persistence_store: DynamoDBPersistenceLayer,
lambda_apigw_event,
timestamp_future,
serialized_lambda_response,
deserialized_lambda_response,
hashed_idempotency_key_with_envelope,
mock_function,
... | 75e0d3a8aabb3e3520c06a0268a7e2d1e534d249 | 3,637,023 |
def get_version_if_modified(gh_type, repo_name, typ, force=False):
"""
Return the latest version if the latest version is different
from the previously indexed version.
Return None if no change.
if force in True, always return the latest version
"""
latest_version = get_latest_version(gh_typ... | 51dcd251dece6e6e401261f79007be8fcd653844 | 3,637,025 |
import requests
import json
def do_rest_request(**kwargs):
"""This function expects full_url or in absence of which, expects a combination of "url" and "query_params"""
if 'full_url' in kwargs:
query_url = kwargs['full_url']
elif 'rest_url' in kwargs and 'query_params' in kwargs:
query_ur... | 0ee2d7e20ca98e2c73b8d4b3e89d709a1b14a911 | 3,637,026 |
def variable(init_val, lb=None, ub=None):
"""
Initialize a scalar design variable.
:param init_val: Initial guess
:param lb: Optional lower bound
:param ub: Optional upper bound
:return: The created variable
"""
var = opti.variable()
opti.set_initial(var, init_val)
if lb is not N... | 6cd346effba937a43c555e3e0e1e7b3fecf231e3 | 3,637,027 |
def current_user() -> str:
"""
Retorna o usuário corrente.
"""
session_id = request.get_cookie(cookie_session_name())
c = get_cursor()
c.execute(
"""
select username
from sessions
where session_id = :session_id
""",
{"session_id": session_id},
)
... | ec2b16f671a9fd11762160bcb73f770d9bc5eb7a | 3,637,028 |
async def async_setup(hass, hassconfig):
"""Setup Component."""
hass.data.setdefault(DOMAIN, {})
config = hassconfig.get(DOMAIN) or {}
hass.data[DOMAIN]['config'] = config
hass.data[DOMAIN].setdefault('entities', {})
hass.data[DOMAIN].setdefault('configs', {})
hass.data[DOMAIN].setdefault('... | 5708286ac76bc01ff8b979632d8d030192600e3f | 3,637,029 |
def get_node_centroids(mesh):
"""
Calculate the node centroids of the given elements.
Parameters
----------
mesh : list of dicts or single dict
each dict containing
at least the following keywords
nodes : ndarray
Array with all node postions.
... | eb7244184921a9728ce12e0f7eaf46bd52cf2399 | 3,637,031 |
def find_saas_replication_price(package, tier=None, iops=None):
"""Find the price in the given package for the desired replicant volume
:param package: The product package of the endurance storage type
:param tier: The tier of the primary storage volume
:param iops: The IOPS of the primary storage volu... | 5f3abdd4a2edd24abd8c19752316b06e76212532 | 3,637,032 |
def _get_option_of_highest_precedence(config, option_name):
"""looks in the config and returns the option of the highest precedence
This assumes that there are options and flags that are equivalent
Args:
config (_pytest.config.Config): The pytest config object
option_name (str): The name of... | 4f3bca4ff5b0a1eb04fbdc7a5d22bc09dbc95df6 | 3,637,033 |
def get_industry_categories():
"""按编制部门输出{代码:名称}映射"""
expr = STOCK_DB.industries.drop_field('last_updated')
df = odo(expr, pd.DataFrame)
res = {}
for name, group in df.groupby('department'):
res[name] = group.set_index('industry_id').to_dict()['name']
return res | 5b50dc2845a903e56071b57b0ee8d307f5e52f27 | 3,637,034 |
def rate(t, y, dt, elph_tau, pol_tau, delay, start):
"""Rate equation function for two state model. y[0] is charge transfer state,
y[1] is polaron state, elph_tau is electron-phonon scattering constant, pol_tau is
polaron formation constant."""
dydt = [(pulse(t, dt, delay, start) - (y[0] - y[1])/elph_t... | dd98606f0ab4dd5c3334acfbd080959ac4921030 | 3,637,035 |
import copy
def trace_module(no_print=True):
""" Trace my_module_original exceptions """
with putil.exdoc.ExDocCxt() as exdoc_obj:
try:
docs.support.my_module.func('John')
obj = docs.support.my_module.MyClass()
obj.value = 5
obj.value
except:
... | f407cba3f2ae8582bdaa685ae5bcba1ca908e9a9 | 3,637,036 |
def data_to_seq(X, Y,
t_lag=8,
t_future_shift=1,
t_future_steps=1,
t_sw_step=1,
X_pad_with=None):
"""Slice X and Y into sequences using a sliding window.
Arguments:
----------
X : np.ndarray with ndim == 2
Y : n... | 477366408309483eb1c9dcc2d90c70f7bd3ab143 | 3,637,037 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.