content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import sys
def getVPCs(account="*", region="*", debug=False, save=False):
"""Retrieve all data on VPCs from an AWS account and optionally save
data on each to a file"""
print("Collecting VPC data...", file=sys.stderr)
vpclist = {}
for vpc in skew.scan("arn:aws:ec2:%s:%s:vpc/*" % (region, account)... | 4bf661c5dfa437930bb2deec7e93e20fcb4b9260 | 3,652,200 |
def get_cache_timeout():
"""Returns timeout according to COOLOFF_TIME."""
cache_timeout = None
cool_off = settings.AXES_COOLOFF_TIME
if cool_off:
if isinstance(cool_off, (int, float)):
cache_timeout = timedelta(hours=cool_off).total_seconds()
else:
cache_timeout =... | 4804576c2017aa51edb862e75a99e9e193eb3f20 | 3,652,201 |
def find_records(dataset, search_string):
"""Retrieve records filtered on search string.
Parameters:
dataset (list): dataset to be searched
search_string (str): query string
Returns:
list: filtered list of records
"""
records = [] # empty list (accumulator pattern)
for ... | c6cbd5c239f410a8658e62c1bbacc877eded5105 | 3,652,202 |
from pattern.en import parse, Sentence
def mood(sentence, **kwargs):
""" Returns IMPERATIVE (command), CONDITIONAL (possibility), SUBJUNCTIVE (wish) or INDICATIVE (fact).
"""
if isinstance(sentence, basestring):
try:
# A Sentence is expected but a string given.
# Attempt to... | 50d495e0a07a89c912288e93bf17a3d72cb78e87 | 3,652,203 |
def create_script(*args, **kwargs):
"""Similar to create_file() but will set permission to 777"""
mode = kwargs.pop("mode", 777)
path = create_file(*args, **kwargs)
path.chmod(mode)
return path | 24a907b8e8cdb51bd1a224283d98756985ea1030 | 3,652,204 |
import torch
def unique(x, dim=None):
"""Unique elements of x and indices of those unique elements
https://github.com/pytorch/pytorch/issues/36748#issuecomment-619514810
e.g.
unique(tensor([
[1, 2, 3],
[1, 2, 4],
[1, 2, 3],
[1, 2, 5]
]), dim=0)
=>
ten... | 8282e6a176b36f75baee8a9101d3cce49f41364d | 3,652,205 |
def _convert_arg(val, name, type, errmsg=None):
""" Convert a Python value in CPO and check its value
Args:
val: Value to convert
name: Argument name
type: Expected type
errmsg: Optional error message
"""
val = build_cpo_expr(val)
assert val.is_kind_of(type), errmsg ... | cf70cc4ec9247ee9941cb715f99180b34f5b378f | 3,652,206 |
import json
def into_json(struct):
"""
Transforms a named tuple into a json object in a nice way.
"""
return json.dumps(_compile(struct), indent=2) | 23470d184caff5540760782c8a1eee1589a61026 | 3,652,207 |
import random
def generate_integer_seeds(signature):
"""Generates a set of seeds. Each seed
is supposed to be included as a file for AFL.
**NOTE** that this method assumes that the signature
only have int types. If a non int type is found,
None is returned.
Param:
(str) signature: fu... | c058f730a6bd41d66ca64e3bfeffc5f4f65c2f60 | 3,652,208 |
from typing import Tuple
def adjust_time(hour: int, minute: int) -> Tuple[int, int]:
"""Adjust time from sunset using offset in config.
Returns:
Tuple[int, int]: (hour, minute) of the adjusted time
"""
today = pendulum.today().at(hour, minute)
today = today.add(hours=config.OFFSET_H, min... | bbd3b170976df934a541db91d728cb68420d0a4b | 3,652,209 |
import os
import random
def read_data_unet(path_images, path_masks, img_dims, norm, stretch, shuffle):
"""
load, crop and normalize image data
option to select images form a folder
:param image_path: path of the folder containing the images [string]
:param mask_path: path of the folder containing ... | 52cc287c3a1f11414a6393a4aaa91e979edfa7a6 | 3,652,210 |
from functools import reduce
def flatten(l):
"""Flatten 2 list
"""
return reduce(lambda x, y: list(x) + list(y), l, []) | 85b4fad4ef0326304c1ee44714d8132841d13b16 | 3,652,211 |
def _rep_t_s(byte4):
"""
合成置换T', 由非线性变换和线性变换L'复合而成
"""
# 非线性变换
b_array = _non_linear_map(_byte_unpack(byte4))
# 线性变换L'
return _linear_map_s(_byte_pack(b_array)) | d82db42a848cdc84ba042b61a2825113feab5078 | 3,652,212 |
def get_mapping():
"""
Returns a dictionary with the mapping of Spacy dependency labels to a numeric value, spacy dependency annotations
can be found here https://spacy.io/api/annotation
:return: dictionary
"""
keys = ['acl', 'acomp', 'advcl', 'advmod', 'agent', 'amod', 'appos', 'attr', 'aux', '... | 164d2292bdd573a5805f9a66f685d21aac92061e | 3,652,213 |
def create_root_folder(path: str, name: str) -> int:
"""
Creates a root folder if folder not in database.
Fetches id if folder already in database.
Handles paths with both slash and backslash as separator.
:param path: The path to the folder in the users file system.
:param name: The name of th... | 54ab207501490b7f154111d6091e9a04b59603c9 | 3,652,214 |
import logging
def get_document_term_matrix(all_documents):
""" Counts word occurrences by document. Then transform it into a
document-term matrix (dtm).
Returns a Tf-idf matrix, first count word occurrences by document.
This is transformed into a document-term matrix (dtm). This is also
just cal... | b43cd43d68f48c0296a37668c5f48375ac7e38df | 3,652,215 |
def f_raw2(coordinate, packedParams):
"""
The raw function call, performs no checks on valid parameters..
:return:
"""
gaussParams = packedParams['pack']
res = 0
for p in gaussParams:
res += gaussian_2d.f_noravel(coordinate, *p)
return res | 2071e4d6c227975b308ea717658d0bf1af567fca | 3,652,216 |
def example_serving_input_fn():
"""Build the serving inputs."""
example_bytestring = tf.placeholder(
shape=[None],
dtype=tf.string,
)
features = tf.parse_example(
example_bytestring,
tf.feature_column.make_parse_example_spec(INPUT_COLUMNS))
return tf.estimator.export.ServingI... | d94f7add7ba7a549263a85ef4d21cd78bae298ca | 3,652,217 |
def add_file_uri_to_path(filepath):
"""Add the file uri preix: "file://" to the beginning of a path"""
if not filepath:
return False, "The filepath must be specified"
if filepath.lower().startswith(FILE_URI_PREFIX):
#
#
return True, filepath
updated_fpath = '%s%s' % (FI... | dc0640f6101b92a8623e360ac6782b3b23b6e45d | 3,652,218 |
def np_slope_diff_spacing(z, xspace, yspace):
"""
https://github.com/UP-RS-ESP/TopoMetricUncertainty/blob/master/uncertainty.py
Provides slope in degrees.
"""
dy, dx = np.gradient(z, xspace, yspace)
return np.arctan(np.sqrt(dx*dx+dy*dy))*180/np.pi | 45527de535339a4cae17694dbf5313fb57a02bef | 3,652,219 |
import torch
def build_dist(
cfg, feat_1, feat_2=None, dist_m=None, verbose=False,
):
"""Computes distance.
Args:
input1 (torch.Tensor): 2-D feature matrix.
input2 (torch.Tensor): 2-D feature matrix. (optional)
Returns:
numpy.ndarray: distance matrix.
"""
if dist_m i... | 2022386bf74939f9eb7039af8d67f718121062a0 | 3,652,220 |
def call_inverse_cic_single_omp(img_in,yc1,yc2,yi1,yi2,dsi):
"""
Input:
img_in: Magnification Map
yc1, yc2: Lens position
yi1, yi2: Source position
dsi: pixel size on grid
"""
ny1,ny2 = np.shape(img_in)
img_in = np.array(img_in,dtype=ct.c_float)
yi1 = np.array(yi1... | 286c650117e9c3df17bc081e3d9ddbe47755e010 | 3,652,221 |
def filter_spans(spans):
"""Filter a sequence of spans and remove duplicates or overlaps. Useful for
creating named entities (where one token can only be part of one entity) or
when merging spans with `Retokenizer.merge`. When spans overlap, the (first)
longest span is preferred over shorter spans.
... | 3b15a79b14f02ffa870b94eb9b61261c4befc0eb | 3,652,222 |
def get_col_names_for_tick(tick='BCHARTS/BITSTAMPUSD'):
"""
Return the columns available for the tick. Startdate is late by default to avoid getting much data
"""
return quandl.get(tick, start_date=None).columns | d80ae9b93b4bb817306f8ade404a083126507802 | 3,652,223 |
import os
def check_if_needs_inversion(tomodir):
"""check of we need to run CRTomo in a given tomodir
Parameters
----------
tomodir : str
Tomodir to check
Returns
-------
needs_inversion : bool
True if not finished yet
"""
required_files = (
'grid' + os.se... | 8ba837eb2295f7cc3a5698e2877a310f17b805c5 | 3,652,224 |
def check_result(request):
"""
通过任务id查询任务结果
:param request:
:param task_id:
:return:
"""
task_id = request.data.get('task_id')
if task_id is None:
return Response({'message': '缺少task_id'}, status=status.HTTP_400_BAD_REQUEST)
res = AsyncResult(task_id)
if res.ready(): # 检... | b43001fb598188f030a58166ab445a919b9b1d4e | 3,652,225 |
def get_debug_device():
"""Get the profile to debug from the RIVALCFG_DEVICE environment variable,
if any.
This device should be selected as the one where the commands will be
written, regardless of the selected profile. This is usefull to debug a
mouse that have the same command set than an other ... | 82e4fce316568df89537d41691f475ef58b5a8a1 | 3,652,226 |
from typing import Tuple
def _remove_node(node: int, meta: IntArray, orig_dest: IntArray) -> Tuple[int, int]:
"""
Parameters
----------
node : int
ID of the node to remove
meta : ndarray
Array with rows containing node, count, and address where
address is used to find the f... | 1112fc1907e3668f5c2d559d78ee1deba8583754 | 3,652,227 |
def forward_many_to_many_without_pr(request):
"""
Return all the stores with associated books, without using prefetch_related.
100ms overall
8ms on queries
11 queries
1 query to fetch all stores:
SELECT "bookstore_store"."id",
"bookstore_store"."name"
FROM "bookstore_store"... | c67e3af971c67e37f4221147518a054ee49f19a2 | 3,652,228 |
import itertools
def generate_combinations (n, rlist):
""" from n choose r elements """
combs = [list(itertools.combinations(n, r)) for r in rlist]
combs = [item for sublist in combs for item in sublist]
return combs | 7339b61a7ea76813c8356cf4a87b1e81b67ce10e | 3,652,229 |
import six
import traceback
def conv_datetime(dt, version=2):
"""Converts dt to string like
version 1 = 2014:12:15-00:00:00
version 2 = 2014/12/15 00:00:00
version 3 = 2014/12/15 00:00:00
"""
try:
if isinstance(dt, six.string_types):
if _HAS_PANDAS:
dt = pd.... | 19999cd2517832e06949fbb0939d3b622605d047 | 3,652,230 |
def get_description_value(name_of_file):
"""
:param name_of_file: Source file for function.
:return: Description value for particular CVE.
"""
line = name_of_file.readline()
while 'value" :' not in line:
line = name_of_file.readline()
tmp_list = line.split(':')
if len(tmp_list) =... | a7b0915feff7fcd2a175bdb8fe9af48d0d9f14d7 | 3,652,231 |
def octaves(p, fs, density=False,
frequencies=NOMINAL_OCTAVE_CENTER_FREQUENCIES,
ref=REFERENCE_PRESSURE):
"""Calculate level per 1/1-octave in frequency domain using the FFT.
:param x: Instantaneous signal :math:`x(t)`.
:param fs: Sample frequency.
:param density: Power density ... | 98e1604e95bdcb72fa6d401fee020b973f1f19d4 | 3,652,232 |
def build_embed(**kwargs):
"""Creates a discord embed object."""
return create_embed(**kwargs) | b1a181de866cd78959c5b4bec8e14b30e8cd99d7 | 3,652,233 |
def VAMA(data, period=8, column='close'):
"""
Volume Adjusted Moving Average
:param pd.DataFrame data: pandas DataFrame with open, high, low, close data
:param int period: period used for indicator calculation
:param str column: column used for indicator calculation (default = "close")
:param p... | 5133aae3b33e0f8ef3298790a840dd3dcb6053ce | 3,652,234 |
def link_syscall(oldpath, newpath):
"""
http://linux.die.net/man/2/link
"""
# lock to prevent things from changing while we look this up...
filesystemmetadatalock.acquire(True)
# ... but always release it...
try:
trueoldpath = _get_absolute_path(oldpath)
# is the old path there?
if trueo... | ee2964262288f518aab830ae84f777a18044af0a | 3,652,235 |
def doc_vector(text, stop_words, model):
"""
计算文档向量,句子向量求平均
:param text: 需要计算的文档
:param stop_words: 停用词表
:param model: 词向量模型
:return: 文档向量
"""
sen_list = get_sentences(text)
sen_list = [x[1] for x in sen_list]
vector = np.zeros(100, )
length = len(sen_list)
for sentence i... | 73652ced2cd8a5fdf264d68be9b78969dfe2c78d | 3,652,236 |
def get_ether_pkt(src, dst, ethertype=ether.ETH_TYPE_IP):
"""Creates a Ether packet"""
return ethernet.ethernet(src=src, dst=dst, ethertype=ethertype) | 94c778e16f680e73a04591e3808fa5d07c8c5afa | 3,652,237 |
import inspect
def _resolve_dependency(param: inspect.Parameter, class_obj: Instantiable , app: App):
"""
Try to get the instance of a parameter from a bound custom resolver for the class which needs it.
if not able to do the above, try to get a registered binding for the parameter's Annotation.
... | 6bbe3f6fd74d037584ab96c761503a2b47cc901a | 3,652,238 |
import re
def parse_compute_hosts(compute_hosts):
""" Transform a coma-separated list of host names into a list.
:param compute_hosts: A coma-separated list of host names.
:type compute_hosts: str
:return: A list of host names.
:rtype: list(str)
"""
return filter(None, re.split('[^a-zA... | efbfe7b06290b90d044e89343bfd4ecf94733d9c | 3,652,239 |
def get_bbox(mask_frame):
"""
get rectangular bounding box for irregular roi
Args:
mask_frame (np.ndarray): the frame containing the mask
Returns:
bbox (np.ndarray): numpy array containing the indexes of the bounding box
"""
bbox = np.zeros(4)
bbox[0] = np.min(np.where(np.m... | e7cc63cc8b5dfa1e4d59b0696f6e9747e33f69bc | 3,652,240 |
def view_create_log_entry_verbose(request):
"""Create a new BehavioralLogEntry. Return the JSON version of the entry"""
return view_create_log_entry(request, is_verbose=True) | d461f9f9893756f8e45aa6578e6fb9625957b415 | 3,652,241 |
import json
import queue
import time
def webhook_server_factory(free_port):
"""For making a server that can accept Onshape webhooks."""
servers = []
threads = []
def _webhook_server_factory():
""" Create a factory to handle webhook notifications coming in.
:param on_recieved: functio... | 66a96cdf0226a2e164492d229bd50e675c7ac667 | 3,652,242 |
def generator_validator(file_path: Text):
"""
Validates that the generator module exists and has all the required
methods
"""
if not exists(file_path):
raise ArgumentTypeError(f"File {file_path} could not be found")
try:
module = import_file("generator", file_path)
except S... | 4a1f42198ad8421bcbb333d1bc5cfd1fc6ef0b3e | 3,652,243 |
from typing import Optional
from typing import List
import gzip
import google
def from_bytes(
data: bytes, idx_list: Optional[List[int]] = None, compression: Optional[str] = "gz"
) -> List[ProgramGraph]:
"""Deserialize Program Graphs from a byte array.
:param data: The serialized Program Graphs.
:pa... | 3d8e0291af3b283616eef06ac1e8161b248bb4e6 | 3,652,244 |
def runTimer(t):
"""t is timer time in milliseconds"""
blinkrow = 500 #in milliseconds
eachrow = t // 5
for i in range(5):
for _ in range(eachrow//(2*blinkrow)):
display.show(Image(hourglassImages[i+1]))
sleep(blinkrow)
display.show(Image(hourglassImages[i]))... | b3d0fa8c5ac2c179b206a1679e9951e91d9c8b44 | 3,652,245 |
import math
def ascMoveFormula(note_distance, finger_distance, n1, n2, f1, f2):
"""This is for situations where direction of notes and fingers are opposite,
because either way, you want to add the distance between the fingers.
"""
# The math.ceil part is so it really hits a value in our moveHash.
... | a9f4ef27f1a922eea1f9ec4a400d120e6b0c892b | 3,652,246 |
def create_stomp_connection(garden: Garden) -> Connection:
"""Create a stomp connection wrapper for a garden
Constructs a stomp connection wrapper from the garden's stomp connection parameters.
Will ignore subscribe_destination as the router shouldn't be subscribing to
anything.
Args:
gar... | 862d6a6862246a02b132313bbf9ab8f62d62a3be | 3,652,247 |
def W_n(S, n_vals, L_vals, J_vals):
""" Field-free energy. Includes extra correction terms.
-- atomic units --
"""
neff = n_vals - get_qd(S, n_vals, L_vals, J_vals)
energy = np.array([])
for i, n in enumerate(n_vals):
en = -0.5 * (neff[i]**-2.0 - 3.0 * alpha**2.0 / (4.0 * n**4.0) + ... | 2a4aa2ab0c6a7d935547ac18933d835848c45d5e | 3,652,248 |
def obter_movimento_manual(tab, peca): # tabuleiro x peca -> tuplo de posicoes
"""
Recebe uma peca e um tabuleiro e um movimento/posicao introduzidos
manualmente, dependendo na fase em que esta o programa.
Na fase de colocacao, recebe uma string com uma posicao.
Na fase de movimentacao, recebe uma ... | 2ac683c047a7852d56b228c11663007b9cdd7a33 | 3,652,249 |
import base64
def parse_header(req_header, taint_value):
"""
从header头中解析污点的位置
"""
header_raw = base64.b64decode(req_header).decode('utf-8').split('\n')
for header in header_raw:
_header_list = header.split(':')
_header_name = _header_list[0]
_header_value = ':'.join(_header... | f0ffdf7a823bd07e0648970a7d0791e44ad9c4a9 | 3,652,250 |
from typing import Union
from typing import List
from pathlib import Path
import os
def filter_and_sort_files(
fnames: Union[str, List[str]], return_matches: bool = False
):
"""Find all timestamped data files and sort them by their timestamps"""
if isinstance(fnames, (Path, str)):
fnames = os.list... | 4670a5a88d257accb42e9feda868be6c6935427f | 3,652,251 |
def fake_batch(obs_space, action_space, batch_size=1):
"""Create a fake SampleBatch compatible with Policy.learn_on_batch."""
samples = {
SampleBatch.CUR_OBS: fake_space_samples(obs_space, batch_size),
SampleBatch.ACTIONS: fake_space_samples(action_space, batch_size),
SampleBatch.REWARDS... | 1e71e17eecdabd8c95aa517564e494e303e10a4b | 3,652,252 |
import collections
def compute_macro_f1(answer_stats, prefix=''):
"""Computes F1, precision, recall for a list of answer scores.
This computes the *language-wise macro F1*. For minimal answers,
we also compute a partial match score that uses F1, which would be
included in this computation via `answer_stats`.... | 08c774b6a06230c298dcbf031d2e188a643df9ef | 3,652,253 |
def piecewise_linear(x, rng, NUM_PEOPLE):
"""
This function samples the piecewise linear viral_load model
Args:
x ([type]): [description]
rng (np.random.RandomState): random number generator
NUM_PEOPLE (int): [description]
Returns:
np.array: [description]
"""
vi... | 27c27c89769674d7fcf8008f21334ec12acd588c | 3,652,254 |
def mol_sim_matrix(fingerprints1,
fingerprints2,
method='cosine',
filename=None,
max_size=1000,
print_progress=True):
"""Create Matrix of all molecular similarities (based on molecular fingerprints).
If filename is n... | 43bd1fd26d3c4372d7285c8f93ad3a7e7e7d8a61 | 3,652,255 |
def energies_over_delta(syst, p, k_x):
"""Same as energy_operator(), but returns the
square-root of the eigenvalues"""
operator = energy_operator(syst, p, k_x)
return np.sqrt(np.linalg.eigvalsh(operator)) | b610ca896791d6036c1a5ed1295f3293408f898a | 3,652,256 |
def count_matching(d1: Die, d2: Die, num_rolls: int) -> int:
""" Roll the given dice a number of times and count when they match.
Args:
d1 (Die): One Die object (must not be None)
d2 (Die): Another Die object (must not be None)
num_rolls (int): Positive number of rolls to toss.
Ret... | f5e7f119ef639a910b7b824a3aabb47ce7bf1f60 | 3,652,257 |
def autoaugment_preproccess(
input_size,
scale_size,
normalize=None,
pre_transform=True,
**kwargs):
"""
Args:
input_size:
scale_size:
normalize:
pre_transform:
**kwargs:
Returns:
"""
if normalize is None:
nor... | de24dd19015ff8e4210f98ec5702fbf9ee637ebd | 3,652,258 |
def pubchem_image(cid_or_container, size=500):
"""
Generate HTML code for a PubChem molecular structure graphic and link.
Parameters:
cid_or_container: The CID (int, str) or a subscriptable object that
contains a key ``cid``.
Returns:
HTML code for an image from PubChem.
... | ca7f9fd9ad31bf834596460f047bf393e3cfd486 | 3,652,259 |
from typing import Optional
from typing import List
def to_lines(text: str, k: int) -> Optional[List[str]]:
"""
Given a block of text and a maximum line length k, split the text into lines of length at most k.
If this cannot be done, i.e. a word is longer than k, return None.
:param text: the block of... | 1797f45ce4999a29a9cc74def3f868e473c2775a | 3,652,260 |
def _image_pos(name):
"""
查找指定图片在背景图中的位置
"""
imsrc = ac.imread('images/bg/{}.png'.format(name[1:]))
imobj = ac.imread('images/{}.PNG'.format(name))
# find the match position
pos = ac.find_template(imsrc, imobj)
circle_center_pos = pos['result']
return circle_center_pos | 6d4bd64b252c2acbf86e22e8048150a3e1976045 | 3,652,261 |
from typing import Callable
from typing import Optional
import os
import logging
def handle_greenness_indices(parameters: tuple, input_folder: str, working_folder: str, msg_func: Callable, err_func: Callable) -> \
Optional[dict]:
"""Handle running the greenness algorithm
Argume... | 4e80f185ea9732c7a7556999db7a1d8c0f8e38fe | 3,652,262 |
def product_except_self(nums: list[int]) -> list[int]:
"""Computes the product of all the elements of given array at each index excluding the value at that index.
Note: could also take math.prod(nums) and divide out the num at each index,
but corner cases of num_zeros > 1 and num_zeros == 1 make code inele... | 15090d4873b0dec9ea6119e7c097ccda781e51fa | 3,652,263 |
import os
def fetch_pkey():
"""Download private key file from secure S3 bucket"""
s3_client = boto3.client('s3')
s3_client.download_file(S3_BUCKET, BUCKET_KEY, PKEY_FILE)
pkey_filename = PKEY_FILE.replace("/tmp/", "")
if os.path.isfile(PKEY_FILE):
return print(f"{pkey_filename} successfull... | 00fe81e359b5e464e292ef8a0b16a1515b45a66e | 3,652,264 |
import itertools
def so_mörk():
"""Sagnorð."""
return itertools.chain(
# Nafnháttur - nútíð er sleppt og ekki til í þáttíð miðmynd
{"sng---", "sng--þ", "snm---"},
# Boðháttur - alltaf 2.p og nútíð
string_product({"sb"}, MYND, {"2"}, TALA, {"n"}),
# Lýsingarháttur nútíða... | 07a5c79a78083392a5ce96cfb74c13d644a5585e | 3,652,265 |
def _histogram(values, value_range, nbins=100, dtype=tf.int32, name=None):
"""Return histogram of values.
Given the tensor `values`, this operation returns a rank 1 histogram counting
the number of entries in `values` that fell into every bin. The bins are
equal width and determined by the arguments `... | d15d1a8aac528c5641e391d56cb8141f07c244c5 | 3,652,266 |
def find_missing_letter(chars):
"""
chars: string of characters
return: missing letter between chars or after
"""
letters = [char for char in chars][0]
chars = [char.lower() for char in chars]
alphabet = [char for char in "abcdefghijklmnopqrstuvwxyz"]
starting_index = alphabet.index(chars[0])
for lett... | bc663b68ac49095285a24b06554337c1582c8199 | 3,652,267 |
def series_to_pyseries(
name: str,
values: "pl.Series",
) -> "PySeries":
"""
Construct a PySeries from a Polars Series.
"""
values.rename(name, in_place=True)
return values.inner() | 958e08e428948adbdf353b911b9e5ab814e06cdb | 3,652,268 |
def _stagefile(coption, source, destination, filesize, is_stagein, setup=None, **kwargs):
"""
Stage the file (stagein or stageout)
:return: destination file details (checksum, checksum_type) in case of success, throw exception in case of failure
:raise: PilotException in case of controlled e... | 725fb5d77489746a8ed0dd587a32bda669008456 | 3,652,269 |
def tally_cache_file(results_dir):
"""Return a fake tally cache file for testing."""
file = results_dir / 'tally.npz'
file.touch()
return file | 271c58cc263cf0bfba80f00b0831303326d4d1a8 | 3,652,270 |
import torch
def get_soft_label(cls_label, num_classes):
"""
compute soft label replace one-hot label
:param cls_label:ground truth class label
:param num_classes:mount of classes
:return:
"""
# def metrix_fun(a, b):
# torch.IntTensor(a)
# torch.IntTensor(b)
# metr... | e08e6fc86252bf76dd8a852c63e92776b4fdcfc3 | 3,652,271 |
def get_option(args, config, key, default=None):
"""Gets key option from args if it is provided, otherwise tries to get it from config"""
if hasattr(args, key) and getattr(args, key) is not None:
return getattr(args, key)
return config.get(key, default) | 54d77c6ae3e40b2739156b07747facc4a952c237 | 3,652,272 |
from operator import index
def z_decode(p):
"""
decode php param from string to python
p: bytes
"""
if p[0]==0x4e: #NULL 0x4e-'N'
return None,p[2:]
elif p[0]==0x62: #bool 0x62-'b'
if p[2] == 0x30: # 0x30-'0'
ret... | e4735532f783bdbcc76512ba414b296b743ebeb7 | 3,652,273 |
import re
def parse_extension(uri):
""" Parse the extension of URI. """
patt = re.compile(r'(\.\w+)')
return re.findall(patt, uri)[-1] | 5ed4eee77b92f04e62390128939113168d715342 | 3,652,274 |
import math
def rotz(ang):
"""
Calculate the transform for rotation around the Z-axis.
Arguments:
angle: Rotation angle in degrees.
Returns:
A 4x4 numpy array of float32 representing a homogeneous coordinates
matrix for rotation around the Z axis.
"""
rad = math.radia... | 4332242c5818ccc00d64cbebf7a861727e080964 | 3,652,275 |
def getBits(data, offset, bits=1):
"""
Get specified bits from integer
>>> bin(getBits(0b0011100,2))
'0b1'
>>> bin(getBits(0b0011100,0,4))
'0b1100'
"""
mask = ((1 << bits) - 1) << offset
return (data & mask) >> offset | 0bdae35f5afa076d0e5a73b91d2743d9cf156f7d | 3,652,276 |
def rescale(img, input_height, input_width):
"""Code from Loading_Pretrained_Models.ipynb - a Caffe2 tutorial"""
aspect = img.shape[1]/float(img.shape[0])
if(aspect>1):
# landscape orientation - wide image
res = int(aspect * input_height)
imgScaled = skimage.transform.resize(img, (in... | 6d6ac5cf1f496c9b7209e2b665e314c587471e82 | 3,652,277 |
def compute_halfmax_crossings(sig):
"""
Compute threshold_crossing, linearly interpolated.
Note this code assumes there is just one peak in the signal.
"""
half_max = np.max(sig)/2.0
fwhm_set = np.where(sig > half_max)
l_ndx = np.min(fwhm_set) #assumes a clean peak.
if l_ndx > 0:
... | 81347177aa442bf20ac56194127444ab5948a065 | 3,652,278 |
def quote_identities(expression):
"""
Rewrite sqlglot AST to ensure all identities are quoted.
Example:
>>> import sqlglot
>>> expression = sqlglot.parse_one("SELECT x.a AS a FROM db.x")
>>> quote_identities(expression).sql()
'SELECT "x"."a" AS "a" FROM "db"."x"'
Args:
... | 7689e883eb5360bee7e22c57b4e177be2f732e8b | 3,652,279 |
import struct
import zlib
def write_png(data, origin='upper', colormap=None):
"""
Transform an array of data into a PNG string.
This can be written to disk using binary I/O, or encoded using base64
for an inline PNG like this:
>>> png_str = write_png(array)
>>> 'data:image/png;base64,'+png_st... | 516c609bbe19974065a1dc32b34de80bab06c17e | 3,652,280 |
def prepare_url(url, source_url=None):
"""
Operations that purify a url, removes arguments,
redirects, and merges relatives with absolutes.
"""
try:
if source_url is not None:
source_domain = urlparse(source_url).netloc
proper_url = urljoin(source_url, url)
... | 867d3eb31a20893f6f5be4bd4f6a925f38d7c1a3 | 3,652,281 |
import re
def str_contains_num_version_range_with_x(str):
"""
Check if a string contains a range of number version with x.
:param str: the string to check.
:return: true if the string contains a a range of number version with x, false else.
"""
return bool(re.search(r'\d+((\.\d+)+)?(\.x)? < \d... | d11c34d1378b29df279da63882a9e34581fd9c13 | 3,652,282 |
import argparse
def get_args():
"""
gets cli args via the argparse module
"""
msg = "This script records cpu statistics"
# create an instance of parser from the argparse module
parser = argparse.ArgumentParser(description=msg)
# add expected arguments
parser.add_argument('-s', dest='si... | a97cdbf33710bac17d78581548970e85c2397e15 | 3,652,283 |
from typing import Callable
from typing import Coroutine
def mpc_coro_ignore(
func: Callable[..., Coroutine[SecureElement, None, SecureElement]]
) -> Callable[..., SecureElement]:
"""
A wrapper for an MPC coroutine that ensures that the behaviour of the code is unaffected by
the type annotations.
... | eefd690145067856709c4edf02958eba428a4313 | 3,652,284 |
def is_all_in_one(config):
"""
Returns True if packstack is running allinone setup, otherwise
returns False.
"""
# Even if some host have been excluded from installation, we must count
# with them when checking all-in-one. MariaDB host should however be
# omitted if we are not installing Mar... | 35bd2f2edf3f12575612edb27218509db769d68f | 3,652,285 |
def index():
"""
example action using the internationalization operator T and flash
rendered by views/default/index.html or views/generic.html
if you need a simple wiki simply replace the two lines below with:
return auth.wiki()
"""
response.title = 'Award management'
data = {"message":... | 6a0e910c793bf538f65826579a9ba6c9401bd4de | 3,652,286 |
import requests
import json
def session_generate(instanceAddress, appSecret): # pragma: no cover
"""
**Deprecated**
Issue a token to authenticate the user.
:param instanceAddress: Specify the misskey instance address.
:param appSecret: Specifies the secret key.
:type instanceAddress: str
... | 69e8b6cf54d92041326cc4f8d2dafa82a0f043a7 | 3,652,287 |
def _dream_proposals( currentVectors, history, dimensions, nChains, DEpairs, gamma, jitter, eps ):
"""
generates and returns proposal vectors given the current states
"""
sampleRange = history.ncombined_history
currentIndex = np.arange(sampleRange - nChains,sampleRange)[:, np.newaxis]
combi... | d72075d09589b77f7077a5785db9f77e6a4182b0 | 3,652,288 |
from typing import Optional
import os
import tempfile
import shutil
def handle_compressed_file(
file_prefix: FilePrefix,
datatypes_registry,
ext: str = "auto",
tmp_prefix: Optional[str] = "sniff_uncompress_",
tmp_dir: Optional[str] = None,
in_place: bool = False,
check_content: bool = True... | 980857aece095f894580b0d523dc10b4c94a6977 | 3,652,289 |
import copy
import json
def compress_r_params(r_params_dict):
"""
Convert a dictionary of r_paramsters to a compressed string format
Parameters
----------
r_params_dict: Dictionary
dictionary with parameters for weighting matrix. Proper fields
and formats depend on the... | 4e56badfb7ea773d9d1104b134aa61b83d8d2f2f | 3,652,290 |
def replace_ext(filename, oldext, newext):
"""Safely replaces a file extension new a new one"""
if filename.endswith(oldext):
return filename[:-len(oldext)] + newext
else:
raise Exception("file '%s' does not have extension '%s'" %
(filename, oldext)) | 33ab99860cfe90b72388635d5d958abe431fa45e | 3,652,291 |
def getAllArt():
"""
1/ verify if user is authenticated (login)
2/ if yes he can post a new article
if not he can only read article
"""
if request.method == "GET":
articles = actualArticle.getAll()
return articles
elif request.method == 'PUT':
if 'logged_in... | d7506d4fbe3b4f670c30ce18501fe6ea4d410169 | 3,652,292 |
from typing import Union
from typing import Tuple
import warnings
def normalize_citation(line: str) -> Union[Tuple[str, str], Tuple[None, str]]:
"""Normalize a citation string that might be a crazy URL from a publisher."""
warnings.warn("this function has been externalized to :func:`citation_url.parse`")
... | c004e75aae0bcb625d8906421057a484b6831606 | 3,652,293 |
import joblib
import os
def cnn_predict_grid(data_in=None,
win_sizes=[((int(8), int(5)), 2, 1),((int(10), int(6)), 3, 2),((int(13), int(8)), 4, 3)],
problim = 0.95,
model_fpath=model_fpath,
scaler_fpath=scaler_fpath,
nc_fpath='D:/Master/data/cmems_data/glo... | 4d29cea83917b32969d3e9b0b271e337508757b7 | 3,652,294 |
def connect_syndicate( username=CONFIG.SYNDICATE_OPENCLOUD_USER, password=CONFIG.SYNDICATE_OPENCLOUD_PASSWORD, user_pkey_pem=CONFIG.SYNDICATE_OPENCLOUD_PKEY ):
"""
Connect to the OpenCloud Syndicate SMI, using the OpenCloud user credentials.
"""
debug = True
if hasattr(CONFIG, "DEBUG"):
debu... | 61530129f45c89d6b735979dfa2fec347d364a06 | 3,652,295 |
def get_all_comb_pairs(M, b_monitor=False):
"""returns all possible combination pairs from M repeated measurements (M choose 2)
Args:
M (int): number of measurements per
Returns:
indices1, incides2
"""
indices1 = np.zeros(int(M*(M-1)/2))
indices2 = np.zeros(int(M*(M-1)/2... | 9b537d040463e6db2a0bd0616bc3110cf0c9e7f6 | 3,652,296 |
def gomc_sim_completed_properly(job, control_filename_str):
"""General check to see if the gomc simulation was completed properly."""
with job:
job_run_properly_bool = False
output_log_file = "out_{}.dat".format(control_filename_str)
if job.isfile(output_log_file):
# with ope... | 95c5b9dec8e38f5a06ad4031c72d14629ebdefe3 | 3,652,297 |
import functools
import time
def debounce(timeout, **kwargs):
"""Use:
@debounce(text=lambda t: t.id, ...)
def on_message(self, foo=..., bar=..., text=None, ...)"""
keys = sorted(kwargs.items())
def wrapper(f):
@functools.wraps(f)
def handler(self, *args, **kwargs):
# C... | ac457a68834f1a6305ff4be8f7f19607f17e95fb | 3,652,298 |
def isolated_add_event(event, quiet=True):
"""
Add an event object, but in its own transaction, not bound to an existing transaction scope
Returns a dict object of the event as was added to the system
:param event: event object
:param quiet: boolean indicating if false then exceptions on event add... | e2a20c21738c42dbed36d545b127131c13f98c59 | 3,652,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.