content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
import time
def analyze_top(directory):
"""Analyze output data from the linux 'top' command.
Args:
directory (str): full path to the measurement directory.
For example: 'md-20160406-095339-g0_500-n120000'
"""
# Extract date from directory name
subdir_name = os.path.basenam... | 151c6d6b4a0b5f13eaea5b16e33e03d77ac69acb | 3,622,300 |
def data_process(num=250):
"""
从数据集中获取实验评估数据,默认为250条,将数据加载到句子1和2对应的列表中并进行返回
:param num: 实验数据的条数,默认为250
:return: 句子1组成的集合,句子2组成的集合
"""
content = pd.read_csv(util.data_path(), sep='\n', header=None)
content = content.head(num)
sen1_list = []
sen2_list = []
print("开始处理实验数据")
fo... | d40640fabb01af9ac1a916313fb9ba5d1ae826c0 | 3,622,301 |
import gc
def sample_from_distance_matrix(dist_matrix, dist_mul=1, const_mul=8500, start=None, end=None, **kwargs):
"""Sample TSP qubo from given distance matrix and return lowest-energy sdolution.
This is basically the same as :py:func:`sample_from_locations` except it skips
calculation of distance matr... | bd68b425a694cb373980a5aae76889a02288100a | 3,622,302 |
import torch
def _add_embedding_layer(model_1, model_2):
"""
Returns an embedding layer with a weight matrix
of the follwing structure:
[MODEL_1 EMBEDDING MATRIX ; MODEL_2 EMBEDDING MATRIX]
"""
result_layer = torch.nn.Embedding(
model_1.num_embeddings, model_1.embedding_dim + model... | 2b4f4f3e36d56c57302cdcbf07c6cbbdb5165e11 | 3,622,303 |
def generate_key_lu_dict(
dict_tuple_keys,
unique_identifier,
enduses,
sectors,
technologies
):
"""Generate look_up keys to position in 'load_profiles'
Arguments
----------
dict_tuple_keys : dict
Already existing lu keys
unique_identifier : string... | adc2fd7357d16b3026ae7d0d8f363919b61f8525 | 3,622,304 |
from io import StringIO
def dumps(obj):
"""
Similar method to json dumps, prepending data with message length
header. Replaces pickle.dumps, so can be used in place without
the memory leaks on receiving side in pickle.loads (related to
memoization of data)
NOTE: Protocol is ignored when json ... | d5607df3e894fa9031da1cd0ce01ec18b5c441da | 3,622,305 |
from typing import Optional
from typing import Union
from typing import List
def load_tensor(name: Text) -> Optional[Union["tf.Tensor", List["tf.Tensor"]]]:
"""Load tensor or set it to None"""
tensor_list = tf.get_collection(name)
if not tensor_list:
return None
if len(tensor_list) == 1:
... | e0160ecd7126ea49325d86143bc03445f23312da | 3,622,306 |
def rdns_domain(network):
"""Transform :py:class:`netaddr.IPNetwork` object to rDNS zone name"""
if network.prefixlen == 0:
return "ip6.arpa" if network.version == 6 else "in-addr.arpa"
if network.version == 4:
return ".".join(map(str, reversed(
network.ip.words[:network.prefixle... | b94656f270d39ac175efb8bc8a99af0d29dad7df | 3,622,307 |
def make_dataset(dataset_type, path, args, **kwargs):
"""function to create datasets+tokenizers for common options"""
return get_dataset_by_type(dataset_type, path, args) | 220cbd2515fc359b6adcd7ff8420947abc301596 | 3,622,308 |
def to_undirected(graph):
"""Returns an undirected view of the graph `graph`.
Identical to graph.to_undirected(as_view=True)
Note that graph.to_undirected defaults to `as_view=False`
while this function always provides a view.
"""
return graph.to_undirected(as_view=True) | 96ceb4e2d7dbe2a9c120b8e1ac7cad0ef2b2c6ae | 3,622,309 |
import ctypes
import sys
def c_str(string : str) -> ctypes.c_char_p:
"""Create ctypes char * from a Python string."""
if sys.version_info[0] > 2:
py_str = lambda x: x.encode('utf-8')
else:
py_str = lambda x: x
return ctypes.c_char_p(py_str(string)) | e2c783d5d72eece66aef14245e2770bc8a43588b | 3,622,310 |
def CDLUNIQUE3RIVER(df):
"""
函数名:CDLUNIQUE3RIVER
名称:Unique 3 River 奇特三河床
简介:三日K线模式,下跌趋势中,第一日长阴线,第二日为锤头,最低价创新低,第三日开盘价低于第二日收盘价,收阳线,收盘价不高于第二日收盘价,预示着反转,第二日下影线越长可能性越大。
python API
integer=CDLUNIQUE3RIVER(open, high, low, close)
:return:
"""
open = df['open']
high = df['high']
low... | b85e213bb16ab902f9c48232ea50fe64e2b57dcd | 3,622,311 |
def single_leg_credit(trade):
"""Generate a message for a single leg credit trade."""
action = "closed" if trade['close_date'] else "opened"
trade_type = trade['type'].lower()
user = trade['User']['username']
strike = trade['short_put'] if "put" in trade_type else trade['short_call']
symbol = tr... | 8425e24e45fff6d694d593c39fa9277fa21da0e1 | 3,622,312 |
def remove_absolute_impute__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
""" Remove Absolute (impute)
xlabel = "Max fraction of features removed"
ylabel = "1 - ROC AUC"
transform = "one_minus"
sort_order = 9
"""
return __run_measure(measures.remove_mask, X, y, model_generator... | d3cfbac378c8811f9c22b1e433c6470dccca9ab8 | 3,622,313 |
def getText(rng):
"""
Get the pure text that is included in a js range
@param range js range to get the text of
@return string of the range's text
"""
return rng.toString() | 71c7c2eccb850ab1d807496d8033bb426b467492 | 3,622,314 |
def create_rain_array(rain_file, values):
"""Shuffles the rain distribution columns and creates an array of fractional values the same
length as the precip input. This can be passed to the chop_daily_to_hourly_precip function
Every 24 values should sum to ~1.0.
:param rain_file: path to .csv ppt distri... | 821911ff9f7b035f1eaec0a5083be0b7ed08ae60 | 3,622,315 |
def get_Xy_v6(filename='./data/train.csv'):
"""Data Encoding
Version 5
* same as version 4 except encode 3rd class as the number 4
* to better reflect the added difficultly of being in 3rd class
"""
def extract_title(x):
title = x.split(',')[1].split('.')[0].strip()
if title no... | bdc48e6ae796148282625a3da850ac147146da03 | 3,622,316 |
import os
import pathlib
def build_nmet2_nmet2shell_plot(metals, shape, num_shells,
show_ee=True, show=True, save=False,
pctx=False, pcty=False):
"""Plots number of metal2 in shell_i vs number of metal2 in NP
Args:
- metals (str): two metals... | 240803a252defe2a346cb9d16134828f388121d4 | 3,622,317 |
from datetime import datetime
def recordPrices(*args, **kwargs):
"""Records the prices today or tomorrow.
:param bool args[0]: If args[0] is True then get today's prices
:return True on success
"""
c = kwargs['Cursor']
servos = c.execute('Select servo_name,servo_id from servo;').fetc... | 14b5ad374cbab91a71be7038ced8dece151c4048 | 3,622,318 |
def _asarray1d(arr, copy=False):
"""Ensure 1D array for one array.
"""
if copy:
return asarray(arr).flatten()
else:
return asarray(arr).ravel() | b6f8bfc1ec2e411017f5da84d23674345f315dfb | 3,622,319 |
import argparse
from pathlib import Path
def parse_arguments():
""" A wrapper around the argparse code. """
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-c', '--criterion', action='store',
choices=['suffix', 'mime_name', 'mime_content'],
... | fb556a3a52c31d71b0fb2248465366aa624ad3c6 | 3,622,320 |
from typing import Iterable
import torch
def pssm1D(seq: Iterable, pssm=None, return_type='Array', **kwargs):
"""Obtain pssm given sequence."""
if pssm is None:
pssm = read_pssm(return_type=return_type, **kwargs)
pssm_values = [pssm[i, aa2index(aa)] for i, aa in enumerate(seq)]
return torch.t... | 76d6d12754a326bc0042c5434c7e786b34b74dfb | 3,622,321 |
def _chain_validator(*funcs):
"""Chain a series of validators."""
def chained(value):
for func in funcs:
value = func(value)
return value
return chained | 40082602f92a28160306bfff4d7b61703ea2e962 | 3,622,322 |
from typing import MutableMapping
from typing import Any
def remove_keys(
_dict: MutableMapping[str, Any] | None, keys: list[str]
) -> MutableMapping[str, Any]:
"""Remove keys from a dictionary."""
if not _dict:
return {}
new = dict(_dict)
for key in keys:
new.pop(key, None)
re... | 7a0ee8482eea69b0be7f7ecfd41355206adcf01c | 3,622,323 |
def delete_contact(id):
"""Removes contact by ID."""
contact = current_user.get_contact_or_404(id)
if contact.is_primary:
flash('Cannot delete primary contact.')
elif list(contact.attendance):
flash('Cannot delete contact involved in events.')
else:
with db.transaction as ses... | 314a2d449aa5ddbe78258bc5e7a9bc6a55af6f65 | 3,622,324 |
def concat_coords_maps(x: TENSOR_OR_SEQ_OF_TENSORS_T, channel_dim: int = 1) -> TENSOR_OR_SEQ_OF_TENSORS_T:
""" Concats N new features maps of euclidian coordinates (1D, 2D, ..., ND coordinates if `x` has N dimensions after `channel_dim`'s dimension) into given `x` tensor. Coordinates are concatenated at `channel_di... | 338035184e88fcd0baf65dc970e95a667c7b0713 | 3,622,325 |
from io import StringIO
def create_payload(data, kwargs):
"""
Creates a new ``PayloadBase`` instance with the given parameters.
Parameters
----------
data : (`list` of ``PayloadBase`` instances), ``BodyPartReader``, `bytes`, `bytearray`, `memoryview`, `str`, \
`BytesIO`, `StringIO... | c774e09907ddffc230ac62816978c87256c46ee1 | 3,622,326 |
def create_app():
"""Creates the Flask app object."""
app = Flask(__name__)
app.config.from_object(AppConfig)
api = Api(app)
configure_resources(api)
configure_extensions(app)
return app | 18fd00a52a777aa72a4f87d0338a794f5f9a6afd | 3,622,327 |
def ymdhms_format_from_tai(tai, sep="T", digits=None, suffix="",
buffer=None):
"""Date and time in ISO format 'yyyy-mm-ddThh:mm:ss....' given seconds TAI.
Works for both scalars and arrays.
Input:
tai number of elapsed seconds from TAI January 1, 2000.
sep... | 5dda1c30790290dd9388e9e8d466450f2739595a | 3,622,328 |
def _get_project_ids():
"""Return the GCE project IDs."""
return list(local_config.Config(local_config.GCE_CLUSTERS_PATH).get().keys()) | b3a94b5130a9f3915dceb820750c6711d6778f0e | 3,622,329 |
def drop_multiple_fha_numbers(df):
"""drops multiple fha_numbers by dropping issued data when a reissue is available in firm commitment activity"""
#create df of rows unique fha_numbers
unique_fha_list = df.fha_number.value_counts()[df.fha_number.value_counts() == 1]
def in_unique_list(x):
... | f884e6ef22221308783a3cbb235d5c17801ad80b | 3,622,330 |
from datetime import datetime
def create_accelerate_order() -> jsonify:
"""
生成刷票订单
:return:
"""
try:
data = loads(request.get_data().decode('utf-8'))
except ValueError:
return jsonify({'code': '2000', 'message': '服务器内部错误'})
# 防止重复下单
order_list = TicketOrder().query.fi... | 27f94a5449267b6243df1732f41ddd4d150edccd | 3,622,331 |
import json
def set_volume(intent, session_attributes):
""" set receiver volume (may be capped). """
card_title = intent['name']
should_end_session = not keep_baker_open(session_attributes)
# the value is "?" if it's given bogus input
slot = intent_slot(intent, 'volume_level')
volume_level =... | e9f351ca90709f55e86d44f0ac0b7e486bab2f71 | 3,622,332 |
def rect2ang(rect, zenith=False, axis=0):
"""The inverse of ang2rect."""
x,y,z = moveaxis(rect, axis, 0)
r = (x**2+y**2)**0.5
phi = np.arctan2(y,x)
if zenith: theta = np.arctan2(r,z)
else: theta = np.arctan2(z,r)
return moveaxis(np.array([phi,theta]), 0, axis) | 71c80a7295203d53ca5afe65959b79632aa633fe | 3,622,333 |
def mutate_single_base(base):
"""Takes single nucleic acid and changes it to a different nucleic acid."""
bases = "GATC"
idx = bases.index(base)
return choice(bases[:idx] + bases[idx + 1:]) | 04cfd6b33e02776485ffc64d4be1f016a23c859b | 3,622,334 |
def filterFileGroups(filegroups, fixedcols):
"""Filters out empty, duplicate and redundant rows, and empty columns,
from ``filegroups``
:arg filegroups: List of :class:`FileGroup` objects.
:arg fixedcols: List of ``(ftype, { var : value })`` mappings
:returns: A tuple containing the filtere... | 05bdcbc5ca3375913e426a5adc3365bed45f225a | 3,622,335 |
import os
import pickle
def authBuild(SCOPES, PATH=''):
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when t... | a9182a9bfd9b139f532deb11008cef87e5398030 | 3,622,336 |
from typing import Iterable
def filter_star_import(
line: bytes,
marked_star_import_undefined_name: Iterable[bytes],
) -> bytes:
"""Return line with the star import expanded."""
undefined_name = sorted(set(marked_star_import_undefined_name))
return Regex.STAR.sub(b", ".join(undefined_name), line) | 99eff31b5ba081a5683e7a3e7df216c25e62bb7a | 3,622,337 |
def zeros(shape, dtype, allocator=drv.mem_alloc, order="C"):
"""Returns an array of the given shape and dtype filled with 0's."""
result = GPUArray(shape, dtype, allocator, order=order)
zero = np.zeros((), dtype)
result.fill(zero)
return result | ef7e7668378cdd5b2321caaeb0038e6e5784414d | 3,622,338 |
def weighted_geometric_mean(values, weights):
"""
Returns the weighted geometric mean of values.
Args:
values (iterable):
weights (iterable):
Returns:
float:
"""
assert len(values) == len(weights)
return np.exp(sum([weights[i] * np.log(values[i]) for i in range(len... | f0d3eff6e5948685f16cc330e19b7650084c7dc8 | 3,622,339 |
from typing import Dict
def make_information_functions() -> Dict[str, ecole.typing.InformationFunction]:
"""Create the information function used in benchmarking the observation.
This is a combination of sloving features such as number of nodes, and the timing of
observation functions.
"""
informa... | 6de6cb6e40966a9e2f59f869d65a3e6fd47034c9 | 3,622,340 |
import struct
def read64(f):
"""Read 8 bytes from a file and return as an 64-bit unsigned int (little endian).
"""
return struct.unpack("<Q", f.read(8))[0] | 4a055188bd9db074ca3807771d779eccb25e5484 | 3,622,341 |
import math
def get_cosine_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, num_cycles=.5, last_epoch=-1):
""" Create a schedule with a learning rate that decreases following the
values of the cosine function between 0 and `pi * cycles` after a warmup
period during which it increases ... | 31eaef9f633ded9b4853bda76a3600e27f83ca28 | 3,622,342 |
def neighbor_weights(dist):
"""Return the weights of neighbors in time seires estimates.
Params
------
dist (np.ndarray): $M \times (N+1)$ array of Euclidean distances between a
point to its nearest neighbors in the shadow data cloud
(sorted by increasing o... | 6a07b3853463d8ed7156b3c3e0a14661cc55f51b | 3,622,343 |
from typing import Any
from typing import Tuple
from typing import Optional
def get_train_and_validation_loaders(
args: Any, image_size: Tuple[int, ...], task: Optional[Tasks] = None
):
"""
:param args: Object containing relevant configuration for the task
:param image_size: A Tuple of integers repres... | e160dd10a1be710dbc08fddddbb8a3dd2906741c | 3,622,344 |
def is_alef(archar):
"""Checks for Arabic Alef forms.
ALEFAT = (ALEF, ALEF_MADDA, ALEF_HAMZA_ABOVE, ALEF_HAMZA_BELOW, ALEF_WASLA, ALEF_MAKSURA )
@param archar: arabic unicode char
@type archar: unicode
@return:
@rtype:Boolean
"""
return archar in ALEFAT | 246084efce49d17a2b2af34b9db39aa1440d6a03 | 3,622,345 |
import re
def p_regex(regex, flags=0):
""" p_regex returns a parser that matches a regex at the current offset """
r = re.compile(regex, flags=flags)
@SugarParser
def parse(str, offset=0):
match = r.match(str, offset)
if match is None:
return None, -1
match = match... | fa5c2e4f18320a7ebeccebc71c29112033377a49 | 3,622,346 |
from typing import Optional
from typing import Tuple
def _decode_and_center_crop(
image_bytes: tf.Tensor,
jpeg_shape: Optional[tf.Tensor] = None,
) -> Tuple[tf.Tensor, tf.Tensor]:
"""Crops to center of image with padding then scales."""
if jpeg_shape is None:
if image_bytes.dtype == tf.dtypes.string:
... | 1baa7fa938d7adf2e3e1782414b5b1f654971294 | 3,622,347 |
def macd(X: pd.DataFrame,
lower: int = 7,
upper: int = 14,
price_window: int = 63,
window: int = 252):
"""
Computes the Moving Average Convergence Divergence.
References:
- https://arxiv.org/pdf/1911.10107.pdf
Arguments:
X : pd.DataFrame
A ... | 97279bc8ea56ee703bf910601dee898d1a439570 | 3,622,348 |
import os
import subprocess
import json
def probe_video(path):
"""
Returns a probe object with vcodec, acodec and brand fields
Returns None if the file is not a video
If the video has no brand, brand is None
"""
path = os.path.abspath(path)
class Probe:
def __init__(self, vcodec... | 290f83b4fc3bd927b2df4a419f6ab0b66d9fc643 | 3,622,349 |
from sage.misc.latex import _run_latex_, _latex_file_
from sage.misc.temporary_file import tmp_filename
def has_latex():
"""
Test if Latex is available.
EXAMPLES::
sage: from sage.doctest.external import has_latex
sage: has_latex() # random
True
"""
try:
f = tmp_f... | 329c7a053219901c6c2242ce99363b5b7e103fd9 | 3,622,350 |
import os
import importlib
import sys
def import_local_module(project_dir, module_name):
"""
Import a module from a pathname.
"""
# get the full path
if not os.path.isdir(project_dir):
raise FileNotFoundError("Project dir does not exist: %s" % project_dir)
# there are 2 possibilities:... | a5c61aa057a9715aaaa44022201854a2e3c2338a | 3,622,351 |
def crop_to_bbox(objs, bbox):
"""
Filters objs to only those intersecting the bbox,
and crops the extent of the objects to the bbox.
"""
if isinstance(objs, dict):
return dict((k, crop_to_bbox(v, bbox))
for k,v in objs.items())
initial_type = type(objs)
objs = to_list(ob... | c8b0e8742e5e2104c92708c4a067b3df6fe0a2c6 | 3,622,352 |
import glob
def calibrate_camera(nx=9, ny=6, images_folder='camera_cal/calibration*.jpg'):
""" Use the corners to calibrate camera """
# prepare object points, like (0,0,0), (1,0,0)...(6,5,0)
# further study these two lines
objp = np.zeros((nx*ny,3), np.float32)
objp[:, :2] = np.mgrid[:nx, :ny].T... | 94ccbe7372497baf30b628b7f4ff3ede84335af1 | 3,622,353 |
def run_command_async(cmd):
"""
Run a command using the asynchronous `tornado.process.Subprocess`.
Parameters
----------
iterable
An iterable of command-line arguments to run in the subprocess.
Returns
-------
A tuple containing the (return code, stdout)
"""
process = S... | 28e184735cbdcf99bf35b6b2e648f09b59a35d9c | 3,622,354 |
async def webhook(request):
"""Webhook to retrieve action calls."""
action_call = await request.json()
try:
response = await executor.run(action_call)
except ActionExecutionRejection as e:
logger.error(str(e))
response = {"error": str(e), "action_name": e.action_name}
res... | 96ee5097e6c81ed9918fb8509dfc8c2cd619717d | 3,622,355 |
import re
def contain_static(val):
"""
Check if URL is a static resource file
- If URL pattern ends with
"""
if re.match(r'^.*\.(jpg|jpeg|gif|png|css|js|ico|xml|rss|txt).*$', val, re.M|re.I):
# Static file, return True
return True
else:
# Not a static f... | 9b69c0e8c69f9a97abbea82855d0c387de2a381a | 3,622,356 |
def text_messages_joint_log_prob(count_data, lambda_1, lambda_2, tau):
"""Joint log probability function."""
alpha = (1. / tf.reduce_mean(input_tensor=count_data))
rv_lambda = tfd.Exponential(rate=alpha)
rv_tau = tfd.Uniform()
lambda_ = tf.gather(
[lambda_1, lambda_2],
indices=tf.cast(
... | 5c644fede815607179cc3d99451b04015c162f4d | 3,622,357 |
from ooiservices.app.uframe.asset_tools import verify_cache
def build_assets_cache():
""" Force update of asset information.
"""
try:
asset_list = verify_cache(refresh=True)
print '\n Completed compiling asset information.'
print '\n Number of assets: ', len(asset_list)
res... | 562077350bce0dcf403a5cec69d22fd97a716142 | 3,622,358 |
def is_dataset(obj):
"""
True if the object is a h5py.Dataset-like object.
:param obj: An object
"""
t = get_h5_class(obj)
return t == H5Type.DATASET | 0360e7fa312f4f49fd2b47fdcda7f290e516e998 | 3,622,359 |
def get_court_id_from_url(url):
"""Extract the court ID from the URL."""
parts = tldextract.extract(url)
return parts.subdomain.split(".")[1] | 18d6b0f5a817910c09b2cf2063770665a0e587f7 | 3,622,360 |
def insertgroup(request):
"""Insert group in database."""
# Get data
group_name = request.POST.get('group', None)
# Add to inventory
inventory = spotmax.SPOTGroup()
inventory.add_group(group_name)
message = 'Group added!'
return render(
request,
'addgroup.htm',
context={'message': m... | 694909fbe91a179245a2b3c436d9fd53f992b431 | 3,622,361 |
def get_rockets(method=""):
"""Gets information related to SpaceX rockets
Gets information related to rockets from
the API
Parameters
----------
method : str (optional)
the method used for the request
Returns
-------
list
a list of the rocke... | db0bc299b1a7683908ec1e691a0aff318a5aa409 | 3,622,362 |
import os
import shlex
def run_command(command: str, log_file: str = None, line_callback: callable = None):
"""
Runs a shell command with or without log file with STDOUT and STDERR
Args:
command: A unix command to run
log_file: Write stdout and stderr to log file
line_callback: fu... | d2a3ca3120c5f29a5de9c0273140d7a03d09e16b | 3,622,363 |
def load_config():
"""Load configuration file"""
return load_properties_file(CONFIG_FILE_PATH) | 7970c7b00f2912ffbf46c8666110b1ddd46ae434 | 3,622,364 |
def lerp10(h, h1, h2, o1, o2):
"""Returns 10**o, where o is the linear interpolation of value h between (h1, o1)
and (h2, o2)."""
return 10**np.interp(h, [h1, h2], [o1, o2]) | 76faddc8bbac17b8054bf3e2c1920351d81688dc | 3,622,365 |
def get_all_urls(titles, title_data):
"""converts every title into """
urls = []
for title in titles:
title_data[title].append(WIKI_URL+title)
return urls | 471dabeb4268afca4f96a3ae07b547ac221f1426 | 3,622,366 |
def find_system_symbol(img, instruction_addr, system_info=None):
"""Finds a system symbol."""
return DSymSymbol.objects.lookup_symbol(
instruction_addr=instruction_addr,
image_addr=img['image_addr'],
image_vmaddr=img['image_vmaddr'],
uuid=img['uuid'],
cpu_name=get_cpu_nam... | b639b64747d396d539847d7e68e12feb849d3bc6 | 3,622,367 |
def make_univariate(F, T):
"""
Given a homogeneous bivariate polynomial `F(xi,xj)`,
sitting inside a ring `K[x0,x1,x2]`, dehomogenise it
into ring T (univariate), for later factoring.
"""
assert(F.is_homogeneous() and len(F.variables())<3)
R = F.base_ring()
S = F.parent()
x0,x1,x2 = ... | 0f2c230e9e19bcb61b687bcd7aff5ec6d5069347 | 3,622,368 |
def doConvertBlackAndWhiteFilter(image: Image.Image, mode: str):
"""Low level function...
Convert an image to black and white based on a filter: filter-darker and
lighter respectively make pixels darker than the average black and pixels
that are lighter than the average black.
Args:
image (Image.Image): A PIL ... | a66654b00edb4d40b50a1137e698fe4313c5a443 | 3,622,369 |
from typing import List
import time
import subprocess
def train(directory, parfile, makeargs="", output_markdown=True) -> List["LevelStats"]:
"""Make patterns with the given parfile and makeargs.
Supply a parameter name like liang, not out/liang.par or out/liang.
Patterns will be trained on wordlist spec... | af4a796546ccd289e78c3f1029f6abec6e7c70d2 | 3,622,370 |
def copy(
store: BaseAccessStore,
from_principal: str,
from_principal_type: str,
to_principal: str,
to_principal_type: str,
) -> bool:
"""
copies a relationship from the from_principal to the to_principal
for the given types
"""
# print(f'copying from {from_principal_type} {from_... | 5f2495b6c5006e10c2e5a727d5e3d2381bb5aa13 | 3,622,371 |
def expand_list(inlist, keyname, expandables, defaults={}, fmt=[]):
"""[summary]
Output is a a dictionary of an element that has an array
of elements each has expandables set to the inlist values
and for any optional value, revert to the default list.
Example:
inlist = [{"name": "abc", "writable": True}... | 8a8a8dd73a3f995b64389ddbcaebf7d861d2e690 | 3,622,372 |
def get_answers(question_id, **params):
"""获得答案列表"""
conditions = list()
sort_conditions = list()
query = Answer.query
if 'ids' in params:
conditions.append(Answer.question_id.in_(params['ids']))
if params.get('create_time_sort') is not None:
sort_condition = (
Answ... | e1117a26dde9d6dccc661a1dc7c0279726f63107 | 3,622,373 |
import base64
def download_gift(gift):
"""Generates a link allowing the gift file to be downloaded
in: test string data
out: href string to gift formatted test
"""
b64 = base64.b64encode(gift.encode()).decode(
) # some strings <-> bytes conversions necessary here
href = f'<a href="data:f... | f007e35133d2ea0d61471290e7ea3ad4b591db3e | 3,622,374 |
def _showFloatDiffs(asserter, expect, actual, **kwargs):
"""Indicate the differences between two floats.
:Parameters:
expect, actual
The expected and actual float.
kwargs
ignored.
:Return:
A string showing why the float values differ.
"""
ulpDiff = UlpCompare.u... | 0a5af1867d35bfaf56ac43b82967800e59d50280 | 3,622,375 |
def is_recovery_active():
"""Report whether recovery mode is active."""
return RECOVERY_ACTIVE | eb9d061aa2901f591d269543158ce63d8ab63458 | 3,622,376 |
def create_icon_score_stub(**kwargs) -> IconScoreInnerStub:
"""Create IconScoreInnerStub.
Note that return value is actually `mock.Mock`.
"""
task: IconScoreInnerTask = AsyncMock(IconScoreInnerTask)
task.validate_transaction.return_value = "result"
task.query.return_value = {
"result": ... | 6d258a954d9950df8e76c34df59758e0be344243 | 3,622,377 |
import json
def wait_message():
"""
Wait message from websocket, return the message in the format of a dict.
"""
try:
msg = connection.recv()
except websocket._exceptions.WebSocketConnectionClosedException as e:
print(e)
global connection
connection = connect()
... | d7e05ed51c2a74d6e37a50341973d02ed3facd42 | 3,622,378 |
def create_classification_for_sample_and_variant_objects(
user: User,
sample: Sample,
variant: Variant,
genome_build: GenomeBuild,
refseq_transcript_accession: str = None,
ensembl_transcript_accession: str = None,
annotation_version: str = None):
""" Create in... | 8d6c1b014d61cf3b58cf6ffd1f8eb0299f91f8f3 | 3,622,379 |
def rectifier(x):
""" element-wise ReLU """
return tensor.maximum(0., x) | bfc89136f7a6d0e7c8d0bbd0da1c73795e36bd7f | 3,622,380 |
import json
import re
def unsubChange(doc, API, session):
""" Calculate a mailing list unsub request """
diff = ""
mls = {}
with open("private/json/ml-modsubs.json") as f:
mls = json.load(f)
f.close()
li = doc['listname']
l,d = li.split('@', 2)
d = d.replace(".apache.org", ... | 72b1e1d0886222b43ff0df4deccfbce5e4f55332 | 3,622,381 |
import json
def get_wbt_dict():
"""Generate a dictionary containing information for all tools.
Returns:
dict: The dictionary containing information for all tools.
"""
url = "https://github.com/giswqs/whiteboxgui/raw/master/whiteboxgui/data/whitebox_tools.json"
response = urlopen(url)
... | f2c3c6a2f8881eec05cc4677098d104d30d4f8ea | 3,622,382 |
def abs_path_from_ryven_dir(path_rel_to_ryven_dir: str):
"""Given a path string relative to the ryven dir '~/.ryven/', return the file/folder absolute path
:param path_rel_to_ryven_dir: path relative to ryven dir (e.g. saves)
:return: file/folder absolute path
"""
return abspath(join(ryven_dir_pat... | 7eb365ad57e6a2ae6bb036699c53de98bc26a8a2 | 3,622,383 |
def get_points(features, fpn_strides):
"""Get points according to feature map sizes.
Args:
features (list[Tensor]): Multi-level feature map. Axis 0 represents the number of
images `N` in the input data; axes 1-3 are channels, height, and width, which
may vary between feature map... | 37f452120c26091c170e7390fb5ee0f265b7b7d0 | 3,622,384 |
import tty
def test_install_read_locked_requeue(install_mockery, monkeypatch, capfd):
"""Cover basic read lock handling for uninstalled package with requeue."""
orig_fn = inst.PackageInstaller._ensure_locked
def _read(installer, lock_type, pkg):
tty.msg('{0}->read locked {1}' .format(lock_type, p... | bfb360eb66ebe26d7046cff115f0a482dc531350 | 3,622,385 |
def _read(fpath):
"""Read content of numpy archive file at <fpath>."""
if not pth.__is_file(fpath):
log.critical("Numpy file \"{0}\" not found, cannot read data".format(fpath))
log.debug("Reading data from \"{0}\"".format(fpath))
return np.load(fpath) | 004b2d48f85f5358f862290ef28629309cfc17ca | 3,622,386 |
from typing import List
import time
async def get_proof_request(
connection_id: str,
schema_id: str,
name_proof_request: str,
zero_knowledge_proof: List[dict] = None,
requested_attrs: List[str] = Query(None),
self_attested: List[str] = None,
revocation: int = None,
exchange_tracing: bo... | b39aa7bc7ebad273baa0e1dfb153d0fb3e3ffefe | 3,622,387 |
def add_saved_albums(auths=None, albums=(None,)):
"""
Adds/follows albums.
:param auths: dict() being the 'destinations'-tree of the auth object as returned from authorize()
:param albums: list() containing the albums IDs to add to the 'destinations' accounts
:return: True
"""
for username i... | 705dcd0a66e401866ce9a07c3ea7ca3eacf0dc19 | 3,622,388 |
def get_min(statistical_series):
"""
Get minimum value for each group
:param statistical_series: Multiindex series
:return: A series with minimum value for each group
"""
return statistical_series.groupby(level=0).agg('min') | c032f2f834cfe298a6c9f98c9116aaf354db0960 | 3,622,389 |
import time
def now():
"""
Get the current time function.
:return: Time function.
:rtype: function
"""
if hasattr(time, 'monotonic'):
return time.monotonic
return time.time | a50542697bbf4fa78d942fb564749e4e26b37ff4 | 3,622,390 |
def to_roman(value: int, make_upper: bool = True) -> str:
""" The presence of 500 (D) and 50 (L), coupled with the special handling of 400, 900, 40, 90, 4
and 9, make table lookup seem like the best approach.
"""
if value == 0:
return 'Zero'
if value > 3999:
return f'{value:,}'
thousands, value ... | d74982f73848b2d64c421a10a2b3bed6c89a7c54 | 3,622,391 |
def plot_inventory_chart(remaining):
"""Update inventory chart.
Parameters
----------
remaining : pandas.Series
Series object containing the number of remaining items
for each product category.
Returns
-------
fig : plotly.graph_objects.Figure
Bar chart showing the ... | 9661e1484936c39cc99cfa8522e4aff8aee9c7fd | 3,622,392 |
import csv
def readfile(path, filename):
""" Parses a file created by the measurement software (which is based on LabVIEW)
:param path: str
:param filename: str
:return: np.array
"""
rawfile = open(path + filename)
file = csv.reader(rawfile, delimiter="\t")
datalist = []
for row in... | 6543a6ae878cd49d17e2961f2551975727085bd4 | 3,622,393 |
def get_isotropic_level(hierarchy_method, x_voxel_size, y_voxel_size, z_voxel_size):
"""Method to get the resolution level where the data is closest to isotropic
Args:
hierarchy_method(str): isotropic or anisotropic
x_voxel_size(int): voxel size in x dimension
y_voxe... | 62b9bc3c730c4b41f2d6abf42858a51998859e9f | 3,622,394 |
import scipy
def pearson(exprDF, lMirUser = None, lGeneUser = None, n_core = 2, pval = True):
"""
Function to calculate the Pearson correlation coefficient, and pval
of each pair of miRNA-mRNA, return a matrix of correlation coefficients
with columns are miRNAs and rows are mRNAs.
Args:
... | 5decd8490edc5b2bc642fab188e09aba5991de9f | 3,622,395 |
def detect_mode(editor):
""" hook called to detect if this mode should be used for a file, returns True if it should be used, False otherwise """
workfile = editor.getWorkfile()
global lexer
try:
filename = workfile.getFilename()
if filename:
lexer = get_lexer_for_filename(fi... | 09809b245519a2cbbf47f435b6b672477450d4ed | 3,622,396 |
def find_duplicate(strings: list):
"""find the first duplicate string from list:strings"""
strings = [str(x) for x in strings.split(',')]
map = defaultdict(int)
duplicate_string = ''
for word in strings:
if map[word]:
duplicate_string = word
print(f'The duplicate string is "{word}"')
break
else:
... | fe94b14f1f425605bc2ae2dbb2ac4b3f01cdd2f4 | 3,622,397 |
import copy
def enemyEnclosed(bo:board, us:snake, snakes:list):
"""
Returns a list of targets we can enclose the enemy
(1) Find squares we can get to first
(2) Calcualte enemy chance board, looking for 100%
(3) Find intercept of 100% and squares we can get to
==
bo: boardClass... | 0441db28aa8210f36db59fcad4ffd1cdf1fd1bab | 3,622,398 |
def get_daily_returns(port_val):
"""Get daily returns of a portfolio value dataframe.
Args:
port_val (dataframe): daily portfolio value
Returns:
daily_ret (dataframe): daily returns
"""
daily_ret = port_val.copy()
daily_ret[1:] = (port_val[1:] / port_val[:-1].values)-1
dail... | 8d1a2dd03c2a5992b97b5d8d4b00cc65ebe4caba | 3,622,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.