content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def status(request):
"""
Status page for the Product Database
"""
app_config = AppSettings()
is_cisco_api_enabled = app_config.is_cisco_api_enabled()
context = {
"is_cisco_api_enabled": is_cisco_api_enabled
}
if is_cisco_api_enabled:
# test access (once every 30 minutes... | ef4c2f5444cfa38b46edd5e138531846f3ac04ee | 26,107 |
import torch
from typing import Optional
def _evaluate_batch(
batch: torch.LongTensor, # statements
model: QualifierModel,
column: int,
evaluator: RankBasedEvaluator,
all_pos_triples: Optional[torch.LongTensor], # statements?
relation_filter: Optional[torch.BoolTensor],
filtering_necessa... | 2cba006cf6ceb7ec0941c436cb26cf8b1a34bdeb | 26,108 |
import codecs
def readFile(f):
"""
This helper method returns an appropriate file handle given a path f.
This handles UTF-8, which is itself an ASCII extension, so also ASCII.
"""
return codecs.open(f, 'r', encoding='UTF-8') | b3eb20cf26c6ebe58aec181f1dafc77997f36b6c | 26,109 |
import re
def _RegistryGetValue(key, value):
"""Use _winreg or reg.exe to obtain the value of a registry key.
Using _winreg is preferable because it solves an issue on some corporate
environments where access to reg.exe is locked down. However, we still need
to fallback to reg.exe for the case where the _win... | 5a458b165b999dda809b61433fec0cdfd2eb5a54 | 26,110 |
def reverse_complement_sequence(sequence, complementary_base_dict):
"""
Finds the reverse complement of a sequence.
Parameters
----------
sequence : str
The sequence to reverse complement.
complementary_base_dict: dict
A dict that maps bases (`str`) to their complementary bases
... | 1130f5b321daf72cdd40704fc8671ba331376ded | 26,111 |
def mergeWithFixes(pullRequest: PullRequest.PullRequest, commit_title: str,
commit_message: str, merge_method: str, sha: str):
"""Fixed version of PyGithub merge with commit_title, merge_method, and sha."""
post_parameters = dict()
post_parameters["commit_title"] = commit_title
post_parameters["... | 25709e30d209e18cffe34a6dd09c29d5e2286f08 | 26,112 |
import math
def top2daz(north, east, up):
"""Compute azimouth, zenith and distance from a topocentric vector.
Given a topocentric vector (aka north, east and up components), compute
the azimouth, zenith angle and distance between the two points.
Args:
north (float): the north... | 67a127957b0dc131a6fe5505de05b89871542009 | 26,113 |
import torch
def get_ground_truth_vector(classes : torch.Tensor, n_domains : int,
n_classes : int) -> torch.Tensor:
"""
Get the ground truth vector for the phase where the feature extractor
tries that discriminator cannot distinguish the domain that the sample
comes from.
... | 429c0c69d85572073aab66372d651d4981324e2b | 26,114 |
from numpy import array
from numpy import array, log10
def get_midpoints(ar, mode='linear'):
"""
Returns the midpoints of an array; i.e. if you have the left edge of a set
of bins and want the middle, this will do that for you.
:param ar:
The array or list of length L to find the midpoints of... | 5bb8ccd674d6a1eb71c02ff8577149f495f3bed4 | 26,115 |
def tokenize(text):
"""
INPUT:
text (str): message strings which need to be cleaned
OUTPUT:
clean_tokens: tokens of the messages which are cleaned
"""
# remove punctuations
tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize(text)
tokens = [w for w in tokens if ... | 8d8bf0cc4933bd79db7e59870ae50d33b0fe2fb2 | 26,116 |
import random
import example
def time(is_train):
"""Questions for calculating start, end, or time differences."""
context = composition.Context()
start_minutes = random.randint(1, 24*60 - 1)
while True:
duration_minutes = random.randint(1, 12*60 - 1)
if train_test_split.is_train(duration_minutes) == i... | 19c4726282776db74bac09c76f1c8b59dce99f4d | 26,117 |
def countpaths(pseq, distinct=True, trim=True):
"""
This function returns the number of paths in a path dictionary or list.
The distinct parameter excludes paths that are reverses of other paths
in the count.
The trim parameter excludes loops.
"""
if isinstance(pseq, list):
if not... | 0b15bcdc3277e812cbbc0d51a764269f5db6135a | 26,119 |
def get_all_active_alerts(strategy):
"""
Generate and return an array of all the actives alerts :
symbol: str market identifier
id: int alert identifier
"""
results = []
with strategy._mutex:
try:
for k, strategy_trader in strategy._strategy_traders.items():
... | 85c3f1f43bb701fa6adb7dde8b2bac4423ece143 | 26,120 |
def one_hot_vector(val, lst):
"""
Converts a value to a one-hot vector based on options in lst
"""
if val not in lst:
val = lst[-1]
return map(lambda x: x == val, lst) | 101865c6ddb3fae03838ecdd73d517ca8bd19828 | 26,121 |
def to_rgb(array):
"""Add a channel dimension with 3 entries"""
return np.tile(array[:, :, np.newaxis], (1, 1, 3)) | 1fba6b7ab8a0ea4c4a2b36cfbf6315b1870bcc80 | 26,122 |
import re
import keyword
def is_valid_identifier(string):
"""
Check if string is a valid package name
:param string: package name as string
:return: boolean
"""
if not re.match("[_A-Za-z][_a-zA-Z0-9]*$", string):
return False
if keyword.iskeyword(string):
return False
... | 138d740dbe335f094af46bfe0f8d7b6636311d61 | 26,123 |
from typing import Callable
from typing import Any
import time
def _wait_for_indexer(func: Callable) -> Callable:
"""A decorator function to automatically wait for indexer timeout
when running `func`.
"""
# To preserve the original type signature of `func` in the sphinx docs
@wraps(func)
def w... | 10d3f5070a88ed3c592022442e1fdb1547b8fef7 | 26,124 |
def test10(args):
"""
CIFAR-10 test set creator.
It returns a reader creator, each sample in the reader is image pixels in
[0, 1] and label in [0, 9].
:return: Test reader creator.
:rtype: callable
"""
return reader_creator_filepath(args.data, 'test_batch', False, args) | cf403342c879e6e1a199d21472fd2991ec8c196d | 26,125 |
def get_saver(moving_average_decay, nontrainable_restore_names=None):
"""
Gets the saver that restores the variavles for testing
by default, restores to moving exponential average versions of
trainable variables
if nontrainable_restore_names is set, then restores
nontrainable variables that ma... | ddb3670b323d310a7ab24a7c507d65afa5abfcaa | 26,126 |
def _get_data(preload=False):
"""Get data."""
raw = read_raw_fif(raw_fname, preload=preload, verbose='warning')
events = read_events(event_name)
picks = pick_types(raw.info, meg=True, eeg=True, stim=True,
ecg=True, eog=True, include=['STI 014'],
exclude='bad... | 7fbafeb3a21d653388c35988e26871293e69fb69 | 26,128 |
def make_full_filter_set(filts, signal_length=None):
"""Create the full set of filters by extending the filterbank to negative FFT
frequencies.
Args:
filts (array_like): Array containing the cochlear filterbank in frequency space,
i.e., the output of make_erb_cos_filters_nx. Each row of ``filts`` is a
... | 3d5bdd176ced736c6b06468a90510e9af5a1c635 | 26,129 |
def from_autonetkit(topology):
"""Convert an AutoNetKit graph into an FNSS Topology object.
The current implementation of this function only renames the weight
attribute from *weight* to *ospf_cost*
Parameters
----------
topology : NetworkX graph
An AutoNetKit NetworkX graph
Retur... | a087af7739506d86b91aaaeb31d8db4eb1dcc075 | 26,130 |
def create_default_fake_filter():
"""Return the default temporal, spatial, and spatiotemporal filters."""
nx, ny, nt = get_default_filter_size()
time = np.arange(nt)
return create_spatiotemporal_filter(nx, ny, nt) | 01a64ecd2b599810c61690c67c1539c5126eb160 | 26,131 |
def ClementsBekkers(data, sign='+', samplerate=0.1, rise=2.0, decay=10.0, threshold=3.5,
dispFlag=True, subtractMode=False, direction=1,
lpfilter=2000, template_type=2, ntau=5,
markercolor=(1, 0, 0, 1)):
"""Use Clementes-Bekkers algorithm to find events in... | 242e7cdcbed9b8c85d08a086ed08dd2889756029 | 26,132 |
import re
def extract_words(path_to_file):
"""
Takes a path to a file and returns the non-stop
words, after properly removing nonalphanumeric chars
and normalizing for lower case
"""
words = re.findall('[a-z]{2,}', open(path_to_file).read().lower())
stopwords = set(open('../stop_words.txt'... | 4f5031693d10542c31a3055341d1794d0d7bf4f0 | 26,133 |
import math
def umass_coherence(T, corpus):
"""
Find the UMass coherence of a topic
input:
T (list of strings): topic to find coherence of
"""
sum = 0
# Go through all distinct pairs in the topic
for i, item_i in enumerate(T):
w_i, weight_i = item_i
for... | d92a8f463b123eb62f4732db358cc8e401091c9f | 26,134 |
def get_train_test_sents(corpus, split=0.8, shuffle=True):
"""Get train and test sentences.
Args:
corpus: nltk.corpus that supports sents() function
split (double): fraction to use as training set
shuffle (int or bool): seed for shuffle of input data, or False to just
take the trai... | 796ce26db107f3582e9002a5df7144fbcb2fb960 | 26,135 |
def load_cifar10(filename):
"""
Load the Preprocessed data
"""
features, labels = pckl.load(open(filename, mode="rb"))
return features, labels | 9f6ee68c5b580370e1165287c9a26ab80d666615 | 26,136 |
import unittest
def suite():
"""Gather all the tests from this package in a test suite."""
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(TestBodyEval, "test"))
return test_suite | 2b3c4c642e1964d887e7b3d18db89d0cb69555c3 | 26,137 |
from typing import List
def fetch_quality(data: dict, classification: ClassificationResult, attenuations: dict) -> dict:
"""Returns Cloudnet quality bits.
Args:
data: Containing :class:`Radar` and :class:`Lidar` instances.
classification: A :class:`ClassificationResult` instance.
atte... | 4de1fd337ed31c7b3434458c31aa8bd350b7a8fa | 26,138 |
from typing import Any
def _batch_set_multiple(batch: Any, key: Any, value: Any) -> Any:
"""Sets multiple key value pairs in a non-tuple batch."""
# Numpy arrays and Torch tensors can take tuples and lists as keys, so try to do a normal
# __getitem__ call before resulting to list comprehension.
try:
... | 224c560698bf00e31eb6e9df616773bb7f3ebc5e | 26,139 |
def add_subscription_channel(username, profile_name, device_id, channel):
"""
:param username: Username of a user requesting the data
:param profile_name:
:param device_id:
:param channel:
:return:
"""
def append_channel(subscriptions):
subscriptions.append(channel)
retu... | 62ca9028a46119389bd21182c5aef84671d2ee0e | 26,141 |
def fft2erb(fft, fs, nfft):
"""
Convert Bark frequencies to Hz.
Args:
fft (np.array) : fft bin numbers.
Returns:
(np.array): frequencies in Bark [Bark].
"""
return hz2erb((fft * fs) / (nfft + 1)) | fbc699b3474405a1d939d38389bed62df7545e57 | 26,142 |
def get_activity_id(activity_name):
"""Get activity enum from it's name."""
activity_id = None
if activity_name == 'STAND':
activity_id = 0
elif activity_name == 'SIT':
activity_id = 1
elif activity_name == 'WALK':
activity_id = 2
elif activity_name == 'RUN':
acti... | b5e18063b5448c3f57636daa732dfa2a4f07d801 | 26,143 |
import socket
def is_ipv4(v):
"""
Check value is valid IPv4 address
>>> is_ipv4("192.168.0.1")
True
>>> is_ipv4("192.168.0")
False
>>> is_ipv4("192.168.0.1.1")
False
>>> is_ipv4("192.168.1.256")
False
>>> is_ipv4("192.168.a.250")
False
>>> is_ipv4("11.24.0.09")
... | e81fae435a8e59dbae9ab1805941ce3ba9909ba9 | 26,144 |
from typing import Optional
from typing import Callable
import warnings
def deprecated(help_message: Optional[str] = None):
"""Decorator to mark a function as deprecated.
Args:
help_message (`Optional[str]`): An optional message to guide the user on how to
switch to non-deprecated usage o... | cc353ac874c61e679ebac5c00e85d1266ee831e5 | 26,145 |
def permitted_info_attributes(info_layer_name, permissions):
"""Get permitted attributes for a feature info result layer.
:param str info_layer_name: Layer name from feature info result
:param obj permissions: OGC service permissions
"""
# get WMS layer name for info result layer
wms_layer_name... | 57fcb05e5cd1c7e223c163929e78ecdb00d1ad09 | 26,146 |
def generate_balanced_tree(branching, depth, return_all=False):
""" Returns a DirectedGraph that is a balanced Tree and the root of the tree. (From left to right)
branching = 2, depth = 2
Depth 0 : "ROOT"
Depth 1 : "!#_B0_" "!#_B1_"
Depth 2 : "B0_B0_" "B1_B0_" "B0_B1_" "B1_B1_"
"""
total_siz... | b78f65af8b8609cb6db2e5d7c2cd6da2634c588a | 26,147 |
import string
def rand_ssn():
"""Random SSN. (9 digits)
Example::
>>> rand_ssn()
295-50-0178
"""
return "%s-%s-%s" % (rand_str(3, string.digits),
rand_str(2, string.digits),
rand_str(4, string.digits)) | c878de150989e040683280493b931350e9191d40 | 26,148 |
from typing import Dict
from typing import Any
def cast_arguments(args: Dict[str, Any]) -> Dict[str, str]:
"""Cast arguments.
:param args: args
:return: casted args
"""
casted_args = {}
for arg_name, arg_value in args.items():
casted_args[arg_name] = cast_argument(arg_value)
retur... | bedf813f1b4cb07468bc59c31ac4656757b547f2 | 26,149 |
def lmax_modes(lmax):
"""Compute all (l, m) pairs with 2<=l<=lmax"""
return [(l, m) for l in range(2, lmax + 1) for m in range(-l, l + 1)] | 10ca6d19c2e4f4ffa07cf52c3b6e9b14f8242d09 | 26,150 |
def scale_image(image, flag, nodata_value=VALUE_NO_DATA):
""" Scale an image based on preset flag.
Arguments:
image - 3d array with assumed dimensions y,x,band
flag - scaling flag to use (None if no scaling)
Return:
An image matching the input image dimension with scaling applied to it.
"""... | 03bba109b7e5da098b2ef80beb399daf62dfda20 | 26,151 |
import re
def import_student_to_module(request, pk):
"""
Take .xlsx file, as produced by def:export_student_import_format and retrieve all students and metainformation from it.
Case 1 - Known User - Add the user to the active module edition with the right study and role by making a new Studying object
... | 607341968909fa5442832e7e27c0df9e70020650 | 26,152 |
def adjust_poses(poses,refposes):
"""poses, poses_ref should be in direct"""
# atoms, take last step as reference
for i in range(len(poses)):
for x in range(3):
move = round(poses[i][x] - refposes[i][x], 0)
poses[i][x] -= move
refposes = poses.copy()
return poses, re... | 9bf0ea3a07efdd8666a3482798c28fe5256c5556 | 26,153 |
def eval_validation(
left: pd.DataFrame,
right: pd.DataFrame,
left_on: IndexLabel,
right_on: IndexLabel,
validate: str,
):
"""
Evaluate the validation relationship between left and right and ensures
that the left and right dataframes are compatible with the validation
strategy.
... | 184f73e77133fef751b4aeec6cdfccbca0a817ad | 26,154 |
def get_region_props_binary_fill(heatmapbinary, heatmap):
"""
The function is to get location and probability of heatmap
using ndimage.
:param heatmapbinary: the binarized heatmap
:type heatmap_binary: array
:param heatmap: the original heat_map
:type heatmap: array
:returns: regionprop... | 0b7351e7a52f0c1d71b4839894fb2f71aa4e0774 | 26,156 |
def login_response(request, username, password):
"""
Authenticates user and redirects with the appropriate state.
"""
user = authenticate(username=username, password=password)
if user:
login(request, user)
logger.info("User '{}' logged in.".format(user.username))
return red... | 99c9dc48052a0b99728babd591c0c5e3edae8969 | 26,157 |
def is_metageneration_specified(query_params):
"""Return True if if_metageneration_match is specified."""
if_metageneration_match = query_params.get("ifMetagenerationMatch") is not None
return if_metageneration_match | d37c513f3356aef104e7f6db909d5245e2664c90 | 26,158 |
import functools
def converter(fmt):
"""
Create a converter function for some specific format
Parameters
----------
fmt : str
The format to convert to, e.g. `"html"` or `"latex"`.
Returns
-------
function
"""
return functools.partial(convert, fmt=fmt) | b1ff4830a42eb5ced35205f1041367784eab4be6 | 26,159 |
def createRunner(name, account, user, conf={}):
"""
Creates a reusable spark runner
Params:
name: a name for the runner
account: an account
user: a user
conf: a json encoded configuration dictionary
"""
master = ""
if LOCAL:
master = "local"
else:
... | cf434ddd8b234776eb1269fe461e1f420b8f50ef | 26,160 |
def auth_req_generator(
rf, mocker, rq_mocker, jwks_request, settings, openid_configuration
):
"""Mock necessary functions and create an authorization request"""
def func(id_token, user=None, code="code", state="state", nonce="nonce"):
# Mock the call to the external token API
rq_mocker.pos... | 56990b36dff74a8c27dcb6261066902a83f17184 | 26,161 |
from datetime import datetime
def get_current_time():
"""
Returns the current system time
@rtype: string
@return: The current time, formatted
"""
return str(datetime.datetime.now().strftime("%H:%M:%S")) | 1a3c2ae5427ba53ebdffc08d26e0d0c28643b6ef | 26,162 |
def mock_addon_options(addon_info):
"""Mock add-on options."""
return addon_info.return_value["options"] | 52d20879710e60b4973b302279a624f617bbc6c2 | 26,163 |
from typing import Optional
import torch
from typing import Tuple
def run(
task: Task,
num_samples: int,
num_simulations: int,
num_observation: Optional[int] = None,
observation: Optional[torch.Tensor] = None,
population_size: Optional[int] = None,
distance: str = "l2",
epsilon_decay: ... | ebcec3f8985dd30cbffbfa01cdd6a686123806dc | 26,165 |
def _preprocess_symbolic_input(x, data_format, mode, **kwargs):
"""Preprocesses a tensor encoding a batch of images.
# Arguments
x: Input tensor, 3D or 4D.
data_format: Data format of the image tensor.
mode: One of "caffe", "tf" or "torch".
- caffe: will convert the images f... | 2a42723cc1c61f143b8e1df20622f5d83ce5e719 | 26,166 |
from typing import Dict
def line_column(position: Position) -> Dict[str, int]:
"""Translate pygls Position to Jedi's line / column
Returns a dictionary because this return result should be unpacked as a
function argument to Jedi's functions.
Jedi is 1-indexed for lines and 0-indexed for columns. LSP... | b7f41db9d748b5d3c4f29470d4c5479aa59f95ec | 26,168 |
import math
def rotZ(theta):
""" returns Rotation matrix such that R*v -> v', v' is rotated about z axis through theta_d.
theta is in radians.
rotZ = Rz'
"""
st = math.sin(theta)
ct = math.cos(theta)
return np.matrix([[ ct, -st, 0. ],
[ st, ct, 0. ],
... | 0daf8b021f0011c1bd70adf6c86fb2b91308232a | 26,170 |
import json
def main(event, context):
"""Validate POST request and trigger Lambda copy function."""
try:
body = json.loads(event['body'])
bucket = body['bucket']
project = body['project']
token = body['token']
except (TypeError, KeyError):
return {
"st... | 66742763a71c55006072f99b8c13309bec913cde | 26,171 |
import random
def random_k(word_vectors, k):
"""
:return: ({cluster_id: [cluster elements]})
"""
clusters = defaultdict(list)
for word in word_vectors.vocab:
chosen_cluster = random.randint(0, k-1)
clusters[chosen_cluster].append(word)
return clusters | e22e28f1836f8701edbefb92b16751713f1580af | 26,172 |
from typing import Optional
def get_human_label(scope: str) -> Optional[str]:
"""The the human-readable label for a scope, for display to end users."""
return _HUMAN_LABELS.get(scope) | d3259e5dc3b1ab825c3fe9c3f0a860f0a1ebe7c0 | 26,173 |
import inspect
def lineno():
"""Returns the current line number in our program."""
return str(' - RuleDumper - line number: '+str(inspect.currentframe().f_back.f_lineno)) | c6956415e297b675082913d8e17c606d45a01147 | 26,174 |
def run_simulation(input_dataframe, num_cells_per_module, temperature_series, lookup_table, mod_temp_path,
module_start, module_end, database_path, module_name, bypass_diodes, subcells, num_irrad_per_module):
"""
:param input_dataframe: irradiation on every cell/subcell
:param num_cells_p... | 43c25140d5a619479160d0f723ad7150e82db5b4 | 26,175 |
import six
def qualified_name(obj):
"""Return the qualified name (e.g. package.module.Type) for the given object."""
try:
module = obj.__module__
qualname = obj.__qualname__ if six.PY3 else obj.__name__
except AttributeError:
type_ = type(obj)
module = type_.__module__
... | 02444c19d200650de8dc9e2214f7788fca0befd2 | 26,176 |
def cast_mip_start(mip_start, cpx):
"""
casts the solution values and indices in a Cplex SparsePair
Parameters
----------
mip_start cplex SparsePair
cpx Cplex
Returns
-------
Cplex SparsePair where the indices are integers and the values for each variable match the variable type sp... | df51191d5621cf65d39897ff474785a05ae722d1 | 26,177 |
def encode(value, unchanged = None):
"""
encode/decode are performed prior to sending to mongodb or after retrieval from db.
The idea is to make object embedding in Mongo transparent to the user.
- We use jsonpickle package to embed general objects. These are encoded as strings and can be dec... | c7ab759a5c25199e3de2f5e2a691c09cca77eaa7 | 26,178 |
def ConvertToCamelCase(input):
"""Converts the input string from 'unix_hacker' style to 'CamelCase' style."""
return ''.join(x[:1].upper() + x[1:] for x in input.split('_')) | 8070516c61768ea097eccc62633fc6dea2fa7096 | 26,179 |
from supersmoother import SuperSmoother as supersmoother
def flatten(time,
flux,
window_length=None,
edge_cutoff=0,
break_tolerance=None,
cval=None,
return_trend=False,
method='biweight',
kernel=None,
kernel_s... | 048ae9b148ee0e248e0078ade08c56a641b426e1 | 26,180 |
def frequency(seq, useall=False, calpc=False):
"""Count the frequencies of each bases in sequence including every letter"""
length = len(seq)
if calpc:
# Make a dictionary "freqs" to contain the frequency(in % ) of each base.
freqs = {}
else:
# Make a dictionary "base_counts" to ... | 84f17aef0e02fbc927b4da49dab2e31c6121730d | 26,181 |
def packages(request):
"""
Return a list of all packages or add a list of packages
"""
if request.method == "GET":
package_list = Package.objects.all()
serializer = PackageSerializer(package_list, many=True)
return Response(serializer.data)
if request.method == "POST":
... | 778607965b867578b9df363eee19382bc97078ca | 26,182 |
def progressive_multiple_alignment(
Gs, cost_params, similarity_tuples, method, max_iters,
max_algorithm_iterations, max_entities, shuffle, self_discount,
do_evaluate, update_edges=False):
"""
Merge input graphs one graph at a time using any 2-network alignment method.
Input:
... | ed2353aa196b1666ac8b165f0b758d429e7a5a32 | 26,183 |
def meet_sigalg(dist, rvs, rv_mode=None):
"""
Returns the sigma-algebra of the meet of random variables defined by `rvs`.
Parameters
----------
dist : Distribution
The distribution which defines the base sigma-algebra.
rvs : list
A list of lists. Each list specifies a random va... | c03bbceae5bcec561ffe38ad8df8a85443f84639 | 26,184 |
import json
def ongoing_series():
""" Retrieve all series that are supposedly ongoing.
This call is *very* slow and expensive when not cached;
in practice, users should *never* get a non-cached response.
:return: json list with subset representation of
:class:`marvelous.Series` instances
... | 05eaf4314eda6f4622c7624c6a742d23447a5e31 | 26,185 |
def check_inputs(Y, T, X, W=None, multi_output_T=True, multi_output_Y=True):
"""
Input validation for CATE estimators.
Checks Y, T, X, W for consistent length, enforces X, W 2d.
Standard input checks are only applied to all inputs,
such as checking that an input does not have np.nan or np.inf targe... | f9514eb4d8717dfbd2aae9ef89d50353324f14f8 | 26,186 |
def register(request):
""" Register a new node
"""
if request.method != 'POST':
return HttpResponse("Invalid GET")
#
# Registration requires only the exchange of a PSK.
#
# hash
skey = request.POST.get('skey')
node_id = None
if 'node_id' in request.POST:
node_i... | dd9ce231dfb6ff9c71ccb90595ab6c0cc3d7632d | 26,187 |
def get_tag_messages(tags_range, log_info):
"""
Add tag messages, commit objects and update the max author length in
`log_info`.
Args:
tags_range(list[:class:`~git.refs.tag.TagReference`]): Range of tags to
get information from
log_info(dict): Dictionary containing log infor... | 743705cf191593fda37396e92905742fff3e4e06 | 26,188 |
def _profile_info(user, username=None, following=False, followers=False):
"""
Helper to give basic profile info for rendering the profile page or its child pages
"""
follows = False
if not username or user.username == username: #viewing own profile
username = user.username
if fo... | e4c7bf4397468799c7a3e176f385e6209155c2fa | 26,189 |
def _ProcessMergedIntoSD(fmt):
"""Convert a 'mergedinto' sort directive into SQL."""
left_joins = [
(fmt('IssueRelation AS {alias} ON Issue.id = {alias}.issue_id '
'AND {alias}.kind = %s'),
['mergedinto'])]
order_by = [(fmt('ISNULL({alias}.dst_issue_id) {sort_dir}'), []),
(fm... | 290dd7e79f936f5d125a12a5bb920c65f1812296 | 26,190 |
def Plot3DImage(rgb_image,depth_image,sample=True,samplerate=.5,ignoreOutliers=True):
"""
Input:
rgb_image[pixely,pixelx,rgb] - Standard rgb image [0,255]
depth_image[pixely,pixelx,depth] - Image storing depth measurements as greyscale - 255=5m, 0=0m
sample(Bool) - Plot full image or... | 0b5ee3abde0255d6a853afbf31f12d72c9aef809 | 26,192 |
def smooth_curve(x, y, npts=50, deg=12):
"""Smooth curve using a polyfit
Parameters
----------
x : numpy array
X-axis data
y : numpy array
Y-axis data
npts : int
Optional, number of points to resample curve
deg : int
Optional, polyfit degree
Returns
... | 998ffaa0dfd9fc2d2e0f04e7f0d8a5fa8fe00943 | 26,193 |
def gather_allele_freqs(record, samples, males_set, females_set, parbt, pop_dict, pops,
sex_chroms, no_combos=False):
"""
Wrapper to compute allele frequencies for all sex & population pairings
"""
# Add PAR annotation to record (if optioned)
if record.chrom in sex_chroms an... | 8e7b1f605d6473e77128806e4e6c64e3a338fff5 | 26,194 |
from datetime import datetime
import json
def get_history_events_closest():
""" Получение полного списка страниц в json"""
try:
event_schema = HistoryEventsSchema(many=True)
datef = datetime.today()
further_date = datef + timedelta(days=14)
if further_date.year > datetime.toda... | a35cab21c9fbd18ff8c31fc08760995ce1d22158 | 26,195 |
def get_archive_url(url, timestamp):
"""
Returns the archive url for the given url and timestamp
"""
return WEB_ARCHIVE_TEMPLATE.format(timestamp=timestamp.strftime(WEB_ARCHIVE_TIMESTAMP_FORMAT), url=url) | a7b79868ccaf1244591b8b5ffec7ac8ff2310772 | 26,196 |
import requests
import json
import pprint
def get_text(pathToImage):
"""
Accesses API to get json file containing recognized text
"""
print('Processing: ' + pathToImage)
headers = {
'Ocp-Apim-Subscription-Key': API_KEY,
'Content-Type': 'application/octet-stream'
}
params = ... | 037f22c0fda02ddb7df59def274395c537b67369 | 26,197 |
def match_summary(df):
""" summarize the race and ethnicity information in the dataframe
Parameters
----------
df : pd.DataFrame including columns from race_eth_cols
"""
s = pd.Series(dtype=float)
s['n_match'] = df.pweight.sum()
for col in race_eth_cols:
if col in df.columns:
... | 5886563d59426f952542bdf5ae579b612475b934 | 26,198 |
def parse_git_version(git) :
"""Parses the version number for git.
Keyword arguments:
git - The result of querying the version from git.
"""
return git.split()[2] | f4af03f0fad333ab87962160ed0ebf5dcbeea22a | 26,199 |
def onRequestLogin(loginName, password, clientType, datas):
"""
KBEngine method.
账号请求登陆时回调
此处还可以对登陆进行排队,将排队信息存放于datas
"""
INFO_MSG('onRequestLogin() loginName=%s, clientType=%s' % (loginName, clientType))
errorno = KBEngine.SERVER_SUCCESS
if len(loginName) > 64:
errorno = KBEngine.SERVER_ERR_NAME
if len(... | 08c428f5ac27e009b9d1ffe1af9daee1c5cca2f1 | 26,200 |
import logging
from typing import Callable
from typing import Any
def log_calls(
logger: logging.Logger, log_result: bool = True
) -> GenericDecorator:
"""
Log calls to the decorated function.
Can also decorate classes to log calls to all its methods.
:param logger: object to log to
"""
... | 43e71d224ed45a4f92ddda5f4ac042922b254104 | 26,201 |
def bag(n, c, w, v):
"""
测试数据:
n = 6 物品的数量,
c = 10 书包能承受的重量,
w = [2, 2, 3, 1, 5, 2] 每个物品的重量,
v = [2, 3, 1, 5, 4, 3] 每个物品的价值
"""
# 置零,表示初始状态
value = [[0 for j in range(c + 1)] for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, c + 1):
value[i][... | 27dd9c5f9367afe865686c8f68853bc966bcdaa6 | 26,202 |
def _to_bytes(key: type_utils.Key) -> bytes:
"""Convert the key to bytes."""
if isinstance(key, int):
return key.to_bytes(128, byteorder='big') # Use 128 as this match md5
elif isinstance(key, bytes):
return key
elif isinstance(key, str):
return key.encode('utf-8')
else:
... | 8df22eb02674cb61ef0e8a413f1eed7dc92f0aef | 26,203 |
def _online(machine):
""" Is machine reachable on the network? (ping)
"""
# Skip excluded hosts
if env.host in env.exclude_hosts:
print(red("Excluded"))
return False
with settings(hide('everything'), warn_only=True, skip_bad_hosts=True):
if local("ping -c 2 -W 1 %s" % machin... | 114b9b708d81c6891a2f99c5c600d9d4aa59c138 | 26,204 |
def get_expectation_value(
qubit_op: QubitOperator, wavefunction: Wavefunction, reverse_operator: bool = False
) -> complex:
"""Get the expectation value of a qubit operator with respect to a wavefunction.
Args:
qubit_op: the operator
wavefunction: the wavefunction
reverse_operator: ... | e0e634bc6c0d5c9d5252e29963333fac3ccc3acd | 26,207 |
def create_proxy_to(logger, ip, port):
"""
:see: ``HostNetwork.create_proxy_to``
"""
action = CREATE_PROXY_TO(
logger=logger, target_ip=ip, target_port=port)
with action:
encoded_ip = unicode(ip).encode("ascii")
encoded_port = unicode(port).encode("ascii")
# The fir... | 006ae25e069f3ac82887e9071170b334a0c6ea74 | 26,208 |
def get_output_shape(tensor_shape, channel_axis):
"""
Returns shape vector with the number of channels in the given channel_axis location and 1 at all other locations.
Args:
tensor_shape: A shape vector of a tensor.
channel_axis: Output channel index.
Returns: A shape vector of a tensor... | 7c7058c2da9cb5a4cdb88377ece4c2509727894a | 26,209 |
import numbers
def process_padding(pad_to_length, lenTrials):
"""
Simplified padding interface, for all taper based methods
padding has to be done **before** tapering!
Parameters
----------
pad_to_length : int, None or 'nextpow2'
Either an integer indicating the absolute length of
... | b018e32c2c12a67e05e5e324f4fcd8547a9d992b | 26,210 |
from ..constants import asecperrad
def angular_to_physical_size(angsize,zord,usez=False,**kwargs):
"""
Converts an observed angular size (in arcsec or as an AngularSeparation
object) to a physical size.
:param angsize: Angular size in arcsecond.
:type angsize: float or an :class:`AngularSepa... | 80fbd5aa90807536e06157c338d86973d6050c7c | 26,211 |
def is_tuple(x):
"""
Check that argument is a tuple.
Parameters
----------
x : object
Object to check.
Returns
-------
bool
True if argument is a tuple, False otherwise.
"""
return isinstance(x, tuple) | ac129c4ab7c6a64401f61f1f03ac094b3a7dc6d4 | 26,213 |
def find_verbalizer(tagged_text: str) -> pynini.FstLike:
"""
Given tagged text, e.g. token {name: ""} token {money {fractional: ""}}, creates verbalization lattice
This is context-independent.
Args:
tagged_text: input text
Returns: verbalized lattice
"""
lattice = tagged_text @ ver... | fef98d7a2038490f926dc89fc7aefbbda52ed611 | 26,214 |
def get_color_pattern(input_word: str, solution: str) -> str:
"""
Given an input word and a solution, generates the resulting
color pattern.
"""
color_pattern = [0 for _ in range(5)]
sub_solution = list(solution)
for index, letter in enumerate(list(input_word)):
if letter == solution... | a8746a5854067e27e0aefe451c7b950dd9848f50 | 26,215 |
import inspect
def getargspec(obj):
"""Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments ... | bcfe75de95ccf22bcefdba52c8556f0722dbbcb7 | 26,216 |
def nearest(x, xp, fp=None):
"""
Return the *fp* value corresponding to the *xp* that is nearest to *x*.
If *fp* is missing, return the index of the nearest value.
"""
if len(xp) == 1:
if np.isscalar(x):
return fp[0] if fp is not None else 0
else:
return np.a... | 77ebcb08adbc5b1a70d801c7fe1f4b31f1b14717 | 26,217 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.