content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_affiliate_empty(affiliate_obj):
"""
Check for an empty Affiliate object to detect for empty Excel rows.
:param affiliate_obj: Affiliate
:return: Boolean
"""
if affiliate_obj.affiliate_name is None \
and affiliate_obj.is_accs is False \
and affiliate_obj.is_pcp is F... | 3e87f8dd9d9123780753eeed3ea480e90f97d013 | 644,195 |
def score_defaults(gold_labels):
"""
Compute the "all false" baseline (all labels as unrelated) and the max
possible score
:param gold_labels: list containing the true labels
:return: (null_score, best_score)
"""
unrelated = [g for g in gold_labels if g['Stance'] == 'unrelated']
null_sco... | 7c3f794f364975a5090892e1d60d7142695573db | 644,197 |
from typing import List
import requests
import string
def get_public_suffixes() -> List[str]:
"""
Retrieves an extensive list of public suffixes used and filters out non
ASCII suffixes. In case of any issues connecting to the website this
function returns a much less comprehensive builtin list.
""... | 24993476cba0ddec3f60cd72e745a77874e37b20 | 644,200 |
def strip_right_above_below(chars):
"""Drop leading and trailing blank lines, and drop trailing spaces in each line"""
lines_plus = chars.splitlines()
lines = list(_.rstrip() for _ in lines_plus)
while lines and not lines[0]:
lines = lines[1:]
while lines and not lines[-1]:
lines ... | bef9218dc7a2aed5ca9beae40246cbd6542bf11a | 644,205 |
import csv
def get_max_node_id(nodes_file):
"""
Examines the 'nodes_file' passed in and finds the value of
highest node id.
It is assumed the 'nodes_file' a tab delimited
file of format:
<CLUSTER NAME> <# NODES> <SPACE DELIMITED NODE IDS> <SCORE>
:param nodes_file:
:type nodes_file:... | 76a580eba12767a113f288cf367de834d5b4b104 | 644,209 |
def get_verbose_field_name(instance, field_name):
"""
Get the verbose_name for a field in a model instance
Parameters
----------
instance : Django models.Model
An instance of any sub-class of a Django models.Model
field_name : str
Name of the field to return the verbose field na... | 3d1dd01270857ef3215b88b5a7c31e7655906f95 | 644,212 |
def _split_channels(num_chan, num_groups):
"""Split range(num_chan) in num_groups intervals. The first one is larger if num_chan is not a multiple of num_groups"""
split = [num_chan // num_groups for _ in range(num_groups)]
# add the remaining channels to the first group
split[0] += num_chan - sum(split... | 9546d317f297584167a411b2702d442553f5bffa | 644,213 |
def get_instances_joined(game, player):
""" Return the instance ids of instance that player has joined.
Args:
game: The parent Game database model to query for instances.
player: The email address of the player to look for in instances.
Returns:
An empty list if game is None. Else, returns a list of... | 3c968b614d15d2986c076588fa24a4ee3d1b1ca2 | 644,220 |
def is_subset(a, b):
"""Test whether every element in a is also in b."""
return set(a).issubset(set(b)) | da8c42d9299b4e37d6f71a23c84e51506e69fb0e | 644,229 |
def read_ppm_header(fp, filename):
"""Read dimensions and headersize from a PPM file."""
headersize = 0
magic_number = fp.readline()
if magic_number != "P6\n":
raise TypeError("Hey! Not a ppm image file: %s" % filename)
headersize += len(magic_number)
comment = fp.readline()
if comment[0] == "#":
... | 0b7540ad5dc505e313393e9d6a5f870fb95185fa | 644,230 |
def readFile(nam):
"""
Read a file and return its content as a string.
"""
f = open(nam,"r")
s = f.read()
f.close()
return s | 35a7b1f044807872ab514ef08b46e91646415b7e | 644,231 |
def top_players_stat(fifa_df, stat, no_of_players):
"""
Returns the top x no players in a stat
Parameters
----------
fifa_df
The fifa versions players (df)
no_of_players
The number of players to return (int)
stat
The stat to sort by (str)
Returns
-------
... | 989dcc66e62236a797915fd25dd85c00a0fb6ca8 | 644,233 |
def get_the_node_dict(G, name):
"""
Helper function that returns the node data
of the node with the name supplied
"""
for node in G.nodes(data=True):
if node[0] == name:
return node[1] | d73db645177f00377ae1f202181b69d2f51d540b | 644,237 |
def make_kw(bbox, time_range):
"""Make kw for search.
Parameters
----------
bbox: list
Geographic bounding box: [min_lon, min_lat, max_lon, max_lat]
time_range: list
[start_time, end_time] where each are strings that can be interpreted
with pandas `Timestamp`.
Returns
... | 887a41a65454284c82e00c76b3864313e7bb4549 | 644,240 |
def slice_text(text,
eos_token="<s>",
sos_token="</s>"):
"""Slices text from <s> to </s>, not including
these special tokens.
"""
eos_index = text.find(eos_token)
text = text[:eos_index] if eos_index > -1 else text
sos_index = text.find(sos_token)
text = text[sos_index+len(so... | 1c53cf904b44580ba9e63c293fff3a674c349267 | 644,242 |
def after_userlogin_hook(request, user, client):
"""Marks Django session modified
The purpose of this function is to keep the session used by the
oidc-provider fresh. This is achieved by pointing
'OIDC_AFTER_USERLOGIN_HOOK' setting to this."""
request.session.modified = True
# Return None to c... | 8106da9387c9e2e4bac08aebe06b0e96bf1b0288 | 644,248 |
def dist_rgb(rgb1, rgb2):
"""
Determine distance between two rgb colors.
:arg tuple rgb1: RGB color definition
:arg tuple rgb2: RGB color definition
:returns: Square of the distance between provided colors
:rtype: float
This works by treating RGB colors as coordinates in three dimensional
... | fe170840d543d9be9347d6055631987f622daaff | 644,251 |
import yaml
def load_config(path):
"""Load yaml collection configuration."""
with open(path, 'r') as stream:
return yaml.load(stream, Loader=yaml.SafeLoader) | 4beb9fff0d471bb23e06b55e18f4d286263fbd4e | 644,258 |
def build_param_bul (param):
""" Builds a configuration parameter documentation bullet from a parameter tuple.
Args:
param (tuple): The parameter tuple.
Returns:
string: The documentation bullet markdown.
"""
return param[0] + ' (' + param[1] + '): ' + param[2] | 439921cd3ef588afebc000a2cdf2559711baab3e | 644,259 |
def output_fn(prediction, response_content_type):
"""
Return model's prediction
"""
return {'generated_text':prediction} | 7be30483787747191b458f46b8d4fc215a0e7de0 | 644,263 |
def first(sequence, condition=None):
"""
Returns the first item in a sequence that satisfies specified condition or
raises error if no item found.
Args:
sequence: iterable
Sequence of items to go through.
condition: callable
Condition to test.
... | 879c3aaf4d07e367e275227c963422f021be509f | 644,265 |
def to_signed_byte(num):
"""
Convert given byte number to signed byte number.
:param num: Unsigned byte number in range from 0 to 255.
:return: Signed number in range from -128 to 127.
"""
assert 0 <= num <= 255, 'Value out of range (0 - 255): {0}!'.format(num)
if num <= 127:
ret =... | 174e30041921cefe02576951e3009541b228bf1e | 644,267 |
import sqlite3
from typing import Any
def transaction(conn: sqlite3.Connection,
sql: str, *args: Any) -> sqlite3.Cursor:
"""Perform a transaction.
The transaction needs to be committed or rolled back.
Args:
conn: database connection
sql: formatted string
*args: ar... | c9a27edd532fe40661b8ddab2010f45d58b1b57a | 644,268 |
def non_none_dict(d):
"""return a copy of the dictionary without none values."""
return dict([a for a in d.items() if a[1] is not None]) | ab8ed0be802282864f801fb6a42a085946d5eab1 | 644,270 |
def java_class_params_to_key(package: str, class_name: str):
"""Returns the unique key created from a package and class name."""
return f'{package}.{class_name}' | aa602033da7618d5454eb7d7b493508fcf3103c9 | 644,271 |
def create_symbol(
client, symbol_file, point, drawing=None, replace_values=None, sheet=None
):
"""Add a symbol instance to a drawing.
Args:
client (obj):
creopyson Client
symbol_file (str):
Name of the symbol file.
point (dict):
Coordinates for t... | 82a90571de8f3a988659d6da8b20afe37044c8eb | 644,272 |
from typing import Set
def get_all_subclasses(cls: type) -> Set[type]:
"""Return all subclasses of a give cls class."""
return set(
cls.__subclasses__()).union(
[s for c in cls.__subclasses__() for s in get_all_subclasses(c)]
) | 3d531ebf8f26fe5e79da17c32d039d963d38f009 | 644,273 |
def get_containers(client, pod, namespace):
"""
makes a request against the Kubernetes api and extracts the names of pod's containers
:param client the Kubernetes api client
:param str pod: the name of the pod
:param str namespace: the namespace where to search for the pod
:return: the... | 1aee93569fbf348a48ee2b1ac9f4ae0bde6d115a | 644,275 |
def uniqueify(items):
"""Return a list of the unique items in the given iterable.
Order is NOT preserved.
"""
return list(set(items)) | b7b85edd311ec261e1db47c17386afaa44a08088 | 644,278 |
import pathlib
import hashlib
def _md5(file: pathlib.Path) -> str:
"""Calculates the MD5 hash code of a file for integrity."""
hash_md5 = hashlib.md5()
with file.open("rb") as f:
# Read and update hash string value in blocks of 4K
for chunk in iter(lambda: f.read(4096), b""):
h... | 189c209f1278cab2e2d81aaf6dbe2175f3b09560 | 644,284 |
def print_nums_opt(*numbers: int) -> str:
"""Fill numbers with zeros (optimizible).
Args:
*numbers: <int> sequence of numbers
Returns: zero filled string.
Examples:
>>> assert print_nums_opt(11, 12, 23) == '11 12 23'
"""
return ' '.join(str(num).zfill(len(max(str(num)))) for n... | 44481e557eaa87463ac3d79ebb1ce22030ad7bae | 644,285 |
def unnormalize(z, bounds):
"""Inverse of normalize"""
return z * (bounds[:, 1] - bounds[:, 0]) + bounds[:, 0] | 9a39768cdaaa1c169ea88b8dfcb5080a38b9e358 | 644,289 |
def parse_nsvca(nsvca):
"""
Take module name, stream, version, context and architecture in a N:S:V:C:A
format and return them as a separate values.
"""
split = nsvca.split(":")
if len(split) != 5:
raise ValueError("N:S:V:C:A in unexpected format")
split[2] = int(split[2])
return ... | a8fc0d8b679c998b7984db09d3a987626f6acf82 | 644,295 |
def pic_flag(compiler=None):
"""
returns PIC (position independent code) flags, such as -fPIC
"""
if not compiler or compiler == 'Visual Studio':
return ""
return '-fPIC' | 2419c84c9395bb2085b13ba9e8784d415897981e | 644,296 |
import json
def read_json(file_path):
"""Read json file from file_path."""
with open(file_path, encoding="utf-8", errors="surrogateescape") as f:
return json.load(f)["data"] | 67a1634b5465fe8e82e1566f47c32ce7cc48d3a9 | 644,299 |
def ignore_exception(*exception_classes):
"""
A function decorator to catch exceptions and pass.
@ignore_exception(ValueError, ZeroDivisionError)
def my_function():
...
Note that this functionality should only be used when you don't care about
the return value of the functi... | 2e007f124c84843c0abf0956a1b2b7326d7b4ec7 | 644,303 |
def ring_to_vector(z_list: list, max_size: int = 9) -> list:
"""
Convert the ring sizes vector to a fixed length vector
For example, l can be [3, 5, 5], meaning that the atom is involved
in 1 3-sized ring and 2 5-sized ring. This function will convert it into
[ 0, 0, 1, 0, 2, 0, 0, 0, 0, 0].
Arg... | c90966efe5cbc2e9222a3ed3a69a620eaccd0c49 | 644,304 |
def mag(db_image):
"""Reverse of log/db: decibel to magnitude"""
return 10 ** (db_image / 20) | 6f8271e4e7f785a881a15f3f8fac141a02557348 | 644,308 |
from typing import Any
from typing import Optional
from typing import Tuple
from typing import Dict
import inspect
def gather_init_params(
obj: Any,
ignore: Optional[Tuple[str, ...]] = None,
) -> Dict[str, Any]:
"""Extract the parameters passed to an object's ``__init__()``.
Args:
obj (object... | 8299fd24cadfdf08e38b2f55b82ef88c0792ae13 | 644,313 |
def pythonize(t):
""" Make valid fields ints, essentially deserialize """
t["retweet"] = True if t["retweet"] == "True" else False
t["likes_count"] = int(t["likes_count"])
t["replies_count"] = int(t["replies_count"])
t["retweets_count"] = int(t["retweets_count"])
t["photos"] = t["photos"].split(",")
t["hashtags"... | aa859f74b3967a3149484dbfd60f25b0914fad80 | 644,320 |
def check_required_params(req, keys):
"""
Helper to check if all valid params are present
"""
for key in keys:
if key not in req.keys():
return False
return True | 7e0456f7461d2c266f1f6dc44369eb560ccbb15c | 644,323 |
import torch
import math
def mu_transform(x):
""" Forward operation of mu-law transform for 16-bit integers. """
assert x.min() >= -1 and x.max() <= 1
return torch.sign(x) * torch.log(1 + 32768. * torch.abs(x)) / math.log(1 + 32768.) | b652847ed06384ce059c1095988ae3487e900d01 | 644,326 |
def max_min_layers(nx_graph, max_layer=True):
"""
Returns the maximal (highest in hierarchy) layer (those nodes with in degree = 0) or the minimal layer (k_out = 0)
:param nx_graph: networkX graph
:param max_layer: Bool, if True, returns maximal layer (k_in = 0), else returns nodes for which k_out = 0, ... | 108bb64fd8f14d780173214e1629d00a9b1d3f72 | 644,328 |
def check_balanced_parens(parens):
"""
Given that a string can be composed of parentheses, brackets,
and curly braces, check whether an input string has balanced
brackets.
"""
matches = {
'}': '{',
')': '(',
']': '[',
}
ls = []
for paren in parens:
i... | 655823f8e3278ec40ea8e3797e4e306e7d01f809 | 644,332 |
def read_file_lines(file):
"""Returns a list of str lines in text file"""
with open(file, mode="rt", encoding="utf-8") as f:
return f.readlines() | dac8acbf25c7c9833f20b913d4aff068afa57fa9 | 644,334 |
def name(layer):
"""Returns the class name of a protocol layer."""
return layer.__class__.__name__ | 1f2993fd9c00cea020898e15fb78adc912663f8a | 644,335 |
import torch
def training_collate(batch):
"""Custom collate fn for dealing with batches of images.
Arguments:
batch: (tuple) A tuple of tensor images
Return:
(tensor) batch of images stacked on their 0 dim
"""
# imgs = list()
# for img in batch:
# _c, _h, _w = img.sha... | 0a0fa8e41d2ed3cd77e53118fc4635f672ac5aa9 | 644,336 |
def frequency_to_probability(counts_table):
"""
Convert a contingency table expressed in frequencies to one
expressed in probabilities.
"""
total = counts_table.sum()
probs_table = counts_table / float(total)
return probs_table | 395e4fc4403d6a01d6f6d17746351c5f829433f9 | 644,339 |
def top_preds(preds, labels, k=5):
"""
Top 1 and top k precision
:param preds: Softmax output tensor with probabilities
:param labels: Labels in batch
:param k: top k precision, default top5
:return:
"""
correct = 0
topk = 0
for i in range(len(labels)):
classes = (-preds... | 273f67d72509f62a6f00391588bc5a54149ab920 | 644,340 |
import yaml
def get_input_files(cfg, index=0):
"""
Load input configuration file.
Get a dictionary with input files from the metadata.yml files.
"""
metadata_file = cfg['input_files'][index]
with open(metadata_file) as input_file:
metadata = yaml.safe_load(input_file)
return metad... | 3a65bcc019972de83ada05d70d8cfe04d520127e | 644,342 |
from typing import List
def gauss_points(
n: float,
) -> List[List[float]]:
"""Returns the Gaussian weights and locations for *n* point Gaussian integration of
a linear triangular element.
:param int n: Number of Gauss points (1, 3 or 6)
:return: An *n x 3* matrix consisting of the integration w... | 393faa2733a5e34b25cf5ea2ecab725e1856ec3d | 644,348 |
def get_game_info(game):
"""
Gets printable game information.
"""
return (
"%d (%s: %s [%d] vs. %s [%d])" % (
game['game_id'], game['date'], game['home_team'], game['home_score'], game['road_team'], game['road_score'],
)) | f54027c7a8e094288ba1959b6f222526ebb5c579 | 644,353 |
def scaleData(features):
"""
Normalizes features in order for gradient descent to work correctly (improves the convergence speed of the logistic regression algorithm)
features is an arg containing the sample of feature data to be normalized
Normalization is made using Rescaling (min-max normalization) ... | f784490423ec92e17b69a3720d1785b359711767 | 644,355 |
def _GetColFormatString(width, align_right):
"""Returns the format string for a field.
"""
if align_right:
sign = ""
else:
sign = "-"
return "%%%s%ss" % (sign, width) | 93febf83be8cd467ac7a70acb7e8816c12068f6d | 644,360 |
import re
def parse_vocab_test(text):
"""
Parse the following structure into list of vocab tokens
Input:
..
..
..
Output:
[result,
hair,
strong,
tear,
..
..
..
]
"""
text = re.sub(' ?\d+ \xef\x81\xb1 ?', '\n', text)
text = re.sub(' ?\d+ ... | 5687bc78588db37f9909946619861819452b51b0 | 644,362 |
def AddNodeVersionFlag(parser, hidden=False):
"""Adds a --node-version flag to the given parser."""
help_text = """\
The Kubernetes version to use for nodes. Defaults to server-specified.
The default Kubernetes version is available using the following command.
$ gcloud container get-server-config
"""
return ... | 33bc8311ec77d75fae77c8bbe9b4fdd324f0cd42 | 644,363 |
def match_keypoints(optical_flow, prev_kps):
"""Match optical flow keypoints
:param optical_flow: output of cv2.calcOpticalFlowPyrLK
:param prev_kps: keypoints that were passed to cv2.calcOpticalFlowPyrLK to create optical_flow
:return: tuple of (cur_matched_kp, prev_matched_kp)
"""
# 当前帧的角点,状态... | bd05ca28e05c2417cb774ff352ae35ed4d036f5e | 644,370 |
from pathlib import Path
def default_dataset_location(dataset_name: str) -> Path:
"""
Return the default location of a dataset.
This currently returns "~/.avalanche/data/<dataset_name>" but in the future
an environment variable bay be introduced to change the root path.
:param dataset_name: The ... | 296a5022d7e4f1542265937c104a883b1f075abc | 644,373 |
def get_km_user_image_upload_path(km_user, imagename):
"""
Get the path to upload the kmuser image to.
Args:
km_user:
The km_user whose image is being uploaded.
imagename (str):
The original name of the image being uploaded.
Returns:
str:
The... | 01b350177f9d605b508debc5c391964dffcaf5e1 | 644,382 |
def peak(lst: list[int]) -> int:
"""
Return the peak value of `lst`.
>>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1])
5
>>> peak([1, 10, 9, 8, 7, 6, 5, 4])
10
>>> peak([1, 9, 8, 7])
9
>>> peak([1, 2, 3, 4, 5, 6, 7, 0])
7
>>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2])
4
"""
# mid... | 59b6feeb91324a6caeb721756a778f52510f5c03 | 644,386 |
def get_country_lat_lon_extent(country):
"""
See https://data.humdata.org/dataset/bounding-boxes-for-countries/resource/aec5d77d-095a-4d42-8a13-5193ec18a6a9
Args:
country:
Returns: longitude(left) longitude(right), latitude (bottom), latitude(top)
"""
#
# 'mexico', 'south_africa', ... | d6e5d5c833f33244ee1e02b1b1aafbcad7f836a1 | 644,390 |
from pathlib import Path
import re
def test_versions(run):
"""Test versions.
config.json - contains the HASS addon version
Dockerfile - installs the specific sunsynk library from pypi
setup.py - sunsynk library on pypi
"""
def _get_version(filename, regex):
txt = Path(filename).r... | ad5bb7751272f9a62295e4526540aad6ce92a345 | 644,391 |
def hdu_get_time(hdu, time_format='bmjd'):
"""
Will be used as a key function for the list.sort() or sorted() functions.
Example,
hdus.sort(key=hdu_fits_by_time)
where hdus is a list of HDU objects, will call hdu_by_time() on each element
in the list, and then sort the elements according t... | d51f06b584eb2f26ede7a002eb44dd65e331bfbd | 644,394 |
def title_case(f_name, l_name):
"""
Take a first name and last name and format it
to return the title case version.
"""
if f_name == "" or l_name == "":
return "You didn't provide valid inputs"
f_name = f_name.lower()
l_name = l_name.lower()
f_name_T = ("{:s}{:s}".format(f_name[... | d8d187f8ab9dd278333027c5e42b912aa949b9b5 | 644,396 |
def is_nt_arc_present(rtn, nt_arc_label):
"""
Check if rtn contains nonterminal arc with label nt_arc_label.
:param rtn: RTN FST object
:param nt_arc_label: Nonterminal arc label
:return: Boolean
"""
nt_arc_label = int(nt_arc_label)
for state in rtn.states:
for arc in state.arc... | a51ce978f00445e11c8a91d6e51d722838729085 | 644,398 |
import heapq
def largest_export_versions(n):
"""Creates a filter that keeps the largest n export versions.
Args:
n: number of versions to keep.
Returns:
A filter function that keeps the n largest paths.
"""
def keep(paths):
heap = []
for idx, path in enumerate(paths):
if path.export_... | 7bdf48e894c7eaf7256d23b81e76d2e486e89289 | 644,399 |
def build_extracted_list(input_list, subinterval):
""" A utility function to extract a number of elements from a list, leaving only a certain subset.
Generates a new list with just the subset. Creates the subset by specifying a sub-interval.
:param input_list: The list to be extracted
:type input_l... | 8e9bf9c9ac407a7976d4ec3a16f1dd36aed8af48 | 644,400 |
def subject_destroy(client, subject_id):
"""Destroy the subject or raise if it does not exist."""
return client.subject_destroy(subject_id=subject_id) | 71f531cdf64f0758cad719022e0fac6bc08a0afa | 644,401 |
from typing import Dict
from typing import Any
def convert_drive_files_old_to_new(old: Dict[str, Any]) -> Dict[str, Any]:
"""Convert data from the original format (which had "answers-cleaned" field) to a clearer format."""
question_id = old["questionid"]
raw = old["raw-original-answers"]
clusters = {
... | 32189bbda13a129306f0d4432350e686f587f6ff | 644,402 |
def inclusion_explicit_no_context(arg):
"""Expected inclusion_explicit_no_context __doc__"""
return {"result": "inclusion_explicit_no_context - Expected result: %s" % arg} | 2e0880d3940c961f6ccc2715e7fa300f9b969787 | 644,403 |
def measurement_id(measurement_uuid: str, agent_uuid: str) -> str:
"""
Measurement IDs used by Iris
>>> measurement_id("57a54767-8404-4070-8372-ac59337b6432", "e6f321bc-03f1-4abe-ab35-385fff1a923d")
'57a54767-8404-4070-8372-ac59337b6432__e6f321bc-03f1-4abe-ab35-385fff1a923d'
Measurement IDs used by... | 95a9c98213542b8ad21f0bbf8c015f584e9c8822 | 644,405 |
def fourier_make_response_real(response):
"""
Turn a frequency filter function into a real one (in the time domain).
Done by reflecting and complex conjugating positive frequency part to negative frequencies.
`response` is a function with a single argument (frequency), return value is a modified fu... | ba2a99e479470027a4890be3d97f9a204607afa1 | 644,413 |
def get_avatar(member):
"""Returns default avatar, if custom doesn't exist"""
if member.avatar_url:
return member.avatar_url
return member.default_avatar_url | 77b442815ac813527a8d19448601e2dcfd8aade7 | 644,414 |
def transform_tone(tone):
"""Transforms keyword `negative`, `neutral` or `positive` into `-1`, `0` or `1`.
:param tone: string representation of tone.
:type tone: str
:return: number representation of tone.
:rtype: str
"""
if 'negative':
return '-1'
elif 'neutral':
retu... | 036a3de752bffd3f97636e132c5ce80aae7ee2c2 | 644,417 |
def update_param_grid(param_grid, sizes):
"""Update parameters of the grid search.
Args:
param_grid: current grid search dictionary
sizes: dataset.shape
Returns:
param_grid: updated grid search dictionary
"""
if 'h_units' in param_grid.keys():
# NN and simple_linear data
if sizes[1] > 1:
... | 54e40e6349dcacffa042d9a6d697319ff862ba31 | 644,419 |
def polynomial_mul_polynomial(a, b):
"""
Multiplication function of two polynomials.
:param a: First polynomial.
:param b: Second polynomial.
:return: The result of multiplication two polynomials
"""
number_type = type(a[0]) if a else type(b[0]) if b else float
len_a, len_b = len(a), len... | 80f3755e59f263460f1ef20d1521ca777de2169c | 644,422 |
def normalize_GSC_weights(weights_dict, rooted_tree):
"""
This is a novel (I believe) normalization scheme that I came up with to re-scale
GSC weights. It simply divides the weight for each terminal by the overall depth of that
terminal and therefore can/should(?) be thought of as a % independence.
... | 64cd87c020b376d861c4ff759e6d2e0d671be9ee | 644,426 |
def get_attribute(node_id, runtime_property, deployment_id, rest_client):
""" Get a runtime property for the first node instance of a node in
a deployment.
:param node_id: The ID of a node template in a deployment.
:type node_id: str
:param runtime_property: The key of a runtime property.
:type ... | ccdcf619f6136f8889c44183594b58ab0a318745 | 644,430 |
import hashlib
def _HashFileHandle(fh):
"""sha1 of a file like object.
Arguments:
fh: file handle like object to hash.
Returns:
sha1 as a string.
"""
hasher = hashlib.sha1()
try:
while True:
data = fh.read(4096)
if not data:
break
hasher.update(data)
finally:
f... | feee252b4ed3eb1dcbe531eafe002168458b079b | 644,436 |
def aztec_tonalpohualli_name(date):
"""Return the name field of an Aztec tonalpohualli
date = [number, name]."""
return date[1] | 13a36db7be63ec29ea2900e02fdd65e5cc362019 | 644,438 |
def _classify_rec(rec):
"""Determine class of variant in the record.
"""
if max([len(x) for x in rec.alleles]) == 1:
return "snp"
else:
return "indel" | 8d30bbcb0eb366056f0643e911a09a991493c333 | 644,439 |
def is_last_best(name, history, min_delta):
"""Checks whether the last element is the best score so far
by taking into account an absolute improvement threshold min_delta."""
if len(history) == 1:
# If first validation, return True to save it
return True
new_value = history[-1]
# b... | 085e9f8765ee801c0091e05101bcac45a5f0574e | 644,442 |
def leiaInt(msg='', dado='Número', f=False):
"""
Um input que só aceita e continua a execução caso receba um número inteiro
:param msg: Mensagem que será exibida antes de pedir o input
:param dado: o tipo de valor lido para personalizar a mensagem de erro - "[!] 'dado' inválido! Digite novamente."
... | 0979f36c1b8a4cee4fc88575ab6494485a8e2123 | 644,445 |
def discrete_distribution(data):
"""
Build a discrete distribution in form of { point : probability }
:param data: numpy.array, (data points, dimension)
:return: dict of distribution
"""
distr = { }
n = data.shape[0]
for point in data:
if tuple(point) in distr:
distr[... | 494e3bcb8552419d4303732a0f4e8f3c6d6e36ef | 644,452 |
def get_filename(pathname, split_char='/'):
"""
:param pathname: path name
:param split_char: Path interval character
:return: file name
"""
pathname = pathname.split(split_char)
return pathname[-1] | 11bead040c84c105ce0c0c4dc354ef04400e1b57 | 644,456 |
from typing import List
def to_indexes(input_range: str) -> List[int]:
"""
Takes a string representing some indexes and returns a list of integers containing the indexes.
>>>
>>> to_indexes('2, 5-8, 21')
[2, 5, 6, 7, 8, 21]
>>>
:param input_range: str
:return: List[int]: A list contai... | d04038141fe3fb12abf2027dc7436b875105a545 | 644,457 |
def version_tuple(v):
"""Creates a version tuple from a version string for consistent comparison of versions.
Conversion to tuples is needed because version '2.12.9' is higher then '2.7.8' however::
>>> '2.12.9' > '2.7.8'
False
Instead we need:
>>> version_tuple('2.12.9') > version_tuple('2.... | b665d5d0cf4bf9539e1b804adfcc1f74e73f8e0f | 644,460 |
import struct
def read_1(stream):
""" read 1 byte from stream """
return struct.unpack('<B', stream.read(1))[0] | 5208fdf0ede3d615d7d9dd7172f09a0be91c67d9 | 644,462 |
import torch
def collate_fn(data):
"""Pad the sequences.
This function will be used to pad the sessions to max length
in the batch and transpose the batch from
batch_size x max_seq_len to max_seq_len x batch_size.
It will return padded vectors, labels and lengths of each session (before padding)
... | 9577998d883233aea8d6cb6026b3e2c7892aa5a5 | 644,463 |
def get_sphinx_build_command(project):
"""Builds the sphinx-build command using project properties.
"""
options = ["-b %s" % project.get_property("sphinx_builder"),
"-c %s" % project.expand_path(project.get_property("sphinx_config_path")),
project.expand_path(project.get_proper... | 13a770deb39149a02f283ed90615ae686fedb96e | 644,467 |
import torch
def collate_list(vec):
"""
If vec is a list of Tensors, it concatenates them all along the first dimension.
If vec is a list of lists, it joins these lists together, but does not attempt to
recursively collate. This allows each element of the list to be, e.g., its own dict.
If vec i... | a5d272fcc651a6dcbfd58d51f21e2013a4c4bfe2 | 644,469 |
from textwrap import dedent
def build_brace_pattern(level, separators):
"""
Build a brace pattern upto a given depth
The brace pattern parses any pattern with round, square, curly, or angle
brackets. Inside those brackets, any characters are allowed.
The structure is quite simple and is recursiv... | 35c1fe4f0b86d5b459c9c504a67f12274a68e308 | 644,478 |
import itertools
def choose_n(total, sample_size):
"""Given a number of items N and a sample size S, returns all possible
unordered S-tuples of integers up to N."""
return list(itertools.combinations(range(1, total + 1), sample_size)) | b032ba2a4d044de23aff0093c15b4f47e59df6ea | 644,481 |
def decode_varint_py(buffer, pos=0):
""" Decode an integer from a varint presentation. See
https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints
on how those can be produced.
Arguments:
buffer (bytearry): buffer to read from.
pos (int): optional position... | e51e7f9f225ce0edd7d157239f1db9e051518bdc | 644,482 |
def expand_year(year):
"""Convert 2-digit year to 4-digit year."""
if year < 80:
return 2000 + year
else:
return 1900 + year | 6a9b47a09493523554c123dc7c3a92897d8464b3 | 644,483 |
def readList(infile,
column=0,
map_function=str,
map_category={},
with_title=False):
"""read a list of values from infile.
Arguments
---------
infile : File
File object to read from
columns : int
Column to take from the file.
map... | e9708a136f248dc3579fcd06fdc52527e9260e54 | 644,485 |
def is_file_covered(file_cov):
"""Returns whether the file is covered."""
return file_cov['summary']['regions']['covered'] | 39458fd70145772e1dddc978fd825ba0287c0b72 | 644,488 |
import string
import random
def random_string(len: int) -> str:
""" Generate a _random string of desired length.
:param len: Desired character length for generated string.
:return: Generated _random string.
"""
alphanumeric_alphabet = ''.join([string.ascii_letters, string.digits])
generated_s... | af7a32425325490a01f8c7e4e72ac295b3e0a910 | 644,489 |
def is_multi_label(labels_list):
"""Whether labels list provided is a multi-label dataset.
Parameters
----------
labels_list : list
list of labels (integers) or multiple labels (lists of integers) or mixed
Returns
-------
True if multi-label
"""
return any([isinstance(l, li... | 7c51f84639cc68f263b55b0a71bb5f62d0dffdfd | 644,490 |
def valid_operation(x: str) -> bool:
"""
Whether or not an opcode is valid
:param x: opcode
:return: whether or not the supplied opcode is valid
"""
return not x.startswith("__") and not x == "bytecode_format" | 947f1f1e7b58f0d56d772c017c100657a84ba5ca | 644,494 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.