content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_app():
"""Create and configure an instance of the Flask application."""
app = Flask(__name__)
# vvvvv use sqlite database vvvvv
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
# vvvvv have DB initialize the app
DB.init_app(app)
@app.route('/')
def root():
... | 92663b60bd9faf1d850f69a550b17102b92ffcb9 | 3,636,300 |
from mpi4py import MPI
def MPITest(commsize):
"""
A decorator that repeatedly calls the wrapped function,
with communicators of varying sizes.
This converts the test to a generator test; therefore the
underlyig test shall not be a generator test.
Parameters
----------
commsize: scala... | 3bb33e5d3d6919916ba865d79a5e0a16cdbb1b99 | 3,636,301 |
def getClassicalPitchNames(pitches):
"""
takes a list of pitches and returns a list of classical pitch class names
"""
return getPitchNames([normalizePitch(x,12) for x in pitches],getClassicalPitchNameCandidates) | 737dccb3abe83c2bbb2c983cfa3fb80a4fbc5052 | 3,636,302 |
import pymel.core.uitypes
def toPyUIList(res):
# type: (str) -> List[pymel.core.uitypes.PyUI]
"""
returns a list of PyUI objects
Parameters
----------
res : str
Returns
-------
List[pymel.core.uitypes.PyUI]
"""
if res is None:
return []
return [pymel.core.uity... | 6f3d35a1a7c10bc461561edcdb4b52404de3e5a7 | 3,636,303 |
def best_B(Ag):
""" Given an antigenic determinant Ag this function returns the binding
value of the best possible binder. """
top = 0
for i in range(len(Ag)):
etop = np.min(cf.TD20[int(Ag[i]) - 1])
top += etop
return top | b02afd943de6a4c8b2f9f1b4d897e5f03074c000 | 3,636,304 |
def forward_gradients_v2(ys, xs, grad_xs=None, gate_gradients=False):
"""Forward-mode pushforward analogous to the pullback defined by tf.gradients.
With tf.gradients, grad_ys is the vector being pulled back, and here d_xs is
the vector being pushed forward."""
if type(ys) == list:
v = [tf.ones_... | 02fea7fc2367e69d2c6b085ea1a1379b7a442674 | 3,636,305 |
import resource
def __limit_less(lim1, lim2):
"""Helper function for comparing two rlimit values, handling "unlimited" correctly.
Params:
lim1 (integer): first rlimit
lim2 (integer): second rlimit
Returns:
true if lim1 <= lim2
"""
if lim2 == resource.RLIM_INFINITY:
... | 8c8faebd4cc1eecfbd8e0a73b16b2bee0a433572 | 3,636,306 |
from typing import List
def getswarmlocations() -> List[str]:
"""
checks if the provided location is a location where a swarm can happen.
:param location: the provided location
:return: boolean if location is in the list of locations where swarms can happen,
"""
swarmlocationlist = open("comma... | 3a7db13c8a0176a4cc9a9dda38b23041639917a9 | 3,636,307 |
from typing import Any
from typing import Optional
def Request(
default: Any = Undefined,
*,
default_factory: Optional[NoArgAnyCallable] = None,
alias: Optional[str] = None,
) -> Any:
"""
Used to provide extra information about a field.
:param default: since this is replacing the field’s ... | 83ad97bc7a276e0d9d715031f263cf8d66fdaf78 | 3,636,308 |
import sys
from django.conf import settings
import os
def get_jobs(when=None, only_scheduled=False):
"""
Returns a dictionary mapping of job names together with their respective
application class.
"""
# FIXME: HACK: make sure the project dir is on the path when executed as ./manage.py
try:
... | 9cb4ac165b446596f5728659c1cdf291fc7ef043 | 3,636,309 |
import os
import json
import logging
def get_project_id():
""" Gets the project ID. It defaults to the project declared in the
enviorment variable PROJECT but if it can't find it there it will
try looking for a service account and take the project ID from there
Args:
Returns:
"""
service_acc_address = os.... | ce06f65be2fa70898a71f10d4f848afdf944da48 | 3,636,310 |
def val_err_str(val: float, err: float) -> str:
"""
Get a float representation of a value/error pair and create a string representation
12.345 +/- 1.23 --> 12.3(12)
12.345 +/- 0.012 -> 12.345(12
12345 +/- 654 ---> 12340(650)
:param val: float representing the value
:param err: float represe... | 5b759ff8e6996704edb7f6b68f6cb7e307593c9e | 3,636,311 |
import os
def discrete_distribution(probabilities, path='', fig_name='distribution_events_states.pdf', v_labels=None,
h_labels=None, title=None, color_map=None, figsize=(12, 6), size_labels=16, size_values=14,
bottom=None, top=None, left=None, right=None, savefig=Fa... | e9da72db62779a760b71d7e498d733cf3f052ec4 | 3,636,312 |
import re
def find_map(address):
"""
Look up a specified address in the /proc/PID/maps for a process.
Returns: A string representing the map in question, or None if no match.
"""
maps = fetch_maps()
for m in re.finditer(begin_pattern, maps):
begin = int(m.group("begin"), 16)
e... | c9a07d982b92ef1e165fa8e1bcc9ea3873f2f912 | 3,636,313 |
import regex
def _format_css_declarations(content: list, indent_level: int) -> str:
"""
Helper function for CSS formatting that formats a list of CSS properties, like `margin: 1em;`.
INPUTS
content: A list of component values generated by the tinycss2 library
OUTPUTS
A string of formatted CSS
"""
output = ... | 56205e557858349f17a8d7a549d472c3f549c2cc | 3,636,314 |
def rosen_hess(x):
"""
The Hessian matrix of the Rosenbrock function.
Parameters
----------
x : array_like
1-D array of points at which the Hessian matrix is to be computed.
Returns
-------
rosen_hess : ndarray
The Hessian matrix of the Rosenbrock function at `x`.
... | 449c869e821c0e97e4126bd5955df5bd39d93f95 | 3,636,315 |
def flow_corr():
"""
Symmetric cumulants SC(m, n) at the MAP point compared to experiment.
"""
fig, axes = plt.subplots(
figsize=figsize(0.5, 1.2), sharex=True,
nrows=2, gridspec_kw=dict(height_ratios=[4, 5])
)
observables = ['sc', 'sc_normed']
ylims = [(-2.5e-6, 2.5e-6), (... | c2d887e3a646ad5e3f1f7570f8a7ee19bf25d1b1 | 3,636,316 |
def dodecagon(samples=128, radius=1):
"""Create a dodecagon mask.
Parameters
----------
samples : `int`, optional
number of samples in the square output array
radius : `float`, optional
radius of the shape in the square output array. radius=1 will fill the
x
Returns
... | a45a8eaa723c9c0da93fa6477a07d1a13d6524e0 | 3,636,317 |
def port_name(name, nr=0):
"""Map node output number to name."""
return name + ":" + str(nr) | a82e0b9940fa6b7f11f1a11fbd8a1b9b1a57c07b | 3,636,318 |
import os
import urllib
def url(ticker, start_date, end_date):
"""Format the correct URL from the params"""
base_url = ''.join([API_BASE_PATH, ticker, '.csv'])
params = {'start_date': start_date, 'end_date': end_date}
if API_KEY_ENV in os.environ:
params['api_key'] = os.environ[API_KEY_ENV]
... | 0a19ee5bdc88f1a071b3b7bb3508f60dcda6ee7a | 3,636,319 |
def AC3(csp, queue=None, removals=None, arc_heuristic=csp.dom_j_up):
"""[Figure 6.3]"""
if queue is None:
queue = {(Xi, Xk) for Xi in csp.variables for Xk in csp.neighbors[Xi]}
csp.support_pruning()
queue = arc_heuristic(csp, queue)
checks = 0
while queue:
(Xi, Xj) = queue.pop()
... | 507e942633da0ac1487db0c75375ac0e6d37a069 | 3,636,320 |
from typing import Optional
from typing import List
from typing import Union
import pandas
def load(
name: str,
ids: Optional[List[Union[str, int]]] = None,
limit: Optional[int] = None,
) -> pandas.DataFrame:
"""Load dataset data to a pandas DataFrame.
Args:
name:
The dataset ... | 40499ccc3942d4c59c8588257c9f40a2d622109d | 3,636,321 |
def _stringify(values):
"""internal method: used to convert values to a string suitable for an xml attribute"""
if type(values) == list or type(values) == tuple:
return " ".join([str(x) for x in values])
elif type(values) == type(True):
return "1" if values else "0"
else:
return ... | a8f3c290ef949a254ca5dca9744ff3f4c602c4d2 | 3,636,322 |
def xml_safe(s):
"""Returns the XML-safe version of a given string.
"""
new_string = s.replace("&", "&").replace("<", "<")
new_string = new_string.replace("\r", "").replace("\n", "<br/>")
return new_string | 166bf2b78441b4f22bf3a89f8be56efb756fe72f | 3,636,323 |
import re
def range_values(ent):
"""Extract values from the range and cached label."""
data = {}
range_ = [e for e in ent.ents if e._.cached_label.split('.')[0] == 'range'][0]
values = re.findall(FLOAT_RE, range_.text)
if not all([re.search(INT_TOKEN_RE, v) for v in values]):
raise Rejec... | 4fe1388727ef432a6b9587a2c179dafc6f60d42a | 3,636,324 |
import os
def plot_mw_nii_bars(ax, snr_min = None, shaded_kwargs = {}, **kwargs):
"""
Plots vertical lines and bars on bpt Diagram for Tilted Disk where only
NII/HA line is detected
Parameters
----------
ax 'matplotlib.pyplot.figure.axes'
axes to plot lines on
snr_min: 'number', ... | b274b213a183404d21aa3429fa6f0edefb3be25e | 3,636,325 |
def get_weights(connections):
"""Returns the weights of the connections
:param connections:
:return: Numpy array of weights
"""
return np.array(nest.GetStatus(connections, keys="weight")) | 50371989cf32b37bc7a25837db2c866e579ac0b6 | 3,636,326 |
def w2v_matrix_vocab_generator(w2v_pickle):
"""
Creates the w2v dict mapping word to index and a numpy matrix of (num words, size of embedding), words will
be mapped to their index, such that row ith will be the embedding of the word mapped to the i index.
:param w2v_pickle: Dataframe containing token ... | 3228d73facc7756cfcf32fb10d9d54f0b40c84d7 | 3,636,327 |
def concat(
dfs, axis=0, join="outer", uniform=False, filter_warning=True, ignore_index=False
):
"""Concatenate, handling some edge cases:
- Unions categoricals between partitions
- Ignores empty partitions
Parameters
----------
dfs : list of DataFrame, Series, or Index
axis : int or s... | 7f89a93410c3171e967682df954d259651cc5b91 | 3,636,328 |
def resize(dataset: xr.Dataset, invalid_value: float = 0) -> xr.Dataset:
"""
Pixels whose aggregation window exceeds the reference image are truncated in the output products.
This function returns the output products with the size of the input images : add rows and columns that have been
truncated. Thes... | 75729c99cf77ffeb79153bb4ff17ea69dac12f7b | 3,636,329 |
import requests
def score(graphs, schema, url, port):
"""
graphs is expected to be a list of dictionaries, where each entry in the
list represents a graph with
* key idx -> index value
* key nodes -> list of ints representing vertices of the graph
* key edges -> list of list of ints represen... | 090846132114dfadfc950f3fff384e26c439acce | 3,636,330 |
from typing import List
from typing import Dict
def group_by_author(commits: List[dict]) -> Dict[str, List[dict]]:
"""Group GitHub commit objects by their author."""
grouped: Dict[str, List[dict]] = {}
for commit in commits:
name = commit["author"]["login"]
if name not in grouped:
... | 239c523317dc8876017d4b61bc2ad8887444085e | 3,636,331 |
import re
def convert(name):
"""
CamelCase to under_score
:param name:
:return:
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | c92db5a27d4086f8c46cbcb17005e3fc0534b2cb | 3,636,332 |
def plot(graph, particles=None, polyline=None, particles_alpha=None, label_start_end=True,
bgcolor='white', node_color='grey', node_size=0, edge_color='lightgrey', edge_linewidth=3, **kwargs):
"""
Plots particle approximation of trajectory
:param graph: NetworkX MultiDiGraph
UTM projection
... | 3f57d69bd69c9164715db9fde5020c7da8aa42df | 3,636,333 |
def non_empty_string(value):
"""Must be a non-empty non-blank string"""
return bool(value) and bool(value.strip()) | 707d6c39a52b1ec0e317d156e74fef78170739d9 | 3,636,334 |
def metadataAbstractElementRequiredChildElementTest6():
"""
Optional child elements, child elements required.
>>> doctestMetadataAbstractElementFunction(
... testMetadataAbstractElementKnownChildElements,
... metadataAbstractElementRequiredChildElementTest6(),
... requiredChildEleme... | dd114d393269b9731aba8bbc6681f1a1b29643e0 | 3,636,335 |
def index():
"""
List containers
"""
containers = g.api.get_containers()
clonable_containers = []
for container in containers:
if container['state'] == 'STOPPED':
clonable_containers.append(container['name'])
context = {
'containers': containers,
'clonable... | 5e5178eba9824a9a4c83b5e179cf1fd6b3b8ed30 | 3,636,336 |
import torch
def spatial_discounting_mask():
"""
Input:
config: Config should have configuration including HEIGHT, WIDTH,
DISCOUNTED_MASK.
Output:
tf.Tensor: spatial discounting mask
Description:
Generate spatial discounting mask constant.
Spatial discounting ma... | 1ac2ffaf0b3ef70b9efe0965ef9ecd8bb16fe7ce | 3,636,337 |
from pathlib import Path
import os
def does_file_exist(filepath:Path)-> bool:
"""
Checks if file path exists.
"""
if os.path.exists(filepath):
LOG.info("Data path detected:\n{}\.".format(filepath))
return True
else:
LOG.info("Data path\n{}\nnot detected. Downloading now..... | 615d1eea9d43fd7af966a22981d178366b161e05 | 3,636,338 |
def pca_results(scaled, pca):
"""
Plot the explained variance of the DataSet as a barchart,
and return a DataFrame with the explained variance for each
feature, for each dimension of the PCA.
-----------------------------------------------------------
# Parameters:
# scaled (pd.DataFrame): The DataFrame in wh... | 48c5e2c740238c0005740de9171ad509e146fbed | 3,636,339 |
import pwd
def get_uid_from_user(user):
"""Return UID from user name
Looks up UID matching the supplied user name;
returns None if no matching name can be found.
NB returned UID will be an integer.
"""
try:
return pwd.getpwnam(str(user)).pw_uid
except KeyError:
return No... | dd4f6f839f985b923199b438216c567e1e84327d | 3,636,340 |
def get_approval_distance(election_1: ApprovalElection, election_2: ApprovalElection,
distance_id: str = None) -> float or (float, list):
""" Return: distance between approval elections, (if applicable) optimal matching """
inner_distance, main_distance = extract_distance_id(distance_... | 776640b12ac799248a35b49f6751c5fa27303ab8 | 3,636,341 |
from pathlib import Path
def get_base_folder():
"""Return the base folder of ProfileQC."""
return Path(__file__).parent | e0a49bbbe018333dd107466a5178c5579327edc1 | 3,636,342 |
def u16le_list_to_byte_list(data):
"""! @brief Convert a halfword array into a byte array"""
byteData = []
for h in data:
byteData.extend([h & 0xff, (h >> 8) & 0xff])
return byteData | 6e4dd1fe69a24f135d0dfa38d5d0ba109ad24b9e | 3,636,343 |
def process_IBM_strings(string):
"""
Format all the IBM string in the same way, creating a single string of lowercase characters
:param string:
:return:
"""
parts = string.split()
result = str(parts[0].lower())
for part in parts[1:]:
result += " " + str(part.lower())
return r... | 72216b014a18c72d4dec9ec54f24f13de0d46583 | 3,636,344 |
def get_sample_size(number_of_clones, fold_difference, error_envelope_x_vals, error_envelope_y_vals, number_of_error_bars):
"""
This returns the number of cells in a sample that produce the an
error bar of max_error_bar for a given number_of_clones in the
parent population.
This is the inverse ... | 392009961cd3797bdaab460cfee5808c8a0c4969 | 3,636,345 |
def get_r2(y,yhat):
""" Calcualte the coef. of determination (R^2) """
ybar = np.mean(y)
return 1 - (np.sum((y-yhat)**2))/(np.sum((y-ybar)**2)) | e632765696b92eb76032681be790b1e25979a6d3 | 3,636,346 |
from typing import Dict
from typing import Any
def get_context() -> Dict[str, Any]:
"""
Retrieve the current Server Context.
Returns:
- Dict[str, Any]: the current context
"""
ctx = _context.get() # type: ignore
if ctx is not None:
assert isinstance(ctx, dict)
return ... | dad971abb645fa7c194db5cd9ce45e7c38166f31 | 3,636,347 |
import pandas as pd
def kiinteisto_alueiksi(kiinteisto):
"""
kiinteist: kiinteisto/property register
An artificial property / constituency division will be made for the regionalization of postal codes.
A brute-force distribution is used, where the relative number of residential properties i... | fee095ccc4cb82b735c2d314a96ab20bf0790a9a | 3,636,348 |
def G1DListCrossoverSinglePoint(genome, **args):
"""
The crossover of G1DList, Single Point
.. warning:: You can't use this crossover method for lists with just one element.
"""
sister = None
brother = None
gMom = args["mom"]
gDad = args["dad"]
if len(gMom) == 1:
utils.raise... | 1cf77e96fb648a6d8664d157425f47f789248739 | 3,636,349 |
def optional_observation_map(env, inner_obs):
"""
If the env implements the `observation` function (i.e. if one of the
wrappers is an ObservationWrapper), call that `observation` transformation
on the observation produced by the inner environment
"""
if hasattr(env, 'observation'):
retur... | b1b57e74e498e520df80a310f95d1c79799a517d | 3,636,350 |
def RunMetadataLabels(run_metadata):
"""Returns all labels in run_metadata."""
labels = []
for dev_stats in run_metadata.step_stats.dev_stats:
for node_stats in dev_stats.node_stats:
labels.append(node_stats.timeline_label)
return labels | 277745263c75c4c6037f8b7a26b9421699bec3a5 | 3,636,351 |
import sys
import re
def ShouldPackageFile(filename, target):
"""Returns true if the file should be a part of the resulting archive."""
if chromium_utils.IsMac():
file_filter = r'^.+\.(a|dSYM)$'
elif chromium_utils.IsLinux():
file_filter = r'^.+\.(o|a|d)$'
else:
raise NotImplementedError('%s is no... | f3321d205378e4dad4ea6734bf0399d3e286b241 | 3,636,352 |
def is_entity_extractor_present(interpreter: Interpreter) -> bool:
"""Checks whether entity extractor is present."""
extractors = get_entity_extractors(interpreter)
return extractors != [] | 0227bdd1f6d7a5040bff853de62075f040337f23 | 3,636,353 |
def get_workflow(name, namespace):
"""Get a workflow."""
api_group = "argoproj.io"
api_version = "v1alpha1"
co_name = "workflows"
co_client = _get_k8s_custom_objects_client()
return co_client.get_namespaced_custom_object(api_group, api_version,
n... | cea58e40b9279a3134766374cd8f5e9eb2e1b4f8 | 3,636,354 |
import torch
def step(x, b):
"""
The step function for ideal quantization function in test stage.
"""
y = torch.zeros_like(x)
mask = torch.gt(x - b, 0.0)
y[mask] = 1.0
return y | bac5dd8cbaa4da41219f03a85e086dd3bdd1e554 | 3,636,355 |
from typing import Union
def encode_intended_validator(
validator_address: Union[Address, str],
primitive: bytes = None,
*,
hexstr: str = None,
text: str = None) -> SignableMessage:
"""
Encode a message using the "intended validator" approach (ie~ version 0)
defined... | bb86535c06204bb0b2bf25a7e595cddb3bc83603 | 3,636,356 |
def _ip_desc_from_proto(proto):
"""
Convert protobuf to an IP descriptor.
Args:
proto (protos.keyval_pb2.IPDesc): protobuf of an IP descriptor
Returns:
desc (magma.mobilityd.IPDesc): IP descriptor from :proto:
"""
ip = ip_address(proto.ip.address)
ip_block_addr = ip_address(... | b24fd6636cc30c707b8f1539cf16515946370b39 | 3,636,357 |
import inspect
def inheritdocstrings(cls):
"""A class decorator for inheriting method docstrings.
>>> class A(object):
... class_attr = True
... def method(self):
... '''Method docstring.'''
>>> @inheritdocstrings
... class B(A):
... def method(self):
... pass
... | 4af61e59dc7b3ba53243107bacd0738c2bc2e2a9 | 3,636,358 |
def get_totd_text():
"""
Get the text for the Top of the Day post.
:return: The body for the post.
"""
sections = []
# Most Upvoted Posts
top_submissions = sorted([submission for submission in get_reddit().subreddit("all").top("day", limit=5)], key=lambda x: x.score, reverse=True)
items... | 2077da29ea28f2563485eed14dc277b1646e27cd | 3,636,359 |
import os
def check_checkpoints(store_path):
"""
Inputs
1) store_path: The path where the checkpoint file will be searched at
Outputs
1) checkpoint_file: The checkpoint file if it exists
2) flag: The flag will be set to True if the directory exists at the path
Function: This function takes in the store_pa... | f4328a23d9c20258b89c9825ed827aff3308e461 | 3,636,360 |
import pickle
import time
def dump_ensure_space(file, value, fun_err=None):
"""
Only dump value if space enough in disk.
If is not enough space, then it retry until have space
Note: this method is less efficient and slowly than simple dump
>>> with open("test_ensure_space.tmp", "wb") as f:
..... | 622ed232a3e747e55004ab28225418fc3c6570ef | 3,636,361 |
import torch
def store_images(input, predicts, target, dataset='promise12'):
"""
store the test or valid image in tensorboardX images container
:param input: NxCxHxW
:param predicts: NxCxHxW
:param target: NxHxW
:return:
"""
N = input.shape[0]
grid_image_list = []
for i... | 14d853cdf98bea358f9170162d6a5ea27c1f88a8 | 3,636,362 |
from typing import Optional
from typing import List
from typing import Dict
import csv
def snmptable(ipaddress: str, oid: str, community: str = 'public',
port: OneOf[str, int] = 161, timeout: int = 3,
sortkey: Optional[str] = None
) -> OneOf[List[Dict[str, str]], Dict[str, Di... | bb3e749d17c5038a2ed8857fab2ac226ee175c3f | 3,636,363 |
def GetFile(message=None, title=None, directory=None, fileName=None, allowsMultipleSelection=False, fileTypes=None):
"""Ask the user to select a file.
Some of these arguments are not supported:
title, directory, fileName, allowsMultipleSelection and fileTypes are here for compatibility reasons.
"""
default_f... | 88b4d01b66542f4414f24cf123ba3a92e98befe2 | 3,636,364 |
def lda_recommend(context_list):
""" With multiprocessing using Dask"""
print("Recommending")
topn = 500
sleep(0.2)
vec_bow = id2word_dictionary.doc2bow(context_list)
# This line takes a LONG time: it has to map to each of the 300 topics
vec_ldamallet = ldamallet[vec_bow]
# Convert the q... | 7435de1aee9e43596b5467036b00b706502aa254 | 3,636,365 |
def grids_skf_lr(data_x, data_y, grid_params, weight_classes=None, scv_folds=5):
"""
:param data_x:
:param data_y:
:param grid_params:
:param weight_classes:
:param scv_folds:
:return:
"""
if weight_classes is None:
weight_classes = {0: 1, 1: 1}
m_log = LogisticRegressio... | 7cf79512b3663e8b01ea96219d746c3a6a2fd4b0 | 3,636,366 |
def zeros(rows, cols, fortran=True):
"""Return the zero matrix with the given shape."""
order = "F" if fortran else "C"
cparr = cp.zeros(shape=(rows, cols), dtype=cp.complex128, order=order)
return CuPyDense._raw_cupy_constructor(cparr) | 90e2a7bb7bfdaa5b8b242d1aa543b93dab5d1a60 | 3,636,367 |
def compute_trapezoidal_approx(bm, t0, y0, dt, sqrt_dt, dt1_div_dt=10, dt1_min=0.01):
"""Estimate int_{t0}^{t0+dt} int_{t0}^{s} dW(u) ds with trapezoidal rule.
Slower compared to using the Gaussian with analytically derived mean and standard deviation, but ensures
true determinism, since this rids the rand... | 719090d6427c0f37dd8aab4f8bfb60dfdfb8c362 | 3,636,368 |
def vavrycuk_psencik_hti(vp1, vs1, p1, d1, e1, y1,
vp2, vs2, p2, d2, e2, y2,
phi, theta1):
"""
Reflectivity for arbitrarily oriented HTI media, using the formulation
derived by Vavrycuk and Psencik [1998], "PP-wave reflection coefficients
in weakly aniso... | a48ff4cb76341e199c3d386b40d58bd6a2031e01 | 3,636,369 |
def concatenate_time_series(time_series_seq):
"""Concatenates a sequence of time-series objects in time.
The input can be any iterable of time-series objects; metadata, sampling
rates and other attributes are kept from the last one in the sequence.
This one requires that all the time-series in the lis... | ce2f51e0a14bf2b6de16ce366041522556b0793f | 3,636,370 |
def deeplink_url_patterns(
url_base_pattern=r'^init/%s/$',
login_init_func=login_init,
):
"""
Returns new deeplink URLs based on 'links' from settings.SAML2IDP_REMOTES.
Parameters:
- url_base_pattern - Specify this if you need non-standard deeplink URLs.
NOTE: This will probably clos... | bda7c28e0ce46e4b7f236562a3f8da09a5977c0b | 3,636,371 |
def read_words():
"""
Returns an array of all words in words.txt
"""
lines = read_file('resources/words.txt')
words = []
for line in lines:
words.extend(line.split(' '))
return words | 96768fc1cd593b29caefaa1489f0478832b10886 | 3,636,372 |
def lynotename(midinote):
"""Find the LilyPond/Pently name of a MIDI note number.
For example, given 60 (which means middle C), return "c'".
"""
octave, notewithin = midinote // 12, midinote % 12
notename = notenames[notewithin]
if octave < 4:
return notename + "," * (4 - octave)
else:
... | 7eda2d4b5075759413e25626b70c5cd56c183447 | 3,636,373 |
from datetime import datetime
def json_serial(obj):
"""
Fallback serializier for json. This serializes datetime objects to iso
format.
:param obj: an object to serialize.
:returns: a serialized string.
"""
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoform... | 1b4c23d84e89cb77d111160a5328046c62fb4227 | 3,636,374 |
import logging
import glob
import os
import copy
import warnings
def get_library_file(instrument, detector, filt, pupil, wfe, wfe_group,
library_path, wings=False, segment_id=None):
"""Given an instrument and filter name along with the path of
the PSF library, find the appropriate library... | f6b18cc2e57544685c6c8aaf95c7da44a4039ef8 | 3,636,375 |
def html_mail(sender='me@mail.com', recipients=['them@mail.com'],
html_content='<p>Hi</p>', subject='Hello!',
mailserver='localhost'):
""" html_mail takes input html, sender, recipents and
emails it in a mime type that will show as text or html on
the recipients mail reader.
... | 83257bb4718063153587bbc685c650595b911554 | 3,636,376 |
def gotu(input_path: str) -> biom.Table:
"""Generate a gOTU table based on sequence alignments.
"""
profile = workflow(input_path, None)['none']
return profile_to_biom(profile) | 59e119392da0c6179ed84b6de7da517ccad5107d | 3,636,377 |
def read_data_megset(beamf_type):
""" Read and prepare data for plotting."""
if beamf_type == 'lcmv':
settings = config.lcmv_settings
settings_columns = ['reg', 'sensor_type', 'pick_ori', 'inversion',
'weight_norm', 'normalize_fwd', 'use_noise_cov',
... | 6d2f3cd765779276e6730c56865e374058849662 | 3,636,378 |
import getpass
import logging
def collect_user_name():
""" Returns the username as provided by the OS. Returns a constant if it
fails.
"""
try:
uname = getpass.getuser()
except Exception as e:
logger = logging.getLogger(__name__)
msg = "Failed to collect the user name: erro... | 40e18be0ea51659346c7f761bafa8af194937e14 | 3,636,379 |
def get_dataframe() -> pd.DataFrame():
"""Dummy DataFrame"""
data = [
{"quantity": 1, "price": 2},
{"quantity": 3, "price": 5},
{"quantity": 4, "price": 8},
]
return pd.DataFrame(data) | 3089e1a33f5f9b4df847db51271f7c3f936b351c | 3,636,380 |
def get_node_mirna(mirna_name, taxid, psi_mi_to_sql_object):
"""
This function sets up a node dict and returns it. If the node is already in the SQLite database it fetches that node from the db, so it won't be inserted multiple times.
"""
# Testing if the node is already in the database
node_dict =... | daab8ab8f43c1e9395dbbc2640ecb78b39f6867f | 3,636,381 |
import urllib
import sys
def Web(website, system_id, address, page, params = {}):
"""Routine for connecting to website that is hosting the database"""
data = ''
params['systemid'] = system_id
params = urllib.urlencode(params)
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept"... | 58fc756411a8dc23fa88937157df4c4900486a3a | 3,636,382 |
def generate_output_file_name(input_file_name):
"""
Generates an output file name from input file name.
:type input_file_name: str
"""
assert isinstance(input_file_name, str)
output_file_name = input_file_name + ".gen.ipynb"
return output_file_name | e638d676048e062711ca1a09d88a12d76fb9239d | 3,636,383 |
def prefixed_field_map(name: str) -> Mapper:
"""
Arguments
---------
name : str
Name of the property.
Returns
-------
Mapper
Field map.
See Also
--------
field_map
"""
return field_map(
name,
api_to_python=add_signed_prefix_as_needed,
... | 48be07a06f4f5b70d4e7b389a1896c94a181e62c | 3,636,384 |
import sys
def a_star(grid, start, end):
"""A-star algorithm implementation"""
# open and closed nodes
open_nodes = []
closed_nodes = []
# Create a start node and an goal node
start_node = Node(start, None)
goal_node = Node(end, None)
# Add the start node
open_nodes.append(start_... | b60fd2193b7b05b042aec29aa65cc3d57453f4d1 | 3,636,385 |
def is_water(residue):
"""
Parameters
----------
residue : a residue from a protein structure object made with PDBParser().
Returns
-------
Boolean
True if residue is water, False otherwise.
"""
residue_id = residue.get_id()
hetfield = residue_id[0]
return hetfield[0... | 2d547da9dc8def26a2e9581a240efa5d513aab64 | 3,636,386 |
def gelu(input_tensor):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
input_tensor: float Tensor to perform activation.
Returns:
`input_tensor` with the GELU activation applied.
"""
cdf = 0.5 * (1.0 + tf.erf(input_tens... | c4f8fead676ef7e4b036f8c94467402445044330 | 3,636,387 |
def index():
""" Route for signing the policy document or REST headers. """
request_payload = request.get_json()
if request_payload.get('headers'):
response_data = sign_headers(request_payload['headers'])
else:
credential = [c for c in request_payload['conditions'] if 'x-amz-credential'... | f914761d9b58a290f20b537c4df9ce8272dd7b6c | 3,636,388 |
from sphinx.jinja2glue import BuiltinTemplateLoader
def create_template_bridge(self):
"""Return the template bridge configured."""
if self.config.template_bridge:
templates = self.app.import_object(
self.config.template_bridge, 'template_bridge setting')()
else:
templates = Bui... | 64a7a1dd70035b2507a0b8b9b3af8c91ccadb0ec | 3,636,389 |
def make_answer(rdtype, answers=None, additionals=None, authorities=None):
"""For mocking an answer. We make an answer without any message (what would
normally come over the network, to be parsed. We instead make a blank
object for the sake of test complexity, and later attach the appropriate\
rrsets to... | 877f0acefd3082189c91885ff98ac056799c1e1b | 3,636,390 |
def consolidate_payoff_results(period, reporter_configuration, simulation_output, score_map, priority_based):
"""
Gather per-run metrics according to a simulation result.
:param resolved_per_reporter: Resolved issues per priority, including a priority detail.
:param period: Description of the period.
... | 34fc8079455972455fcd47aa1e582017d0a0d83a | 3,636,391 |
def single_ray_belief_propagation(
S,
ray_voxel_indices,
ray_to_occupancy_accumulated_pon,
ray_to_occupancy_messages_pon,
output_size
):
"""Run the sum product belief propagation for a single ray
Arguments
---------
S: tensor (M,) dtype=float32
The depth probability distribut... | 5c9c7acbf13e0f0f8adef3f5bebb5b14b81a2b8e | 3,636,392 |
def cse_postprocess(cse_output):
""" Perform CSE Postprocessing
:arg: output from SymPy CSE with tuple format: (list of ordered pairs that
contain substituted symbols and their replaced expressions, reduced SymPy expression)
:return: output from SymPy CSE where postprocessing... | ec7211d366550de93fa2839232820fd2fb3746f7 | 3,636,393 |
def lap(j, s, alpha):
""" Laplace coefficient """
def int_func(x):
return np.cos(j*x)/(1. - (2.*alpha*np.cos(x)) + alpha**2.)**s
integral = integrate.quad(int_func, 0., 2.*np.pi)[0]
return 1./np.pi*integral | 013cb3611e7f678aac560896b80930e19e3d0579 | 3,636,394 |
import google
def calendar_add():
"""Adds a calendar to the database according to the infos in POST data.\
Also creates the calendar in google calendar service if no google_calendar_id is present in POST data.
"""
calendar_name = request.form["calendar_name"]
std_email = request.form["std_ema... | 558c8b3580109773d4012b1048f33f56aca376ee | 3,636,395 |
def proportional_allocation_by_location_and_activity(df, sectorcolumn):
"""
Creates a proportional allocation within each aggregated sector within a location
:param df:
:param sectorcolumn:
:return:
"""
# tmp replace NoneTypes with empty cells
df = replace_NoneType_with_empty_cells(df)
... | fb9376411d0b448a99563f41091f43863b694b8f | 3,636,396 |
import os
def Console():
""" Factory method that returns the Console object most appropriate for the current OS envrionment. """
if os.name == "posix":
return POSIXConsole()
elif os.name == "nt":
return NTConsole()
else:
raise NotImplementedError("Console support not implement... | 598be9cf1f5f9da8dcef0e61ff2ed398845e6639 | 3,636,397 |
def prepare_target():
"""
Creates a example target face
:return: list of RFTargetVertex
"""
# size = 2
# target = [
# rfsm.RFTargetVertex(0, 0, 0, -size, -size),
# rfsm.RFTargetVertex(0, 1, 1, -size, size),
# rfsm.RFTargetVertex(1, 1, 1, size, size),
# rfsm.RFTarg... | 27fa9a8bd2b5c7943b5882d2bf76312ea7e418bb | 3,636,398 |
import json
def data_fixture():
"""Fixture data."""
data = json.loads(load_fixture("data.json", "evil_genius_labs"))
return {item["name"]: item for item in data} | 9eebcabb4f1517d66f76be8956f74ce438aab8f1 | 3,636,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.