content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def b85encode(octet_string):
"""Encode a octet_string using 85 characters.
Compliant with RFC1924
Intended originally for only 128 bit IPv6 addresses
Longer or shorter strings will work.
"""
return base_N_encode(octet_string, _b85chars ) | 17533ca3c91b26c8521a8fb4194b3048d4c93bfc | 47,800 |
def computeIoUs(preds, truths):
"""
Compute intersection over union for the predicted masks vs ground-truth masks. @preds and @truths must have the same length and both are iterables of numpy matrices of same dimensions.
"""
# List to collect IoU for each pair
IoUs = []
# Iterate over the collections and comput... | 208606710c07878bccf8cae0f3b95ce65cb4180a | 47,801 |
def gamma_prior(mode,std):
"""
In general you should prefer the log_normal prior.
"""
a = std/mode#sqrt(k)/(k-1)
shape = (2* a**2 + np.sqrt((4 * a**2 + 1)/a**4) * a**2 + 1)/(2 *a**2)
scale = std/np.sqrt(shape)
return gp.priors.Gamma(shape,scale) | 6aaac79facbd5da60349c44b65d42df724c3bdd9 | 47,802 |
def test_no_global_imports_of_banned_package():
"""This test ensures that neither of the banned packages are imported module wise in any of our code files.
If one of the dependencies is needed, they should be imported within a function."""
banned_packages = ["spacy", "mitie", "sklearn", "duckling"]
... | 154870ebaff7df266d65d1be805929627c3d675c | 47,803 |
import os
def white_balance(img, mode='hist', roi=None):
"""
Corrects the exposure of an image based on its histogram.
Inputs:
img = An RGB image on which to perform the correction, correction is done on each channel and then reassembled,
alternatively a single channel can be input ... | 81d5804ff6e509d01f1e51c88f7f22815878bf07 | 47,804 |
import getpass
import os
import json
import random
def aes_encrypt(text, passphrase = None):
"""
Encrypt text with passphrase
:param text: The text to be encrypted.
:param passphrase: The key material
:return:
"""
if not passphrase:
passphrase = getpass.getpass('Enter passphrase: '... | 5d707e98c05375aa030cb36f5bee30f30d79a1b4 | 47,805 |
def remove_host(mac, *args, **kwargs):
"""
Delete a host from the system
Variables:
mac => MAC Address of the host to be deleted
Arguments:
None
Data Block:
None
Result example:
{"success": True}
"""
STORAGE.delete_node(mac)
return make_api_... | 2308b7bc3496eee7cfda31c6e468fd33af60bff6 | 47,806 |
def get_ordered_tests(tests_setup, test_type):
"""Determines the order of tests to be run, filtered to only return the specified type.
Args:
tests_setup (dict): Map of test name to its configuration (see: res/test/translator.json).
test_type (str): Which apps are to be tested. Must be one of "c... | fa5f04ea46d1385ac3f174c2f9733d68b7d97ecf | 47,807 |
import re
import random
def flip(message, txt):
"""
<text> -- Flips <text> over.
:param message: Slackbot message object
:param txt: Text to flip
:return: Message to slack channel
"""
global table_status
chan = message._body['channel']
text = txt.strip()
if re.match(re_table, ... | 39c2ea731a74b64e5a08870ba73d7b16f0c33801 | 47,808 |
import shutil
import sys
def cli(ctx, path, **kwds):
"""Create a Galaxy tool tarball.
This will use the .shed.yml file to prepare a tarball
(which you could upload to the Tool Shed manually).
"""
def build(realized_repository):
tarpath = shed.build_tarball(realized_repository.path)
... | 60ae47516b24c4763e7588da8c802348dc0a37ae | 47,809 |
def ilr(X: np.ndarray):
"""
Isometric Log Ratio transformation.
Parameters
---------------
X : :class:`numpy.ndarray`
Array on which to perform the transformation, of shape :code:`(N, D)`.
Returns
--------
:class:`numpy.ndarray`
ILR-transformed array, of shape :code:`(N... | 988e1591ff996e12067d188ebe2c137c45238535 | 47,810 |
def _stub_create_regularizer(op_slice, model_stub):
"""Create a StubOpRegularizer for a given OpSlice.
Args:
op_slice: A op_regularizer_manager.OpSlice.
model_stub: Module name where REG_STUB and ALIVE_STUB will be found.
Returns:
StubOpRegularizer with stubbed regularization and alive vectors.
""... | 34db10bbf19cafcd0f052391dadd71b450215ba5 | 47,811 |
def standard_method(row, iters):
"""
Given a tape represented as a row of Booleans, compute (in-place) the next
row according to the Rule 110 ruleset.
Assume that the tape wraps around to form a cylinder, i.e. for a tape of
length `n`, column 0 is adjacent to column 1 and column n-1.
Inputs:
... | 015aef5bc6b1c757163917a43669d57067e97d6a | 47,812 |
def compute_mi(dataset, target_name, vocab, level=None):
""" compute the mutual information for each token in a lexicon
"""
if not level:
# bucket based on bottom/top 30%
response = dataset.datafile_to_np(
datafile=dataset.whole_data_files[target_name])
response = respons... | 2be687af778a9772d89453a9ce0ba907d90ab77e | 47,813 |
def split_code_to_cells(code):
"""converts code to a list of AbstractCell
:param code: string representing the code
:return: list of AbstractCell
"""
raw_cells = _split_to_raw_cells(code)
return _raw_cells_to_cells(raw_cells) | 26c8451cbc7adec12948d23d379ff6937cf051a3 | 47,814 |
def present(name, service_name, auth=None, **kwargs):
"""
Ensure an endpoint exists and is up-to-date
name
Interface name
url
URL of the endpoint
service_name
Service name or ID
region
The region name to assign the endpoint
enabled
Boolean to cont... | 1c042ac2ad30bb92d231d9747be5b7f564f1ecff | 47,815 |
def registration(request):
"""Render the registration page"""
#redirect to the index page if user is authenticated
if request.user.is_authenticated:
return redirect(reverse('index'))
if request.method == "POST":
# create an instance of the reg form using values within the pos request
# ... | 9e2ff50b7b329ceb75fd0e83ca3a90897f9f2894 | 47,816 |
import posixpath
from urllib.parse import unquote
from urllib import unquote
def url_collapse_path(uripath):
"""Mimic standard lib's _url_collapse_path() but return a tuple
That is, a tuple of path, trailing slash, everything else (query and
fragment).
The only other difference is that the path comp... | f0f562f5df4436f920a18ea7977c783426aa0dd3 | 47,817 |
from datetime import datetime
import traceback
def compute_use_days(personnel):
"""计算已用天数
1/如果”改善状态”字段是“改善“,则等于改善日期-问题日期
2/如果"改善状态”字段是“持续“,则等于当前日期-问题日期
:param personnel:个人操作质量单条数据对象
:return:天数
"""
use_day = 0
try:
now_date = datetime.date.today() # 现在日期
improve_status = personnel.improve_status.name # 改... | aeb67af3865221855409840a1b4a8d5b7376cb8c | 47,818 |
import inspect
def layer_test(test_case, layer_cls, kwargs={}, input_shape=None, input_dtype=None,
input_data=None, expected_output=None,
expected_output_dtype=None, fixed_batch_size=False):
"""
Test routine for a layer with a single input tensor
and single output tensor.
... | 3e4f35ca2048b07e0ba0f5252e4f0bad75d1f465 | 47,819 |
import re
def remove_special_char(in_seq):
"""
Function is responsible for normalize strings to defined format (UPPERCASE with '_' replacing any special character)
:param in_seq: list of strings
:return: list of strings
"""
_sub = re.sub(" {1,5}", "_", in_seq.strip()).lower()
_chars = ['*', '\\', '&', '/', '+'... | 425f8a7fcd6a2df7db667063564f419536ae68d9 | 47,820 |
import numpy
def position_from_msg(tf_msg, fmt='xyz'):
"""Extract position from geomety_msg/TransformStamed message."""
return numpy.array([getattr(tf_msg.transform.translation, d) for d in fmt]) | f74b5aa4fe9e9e462e6eedc4dafa22c7ba2be1e8 | 47,821 |
import json
def format_navigation_links(additional_languages, default_lang, messages, strip_indexes=False):
"""Return the string to configure NAVIGATION_LINKS."""
f = u"""\
{0}: (
("{1}/archive.html", "{2[Archive]}"),
("{1}/categories/{3}", "{2[Tags]}"),
("{1}/rss.xml", "{2[RSS fee... | 81882137af3e80ba24a3de797ebb9f30e6d5a877 | 47,822 |
def fixture_spring_metadata(
first_read, second_read, spring_tmp_path, checksum_first_read, checksum_second_read
):
"""Return metada information"""
metadata = [
{
"path": str(first_read.absolute()),
"file": "first_read",
"checksum": checksum_first_read,
... | f6e9964b811fd1ce4e873f7a5f57d392ebb3fe98 | 47,823 |
def get_clocks(work,
start_date = None,
end_date = None,
errant_clocks = None,
case_sensitive = False,
adjust_clocks = True):
"""Filter work by messages conataining the word 'clock' """
if errant_clocks is not None:
work = work[~work.hash.isi... | 2df5ce8379e7155b594f3459b90acd603643fcad | 47,824 |
def loss_K(loss_mat, Segmentation = False):
"""
TF function to calculate loss from the loss matrix:
Inputs:
y_true: true values (N,D)
y_pred: predicted values (N,D)
loss_mat: matrix of loss values for selecting outputs (D,D)
"""
loss_mat = tf.constant(loss_mat,dtype=tf.float32)
if Segmentation:
def lo... | 1a09e5f4101fdcf972c0ef24450daadacb2651ad | 47,825 |
def ActionClear( request, id, command ):
"""
Clear trash or cache folders
and than redirect back
"""
if request.user.is_anonymous( ) and not settings.LIMITED_ANONYMOUS:
return HttpResponseRedirect( '%s?next=%s' % (settings.LOGIN_URL, request.path) )
lib_id = int( id )
home = get_ho... | 7648c4c472e2f1bb4679ea1bdf1b37574315a7ec | 47,826 |
def ConvertArgsToSingleString(*args):
"""
:param *args:
"""
max_line_total, width_used, total_lines, = 0, 0, 0
single_line_message = ''
# loop through args and built a SINGLE string from them
for message in args:
# fancy code to check if string and convert if not is not need. Just ... | 0051b46460790f2ef92c7cf636b196356d1f7ca8 | 47,827 |
def diff_left(l1, l2):
"""
Computes which elements are in l1 but not in l2
:param l1: Array
:param l2: Array
:return: diff -> Array
"""
diff = l1.copy()
for e2 in l2:
for e1 in l1:
if e1 == e2:
diff.remove(e1)
return diff | aceb89661dbcad8b620876d0b34875f0670c190d | 47,828 |
import torch
def calc_gradient_penalty(params, d_model, obs_mag, g_out, conditions, true_mag):
"""Calculate the gradient penalty
Args:
params: the hyperparameters used for training
d_model: the Discriminator model
obs_mag: the ground truth observed galaxy magnitudes
g_out: the... | 169fd37cfe4b02eb4405c0864570d9d83ca1adb1 | 47,829 |
def _add_pos1(token):
"""
Adds a 'pos1' element to a frog token.
"""
result = token.copy()
result['pos1'] = _POSMAP[token['pos'].split("(")[0]]
return result | d98893a8b320eabea7af6c2ab2e83ad31ecbcefd | 47,830 |
def check_JR(profile, committee):
"""Test whether a committee satisfies JR.
Parameters
----------
profile : abcvoting.preferences.Profile
approval sets of voters
committee : set / list / tuple
set of candidates
Returns
-------
bool
Reference
---------
Aziz,... | f417bdec5818c7ff52ce51c7683dab60eb737ea6 | 47,831 |
import sys
import urllib
import tarfile
import shutil
import os
def create_geoip_db():
"""Open GeoIP DB if available, download if needed"""
try:
# Try to open an existing GeoIP DB
geoip_db = open_database('GeoLite2-City.mmdb')
return geoip_db
except IOError:
try:
... | 06b1458f9f57664de33fe5dc7764de3089c45617 | 47,832 |
import re
import os
def reformat_comment(comment: str, add_tab=False):
"""
:param comment:
:param add_tab
:return:
"""
comment = re.sub(r'\s+', ' ', comment)
sentence_len = 0
tmp = []
for word in comment.split(' '):
if sentence_len >= 70:
sentence_len = len(w... | 2e14cb1866c5f098ee40e7301551d5e145214389 | 47,833 |
import os
def are_ensembles_created(path, number_of_ensembles):
"""Checks and reads the ensembles ids from the ensembles file in the
path directory
"""
ensemble_ids = []
try:
with open("%s%sensembles" % (path, os.sep)) as ensembles_file:
for line in ensembles_file:
... | eafe826425b0355f8991c5697a2cf63c69324091 | 47,834 |
import re
def untokenize(words):
"""
Untokenizing a text undoes the tokenizing operation, restoring
punctuation and spaces to the places that people expect them to be.
Ideally, `untokenize(tokenize(text))` should be identical to `text`,
except for line breaks.
"""
text = ' '.join(words)
step... | 825fb69106e5bf8532ff98c0db0dbc8077fe634b | 47,835 |
def ingest_running():
"""
Starts up the fake ingest/metricproxy combo and also adds a write_http
config to use that. Yields the final config with write_http configured and
the ingest interface
"""
with fake_backend.run_all() as (ingest, mp_url):
def render_config(config):
re... | 2eb915ff3d190d0bcc28231e475eebbd14e3d13d | 47,836 |
import os
import sys
def parse_chebi_xml(filename):
"""Keeps data in lists so we can capture multiple values eventually, do not know
what to expect at the moment.
ChEBI keeps substance names in two places, <NAME> and <SYNONYM> tags.
"""
_chebi_id = None
_definition = []
_names = [] # do ... | 56402e347858ef350a2d850b019396869b543f72 | 47,837 |
def sexp2tree(sexp):
"""
Parameters
----------
sexp: list[str]
Returns
-------
NonTerminal
Notes
-----
Please note that the input ``sexp'' is assumed to be the raw version in RST-DT.
So, if you want to convert a loaded S-expression after preprocessing, please use ``treetk.s... | 476ad9833fc8f8bf213146b778a9954ca8e655e6 | 47,838 |
import os
def catl_sdss_dir(catl_kind='data', catl_type='mr', sample_s='19',
catl_info='members', perf_opt=False, print_filedir=True,
Program_Msg=fd.Program_Msg(__file__)):
"""
Extracts the path to the catalogues
Parameters
----------
catl_kind: string, optional (default = 'data')
... | eb1660219624eb63c5f6d3c7047bd15085a72e40 | 47,839 |
def wait_for_pool_ready(
batch_client, blob_client, config, pool_id, addl_end_states=None):
# type: (batch.BatchServiceClient, azure.storage.blob.BlockBlobCLient,
# dict, str, List[batchmodels.ComputeNode]) ->
# List[batchmodels.ComputeNode]
"""Wait for pool to enter steady state a... | 8b7af75d32e3b6c29b1edde771bb9d7234c2d901 | 47,840 |
def create_adv_inputs(states):
"""
Create the input for the ADV Net: cab-positions + psng-positions
"""
# For testing this only works for 2 agents and 2 passengers
assert len(states) == 2
assert len(states[0]) == 11
# passengers are the same for all cabs
pass1_x, pass1_y = states[0][7],... | ff6f56ab112b71fc636439afb4b72b4858d098eb | 47,841 |
def fizz_buzz(num):
"""
return 'Fizz', 'Buzz', 'FizzBuzz', or the argument it receives,
all depending on the argument of the function,
a number that is divisible by, 3, 5, or both 3 and 5, respectively.
"""
if not isinstance(num, int):
raise TypeError("Expected integer as... | 8b741800f80ebe631f6821a865c9080c33eb4e27 | 47,842 |
def get_bodylength(data, tail_tag: str='', head_tag: str=''):
""" get length of mouse body at all frames and avg length"""
if not tail_tag or not head_tag:
print('Need to have the name of the head and tail bodyparts to extract bodylength from DLC data')
return False
else:
# Calculate... | ca98c4aabcc3a12d25b393888bbda0bf23372ad4 | 47,843 |
def get_diagonal_quadface_from_2points(mesh,vi):
""" similar to above: get_diagonal_polyline_from_2points
from given 2diagonal vertices [iv1,iv3], get the whole diagonal quads
[v1,v2,v3,v4]
"""
H = mesh.halfedges
es1 = np.where(H[:,0]==vi[0])[0]
es2 = np.where(H[:,0]==vi[1])[0]
f1 = H[es... | eb952b6fb632617a22632824d79359be90644a05 | 47,844 |
def run_petronia(bus: EventBus, args: UserArguments) -> int:
"""
Run the actual Petronia program.
"""
if args.platform:
platform_module = get_user_platform_module(args.platform)
else:
platform_module = get_platform_module()
return run_platform_main(bus, platform_module) | 145776b898fffd4e2973b270c37bb18dd79fa778 | 47,845 |
def weighted_sw_index(matrix, n_avg=1, n_iter=1):
"""Calculate the weighted small world coefficient omega of a matrix."""
C = weighted_clustering_coeff_z(matrix)
L = weighted_characteristic_path_length(matrix)
indices = []
for i in range(n_avg):
random_graph = random_reference(matrix, n_iter=n_iter)
... | d415cc7be59e2e172d9effc9d4bf5cd2ae2d3b7a | 47,846 |
import argparse
def generate_cli():
"""
Generate a simplistic command-line interface.
"""
parser = argparse.ArgumentParser()
commands = parser.add_subparsers()
validation = commands.add_parser('validation')
validation.set_defaults(func=run_validation_suite)
custom = commands.add_parser('custom')
custom.se... | c4ab24746507f7ccab48127ddef59a53a16cafcc | 47,847 |
def dict_to_cvode_stats_file(file_dict: dict, log_path: str) -> bool:
"""
Turns a dictionary into a delphin cvode stats file.
:param file_dict: Dictionary holding the information for the cvode stats file
:param log_path: Path to were the cvode stats file should be written
:return: True
"""
... | 4b6d92ad610c47eed5b2e593980a74f617ed44f4 | 47,848 |
import re
def isNumber(test):
"""
Test if the string is a valid number
Return the converted number or None if string is not a number.
"""
try:
test = str(test)
if re.search('\.',test):
try:
return float(test)
except:
return N... | 93f3afd1c3e8cefc64b1ff738e3f8336a1b8ffd6 | 47,849 |
def add_instances_to_subnets(subnet_list, instance_list):
""" Using the subnet nodes as father to build the instance nodes
and adding them to the subnet nodes children
"""
if len(subnet_list) < 1:
return []
# Sorting the instance list to avoid the search
# when several instances are... | 69b61db5fd7d61e34f2545f5802622a94c664854 | 47,850 |
import os
import time
import shutil
def default_pyinstaller_way(pyInstallerDir : str, pyInstallerZip : str,path_to_python : str) -> bool:
"""
if we failed in compiling the bootloader, we will just install the "plain"
pyinstaller, and keep it up with the dropper
"""
if os.path.exists(pyInstallerDir... | a6176a9092e0954f860316dd57e18ed14abafc5b | 47,851 |
def unskew_S1(S1, M, N):
"""
Unskew the sensivity indice
(Jean-Yves Tissot, Clémentine Prieur (2012) "Bias correction for the
estimation of sensitivity indices based on random balance designs.",
Reliability Engineering and System Safety, Elsevier, 107, 205-213.
doi:10.1016/j.ress.2012.06.010)
... | c82dfb842ff61781a45d132acd66f88ab018690c | 47,852 |
def deform_face_geometric_style(lms, p_scale=0, p_shift=0):
""" deform facial landmarks - matching ibug annotations of 68 landmarks """
lms = deform_scale_face(lms.copy(), p_scale=p_scale, pad=0)
lms = deform_nose(lms.copy(), p_scale=p_scale, p_shift=p_shift, pad=0)
lms = deform_mouth(lms.copy(), p_sca... | c2f84d9469f39652051c02e3d6c830bb39040984 | 47,853 |
def _inf_time_obs(rho,istate,Obs=False,delta_t_Obs=False,delta_q_Obs=False,Sd_Renyi=False,Srdm_Renyi=False,alpha=1.0):
"""
This function calculates various quantities (observables, fluctuations, entropies) written in the
diagonal basis of a density matrix 'rho'. See also documentation of 'Diagonal_Ensemble'. The
f... | 006f34861de0494c7771395f70ac0a3336ecba04 | 47,854 |
def AnyListItemValidates(list_item_validator):
"""
Validate that at least one item in the list complies with
'list_item_validator'.
"""
@wraps(AnyListItemValidates)
def _validate(value):
if not isinstance(value, list):
raise Invalid('expected a list')
list_item_sche... | fd0a77b5ae3f66a63f51eea2c7f9bc385e13a88b | 47,855 |
def get_array(pdi, field, name):
"""Gets an array from a vtkDataObject given its field association and name.
Notes:
- Point Data: 0
- Cell Data: 1
- Field Data: 2
- Row Data: 6
Args:
pdi (vtkDataObject) : the input data object
field (int or str) : the field ... | 87fd086fa0a94ab1a836e2724862635da454de9d | 47,856 |
from typing import Set
from typing import List
def power_set(numbers: Set[int]) -> List[Set[int]]:
""" Finds all subsets of the given set """
indexed_numbers: List[int] = list(numbers)
result: List[Set[int]] = []
result.append(set())
for i in range(0, len(indexed_numbers)):
subsets: List[Set[int]] = build_s... | 9cd5044c8fba38c2dc0fd1e1f02f84f36c6bd8fa | 47,857 |
import inspect
def getBaseObject(object):
"""Return base object and dropSelf indicator for an object."""
if inspect.isbuiltin(object):
# Builtin functions don't have an argspec that we can get.
dropSelf = 0
elif inspect.ismethod(object):
# Get the function from the object otherwise... | 8811c7ac4cfbc9b08c2b7e470289f3b48da480d1 | 47,858 |
def split_list(l, break_pts):
"""returns list l split up into sublists at break point indices"""
l_0 = len(l)
sl = []
# Return a list containing the input list if no breakpoints indices selected
if len(break_pts) == 0:
return [l]
# Else splits the list and return a list of sub lists. A... | 940fe3425e9708e1852fd4930cb5af3e96076b1f | 47,859 |
def repr_dps(n):
"""Return the number of decimal digits required to represent
a number with n-bit precision so that it can be uniquely
reconstructed from the representation."""
dps = prec_to_dps(n)
if dps == 15:
return 17
return dps + 3 | c352ee5baefe0dc1e10aa13e85395e880ac68fc4 | 47,860 |
def get_builder(regulation, version, inline_applier, p_applier, s_applier):
""" Returns an HTML builder with the appliers, and the regulation tree. """
builder = HTMLBuilder(inline_applier, p_applier, s_applier)
builder.tree = get_regulation(regulation, version)
return builder | fc9530f4c9eeaf8548c2f485a422ac27a08b7a73 | 47,861 |
def get_fine_tune_model(symbol, arg_params, num_classes, layer_name, dtype='float32'):
"""
symbol: the pre-trained network symbol
arg_params: the argument parameters of the pre-trained model
num_classes: the number of classes for the fine-tune datasets
layer_name: the layer name before the last full... | 92192a80c7ec92f4e0198f38103bfb53ee21899a | 47,862 |
import asyncio
async def async_setup(hass, config):
"""Load the scripts from the configuration."""
hass.data[DOMAIN] = component = EntityComponent(_LOGGER, DOMAIN, hass)
await _async_process_config(hass, config, component)
async def reload_service(service):
"""Call a service to reload script... | 4c206b561b559bc91a2d5307958513296dcc9383 | 47,863 |
import base64
def aes_decrypt(key, iv, content):
"""
AES解密
key,iv使用同一个
模式cbc
去填充pkcs7
:param key:
:param content:
:return:
"""
cipher = AES.new(key, AES.MODE_CBC, iv)
# base64解码
encrypt_bytes = base64.b64decode(content)
# 解密
decrypt_bytes = cipher.decrypt(encry... | 04feb90a3f30b3c26f287ab0bf89ec8bc7930527 | 47,864 |
import requests
import time
import traceback
from bs4 import BeautifulSoup
def get_comments(code, sleep=1):
"""获取股票code的雪球评论
:param str code: 股票代码,如 `600122`
:param float sleep: 睡眠时间, 默认值为 1
:return:
"""
headers = get_header()
sess = requests.Session()
# 访问首页,获取cookies
sess.get(X... | 48e64ead34ee9cdfd2c63835d573cbeb1f994324 | 47,865 |
def has_same_base_dtype(df_1, df_2, columns=None):
"""Check if specified columns have the same base dtypes across both DataFrames.
Args:
df_1 (pd.DataFrame): first DataFrame.
df_2 (pd.DataFrame): second DataFrame.
columns (list(str)): columns to check, None checks all columns.
Retu... | 6c9f7acdba47bed0c98c830958573026c4666099 | 47,866 |
def upsample(zs, labels, sampling_kwargs, priors, hps):
"""Upsample given already generated upper-level codes"""
sample_levels = list(range(len(priors) - 1))
zs = _sample(zs, labels, sampling_kwargs, priors, sample_levels, hps)
return zs | c16c812dc93afc995123d1ddd551195f86f70b26 | 47,867 |
def k_12():
"""Define the k12 component of permeability tensor."""
return np.zeros((1, 1)) | 5692054b0ec2e4f8dea7d5b9c039a86cc859ef2f | 47,868 |
import warnings
import os
from sys import path
def tpath(request):
"""
Fixture that takes the value of the special test-specific folder for test
run data and plots. Usually the <folder of the test>/tresults/test_name/
"""
tpath_root, tpath_local = utilities.tpath_root_make(request)
os.makedir... | 775d4d6e4040809d7fcd664a2b0c5cbac706adbf | 47,869 |
def historical_limit():
"""max days"""
return 90 | c152cf6638c46a537aa9659f8435e2d3d7e67baf | 47,870 |
def get_dataloader(url_list, model_name=cfg.model_name, batch_size=cfg.batch_size, num_workers=cfg.num_workers):
"""Create and return an instance of dataloader
Args:
url_list (list): List of http(s) or S3 urls to fetch images from.
model_name (str, optional): Model name, used for corresponding ... | c20b7c7f792d85395038d7744ab5a5e5cd71bb9f | 47,871 |
from sage.misc.superseded import deprecation
def coxeter_matrix(t):
"""
This was deprecated in :trac:`17798` for :class:`CartanMatrix`.
EXAMPLES::
sage: coxeter_matrix(['A', 4])
doctest:...: DeprecationWarning: coxeter_matrix() is deprecated. Use CoxeterMatrix() instead
See http:... | 0fda2399c6f49884bc54da6112eb88f57bf183b7 | 47,872 |
import sys
def HaveGoodGUI():
"""Returns true if we currently have a good gui available.
"""
return "pywin.framework.startup" in sys.modules | e57c7063959024baaa84bd545fa6650516ba11e8 | 47,873 |
def run_ralston(system, slope_func, **options):
"""Computes a numerical solution to a differential equation.
`system` must contain `init` with initial conditions,
and `t_end` with the end time.
`system` may contain `t_0` to override the default, 0
It can contain any other parameters required by... | b69a468a2da29c9d7055bda9f50f2d7621c56199 | 47,874 |
import gzip
def __output_block_mtx(block_cell, nblock, ncell, block_ad_file, block_dp_file, _gzip = 0):
"""
@abstract Output block-cell AD & DP matrices to mtx file
@param block_cell A dict of {reg_idx:{cell_idx:{ad:ad_depth, dp:dp_depth}, }} pairs [dict]
@param nblock Number of t... | 0d813f72c70047e0f8d12d0447a86a9c2281c861 | 47,875 |
def prep_im_for_blob(im, pixel_means, target_size, max_size):
"""Mean subtract and scale an image for use in a blob."""
im = im.astype(np.float32, copy=False)
im -= pixel_means
im_shape = im.shape
#-------------------------------------------------------------
interp_mode = cv2.INTER_LINEAR
... | ecd2f31f83b9c29b3c233d24f2771f31d52d2e5f | 47,876 |
from typing import List
def solve(capacities: List, waters: List) -> int:
"""Solve the question 1. See this module docstring.
Parameters
----------
capacities : List
the capacities of tankers.
waters : List
the amount of water in tankers.
Returns
-------
int
t... | 31b330373701afeb2a0abbe988ae54e8cfc7ead4 | 47,877 |
import torchvision
import string
import torch
import pdb
import logging
def load_torchvision_data(dataname, valid_size=0.1, splits=None, shuffle=True,
stratified=False, random_seed=None, batch_size = 64,
resize=None, to3channels=False,
maxsize = None, maxsiz... | a5710a08ad37928d44c0073490016cd5dcc25b3a | 47,878 |
import csv
def class_names_from_csv(class_map_csv_text):
"""Returns list of class names corresponding to score vector."""
class_names = []
with tf.io.gfile.GFile(class_map_csv_text) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
class_names.append(row['display_name'])
return cl... | 1bfe1690719382990d3ab983042856f5ee68baad | 47,879 |
def np_col_vec (init_list):
"""Generates a Numpy-compatible column vector."""
return np_row_vec (init_list).T | b39e6b4c0d47aba460113509540a608bcf29cc76 | 47,880 |
def _gcd(a, b):
"""
Return greatest common divisor using Euclid's Algorithm.
"""
if a == 0: return b
if b == 0: return a
while b:
a, b = b, a % b
return abs(a) | 2b92f47552285b3f12deb74deb780e660c44d2ab | 47,881 |
def index(request):
"""renders listing main page"""
listings = Listing.objects.all().order_by(
'-list_date').filter(is_published=True)
paginator = Paginator(listings, 3)
page_number = request.GET.get('page')
paged_listing = paginator.get_page(page_number)
context = {
"listings... | acde94fe152bc774e32458ac14130d5fae2cd9ec | 47,882 |
import os
def do_not_have_mysql():
"""Checks if mysql exists on this platform"""
for path in os.environ["PATH"].split(os.pathsep):
if os.path.exists(os.path.join(path, 'msql')):
return True
return False | 367fcc0c21803eb2295cd9c7771844e47baddaf1 | 47,883 |
import os
import re
def dashStreamsReady(manifest_path):
"""Wait for DASH streams to be ready.
Return True if the DASH manifest exists and each Representation has at least
one segment in it.
"""
# Check to see if the DASH manifest exists yet.
if not os.path.exists(manifest_path):
return False
# W... | 95a26e3a8b3da458decc43fbd65c455bf5bd93aa | 47,884 |
def has_func(obj, fun):
"""check if a class has specified function: https://stackoverflow.com/a/5268474
Args:
obj: the class to check
fun: specified function to check
Returns:
A bool to indicate if obj has funtion "fun"
"""
check_fun = getattr(obj, fun, None)
return call... | 3284c1a30c3b74c93c1c34c102632beb99bf5576 | 47,885 |
def _make_interp_probe_count_for_dataset_standard_fn(probe_counts,
cover_extension_scale=1.0/10):
"""Generate and return a function that interpolates probe count for a dataset.
This operates only on the mismatches and cover_extension parameters.
Args:
probe_counts: dict giving number of pr... | 893bce0e623a95b7a0524bd44ce7f7856ab3d9e1 | 47,886 |
import pandas
def GenerateSimplePrediction(results, years):
"""Generates a simple prediction.
results: results object
years: sequence of times (in years) to make predictions for
returns: sequence of predicted values
"""
n = len(years)
inter = np.ones(n)
d = dict(Intercept=inter, year... | cb51a096adc7f7d0131c2926b5bf8b2d69aeeb63 | 47,887 |
def write_file_on_mismatched_content(desired_content, target, write):
"""
Write the contents to a new target.
The copy is atomic, ensuring that the target file never exists with
partial contents. The code avoids writing the file if the contents
do not need to be updated. The return value is a boo... | 337cdb8c7c87a6ed6a73fbc42618f71dd411a1f0 | 47,888 |
import torch
def detr_load():
"""
Loads the detr model using resnet50
Returns: the detr model pretrained on COCO dataset
"""
model = torch.hub.load('facebookresearch/detr', 'detr_resnet50', pretrained=True)
model.eval()
return model | 71e20ac9f29ff7211ecb36514758145d929636fc | 47,889 |
def is_string(s):
"""判断是否是字符串
"""
return isinstance(s, basestring) | 57ef8bfc2105365aaeda7559264c98fbd9f34437 | 47,890 |
def check_if_consistent(dfs, cast_info):
"""
checks name and types of columns of each dataframes in 'dfs',
returns False, in case any one of them if found to be inconsistent,
otherwise returns True.
"""
index_names = np.asarray([df.index.name if df.has_index() \
else No... | ced1f0d191a4366ea9fcf6f5481d810b7200a225 | 47,891 |
def _collapse_complexes(data):
"""Given a list or other iterable that's a series of (real, imaginary)
pairs, returns a list of complex numbers. For instance, given this list --
[a, b, c, d, e, f]
this function returns --
[complex(a, b), complex(c, d), complex(e, f)]
The returned list is a... | 4ec889167dbe1ecc2251610f890f21ed18c2db09 | 47,892 |
def find_lottery_winner(root: SumTree, lottery_number: float) -> int:
"""
Find lottery winner index
:param root: the root node of the sum tree
:param lottery_number: float number in range of 0 to 1
:return: winner wallet index
"""
search_number = lottery_number * root.sum
winner = root.... | f0177d69cbe72390396e8daaf4a9de36fb9e4bfa | 47,893 |
def calc_one_dissimilarity_cv(dataset, descriptor, i_des, j_des,
method='euclidean',
noise=None, weighting='number',
prior_lambda=1, prior_weight=0.1,
cv_descriptor=None, enforce_same=False):
"""
... | 5209d9f830733c5d8a213829a0d4672ca6752ee8 | 47,894 |
def get_cron_time_samples(start,stop,samples):
"""Get a comma-separated samples as a
string for cron jobs.
Keyword arguments:
start -- start integer to sample
stop -- stop integer to sample
samples -- number of samples
Returns:
string -- comma-separated list of samples
from the s... | 059002fcd63b58d633c2cdeecd90dc6728b6a4e4 | 47,895 |
def round_up_to_odd(f):
"""round float to the nearest odd integer"""
return np.asarray(np.round((f - 1) / 2) * 2 + 1, dtype=np.int64) | 3a83dd2e53f12e3415441797a933743bf9c40fb8 | 47,896 |
def backend_filter(cls):
"""
Verify that the type proper subclass of BackendModule.
:type cls: type
:rtype: bool
:param cls: A class object
:return: True if match, else false
"""
return issubclass(cls, BackendModule) and cls != BackendModule | edd05f0a9cdc5f040963a894045d37ec382d6202 | 47,897 |
from typing import List
from typing import Dict
from typing import Tuple
def group_force_by_parameter_id(
handler_force: openmm.Force,
parameters: List[SMIRNOFFParameterType],
parameter_map: Dict[str, List[Tuple[int, ...]]],
) -> Dict[str, openmm.Force]:
"""Partitions the parameters in a force into a ... | e9717708d76a8f4e83137b3baf36d18cea39cfb6 | 47,898 |
from io import StringIO
import os
def loadMtlFile(mtllib, texParams=None):
"""Load a material library file (*.mtl).
Parameters
----------
mtllib : str
Path to the material library file.
texParams : list or tuple
Optional texture parameters for loaded textures. Texture parameters a... | 1c5aa4780e1a0093b7c003a27f82bd3dbd292c54 | 47,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.