content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def tokenize_tweet(inputRow, fields):
"""
A simple tokenizer that takes a tweet as input and, splitting on whitespace, and returns words in the tweet
Args:
inputRow (Row): A spark sql row containing a tweet
fields (list): A list of field names which directs tokenize on which fields to use as so... | 60e1cb52f9e4d537c0d0809b0bd75117468a0338 | 3,624,425 |
def seq_to_kmercount(seq, kmerdict, kmersize):
"""DNA sequence and count number of kmers
in the dictionary, and return this dictionary
"""
seq = str(seq).upper()
length = len(seq) - kmersize + 1
for i in range(length):
kmer = seq[i:i+kmersize]
# select lexographically lowest km... | fa8b67863092d43d5a9167048702d4b7a089f7b1 | 3,624,426 |
def create_resource_from_db_row(row):
"""Create a resource type from a database resource row.
Args:
row (Resource): the database resource row.
Returns:
Resource: the concrete resource type.
"""
parent = (
create_resource_from_db_row(row.parent) if row.parent else None)
... | 977196a83c8de1a580c408228b12379903fbb513 | 3,624,427 |
def build_embeddings(symbolic_features, integer_features,
embeddings, large_discrete, merged_inputs,
X, test_X, train_dict, test_dict, dataset):
"""Define embedding layers/inputs"""
merged_dim = 0
for (name, values) in symbolic_features.items():
feature_name... | 7aa0fa92f1aadd4f4f6554b11be378657575deea | 3,624,428 |
def get_results(job_key):
"""
Results page for <job_key>. If job is still running, this will redirect to the same page with the link to refresh again. When its done,
the refresh link will link to the tables.
"""
job = Job.fetch(job_key, connection=current_app.redis)
### Return results
if... | 4976e09be902da7e4d3c4f02558cc4d25dbb706a | 3,624,429 |
def getFlipboardTitles():
""" Get title of all dashboard inside Config/ """
config_names = getConfigNames()
listNameDashboard = list()
rcx = 1
for config in config_names:
config = parseXmlLayout(config)
if 'details' in config and 'page_title' in config['details']:
listNam... | f6b54d9abb43cab02f4c9fc2d575660577f919aa | 3,624,431 |
def availability(url, session=None):
"""
Check HTTP status code of given URL.
200 or 301-308 is OK, else is not.
:param url: URL to check.
:type url: str
:param session: Requests session object, default is created on the fly.
:type session: requests.Session()
"""
status = getcode(u... | 4d895223b84b02243705878c747b0ee15b988acd | 3,624,432 |
import ctypes
def cudnnGetConvolution2dForwardOutputDim(convDesc, inputTensorDesc, filterDesc):
""""
Return the dimensions of the output tensor given a convolution descriptor.
This function returns the dimensions of the resulting 4D tensor of a 2D
convolution, given the convolution descriptor, the in... | 28d3421fdf838f93dceaeea462cad1cacdde09ee | 3,624,433 |
from datetime import datetime
def ocean_loading(time, amp, phases, lon):
"""
time is in hours from Jan 1, 1900, stationlongitude is longitude
purpose: To assess the ocean loading/gravity effect due to the
separate tidal primary components derived from the Agnew
pr... | dcfb7ae82dfeb6ace524033fafdd4ad7cb907c3a | 3,624,434 |
def convert_ms_2_tf(tf_ckpt_path, ms_ckpt_path, new_ckpt_path):
"""
convert ms checkpoint to tf checkpoint
"""
# load MS checkpoint
ms_param_dict = load_checkpoint(ms_ckpt_path)
for name in ms_param_dict.keys():
if isinstance(ms_param_dict[name].data, Tensor):
ms_param_dict[n... | 1214438ed29c8e4e9c9f35c7f8549e837b9f423d | 3,624,436 |
def servers():
"""Unauthorized endpoint to check for configured servers. Returns the name and ID of the server for selection
when logging in. Also indicates the current server (if one is selected)
"""
server_list = []
for s in current_app.config['LABMGR_CONFIG'].list_available_servers():
s... | 78ac93693b493fea8e9583337d7e1f24aea313c5 | 3,624,437 |
def ammonia_fake() -> (oechem.OEMol, oechem.OEAtomBase):
"""
Creates an ammonia molecule with fake Wiberg bond orders. Also returns
the trivalent nitrogen in the molecule
"""
ammonia = oechem.OEMol()
oechem.OESmilesToMol(ammonia, "N")
oechem.OEAddExplicitHydrogens(ammonia)
fake_wbo = [1... | 9f0f9ec19d7d8b7a373d047dd023f361ddfa61ed | 3,624,438 |
def check_token():
""" Token checking endpoint.
---
get:
summary: Check the validity of a token.
description: This endpoint checks for the validity of a given authentication token.
parameters:
- token: The token to check.
responses:
200:
... | 14d2b08fe717f9760e0f535a455f56f1b5a667c0 | 3,624,439 |
from typing import Tuple
def subgrid(
A: xr.Dataset, subgrid_spec: Tuple[int, int, int, int], stagger: str = "outer"
) -> xr.Dataset:
"""Make a ROMS xarray Dataset on a horizontal subgrid"""
# Suppese xi_rho and eta_rho allways present
# imax = len(A.xi_rho)
# jmax = len(A.eta_rho)
# How abo... | efd709562d340bfa570086b4383d85e71e5555f3 | 3,624,440 |
def format_decimal(number):
"""Formats `number` for current locale."""
attan = Xuanzang.get_attan()
return attan.format_decimal(number) | 067dd4a02a3b7932762e124a101acc051d49aed6 | 3,624,441 |
def optimization_for_fishfeed_substitution(fishfeed_table, lipidmicro,
protmicro, carbmicro, watermicro,
ashmicro, incorporation_rate,
MJ_kgcarb, MJ_kgprot, MJ_kglip):
"""Returns the subs... | 88c2bfe33249dfd099201fab2dd0fd7c07fd218a | 3,624,442 |
import re
def remove_repeating_characters(sentence):
"""
remove non alphaneumeric characters which repeat more than 3 times by its 3 occurrence (e.g. ----- to ---)
:param sentence:
:return:
"""
sentence = re.sub('(\W)\\1{3,}', '\\1', sentence)
return sentence.strip() | 9bf8e53c3fed78b2a8cd4c91a6a68f980c270654 | 3,624,443 |
import random
def crossover(p_1, p_2, r_cross):
"""
order 1 crossover / OX / order crossover
:param p_1: parent 1
:param p_2: parent 2
:param r_cross: rate of crossover
"""
if random.random() < r_cross:
c1, c2 = p_1.copy(), p_2.copy()
pt_1 = random.randint(0, len(p_1)-1)
... | d0bdc28803feed1a67864204b8b3177f70f8cda7 | 3,624,445 |
def tree_to_treesegment(canvas, t, make_node=TextWidget,
make_leaf=TextWidget, **attribs):
"""
Convert a Tree into a ``TreeSegmentWidget``.
:param make_node: A ``CanvasWidget`` constructor or a function that
creates ``CanvasWidgets``. ``make_node`` is used to convert
... | ba9e6d9546a726adefc6259d87f2a5b05f41788d | 3,624,446 |
import numpy
def borrow_for_color_red(base_color_dict, from_left, from_right):
"""!
@brief Borrows colors for the base color red.
@param base_color_dict Dictionary with arrays of all the base colors.
@param from_left Boolean flag for recursive calls, if we came from the left.
@param from_rig... | 1f3b58f11390dfd51301dce234a3df35655673f5 | 3,624,447 |
def requestPdpContextActivationReject():
"""REQUEST PDP CONTEXT ACTIVATION REJECT Section 9.5.5"""
a = TpPd(pd=0x8)
b = MessageType(mesType=0x45) # 01000101
c = SmCause()
packet = a / b / c
return packet | a34b694cd7bbd78b6c67c8362da0c6dd92b72792 | 3,624,448 |
def add_month(year, month, delta):
"""
Helper function which adds `delta` months to current `(year, month)` tuple
and returns a new valid tuple `(year, month)`
"""
year, month = divmod(year * 12 + month + delta, 12)
if month == 0:
month = 12
year = year - 1
return year, month | 8f509bba44bb27579b948c3b26e5f7c027be445c | 3,624,449 |
from datetime import datetime
def extractTime(line):
"""
extracts date or time from an event file input line
and returns a datetime object.
"""
dt = line.split(None, 1)[0]
if len(dt) > 20:
print(dt, 'Invalid dateTime string')
return
#print('extractTime : ', line )
... | 18692ef0b8ce79182ee7e98b523160dc6feea4b0 | 3,624,450 |
def ramp(width=32, height=32, density=0.25):
"""Support downward forces on a ramp."""
return staircase(width, height, density, num_stories=1) | bb0b4cb5b36047b37e43c932d9923f5541434f35 | 3,624,451 |
def zeros(shape, backend=TensorFunctions):
"""
Produce a zero tensor of size `shape`.
Args:
shape (tuple): shape of tensor
backend (:class:`Backend`): tensor backend
Returns:
:class:`Tensor` : new tensor
"""
return Tensor.make([0] * int(operators.prod(shape)), shape, ba... | 9af26b57e46984e6158168183a43c42101d73f0d | 3,624,452 |
def getInitFile():
"""
function: get init file
input : NA
output : NA
"""
if isSupportSystemOs():
return INIT_FILE_REDHAT
else:
return INIT_FILE_SUSE | a2b197ce97cf96565846427beb516803c4fd603d | 3,624,453 |
def compare(returns, benchmark, aggregate=None, compounded=True,
round_vals=None, prepare_returns=True):
"""
Compare returns to benchmark on a
day/week/month/quarter/year basis
"""
if prepare_returns:
returns = _utils._prepare_returns(returns)
benchmark = _utils._prepare_benc... | 5f04b9ba9d614424fd3244a02971809356f04850 | 3,624,454 |
import json
def __get_job_obj(profile):
"""Return the 'job' object in the profile."""
with open(profile, 'rt') as json_fobj:
data = json.load(json_fobj)
return data['jobs'][0] | 2af6658f8a54987229dffe35efe37d2dace9f0bb | 3,624,455 |
import configparser
def getconfloc() :
""" Renvoie la configuration total des localisations"""
cfg = configparser.ConfigParser()
cfg.read(clt_path)
location = {}
for i in cfg.options('Locations') :
location[i] = getlocation(i)
return location | 33101369c2d93fc47d2c198c38d7604b4458dbca | 3,624,456 |
def median(r):
"""Return the median of an iterable of numbers.
The median is the point at which half the numbers are lower than it and
half the numbers are higher. This gives a better sense of the majority
level than the mean (average) does, because the mean can be skewed by a few
extreme numbers ... | ed1bb07e39ddec8c702f55fb3555ca3b03ca0c74 | 3,624,457 |
def flatten_evidence(stmts, collect_from=None):
"""Add evidence from *supporting* stmts to evidence for *supported* stmts.
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
A list of top-level statements with associated supporting statements
resulting from bui... | c5374a57b36d3e4ad8537d05c4ce2beb76c9450b | 3,624,458 |
def get_binary_image(image):
"""Converts image to black and white"""
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
(thresh, black_white_image) = cv2.threshold(
gray_image, 150, 255, cv2.THRESH_BINARY_INV)
return thresh, black_white_image | 8bdf03ef008e9c9fc603197007b867f450dba26f | 3,624,459 |
def analyze_sentiment(text):
"""
Sends a request to the Google Natural Language API to analyze
the sentiment of the given piece of text.
"""
request = language_service.documents().analyzeSentiment(
body={
'document': {
'type': 'PLAIN_TEXT',
'content': text,
... | 62591cb06c5694c9d09b8bf43397e39bbea64fab | 3,624,460 |
def php_array_slice(_array, _offset, _length=None, _preserve=False):
"""
>>> input = Array("a", "b", "c", "d", "e")
>>> php_array_slice(input, 2)
{0: 'c', 1: 'd', 2: 'e'}
>>> php_array_slice(input, -2, 1)
{0: 'd'}
>>> php_array_slice(input, 0, 3)
{0: 'a', 1: 'b', 2: 'c'}
>>> php_arra... | c88d107da70191351a52e42e8f1a91407b0c4581 | 3,624,461 |
def scale_clips(boxes, canvas_area, density=0.40):
"""
Resizes and returns cropped words based on canvas area, density, and word complexity
Input:
`boxes` user words pandas dataframe
`canvas_area` total area of canvas
`density` float of desired area to fill on canvas
Output:
... | 5b9623041ccd3ca6d3a6a9e61a56fba39dda6fa6 | 3,624,462 |
def create_snippet(text):
"""
:param text:
:return:
"""
if len(text) < 500:
return text
initial_cut = text[:550]
last_index_of_space = initial_cut.rfind(' ')
last_index_of_semicolon = initial_cut.rfind(';')
last_index_of_comma = initial_cut.rfind(',')
last_index_of_per... | 171f6d9d9e8dfb9e72cd5d075b19a08370eba163 | 3,624,464 |
def collect_args():
"""
Sets up and collects necessary arguments using ArgumentParser.
Returns
-------
args : argparse.Namespace
Namespace containing the arguments and their values specified by the user.
"""
parser = ArgumentParser('python intensity.py')
parser.add_arg... | 9ea5e29af0185d329f5a33473d8430e0cfd1b20e | 3,624,466 |
def get_losses(model, dataset, criterion, device):
"""
calculates loss for each item
"""
model.eval()
loader = DataLoader(dataset, batch_size=1)
losses = []
for i,data in enumerate(loader):
data = Variable(data).to(device)
# ===================forward=====================
... | 1b26ae1eefb09ff857b1734e08221124fa3b7cc7 | 3,624,467 |
import requests
def get_dnac_jwt_token(dnac_auth):
"""
Create the authorization token required to access DNA C
Call to Cisco DNA Center - /api/system/v1/auth/login
:param dnac_auth - Cisco DNA Center Basic Auth string
:return: Cisco DNA Center JWT token
"""
url = DNAC_URL + '/dna/system/ap... | 93144fc43306eb668ff780b7a93834b9b21d2b07 | 3,624,468 |
import types
def get_reconstruction_origin(r):
"""Compute the origin of a reconstruction."""
s = r.scale
pose = types.Pose([r.rx, r.ry, r.rz], [r.tx / s, r.ty / s, r.tz / s])
return pose.get_origin() | 63c82c9b365e753ff665a6dd95c23aff3160acd2 | 3,624,469 |
def is_empty(table: Map[Key, Value]) -> bool:
"""Is the map empty?
Args:
table: The input map.
Returns:
True if the map is empty.
"""
return table.is_empty() | 419382c02af5320dea6c754a4d32843b58e39eaa | 3,624,471 |
from typing import Optional
def to_latex(circuit: Program, settings: Optional[DiagramSettings] = None) -> str:
"""
Translates a given pyQuil Program to a TikZ picture in a LaTeX document.
Here are some high points of the generation procedure (see ``pyquil/latex/_diagram.py``):
- The most basic build... | 78b7c9f7efddbb3e874a4f4a61d7c3c3c0e44da5 | 3,624,472 |
def autodetect_filename(fn):
"""Guess based on filename.
"""
for k in EXT_MAP:
if fn.endswith(k):
return EXT_MAP[k]
return None | a2001bdead333334a9b922fa219696fcd62cc122 | 3,624,473 |
def get_password_hash(password):
"""
Se calcula el hash de un string
Parameters
----------
password : str
Texto al que se le calculara el hash.
Returns
-------
out : str
String con el hash correspondiente al texto.
"""
return pwd_context.hash(password) | d738da51c57560d6e84c91cfc46b78367fceb0b8 | 3,624,474 |
def transform_function(fromsys, tosys, copyobstime=True, priority=1):
"""
A function decorator for defining transformations between coordinate
systems.
.. note::
If decorating a static method of a class, ``@staticmethod``
should be added *above* this decorator.
Parameters
----... | c8ffde1729791c8d03611c296b8adf5f941099ed | 3,624,476 |
def remove_empty_boxes(boxes, labels):
"""Removes bounding boxes of W or H equal to 0 and its labels
Args:
boxes (ndarray): NP Array with bounding boxes as lines
* BBOX[x1, y1, x2, y2]
labels (labels): Corresponding labels with boxes
Returns:
ndarray: ... | 4f004a9d77cc39eb18d62f6386d7e51ddd077e9d | 3,624,477 |
def add_hr_zones(df):
"""Add columns with the time spent at each zone."""
df_zones = create_df_with_zones(df['file'])
out = pd.concat([df, df_zones], axis=1)
out.loc[:, 'z1/z2':'z5'] = round(out.loc[:, 'z1/z2':'z5']/60, 1)
return out | 85fd453a9735303f230d47a0e137052aa45a9ef6 | 3,624,478 |
def check_data(ctx, datasets):
"""
checks the data of the current experiment folder; note: must follow before data aggregation
:return True if all OK; False otherwise
"""
print('### checking data ###')
experiment = 'r_' + ctx['experiment_folder']
run = create_or_get_dict(datasets, experiment... | 042c10c8447c6cd51e62bb8b39f2c4fc3324a78b | 3,624,479 |
def _ParseJobIds(job_ids, sparse_log, error_log):
"""Parse job ids."""
if ':' in job_ids:
job_ids = job_ids.split(':')
assert len(job_ids) == 3
job_ids = [int(x) for x in job_ids]
job_ids = np.arange(job_ids[0], job_ids[1], job_ids[2])
job_ids = [str(x) for x in job_ids]
elif ',' in job_ids:
... | a83553a32f8882922e1b90b60bfd353b261895fb | 3,624,480 |
import torch
def model_fn(batch, model, criterion, device):
"""Forward a batch through the model."""
mels, labels = batch
mels = mels.to(device)
labels = labels.to(device)
outs = model(mels)
loss = criterion(outs, labels)
# Get the speaker id with highest probability.
preds = outs.... | 2b9907e8f0fbec50b955082efb30d8cddc88b663 | 3,624,481 |
def tree_is_to_be_used(tree):
"""
discard the input tree if:
1) the root is FRAG
2) it contains empty category such as *T*
3) a node with more than two children
"""
def rec(node):
if isinstance(node, Tree):
if len(node.children) > 2:
# logger.warn(f'more t... | 051c7c23a464573e8f687eff690c1f42cd5d9eaf | 3,624,482 |
import scipy
def score_gene_sets(ds, gs, method='mean_z_score', permutations=None,
random_state=0, smooth_p_values=True, progress=False):
"""Score gene sets.
Note that datasets and gene sets must be aligned prior to invoking this method. No check is done.
mean_z_score: Compute the z-... | 877cdf3eddfd1a1484c8a778a4106cad6dbcbaed | 3,624,483 |
from plotly.basedatatypes import BaseFigure, BaseLayoutType
def iplot(figure_or_data, **plot_options):
"""Create a unique url for this plot in Plotly and open in IPython.
plot_options keyword arguments:
filename (string) -- the name that will be associated with this figure
sharing ('public' | 'privat... | 4c14b04f410fa685395376a6d129af06e0e8b73f | 3,624,485 |
def _fread3_many(fobj, n):
"""Read 3-byte ints from an open binary file object."""
b1, b2, b3 = np.fromfile(fobj, ">u1",
3 * n).reshape(-1, 3).astype(np.int64).T
return (b1 << 16) + (b2 << 8) + b3 | ba3cc17a2f0b87a015a2dbfb309a947492246114 | 3,624,486 |
def _extract_rel_addr(op_bytes, mnemonic_type):
"""
Extract the relative address at the level from the
binary operation (borrowed from Koo's and Polychronakis'
implementation).
"""
addr = 0x0
mask = 0x0
# Aside from mnemonic bytes, all remaining bytes wou... | 231cbd14262fe92038a2394d9896240b8805b5c0 | 3,624,487 |
def is_transformer(actor):
"""
Checks whether the actor is a transformer.
:param actor: the actor to check
:type actor: Actor
:return: true if a transformer actor
"""
return isinstance(actor, OutputProducer) and isinstance(actor, InputConsumer) | 3b10a212dce64b472ad27651596a269a0ce02102 | 3,624,488 |
def ChoiceToEnum(choice, enum_type, item_type='choice', valid_choices=None):
"""Converts the typed choice into an apitools Enum value."""
if choice is None:
return None
name = ChoiceToEnumName(choice)
valid_choices = (
valid_choices or
[arg_utils.EnumNameToChoice(n) for n in enum_type.names()])
... | 291702a17fc7dcc57ed09dbf9cba0d1a466e982f | 3,624,490 |
def resubmit_alert(uuid, *args, **kwargs):
"""Resubmit an alert for analysis. This means the alert will be re-analyzed as-if it was new.
:param str uuid: The uuid of the alert to be resubmitted.
:return: A result dictionary (has 'result' key).
:rtype: dict
"""
return _execute_api_call('analysis... | 18b5526544a5507061e44f454f984065f17a8833 | 3,624,492 |
def get_context(canvas):
"""Get ``cairo.Context`` used to draw onto the canvas."""
return canvas.renderer._get_context() | 1d68e6eb742dff906b6e64c85d9609e34f508b77 | 3,624,493 |
from traitsui.toolkit_traits import FontTrait
def Font(*args, **metadata):
""" Returns a trait whose value must be a GUI toolkit-specific font.
.. deprecated:: 6.1.0
``Font`` trait in this package will be removed in the future. It is
replaced by ``Font`` trait in TraitsUI package.
"""
... | ea3d97e1fab8ad177cec3defcca6d1fc99323819 | 3,624,494 |
def ArclinkRequestSummary_Meta():
"""ArclinkRequestSummary_Meta() -> MetaObject"""
return _DataModel.ArclinkRequestSummary_Meta() | fc204332096109e44600936439fd12510f600e41 | 3,624,496 |
from datetime import datetime
def convert_datetime_to_string_date(now: datetime = datetime.now()) -> str:
"""
Converts now to string format yyyy-dd-yy-hh-mm-ss
:param now: datetime. Date in datetime format. Default value is datetime.now().
:return: str.
"""
year = now.year
month = add_zero... | f5f99498e98975409f81a90f0a1aabaca744d328 | 3,624,497 |
import math
def _sin(num):
"""The sin function.
Args:
num -- A number.
Returns:
sin(num)
"""
if var_type(num) == "number":
# This only works with 1D arrays
# Just implemented for scalar at this point
return math.sin(num)
raise Val... | c2ecc0e0607ea061d7add614ac58003503f17f02 | 3,624,498 |
def fahrenheit_from(celsius):
"""Convert Celsius to Fahrenheit degrees."""
try:
fahrenheit = float(celsius) * 9 / 5 + 32
fahrenheit = round(fahrenheit, 3) # Round to three decimal places
return str(fahrenheit)
except ValueError:
return "invalid input" | e31ac8c62f108652fe3cc2ee1516a5b3a1a9e568 | 3,624,500 |
from typing import Dict
def evaluate_task(
task: TaskDocument,
funct_scores: Dict[str, int] = SETTINGS.QCHEM_FUNCTIONAL_QUALITY_SCORES,
basis_scores: Dict[str, int] = SETTINGS.QCHEM_BASIS_QUALITY_SCORES,
solvent_scores: Dict[str, int] = SETTINGS.QCHEM_SOLVENT_MODEL_QUALITY_SCORES,
task_quality_sco... | 881aaa390ecc8b6f532080a3bbc890478c8a6844 | 3,624,501 |
import smtplib
def send_email_reports(email_setting,summary):
"""
根据传入的邮件策略发送邮件
:param email_setting: 邮件策略;string;"1"--代表始终发送
:param summary: 测试结果集;dict;{}
:return: response: 统一的结果体;dict;{}
"""
if '@sina.com' in EMAIL_SEND_USERNAME:
smtp_server = 'smtp.sina.com'
elif '@163.com... | ca2d46ee29e3220b36047888227221798e39fc0a | 3,624,502 |
def compute_q(a, N):
"""
Given: an vector a in R^m (except for 0 vector),
compute the discrete approximation to the convolution
q(u) = (p_0 * p_1 * ...)(u) = int p_0(t) p_1(u-t) ... dt
where x_i ~ UNIF[-1,1], i.e. p_i = 1/2 if |x_i|<=1 or 0 o.w.
Returns
(N,) numpy.array, q = [q_0, ..., q_N-... | 9ef04807d55c16542623055e58cadc82629e7a99 | 3,624,503 |
import math
import traceback
def align_face(image, coordinates):
""" Face detection from dlib landmark detection
:param: facial image local path or image of numpy array
:return: faces coordinates list and landmarks
"""
try:
d = dlib.rectangle(coordinates[2], coordinates[0], coordinates[3],... | e8c55e1cf88c9289cbf047634b1ff802fb2f12b3 | 3,624,504 |
def make_s3_client(credentials):
"""Make a client for uploading to S3.
credentials: an orgtup.AwsCredentials object
"""
return client(
's3',
aws_access_key_id=credentials.access_key_id,
aws_secret_access_key=credentials.secret_access_key) | cc7eb7ace4acb4f4cd99b35e3fe3cf09f738ba5e | 3,624,505 |
def rdkit(function):
"""
"""
def wrapper(self, *args, **kwargs):
"""
"""
if config['extras']['rdkit']:
return function(self, *args, **kwargs)
else:
warn("The RDKit Python wrappers are not installed.", UserWarning)
return wrapper | 07846fbf3db95bed8897c79f1615983b704c811d | 3,624,506 |
def review_filters_inline(request, review_id, template_name="manage/reviews/review_filters_inline.html"):
"""Renders the filter section of the review view.
"""
review_filters = request.session.get("review-filters", {})
review = lfs_get_object_or_404(Review, pk=review_id)
return render_to_string(tem... | 18491e8cc7c403542e77b621bd1691e27d2220d2 | 3,624,507 |
def get_text(title='Enter a label', default=None):
"""Prompt the user to enter text using QT
:param title: Name of the prompt
:param default: Default text to show in prompt
Returns:
The text the user typed, or None
"""
result, isok = QtWidgets.QInputDialog.getText(
None, title, ... | 807861a62ade7adc6361e264c422a072a278ed76 | 3,624,508 |
def is_edge():
"""is_edge.
"""
try:
IoTHubModuleClient.create_from_edge_environment()
return True
except Exception:
return False | 1cb09bceb7a12d7fe4361528b07954b9025be265 | 3,624,509 |
def get_target_supported_toolchains(target):
""" Returns target supported toolchains list """
return TARGET_MAP[target].supported_toolchains if target in TARGET_MAP else None | cd37a32ec1342bb4825a121c608aec41c4151ec2 | 3,624,511 |
def big_endian_to_int(value):
"""
Ethereum RLP Utils:
Convert big endian to int
:param value: big ending value
:return: int value
"""
return int.from_bytes(value, byteorder="big") | 57c9b05471e3558cae1a0d36dd3089b4d180faeb | 3,624,512 |
def supply(request, page_name):
""" Handle the request for viz_chart widget."""
_ = page_name
_ = request
all_lounges = Team.objects.order_by('name').all()
return {
"all_lounges": all_lounges,
} | 4e9090c991069338d8db451d309dd0575d3ea91a | 3,624,513 |
def human_time(runtime, decimals=2):
"""Display runtime in a human friendly format."""
if runtime < 1:
return str('mms: ' + str('{:f}'.format(rounder(runtime * 1000, decimals))))
elif runtime < 60:
return str('sec: ' + str('{:f}'.format(rounder(runtime, decimals))))
else:
return ... | 40364bf000f37e59a23fa3cb8163d9e2ae8f6fbb | 3,624,514 |
def calc_c_s(p, polyol_data_file):
"""
Estimates the saturation concentration of CO2 in a polyol solution using
interpolated measurements of solubility.
Parameters
----------
p : float
pressure at which to estimate the saturation concentration [Pa]
polyol_data_file : string
... | 0af3df6554c0c1a4098b54295cde2de9842c2420 | 3,624,515 |
def _read_files(file_names):
"""
Reads content from all specified file names
Args:
file_names: set of file names
Returns:
list of lines from all files
"""
all_lines = []
for file_name in file_names:
try:
with open(file_name) as f:
lines = f... | 98fabeeaeaf6dd142acaf7cf84c0ac25583bcdbf | 3,624,516 |
def create_track_log(db, sessionID):
"""
Instantiate the Track History Collection.
:param db: The database object.
:param sessionID: Current user's session ID.
:return: The Track History Collection object.
"""
collection_name = 'track_history_' + sessionID
track_collection = db[collecti... | 5fb72ae83e5a805ad8e35f62c9474e51170d3fb2 | 3,624,517 |
def parse_events(handle, blocksz):
"""
This function reads an events.txt file as it's written by the source
engine, returns a list of DemoInfo instances containing demo name,
killstreaks and bookmarks.
handle : Open file handle to the events file. Must be readable.
blocksz : Block size the handle file should be ... | 3afd0aa4c28a839d09ac6a85e42d68d0938a60f6 | 3,624,518 |
def sum_allcation_from_shimenreservoir():
"""
Real Name: Sum Allcation From ShiMenReservoir
Original Eqn: Sum Allocation ShiMenReservoir To HouChiWeir+Sum Allocation ShiMenReservoir To ShiMenAgriChannel
Units: m3
Limits: (None, None)
Type: component
Subs: None
"""
return (
... | c21e48d87f35451bf2bc090d82272bec9389e24f | 3,624,519 |
from typing import Optional
from typing import Callable
def scale_by_fromage(
step_size: float = 1e-3,
min_norm: float = 1e-6,
step_size_factor_fn: Optional[Callable[[jnp.ndarray], jnp.ndarray]] = None,
) -> GradientTransformation:
"""Scale updates by Frobenius norm of parameters and grads.
Refer... | af39416b6ccd23d7aced1c65b79fa8e0fbf9cf4e | 3,624,520 |
def create_app(configobj=ProdConfig):
""" Create and configure Flask Application """
app = Flask(__name__)
app.config.from_object(configobj)
configure_blueprints(app)
configure_extensions(app)
configure_callbacks(app)
configure_filters(app)
configure_error_handlers(app)
return app | bcdfbc1e7a415204d8bc222f40b5d3a874cb0276 | 3,624,521 |
def istowest(bb1, bb2, north_vector=[0,1,0]):
""" Returns True if bb1 is to the west of bb2.
For obj1 to be to west of obj2:
- obj1 is close to obj2
- The side faces for obj1 and obj2 overlap
- obj1 is west obj2
"""
#Currently a North Vector of 0,1,0 (North is in the positive Y... | 73f5c4fdf333e2af395fc1b13dd5ccb82837c93d | 3,624,522 |
import warnings
def _generic_dimensions(array, unit, className="Dimension", **kwargs):
"""Return a dimension object based on the array coordinates."""
# labeled
if str(array.dtype)[:2] in [">U", "<U"]:
if unit != "":
warnings.warn("Ignoring unit argument for LabeledDimension.")
... | 4fc002cf38560cbfc138332c28034705b894153d | 3,624,523 |
def InvertDepthNorm(
depth, maxDepth=1000.0, minDepth=10, transform_type='inverse'
):
"""Renormalizes predictions back to targets space"""
if transform_type == 'inverse':
return maxDepth / depth
elif transform_type == 'scaled':
return depth * minDepth
elif transform_type == 'log':
... | 634ae5d7e3e92b84328c42683fe321d8c8ab7ced | 3,624,524 |
from typing import Dict
def rename_columns(df: pd.DataFrame, columns: Dict[str, str]) -> pd.DataFrame:
""" Rename columns of given dataframe `df`. """
return df.rename(columns=columns) | 1f321d4856ef75e77e24fb4a6bd60fdab7f2f6f6 | 3,624,525 |
def solid_material(color):
"""Create a material."""
material = rt.StandardMaterial()
material.Ambient = color
material.Diffuse = color
material.Specular = rt.Color(255, 255, 255)
material.Shininess = 50.0
material.ShinyStrength = 70.0
material.SpecularLevel = 70.0
return material | 4e280b01ba21254fe95260335b33c67c3b2de266 | 3,624,526 |
import re
def only_en(x):
"""
Only keeps English alphabets in a string or a pandas.DataFrame.
Args:
x: The content to be parsed. Either a string or a pandas.DataFrame.
Returns:
A new string or a pandas.DataFrame only includes English alphabets.
|
"""
def func(_s):
... | 8a32bfedf7e1d9bfa6a656bcc67fb718951d1f38 | 3,624,527 |
from datetime import datetime
def test_reformat_params_reduction(monkeypatch):
"""reformat_params should remove "%" and convert to float"""
yr = datetime.today().year
def mock_expr_str_to_datetime(string):
return datetime(yr, 12, 31)
monkeypatch.setattr(vp, "expiration_str_to_datetime", mock... | 571f66e5c826e08af05b4b7bf827f5df1e5fc4d2 | 3,624,528 |
import torch
def gen_noise_Gaussian(num_instance, n_dim=2):
"""generate n-dim Gaussian random noise"""
return torch.randn(num_instance, n_dim) | 77237cf7a81408fae9099d4647e30c53e9866ab3 | 3,624,530 |
def detect_api_mismatch(ref_api, other_api, *, ignore=()):
"""Returns the set of items in ref_api not in other_api, except for a
defined list of items to be ignored in this check.
By default this skips private attributes beginning with '_' but
includes all magic methods, i.e. those starting and ending ... | 4353f3f6b825570e3193b57dbb08c3a26c7f59b9 | 3,624,531 |
def object_storage_name(instance, filename):
"""
Create a name spaced file path from the File obejct's checksum property.
This path will be used to store the content copy
:param instance: File (content File model)
:param filename: str
:return: str
"""
return generate_object_storage_name... | b836aedf6bc9034f5677796303abfb050d716c9c | 3,624,532 |
def unbatch_padded(x, lens_x):
"""Make a list of individual batch elements with padded (masked) entries omitted"""
x_split = x.chunk(x.shape[0], dim=0)
x_clean = [x_split[i].reshape(-1, 2)[:lens_x[i]].detach().cpu().numpy()
for i in range(len(lens_x))]
return x_clean | 8042076f8637ced12ba31e077198de6ed6841145 | 3,624,533 |
from typing import Any
def strip_non_null_and_list_from_type(graphql_type: GraphQLOutputType) -> Any:
"""Return the GraphQL type stripped of its GraphQLNonNull and GraphQLList annotations."""
while isinstance(graphql_type, (GraphQLNonNull, GraphQLList)):
graphql_type = graphql_type.of_type
return ... | a074e5dfd2e6c4855f68e3c6b8b1a2cacadd997f | 3,624,534 |
def _make_p_M_x(p_M_min=5., p_M_max=8.5, M_step=0.1, n_M=None):
"""
Makes the X values (i.e., the magnitudes) for a p_M distribution.
"""
if n_M is not None:
p_M_x = np.linspace(p_M_min, p_M_max, num=n_M)
else:
if M_step is None:
M_step = 0.1 # in case it's passed a... | be2fbc3fc3d647243775ffd9fb057a982df76cdc | 3,624,535 |
def make_ip_thermostat(
device: hm_device.HmDevice, device_address: str, group_base_channels: list[int]
) -> list[hm_entity.BaseEntity]:
"""Creates IPThermostat entities."""
return make_custom_entity(
device=device,
device_address=device_address,
custom_entity_class=CeIpThermostat,
... | 46fc3ac8d19dbde4cac56392f67bef22df887f65 | 3,624,536 |
from typing import Iterable
def deepmap(func, obj):
"""Deep traverse obj, and apply func to each of its non-Iterable
elements"""
if isinstance(obj, Iterable):
return [deepmap(func, x) for x in obj]
else:
return func(obj) | 418d3342c86c422f5d4231030d66c03a08e89a9d | 3,624,537 |
def shufflenet_g1_wd4(**kwargs):
"""
ShuffleNet 0.25x (g=1) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
Devices,' https://arxiv.org/abs/1707.01083.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights f... | 929d1b2dd9ff0d8623b6be5bc9b3c352186bdc6a | 3,624,538 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.