content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def isnetid(s):
"""
Returns True if s is a valid Cornell netid.
Cornell network ids consist of 2 or 3 lower-case initials followed by a
sequence of digits.
Examples:
isnetid('wmw2') returns True
isnetid('2wmw') returns False
isnetid('ww2345') returns True
isnetid('w2345') r... | d4ddd91a9a7a7a4e2e7de778525718ec41c42cbc | 3,609,500 |
def delete_column(idf, list_of_cols, print_impact=False):
"""
:param idf: Input Dataframe
:param list_of_cols: List of columns to delete e.g., ["col1","col2"].
Alternatively, columns can be specified in a string format,
where different column names are separ... | 020ffa98855bdfa3de934122cbd6df79bc2c00e6 | 3,609,501 |
def generate_sql_verification_data(sql_results_instance):
"""Generates the verification text for a given result sql.
Keyword arguments:
sql_results_instance -- the sql results returned from athena
show_columns -- boolean for whether to show column names or not in the results
"""
results_string ... | ac2a880c6f4e2138f2d229aee96d42b81fa6e73b | 3,609,502 |
from pathlib import Path
import glob
def filter_paths(paths, excluded_paths):
"""Filter out path matching one of excluded_paths glob
Args:
paths: path to filter.
excluded_paths: List for glob of modules to exclude.
Returns: An iterable of paths Python modules (i.e. *py files).
"""
... | 8b8e9e19ebc0a47d84e1b55a497438b961af6764 | 3,609,503 |
def get_user_data(username):
"""Returns user data."""
user = User.query(User.username_lower == username.lower()).get()
if user:
user.data["metadata"]["last_updated"]=user.last_updated
return jsonify(data=user.data) if user else jsonify(error=404) | f01106c6c06fc32411ab5e89677933a8f9a040f1 | 3,609,504 |
def filter_roidb(roidb):
"""
Remove roidb entries that have no usable RoIs.
"""
def is_valid(entry):
# Valid images have:
# (1) At least one foreground RoI OR
# (2) At least one background RoI
overlaps = entry['max_overlaps']
# find boxes with sufficient over... | 31ba6a3921e2fc2aabb2e42c6af8ba2bc3566c9b | 3,609,505 |
def _extract_keywords(tweets):
"""...
Args:
tweets: List of tweets.
"""
neg, neu, pos = {}, {}, {}
for tweet in tweets:
for word in tokenizer.tokenize(RE_RUS_LETTERS.sub(u"", tweet["text"].lower())):
keyword = morph.parse(word)[0].normal_form
if keyword in ... | 1b2fb14d010e56695df2586856859c16fff04f56 | 3,609,506 |
import os
def read_captcha(path):
"""
读取验证码图片
:param path: 原始验证码存放路径
:return: image_array, image_label:存放读取的iamge list和label list
"""
image_array = []
image_label = []
file_list = os.listdir(path)#获取captcha文件
for file in file_list:
image = Image.open(path + '/' + file)#打开图片... | 74d463dcf0e8e643d38c79fdc2ee8335944b053a | 3,609,507 |
from typing import Tuple
import torch
def getDiscriminatorModels() -> Tuple[torch.nn.Module, torch.nn.Module]:
"""
Prepares the CycleGAN discriminator models based on the given configuration.
Returns
-------
Tuple[torch.nn.Module, torch.nn.Module]
clean discriminator, distorted discrimina... | a79e5a4933e5ee66b625d08dce69204b5ae7d59b | 3,609,508 |
def merge_runs_by_tag(runs, tags):
"""
Collect the (step, value) tuples corresponding to individual tags for all runs.
Therefore the result might look like this:
<tagA>
+ step:
- <run-1-steps>
- <run-2-steps>
+ value:
- <run-1-values>
- <run-2-values>
.... | 90440ec8d718692978e617920eac52e0ea43bfce | 3,609,509 |
import math
def compute(formula, key, amount=1):
"""Function that computes the amount of fuel needed to create the
component KEY. Uses the formula input to follow the process chain."""
# If you reach FUEL, just return how much <fuel> you need
if key == "FUEL":
return amount
# Count how m... | 9c48f342f5771c8922ea19c101c613e34f884f4f | 3,609,510 |
import numpy
def moment(array,substract_one_in_variance_n=True):
"""
Calculate the first four statistical moments of a 1D array
:param array:
:param substract_one_in_variance_n:
:return: array with: m0 (mean) m1 (variance) m2 (skewness) m3 (kurtosis)
"""
a1 = numpy.array(array)
m0 = a1... | 9eae3d87b76ece9f6d351fe17de2bf439a447718 | 3,609,511 |
def best(z, i, down, values):
""" find best number (first possible downwards or upwards) that leads to z == zero at end"""
for digit in (range(9, 0, -1) if down else range(1, 10, 1)):
z_after = run(z, digit, i, values)
if i == 13: # at the end of the number, z must be zero
if z_afte... | cc440547058e398fc126ab59dec031a0808eda50 | 3,609,512 |
from typing import List
from typing import Tuple
def Gbk_presel(best_gain: List[int], cand1: int, cand2: int, gcode0: int) -> Tuple[int, int]:
"""
# (i) [0] Q9 : unquantized pitch gain
# (i) [1] Q2 : unquantized code gain
# (o) : index of best 1st stage vector
# (o) : index of best 2nd stag... | 1c88fd0c667199647ec9680071ec2ce620dea567 | 3,609,513 |
import struct
def getCommandString(commandCode):
"""Returns a readable string representation of a message code
"""
return struct.pack('<L', commandCode) | 1e0c63a13f9a727cc4aac7a6d24eacad958b0040 | 3,609,514 |
import json
import os
def funcs_for_external(external_fp_fn,
summary_path,
rd_path):
"""
If requesting an external method to get and compare
fingerprints, then use this function to get a dictionary
of pickle paths for each smiles, and the external
fing... | e58ed2b4c0958267a4262c159201905cadf926e1 | 3,609,515 |
from typing import Union
from typing import Optional
def from_graph(graph: nx.Graph,
prob: Union[float, int] = 0.1,
rng: Optional[np.random.Generator] = None) -> nx.Graph:
"""Generates mutated graph with the given mutation probability.
Parameters
----------
graph
... | 4d5b37ae33d718671af92bb1c00996a4b036b0b0 | 3,609,516 |
def get_preprocessed_data_set(data_path):
"""Preprocess the data set and return it. Because a list of targets and the paths
to the images are needed later, the class ImageFolderWithTargetListAndPaths
is used. Preprocessing follows standard ResNet-preprocessing.
Args:
data_path: path to folder... | a57e434e986a3ab875506fd2cc3d15814f6bbae5 | 3,609,517 |
from typing import List
from typing import Tuple
def parse_meta_staff_elem(
staff_elem: Element, resolution: int, measure_indices: List[int]
) -> Tuple[List[Tempo], List[KeySignature], List[TimeSignature], List[Beat]]:
"""Return data parsed from a meta staff element.
This function only parses the tempos,... | 8e1fbef69d4be59af67b3a252e46c0c56e679ee2 | 3,609,518 |
def get_row_audio(syllable_df, wav_loc, hparams):
""" load audio and grab individual syllables
TODO: for large sparse WAV files, the audio should be loaded only for the syllable
"""
# load audio
rate, data = prepare_wav(wav_loc, hparams)
data = data.astype('float32')
# get audio for ea... | 2acc8b4e6fcd909c6183bb97c3fc314d189f59d3 | 3,609,519 |
def perform_import(val, setting_name):
"""
If the given setting is a string import notation,
then perform the necessary import or imports.
"""
if val is None:
return None
elif isinstance(val, string_types):
return import_from_string(val, setting_name)
elif isinstance(val, (li... | 8ceee3d8e42db5de5e1bc08d89b82c8244981a82 | 3,609,520 |
def get_root_url(g, website_url):
"""Given website url, get its root node."""
return (
g.V(website_url)
.hasLabel("website")
.in_("links_to")
) | 662eca8a6d1e6ea1e4e19d8807c3467154a8e715 | 3,609,521 |
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 |
import os
import subprocess
def hg(args):
"""Run a Mercurial command and return its output.
All errors are deemed fatal and the system will quit."""
full_command = ['hg']
full_command.extend(args)
try:
output = check_output(full_command, env=os.environ, universal_newlines=True, shell=True... | e7d2c617375f1791f61c5ecfe494eb8568d063d5 | 3,609,538 |
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 |
import os
def install_user():
""" returns current user
"""
user = os.getenv('USER', None)
if user is None:
raise Exception("Unable to determine current user.")
return user | ca83a4dfb83a3b7fe1ba9129afb39e387bfd059f | 3,609,550 |
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 |
from typing import List
import logging
def vectorize_sentence(sentence: List[str], model, empty_strategy):
"""
Given a text transform it in a list of vectors using Word Embeddings techniques
:param sentence: string containing a sentence
:param model: word embedding model
:param empty_strategy: whi... | fdaca731880d12db70615851b1209f23ecd478be | 3,609,557 |
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 |
def register(ref_img, in_img, ref_weights=None, in_weights=None, cmd=None):
"""Find the 4D affine transform that registers in_img to ref_img
Args:
ref_img -- (type: ndarray) reference image
in_img -- (type: ndarray) input image to be registered
ref_weights -- (type: ndarray, def... | b88596617956a433b3e4d4cde4c9520bd5cbacb9 | 3,609,559 |
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 |
import os
def get_filenames(is_training,datadir):
"""Returns a list of filenames."""
assert os.path.exists(datadir), (
'Can not find data at given directory!!')
if(is_training):
labels = []
data_dir = []
with open('/home/qnie/PycharmProjects/ntumotion/training_protocol/fEDM_R_CS_trainimg... | 355e52ec93fc5b8b6922f68b4050524b13b8ddb7 | 3,609,571 |
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 |
import os
def join_sqlite(
dataset,
file=None,
table_name=None,
compile=False,
debug=False,
quiet=False,
use_cache=True,
):
"""Install scripts in sqlite."""
if not table_name:
table_name = "{db}_table"
if not file:
file = os.path.join(DATA_DIR, "sqlite.db")
... | 06a0d1ae6a3e347b2b2e8e0d43321b73bdbdc7f8 | 3,609,585 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.