content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
def tokens_to_smiles(tokens: List[str], special_tokens: List[str] = BAD_TOKS) -> str:
"""Combine tokens into valid SMILES string, filtering out special tokens
Args:
tokens: Tokenized SMILES
special_tokens: Tokens to not count as atoms
Returns:
SMILES repres... | ac266d84808bd20cc80e4828372c1591bef63591 | 3,635,500 |
def _get_port_by_uuid(client, port_uuid, **params):
"""Return a neutron port by UUID.
:param client: A Neutron client object.
:param port_uuid: UUID of a Neutron port to query.
:param params: Additional parameters to pass to the neutron client
show_port method.
:returns: A dict describing t... | d6857d5c6902043a1baebf582024490e70a01bd3 | 3,635,501 |
def is_unit_by_year(text: str) -> bool:
"""
是否是以年为计量单位
@param text:
@return:
@rtype: bool
"""
log.info(f'invoke method -> is_unit_by_year(), time unit text: {text}')
try:
unit = DateUnit(text.strip())
except ValueError as e:
log.error(str(e))
return False
... | 7be058b4be02a07da0ae88f7414f58f7f0eba605 | 3,635,502 |
def merge_leading_dims(array_or_tensor, n_dims=2):
"""Merge the first dimensions of a tensor.
Args:
array_or_tensor: Tensor to have its first dimensions merged. Can also
be an array or numerical value, which will be converted to a tensor
for batch application, if needed.
n_dims: Number of d... | dcf80aaa00cad4b49ecdddbe137ce9d5d8fccec8 | 3,635,503 |
def ootf_inverse_HLG_BT2100_1(F_D, L_B=0, L_W=1000, gamma=None):
"""
Defines *Recommendation ITU-R BT.2100* *Reference HLG* inverse opto-optical
transfer function (OOTF / OOCF) as given in *ITU-R BT.2100-1*.
Parameters
----------
F_D : numeric or array_like
:math:`F_D` is the luminance ... | 419a7e2f21745849bc63a7491fc144b7714065a4 | 3,635,504 |
def get_categories_for_area(area_id):
"""
Return a list of rows from the category table that all contain the given area.
"""
return request_or_fail("/area/" + str(area_id) + "/category") | 4841d072d41eae51e4d943207935f79ca9e67b57 | 3,635,505 |
def iou(box1, box2, x1y1x2y2=True):
""" iou = intersection / union """
if x1y1x2y2:
# min and max of 2 boxes
mx = min(box1[0], box2[0])
Mx = max(box1[2], box2[2])
my = min(box1[1], box2[1])
My = max(box1[3], box2[3])
w1 = box1[2] - box1[0]
h1 = box1[3] -... | 6ad0d3d7dd3a3031d28f8a0b9d0075ecf9362792 | 3,635,506 |
def mock_get_data(mocker, remote_path):
"""Mock the get_data funcion of SegmentClient class.
Arguments:
mocker: The mocker fixture.
remote_path: The remote path of data.
Returns:
The patched mocker and response data.
"""
response_data = [RemoteData(remote_path=remote_path)... | 586493a65f6428ccbd2f904a87c9c39609cddec2 | 3,635,507 |
def gen_string(**kwargs) -> str:
"""
Generates the string to put in the secrets file.
"""
return f"""\
apiVersion: v1
kind: Secret
metadata:
name: keys
namespace: {kwargs['namespace']}
type: Opaque
data:
github_client_secret: {kwargs.get('github_client_secret')}
... | ed2702c171f20b9f036f07ec61e0a4d74424ba03 | 3,635,508 |
import random
def draw_one_group_members(applications, winners_num, set_just=True,
**kwargs):
"""internal function
decide win (waiting) or lose for each group
"""
target_status = \
kwargs['target_status'] if 'target_status' in kwargs else "pending"
win_status... | 02c3f0edefea004ad731df0eae7b6aedb95a5ad2 | 3,635,509 |
def get_props_from_row(row):
"""Return a dict of key/value pairs that are props, not links."""
return {k: v for k, v in row.iteritems() if "." not in k and v != ""} | a93dfbd1ef4dc87414492b7253b1ede4e4cc1888 | 3,635,510 |
def generate_url(resource, bucket_name, object_name, expire=3600):
"""Generate URL for bucket or object."""
client = resource.meta.client
url = client.generate_presigned_url(
"get_object",
Params={"Bucket": bucket_name, "Key": object_name},
ExpiresIn=expire,
)
return url | 8a74618d5cfcd39c8394577035b497ecb5835765 | 3,635,511 |
from typing import Iterable
from typing import List
def khal_list(
collection,
daterange: Iterable[str] = None,
conf: dict = None,
agenda_format=None,
day_format: str=None,
once=False,
notstarted: bool = False,
width: bool = False,
env=None,
datepoint=None,
):
"""returns a ... | e199512958b023456386891aab2e404320b324c9 | 3,635,512 |
from datetime import datetime
def get_current_time(tzinfo=timezone.utc):
"""Get current time."""
return datetime.utcnow().replace(tzinfo=tzinfo) | b77b32e1e11060dd3a5a68c7fba0b391d92f864d | 3,635,513 |
import math
def F7(x):
"""Easom function"""
s = -math.cos(x[0])*math.cos(x[1])*math.exp(-(x[0] - math.pi)**2 - (x[1]-math.pi)**2)
return s | a17060f046df9c02690e859e789b7ef2591d1a3c | 3,635,514 |
def get_local_real_format():
"""
Returns : char **rf,int *rflen
*args :
C prototype: int cbf_get_local_real_format (char ** real_format );
CBFLib documentation:
DESCRIPTION
cbf_get_local_integer_byte_order returns the byte order of integers
on the machine on which the API is being... | b35ad022544c1ec8614bed8b87cb1ce786fafa7e | 3,635,515 |
import torch
def zaxis_to_world(kpt: torch.Tensor):
"""Transform kpt from 2D+Z to 3D Real World Coordinates (RWC) for ITOP Dataset
Args:
kpt (np.ndarray): Array containing keypoints to transform
Returns:
np.ndarray: Converted keypoints
"""
tmp = kpt.clone()
tmp[..., 0] = (tm... | d925382c62d370a991fa2dfd4c51cb43d051423e | 3,635,516 |
from io import StringIO
def mock_response(req, resp_obj, resp_code):
""" Mock response for MyHTTPSHandler
"""
resp = urllib2.addinfourl(StringIO(resp_obj),
'This is a mocked URI!',
req.get_full_url())
resp.code = resp_code
resp.msg = "OK"
return resp | b786dae396b97cd7b67597496b0bb6204656c3f3 | 3,635,517 |
def http_login(request):
"""
Called after successfull basic HTTP authentication and check if user filled
his profile.
"""
logger.debug('Request full path: %s', request.get_full_path())
redirection = ""
# Should we redirect after login ?
if "next" in request.GET:
qr = request.GET... | 0232f22c4947e5588833f7ddcb993328e0fe5b2e | 3,635,518 |
def py_func_bernoulli(input):
"""
Binormial python function definition
"""
prob_array = sigmoid(np.array(input))
sample = np.random.binomial(1, prob_array)
return sample | 70d7583e07b062f74ea3fa8e7219e3dd1304dc9c | 3,635,519 |
def dist(subnetworks, node_id,
path_method='dijkstra',
inter_group=False, inter_group_dist=None, rep_dist=None):
"""
Parameters
----------
subnetworks (subg): LIST. List of sub-graphs for each sub-network.
node_id : INT. Source node ID for calculating in-group distances.
path_m... | dcea802ee2e996447f5ad9c4e87db6bf96bee522 | 3,635,520 |
def update_account():
"""
Update an account
"""
account = Account.query.filter(Account.id == session['user']['account']['id']).first()
for key, value in request.form.items():
setattr(account, key, value)
db_session.add(account)
db_session.commit()
session['user']['account... | 18ddf48079b04da6c2c8f96a306fdb5e06738839 | 3,635,521 |
import numpy
def quaternion_multiply(quaternion1, quaternion0):
"""Return multiplication of two quaternions.
>>> q = quaternion_multiply([1, -2, 3, 4], [-5, 6, 7, 8])
>>> numpy.allclose(q, [-44, -14, 48, 28])
True
"""
x0, y0, z0, w0 = quaternion0
x1, y1, z1, w1 = quaternion1
return n... | bcc6973f169840400c86b5eaf673deb75444a63f | 3,635,522 |
def triangulate_nviews(P, ip):
"""
Triangulate a point visible in n camera views.
P is a list of camera projection matrices.
ip is a list of homogenised image points. eg [ [x, y, 1], [x, y, 1] ], OR,
ip is a 2d array - shape nx3 - [ [x, y, 1], [x, y, 1] ]
len of ip must be the same as len of P
... | e9cdb99070ea5a4a2a1667237ee03b0f67b29018 | 3,635,523 |
import os
def get_require_files(path,require_file_list,regex=True,matched_part='xls',if_walk_path=True):
"""
检查某个路径是否包含必须的文档
:param path:路径
:param require_file_list: 要检查的文档/文件夹是否存在
:param regex : 是否需要用re去匹配
:return : 如果不存在,返回空字典,如果文档存在 返回需要文档的对应绝对路径字典
"""
if type(require_file_list) != ... | d180a64a509131c8300cba0390a07760fa31c2cf | 3,635,524 |
from typing import Dict
import re
def decompose_entry_to_dict_2107_Stavropol(entry:str)-> Dict:
"""
Выделяем данные из одной записи в dictionary
------------------------------------------------------------------------------------------------------
03.07.2021 12:52 -> Перевод с карты -> 3 500,00 -> 28 655... | 95ea242516619505fff9a8039c51097c20935235 | 3,635,525 |
import array
def _create_data_sources(data, index_sort="none"):
"""
Returns datasources for index and value based on the inputs. Assumes that
the index data is unsorted unless otherwise specified.
"""
# if not isinstance(data, ndarray) and (len(data) < 2):
# raise RuntimeError("Unable to ... | 9125afad2b1ad8ee350ae81b87ba3b9970e3e218 | 3,635,526 |
def discriminate(outputs, classes_to_detect):
"""Select which classes to detect from an output.
Get the dictionary associated with the outputs instances and modify
it according to the given classes to restrict the detection to them
Args:
outputs (dict):
instances (detectron2.struct... | a50be55dbdb546cb4857b87389fe94c5eb64b961 | 3,635,527 |
import requests
def request_get_with_timeout_retry(url: str, retries: int) -> Response:
"""
Makes a GET request, and retries if the server responds with a 504 (timeout)
Args:
url (str): The URL of the Mailgun API endpoint
retries (int): The number of times to retry the request
Return... | 41f85933d6a036d3ef2abf9f172eb6dd54871eba | 3,635,528 |
import talib
def SMA(value, day):
"""
返回简单移动平均序列。传入可以是列表或序列类型。传出是历史到当前周期为止的简单移动平均序列。
"""
# result = statistics.mean(value[-day:])
result = talib.SMA(value, day)
return result | 2ac504552d8a6b259c61cc53b0bb0c267535b1f5 | 3,635,529 |
def get_filtered_ecs_service_names(ecs_client, ecs_cluster_name, name_prefix):
"""Retrives the service names for the given cluster, using an optional regex
Keyword arguments:
ecs_client -- Autoscaling boto3 client (if None, will create one)
ecs_cluster_name -- the name of the cluster the service is in
... | a50f6c3af71af3893c4f313edd25b4a05e64433f | 3,635,530 |
def remove_zero_pairs(xy):
"""Returns new xy-pair Numpy array where x=y=0 pairs have been removed
Arguments:
xy(numpy array): input array
"""
mask = np.where((xy[:, __X] != 0.0) & (xy[:, __Y] != 0.0))[0]
return xy[mask, :] | f84a75af111f5371fb1b827cc8151ecb4d80558a | 3,635,531 |
def AddMEBTChopperPlatesAperturesToSNS_Lattice(accLattice,aprtNodes):
"""
Function will add two Aperture nodes at the entrance and exit of
MEBT chopper plates. It returns the list of Aperture nodes.
"""
x_size = 0.060
y_size = 0.018
shape = 3
node_pos_dict = accLattice.getNodePositionsDict()
node1 = accLattice... | 98a7809eb0d8f69f51f23eafe7ac2d10fa7fb89f | 3,635,532 |
import argparse
def build_parser():
"""Build argument parser."""
parse = argparse.ArgumentParser(description=("Use this script to generate new APBS input "
"files or split an existing parallel input "
"file into ... | 7e7ba1d7a2d818959b825b7044a9e03c2196e293 | 3,635,533 |
def find_adjective(sent):
"""Given a sentence, find the best candidate adjective."""
adj = None
for w, p in sent.pos_tags:
if p == 'JJ': # This is an adjective
adj = w
break
return adj | 1aabeafb1c73f1b0f2e128c8dd09f977efc99442 | 3,635,534 |
def tensor_index_by_number(data, number):
"""Tensor getitem by a Number which may be integer/float/bool value"""
number_type = const_utils.check_number_index_type(number)
if number_type == const_utils.BOOL_:
return tensor_index_by_bool(data, number)
if number_type == const_utils.INT_:
re... | 0b47eeb4d55a928a0a9525e58a682adf8f3decf8 | 3,635,535 |
from datetime import datetime
def _get_stop_as_datetime(event_json)->datetime:
"""Reads the stop timestamp of the event and returns it as a datetime
object.
Args:
event_json (json): The event encapsulated as json.
Returns
datetime: Timestamp of the stop of the event.
"""
name ... | 958915a568c66a04da3f44abecf0acca90181f43 | 3,635,536 |
def ascon_finalize(S, rate, a, key):
"""
Ascon finalization phase - internal helper function.
S: Ascon state, a list of 5 64-bit integers
rate: block size in bytes (8 for Ascon-128, Ascon-80pq; 16 for Ascon-128a)
a: number of initialization/finalization rounds for permutation
key: a bytes object... | 7a1115c0dfbc543e9e0cceb8fbac678e8bff4f55 | 3,635,537 |
def _click_command(
state: State,
path: str,
files: str,
batch: int,
runid_log: str = None,
wait: bool = False,
skip_existing: str = False,
simulate: bool = False,
):
"""Ingest files into OSDU."""
return ingest(state, path, files, batch, runid_log, wait, skip_existing, simulate) | 741dd7a7a39360ba69d55dda4f08848559f4e9d4 | 3,635,538 |
def datasheet_search_query(doctype, txt, searchfield, start, page_len, filters):
"""
:param doctype:
:param txt:
:param searchfield:
:param start:
:param page_len:
:param filters:
:return:
"""
db_name = frappe.conf.get("db_name")
sql = f"""
SELECT
`m`.`name`
, `m`.`title`
FROM `{db_name}`.tabDC_Doc_Datas... | 15eaf231adf54792ad6b678de702eb349ac6a219 | 3,635,539 |
def client():
"""Define client connection to server BaseManager
Returns: BaseManager object
"""
port, auth = get_auth()
mgr = BaseManager(address=('', port), authkey=auth)
mgr.register('set_event')
mgr.connect()
return mgr | 9a61d7b546a72eb0f5b5e91a7297715a773da516 | 3,635,540 |
def set_remote_sense(is_remote=False):
"""Docstring"""
built_packet = build_cmd(0x56, value=int(is_remote))
resp = send_recv_cmd(built_packet)
return resp | 3931c8b4935cb92712a892189a28fb36c68de973 | 3,635,541 |
def printImproperDihedral(dihedral, shift, molecule, alchemicalTransformation):
"""Generate improper dihedral line
Parameters
----------
dihedral : Angle Object
Angle Object
shift : int
Shift produced by structural dummy atoms
molecule : molecule object
Molecule object
... | 77c39e1b9884ba8dd5b940f62b3c4dc0c698b60a | 3,635,542 |
def mmd_est(x, y, c):
"""
Function for estimating the MMD between samples x and y using Gaussian RBF
with scale c.
Args:
x (np.ndarray): (n_samples, n_dims) samples from first distribution.
y (np.ndarray): (n_samples, n_dims) samples from second distribution.
Returns:
float: The mmd estimate."""
n_x = x.s... | b0de0f7725e6f5c3fa35096d2e9e48f52a341727 | 3,635,543 |
from typing import Dict
def contents_append_notable_sequence_event_types(sequence, asset_sequence_id) -> Dict:
"""Appends a dictionary of filtered data to the base list for the context
Args:
sequence: sequence object
asset_sequence_id: asset sequence ID
Returns:
A contents list w... | fca27e5242968fa0db3c9d450588d77e4b307d1e | 3,635,544 |
def get_tx_in_db(session: Session, tx_sig: str) -> bool:
"""Checks if the transaction signature already exists for Challenge Disburements"""
tx_sig_db_count = (
session.query(ChallengeDisbursement).filter(
ChallengeDisbursement.signature == tx_sig
)
).count()
exists = tx_sig_... | 51570741326bfa1393d1c885c8a43b80e25e422b | 3,635,545 |
def saturation_correlate(Ch_L, L_L):
"""
Returns the correlate of *saturation* :math:`S_L`.
Parameters
----------
Ch_L : numeric or array_like
Correlate of *chroma* :math:`Ch_L`.
L_L : numeric or array_like
Correlate of *Lightness* :math:`L_L`.
Returns
-------
numer... | 08b401caa24369a46c4f38b1c6006479c7b86421 | 3,635,546 |
def RHS(qmc_data):
"""
RHS(qmc_data)
-------------
We solve A x = b with a Krylov method. This function extracts
b from Sam's qmc_data structure by doing a transport sweep with
zero scattering term.
"""
G = qmc_data.G
Nx = qmc_data.Nx
Nv = Nx*G
zed = np.zeros((Nx,G))
... | c5300ad0c197eaf483d346a36f0957b8881b575f | 3,635,547 |
def parseThesaurus(eInfo):
"""Return thesaurus object
"""
assert (isinstance(eInfo, pd.Series))
try:
res = eInfo.apply(parseJsonDatum)
except:
# print "\nWarning: parseThesaurus(): blanks or non pd.Series"
res = eInfo.apply(lambda x: "" if x is None else x)
return ... | 736182fad6405fe01a0c31aec5286da99abeb90c | 3,635,548 |
import string
import random
def gen_pass(length=8, no_numerical=False, punctuation=False):
"""Generate a random password
Parameters
----------
length : int
The length of the password
no_numerical : bool, optional
If true the password will be generated without 0-9
punctuation : ... | dc0ca0c228be11a5264870112e28f27817d4bbc8 | 3,635,549 |
def document_version_title(context):
"""Document version title"""
return context.title | 1589a76e8bb4b4a42018783b7dbead9efc91e21a | 3,635,550 |
def get_validation_errors(schema, value, validate_invariants=True):
"""
Validate that *value* conforms to the schema interface *schema*.
This includes checking for any schema validation errors (using
`get_schema_validation_errors`). If that succeeds, and
*validate_invariants* is true, then we proce... | 857f2527ac3df8325154c78b79fd8bf2f4f535fb | 3,635,551 |
def kruskal_suboptimal_mst(graph):
""" Computes the MST of a given graph using Kruskal's algorithm.
Complexity: O(m*n) - it's dominated by determining if adding a new edge
creates a cycle which is O(n). This implementation does not use union-find.
This algorithm also works for directed graphs.
Di... | 2ff1f96618324deee59ff61f57dcdb4715442fbb | 3,635,552 |
def set_url_for_recrawl(db, url):
"""Set url for recrawl later"""
url_hash = urls.hash(url)
result = db['Urls'].find_one_and_update({'_id': url_hash},
{'$set': {'queued': False,
'visited': False}})
return... | 00f36e9a313c8dae07541bc016da56ce47f7ee45 | 3,635,553 |
def vertical(hfile):
"""Reads psipred output .ss2 file.
@param hfile psipred .ss2 file
@return secondary structure string.
"""
result = ''
for l in hfile:
if l.startswith('#'):
continue
if not l.strip():
continue
l_arr = l.strip().split()
... | c118b61be6edf29b42a37108c5fe21a0e62b801a | 3,635,554 |
from operations import run
def run(command, use_sudo=False, user='', group='', freturn=False, err_to_out=False, input=None, use_which=True, sumout='', sumerr='', status=0):
"""Dummy executing command on host via ssh or subprocess.
If use_which is not False, original run command will be executed with 'which' ... | cc6b7fb311993f91b4fa8a82fd6d87694922f432 | 3,635,555 |
def decide_play(lst):
"""
This function will return the boolean to control whether user should continue the game.
----------------------------------------------------------------------------
:param lst: (list) a list stores the input alphabet.
:return: (bool) if the input character is alphabet and if only one char... | 3062e1335eda572049b93a60a0981e905ff6ca0d | 3,635,556 |
def vocabfile_to_hashdict(vocabfile):
"""
A basic vocabulary hashing strategy just uses the line indices
of each vocabulary word to generate sequential hashes. Thus,
unique hashes are provided for each word in the vocabulary, and the
hash is trivially reversable for easy re-translati... | f26515fbb406897f4f348436a8776fd2b86ce5e4 | 3,635,557 |
def lnprior(theta, ref_time, fit_qm=False, prior_params=prior_params_default):
"""
Function to compute the value of ln(prior) for a given set of parameters.
We compute the prior using fixed definitions for the prior distributions
of the parameters, allowing some optional parameters for some of them... | 49c2befb75fa5b8e1fa678101ddddd0de6fe8fc2 | 3,635,558 |
from datetime import datetime
def doy_to_month(year, doy):
"""
Converts a three-digit string with the day of the year to a two-digit
string representing the month. Takes into account leap years.
:param year: four-digit year
:param doy: three-digit day of the year
:return: two-digit string... | b897c25e048dd5cd0e4d4371160d7ea7aa75cf90 | 3,635,559 |
def process_shot(top, full_prefix):
"""
Given the top directory and full prefix,
return essential info about the shot
Parameters
----------
top: string
directory place of the shot
full_prefix: string
shot description
returns: tuple
shot parameters
"""
... | 6e0daa7163e0971bbf87417fd0ee84c73a512b0e | 3,635,560 |
def open(filename, debug=False):
"""This function opens an existing object pool, returning a
:class:`PersistentObjectPool`.
Raises RuntimeError if the file cannot be opened or mapped.
:param filename: Filename must be an existing file containing an object
pool as created by :func:... | 491f9ceaffbe4aa4801afc26dd66aaa5f9d8d5c4 | 3,635,561 |
def dplnckqn(spectral, temperature):
"""Temperature derivative of Planck function in wavenumber domain for photon rate.
Args:
| spectral (scalar, np.array (N,) or (N,1)): wavenumber vector in [cm^-1]
| temperature (scalar, list[M], np.array (M,), (M,1) or (1,M)): Temperature in [K]
Ret... | c17b7340a09eb793c7b12af9ba27d00a74eaae1b | 3,635,562 |
def specificity(ground_true, predicted):
"""Computes the specificity.
Args:
ground_true ground_true (np.ndarray[bool]): ground true mask to be compared with predicted one.
predicted predicted (np.ndarray[bool]): predicted mask.
Should be the same dimension as `ground_true`.
Retu... | b0b40509fd663236b8e8ac13875e47c493921c02 | 3,635,563 |
from typing import Type
from typing import FrozenSet
def _get_node_feature_mapper(
node_feature_mapper_cls: Type[NodeFeatureMapper],
current_state: FrozenSet[Proposition],
problem: STRIPSProblem,
) -> NodeFeatureMapper:
"""
The node feature mappers need to be instantiated based on the current
... | 03ffeeda63a3333c3d795e3b3af2952108bac1f3 | 3,635,564 |
def curvInterp(curv,p1,p2,size):
"""
Args:
curv: 2D ndarray
N-by-2 matrix, N points
p1,p2: list or ndarray
length = 2, p1 left point, p2 right point
size: int
the size of new curv (number of points)
"""
if curv[0,0]>curv[-1,0]:
print("... | b66355d21fa0a4b0a511708283b86b6051df2e29 | 3,635,565 |
def create_key_pair(key_pair_name):
"""Create a new key pair with a provided name and story to a local file"""
pem_outfile = open(f"{key_pair_name}.pem", "w")
response = ec2.create_key_pair(KeyName=key_pair_name)
key_pair = str(response.key_material)
pem_outfile.write(key_pair)
print(f"Create Ke... | 430f54fa4d89d4dcb99c8ae0ddcbc459d1d1d4ee | 3,635,566 |
import hashlib
def chunk_hash( data ):
""" We need to hash data in a data stream chunk and store the hash in mongo. """
return hashlib.md5( data ).digest().encode('base64') | 4c60ef09f5db7e9868a5d44f4bfa1ae5baf81338 | 3,635,567 |
from kombu.abstract import Object as KombuDictType
from datetime import datetime
def jsonify(obj,
builtin_types=(int, float, string_t), key=None,
keyfilter=None,
unknown_type_filter=None):
"""Transforms object making it suitable for json serialization"""
_jsonify = partial(... | d9504d2fd8a110bb4a8c07220b131fbbefc31141 | 3,635,568 |
import struct
def pack(code, *args):
"""Original struct.pack with the decorator applied.
Will change the code according to the system's architecture.
"""
return struct.pack(code, *args) | 851e8db4d0e710edf2ea15503d92e76d352a2f05 | 3,635,569 |
from typing import Iterable
def find_faces(image: Image) -> Iterable[CropData]:
"""
Get a list of the location of each face found in an image.
"""
detector = cv2.CascadeClassifier(
str(
MODELS_DIR / "haarcascades" / "haarcascade_frontalface_default.xml"
)
)
grayscal... | 18d4d2dc588e15fa7ea620e5a31627a772e1466f | 3,635,570 |
import os
def getpath():
""" Generate filepath to the present file.
:return: filepath to the present file.
:rtype: str
"""
return os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) | 7feb3e0662a512231d6aa02afdb724555cb78ebb | 3,635,571 |
from typing import List
from sys import path
def connect_nodes(contents: List[str]) -> path.NODES:
"""Connect the nodes of the cave system by assigning input pairs.
Args:
contents (List[str]): the file contents
Returns:
path.NODES: a mapping of start to end in a path
"""
nodes: ... | 27d73090b689b7a12fab8188c770db4d2683b245 | 3,635,572 |
def create_clients(KEY, SECRET):
"""
Creates the necessary recources and clients
that will be used to create the redshift cluster
:return: ec2, iam, redshift clients and resources
"""
ec2 = boto3.resource(
'ec2',
region_name="us-west-2",
aws_access_key_id=K... | 12b8c58d60f3d2d1f3b4c65a6927118d8c97d974 | 3,635,573 |
import sys
def create_app() -> FastAPI:
"""Create and do initial configuration of fastapi app"""
db = Database()
try:
db.create_database()
except Exception: # pylint: disable=broad-except
sys.exit(1)
app_ = FastAPI()
# Add routers
# app_.include_router(project_controlle... | 4ee327a5638788fb4de74f10b7c3e3bb3038aa0e | 3,635,574 |
def _md_fix(text):
"""
sanitize text data that is to be displayed in a markdown code block
"""
return text.replace("```", "``[`][markdown parse fix]") | 2afcad61f4b29ae14c66e04c39413a9a94ae30f8 | 3,635,575 |
def nameOrIdentifier(token):
"""
Determine if the given object is a name or an identifier, and return the
textual value of that name or identifier.
@rtype: L{str}
"""
if isinstance(token, Identifier):
return token.get_name()
elif token.ttype == Name:
return token.value
e... | a7f92d40f3ec1401bbe46d2f0b11506114c10e36 | 3,635,576 |
def exact_kinematic_aug_diff_f(t, y, args_tuple):
"""
"""
_y, _, _ = y
_params, _key, diff_f = args_tuple
aug_diff_fn = lambda __y : diff_f(t, __y, (_params,))
_f, scales, translations = aug_diff_fn(_y)
trace = jnp.sum(scales)
return _f, trace, jnp.sum(scales**2) + jnp.sum(translations**... | aa5628cd21b1757a17a3e45480db13149a5367a7 | 3,635,577 |
def inverse_hybrid_transform(value):
"""
Transform back from the IRAF-style hybrid log values.
This takes the hybrid log value and transforms it back to the
actual value. That value is returned. Unlike the hybrid_transform
function, this works on single values not a numpy array. That is because
... | 2b8db45901c6f762c970937058670c5c4c5457ea | 3,635,578 |
def regress_trend_channel(arr):
"""
通过arr计算拟合曲线及上下拟合通道曲线,返回三条拟合曲线,组成拟合通道
:param arr: numpy array
:return: y_below, y_fit, y_above
"""
# 通过ABuRegUtil.regress_y计算拟合曲线和模型reg_mode,不使用缩放参数zoom
reg_mode, y_fit = ABuRegUtil.regress_y(arr, zoom=False)
reg_params = reg_mode.params
x = np.ara... | b0c78fac320e4df6f140858079218c1d410ba1e3 | 3,635,579 |
def answers(provider):
"""Default answers data for copier"""
answers = {}
answers["class_name"] = "TemplateTestCharm"
# Note "TestCharm" can't be used, that's the name of the deafult unit test class
answers["charm_type"] = provider
return answers | 9ae26b4eceab5a40d9b342dcb510d3e6843ee640 | 3,635,580 |
def encode(ds, is_implicit_vr, is_little_endian):
"""Encode a *pydicom* :class:`~pydicom.dataset.Dataset` `ds`.
Parameters
----------
ds : pydicom.dataset.Dataset
The dataset to encode
is_implicit_vr : bool
The element encoding scheme the dataset will be encoded with, ``True``
... | 966aa925eb57a7306ca7f37314938c180bb8d25b | 3,635,581 |
import os
def DetectGae():
"""Determine whether or not we're running on GAE.
This is based on:
https://developers.google.com/appengine/docs/python/#The_Environment
Returns:
True iff we're running on GAE.
"""
server_software = os.environ.get('SERVER_SOFTWARE', '')
return (server_software.startswi... | bcfbcbe3480269a0faca40d26d099fe0f9ff74fa | 3,635,582 |
from PIL import Image, ImageDraw, ImageFont, ImageChops
def set_static_assets(all_objects, log):
"""Save reloading the same thing over and over."""
new_objects = []
if len(all_objects) > 0:
try:
except ImportError:
log.import_error('Pillow')
for obj in all_objects:
... | a36a50df3d272d92dac7bbefa2e9c32de94b700b | 3,635,583 |
def get_side_effects_from_sider(meddra_all_se_file):
"""
Get the most frequent side effects from SIDER
"""
pubchem_to_umls = {}
umls_to_name = {}
with open(meddra_all_se_file, 'r') as med_fd:
for line in med_fd:
fields = line.strip().split('\t')
pubchem = str(int(... | 4fa012cd2a16e09f01d43ae66f99640f1e090e22 | 3,635,584 |
def beam_constraint_I_design_jac(samples):
"""
Jacobian with respect to the design variables
Desired behavior is when constraint is less than 0
"""
X,Y,E,R,w,t = samples
L = 100
grad = np.empty((samples.shape[1],2))
grad[:,0] = (L*(12*t*X + 6*w*Y))/(R*t**2*w**3)
grad[:,1] = (L*(6*t*... | 76553d7ab55221d5a0b52062f6aced8c3d316332 | 3,635,585 |
import os
def get_env_var(name, default_value = None):
"""Get the value of an environment variable, if defined"""
if name in os.environ:
return os.environ[name]
elif default_value is not None:
return default_value
else:
raise RuntimeError('Required environment variable %s not f... | 0f0455ede0e025c9da9fd65769a1d4e52ae520fc | 3,635,586 |
import logging
def check_usage_quota(vol_size_in_MB, tenant_uuid, datastore_url, privileges, vm_datastore_url):
""" Check if the volume can be created without violating the quota. """
if privileges:
error_msg, total_storage_used = get_total_storage_used(tenant_uuid, datastore_url, vm_datastore_url)
... | d02437b3096765f99f8a9e368456bd091489255b | 3,635,587 |
def _css_to_rect(css):
"""
Convert a tuple in (top, right, bottom, left) order to a dlib `rect` object
:param css: plain tuple representation of the rect in (top, right, bottom, left) order
:return: a dlib `rect` object
"""
return dlib.rectangle(css[2], css[1], css[0], css[3]) | 8b60c95d3a7fe965bc66f7ecb3ada4ec249925dd | 3,635,588 |
def parse_arguments():
""" Use arparse to parse the input arguments and return it as a argparse.ArgumentParser. """
ap = standard_parser()
add_annotations_arguments(ap)
add_task_arguments(ap)
return ap.parse_args() | aa6dd1031489ed492190d1e60e512d5b8465d6be | 3,635,589 |
from typing import Optional
from typing import Sequence
def get_alert_contacts(alert_contact_name: Optional[str] = None,
email: Optional[str] = None,
ids: Optional[Sequence[str]] = None,
name_regex: Optional[str] = None,
outpu... | e885d29e56b1403f5b879723247b4d7b28921710 | 3,635,590 |
def read_response(rfile, request_method, body_size_limit, include_body=True):
"""
Return an (httpversion, code, msg, headers, content) tuple.
By default, both response header and body are read.
If include_body=False is specified, content may be one of the
following:
- None, ... | af4eb7c8dcd1f7d0727fe0ae6d07e48b6dc3533c | 3,635,591 |
def epi_approx_tiramisu(image_shape: tuple, num_classes: int,
class_weights=None,
initial_filters: int=48,
growth_rate: int=16,
layer_sizes: list=[4, 5, 7, 10, 12],
bottleneck_size: int=15,
dropout: float=0.2,
learning_rate: float=1e-3,
momentum: float=0.75,
):
"""
Build a Tirami... | 455f31c0f9610db90646c409771dd91197421f64 | 3,635,592 |
def matrix_modinv(matrix, m):
"""Return inverse of the matrix modulo m"""
matrix_det = int(round(linalg.det(matrix)))
return modinv(abs(matrix_det), m)*linalg.inv(matrix)*matrix_det*sign(matrix_det) | 776e00f5d34a31d27f9af0dd065f0edde1449457 | 3,635,593 |
def hexStringToRGB(hex):
"""
Converts hex color string to RGB values
:param hex: color string in format: #rrggbb or rrggbb with 8-bit values in hexadecimal system
:return: tuple containing RGB color values (from 0.0 to 1.0 each)
"""
temp = hex
length = len(hex)
if temp[0] == "#":
... | 7adcb7b247e6fe1aefa1713d754c828d1ac4a5b0 | 3,635,594 |
def remove_element(list, remove):
"""[summary]
Args:
list ([list]): [List of objects]
remove ([]): [What element to remove]
Returns:
[list]: [A new list where the element has been removed]
"""
for object in list:
if object._id == remove[0]:
list.remove(o... | 65a9fe296a6d8369127003c33f58022ededfdcba | 3,635,595 |
def warmup_cosine_decay_schedule(
init_value: float,
peak_value: float,
warmup_steps: int,
decay_steps: int,
end_value: float = 0.0
) -> base.Schedule:
"""Linear warmup followed by cosine decay.
Args:
init_value: Initial value for the scalar to be annealed.
peak_value: Peak value for sc... | 5f6aeea25eff986711e0b7041f4ff18317b4c2b6 | 3,635,596 |
import uuid
def __transform_template_to_graph(j):
"""
Transforms the simple format to a graph.
:param j:
:return:
"""
g = nx.DiGraph()
for a in j["nodes"]:
g.add_node(a[0], label = a[1], id = str(uuid.uuid4()))
for e in j["edges"]:
g.add_edge(e[0], e[1], label = e[2])
... | 5c94b8114e2d5c6811abf12b83f1c5f4c24d3192 | 3,635,597 |
from datetime import datetime
def datetime_to_string(dt):
"""
Convert a datetime object to the preferred format for the shopify api. (2016-01-01T11:00:00-5:00)
:param dt: Datetime object to convert to timestamp.
:return: Timestamp string for the datetime object.
"""
if not dt:
return ... | 0bbda7c2be578245dc24d693b4a52ae69bd1ecf7 | 3,635,598 |
from typing import List
def names(package: str) -> List[str]:
"""List all plug-ins in one package"""
_import_all(package)
return sorted(_PLUGINS[package].keys(), key=lambda p: info(package, p).sort_value) | 545e9d1df93e902940a34bc5537063c4d6ceeb1f | 3,635,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.