content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def can_see_staff_link(user):
"""
Return True if the user should see the staff view.
Example usage: {{ user|can_see_staff_link }}
"""
return should_see_staff_view(user) | 24f4992ce28b5d93b45c127356f8f1750d804df6 | 3,609,522 |
from typing import Sequence
import random
def mutUniformBounded(individual, low, up, indpb):
"""Mutate an individual by replacing attributes, with probability *indpb*,
by a integer uniformly drawn between *low* and *up* inclusively.
:param individual: :term:`Sequence <sequence>` individual to be mutated.
... | aeb6ffc4b94e2891f94085ca9a97f63c78a7f004 | 3,609,523 |
def authenticated_only(*args, **kwargs):
"""Return a permission allowing access to admin and authenticated users.
:returns: a permission allowing only super-admin.
"""
return StrictDynamicPermission(AuthenticatedNeed) | 07df6994b776377ea82406cd56ce6579bd238a60 | 3,609,524 |
def initialize():
"""Forces the initialization for underlying database back-end module"""
return IMPL.initialize() | 44e790275d8d40a503ac68ac911c07eb3da55dc7 | 3,609,525 |
def _not_blank(error_msg):
"""Returns a non-blank validation rule with custom error message."""
return validate.Length(min=1, error=error_msg) | 8cf2c7cb64c95ab337eb3671b3805c94cfba6946 | 3,609,526 |
def _AdjustColHeadings(colHeadings, maxColLabelLen):
""" *For Internal Use*
removes illegal characters from column headings
and truncates those which are too long.
"""
for i in xrange(len(colHeadings)):
# replace unallowed characters and strip extra white space
colHeadings[i] = colHeadings[i... | f413205e39c9518b77bcd959fc9f58026d85c07b | 3,609,527 |
def authenticated_user(client, account):
"""Create an authenticated user for a test"""
# user = G(User, email='test@gmail.com')
account.email = 'test@gmail.com'
account.set_password('my_password123')
account.save()
client.login(email='test@gmail.com', password='my_password123')
return accoun... | b1156f21ca94129fbf0dee8d0b0dbac834fbf59d | 3,609,528 |
def calcENM(atoms, select=None, model='anm', trim='trim', gamma=1.0,
title=None, n_modes=None, **kwargs):
"""Returns an :class:`.ANM` or :class:`.GNM` instance and *atoms* used for the
calculations. The model can be trimmed, sliced, or reduced based on
the selection.
:arg atoms: atoms on... | 1de53be0e70d8a09a429c7494c681edf457ec73e | 3,609,529 |
def is_affine_st(A: Affine, tol: float = 1e-10) -> bool:
"""
Check if transfrom is pure scale and translation.
:return: ``True`` if Affine transform has scale and translation components only
:return: ``False`` if there is non-zero rotation or skew
"""
(_, wx, _, wy, _, _, *_) = A
return ab... | 382b3b84ae834399a92d4ea6941c1b68baf8d0c0 | 3,609,530 |
import logging
def build(path):
"""Build an inference engine from a serialized model.
Args:
path: model or path to a saved onnx/trt checkpoint
"""
logging.info("Deserializing the TensorRT engine from {}".format(path))
with open(path, "rb") as f, trt.Logger() as logger, trt.Runtime(logger) ... | 6d5e8d0e4dc2ee9979aee87cb3b197a32318af5e | 3,609,531 |
def transient_indices_periodic(T1,N):
"""Computes indices for transient handling of periodic signals.
Computes the indices to be used with a vector u of length N that contains
(several realizations of) a periodic signal, such that u[indices] has T1[0]
transient samples prepended to each realization. Th... | 45da6b4897bbd70a7c95a20152d2c17c525daa68 | 3,609,532 |
import random
def make_soup(root, n_p, n_s, verbose=False):
"""
Make a new word from a root, containing n_prefixes and n_suffixes
Also adds a random ending (grammatical form)
"""
soup = root[:-1]
ending = root[-1]
assert ending in {'i', 'o', 'e'}
added_affixes = []
meanings = []
... | 88415b0732c2f05a622eca728145619950f0e7c7 | 3,609,533 |
def build(conf, name='Enc_Anatomy'):
"""
Build a UNet based encoder to extract anatomical information from the image.
"""
spatial_encoder = UNet(conf)
spatial_encoder.input = Input(shape=conf.input_shape)
l1_down = spatial_encoder.unet_downsample(spatial_encoder.input, spatial_encoder.normalise)... | 51e4238b96362092a6dd28299c2d2bd402a4a449 | 3,609,534 |
import torch
def prepare_values(y_true, y_pred):
"""Converts the input values to numpy.ndarray.
Parameters
----------
y_true : torch.tensor
Either a CPU or GPU tensor.
y_pred : torch.tensor
Either a CPU or GPU tensor.
Returns
-------
y_true, y_pred : numpy.ndarray
... | f5fa8a05a3d29c00d7ea310a91a09db1158524be | 3,609,535 |
import time
def timing(f):
"""
Decorator function to add time elapsed
"""
@wraps(f)
def wrapper(*args, **kwargs):
start = time()
result = f(*args, **kwargs)
end = time()
time_elapsed = round(end - start, 2)
if isinstance(result, tuple):
return (... | 5c30e471688ece1d68652c325c0b9676e3bc16ea | 3,609,536 |
from typing import List
def solve(env:Program):
"""
Solve the program!
"""
# emit the generated program
program = GeneratedMain()
program.window_title = "Goes Nowhere, Does Nothing"
program.window_width = 512
program.window_height = 512
dependencies:List[str] = []
if len([t f... | 6736a06864cb991a193a71c380fc9d6fd853791d | 3,609,537 |
def accuracy(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""
Calculate accuracy of given predictions
Parameters
----------
y_true: ndarray of shape (n_samples, )
True response values
y_pred: ndarray of shape (n_samples, )
Predicted response values
Returns
-------
... | c97ce4b57da6f2ffa62193ae03f2b6c71464a713 | 3,609,539 |
import scipy
def breakeven_revenue(
cost_upfront,
carboncost=50, carbontons=0, wacc=7, lifetime=30,
degradationrate=0.5, cost_om=15, cost_om_units='$',
inflationrate=2.5, taxrate=40,
taxrate_federal=None, taxrate_state=None,
schedule='macrs', period=5, itc=0,
maxiter=1000, xtol='default... | 263db0748fb741127e36f5f5c7d12217ef39f7d1 | 3,609,540 |
def get_mesh_pts(N, img_size):
"""
Algorithm is as follows:
First I will place approx 4*sqrt(N) equispaced points around the boundary
of the square and then distributed the remaining N-4*sqrt(N) points uniformly
at random inside the square. Then, I call the Delaunay algorithm to make the
triangu... | f3b4db753559b18cf1b97828cc8b3315f97c654b | 3,609,541 |
def _create_cell_list(hparams, mode):
"""Create a list of RNN cells."""
# Multi-GPU
cell_list = []
for i in range(hparams.num_layers):
# last layers use residual connection
if i >= hparams.num_layers - hparams.num_residual_layers:
residual_connection = True
else:
residual_connection ... | bb73fe10b9bb611cea5ea3aa1456a79d51d104c9 | 3,609,542 |
def lvl_profiles(z_axis, sigma_grid, tau_grid, sig_lvls):
"""Represent sigma and spice profiles as discrete points"""
all_profiles = []
num_profs = sigma_grid.shape[-1]
for i in range(num_profs):
z_lvl = np.interp(sig_lvls, sigma_grid[:, i], z_axis,
left=np.nan, right=... | ab0895d545d7a80b09cd81b3ecdcd7bc28db9b4e | 3,609,543 |
def get_pydot_attributes(index, dot):
"""Helper function to get attributes from pydot graph given index"""
return dot.get_subgraphs()[index].get_nodes()[0].get_attributes() | 8fa6fc43d2318f172785567127c1909a5b0e3587 | 3,609,544 |
def parse_taxon(file_name):
"""
:param file_name:
:return:
"""
res = set()
with open(file_name, 'r') as IN:
for line in IN:
res.add(line.strip())
return res | 779626ad6c52c73d714408087f8f95ab85130735 | 3,609,545 |
def ldns_update_upcount(*args):
"""LDNS buffer."""
return _ldns.ldns_update_upcount(*args) | 7ac9814ca7fb53985e1b8106f62a0a7ab014bd91 | 3,609,546 |
import random
def mate(ind1, ind2, indpb):
"""
Executes a uniform crossover that modify in place the two
individuals. The attributes are swapped according to the
*indpb* probability.
"""
out_success, in_success = True, True
if ind1.out_enabled and random.random() < indpb:
out_succe... | 7b94c2f884819430885740222c2a57d3ecd6fec7 | 3,609,547 |
import time
def time_convert(ens, cls_to, **kwds):
""" Time conversion function """
t0 = time.time()
ens_out = ens.convert_to(cls_to, **kwds)
t1 = time.time()
print("Convert %s to %s with %i pdfs in %.2f s" % (type(ens.gen_obj), cls_to, ens.frozen.npdf, t1-t0))
return ens_out | 0869d5c710f888c090a01ffd8d0ffa0108e8fa4d | 3,609,548 |
def ph_calc_phwater(ref, light, therm, ea434, eb434, ea578, eb578, ind_slp, ind_off, psal=35.0):
"""
Description:
OOI Level 2 pH of seawater core data product, which is calculated using
data from the Sunburst SAMI-II pH instrument (PHSEN). This document is
intended to be used by OOI pro... | 5268698ce1abfbd21091b20bc0ab7eb120885a7b | 3,609,549 |
def Dominates(x, y):
"""Check if x dominates y.
:param x: a sample
:type x: array
:param y: a sample
:type y: array
"""
return np.all(x <= y) & np.any(x < y) | d68cbc7aaf8161a7519f033d8cd2cc42093b7cd2 | 3,609,551 |
def predict(path=None,img=None):
"""
图片文字方向预测
"""
ROTATE = [0,270,180,90]
if path is not None:
im = Image.open(path).convert('RGB')
elif img is not None:
im = Image.fromarray(img).convert('RGB')
w,h = im.size
thesh = 0.05
xmin,ymin,xmax,ymax = int(thesh*w),int(thesh*h),... | d5b654f168e692dcdd9da64f5384c88a92cadf7e | 3,609,552 |
import requests
def get_classic_generated_events(access_token, calendar_id):
"""Gets a list of classic generated events
Args:
access_token (string): User's access token to make the request
calendar_id (string): ID of the specific calendar that the event exists on
Returns:
List: l... | 8c7fef10591f3c78110193c417f83e06976b6d24 | 3,609,553 |
def sumProb(N: int, p: float) -> float:
"""
Biến ngẫu nhiên nhị thức chỉ có hữu hạn symbol, tổng xác suất của tất cả các symbol này bằng 1.
Do đó hàm sumProb cho phép kiểm tra tổng xác suất của biến ngẫu nhiên nhị thức bằng 1.
Chứng minh toán học có trong file explanation.pdf
Parameters:
- N (... | c96dde51d74d82748ee10bdf1050ba7f6caa1da8 | 3,609,554 |
def get_asset_name_and_format_from_string(title_text) -> []:
"""Checks input string for name and format
:param [] title_text: input string formatted by lines
:return: [name, asset_format]
"""
if (
title_text[0].lower() == "NEW".lower()
and title_text[1].lower() == "FREE".lower()
... | 16f911e1507c221ea4165cc4dbfd6b4ca4b0b48f | 3,609,555 |
def average_color(color: list):
"""複数サンプルした時に平均色を求めたい"""
c = color
avg_color = [c[i : i + 4] for i in range(0, len(c), 4)]
avg_color = np.array(avg_color)
avg = np.average(avg_color, axis=0)
return avg | ad4afd39c5ff3a0f84d53f488b627853109f8322 | 3,609,556 |
def frac_diff(dataframe, d, thres=0.01):
"""
Perform Standard Fracdiff - Expanding Window
:param dataframe:
:param d:
:param thres:
:return:
"""
# Get the weights for the longgest series
def get_weights(d, size):
w = [1.]
for k in range(1, size):
w_ = ... | 59bb6abd03778d45cb0cb5626913a149a6d37095 | 3,609,558 |
from typing import List
def sort_loops_based_on_weights_and_date(params: dict) -> List[WeightedLoop]:
"""
:param params: dict of params
:return: list of sorted, signed, and weighted loops
"""
signed_weighted_loops = __find_signed_closed_loops(params)
# sort based on weights and dates
signe... | 6a2801adf9b4c8b048372897563dbbb774b96fe9 | 3,609,560 |
import pprint
import pycountry
def get_alpha2_to_continents_from_wiki():
"""Get Country Codes to Continents from Wikipedia.
"""
data = {}
for continent, countries in get_continents_to_countries_from_wiki().items():
for country_name in countries:
pprint(pycountry.countries.get(name=... | 2387cbc4bc12eb9a97933f37df185f7b7df1d1ec | 3,609,561 |
import html
def make_email_lists(items):
"""Make an HTML and plain text list of items, to be used in emails.
"""
if not items or len(items) == 0:
return "", ""
htm = ["<li>{}</li>".format(html.escape(i if i else "\'blank\'")) for i in items]
htm = "<ul>{}</ul>".format("".join(htm))
tex... | 38fa2cd0abb1e95e1c8294050a5957ac48d2e7c7 | 3,609,562 |
def RemoveDuplicatedVertices(vertices, faces, vnorms = None):
"""Remove duplicated vertices and re-index the polygonal faces such that
they share vertices
"""
vl = {}
vrl = {}
nvert = 0
vertList = []
normList = []
for i,v in enumerate(vertices):
key = '%f%f%f'%tuple(v)
... | ccc76dfe6e449047b8c3757001f4ea4cce8709ce | 3,609,563 |
def is_network_rate_error(exc):
"""
:param exc: Exception
Exception thrown when requesting network resource
:return: bool
True iff exception tells you abused APIs
"""
keys = ["429", "Connection refused"]
for key in keys:
if key in str(exc):
return True
re... | 6302dd39dcf536e0522fa801b245d21d7e3c5358 | 3,609,564 |
def ema(data, n, nans=-1):
""" Computes the exponential MA for each row of the input.
:param data: pandas dataframe.
:param n: MA period.
:return: a new dataframe with the MA values.
"""
if type(data) == pd.Series:
data = data.to_frame()
ma = data.ewm(span=n, adjust=False).mea... | 4084c627b716c7d72139fc00f2a9426faf4e4785 | 3,609,565 |
def listV(t,v):
"""
This function is not very 'smart'
This function creates a vsipl double or integer vector and copies a list into VSIPL.
It will only copy into vectors of type double (real or complex) or of type int.
That is to say vectors of type vsip_vview_d, vsip_cvview_d, and vsip_... | d3e54c0d2e5deddf0fd5391f97cbc5f7674e1897 | 3,609,566 |
def _to_tensor(x, dtype):
"""Convert the input `x` to a tensor of type `dtype`.
# Arguments
x: An object to be converted (numpy array, list, tensors).
dtype: The destination type.
# Returns
A tensor.
"""
x = tf.convert_to_tensor(x)
if x.dtype != dtype:
x = tf.cast... | 2d17c505dc9174b1abe3720f1d47a2f8a8e6407f | 3,609,567 |
def get_econstraints(unknowns, segment):
""" Runs the mission if the equality constraint values are needed
Assumptions:
N/A
Inputs:
state.unknowns [Data]
Outputs:
constraints [array]
Properties Used:
N/A
... | dc637ed9fa2886551ab352fbb2c9ae2745025fb4 | 3,609,568 |
from typing import Optional
def mkdir(path: str, mode: int = 0o777, *,
dir_fd: Optional[int] = None) -> None:
"""Makes a directory with mode
Call the corresponding :func:`IO.mkdir` upon the default handler.
The ``path`` can be a POSIX path or a URI.
"""
global _DEFAULT_CONTEXT
def... | 1d09349c8cb4916944cb35472e2eb59333223ff4 | 3,609,569 |
import time
def receipts_as_vc(tx_receipt: TxReceipt, tol_receipt: dict) -> dict:
"""Convert a raw tx receipt to an unsigned Verifiable Credential"""
# Generate a random UUID, not related to anything in the credential
uid = unique_id.uuid4().hex
# Current time and expiration
now = int(time.time(... | f94dff01e2ff8d514e90b10a4c6c236f43501679 | 3,609,570 |
def join_url(*sections):
"""
Helper to build urls, with slightly different behavior from
urllib.parse.urljoin, see example below.
>>> join_url('https://foo.bar', '/rest/of/url')
'https://foo.bar/rest/of/url'
>>> join_url('https://foo.bar/product', '/rest/of/url')
'https://foo.bar/product/re... | ec535d3efcbf43a4fad4ed78e1b03e20e665d163 | 3,609,572 |
import traceback
def get_vertices(arcpyPolyline, reverse = False):
"""Returns points of a polyline feature class as orded list of points
:param arcpyPolyline:
:return: list of points
"""
try:
points = []
for part in arcpyPolyline:
for pnt in part:
... | 94b377baeb008f07ee410955eb393b00ace1a176 | 3,609,573 |
def getTaggedCommit(repository, sha1):
"""Returns the SHA-1 of the tagged commit.
If the supplied SHA-1 sum is a commit object, then it is returned,
otherwise it must be a tag object, which is parsed to retrieve the
tagged object SHA-1 sum."""
while True:
git_object = repository.f... | e9c8f9d41e22612fa4f29624c748f902e5f8db17 | 3,609,574 |
def register(request):
"""User creation view."""
if settings.USE_ID_SITE:
return redirect('sample:stormpath_id_site_register')
form = StormpathUserCreationForm(request.POST or None)
if form.is_valid():
try:
form.save()
user = authenticate(
userna... | 36d19935f516ca5f1a8e742df020b8aa2c911041 | 3,609,575 |
from typing import Optional
from typing import Union
from typing import List
def _get_span_replace_glob_and_regex(
range_config: range_config_pb2.RangeConfig, is_match_span: bool,
is_match_date: bool,
span_width_str: Optional[Text]) -> Union[Text, List[Text]]:
"""Replace span or date spec if static rang... | b06d94e6f48023ead680fd03a9c3a37e5d60f916 | 3,609,576 |
from re import T
def selu(x: T.Tensor, **kwargs):
"""
SELU activation.
"""
return T.selu(x) | c32aea78028fcad9cb57e50a7efdf0ca344eb227 | 3,609,577 |
def edge_detect(image):
"""
this function will get an image as an input convert it to grayscale apply Gaussian Blurring and Canny Edge detection
then it will return the output image
"""
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gau_blurred = cv2.GaussianBlur(gray_image,(5,5),0)
return cv2.Canny(gau_b... | c7b166a6277168dd0b16d612153fa2308a95ee8a | 3,609,578 |
def solve_classical_ising(J, N, pos):
"""
function to solve classical optimization problem defined by graph
"""
# define and build classical Ising
model, linear, quad, offset = build_classical_ising(J, N)
# Solve classical Ising model
solution = solve_ising(linear, quad)
# print calss... | e2d2e03dad0d66c3d990f93b74d18648994beacb | 3,609,579 |
import csv
def load_fueltech_map(fixture_name):
"""
Reads the CSV to load the fueltech map
Fields are:
fuel_source,fuel_source_desc,tech,tech_desc,fueltech_map,load_type
"""
MAP_KEYS = [
"fuel_source",
"fuel_source_desc",
"tech",
"tech_desc",
... | 80c9530606a8c159d585b5ee0d27e78ba667db04 | 3,609,580 |
def info_df_row(request: SubRequest) -> pd.Series:
"""Create a pd.Series that mimicks a row from the info DataFrame."""
name, num, start, end, word = request.param
data = {"seg_num": num, "seg_start_idx": start, "seg_end_idx": end, "word_id": word}
return pd.Series(data=data, name=name) | e33bfa9317d0dd955b73ebb3064d0b6c53d1d191 | 3,609,581 |
def precision_formatter(layer: Layer):
"""Format Dot nodes by layer precision"""
formatting = {'style': 'filled',
'tooltip': layer.tooltip(),
'fillcolor': precision_colormap[layer.precision]}
return formatting | 3ff525ef7d0009ff27c1b223a90c1f77dfe8af66 | 3,609,582 |
def extend_columns_eventbased(orig_df):
"""
Handles adding extra columns based on a condition the value of another column.
:param orig_df: the original dataframe
:return: a new, modified dataframe
"""
global COL_NAMES_NEW_FROM_EXTENSION
global COL_NAMES_TO_DROP_FROM_EXTENSION
#... | 618b1222ab987041fd094dcec521191bcf8a3bf3 | 3,609,583 |
def incidents_per_year_generator(data):
"""
Generate incidents per year graph
Parameters:
-----------
data: dataframe
Returns:
incidents_per_year: dcc.Graph
"""
data['n_injured+killed'] = data['n_injured'] + data['n_killed']
casualties_by_year = data[['year', 'n_killed', 'n_in... | fa5bdb08e1208ef18e9349f912d4a9b841c1a74d | 3,609,584 |
def apps_users(app, **kwargs):
"""List all users for an application"""
app = _okta_get("apps", app,
selector=_selector_field_find("label", app))
app_id = app["id"]
rv = okta_manager.call_okta(f"/apps/{app_id}/users", REST.get)
rv.sort(key=lambda x: x["credentials"]["userName"])
... | ef06a44bd9138c735cdb6c97b9f17bd770b6bb5d | 3,609,586 |
import six
def decode_for_output(output, target_stream=None, translation_map=None):
"""Given a string, decode it for output to a terminal.
:param str output: A string to print to a terminal
:param target_stream: A stream to write to, we will encode to target this stream if
possible.
:param di... | a9ef352d3b5bf80b2c7265b179ed1e02b6b61578 | 3,609,587 |
import html
def create_null(n):
""" Creates empty data containers.
Empty data containers can be used for headless callbacks.
They can also be used to store information on the client side"""
return html.Div(children=[dcc.Store(id=f'null{i}', data=[]) for i in range(n)]) | 3f20614607d532357164d32c025e0d4886911fcf | 3,609,588 |
def colorline(
x, y, z=None, cmap=plt.get_cmap('copper'),
linewidth=3, alpha=1.0):
"""
http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
http://matplotlib.org/examples/pylab_examples/multicolored_line.html
Plot a colored line with coordinates x and ... | bfb3a1e7d0c6bd9febb947696b5c555faae4d869 | 3,609,589 |
def populate_data_store(data_store, assignment_id=None, episode_ids=None,
steps_per_episode_chunk=None):
"""Populate a datastore with an assignment.
Args:
data_store: data_store.DataStore instance to populate.
assignment_id: Assignment ID to create or ASSIGNMENT_ID if this is None.
... | 817299255e20f3ea8664a0edfe0208b1b31dda94 | 3,609,590 |
def create_pip_configuration(options):
# type: (Namespace) -> PipConfiguration
"""Creates a Pip configuration from options registered by `register`.
:param options: The Pip resolver configuration options.
"""
if options.cache_ttl:
pex_warnings.warn("The --cache-ttl option is deprecated and... | 68b419db6dae495e7c75d54a29b29d8eeda36da1 | 3,609,591 |
from typing import Sequence
from typing import List
def get_motifs(cbn: CausalBayesianNetwork, path: Sequence[str]) -> List[str]:
"""classify the motif of all nodes along a path as a forward (chain), backward (chain), fork,
collider or endpoint"""
for node in path:
if node not in cbn.nodes():
... | 5b41e82e30c546bbce75294f5af52358f9942c6a | 3,609,592 |
def update_manifest_node(node: manifest.ManifestNode) -> bool:
"""Updates NODE in stateful manifest so it is preserved even as we traverse models unless dbt is refreshed"""
ctx.dbt.update_node(node)
# ctx.dbt.build_flat_graph()
return True | cafa53029a62d78f9150b27a02a32d5c0bc5354a | 3,609,593 |
def validate_data(data, allow_restricted_fields, kind):
"""
Check that all the fields in `data` correspond to fields in
`ALLOWED_ENTITIES[kind]`. `data` is a dictionary/dictionary subclass, `kind`
is the datastore entity kind. `allow_restricted_fields` is a bool.
"""
if kind not in ALLOWED_ENTIT... | 3b00527a7b726791df6f97bc302ce720e23b2476 | 3,609,594 |
def get_attr_lang(src, attr, default_locale):
"""
Our index stores localized strings in elasticsearch as, e.g.,
"name_spanish": [u'Nombre']. This takes the current language in the
threadlocal and gets the localized value, defaulting to
settings.LANGUAGE_CODE.
"""
req_lang = amo.SEARCH_LANGUA... | e540a4b119b0c9700ce1f95ac018c178e5293632 | 3,609,595 |
def share_in_range(x,omegas_low,omegas_high):
""" calculate share in range """
# a. allocate memory and inialize
Nomegas = omegas_low.size
Ntrue = np.zeros(Nomegas)
Nactive = 0
# b. compute
for i in range(x.size):
if ~np.isnan(x[i]):
Nactive += 1
for h in r... | e27fc7597d75eda4c46695518eecfa7576f1b5af | 3,609,596 |
def parse_inFile(fileName):
"""
Parses a .cmsisdata file to extract the information necessary for project connection file creation
Returns a tuple of (project_name device_name core linker_script defineList includePathList cSrcList asmSrcList headersList libsList)
"""
inFileData = namedtuple('inFile... | 7d4cf025d4d40f3392e9428b5218d26d42992548 | 3,609,597 |
def trio_hits(l_contig, mid_contig_end, blast_hits, olap_dict, cont_dict):
"""
From a unique contig (l_contig), steps across a repeat (mid_contig) to find the next unique contig,
based on best case of adjacent hits in a reference genome (product of the two blast scores).
Called by grow_scaffold()
""... | 843617464c5818353b502de05e9adc1dab69861d | 3,609,598 |
def remove():
"""Remove a vegetable from the current user's vegetables"""
# Check if the user already has that vegetable
user_veg = []
for vegetable in db.execute('SELECT plant_id FROM users_plants WHERE user_id=?', session['user_id']):
user_veg.append(vegetable['plant_id'])
new_veg = int(... | f31e4a6294278b30fc08276e3b96af2e0ec63a23 | 3,609,599 |
from datetime import datetime
def get_formatted_date(date: datetime.datetime) -> str:
""" Formatted date """
return date.isoformat()[:10] | 10704d33e1ae10de6829e4de1e29e2e260b9bd57 | 3,609,600 |
def get_submission_max_ram(session, submission_id):
"""Get the max amount RAM used by a submission during processing.
Parameters
----------
session : :class:`sqlalchemy.orm.Session`
The session to directly perform the operation on the database.
submission_id : int
The id of the subm... | 56aee778f366e8007292512b2efbade4b161472a | 3,609,601 |
def uuid_to_cbuuid(uuid):
"""Convert native Python UUID type to Objective-C CBUUID type."""
return CBUUID.UUIDWithString_(str(uuid)) | e9e91aca658291adc4f1bbdfae9839e98b5c1709 | 3,609,603 |
import re
def is_valid_hostname(hostname):
"""
Check that hostname passed in is valid.
Pretty much a copy paste of this
https://stackoverflow.com/questions/2532053/validate-a-hostname-string
"""
if len(hostname) > 255:
return False
if hostname[-1] == ".":
hostname = hostnam... | aacf57c7ef740c4cebfe008c67867921d4b8a958 | 3,609,604 |
def delta_soga_from_masso(m_orig, m_new, s_orig):
"""Infer a change in global average salinity from mass"""
delta_s = s_orig * ((m_orig / m_new) - 1)
return delta_s | a0ffb18378c3d997ea8ab88286a11e34b9abbb71 | 3,609,606 |
from typing import Union
from pathlib import Path
from typing import Dict
from typing import List
from typing import OrderedDict
def find_packages_source_files(
packages_path: Union[str, Path]
) -> Dict[str, List[Path]]:
"""
List packages source files.
Args:
packages_path: Path to the package... | d210f00e5311fa609fd3841afeecf636649289f4 | 3,609,607 |
from pathlib import Path
import hashlib
import base64
def calc_sha(obj):
"""Calculates the base64-encoded SHA hash of a file."""
try:
pathfile = Path(obj)
except UnicodeDecodeError:
pathfile = None
sha = hashlib.sha256()
try:
if pathfile and pathfile.exists():
... | 2669046e0053f0f73471e9fbadc95a287ed5d9a4 | 3,609,608 |
def L_model_backward(AL, Y, caches):
"""
Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group
Arguments:
AL -- probability vector, output of the forward propagation (L_model_forward())
Y -- true "label" vector (containing 0 if non-cat, 1 if cat)
caches --... | 1e1cb08914c43b7d017df6735c06f87102e459a6 | 3,609,609 |
from graph_tool.all import load_graph
def load_gt_graph(graph_path):
"""Load a graph in graphml or gt format."""
logger.info(f"loading the generated graph file from {graph_path}")
g = load_graph(graph_path)
return g | ddcc5cb56be87412764ec1d499333b132eee0d87 | 3,609,610 |
def generate_key(name: str) -> str:
"""
Given a display name, generate a global unique value suitable
for use as a step key in Buildkite.
"""
norm = name.lower()
for regex in (RE_NONID, RE_MULTI_US):
norm = regex.sub('_', norm)
if norm not in KEY_COUNT:
KEY_COUNT[norm] = 1
... | d3de408564ac34bec8cac53a0621eb51cc99c8cd | 3,609,611 |
def get_session():
""" Set tf backend to allow memory to grow, instead of claiming everything """
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
return tf.Session(config=config) | 3dc72968da1da0df3e0a1cc641b3833afa225da0 | 3,609,612 |
def get_axis_lims_con(epoch):
"""
Generates an invisible mne.viz.plot_topomap plot and gets the ylim from its
matplotlib.axes._subplots.AxesSubplot. Helper function for plot_connectivity.
Parameters:
epoch: mne.epochs.Epochs
MNE epochs object containing the timestamps.
... | b127bd10c1b6d84ff8ba9f452be84d036d0d50ec | 3,609,614 |
import re
from bs4 import BeautifulSoup
import requests
import urllib
def osdn(url: str) -> str:
""" OSDN direct links generator """
osdn_link = 'https://osdn.net'
try:
link = re.findall(r'\bhttps?://.*osdn\.net\S+', url)[0]
except IndexError:
reply = "`No OSDN links found`\n"
... | 579cc6f14b878a45a764f9584d7cae7be2356245 | 3,609,615 |
def abox2bbox(aboxes):
"""covnert affine boxes to bounding point box
reference: https://www.iquilezles.org/www/articles/ellipses/ellipses.htm
Args:
aboxes ([np.ndarray]): affine boxes shape with [*, 3, 3]
"""
c = aboxes[..., :2, 2]
e = np.linalg.norm(aboxes[..., :2, :2], ord=2, axis=-... | 4c43138f232a7e704a2a2a534c146f795e639908 | 3,609,616 |
def nrrd_2_numpy(input_nrrd, return_all=False):
""" Loads nrrd data and optionally return a nrrd header
in pynrrd's format. If array is 4D, swaps axes so
that time dimension is last to match nifti standard.
"""
nrrd_data, nrrd_options = nrrd.read(input_nrrd)
if nrrd_data.ndim == 4... | 250b01136810a42eef71c939759109ca8486ee70 | 3,609,617 |
from typing import Callable
def make_schedule(schedule: config_pb2.Schedule) -> Callable[int, float]:
"""Creates a schedule."""
if schedule.HasField('inverse_time_decay'):
base_schedule = optimizers.inverse_time_decay(
step_size=schedule.inverse_time_decay.base,
decay_steps=sc... | b41caac8fc4a6da91523c263b366222365b40764 | 3,609,619 |
def procstringT0(candidate):
"""
ProcessingString validation function for T0 specs
"""
if isinstance(candidate, dict):
for candi in viewvalues(candidate):
check(r'^$|[a-zA-Z0-9_]{1,100}$', candi)
return True
else:
return check(r'^$|[a-zA-Z0-9_]{1,100}$', candidate... | 67ad6554dbf452d9607439e76bcf31e8c96e00fe | 3,609,620 |
def index():
"""Return an index page."""
return render_template('index.html') | 2220eb1ea5fd14cbb7d8afa17a6e318874986355 | 3,609,621 |
def rreplace(s, old, new, occurrence = 1):
"""
Replaces the last occurence(s) of an expression in a string.
"""
return new.join(s.rsplit(old, occurrence)) | 92a3fdb0e5a2014debd6e3530c7c6c754ed45953 | 3,609,623 |
def get_cal_params(power_data_dict,particle_data,config_header,config_transducer):
"""
Get calibration params from the unpacked file
Parameters come from config_header and config_transducer (both from header),
as well as particle_data (from .RAW file)
"""
cal_pa... | 081e3cf5d48d14056948617bc01d65205ed242aa | 3,609,624 |
def get_decompounder():
"""
Restarts the JVM with the decompounder. It is necessary once in a while.
"""
javabridge.start_vm(class_path=["tf/jwordsplitter/target/jwordsplitter-4.2-SNAPSHOT.jar"])
java_instance = javabridge.make_instance("de/danielnaber/jwordsplitter/GermanWordSplitter", "(Z)V", Fals... | 3a6196a119c6bbbb8793f038abbbd548637f881c | 3,609,625 |
def get_instance():
"""Return a DB API instance."""
return IMPL | 3bbd1f160adde70ac700e4c5d6fb59e315a1d43c | 3,609,626 |
def loadfile(filename):
"""
Helper function to load content given the filename
@param filename: target file's name
@type filename: C{string}
"""
try:
f = open(filename , "r")
except IOError , e:
print >> sys.stderr, "Fail to load file %s: %s" % (filename, e)
return []... | 8315a80cf7f6e4a2c9fb6f08bd4a0ce04540576c | 3,609,627 |
import re
def num_groups(aregex):
""" Counts groups in regexp """
return re.compile(aregex).groups | 3ce4dc9f08ec5ae2e0edfeac889c213569a3053e | 3,609,629 |
def check_internet(url=None):
"""Check if internet is available"""
url = "https://github.com" if url is None else url
try:
urlopen(url)
except URLError as err:
return False
return True | f9f2b4aede5340725ea28d73997ad635e3d6bc19 | 3,609,630 |
import math
def progress_bar_str(char_limit, max_value, current_value):
"""
Returns a pretty progress bar string, complete with colorization.
:param int char_limit: How wide the progress bar (in characters) should
be. This includes the bar and its brackets. Must be at least 6.
:param int max_... | ec1fde450161645559aa6317015c353e641788cb | 3,609,631 |
def post_profession_evidence(profession_id, body):
"""post_profession_evidence
Post profession evidence # noqa: E501
:rtype: Response
"""
if connexion.request.is_json:
if type(body) is not Evidence:
body = Evidence.from_dict(connexion.request.get_json())
evidence = DB... | 06fd3731d6cdf31a6ff4e15c00fd439a87cff043 | 3,609,632 |
from typing import Dict
def type_updater_columns(graph: Graph, updaters: Updaters) -> Dict:
"""Determines the types of graph columns used by Tally updaters."""
column_dependencies = tally_columns(updaters)
column_types = {
col: type_graph_column(graph, col)
for col in column_dependencies.v... | c0dd3db96945226e733e540515724a37103fd127 | 3,609,634 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.