content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 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 |
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 |
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 _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 |
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 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 |
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 |
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 |
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 |
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 |
def _get_inner_text(html_node):
"""Returns the plaintext of an HTML node.
This turns out to do exactly what we want:
- strips out <br>s and other markup
- replace <a> tags with just their text
- converts HTML entities like and smart quotes into their
unicode equivalents... | 36697baa3ad4bb8b2f33d37109dfbe8513517c13 | 3,635,600 |
def zern_normalisation(nmodes=30):
"""
Calculate normalisation vector.
This function calculates a **nmodes** element vector with normalisation constants for Zernike modes that have not already been normalised.
@param [in] nmodes Size of normalisation vector.
@see <http://research.opt.indiana.edu/Library/VSIA/VSI... | badd1d6f7ec185edcac42e4ec0cc8be748557fdf | 3,635,602 |
def sample_without_replacement(n, N, dtype=np.int64):
"""Returns uniform samples in [0, N-1] without replacement. It will use
Knuth sampling or rejection sampling depending on the parameters n and N.
.. note::
the values 0.6 and 100 are based on empirical tests of the
functions and would n... | d044e09a910f543adb754a6dacd661e985e5bf0f | 3,635,603 |
def bustypes(bus, gen):
"""Builds index lists of each type of bus (C{REF}, C{PV}, C{PQ}).
Generators with "out-of-service" status are treated as L{PQ} buses with
zero generation (regardless of C{Pg}/C{Qg} values in gen). Expects C{bus}
and C{gen} have been converted to use internal consecutive bus numb... | 41f3fd23c217e113f6395475a7920f27199d6dd9 | 3,635,604 |
from typing import Union
from typing import Mapping
from typing import Iterable
from typing import Tuple
from typing import Any
def update_and_return_dict(
dict_to_update: dict, update_values: Union[Mapping, Iterable[Tuple[Any, Any]]]
) -> dict:
"""Update a dictionary and return the ref to the dictionary that... | 8622f96a9d183c8ce5c7f260e97a4cb4420aecc7 | 3,635,605 |
def get_max_value_key(dic):
"""Gets the key for the maximum value in a dict."""
v = np.array(list(dic.values()))
k = np.array(list(dic.keys()))
maxima = np.where(v == np.max(v))[0]
if len(maxima) == 1:
return k[maxima[0]]
# In order to be consistent, always selects the minimum key
... | 56e9c6d54547b16a881bdb110187f36b9812c178 | 3,635,606 |
def main(event, context):
"""一个对时间序列进行线性插值的函数, 并且计算线性意义上的可信度。
"""
timeAxis = event["timeAxis"]
valueAxis = event["valueAxis"]
timeAxisNew = event["timeAxisNew"]
reliable_distance = event["reliable_distance"]
timeAxis = [totimestamp(parser.parse(i)) for i in timeAxis]
timeAxisNew = [... | a5c67afd9f7c9b197c4847394869c27ae145f0bf | 3,635,607 |
import xbmcaddon
def Addon_Info(id='',addon_id=''):
"""
Retrieve details about an add-on, lots of built-in values are available
such as path, version, name etc.
CODE: Addon_Setting(id, [addon_id])
AVAILABLE PARAMS:
(*) id - This is the name of the id you want to retrieve.
The list of buil... | 2fbdca3e5b4486c7fd702db3673433fe17dab4fe | 3,635,608 |
import hashlib
def _hash_string_to_color(string):
"""
Hash a string to color (using hashlib and not the built-in hash for consistency
between runs)
"""
return COLOR_ARRAY[
int(hashlib.sha1(string.encode("utf-8")).hexdigest(), 16) % len(COLOR_ARRAY)
] | 5539fba65f5d4c3cf245faea678f33d05c164aac | 3,635,609 |
def get_build(id):
"""Show metadata for a single build.
**Example request**
.. code-block:: http
GET /builds/1 HTTP/1.1
**Example response**
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 367
Content-Type: application/json
Date: Tue, 01 Mar 2016 17:21:2... | 3903188dad4236ec3675de893c1c7444fe8322a9 | 3,635,610 |
def get_unity_snapshotschedule_parameters():
"""This method provide parameters required for the ansible snapshot
schedule module on Unity"""
return dict(
name=dict(type='str'),
id=dict(type='str'),
type=dict(type='str', choices=['every_n_hours', 'every_day',
... | a25cb6c62a0a69f2586135677802309e033d86bc | 3,635,611 |
def gaussian_kernel(X, kernel_type="gaussian", sigma=3.0, k=5):
"""gaussian_kernel: Build an adjacency matrix for data using a Gaussian kernel
Args:
X (N x d np.ndarray): Input data
kernel_type: "gaussian" or "adaptive". Controls bandwidth
sigma (float): Scalar kernel bandwidth
k... | 6d541e5d1faa12d3b61aa1eb5dba416efb303253 | 3,635,613 |
def get_all_camera_shapes(full_path=True):
"""
Returns all cameras shapes available in the current scene
:param full_path: bool, Whether tor return full path to camera nodes or short ones
:return: list(str)
"""
return maya.cmds.ls(type='camera', long=full_path) or list() | 513207a51bce4ec74ff6bbb08357a0b0b975fffd | 3,635,614 |
def CreateVGGishNetwork(hop_size=0.96): # Hop size is in seconds.
"""Define VGGish model, load the checkpoint, and return a dictionary that points
to the different tensors defined by the model.
"""
vggish_slim.define_vggish_slim()
checkpoint_path = 'vggish_model.ckpt'
vggish_params.EXAMPLE_HOP_SECONDS = h... | dc7725524ede7b02fc9afdf63f8aeecde5c9c092 | 3,635,615 |
def estimate_mpk_parms_1d(
pk_pos_0, x, f,
pktype='pvoigt', bgtype='linear',
fwhm_guess=0.07, center_bnd=0.02
):
"""
Generate function-specific estimate for multi-peak parameters.
Parameters
----------
pk_pos_0 : TYPE
DESCRIPTION.
x : TYPE
DESCRIP... | d1d92548e4d3125bb1df9cea7f5037a262a5594c | 3,635,616 |
from typing import Tuple
from typing import Optional
import json
async def _parse_collection_from_search(
request: Request,
) -> Tuple[Optional[str], Optional[str]]:
"""
Parse the collection id from a search request.
The search endpoint is a bit of a special case. If it's a GET, the collection
an... | 52d392e13dce549905e357dc7a09b592e45d6c9e | 3,635,617 |
import itertools
def make_cnf_clauses_by_group(N_, board_group, varboard_group):
"""
:param board_group: e.g. a row of sudoku board, of shape (M...)
:param varboard_group: e.g. a row of sudoku variable id,
of shape (M..., N_)
"""
cclauses_local = []
board_group = board_group.reshape... | e3dc103a5a1674141780aed4d9af1e1d3eea0927 | 3,635,618 |
from typing import Tuple
def get_operations(
archive_action: str, archive_type: str, compression_type: str
) -> Tuple[Operation]:
"""
A function to fetch relevant operations based on type of archive
and compression if any.
"""
operations = {
"archive_ops": {
"zip": {
... | 39e03759f565a2969a3c50cbe5d314a131d498b4 | 3,635,619 |
def Norm(norm, *args, **kwargs):
"""
Return an arbitrary `~matplotlib.colors.Normalize` instance. Used to
interpret the `norm` and `norm_kw` arguments when passed to any plotting
method wrapped by `~proplot.axes.cmap_changer`. See
`this tutorial \
<https://matplotlib.org/tutorials/colors/colormapnor... | e3018d77dbd629a367c8cdfb10d13318e388ddd3 | 3,635,621 |
def run_trajectory(
model, time_stop, time_step, initial_state,
seed, n_points=500, docker=None):
"""
Run one trajectory using the given model and initial state
Parameters
----------
model: str
smoldyn model description
time_stop: float
Simulation duration
ti... | 38f497f93fdeb978de420d85fc910cd674c0faf4 | 3,635,622 |
from pathlib import Path
def get_project_root_dir() -> Path:
"""
Gets the Root path of Project
Returns:
Path: of Root project
"""
root_path = _get_script_file()
return root_path.parent | 30de0b9a91770e201cf921a56bb512a67e0dd486 | 3,635,623 |
from typing import Dict
def get_deployment_statuses() -> Dict[str, DeploymentStatusInfo]:
"""Returns a dictionary of deployment statuses.
A deployment's status is one of {UPDATING, UNHEALTHY, and HEALTHY}.
Example:
>>> from ray.serve.api import get_deployment_statuses
>>> statuses = get_deployme... | 00fc586f36256b2a73d1b78dff8d5af79b3f5e8e | 3,635,624 |
def dumps_tikz(g, scale='0.5em'):
"""Return TikZ code as `str` for `networkx` graph `g`."""
s = []
s.append(padding_remove(r"""
\begin{{tikzpicture}}[
signal flow,
pin distance=1pt,
label distance=-2pt,
x={scale}, y={scale},
baseline=(current bounding box.center),
]""").format(scale=scale))
... | 7bca58ded761992d455029055b167568414ef759 | 3,635,625 |
def drawModel(ax, model):
"""
将模型的分离超平面可视化
"""
x1 = np.linspace(ax.get_xlim()[0], ax.get_xlim()[1], 100)
x2 = np.linspace(ax.get_ylim()[0], ax.get_ylim()[1], 100)
X1, X2 = np.meshgrid(x1, x2)
Y = model.predict_proba(np.c_[X1.ravel(), X2.ravel()])[:, 1]
Y = Y.reshape(X1.shape)
ax.cont... | 4e4e464682c970ed90e0db8a06696891af51280a | 3,635,626 |
import warnings
def correct_mpl(obj):
"""
This procedure corrects MPL data:
1.) Throw out data before laser firing (heights < 0).
2.) Remove background signal.
3.) Afterpulse Correction - Subtraction of (afterpulse-darkcount).
NOTE: Currently the Darkcount in VAPS is being calculated as
... | 4d1da14d35e26dcd5ebc56fc333969e593ca02f8 | 3,635,628 |
def cutoff_depth(d: int):
"""A cutoff function that searches to depth d."""
return lambda game, state, depth: depth > d | af7396a92f1cd234263e8448a6d1d22b56f4a12c | 3,635,629 |
from typing import Dict
def create_contributor_node(d: Dict, label: str = "Contributor") -> Node:
""" Using the k, v pairs in `d`, create a Node object with those properties.
Takes k, as-is except for 'uuid', which is cast to int.
Args:
d (dict): property k, v pairs
label (str): The py2neo... | bbb83ec8a8c76678c91ea8b009c9e137c03f025b | 3,635,630 |
def extractLipsHaarCascade(haarDetector, frame):
"""Function to extract lips from a frame"""
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
roi_gray = 0
faces = haarDetector.detectMultiScale(gray, 1.3, 5)
if len(faces) == 0:
roi_gray = cv2.resize(gray, (150, 100))
return roi_gray
... | f1d220df5af2dc2d6905aba05344ca04a96de8d5 | 3,635,631 |
def rgb_to_hex(red, green, blue):
"""Return color as #rrggbb for the given RGB color values."""
return '#%02x%02x%02x' % (int(red), int(green), int(blue)) | 7523bcb4b7a033655c9f5059fcf8d0ed656502c8 | 3,635,633 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.