content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
from typing import Any
from typing import Dict
def create_filter_dict(filter_type: str, filter_by: str, filter_value: List[Any], operator: str) -> Dict[str, Any]:
"""Creates a dictionary with the filter for the list-incidents request.
:param filter_type: The filter type.
:param fi... | 31c1a86c9fdfb193669e99cb1425bea9c89bf367 | 700,828 |
def get_resource_name(prefix, project_name):
"""Get a name that can be used for GCE resources."""
# https://cloud.google.com/compute/docs/reference/latest/instanceGroupManagers
max_name_length = 58
project_name = project_name.lower().replace('_', '-')
name = prefix + '-' + project_name
return name[:max_nam... | 7779f71e00063b32566f05d4cb0d8daef81043c0 | 700,829 |
def find_beat(v):
"""
find the beat of a vector format midi using the autocorrelation function
"""
# binary vector for testing autocorrelation
v2 = [0 if x[0] == -1 else 1 for x in v]
result = []
# no need to check more than 24*4 = 96
# i.e. 4 quarter notes of standard midi
for lag i... | b408afced09779eb69b40ae54d1fd2c2cfcf1906 | 700,830 |
def read_line_from_file(file):
"""Reads one line from a file and returns it as string."""
with open(file, "r") as f:
result = f.readline()
return result | 3f3da3642e7931469e853c977aef67cd1024bbe5 | 700,831 |
def round_float(value, precision=1):
"""
Returns the float as a string, rounded to the specified precision and
with trailing zeroes (and . if no decimals) removed.
"""
return str(round(value, precision)).rstrip("0").rstrip(".") | afa167709c73b2c536a795c0e38975e212311210 | 700,832 |
from typing import List
import csv
def read_sts_inputs(path: str) -> List[str]:
"""Read input texts from a tsv file, formatted like the official STS benchmark"""
inputs = []
with open(path, 'r', encoding='utf8') as fh:
reader = csv.reader(fh, delimiter='\t', quoting=csv.QUOTE_NONE)
for row... | 6af4e934d648b550298e71584eaf47e4267316ac | 700,836 |
def standardize_parameter_type(original_type):
"""Standardize parameter type descriptions
Args:
original_type (str): The original type
Returns:
str: The standarized type name
"""
original_type = original_type.lower()
if 'unc' in original_type:
return 'uncertainty'
i... | 49a93bebd8ee4918bdf420ee8c285d6574a3d3d0 | 700,841 |
def _define_names(d_t, d_y, treatment_names, output_names):
"""
Helper function to get treatment and output names
Parameters
----------
d_t: tuple of int
Tuple of number of treatment (exclude control in discrete treatment scenario).
d_y: tuple of int
Tuple of number of outcome.
... | a475968ed70070175f5ef164d1748def62548c9d | 700,845 |
def _as_vw_string(x, y=None):
"""Convert {feature: value} to something _VW understands
Parameters
----------
x : {<feature>: <value>}
y : int or float
"""
result = str(y)
x = " ".join(["%s:%f" % (key, value) for (key, value) in list(x.items())])
return result + " | " + x | 89e10d3bb8ad47ad4add6baee83280fa700ca65e | 700,846 |
def index_settings(shards=5, refresh_interval=None):
"""Configure an index in ES with support for text transliteration."""
return {
"index": {
"number_of_shards": shards,
"refresh_interval": refresh_interval,
"analysis": {
"analyzer": {
... | 29028b545da2e5ee2b0239029d34f863d1d9d943 | 700,851 |
import time
def test_approach(approach: str, sample_no: int, func, args: tuple) -> str:
""" For a given Sample #sample_no evaluates an approach by running func with provided args and logs run time """
res = f"{approach.capitalize()} Programming Approach for the Example #{sample_no}\n"
start = time.time()+... | ef34e7552a887fd4bee221a5d80bb3d5ab0003a9 | 700,852 |
def kwargs_to_str(kwargs):
""" Returns a string of the form '(kw1=val1, kw2=val2)'. """
if len(kwargs) == 0:
return ""
else:
return "(" + ", ".join(f"{k}={v}" for k, v in kwargs.items()) + ")" | 39d50d77620061b99861fb7a1fea77ae2a2dc376 | 700,855 |
def add_CRUD_pset(pset, sm, model_name):
"""Adds the ServerModel CRUD function to the Primitve Set
Parameters
----------
pset : PrimitiveSet
the primitive set for adding the controller functions
sm : ServerModel
the ServerModel with the CRUD functions
model_name : str
... | f0960c3b96789adfa2e56039ca7c072819438984 | 700,856 |
def to_litres(gallons):
"""Convert US gallons to metric litres"""
return 3.78541 * gallons | d1a7be6f01c89b848128218cbec19913e76658cd | 700,857 |
from typing import Sequence
def all_unique(lst):
"""Returns True if all elements of Sequence `lst` are unique.
False otherwise.
"""
assert isinstance(lst, Sequence)
return bool(len(set(lst)) == len(lst)) | 546d4254d5ca287952eec6af2bda048e60bb6b89 | 700,860 |
def generate_average_csv(fname, fields, trait_list):
""" Generate CSV called fname with fields and trait_list """
csv = open(fname, 'w')
csv.write(','.join(map(str, fields)) + '\n')
csv.write(','.join(map(str, trait_list)) + '\n')
csv.close()
return fname | 43195ea054ea537a4860c07c03c96efc263c472f | 700,861 |
def cpo(total_cost, total_transactions):
"""Return the CPT (Cost per Order).
Args:
total_cost (float): Total cost of marketing.
total_transactions (int): Total number of transactions.
Returns:
cpt (float) as total cost per order
"""
return total_cost / total_transactions | aaaaf5a96fcbef65e59591954bded1afa13f8c47 | 700,868 |
def get_ground_truth(obj, image, question):
"""
Get the ground truth value for the image/question combination in reader
study obj.
"""
ground_truths = obj.statistics["ground_truths"]
return ground_truths[image][question] | 522b5550344891e0985bacb9c763c4c52686cb67 | 700,870 |
def solve(f, x0):
"""
Solve the equation f(x) = x using a fixed point iteration. x0 is the start value.
"""
x = x0
for n in range(10000): # at most 10000 iterations
oldX = x;
x = f(x);
if abs(x - oldX) < 1.0e-15:
return x; | d5f5409d689c842c1a8c70b95c621360c9ae7c8c | 700,874 |
def _total_solves(color_info):
"""
Return total number of linear solves required based on the given coloring info.
Parameters
----------
color_info : dict
dict['fwd'] = (col_lists, row_maps)
col_lists is a list of column lists, the first being a list of uncolored columns.
... | 32031f2ba834f7d6ed310b0a71ab43884b424459 | 700,876 |
def gettext(msg, domain='python-apt'): # real signature unknown; restored from __doc__
"""
gettext(msg: str[, domain: str = 'python-apt']) -> str
Translate the given string. This is much faster than Python's version
and only does translations after setlocale() has been called.
"""
return "" | a6d83a79110ec233f86878fc6aa9f37f2b3e61fa | 700,878 |
def get_fields_by_name(model_cls, *field_names):
"""Return a dict of `models.Field` instances for named fields.
Supports wildcard fetches using `'*'`.
>>> get_fields_by_name(User, 'username', 'password')
{'username': <django.db.models.fields.CharField: username>,
'password': <django.d... | 8ce9c845adbff9bb53da50c7d7e208aa8077e718 | 700,884 |
def list_of_comments(fname) :
"""Returns list of str objects - comment records from file.
- fname - file name for text file.
"""
#if not os.path.lexists(fname) : raise IOError('File %s is not available' % fname)
f=open(fname,'r')
cmts = []
for rec in f :
if rec.isspace() : conti... | 5aea0668c006b4a4615cab01acd07db8dc1fb2b5 | 700,885 |
from typing import Dict
def convert_to_km(distance: float, print_output: bool = True) -> Dict[str, float]:
"""Convert a miles distance into the double of km.
Args:
distance: a distance (in miles).
print_output: if True, prints the progress.
Returns:
A dictionary with two keys ('o... | 1fb9dbbeb890a348d0feeebaea1a308bc06b039d | 700,889 |
import aiohttp
def aiohttp_socket_timeout(socket_timeout_s):
""" Return a aiohttp.ClientTimeout object with only socket timeouts set. """
return aiohttp.ClientTimeout(total=None,
connect=None,
sock_connect=socket_timeout_s,
... | c17a40a532aee15557b4e507439b0a7b2e98989e | 700,890 |
def deg_to_arcsec(angle: float) -> float:
"""
Convert degrees to arcseconds.
Args:
angle: Angle in units of degrees.
Returns:
angle: Angle in units of arcseconds.
"""
return float(angle) * 3600. | 02fd099627970116bf5513af8b8d2d62bdc8ed41 | 700,893 |
import json
def update_chart_info(_figure, chart_data_json_str):
"""
A callback function to set the sample count for the number of samples that
have been displayed on the chart.
Args:
_figure (object): A figure object for a dash-core-components Graph for
the strip chart - triggers... | fd28e28b7b48131bb56d6d9f29e4fe438b33bb7a | 700,895 |
def read_file(filename):
""" Return the content of a file as a list of strings, each corresponding to a line
:param filename: string: location and name of the file
:return: content of filename
"""
with open(filename, 'r') as ofile:
content = ofile.read().splitlines()
return content | 58a2718265fef848e484178e407aee6f7017a52a | 700,897 |
def score_1(game, player): # 82.14%
"""
Heuristics computing score using #player moves - k * #opponent moves
:param game: game
:param player: player
:return: score
"""
if game.is_winner(player) or game.is_loser(player):
return game.utility(player)
opponent = game.get_opponent(p... | 3995237f5d5474660c752c308e1077aad1743d06 | 700,898 |
def get_CV_current(CV):
"""
Helper function to compute CV current.
Args:
CV (pd.DataFrame): CV segement of charge
Returns:
(float): current reached at the end of the CV segment
"""
if not CV.empty:
return(CV.current.iat[-1]) | 69e32ecadc57d0855eedfe3404db1e5ec9839862 | 700,904 |
def label_name(event_data):
"""Get the label name from a label-related webhook event."""
return event_data["label"]["name"] | 903173b4fd9ddeb0a74a3e10be94626e0685a037 | 700,907 |
def bit_length_power_of_2(value):
"""Return the smallest power of 2 greater than a numeric value.
:param value: Number to find the smallest power of 2
:type value: ``int``
:returns: ``int``
"""
return 2 ** (int(value) - 1).bit_length() | bb49afee83ac255549ce5b5aaab80bb76ad4e337 | 700,908 |
import json
def json_top_atom_count(json_str):
"""Count the number of atoms in a JSON topology used by wepy HDF5."""
top_d = json.loads(json_str)
atom_count = 0
atom_count = 0
for chain in top_d['chains']:
for residue in chain['residues']:
atom_count += len(residue['atoms'])
... | 0e1e23cd4b9e5cedf3e6b5d815ee817798188752 | 700,910 |
def length_squared(point):
"""
square of length from origin of a point
Args:
point (QPointF) the point
Returns
square of length
"""
return point.x()*point.x() + point.y()*point.y() | 0289ca736f087dd75f9b9e0f1347fdc223d03f84 | 700,911 |
def get_ancestor(taxid, tree, stop_nodes):
"""Walk up tree until reach a stop node, or root."""
t = taxid
while True:
if t in stop_nodes:
return t
elif not t or t == tree[t]:
return t # root
else:
t = tree[t] | f7841bc5104f96cd66122165a0646b70fc3fd33e | 700,914 |
def read_table(data, coerce_type, transpose=False):
"""
Reads in data from a simple table and forces it to be a particular type
This is a helper function that allows data to be easily constained in a
simple script
::return: a dictionary of with the keys being a tuple of the strings
in the fi... | 6701736354b30d41b4adf7c6a11406f26c21c71b | 700,919 |
def cat_arg_and_value(arg_name, value):
"""Concatenate a command line argument and its value
This function returns ``arg_name`` and ``value
concatenated in the best possible way for a command
line execution, namely:
- if arg_name starts with `--` (e.g. `--arg`):
`arg_name=value` is returned (... | bcd99ab465707e594646d2152ad7b10b32956f5e | 700,921 |
def envelops(reg, target_reg):
"""Given a region and another target region, returns whether the region
is enveloped within the target region."""
return (target_reg.start <= reg.start < target_reg.end) \
and (target_reg.start <= reg.end < target_reg.end) | 716f2e905bdb852d9e0b85ff0482a70a64d325f1 | 700,927 |
from typing import MutableMapping
from typing import Any
def include_filter(
include: MutableMapping[Any, Any],
target: MutableMapping[Any, Any]) -> MutableMapping[Any, Any]:
"""Filters target by tree structure in include.
Args:
include: Dict of keys from target to include. An empty dict matches all
... | f1c10ec383a430700d8e7f58e8c9f6bc5180c844 | 700,928 |
def get_route_name(route):
"""Returns route name."""
# split once, take last peice
name = route.split("/", 1)[-1]
return name | 3d5c916711a7631d4eb90c5eff6f1f745c97a664 | 700,932 |
import requests
def get_remote_version(url: str) -> str:
"""Gets the remote file and returns it as a long string."""
response = requests.get(url)
if response:
#print("Getting remote version")
s = response.text
return s
else:
return "Url Not Found." | 5d5ef45c5b74b326f9386214229529d9b71aca3d | 700,934 |
def single_number_hashtable(nums: list[int]) -> int:
"""Returns the only element in `nums` that appears exactly once
Complexity:
n = len(nums)
Time: O(n)
Space: O(n)
Args:
nums: array of integers s.t. every element appears twice, except for one
Returns: the only elemen... | f15b06d4f4683b9604e8b5ab6f2fe9be588551a6 | 700,935 |
def parse_card(card: str) -> tuple:
"""Separates the card into value and suit.
Args:
card (str): String representing a poker card, in the format ValueSuit, like '9D' (9 of Diamonds).
Returns:
tuple: Returns a tuple of the card, like (Value, Suit). Ex: '9D' -> ('9', 'D').
"""
if le... | de9051906327dfcf01a3b2076acbed216ce43ced | 700,937 |
def checksum1(data, stringlength):
""" Calculate Checksum 1
Calculate the ckecksum 1 required for the herkulex data packet
Args:
data (list): the data of which checksum is to be calculated
stringlength (int): the length of the data
Returns:
int: The calculated checksum 1
... | 504b848b651ae5e8c52c987a6a8e270259e1de44 | 700,942 |
def plugin_zip(p):
"""Maps columns to values for each row in a plugins sql_response and returns a list of dicts
Parameters
----------
p : :class:`taniumpy.object_types.plugin.Plugin`
* plugin object
Returns
-------
dict
* the columns and result_rows of the sql_response in P... | b91e5403fd710875c4588afc0eba3da1b1a82c4a | 700,947 |
def get_string_from_ascii(input):
"""
This function is reversed engineered and translated to python
based on the CoderUtils class in the ELRO Android app
:param input: A hex string
:return: A string
"""
try:
if len(input) != 32:
return ''
byt = bytearray.fromhex... | fdf878ac689c614720e9ad5ebeecbd32c9f893b1 | 700,949 |
def compute_mean_median(all_methods_df):
"""
Computes the mean values and the median values for each column of the Pandas.DataFrame grouped by the methods.
Parameters
----------
all_methods_df : Pandas.DataFrame
Returns
-------
list
- means: Pandas.DataFrame containing the ... | b4397bfcef8e0215e3478f1f50708aa4608a14e2 | 700,953 |
import torch
def get_cosinebased_yaw_pitch(input_: torch.Tensor) -> torch.Tensor:
"""
Returns a tensor with two columns being yaw and pitch respectively. For yaw, it uses cos(yaw)'s value along with
sin(yaw)'s sign.
Args:
input_: 1st column is sin(yaw), 2nd Column is cos(yaw), 3rd Column is si... | ca5c10908de8dfa8b86446a1874b1ef780ae5313 | 700,954 |
import re
def CommitPositionFromBuildProperty(value):
"""Extracts the chromium commit position from a builders got_revision_cp
property."""
# Match a commit position from a build properties commit string like
# "refs/heads/master@{#819458}"
test_arg_commit_position_re = r'\{#(?P<position>\d+)\}'
match =... | c0fdb07ce3be907db3ec8628eaefc3ad1453ef34 | 700,955 |
def traverse_tree(t, parent_name=""):
""" Returns the list of all names in tree. """
if parent_name:
full_node_name = parent_name + "/" + t.name
else:
full_node_name = t.name
if (t.children is None):
result = [full_node_name]
else:
result = [full_node_name + "/"]
... | 16b1773895569c108fde5f9a1a43a12a24314dcc | 700,957 |
def merge_again(other, script):
"""
Merge the two DataFrames for other and script together again,
but keeping distinct rows for the cumulated levenshtein distances
for each category (other and script).
Returns DataFrame.
"""
data = other.merge(script, how="left", on="line")
data.rename(c... | 204e716fce02765e2ba601f5d5a7f91efa792838 | 700,960 |
def subset_dict(d, selected_keys):
"""Given a dict {key: int} and a list of keys, return subset dict {key: int} for only key in keys.
If a selected key is not in d, set its value to 0"""
return {key: (0 if key not in d else d[key]) for key in selected_keys} | e16e5ce7a9baa0fa9dbf8bb65eadd9101e188092 | 700,962 |
def ctoa(character: str) -> int:
"""Find the ASCII value of character.
Uses the ord builtin function.
"""
code = ord(character)
return code | dbf3b01f331a976632ae2559e08488a3f6a7f15d | 700,966 |
def resolve_translation(instance, _info, language_code):
"""Get translation object from instance based on language code."""
return instance.translations.filter(language_code=language_code).first() | aedd46bec3dc0d3a567718abf1fd69b460e69ba1 | 700,967 |
def _IsZonalGroup(ref):
"""Checks if reference to instance group is zonal."""
return ref.Collection() == 'compute.instanceGroupManagers' | bf48f2c277fb03db2f0cc3ea42234781df9a2500 | 700,971 |
def lex_ident(node_syn, pred_syn, gold_syn):
"""
1. check if the predicted synset's lexname equals to the gold synset's name
2. check if the predicted synset's lexname is in the set of its wordnet hypernyms' lexnames (including hypernyms/instance_hypernyms)
"""
pred_lex = pred_syn.lexname()
gold... | 487fe7c0772d9ecaf84a6f8fe349b0ec20fd3646 | 700,972 |
def count_set_bits(number):
""" Returns the number of set bits in number """
count = 0
while number:
count += number & 1
number >>= 1
return count | b6326b77d6fb14ff31712571837396fcf2e2b0c0 | 700,976 |
def pjax(template_names, request, default="pjax_base.html"):
"""
Returns template name for request.
:param request: Django request or boolean value
:param template_names: Base theme name or comma-separated names of base and
pjax templates.
Examples::
{% extends "base.html"|pjax:requ... | e74b1c76abfc68999c316021e6b70f6210125a2a | 700,978 |
def make_header(ob_size):
"""Make the log header.
This needs to be done dynamically because the observations used as input
to the NN may differ.
"""
entries = []
entries.append("t")
for i in range(ob_size):
entries.append("ob{}".format(i))
for i in range(4):
entries.app... | 82aa8359dad2e78f8d161a1811a7d71b2e496b49 | 700,980 |
def evaluate_g8( mu, kappa, nu, sigma, s8 ):
"""
Evaluate the eighth constraint equation and also return the jacobian
:param float mu: The value of the modulus mu
:param float kappa: The value of the modulus kappa
:param float nu: The value of the modulus nu
:param float sigma: The value of the... | d1be8deb9f38dae55082a341e2501044d7b2aef7 | 700,981 |
def ChangeBackslashToSlashInPatch(diff_text):
"""Formats file paths in the given patch text to Unix-style paths."""
if not diff_text:
return None
diff_lines = diff_text.split('\n')
for i in range(len(diff_lines)):
line = diff_lines[i]
if line.startswith('--- ') or line.startswith('+++ '):
diff... | 88dce5e16fb400ef2aa1c16950e45491baa5c961 | 700,985 |
def parse_line(text: str) -> str:
"""Parses one line into a word."""
text = text.rstrip()
if text[0] == "+":
return text[1:]
if text[0] == "@" or text[0] == "!" or text[0] == "$":
w = text.split("\t")[1]
if "#" in w:
return w.split("#")[0].rstrip()
else:
... | 44e8bd0defc071438aea15002d3e3c6838e61bfb | 700,986 |
def dict_to_cidr(obj):
"""
Take an dict of a Network object and return a cidr-formatted string.
:param obj:
Dict of an Network object
"""
return '%s/%s' % (obj['network_address'], obj['prefix_length']) | c915c16f28b42322c2f63743cdc43a58b964ba27 | 700,987 |
def replace_tuple(tuple_obj, replace_obj, replace_index):
"""Create a new tuple with a new object at index"""
if len(tuple_obj) - 1 <= replace_index:
return tuple_obj[:replace_index] + (replace_obj,)
else:
return tuple_obj[:replace_index] + (replace_obj,) + tuple_obj[replace_index+1:] | 28c32ab516eddd7feb90e6b62221f56e8106a2f5 | 700,988 |
def center_crop_images(images, crop_resolution: int):
"""
Crops the center of the images
Args:
images: shape: (B, H, W, 3), H should be equal to W
crop_resolution: target resolution for the crop
Returns:
cropped images which has the shape: (B, crop_resolution, crop_resolution, 3... | 3831dde49fba737f24706c5c19c380bf7d9f9222 | 700,989 |
def default_exception_serializer(exception):
"""
The default exception serializer for user exceptions in eval.
"""
return '%s: %s' % (type(exception).__name__, str(exception)) | c630ddb9ec6ffc5381c11c4b06c277e4e55910de | 700,991 |
import copy
def remove_candidates(orders, candidates_to_remove):
"""
Remove a set of candidates from a list representing a preference order.
"""
projection = []
for c_vote in orders:
temp_vote = copy.copy(c_vote)
for c_remove in candidates_to_remove:
temp_vote.remove(c_remove)
projection... | bd0b98acefacaf9891b4ab7109d01d187f1de85a | 700,992 |
def factorial(n):
"""
Calculate n!
Args:
n(int): factorial to be computed
Returns:
n!
"""
if n == 0:
return 1 # by definition of 0!
return n * factorial(n-1) | a0e8e6edbf03bb1fb1e6a11d7ace41e37992b54f | 700,995 |
def unique_filename(filename, upload_id):
"""Replace filename with upload_id, preserving file extension if any.
Args:
filename (str): Original filename
upload_id (str): Unique upload ID
Returns:
str: An upload_id based filename
"""
if "." in filename:
return "."... | 04602532627d8557436c27f2e7d8165f638ed155 | 701,004 |
def ror (endv, iv):
""" This capital budgeting function computes the rate of
return on an investment for one period only.
iv = initial investment value
endv = total value at the end of the period
Example: ror(100000, 129,500)
"""
return (endv - iv)/iv | 43a1339d45725a5e04fd809a6cfb708b6b49b829 | 701,006 |
import torch
def concatenate_list_of_dict(list_of_dict) -> dict:
"""
Concatenate dictionary with the same set of keys
Args:
list_of_dict: list of dictionary to concatenate
Returns:
output_dict: the concatenated dictionary
"""
# check that all dictionaries have the same set of... | e38837d9e55cc17715bf988b585c3f4f371f7398 | 701,009 |
from typing import List
import glob
def get_manifest_list(manifests_dir: str) -> List[str]:
"""Get a list of manifest files from the manifest directory."""
yml_endings = ["yml", "yaml"]
manifest_list = []
for yml_ending in yml_endings:
manifest_list += glob.glob(f"{manifests_dir}/**/*.{yml_en... | 0dc951cf08870c639735e24b048a41fb7ab6ea52 | 701,011 |
def checksum(s, m):
"""Create a checksum for a string of characters, modulo m"""
# note, I *think* it's possible to have unicode chars in
# a twitter handle. That makes it a bit interesting.
# We don't handle unicode yet, just ASCII
total = 0
for ch in s:
# no non-printable ASCII chars, including space... | 836e0f36ed3d87db8d3f2420230eb4f3f5d4d94c | 701,013 |
def text_objects(text, font, color):
"""
Function for creating text and it's surrounding rectangle.
Args:
text (str): Text to be rendered.
font (Font): Type of font to be used.
color ((int, int, int)): Color to be used. Values should be in range 0-255.
Returns:
Text surf... | a9ed3d8a68c80930e2594b4dbef06e828de10513 | 701,017 |
def contains(value, lst):
""" (object, list of list of object) -> bool
Return whether value is an element of one of the nested lists in lst.
>>> contains('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]])
True
"""
found = False # We have not yet found value in the list.
for i in... | 9d3690943c05b4220afabfa65402b7f12c1cb279 | 701,021 |
def UnbiasPmf(pmf, label=''):
"""Returns the Pmf with oversampling proportional to 1/value.
Args:
pmf: Pmf object.
label: string label for the new Pmf.
Returns:
Pmf object
"""
new_pmf = pmf.Copy(label=label)
for x, p in pmf.Items():
new_pmf.Mult(x, 1.0/x)
... | 1146d952bbac0ef3031e3259d98e0f343103598e | 701,023 |
def _num_requests_needed(num_repos, factor=2, wiggle_room=100):
"""
Helper function to estimate the minimum number of API requests needed
"""
return num_repos * factor + wiggle_room | 525af1e3aa5e1c0b35195fcd8e64cd32101bb6f2 | 701,029 |
def same_padding_for_kernel(shape, corr, strides_up=None):
"""Determine correct amount of padding for `same` convolution.
To implement `'same'` convolutions, we first pad the image, and then perform a
`'valid'` convolution or correlation. Given the kernel shape, this function
determines the correct amount of p... | 8d956c75a2e0609a04ec56374a4cb9b3b367b90a | 701,031 |
def _extract_license_outliers(license_service_output):
"""Extract license outliers.
This helper function extracts license outliers from the given output of
license analysis REST service.
:param license_service_output: output of license analysis REST service
:return: list of license outlier package... | 101a916fec08a3a5db1a09a2817e82314ca19f6b | 701,032 |
def center(map, object):
"""
Center an ee.Image or ee.Feature on the map.
Args:
map: The map to center the object on.
object: The ee.Image or ee.Feature to center.
Returns:
The provided map.
"""
coordinates = object.geometry().bounds().coordinates().getInfo()[0]
... | 60a2baa1c4f83b0e9b1221bcc474f109c35cbd7a | 701,034 |
def evaluations_to_columns(evaluation):
"""Convert the results of :meth:`metrics.ScoringMixIn.evaluate` to a pandas DataFrame-ready format
Parameters
----------
evaluation: dict of OrderedDicts
The result of consecutive calls to :meth:`metrics.ScoringMixIn.evaluate` for all given dataset types
... | 26c5f4b2a9830f7547f6b59d9653fea25345b43d | 701,036 |
def merge(left: list, right: list) -> list:
"""Merges 2 sorted lists (left and right) in 1 single list, which is
returned at the end.
Time complexity: O(m), where m = len(left) + len(right)."""
mid = []
i = 0 # Used to index the left list.
j = 0 # Used to index the right list.
while i < ... | 9f6c501469e79a9f5ecfd8e23ee3384fc56c5a48 | 701,037 |
def replace(i_list: list, target: int,new_value: int)-> list:
"""
Replace all the target value with a new value
:param i_list: the list to be analyzed
:param value: the value to replace
:param target: the value to be replaced
:return: the new list
"""
return list(map(lambda value: new_va... | d0d2bc928c915d3456a25cc4ff341b23a66c4098 | 701,038 |
def isPerfectSquare(p: int) -> bool:
"""Checks if given number is a perfect square.
A perfect square is an integer that is a square of another integer.
Parameters:
p: int
number to check
Returns:
result: bool
True if number is a perfect square
F... | d9c725193a5100e06825944239fe3442bed17b92 | 701,043 |
def mean_expression(df, annotation, stage_regex=r".*", normal=False):
"""Return the mean expression values of the subset of samples.
Parameters
----------
df: pandas.DataFrame
Each row is a gene and each column is a sample.
annotation: pandas.DataFrame
A data frame w... | 7e404aa4a69b7b967d830463d21d611e0cd47b36 | 701,046 |
import random
def full_jitter(value):
"""Jitter the value across the full range (0 to value).
This corresponds to the "Full Jitter" algorithm specified in the
AWS blog's post on the performance of various jitter algorithms.
(http://www.awsarchitectureblog.com/2015/03/backoff.html)
Args:
... | 0a5c233d3e0e58873d29de7e3d878fbcf3d0c47a | 701,048 |
def eq(a, b, n):
"""Euler's quadratic formula"""
## : coefficient: a, b int
## : n int | n >= 0
rst = n**2 + a*n + b
return rst | c5f9619e22d3131b905eba6bfe509020d1f7c917 | 701,054 |
def is_unqdn(cfg, name):
"""
Returns True if name has enough elements to
be a unqdn (hostname.realm.site_id)
False otherwise
"""
parts = name.split(".")
if len(parts) >= 3:
return True
else:
return False | 28e530816ea418473858d2cb59e572d25a9f2d81 | 701,055 |
def is_valid_medialive_channel_arn(mlive_channel_arn):
"""Determine if the ARN provided is a valid / complete MediaLive Channel ARN"""
if mlive_channel_arn.startswith("arn:aws:medialive:") and "channel" in mlive_channel_arn:
return True
else:
return False | c2ddbdef180eabbc4f22399dd895b99555bb05d6 | 701,057 |
def convert_tf_to_crowdsourcing_format(images, detections):
"""
Args:
images: dictionary {image_id : image info} (images from Steve's code)
detections: detection output from multibox
Returns:
dict : a dictionary mapping image_ids to bounding box annotations
"""
image_annotation... | ba25ee0cb2eb570f745326dfe85c2bda972a3659 | 701,058 |
def patched_novoed_api(mocker):
"""Patches NovoEd API functionality"""
return mocker.patch("novoed.tasks.api") | 9bd7b15a6b34c9c659755fb36e422698a82be063 | 701,063 |
def tf(seconds):
"""
Formats time in seconds to days, hours, minutes, and seconds.
Parameters
----------
seconds : float
The time in seconds.
Returns
-------
str
The formatted time.
"""
days = seconds // (60*60*24)
seconds -= days * 60*60*24
hours = sec... | 22649dd1bd74cc08d73c5cd43b1b96658a3bcb3a | 701,067 |
def squares_in_rectangle(length, width):
"""This function is the solution to the Codewars Rectangle into Squares Kata
that can be found at:
https://www.codewars.com/kata/55466989aeecab5aac00003e/train/python."""
if length == width:
return None
squares = []
while length > 0 and width > ... | e0e32e2803ca752a24adf4cce353bf6cc49d4c08 | 701,075 |
def keep_node_permissive(data):
"""Return true for all nodes.
Given BEL graph :code:`graph`, applying :func:`keep_node_permissive` with a predicate on the nodes iterable
as in :code:`filter(keep_node_permissive, graph)` will result in the same iterable as iterating directly over a
:class:`BELGraph`
... | 425ebf20686ea309e542b82b2fbbe7aa81cccb63 | 701,076 |
import torch
def get_params(model):
"""Aggregates model parameters of all linear layers into a vector.
Args:
model: A (pre-trained) torch.nn.Module or torch.nn.Sequential model.
Returns:
The aggregated parameters.
"""
weights = list()
biases = list()
for module in model.m... | c6a66f3a013f62e79e51f47d130e65b12b38ff33 | 701,079 |
def get_voted_content_for_user(user):
"""Returns a dict where:
- The key is the content_type model
- The values are list of id's of the different objects voted by the user
"""
if user.is_anonymous():
return {}
user_votes = {}
for (ct_model, object_id) in user.votes.values_li... | 799eff5efd184da0b5121f59025c39d0ddb593a3 | 701,082 |
def odd_occurences_in_array(a):
"""
Finds the odd number of occurences of an element in an array.
XOR of all elements gives us odd occurring element.
Note that XOR of two elements is 0 if both elements are same and XOR of a number x with 0 is x
:param a
"""
result = 0
for number in a:
... | 8085fb8ffa5df9628caa5fef541b5d7b78c372b0 | 701,083 |
import re
def extract_length(value):
"""
extract length data from a provided value
Returns a tuple of a detected length value and a length unit. If no unit
type can be extracted, it will be assumed that the provided value has no
unit.
Args:
value: the value to parse
Returns:
... | b418b76114fafe24c86c2e0dcfa62bb19b29ff59 | 701,087 |
def read_landmarks(f_landmarks):
"""
Reads file containing landmarks for image list. Specifically,
<image name> x1 y1 ... xK yK is expected format.
:param f_landmarks: text file with image list and corresponding landmarks
:return: landmarks as type dictionary.
"""
landmarks_lut = {}
... | 9c4bf6b405f4fb49ace8badb4b3151cc457bbf84 | 701,094 |
import json
def trigger_oauth_expires_test(limit):
""" Test data for IFTTT trigger bunq_oauth_expires """
result = [{
"created_at": "2018-01-05T11:25:15+00:00",
"expires_at": "2018-01-05T11:25:15+00:00",
"meta": {
"id": "1",
"timestamp": "1515151515"
}
... | 6f0bf5ed1f2749bf67d9068ac9eb85cc6fd86e17 | 701,096 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.