content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def flatten(records, fld):
""" Flatten a recordset to list of a particular field
:param records: the recordset to flatten
:param fld: the field from the records to include in list
:return: a list
"""
return [path for fields in records.values_list(fld) for path in fields] if records else [] | 5c90aa8f077e08237a8ccfe194bf8b0622f167a9 | 609,706 |
from typing import List
from typing import Tuple
def get_function_attrs(functions) -> List[Tuple]:
"""Generate a dictionary of attributes for each function in analysis results."""
attrs:List[Tuple] = []
for function in functions:
attrs.append(
(
function.name,
... | 4df7574a36d559f5d182b1657ebacc2911f7ce2b | 609,707 |
def _warning(source, msg, category=Warning):
"""Return a Warning object with source description."""
if isinstance(source, str):
msg = f'@{source}: ' + msg
elif source:
msg = f'@{type(source).__name__} {str(source)}: ' + msg
return category(msg) | df027c812760851439a7db8952cc15d31d907f5e | 609,708 |
def path_to_startdate(path):
""" Given a path of the form fall2018/coursename,
returns corresponding start date.
>>> path_to_startdate('fall2018/coursename')
'2018-09-01'
>>> path_to_startdate(u'fall2018')
'2018-09-01'
>>> path_to_startdate('spring2018/foo/bar/baz')
... | 8e4c72343828e9198d697d82d25b510e865462f1 | 609,711 |
def merge_adjacent_intervals(intervals):
"""
>>> merge_adjacent_intervals([(1, 3), (4, 5)])
[(1, 3), (4, 5)]
>>> merge_adjacent_intervals([(1, 4), (4, 5)])
[(1, 5)]
>>> merge_adjacent_intervals([(1, 2), (2, 5), (5, 7)])
[(1, 7)]
>>> merge_adjacent_intervals([(1, 2), (2, 5), (5, 7), (8, 9... | fa638acf4dc0feed1749c5bc7c569d39a2f5fb30 | 609,714 |
import re
def digits_count(text):
"""Returns the number of the numeric characters in the text
Keyword arguments:
text: text
"""
return re.findall("[0-9]", text).__len__() | ddbd09f26c0953709f45f7fadfc1c45c71282743 | 609,716 |
def num_or_str(x):
"""The argument is a string; convert to a number if
possible, or strip it.
"""
try:
return int(x)
except ValueError:
try:
return float(x)
except ValueError:
return str(x).strip() | 1ecfe1eb509778ee6232b6c9f540906343ee93ab | 609,718 |
def convert_to_boolean(string):
"""
Shipyard can't support passing Booleans to code, so we have to convert
string values to their boolean values.
"""
if string in ['True', 'true', 'TRUE']:
value = True
else:
value = False
return value | 72ac664c6b28616edcd91df0478065e98af1195f | 609,724 |
from pathlib import Path
def is_file_exist(path):
"""Whether the file exists"""
path_info = Path(path)
return path_info.is_file() | 7d5cca1c0c88b351a232cf295c6e1a941cd1b64f | 609,725 |
def chain_tasks(tasks):
"""
Chain given tasks. Set each task to run after its previous task.
:param tasks: Tasks list.
:return: Given tasks list.
"""
# If given tasks list is not empty
if tasks:
# Previous task
previous_task = None
# For given tasks list's each tas... | 9b36d32b4f8acd378359083678d075413ce7c5d6 | 609,728 |
import torch
def convert_locations_to_boxes(locations, priors, center_variance, size_variance):
"""Convert regressional location results of SSD into boxes in the form of (center_x, center_y, h, w).
The conversion:
$$predicted\_center * center_variance = \frac {real\_center - prior\_center} {prior\_hw... | 5de96703affdd1dfe7c4d4755f717b8d4fa6e505 | 609,730 |
import six
def set_show(plotdata):
#------------------------------------------------------------------
"""
Determine which figures and axes should be shown.
plotaxes._show should be true only if plotaxes.show and at least one
item is showing or if the axes have attribute type=='empty', in which
ca... | 4f674bc3e05ad78831e0e6de818e66b2803fed71 | 609,732 |
def get_min_max_QI_values_from_table(df, QI_cols):
"""
Extract min and max values for each QI attribute in the table.
Parameters
----------
:param df: pd.DataFrame
Time series data DF
:param QI_cols: list of str
QI attributes-only column names
Returns
-------
:... | 934d93ca12caf925b55d86689f4ab64b5959c782 | 609,733 |
from typing import List
def get_list(query: str, field: str) -> List[str]:
"""Parse chained query params into list.
>>> get_list("d=id1&d=id2&d=id3", "d")
['id1', 'id2', 'id3']
>>> get_list("d=1&e=2&d=3", "d")
['1', '3']
"""
kv_tuples = [x.split("=") for x in query.split("&")]
return [... | 620e8475aa7364adb9545f16df457d25c67decbc | 609,738 |
def bezier_line(P0, P1, P2, P3):
"""Cubic Bezier formula
Returns:
Function of parameter t (1d array)
Reference
https://en.wikipedia.org/wiki/Bezier_curve"""
return lambda t: (1 - t)**3 * P0 + 3 * (1 - t)**2 * t * P1 + 3 * (1 - t) * t**2 * P2 + t**3 * P3 | 6c7cf18ab77eafd89434528cdd090391e8528bec | 609,739 |
def GetKCDataSummary(kcdata):
""" Summarizes kcdata_descriptor structure
params: kcdata: value - value object representing kcdata_descriptor
returns: str - summary of the kcdata object
"""
format_string = "{0: <#020x} {1: <#020x} {2: <#020x} {3: <10d} {4: <#05x}"
return format_string.for... | fe9f256204966a47c2a92b3b378ac995c4360281 | 609,741 |
import base64
def isBase64(sb):
"""
Check if both string and bytes objects are in base64.
"""
try:
if isinstance(sb, str):
# If there's any unicode here, an exception will be thrown and the function will return false
sb_bytes = bytes(sb, "ascii")
elif isinstanc... | 637bcdf5dbf0756db9a7f2669c3798a378f8fad3 | 609,742 |
def reverse_along_dim(xr_da, dim_name):
"""Reverse `xarray.DataArray` along one of its dimensions."""
out = xr_da.reindex(**{dim_name: list(reversed(xr_da[dim_name]))})
return out | 402d9666415ca186c3c47b7d06f74476662f6a15 | 609,743 |
def preorderTraversal(root, res=[]):
"""Pre Order Traversal, Recursive"""
if not root:
return res
else:
res.append(root.data)
preorderTraversal(root.left, res)
preorderTraversal(root.right, res)
return res | 1e810bbd6dff829a6ca1be0259e8b0d478f4ae92 | 609,745 |
def _find_path(graph, start_addr, end_addr):
"""Determines if there is a path from start_addr to end_addr (note that
edges in the graph are unidirectional).
Args:
graph, dict, a dict that maps a string (the sending address) to a set
that contains every address that has received BTC from... | f8e581991cb8bdfe3611d7659d38b556cd14c2c2 | 609,747 |
async def service_status():
"""Check the status of the service"""
return {"status": "ok"} | 79fcf6a20b0607225f819828930197fa2e6f40b4 | 609,750 |
from typing import List
from typing import Dict
def get_equal_weights(stocks: List[str], value: float = 1.0) -> Dict:
"""Equally weighted portfolio, where weight = 1/# of stocks
Parameters
----------
stocks: List[str]
List of tickers to be included in optimization
value : float
Am... | 6ac0eef8df8747c14f71956472064f68ed31f3b5 | 609,758 |
def _get_viewname(instance, action):
"""
Return the appropriate viewname for adding, editing, or deleting an instance.
"""
# Validate action
assert action in ("add", "edit", "delete")
viewname = "{}:{}_{}".format(instance._meta.app_label, instance._meta.model_name, action)
return viewname | 8fae2fd9f4a19b2e13e26af0d4af0875b3d53618 | 609,760 |
def find_first(predicate, iterable):
""" Return the first element in iterable that satisfies predicate or None """
try: return next(filter(predicate, iterable))
except StopIteration: return None | 1f5cbad32deb832532161f5df721dc08806cf89e | 609,761 |
import math
def get_int_pattern_with_capacity(max_number, zero_padded=True):
"""Gets an integer pattern like "%%03d" or "%%4d" with sufficient capacity
for the given number.
Args:
max_number: the maximum number you intend to pass to the pattern
zero_padded: whether to left-pad with zeros.... | 3a645e3bbe7a53bbfa71501b7b10fa202ae48a3a | 609,764 |
def logM2L(color, a, b):
"""
Calculate the mass-to-light ratio based on the color.
logM2L = a + (b * color)
Parameters
----------
color : float or array like
The color of the galaxy.
a : float
The normalization of the relation.
b : float
The slope of the rela... | cbcec8d61ef7ca39fc5bbd0d41c5875d725f2439 | 609,766 |
def reverse_lookup(d, v):
"""Modify reverse_lookup so that it builds and returns a list of all keys that map to
v, or an empty list if there are none"""
result = []
for k in d:
if d[k] == v:
result.append(k)
return result | 12591e7f52041ec3d5e29d45977e30db73f035bc | 609,767 |
from typing import Dict
import json
def amberscript_uniform_buffer_def(uniform_json_contents: str, prefix: str) -> str:
"""
Returns the string representing AmberScript version of uniform definitions.
Skips the special '$compute' key, if present.
{
"myuniform": {
"func": "glUniform1f",
... | fb6dee7ed359f6c62b0b050c797ed5e3c1590a87 | 609,769 |
def parser_delimiter(delimiter, position):
"""
Separate the event with the separator and return the element in the position
position
:param delimiter: delimiter
:param position: position
:return: the element in the given position
"""
return lambda x: x.split(delimiter)[position] | 6e667475bd5b6dee20beca14dfff49947749c5fa | 609,775 |
def _GetDownloadTempZipFileName(dst_url):
"""Returns temporary file name for a temporarily compressed download."""
return '%s_.gztmp' % dst_url.object_name | 0a94d3bb67656921ce453123f2f9164c0e0437b6 | 609,776 |
def unique_node_id(graph, prefix):
"""Generate a unique id starting by a prefix.
Parameters
----------
graph : networkx.Graph
prefix : str
Prefix that is prepended to the new unique name.
Returns
-------
str
New unique node id starting with a prefix.
"""
if pre... | 78e67b7ae8c4c5051081f6df11c8baebbe6b345e | 609,780 |
import requests
def device_auth_req(url, dauth, dev):
"""Run authorization request to the backend and return requests.Response"""
data, sign = dauth.make_req_payload(dev)
headers = {
"Content-type": "application/json",
"X-MEN-Signature": sign,
}
rsp = requests.post(url, headers=hea... | f600070754fc15760581008d888d1cb493b09f9c | 609,781 |
import math
def sym_ceil(x, tol=1e-08):
"""Round down for negative, round up for positive."""
if abs(x - round(x)) < tol:
return round(x)
elif x > 0:
return math.ceil(x)
else:
return math.floor(x) | 0c57a1389e99557802e47599e336657700f8cd46 | 609,785 |
def buscar(nombre, apellido, datos):
""" Busca el primer elemento que coincida con nombre y con apellido. """
for elemento in datos:
if nombre in elemento[0] and apellido in elemento[1]:
return elemento
return None | 66c7fd273a41998b956f0e8e927c4380eeaba719 | 609,786 |
import torch
def sigmoid(tensor, temp=1.0):
""" temperature controlled sigmoid
takes as input a torch tensor (tensor) and passes it through a sigmoid, controlled by temperature: temp
"""
exponent = -tensor / temp
# clamp the input tensor for stability
exponent = torch.clamp(exponent, min=-50, ... | d073a7883844898a330703b9dae2d6ab9a3ef28a | 609,796 |
def _caseInsensitiveLookup(d, k, default=None):
"""Performs a case-insensitive lookup on the dictionary ``d``,
with the key ``k``.
This function is used to allow case-insensitive retrieval of colour maps
and lookup tables.
"""
v = d.get(k, None)
if v is not None:
return v
key... | 2ce75e7f67c9ec735de5e9a5d944100d3ef6fb01 | 609,799 |
def convert_taxonomy_bool(s):
"""
Returns true/false given a string loaded from the Taxonomy. Values to check are based on
observed values from within the Taxonomy. If the input is not valid this will always return
false.
"""
if s is None:
return False
elif s.strip().lower() in [... | 4be1ee7139ae6736dfd60d1f84026a83e066a637 | 609,806 |
def sorted_names(names):
"""
Sort a list of names but keep the word 'default' first if it's there.
"""
names = list(names)
have_default = False
if 'default' in names:
names.remove('default')
have_default = True
sorted_names = sorted(names)
if have_default:
sort... | 199856f057865f9649dfeecef0d536bc743fde94 | 609,807 |
import uuid
def create_passenger(name, gender, dob, nationality, residency, passport_number):
"""
Create a dictionary representing a passenger given their details. The dictionary
includes a unique identifier
:param name: Full name of the passenger
:param gender: Passenger's gender
:param dob:... | 18550b20ff964af101bbeac63dd35e819ff17dbc | 609,808 |
def _atoi(value):
"""
Try to convert a string to an integer, supporting decimal and hexadecimal.
"""
try:
return int(value)
except ValueError:
return int(value, 16) | e27da8a840c781959188ca4b04def060b8447914 | 609,810 |
def parse_locale(identifier, sep='_'):
"""Parse a locale identifier into a tuple of the form ``(language,
territory, script, variant)``.
>>> parse_locale('zh_CN')
('zh', 'CN', None, None)
>>> parse_locale('zh_Hans_CN')
('zh', 'CN', 'Hans', None)
The default component separator is "_", but ... | d6fc848ecc5c8dd698b354d0b0dfa6ea2cb3c13c | 609,813 |
def get_info_dictionary(rec, info_fields):
"""Parses info into a dictionary with info fields as the keys
Parameters
----------
rec : pysam.libcbcf.VariantRecord
Obatined from iterating over pysam.VariantFile.fetch()
info_fields : list
List of info fields in the vcf
Returns
... | 0e400e8befad3d97f1d424b48f8c3c121ed7536b | 609,814 |
from typing import List
from typing import Tuple
from typing import Union
from typing import Callable
import gc
import timeit
def performance_test(method_descs: List[str], old_methods: List[Tuple[Union[str, Callable], str]],
new_methods: List[Tuple[Union[str, Callable], str]], num_runs: int = 1000, repeats: i... | 1bcf1b4c4ac1cb372e14deaf722650be61d9f94b | 609,824 |
def _get_dicom_comment(dicom_file):
""" Returns the contents of the comment field of a DICOM file.
Args:
dicom_file <dicom.dataset>: Opened DICOM file
Returns:
image_comment <str>: DICOM comment
"""
if hasattr(dicom_file, 'ImageComments'):
return dicom_file.ImageComments
... | 85e1d64f6e1fbbce03648f04484aca78592b680d | 609,825 |
def executeCommand(cur, command, vals, returnValue):
"""
Function for for executing a command with values and handling exceptions
:param Psycopg.Cursor cur: cursor object from psycopg2 library
:param str command: the sql command string
:param list vals: list of values for the command
:param boo... | b5a92a19e5bda9bacb8c622636a827ccc94ed81d | 609,830 |
def get_dvcs_with_cves(dvcs):
"""Get only the devices that have vulnerable sw info."""
return [x for x in dvcs if x.get("specific_data.data.software_cves")] | 2fdb087c59ef212da8efed9e526eaef4ff69d630 | 609,831 |
def remove_duplicates(sentence: str) -> str:
"""
Remove duplicates from sentence
>>> remove_duplicates("Python is great and Java is also great")
'Java Python also and great is'
>>> remove_duplicates("Python is great and Java is also great")
'Java Python also and great is'
"""
retu... | a40a4841115f8dfe5a04307d600b273b6eebb00b | 609,834 |
import sqlite3
def is_slug_used(slug:str) -> bool:
"""
Returns a boolean value whether the given slug has been used or not.
"""
conn = sqlite3.connect("./urls.db")
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS urls(original_url text, slug text)")
c.execute("SELECT (slug) FROM url... | fdeef121e0ec78fc029bda41140fcb2f466a7538 | 609,835 |
def graph2data(graph):
"""Returns the index and data of a sparse matrix.
Parameters
----------
graph : csr_matrix
A sparse matrix of the edges in a graph and corresponding node indexes.
Returns
-------
index1, index2 : array
Arrays of the node indices of the graph.
weig... | 3435fb35da65eebf54ac3baccf1e6a5d80f46dbc | 609,839 |
def assert_exactly_one(*args, **kwargs):
"""Assert that only one of the given arguments passes the provided truthy function (non-None by default).
Args:
truthy_fxn: a filter to redefine truthy behavior. Should take an object and return
True if desired conditions are satisfied. For example:
... | d4bf485f18749e666c2d2e9ed9991a53c8f303cb | 609,840 |
def s3_put_bucket_versioning(s3_obj, bucketname, status="Enabled", s3_client=None):
"""
Boto3 client based Put Bucket Versioning function
Args:
s3_obj (obj): MCG or OBC object
bucketname (str): Name of the bucket
status (str): 'Enabled' or 'Suspended'. Default 'Enabled'
s3_c... | d27aa31a4851111c4af35b7eb154cd3b1dca368e | 609,841 |
def get_converter_type_uuid(*args, **kwargs):
"""
Handle converter type "uuid"
:param args:
:param kwargs:
:return: return schema dict
"""
schema = {
'type': 'string',
'format': 'uuid',
}
return schema | 2841ba2ff4d0994371dabe581f8350b4971a9144 | 609,843 |
def Efw(cf, cw, swi, p, pi):
"""
Calculate formation expansion factor
"""
Efw = ((cf + cw * swi) / (1 - swi)) * (pi - p)
return (Efw) | fb71947bbce089c9eaec96914bbed6ed51292879 | 609,846 |
def getLength(array):
"""
Get the length of an array like object.
INPUT <= array object
OUTPUT => integer array length
"""
count = 0
for _ in array:
count += 1
return count | f95e1b5cb3bc7e7071e5549bdc5581ccf9c5e20a | 609,851 |
import torch
def _shape(img: torch.Tensor) -> torch.Tensor:
"""
Shapes a 4D input tensor from shape [C, X, Y, Z] to [C, Z, X, Y]
* some torchvision functional transforms only work on last two dimensions *
:param img: torch.Tensor image of shape [C, X, Y, Z]
:return:
"""
# [C, X, Y, Z] ->... | 9a2fcbb196f8257f6d45747c7a288e3164217127 | 609,852 |
def getDivisors(n):
"""
input: positive integer 'n' >= 1
returns all divisors of n (inclusive 1 and 'n')
"""
# precondition
assert isinstance(n,int) and (n >= 1), "'n' must been int and >= 1"
ans = [] # will be returned.
for divisor in range(1,n+1):
... | aedf64447bf386b44c289d6ce4b26876a8c6e542 | 609,854 |
import torch
def compute_importance_weights(target_output, behaviour_output, action, requires_grad=False):
"""
Overview:
Computing importance sampling weight with given output and action
Arguments:
- target_output (:obj:`torch.Tensor`): the output taking the action by the current policy ne... | f4fdef08a968b14bb5a80a2638c9fcd5dad31f32 | 609,855 |
def getSquareDistance(p1, p2):
"""
Square distance between two points
"""
dx = p1[0] - p2[0]
dy = p1[1] - p2[1]
return dx * dx + dy * dy | f3ba46e3c57d25335c16139b0b25f829e671094d | 609,856 |
import aiohttp
async def contests_html(
session: aiohttp.ClientSession,
page: int,
) -> str:
"""Get html of a contest page.
Args:
session (aiohttp.ClientSession) : session
page (int) : number of page (0..)
Returns:
Html of page.
"""
url = "https://codeforces.com/c... | e7899ac64c6d1f88a4dc90b69d6ab8f537caa2ec | 609,858 |
def IsInverse(a, b) -> bool:
"""Checks if two provided directions are the opposites of each other.
"""
if (a == 2 and b == 3) or (a == 3 and b == 2):
return True
if (a == 0 and b == 1) or (a == 1 and b == 0):
return True
return False | a3dc11f83a633852db6d0d9f46191a13f22a8b26 | 609,860 |
from json import load
from pathlib import Path
import logging
def load_single(file_name):
"""
Load a single json file
Parameters
----------
file_name : str, Path
file_name to load from
Returns
-------
dict
the loaded json as a dict ``{data}``
"""
if Path(fil... | 9fc75dc3f0adf92bad7ec5883192099087b2048e | 609,862 |
import pickle
def read_pickle(filename, encoding='ASCII'):
"""Read an object from a pickle file.
No error handling is done by this function!
Args:
filename (str): Full path of filename.
Returns:
any (obj): Object within the file. It can be of any type.
"""
with open(filename... | a82d8bc346a949eddaf14941a839928ede443474 | 609,865 |
def calculate_mrr(correct: list, guesses: list):
"""Calculate mean reciprocal rank as the first correct result index"""
for i, guess in enumerate(guesses, 1):
if guess in correct:
return 1 / i
return 0 | bb07d1e8937ae38cf3c2edde71d020aff0425c39 | 609,869 |
def Beta22_1(X):
""" Coefficient for the 1PN tidal correction to h_22 mode
Defined in arXiv:1203.4352, eqn A15
Input
X -- mass fraction of object being tidally deformed
Output
double, coeff for 1PN tidal correction to h_22 mode """
return (-202.+560.*X-340.*X*X+45.*X*X*X)/42./(3.-2.*X) | 2c7dbd9219e7a5bdebf28d8d4894c84c65809204 | 609,872 |
def create_toc(headlines, hyperlink=True, top_link=False, no_toc_header=False):
"""
Creates the table of contents from the headline list
that was returned by the tag_and_collect function.
Keyword Arguments:
headlines: list of lists
e.g., ['Some header lvl3', 'some-header-lvl3', 3]
... | 244e3aa80daac431e7e86751f965fbf38e9572cc | 609,873 |
def extract_tuple(mapping, keys):
"""
Extract a tuple from a mapping by requesting a sequence of keys.
Missing keys will result in `None` values in the resulting tuple.
"""
return tuple([mapping.get(key) for key in keys]) | cbdd62d33599cb86f7b85298544b3f046c950a82 | 609,877 |
from typing import Dict
def _parse_structured(definitions: Dict) -> Dict:
"""
Parse structured workflow definitions.
:param definitions: structured workflow definitions
:returns: dictionary mapping (type, id, version) to definition.
"""
repositories = {repo["name"]: repo["path"] for repo in ... | ea4afb7407546df3951e6a7a1e7b7cb4d05bfb7c | 609,880 |
from typing import Dict
from typing import Callable
from typing import Union
def get_dot_segment_regimes(
dot_segments_classification_result: Dict[int, Dict[str, int]],
determine_regime: Callable[[Dict[str, Union[bool, int]]], int],
) -> Dict[int, int]:
"""Takes the classification results of several datas... | 7365e5a2e9d67837d28d7ff3ef1228f27b4c7640 | 609,882 |
import time
def _runtime(runnable, *args, **kwargs):
"""
Record how long it took to run something
"""
start_time = time.time()
ret = runnable(*args, **kwargs)
end_time = time.time()
return (end_time - start_time), ret | 6c74adfaa550f6470f31b33dca60008c137a9369 | 609,888 |
def drop_sic_codes_na(df):
""" Removes all rows with missing SicCodes
"""
return df.dropna(subset=['SicCodes']).reset_index(drop=True) | 9c923abdf5abb96f963c5f323b6505fcc8ccd08c | 609,892 |
def get_problems(df):
"""
Gets all problem names
"""
problems = df['Problem'].unique()
problems.sort()
return problems | a57751dd1d59c19f28096b9804116ed773191b77 | 609,894 |
def _contents(path: str) -> str:
"""Get contents of a file for comparison."""
with open(path, "r", encoding="utf-8") as out:
return out.read() | 7cd716cbca31fc93f113d0c5a47589df7e50ea4e | 609,900 |
from datetime import datetime
def unix_timestamp_to_wayback_timestamp(unix_timestamp: int) -> str:
"""
Converts Unix time to Wayback Machine timestamp, Wayback Machine
timestamp format is yyyyMMddhhmmss.
"""
return datetime.utcfromtimestamp(int(unix_timestamp)).strftime("%Y%m%d%H%M%S") | bfa61abe2d9dee87ee30e97489be76fc2f9b5393 | 609,901 |
def get_object_by_name_or_id(cb, cls, name_field="name", id=None, name=None):
"""
Locate an object in the API by either ID or name.
Args:
cb (CBCloudAPI): Reference to the CBCloudAPI.
cls (class): Class of object to be found.
name_field (str): Name field to search on.
id (in... | b946199e051acee117a6ba4e87dca8a7c94ae733 | 609,902 |
def check_stats_record_format(record):
"""check that the aggregation buckets have the expected format"""
assert {'key', 'doc_count', 'size'} == set(record.keys())
assert set(record['size'].keys()) == {'value'}
assert isinstance(record['key'], str)
assert isinstance(record['doc_count'], int)
asse... | 8ed3a90f8af6f2380a6e3d8ccf986b738ff8befe | 609,904 |
from textwrap import dedent
def base_spec(cursor):
""" A spec with the existing state of the test database before anything has been done """
spec = dedent("""
postgres:
attributes:
- BYPASSRLS
- CREATEDB
- CREATEROLE
- REPLICA... | 57af1fb7be4be69874435f5adf3d1388c0e67b53 | 609,906 |
import torch
def log_sum_exp(value, dim=None, keepdim=False):
"""Numerically stable implementation of the operation
value.exp().sum(dim, keepdim).log()
"""
if dim is not None:
m, _ = torch.max(value, dim=dim, keepdim=True)
value0 = value - m
if keepdim is False:
m =... | d8b519bb70437b6e710ea81540ce734dd5d8359b | 609,907 |
import binascii
def is_gz_file(data):
"""
check if bytes are gzipped
"""
return binascii.hexlify(data[:2]) == b'1f8b' | 9677602bd3f57828f6d161d576d46f683a349564 | 609,911 |
import re
def extract_form_failures(content):
"""
Given raw HTML content from an HTTP response, return a list of form errors.
"""
FORM_ERROR_REGEX = r'<!-- FORM-ERROR (.*) -->'
return re.findall(FORM_ERROR_REGEX, str(content)) | 1cb8b2549ad7cf0b6cf39d7209480eb50920b060 | 609,912 |
def is_hex(string):
"""test if string is hex"""
try:
int(string, 16)
return True
except ValueError:
return False | 639648505ab7b9661a8c86c33f7a263704810f99 | 609,913 |
import torch
def fft_frame(img):
"""Calculate FFT of a given image.
Args:
img (torch.Tensor): Image tensor. Shape [B,C,H,W]
Returns:
torch.Tensor: Amplitude and phase of FFT result. Shape [B,C,H,W]
"""
fft_im = torch.fft.rfftn(
img, s=img.shape[-2:], dim=[-2, -1], norm="... | 7fc0ae811335010a0de58a8aeddd491d4fc45216 | 609,916 |
def batch_mult(A, u, has_batch=None):
""" Matrix mult A @ u with special case to save memory if u has additional batch dim
The batch dimension is assumed to be the second dimension
A : (L, ..., N, N)
u : (L, [B], ..., N)
has_batch: True, False, or None. If None, determined automatically
Output... | b08ef007918a8a4b1d05eb56b57a019c6e26b426 | 609,919 |
import pathlib
def read_text(path: str) -> str:
"""read ascii content at `path`
e.g
j.sals.fs.read_text("/home/rafy/testing_text.txt") -> 'hello world\n'
Args:
path (str): ascii file path
Returns:
str: ascii content in path
"""
return pathlib.Path(path).read_text() | fbb5da6a431cb2866d85e1b81a025a0b9d468698 | 609,920 |
import json
def get_bundled_metadata(filename):
"""
Retrieve the metadata about a bundled library from a python file
:arg filename: The filename to look inside for the metadata
:raises ValueError: If we're unable to extract metadata from the file
:returns: The metadata from the python file
""... | 1de39c4605198a05ee6b80d28cfe393f8b6c85c9 | 609,922 |
def old_guard(A,B,C,D,E,F,G):
"""return a falsy value (None) if checks fail, otherwise return True
this is the "control" for the experiment"""
# Ignore A without a heavy check on each invocation
# this kills it right at the function call
if A:
return
for _ in range(1):
if B:
break
if C:
if D:
bre... | 2e03bd6ddc1cf649c7c872dd2882a5edca04c945 | 609,925 |
def parse_squares(input_squares):
"""Parse squares from the input_squares.
Returns dict with keys being id of square and value list of str with
square contents"""
squares = {}
for square in input_squares:
if square:
lines = [line.strip() for line in square.split('\n')]
... | 19fd954297070f9aa91f373eacc34c8862be114e | 609,928 |
def parse_directions(filename):
""" Load the direction string from FILENAME. """
# Rooms = '.', walls = '#', doors = '|' or '-'.
# Current position = 'X'.
# Rooms are size 1.
# Movement is possible only through doors.
# Start = '^', end = '$'.
# Parenthesis containing a final '|', e.g. (NEWS... | 376c2bd17fdd114820c685570cf4269e455aaff7 | 609,929 |
def readDiff(fname):
"""Function that returns a list of changes based on a IDA dif file."""
changes = []
with open(fname, "r") as f:
for line in f:
if ':' in line:
offset, diff = line.split(':')
before, after = diff.lstrip().split(' ')
afte... | 318c53ef8e02cff1661df9c08f89a4d3e9b6e3f1 | 609,935 |
def copy_digesters(digesters):
"""Returns copy of provided digesters since deepcopying doesn't work."""
result = {}
for hash_algorithm in digesters:
result[hash_algorithm] = digesters[hash_algorithm].copy()
return result | 56cd4c26d6c8cb5c5f82ac3420f1165bb8c8e9fc | 609,938 |
from typing import Any
from typing import List
def listify(x: Any) -> List[Any]:
"""turns x into a list.
If x is a list or tuple, return as list.
if x is not a list: return [x]
if x is None: return []
Args:
x (Any): some object
Returns:
List[Any]: x, as a list
"""
ret... | e4368f8540adade2edb12092335249bf35047e37 | 609,940 |
def _process_upsert(existing, change):
"""
Process an I{UPSERT} change.
"""
# Replace whatever was there with whatever was specified.
return change | 864cc74f3cb0f0d5f9da737a7ef58db9cfe5121d | 609,941 |
from typing import Tuple
from typing import List
from typing import Dict
import requests
def call_openweatherapi(
api_key: str, location: Tuple[float, float]
) -> Tuple[int, List[Dict]]:
"""
Make a single "one-call" to the Open Weather API and return the API timestamp as well as the 48 hourly forecasts.
... | 85c5358807ca04646e6009cd060687483d92bd91 | 609,943 |
def float_format(number):
"""Format a float to a precision of 3, without zeroes or dots"""
return ("%.3f" % number).rstrip('0').rstrip('.') | dc3cdf8c3325a5fc057f8085fb4216241fe8dc93 | 609,948 |
def binary_to_decimal(string):
"""Converts a binary string, sign bit then msb on left, to an integer.
Negative numbers are assumed to be twos-complements, i.e., bitwise
complement + 1."""
length = len(string)
# negative part doesn't work
if string[0] == '1':
negative = True
else:
... | 04cab5d22242cb58b65964e0681f0b2c722d942e | 609,950 |
def is_edge_esn(esn):
"""Return True if the esn is an EDGE esn"""
return esn.startswith('NFCDIE-02-') | 91ea73762e54f22166d225a62ff3fb6112fdf576 | 609,951 |
def parse_parameters(config):
""" Compile the microbenchmark parameters used when running the test """
return {
'threads': config.num_threads,
'min_runtime': config.min_time
} | 22f65d22616013ccf650befda416e55d3064eff6 | 609,952 |
def remove_ext_filename(filename):
""" Remove OTB extended filenames (keep only the part before the "?") """
if "?" in filename:
return filename[:filename.rfind("?")]
return filename | 8a4a660a0f4d996032f7a660275f9456384d0700 | 609,955 |
def to_list_sorted_by_value(dictionary):
"""Convert a dictionary in a sorted list by value."""
return list(
reversed(
sorted(
[(key, value)
for key, value in dictionary.items()],
key=lambda elm: elm[1]
)
)
) | 6a24ff0d3f81c4b394d2047134737ef2ad14bf9c | 609,956 |
def _get_basic_autoscaling_config() -> dict:
"""The expected autoscaling derived from the example Ray CR."""
return {
"cluster_name": "raycluster-complete",
"provider": {
"disable_launch_config_check": True,
"disable_node_updaters": True,
"namespace": "default... | 184337916d463f3aa5b6f20e84cd8ec9cb20af07 | 609,959 |
def parse_input(txt_path):
"""parse input TXT file to input list"""
inputs = []
with open(txt_path, encoding="UTF-8") as file:
for line in file:
inputs.append([int(x) for x in line.strip()])
return inputs | e4fae22d338a22a6e2f94686307851a269dcce91 | 609,960 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.