content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def ordered_links(d, k0, k1):
"""
find ordered links starting from the link (k0, k1)
Parameters
==========
d : dict for the graph
k0, k1: adjacents nodes of the graphs
Examples
========
>>> from active_nodes import ordered_links
>>> d = {0:[1,4], 1:[0,2], 2:[1,3], 3:[2,4], 4:... | 472e9e7d459e8a574de8edd5272c96b648b50207 | 3,640,868 |
def _exceeded_threshold(number_of_retries: int, maximum_retries: int) -> bool:
"""Return True if the number of retries has been exceeded.
Args:
number_of_retries: The number of retry attempts made already.
maximum_retries: The maximum number of retry attempts to make.
Returns:
True... | c434e1e752856f9160d40e25ac20dde0583e50a6 | 3,640,869 |
import json
def _get_and_check_response(method, host, url, body=None, headers=None, files=None, data=None, timeout=30):
"""Wait for the HTTPS response and throw an exception if the return
status is not OK. Return either a dict based on the
HTTP response in JSON, or if the response is not in JSON format,
... | 559d85ee8f7d21445e5cfa0acc464b3e9ad98fe3 | 3,640,870 |
def moveb_m_human(agents, self_state, self_name, c, goal):
"""
This method implements the following block-stacking algorithm:
If there's a block that can be moved to its final position, then
do so and call move_blocks recursively. Otherwise, if there's a
block that needs to be moved and can be moved... | f99fd14b2091a1e8d0426dcef57ce33b96fc1352 | 3,640,871 |
import tkinter
def BooleanVar(default, callback=None):
"""
Return a new (initialized) `tkinter.BooleanVar`.
@param default the variable initial value
@param callback function to invoke whenever the variable changes its value
@return the created variable
"""
return _var(tkinter.BooleanVar,... | 451a43da5e9eb506fe8b928fa7f4e986c8da6b69 | 3,640,873 |
import re
def parse_header(source):
"""Copied from textgrid.parse_header"""
header = source.readline() # header junk
m = re.match('File type = "([\w ]+)"', header)
if m is None or not m.groups()[0].startswith('ooTextFile'):
raise ValueError('The file could not be parsed as a Praat text file a... | ff47296868f93cbe55d15b29a2245ceb14ed5460 | 3,640,874 |
from datetime import datetime
def create_amsterdam(*args):
"""
Creates a new droplet with sensible defaults
Usage:
[name]
Arguments:
name: (optional) name to give the droplet; if missing, current timestamp
"""
name = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S.%f")
... | ed01c67db180894bbcf2cdfee4cd2f45633cc637 | 3,640,875 |
def convert_inp(float_inp):
"""
Convert inp from decimal value (0.000, 0.333, 0.667, etc) to (0.0, 0.1, 0.2) for cleaner display.
:param float float_inp: inning pitching float value
:return:
"""
# Split inp into integer and decimal parts
i_inp, d_inp = divmod(float_inp, 1)
d_inp = d_in... | ce0e196ca570b02787842db3ec2efb6ac529685c | 3,640,876 |
def is_ipv4(line):
"""检查是否是IPv4"""
if line.find("ipv4") < 6: return False
return True | bd602f5a9ac74d2bd115fe85c90490556932e068 | 3,640,878 |
def format_ica_lat(ff_lat):
"""
conversão de uma latitude em graus para o formato GGMM.mmmH
@param ff_lat: latitude em graus
@return string no formato GGMM.mmmH
"""
# logger
# M_LOG.info(">> format_ica_lat")
# converte os graus para D/M/S
lf_deg, lf_min, lf_seg = deg2dms(ff_lat)
... | d1e6f111e70ec7bd532e3d14afe3c90dc99cb8f8 | 3,640,879 |
def loadData (x_file="ass1_data/linearX.csv", y_file="ass1_data/linearY.csv"):
"""
Loads the X, Y matrices.
Splits into training, validation and test sets
"""
X = np.genfromtxt(x_file)
Y = np.genfromtxt(y_file)
Z = [X, Y]
Z = np.c_[X.reshape(len(X), -1), Y.reshape(len(Y), -1)]
np.ra... | 18fb7269f2b853b089494e6021d765d76a148711 | 3,640,880 |
async def retrieve_users():
"""
Retrieve all users in collection
"""
users = []
async for user in user_collection.find():
users.append(user_parser(user))
return users | 914969f7beb75a9409e370b9e2453c681c37ff42 | 3,640,881 |
import hashlib
def get_file_hash(path):
"""파일 해쉬 구하기."""
hash = None
md5 = hashlib.md5()
with open(path, 'rb') as f:
data = f.read()
md5.update(data)
hash = md5.hexdigest()
info("get_file_hash from {}: {}".format(path, hash))
return hash | a024b0002c019ec9bae4fca40e68919c6236b2fa | 3,640,882 |
from nipy.labs.spatial_models.discrete_domain import \
def apply_repro_analysis(dataset, thresholds=[3.0], method = 'crfx'):
"""
perform the reproducibility analysis according to the
"""
grid_domain_from_binary_array
n_subj, dimx, dimy = dataset.shape
func = np.reshape(dataset,(n_s... | cffb667b80b0a049856dc7c11db6d81fd9521f49 | 3,640,883 |
def api_root(request):
"""
Logging root
"""
rtn = dict(
message="Hello, {}. You're at the logs api index.".format(request.user.username),
)
return Response(rtn) | b002724baefccdd0cd0dcc324fa23d9902186351 | 3,640,884 |
def load_data(filename: str):
"""
Load house prices dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (prices) - either as a single
DataFrame or a Tuple[DataFrame, Series]
"""
... | 412b197274ae4ca06e4cc7f9cd4b7d7b7c5934a0 | 3,640,885 |
def getcollength(a):
"""
Get the length of a matrix view object
"""
t=getType(a)
f={'mview_f':vsip_mgetcollength_f,
'mview_d':vsip_mgetcollength_d,
'mview_i':vsip_mgetcollength_i,
'mview_si':vsip_mgetcollength_si,
'mview_uc':vsip_mgetcollength_uc,
'cmview_... | fe4b4c69f1631c0e571cd1590aa8eeb8fa5bc7bb | 3,640,887 |
from unittest.mock import patch
def test_coinbase_query_balances(function_scope_coinbase):
"""Test that coinbase balance query works fine for the happy path"""
coinbase = function_scope_coinbase
def mock_coinbase_accounts(url, timeout): # pylint: disable=unused-argument
response = MockResponse(
... | d25d8d31ae5a7c22559c322edeed53404fc179ab | 3,640,888 |
def process_phase_boundary(fname):
"""
Processes the phase boundary file, computed mean and standard deviations
"""
singlets = []
chem_pot = []
temperatures = []
with h5.File(fname, 'r') as hfile:
for name in hfile.keys():
grp = hfile[name]
singlets.append(np.... | 4e7f01e3265566f03fa4e7e21f13cb48a1777c9c | 3,640,889 |
def blackman_window(shape, normalization=1):
"""
Create a 3d Blackman window based on shape.
:param shape: tuple, shape of the 3d window
:param normalization: value of the integral of the backman window
:return: the 3d Blackman window
"""
nbz, nby, nbx = shape
array_z = np.blackman(nbz)... | 45ae8132aad01319e1728f0a4355dda4d5d7d145 | 3,640,891 |
def asset_movements_from_dictlist(given_data, start_ts, end_ts):
""" Gets a list of dict asset movements, most probably read from the json files and
a time period. Returns it as a list of the AssetMovement tuples that are inside the time period
"""
returned_movements = list()
for movement in given_d... | b21355ad65c2603559ea00650d4ea6dd2a7d94f0 | 3,640,892 |
def update_work(work_id):
"""
Route permettant de modifier les données d'une collection
:param work_id: ID de l'oeuvre récupérée depuis la page oeuvre
:return: redirection ou template update-work.html
:rtype: template
"""
if request.method == "GET":
updateWork = Work.query.get(... | aed65c45d53fa9d7b551df6909fdece488f2ab65 | 3,640,893 |
def login_view(request):
"""Login user view"""
if request.method == 'POST':
email = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(request, username=email, password=password)
if user is not None:
login(request, user)
... | 702a3aa5a90cd5a5386a4fa3b74ab4b36d3748bb | 3,640,894 |
def mse(im1, im2):
"""Compute the Mean Squared Error.
Compute the Mean Squared Error between the two images, i.e. sum of the squared difference.
Args:
im1 (ndarray): First array.
im2 (ndarray): Second array.
Returns:
float: Mean Squared Error.
"""
im1 = np.asarray(im1)... | 3d14472d3eb211855b53174990c3201bbae49086 | 3,640,896 |
import torch
def bert_text_preparation(text, tokenizer):
"""Preparing the input for BERT
Takes a string argument and performs
pre-processing like adding special tokens,
tokenization, tokens to ids, and tokens to
segment ids. All tokens are mapped to seg-
ment id = 1.
Args:
... | f9b3de4062fd0cc554e51bd02c750daea0a8250c | 3,640,897 |
def possibly_equal(first, second):
"""Equality comparison that propagates uncertainty.
It represents uncertainty using its own function object."""
if first is possibly_equal or second is possibly_equal:
return possibly_equal #Propagate the possibilities
return first == second | 12662df45d6ee0c6e1aadb6a5c4c0ced9352af35 | 3,640,898 |
def get_logs():
"""
Endpoint used by Slack /logs command
"""
req = request.values
logger.info(f'Log request received: {req}')
if not can_view_logs(req['user_id']):
logger.info(f"{req['user_name']} attempted to view logs and was denied")
return make_response("You are not authoriz... | 9708515dbd70c6e817f21c474fa1e96a26a1e9b4 | 3,640,899 |
def list_volumes(vg):
"""List logical volumes paths for given volume group.
:param vg: volume group name
:returns: Return a logical volume list for given volume group
: Data format example
: ['volume-aaa', 'volume-bbb', 'volume-ccc']
"""
out, err = utils.execute('lvs', '--no... | 4cd613c8c10aaec443dce31cef8b132e3b2c65da | 3,640,900 |
def question_aligned_passage_embedding(question_lstm_outs, document_embeddings,
passage_aligned_embedding_dim):
"""create question aligned passage embedding.
Arguments:
- question_lstm_outs: The dimension of output of LSTM that process
... | 8dbcb298a24ec18da4904a8f48a7c63331b27c91 | 3,640,901 |
def lm_loss_fn(forward_fn, vocab_size, params, rng, data, is_training=True):
"""Compute the loss on data wrt params."""
logits = forward_fn(params, rng, data, is_training)
targets = hk.one_hot(data['target'], vocab_size)
assert logits.shape == targets.shape
mask = jnp.greater(data['obs'], 0)
loss = -jnp.su... | 44188d717759a82d80079b5e4f7309b3cf7b5cb0 | 3,640,902 |
def chroms_from_build(build):
""" Get list of chromosomes from a particular genome build
Args:
build str
Returns:
chrom_list list
"""
chroms = {'grch37': [str(i) for i in range(1, 23)],
'hg19': ['chr{}'.format(i) for i in range(1, 23)]
... | c87431911c07c00aaa63357771258394cfff859e | 3,640,904 |
def get_ready_count_string(room: str) -> str:
"""Returns a string representing how many players in a room are ready.
Args:
room (str): The room code of the players.
Returns:
str: A string representing how many players in a room are ready in the format '[ready]/[not ready]'.
"""
pla... | eb8ae2a308ccd58355de5a8a15629bfccd1fcc2c | 3,640,905 |
from typing import List
def switches(topology: 'Topology') -> List['Node']:
"""
@param topology:
@return:
"""
return filter_nodes(topology, type=DeviceType.SWITCH) | e489740b29f8aff7368147274d020cb467422669 | 3,640,906 |
def geometric_progression(init, ratio):
"""
Generate a geometric progression start form 'init' and multiplying
'ratio'.
"""
return _iterate(lambda x: x * ratio, init) | 6b2626bc9d4016518b1cc7e41b63d34924c1ee30 | 3,640,907 |
import urllib
def resolve(marathon_lb_url):
"""Return the individual URLs for all available Marathon-LB instances given
a single URL to a DNS-balanced Marathon-LB cluster.
Marathon-LB typically uses DNS for load balancing between instances and so
the address provided by the user may actually be multi... | f192d66a8a12d772ad33b2b8030796af2393ec16 | 3,640,908 |
def _parse_bluetooth_info(data):
"""
"""
# Combine the bytes as a char string and then strip off extra bytes.
name = ''.join(chr(i) for i in data[:16]).partition('\0')[0]
return BluetoothInfo(name,
''.join(chr(i) for i in data[16:28]),
''.join(chr(i)... | ef46576102cfb5d1df0b40e84529a89e2ed6bfa8 | 3,640,909 |
async def get_reverse_objects_topranked_for_lst(entities):
"""
get pairs that point to the given entity as the primary property
primary properties are those with the highest rank per property
"""
# run the query
res = await runQuerySingleKey(cacheReverseObjectTop, entities, """
SELECT ?ba... | d975ba3ac3a0983d3a08057c91cd96ca466708df | 3,640,910 |
def LU_razcep(A):
""" Vrne razcep A kot ``[L\\U]`` """
# eliminacija
for p, pivot_vrsta in enumerate(A[:-1]):
for i, vrsta in enumerate(A[p + 1:]):
if pivot_vrsta[p]:
m = vrsta[p] / pivot_vrsta[p]
vrsta[p:] = vrsta[p:] - pivot_vrsta[p:] * m
... | 79d6a00b4e16254739b987228fd506cae133907b | 3,640,911 |
def jni_request_identifiers_for_type(field_type, field_reference_name, field_name, object_name="request"):
"""
Generates jni code that defines C variable corresponding to field of java object
(dto or custom type). To be used in request message handlers.
:param field_type: type of the field to be initial... | 4f23ba559124b938fa82a044ae1adc0f16f4a7ad | 3,640,912 |
def _ValidateDuration(arg_internal_name, arg_value):
"""Validates an argument which should have a Duration value."""
try:
if isinstance(arg_value, basestring):
return TIMEOUT_PARSER(arg_value)
elif isinstance(arg_value, int):
return TIMEOUT_PARSER(str(arg_value))
except arg_parsers.ArgumentTyp... | b08b65831e04ece410be7f0a490cd6ebf7bcaa6f | 3,640,913 |
def get_jaccard_dist1(y_true, y_pred, smooth=default_smooth):
"""Helper to get Jaccard distance (for loss functions).
Note: This mirrors what others in the ML community have been using even for
non-binary vectors."""
return 1 - get_jaccard_index1(y_true, y_pred, smooth) | c64ba7fd81c3697bc472d372afeb940e19d35e3c | 3,640,914 |
from pathlib import Path
from typing import Dict
import json
import warnings
def deduplicate_obi_codes(fname: Path) -> None:
"""
Remove duplicate http://terminology.hl7.org/CodeSystem/v2-0203#OBI codes from an instance.
When using the Medizininformatik Initiative Profile LabObservation, SUSHI v2.1.1 inse... | 336a143e30224b64c39358137bab26e4013c5049 | 3,640,915 |
def fold_conv_bns(onnx_file: str) -> onnx.ModelProto:
"""
When a batch norm op is the only child operator of a conv op, this function
will fold the batch norm into the conv and return the processed graph
:param onnx_file: file path to ONNX model to process
:return: A loaded ONNX model with BatchNor... | 25c2748b0e964310cc9909b60e68a9740e3e0df1 | 3,640,916 |
def numdays(year, month):
"""
numdays returns the number of days in the given month of
the given year.
Args:
year
month
Returns:
ndays: number of days in month
"""
NDAYS = list([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31])
assert(year >= 0)
assert(1 <=... | 159a41f3706b087194e0ba5d107a1ceb88583c21 | 3,640,917 |
def normalise_diversity_year_df(y_div_df):
"""Normalises a dataframe with diversity information by year and parametre set"""
yearly_results_norm = []
# For each possible diversity metric it pivots over parametre sets
# and calculates the zscore for the series
for x in set(y_div_df["diversity_metric... | 83e12072e65a707dd61b98383ce295fac8e9f2f7 | 3,640,918 |
def allowed_file(filename):
"""Does filename have the right extension?"""
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS | f42ac5ef5470515258715b4552945206a440effb | 3,640,919 |
from typing import Dict
from typing import Optional
from typing import Any
from typing import List
import tokenize
def render(
template: str,
context: Dict,
serializer: Optional[CallableType[[Any], str]] = None,
partials: Optional[Dict] = None,
missing_variable_handler: Optional[CallableType[[str,... | b660c0ac97915121d061fd5c7dde8cccea42f03f | 3,640,920 |
def preprocess_observations(input_observation, prev_processed_observation, input_dimensions):
""" convert the 210x160x3 uint8 frame into a 6400 float vector """
processed_observation = input_observation[35:195] # crop
processed_observation = downsample(processed_observation)
processed_observation = remo... | 885fbb2a1f81200843bb15d37f3c13726c23ea90 | 3,640,921 |
def expand_configuration(configuration):
"""Fill up backups with defaults."""
for backup in configuration['backups']:
for field in _FIELDS:
if field not in backup or backup[field] is None:
if field not in configuration:
backup[field] = None
... | 218f5c5cb67d3fa0f52b453d3cd00cde40835025 | 3,640,922 |
def create_feature_extractor(input_shape: tuple, dropout:float=0.3, kernel_size:tuple=(3,3,3)) -> tf.keras.Sequential:
"""
Create feature extracting model
:param input_shape: shape of input Z, X, Y, channels
:return: feature extracting model
"""
model = Sequential()
model.add(Conv3D(filters... | 47f52bab452e6bf7c9875a3c9c85bed02b79fcdc | 3,640,923 |
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Set up the component."""
hass.data.setdefault(DOMAIN, {})
async_add_defaults(hass, config_entry)
router = KeeneticRouter(hass, config_entry)
await router.async_setup()
undo_listener = config_entry.add_updat... | beac0da52a530aa63495003b78a87638b869779c | 3,640,924 |
def OGH(p0, p1, v0, v1, t0, t1, t):
"""Optimized geometric Hermite curve."""
s = (t-t0)/(t1-t0)
a0 = (6*np.dot((p1-p0).T,v0)*np.dot(v1.T,v1) - 3*np.dot((p1-p0).T,v1)*np.dot(v0.T,v1)) / ((4*np.dot(v0.T,v0)*np.dot(v1.T,v1) - np.dot(v0.T,v1)*np.dot(v0.T,v1))*(t1-t0))
a1 = (3*np.dot((p1-p0).T,v0)*np.dot(v0.... | 8bf86bbb2105ec26586a3568bb1a6448b284fbec | 3,640,927 |
def permutation_test(v1, v2, iter=1000):
"""
Conduct Permutation test
Parameters
----------
v1 : array
Vector 1.
v2 : array
Vector 2.
iter : int. Default is 1000.
The times for iteration.
Returns
-------
p : float
The permutation test result, p-... | 3b618069b610d0ee37e8bcb32f814e34efaeebab | 3,640,928 |
def registered_paths():
"""Return paths added via registration
..note:: This returns a copy of the registered paths
and can therefore not be modified directly.
"""
return list(_registered_paths) | 4bd8471fc2bff1e09a84b1ae8878c0db5f7afd65 | 3,640,929 |
import torch
def nms_dynamic(ctx, g, boxes: Tensor, scores: Tensor,
max_output_boxes_per_class: int, iou_threshold: float,
score_threshold: float):
"""Rewrite symbolic function for default backend.
Support max_output_boxes_per_class, iou_threshold, score_threshold of
const... | 6b6eea9ce2f2fe84cabb85ddbb069732fa78cca9 | 3,640,930 |
from typing import Union
from datetime import datetime
import pytz
def api_timestamp_to_datetime(api_dt: Union[str, dict]):
"""Convertes the datetime string returned by the API to python datetime object"""
"""
Somehow this string is formatted with 7 digits for 'microsecond' resolution, so crop the last d... | 26f4828a19d17c883a8658eb594853158d70fbcf | 3,640,931 |
from typing import List
def calc_mutation(offsprings: List[List[List[int]]], mut_rate: float, genes_num: int) -> List[List[List[int]]]:
"""
Not necessary, however when provided and returns value other than None, the simulator is going to use
this one instead of the given ones by default, if you are not i... | d665b7c2ff8ddfa2c4b905c3d6bab02028e30ec2 | 3,640,932 |
def compute_targets(ex_rois, gt_rois, weights=(1.0, 1.0, 1.0, 1.0)):
"""Compute bounding-box regression targets for an image."""
return box_utils.bbox_transform_inv(ex_rois, gt_rois, weights).astype(
np.float32, copy=False
) | de2a65b5c3c44bbd4bffcd0d99143982ed4c031c | 3,640,933 |
def _args_filter(args):
"""
zenith db api only accept list of tuple arguments for bind execute, that is ungainly
so we should make all kind of arguments to list of tuple arguments
"""
if isinstance(args, (GeneratorType, )):
args = list(args)
if len(args) <= 0:
return []
if ... | af9a836c1389acc4e0faf0d08e47ef8a39e57345 | 3,640,934 |
def getAreaDF(spark):
"""
Returns a Spark DF containing the BLOCK geocodes and the Land and Water area columns
Parameters
==========
spark : SparkSession
Returns
=======
a Spark DF
Notes
=====
- Converts the AREALAND and AREAWATER columns from square meters to square miles... | 181e84e98ca2cf83be0cf5dbf41a8dbc46b88ad4 | 3,640,935 |
def how_many():
"""Check current number of issues waiting in SQS."""
if not is_request_valid(request):
abort(400)
lapdog_instance = Lapdog()
lapdog_instance.how_many()
return jsonify(
response_type="in_channel",
text="There are 4 issues waiting to be handled",
) | db132bed6c957ad1f922776165ccb999bfcedb32 | 3,640,937 |
import struct
def read_sbd(filepath):
"""Reads an .sbd file containing spectra in either profile or centroid mode
Returns:
list:List of spectra
"""
with open(filepath, 'rb') as in_file:
header = struct.unpack("<BQB", in_file.read(10))
meta_size = header[1] * 20... | 364499580d5531d7361b87d3f575bf006fc79791 | 3,640,938 |
def dct2(X, blksize):
"""Calculate DCT transform of a 2D array, X
In order for this work, we have to split X into blksize chunks"""
dctm = dct_mat(blksize)
#try:
#blks = [sp.vsplit(x, X.shape[1]/blksize) for x in sp.hsplit(X, X.shape[0]/blksize)]
#except:
# print "Some error occurred"
... | 79aa158f4fd05ac35bad2d16c14b3b8cbd8351af | 3,640,939 |
def print_filtering(dataset, filter_vec, threshold, meta_name):
"""Function to select the filtering_names(names of those batches or cell types with less proportion of cells than threshold),
and print an informative table with: batches/cell types, absolute_n_cells, relative_n_cells, Exluded or not.
"""
... | c637a9d219443de730156e546d52461b9bcdfc84 | 3,640,940 |
from typing import Dict
def get_chunk_tags(chunks: Dict, attrs: str):
"""
Get tags for
:param chunks:
:param attrs:
:return:
"""
tags = []
for chunk in chunks:
resource_type = chunk['resource_type']
original_url = chunk['url']
parse_result = urlparse(original_u... | e7076b345bcca4e7fe8ac96002aad7499cf0b0f3 | 3,640,942 |
def __discount_PF(i, n):
"""
Present worth factor
Factor: (P/F, i, N)
Formula: P = F(1+i)^N
:param i:
:param n:
:return:
Cash Flow:
F
|
|
--------------
|
P
"""
return (1 + i) ** (-n) | b6e7424647921b945a524a22d844925573b6490a | 3,640,943 |
def pw2dense(pw, maxd):
"""Make a pairwise distance matrix dense
assuming -1 is used to encode D = 0"""
pw = np.asarray(pw.todense())
pw[pw == 0] = maxd + 1
# pw[np.diag_indices_from(pw)] = 0
pw[pw == -1] = 0
return pw | 68bbf753d80032a0e697b161c8836283a030a54a | 3,640,944 |
from typing import Awaitable
def run_simulation(sim: td.Simulation) -> Awaitable[td.Simulation]:
"""Returns a simulation with simulation results
Only submits simulation if results not found locally or remotely.
First tries to load simulation results from disk.
Then it tries to load them from the ser... | 23524bff78ac326bbf74e2389180d924849e57f4 | 3,640,945 |
def get_cursor_position(fd=1):
"""Gets the current cursor position as an (x, y) tuple."""
csbi = get_console_screen_buffer_info(fd=fd)
coord = csbi.dwCursorPosition
return (coord.X, coord.Y) | b99cf19081af7e0d68523d1efdfc80c89cfe64cc | 3,640,946 |
from typing import Tuple
def _held_karp(dists: np.ndarray) -> Tuple[float, np.ndarray]:
"""
Held-Karp algorithm solves the Traveling Salesman Problem.
This algorithm uses dynamic programming with memoization.
Parameters
----------
dists
Distance matrix.
Returns
-------
T... | 982d771c1fef5e4f6311fd1b36216c95db7f1343 | 3,640,947 |
def NS(s,o):
"""
Nash Sutcliffe efficiency coefficient
Adapated to use in alarconpy by Albenis Pérez Alarcón
contact: apalarcon1991@gmail.com
Parameters
--------------------------
input:
s: simulated
o: observed
output:
ns: Nash Sutcliffe efficient ... | 10c14022ae634a74f0a417454ddfa0fa52d89c8a | 3,640,949 |
def UTArgs(v):
"""
tag UTArgs
"""
tag = SyntaxTag.TagUTArgs()
tag.AddV(v)
return tag | 8d9ff601a5a2bf65e68e074dad1894342881950f | 3,640,950 |
from src.praxxis.sqlite import sqlite_rulesengine
from src.praxxis.notebook.notebook import get_output_from_filename
def rules_check(rulesengine_db, filename, output_path, query_start, query_end):
"""check if any rules match"""
rulesets = sqlite_rulesengine.get_active_rulesets(rulesengine_db, query_start, qu... | a81d29a8a9d61ba6a577fbe9899967b81a25ff7f | 3,640,951 |
def shortstr(s,max_len=144,replace={'\n':';'}):
""" Obtain a shorter string """
s = str(s)
for k,v in replace.items():
s = s.replace(k,v)
if max_len>0 and len(s) > max_len:
s = s[:max_len-4]+' ...'
return s | 396794506583dcf39e74941a20f27ac63de325ec | 3,640,952 |
def update_gms_stats_collection(
self,
application: bool = None,
dns: bool = None,
drc: bool = None,
drops: bool = None,
dscp: bool = None,
flow: bool = None,
interface: bool = None,
jitter: bool = None,
port: bool = None,
shaper: bool = None,
top_talkers: bool = None,
... | d6dce80a8543cae16eebf076eeaa3e1428831df5 | 3,640,953 |
def _get_nearby_factories(latitude, longitude, radius):
"""Return nearby factories based on position and search range."""
# ref: https://stackoverflow.com/questions/574691/mysql-great-circle-distance-haversine-formula
distance = 6371 * ACos(
Cos(Radians(latitude)) * Cos(Radians("lat")) * Cos(Radian... | b94c879d93a486b4ac0dd77bee6fb9d79395dc23 | 3,640,954 |
def add_register(request):
"""
处理注册提交的数据,保存到数据库
:param request:
:return:
"""
form = forms.RegisterForm(request.POST)
if form.is_valid():
data = form.cleaned_data
#清洗数据
data.pop("re_password")
data['password'] = hash_pwd.has_password(data.get('password'))
#添加必要数据
data['is_active'] = 1
#格式化储存
model... | acaf3886773b599df2853a5e73ef504af27f1c53 | 3,640,955 |
import numpy
import pandas
def confidence_interval(data, alpha=0.1):
"""
Calculate the confidence interval for each column in a pandas dataframe.
@param data: A pandas dataframe with one or several columns.
@param alpha: The confidence level, by default the 90% confidence interval is calculated.
@... | f9c31549287723f7f75c265485b7cd9911f68168 | 3,640,956 |
def RunInTransactionOptions(options, function, *args, **kwargs):
"""Runs a function inside a datastore transaction.
Runs the user-provided function inside a full-featured, ACID datastore
transaction. Every Put, Get, and Delete call in the function is made within
the transaction. All entities involved in these ... | 9236024d034f193919e976a04eec9105ee899d48 | 3,640,957 |
def notify(message, key, target_object=None, url=None, filter_exclude={}):
"""
Notify subscribing users of a new event. Key can be any kind of string,
just make sure to reuse it where applicable! Object_id is some identifier
of an object, for instance if a user subscribes to a specific comment thread,
... | 9da7f8a498a3fad1f1acbb9e35e798083d6a25c5 | 3,640,958 |
from pathlib import Path
def get_project_root() -> Path:
"""Return the path of the project root folder.
Returns:
Path: Path to project root
"""
return Path(__file__).parent | 0122844ae89a53b0cd28659be21fb932164719cd | 3,640,959 |
def FTCS(Uo, diffX, diffY=None):
"""Return the numerical solution of dependent variable in the model eq.
This routine uses the explicit Forward Time/Central Space method
to obtain the solution of the 1D or 2D diffusion equation.
Call signature:
FTCS(Uo, diffX, diffY)
Parameters
------... | 4b02749f3f50a2cff74abb75146159289d42b99e | 3,640,960 |
def epicyclic_frequency(prof) -> Quantity:
"""Epicyclic frequency."""
Omega = prof['keplerian_frequency']
R = prof['radius']
return np.sqrt(2 * Omega / R * np.gradient(R ** 2 * Omega, R)) | 917fc1e094719f0dbb6a3ac7ca0396601060bf1c | 3,640,961 |
def get_groups(
a_graph,
method='component_infomap', return_form='membership'):
"""
Return the grouping of the provided graph object using the specified
method. The grouping is returned as a list of sets each holding all
members of a group.
Parameters
==========
a_graph: :cl... | 110dd9dc470d9426b388e0db1289ff0b23c4a963 | 3,640,963 |
def positional_rank_queues (service_platform,
api_key):
""" Get the queues that have positional ranks enabled.
References:
https://developer.riotgames.com/regional-endpoints.html
https://developer.riotgames.com/api-methods/#league-v4/GET_getQueuesWithPositionRanks
... | f48f9a445aac9611d4892e1aab5e7699a4c3ec1f | 3,640,964 |
def maplist(f, xs):
"""Implement `maplist` in pure Python."""
return list(map(f, xs)) | 894a58f9e2cd66fe9c327ea65433b8210051ed60 | 3,640,965 |
import string
import re
def pull_urls_excel_sheets(workbook):
"""
Pull URLs from cells in a given ExcelBook object.
"""
# Got an Excel workbook?
if (workbook is None):
return []
# Look through each cell.
all_cells = excel.pull_cells_workbook(workbook)
r = set()
for cell i... | 0359fb8e1fd552749e15cce631f756130c5199cf | 3,640,966 |
import click
import requests
def do_request(base_url, api_path, key, session_id, extra_params=''):
"""
Voer een aanvraag uit op de KNVB API, bijvoorbeeld /teams; hiermee
vraag je alle team-data op
"""
hashStr = md5.new('{0}#{1}#{2}'.format(key,
api_path,
... | 44217caa2c2cdf7543597405836cf0bb1ac650cd | 3,640,967 |
def write_code():
"""
Code that checks the existing path and snaviewpath
in the environmental viriables/PATH
"""
msg = """\n\n[Code]\n"""
msg += """function InstallVC90CRT(): Boolean;\n"""
msg += """begin\n"""
msg += """ Result := not DirExists('C:\WINDOWS\WinSxS\\x86_Microsoft.VC90... | 429eb64485a4fe240c1bebbfd2a2a89613b4fddd | 3,640,968 |
import re
def get_filenames(filename):
"""
Return list of unique file references within a passed file.
"""
try:
with open(filename, 'r', encoding='utf8') as file:
words = re.split("[\n\\, \-!?;'//]", file.read())
#files = filter(str.endswith(('csv', 'zip')), words)
files = set(filter(lam... | a1d8c396245cfc682ecc37edb3e673f87939b6fa | 3,640,969 |
def format_filename_gen(prefix, seq_len, tgt_len, bi_data, suffix,
src_lang,tgt_lang,uncased=False,):
"""docs."""
if not uncased:
uncased_str = ""
else:
uncased_str = "uncased."
if bi_data:
bi_data_str = "bi"
else:
bi_data_str = "uni"
file_name = "{}-{}_{}.seqlen-{}.tg... | 4a54c1fbfe371d628c1d7019c131b8fa6755f900 | 3,640,970 |
def is_holiday(date) -> bool:
"""
Return True or False for whether a date is a holiday
"""
name = penn_holidays.get(date)
if not name:
return False
name = name.replace(' (Observed)', '')
return name in holiday_names | edb68fa552f0f772b29b5d8a414758e63c252045 | 3,640,971 |
import re
def tokenize_text(text):
"""
Tokenizes a string.
:param text: String
:return: Tokens
"""
token = []
running_word = ""
for c in text:
if re.match(alphanumeric, c):
running_word += c
else:
if running_word != "":
token.appe... | b7f420d081d9cd658435ef623142a9d8ecf7b99b | 3,640,972 |
def generate_dummy_probe(elec_shapes='circle'):
"""
Generate a 3 columns 32 channels electrode.
Mainly used for testing and examples.
"""
if elec_shapes == 'circle':
electrode_shape_params = {'radius': 6}
elif elec_shapes == 'square':
electrode_shape_params = {'width': 7}
eli... | ea0f900390cf808cd8df3a38df9c47b99b77167b | 3,640,973 |
def try_decode(message):
"""Try to decode the message with each known message class; return
the first successful decode, or None."""
for c in MESSAGE_CLASSES:
try:
return c.decode(message)
except ValueError:
pass # The message was probably of a different type.
re... | 1dbbe5a6426b67690834673cd049535b018c0097 | 3,640,974 |
def build_where_clause(args: dict) -> str:
"""
This function transforms the relevant entries of dict into the where part of a SQL query
Args:
args: The arguments dict
Returns:
A string represents the where part of a SQL query
"""
args_dict = {
'source_ip': 'source_ip.va... | 3b85c92346be254646dd5208259cee317f6f9741 | 3,640,975 |
def matrix_scale(s):
"""Produce scaling transform matrix with uniform scale s in all 3 dimensions."""
M = matrix_ident()
M[0:3,0:3] = np.diag([ s, s, s ]).astype(np.float64)
return M | 22949a406865c18fe8200e43ea046ca6f16bdd6f | 3,640,976 |
from typing import List
def magnitude_datapoints(data: DataPoint) -> List:
"""
:param data:
:return:
"""
if data is None or len(data) == 0:
return []
input_data = np.array([i.sample for i in data])
data = norm(input_data, axis=1).tolist()
return data | b6c505f02042cfc34183a19cc0843b28e25dd6b2 | 3,640,977 |
def svn_stringbuf_from_aprfile(*args):
"""svn_stringbuf_from_aprfile(svn_stringbuf_t result, apr_file_t file, apr_pool_t pool) -> svn_error_t"""
return apply(_core.svn_stringbuf_from_aprfile, args) | d9faccd861d5382593988c1e2585207e0b5fa89f | 3,640,979 |
from pathlib import Path
def Arrow_Head_A (cls, elid = "SVG:Arrow_Head_A", design_size = 12, ref_x = None, stroke = "black", marker_height = 6, marker_width = 6, fill = "white", fill_opacity = 1, ** kw) :
"""Return a marker that is an arrow head with an A-Shape.
>>> mrk = Marker.Arrow_Head_A ()
>>> svg... | 661409c1ed37e33e9aea306b1c5b8d2a369bbaf2 | 3,640,980 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.