content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def clean_headers_server(header):
"""
Only allows through headers which are safe to pass to the client
"""
valid = ['content-length', 'content-type', 'x-roll-ntime',
'x-reject-reason', 'noncerange']
for name, value in header.items():
if name.lower() not in valid:
de... | 56ed177fa7fa7df2e9a55dde4f2eed47ef6dabe5 | 594,138 |
def S_find_range_values(_data_list):
"""
Returns smallest and largest values in the one dimensional dataset
"""
return (min(_data_list), max(_data_list)) | fb86f5620b02cf2c6d365f0e0aff4523752f0ae7 | 594,140 |
def delta(a, b):
"""
Function that returns the Kronecker delta delta(a, b).
Returns 1 if a = b and 0 otherwise.
"""
if a==b: return 1
else: return 0 | 8d7df48163a78a0ccaa2ac788bed0d4718efcb92 | 594,146 |
def is_coach(user):
"""
Returns True if the user is a coach, False otherwise.
"""
try:
user.coach
return True
except:
return False | 4e0ffa173e75d5d3033091315affd388127174f0 | 594,147 |
def __format_datetime_input(datetime_input, language):
"""Formats the specified datetime input.
Args:
datetime_input (dict): A datetime input configuration to format.
language (dict): A language configuration used to help format the input configuration.
Returns:
dict: A formatted d... | f9dfc2c8d5865445c83d0d65f7701cc0ac698228 | 594,152 |
def create_name_simu_and_info(index, prm):
"""Create name_simu and info key"""
prm['name_simu'] = prm['name_simu'] + "_" + str(index)
prm['info'] = 'date_' + prm['date'] + '_name_simu_' + prm['name_simu'] + '_model_' + prm['model']
return (prm) | 11cfdd08ab788c50a94076c34b29e14dfe7dbf2c | 594,154 |
def all_of(*conditions):
"""Returns True if all of the conditions match"""
def check():
for c in conditions:
if not c():
return False
return True
return check | f171b56c57bb8b697d55ebd51ccc41fabf5937c3 | 594,156 |
def model_y(ec, params):
"""
Simple model of a kinematic trajectory.
Args:
ec (`dict`): dictionary with a key 't' leading to a float value
params (`dict`): dictionary with keys 'v0' and 'g' leading to float values
Returns:
float: y-value at the given time assuming the given par... | a7625e64262f2eb02beb3f66bdc0b8bf9cc5951a | 594,157 |
def get_value(component, name):
""" Get a variable from a component """
variable = component.variables[name]
vr = [variable.valueReference]
if variable.type == 'Real':
return component.fmu.getReal(vr)[0]
elif variable.type in ['Integer', 'Enumeration']:
return component.fmu.getInte... | 5a36efdea0d36339a8b6f818742bb0bc9827e8ed | 594,160 |
def PO2_Calc(KO2, tO2, Kr, I, qO2):
"""
Calculate PO2.
:param KO2: oxygen valve constant [kmol.s^(-1).atm^(-1)]
:type KO2 : float
:param tO2: oxygen time constant [s]
:type tO2 : float
:param Kr: modeling constant [kmol.s^(-1).A^(-1)]
:type Kr : float
:param I: cell load current [A]... | 425d379d6818a083cc05a905e879ffd94668c14b | 594,163 |
def cast_date(dcm_date):
"""
Cast DICOM date string (YYYYMMDD) into ElasticSearch pre-defined strict_date format (yyyy-MM-dd)
"""
return dcm_date[:4] + '-' + dcm_date[4:6] + '-' + dcm_date[6:] | 6cd5eb8ec361e858d6ae1ccd38a233cc116e28e1 | 594,169 |
def _union_lists(l1, l2):
"""
Returns the union of two lists as a new list.
"""
return l1 + [x for x in l2 if x not in l1] | 5bf64739a42ff54b22d1c47472f4472ceb7da7ac | 594,175 |
import imp
def __import__(name, path):
"""
Imports a module that is outside of python path.
Modified from Python Library Reference.
Arguments:
- name: module name (file name without '.py')
- path: directory where the module resides, relative to the directory
of the calling functi... | 5a8b966ed66f9eceb713124d81baab0c7380a138 | 594,177 |
import socket
def isAvailable(port, family=socket.AF_INET, sockType=socket.SOCK_STREAM):
"""Return True if the specified socket is available, False otherwise
"""
s = socket.socket(family, sockType)
try:
s.connect(("localhost", port))
s.close()
return False
except Exception:... | 199ab1acb556fa0bce4ef08b244eec08edb50bc0 | 594,179 |
def make_stdout(data):
"""Returns a valid log output with given data as message."""
return ' 1553110400.424 5583 5658 D Tag: %s' % data | 4480997cbe71cf58be9737b2525f46922fc42a4a | 594,181 |
def snapshot(path, compression="AUTO", reader_func=None, shard_func=None):
"""API to persist the output of the input dataset.
The snapshot API allows users to transparently persist the output of their
preprocessing pipeline to disk, and materialize the pre-processed data on a
different training run.
This AP... | 6652b69037ca5944661153e96cda4ccc25f8c777 | 594,182 |
def get_exposure_value(tags):
"""Extracts exposure value from given tags
"""
if tags and "EXIF ExposureTime" in tags:
exposure = tags["EXIF ExposureTime"]
exposure = eval(str(exposure))
return exposure
return None | b925eccd462eebf371d1ac540a4e73ffb5155474 | 594,185 |
def get_kappa(searchers: dict):
"""Retrieve kappa from each searcher and return as list"""
kappa_list = []
for s_id in searchers.keys():
s = searchers[s_id]
kappa_list.append(s.kappa)
return kappa_list | 899ebd8b9ca6259f253e380e8000e33550d838b2 | 594,192 |
import string
def first_int(s):
"""Return the first integer in a string, or None"""
# This technique appears to be faster than the re-based method
# by almost an order of magnitude. Prefer it
ret = ''
for c in s:
if c in string.digits:
ret += c
else:
break... | 63499dfd382836571690dc34c80d7a9b319ecb49 | 594,193 |
def chunk(seq, size):
"""Return generator that yields chunks of length `size` from `seq`."""
return (seq[pos:pos + size] for pos in range(0, len(seq), size)) | 48bf7f09a4225ddaad8c746a17bdf0c567aa29d8 | 594,195 |
def get_msg_data(msg):
"""Get message data."""
return msg["data"] | 26abc3d87efc6f06766d5225ede6d0e2e707fd1f | 594,196 |
def is_box_in_zones(box, zones):
"""Determine if an object bounding box is within a list of zones"""
for zone in zones:
# print('alwaysai.py: is_box_in_zones: zone: {}'.format(box, zone))
if zone.box is None:
# zone.box = edgeiq.BoundingBox(zone.start_x, zone.start_y, zone.end_x, zon... | ae9f3fd2bca7d7beca189bb1cba10757eeb1b8dc | 594,199 |
def check_for_border(m_index_list, m_borders):
""" Checks for the borders of membrane regions, from M indices.
Parameters
----------
m_indices : list
List of membrane region indices, extracted from the flatfile, (e.g. IIIMMMMMMMMMOOOO for Inside, Membrane and Outside),
giving the list o... | 566ef9e9a44add45b06a1793ac709a4790f33bfb | 594,203 |
def remove_dupes(L):
"""
Given list L of words, return set of unique words
"""
return list(set(L)) | b31983d5f718e6f307863630d2bc0d05bec7b566 | 594,205 |
def get_markdown_title(markdown_src):
"""
Get the title of a Markdown document. The title in this case is considered
to be a H1 that occurs before any other content in the document.
The procedure is then to iterate through the lines, stopping at the first
non-whitespace content. If it is a title, re... | dcca2c39498b6f6ff7fbbc8841ff591a29e92caf | 594,206 |
from typing import Set
def digit_rotations(n: int) -> Set[int]:
"""Finds all unique digit rotations of a positive integer in base 10.
Args:
n: A positive integer value.
Returns:
A set of all distinct integers that result from rotating the base-10
digits of ``n``. A rotation is gi... | 017c70a3144580154556bdaef17d1228acab1118 | 594,211 |
def get_ycbcr_bands(image):
"""Returns a tuple of the 3 bands (Y, Cb, Cr)."""
color_transformed = image.convert(mode='YCbCr')
return color_transformed.split() | b1a4a5656af3aac7787309d21dfd2e0bdecc0f7f | 594,213 |
from datetime import datetime
def _get_timezone_name(timezone):
"""
Returns the name of ``timezone``.
"""
try:
# for pytz timezones
return timezone.zone
except AttributeError:
# for regular tzinfo objects
local_now = datetime.now(timezone)
return timezone.tz... | 58dd376b70abd2d94dd11e930ffaf464136dcba3 | 594,215 |
def AvgPoolSequence(attn_mask, feats, e=1e-12):
""" The function will average pool the input features 'feats' in
the second to rightmost dimension, taking into account
the provided mask 'attn_mask'.
Inputs:
attn_mask (torch.Tensor): [batch_size, ...x(N), 1] Mask indicating
... | ab78a502dcb15d14774c415877703ba009fec814 | 594,216 |
def find_all_connecting(graph, start, end):
"""Return the set of all nodes along all paths
between start and end. The start and end nodes are included
in the set if they're connected.
"""
if start == end:
return set()
Gsucc = graph.succ
Gpred = graph.pred
fwdset = set()
bac... | 340d731707714624f545dcb3226ccf76dcb803c3 | 594,217 |
def Binom(n, k, d={}):
"""Compute the binomial coefficient "n choose k".
Args:
n: number of trials
k: number of successes
d: map from (n,k) tuples to cached results
Returns:
int
"""
if k == 0:
return 1
if n == 0:
return 0
try:
return d[n, k]... | 3d9c5aefbe59d55df5f379d3499e9aa1cfad94fc | 594,218 |
def get_by_pickup(state,b1):
"""Generate a pickup subtask."""
if state.is_true("clear", [b1]): return [('pickup_task',b1)]
return False | 3a5a6c9960b210ca8d860f914fb848472590d0be | 594,220 |
from pathlib import Path
def path_to_string(value):
"""Convert paths to strings."""
if isinstance(value, Path):
value = str(value)
elif isinstance(value, list) and len(value) and isinstance(value[0], Path):
value = [str(val) for val in value]
return value | 49dacc77801659f333d6bd027a3847b2d705e977 | 594,223 |
def setCopy( set ):
"""(shallow) copy a set"""
return set[:] | 5ccfcf3729d7bd77c173d9ba2aa90911e7c3fe25 | 594,226 |
def find_centroid(gdf):
"""Find the centroid of polygons, even when in a geographic CRS
If the crs is geographic (uses lat/lon) then it is converted to a projection before
calculating the centroid.
The projected CRS used here is:
<Projected CRS: EPSG:2163>
Name: US National Atlas Equal Area
... | 55deee713be88b189e713e226801fee9e628c43c | 594,227 |
def _get_dihedral_rb_torsion_key(dihedral, epsilon_conversion_factor):
"""Get the dihedral_type key for a Ryckaert-Bellemans (RB) dihedrals/torsions
Parameters
----------
dihedral : parmed.topologyobjects.Dihedral
The dihedral information from the parmed.topologyobjects.Angle
epsilon_conver... | 6e706227adff4892be02a799720274c0419c0427 | 594,229 |
def noop(x):
"""No-operation/identity function."""
return x | d248c0f5605428ba22a9d903b3ccad60b2ac8fff | 594,238 |
def probs_out_of_counts(array_counts):
"""
function that takes an array-like object (e.g. a list) with counts and calculates
the corresponding probabilities
"""
sum_count = array_counts.sum()
factor = 100/sum_count
array_probs = []
for i in array_counts:
array_probs.append(i*fac... | c3fee447acc37d1b6abed748419f4d1ca7e4962f | 594,239 |
def user(rel):
"""Add relationship category prefix for user resources.
Parameters
----------
rel: string
Link relationship identifier
Returns
-------
string
"""
return 'users:{}'.format(rel) | 29889bf671dce63a15ec656924e44eae0a935950 | 594,242 |
def get_selected_action(body):
"""Get selected value from an action event"""
if body["actions"] is not None and len(body["actions"]) > 0:
return body["actions"][0]["selected_option"]["value"] | 21f71fdbc13b11b88054161abd25213847ca85ad | 594,244 |
def lbyl_convert(text):
"""
>>> lbyl_convert("123")
123
>>> lbyl_convert("-5")
"""
if text.isdigit():
num= int(text)
else:
num= None
return num | 5f8f5f511f8d1bde7a33ec86166e8297fb772637 | 594,245 |
def find_connected_vertices_to(graph, vertice):
"""Given a graph and a vertice, find all other vertices that are connected to it"""
visited = [] # if the visitation order to vertices isn't relevant, a set is better for performance purposes
def dfs(node):
"""Actual DFS algorithm"""
visited... | 58d9b2622d9be9d2da84964e4cf977cf9955442e | 594,246 |
def build_dataset_attributes_json_object(output_files, container_name, num_files, num_multi_page,
percentage_multi_page):
"""
:param output_files: The files to output
:param container_name: The storage container name
:param num_files: The number of files process... | f49a1f4dbd15d49aea228c9689de4cd3a053b0a1 | 594,248 |
def match_any(iterable, predicate):
"""Returns True if at least one item in the iterable matches the predicate."""
for x in iterable:
if predicate(x):
return True
return False | 93f366b2174e38d9ed230a747e55f59f02dad7c8 | 594,251 |
def get_province(project_object):
"""
Return province of project in lowercase
"""
try:
return project_object['province'].lower().strip()
except:
return 'unknown' | 9799645b7d2cc4b7eeafdb56a9945d35eb81cca9 | 594,252 |
def create_cfg_test_daemon(
run_dir,
receptor_f,
ligand_f,
*ignore,
**everythinelse):
"""
Create HADDOCK3 configuration file that only generates the topology.
This function is usefull to use test the benchmark daemon.
"""
cfg_str = \
f"""
run_dir = {str(run_d... | 898bcf66b812b5ff2fe2f90f1b3264070213b1cf | 594,257 |
def layout_items(layout):
"""
Returns the items from the given layout and returns them
:param layout: QLayout, layout to retrieve items from
:return: list(QWidgetItem)
"""
return [layout.itemAt(i) for i in range(layout.count())] | f3f823908fae217234ab889bf9671d6b32aa9323 | 594,259 |
import math
def text_center(text, width, padchar=" "):
"""
Center `text` in a string of width `width` padded on both sides by varying
lengths of `padchar`.
"""
tlen = len(text)
out = ""
if tlen > width:
# Append "..." to signify a continuation.
out = "..."+text[(-1*width)+2... | 68e563a479f981a1011cc30e892931e19d2122c7 | 594,263 |
def Q_distcooler(P_mass, Cp, t_coolwater_exit, tp):
"""
Calculates the heat load of distilliat cooler.
Parameters
----------
W_mass : float
The mass flow rate of distilliat, [kg/s]
Cp : float
The heat capacity of distilliat, [J/(kg * degrees C)]
t_coolwater_exit: float
... | 200a3fc54e81f1cb5cbd6179e6857b7a599be1e4 | 594,264 |
def status(prog_comp, obs_comp):
"""
Compute weighting factor representative of observation and program status.
- 1.0 if observation and program have not been observed
- 1.5 if program has been partially observed
- 2.0 if observation has been partially observed
Parameters
------... | cec07dca621ac402fe9260b12a063c9c0291c164 | 594,265 |
def _apply_decreasing_rate(value: float, rate: float) -> float:
"""
Apply a decreasing rate to a value
:param value: current value
:param rate: per second
:return: updated value
"""
return value - (60 * rate) | 595364d8f53a3baf8631326a6297ec9aad1d424b | 594,271 |
def round_float_math(number: float) -> int:
"""
Unified rounding in all python versions.
Parameters:
----------
number : float
Input number.
Returns:
-------
int
Output rounded number.
"""
if abs(round(number) - number) == 0.5:
return int(2.0 * round(0.5... | 5b51557787900b472c8eacf9bd89af92be949f78 | 594,275 |
import torch
def log_sum_exp(x):
"""
Compute log(sum(exp(x), 1)) in a numerically stable way.
Assumes x is 2d.
"""
max_score, _ = x.max(1)
return max_score + torch.log(torch.sum(torch.exp(x - max_score[:, None]), 1)) | d827b8de10459ad5b3cdeec63f871fc2c41a85bf | 594,283 |
def get_num_bins(args):
""" Gets the number of bins that will be used in this analysis.
"""
n_maf = 2 if args.maf_bins_2 else 5
n_ld = args.num_ld_bins
return n_maf * n_ld | 86f4360a11713b2331c24e5b0eacbbae75bfffe0 | 594,284 |
from typing import Dict
from typing import Any
def get_asset_custom_context_for_whois(resp: Dict[str, Any], whois_content: Dict[str, Any]) -> Dict[str, Any]:
"""
Modifying the lists fetched from whois details of response to comma separated strings.
:param resp: Response fetched from the API call
:par... | 8c693f11e05a1972f28c07736f383a806fee41c0 | 594,285 |
import math
def expected_unanchored_L2_discrepancy(num_points, dimension):
"""Expected value for unanchored L2 discrepancy of random uniform points.
Note that this is the square root of :math:`\\mathrm{E}(T^2)`, i.e.
``sqrt(1.0 / n * (6 ** -d) * (1 - 2 ** -d))``. For details see
[Morokoff1994]_.
... | 22f3230a6eb2c5a7cecccd97171df3cf85085f86 | 594,287 |
def anagram1(S1,S2):
""" Checks if the two strings are anagram or not"""
S1 = S1.replace(' ', '').lower()
S2 = S2.replace(' ', '').lower()
if len(S1) != len(S2): return False # Edge case check
count = {}
for x in S1:
if x in count:
count[x] += 1
else:
... | 998fe84d5c79b733c30a5162874a3d9e9944b425 | 594,289 |
import json
def load_speeddial(file_path):
"""
Load the bookmark entries from Vivaldi's speed dial and return as
dictionary
"""
# read bookmark file
with open(file_path, encoding="UTF-8") as jfile:
bookmarks = json.load(jfile)
# access speed dial
speeddial = bookmarks["roots"]... | eeabe66817aee8d8c6fb5fa804585657d0b1c192 | 594,291 |
from typing import Union
from pathlib import Path
from typing import List
def readfile(contents: Union[str, Path]) -> List[str]:
"""
Takes a file path or the contents of a file and attemts to split it into lines.
Parameters
----------
contents: Union[str, Path]
Returns
-------
List[str]
The lines in the f... | 96680fcfdb59224d8e75186969c6ce15eea347b8 | 594,294 |
def parse_CPC2_output(path):
"""Returns sequence IDs lists of cds and non-coding sequences. To to passed into fasta subset."""
with open(path, "r") as f:
contents= f.read().split("\n")
cds=[]
ncds=[]
for line in contents:
if line.split("\t")[-1] == "noncoding":
ncds+=[lin... | 0965e97683220315d2d134307b774a93166db55b | 594,296 |
import statistics
def fitness(population, goal):
"""Measure population fitness based on an attribute mean vs target."""
ave = statistics.mean(population)
return ave / goal | ec1524c0377168b6414b17fcc286770a74e2b655 | 594,298 |
def vni_row_name(network_type):
"""Determine name of row for VNI in allocations table.
:param network_type: Network type to determine row name for.
:type network_type: str
:returns: Row name
:rtype: str
:raises: ValueError
"""
if network_type in ('gre',):
return '{}_id'.format(n... | 289c7e248504071279108dab65a59b8c21a01ee4 | 594,299 |
def are_equal_trees(t1, t2):
"""True if t1 and t2 has the same shape and the same contents. False otherwise"""
if t1.is_empty() and t2.is_empty():
return True
elif t1.is_empty() or t2.is_empty():
return False
else:
return t1.root_element() == t2.root_element()\
and... | 18ec662e57d32771fe7abc5f32bd52ad076595c8 | 594,300 |
def _is_builtin(obj):
"""Check if an object need not be converted."""
return isinstance(obj, (float, int, str, bool)) | f8af7039931ab9815de1c03e20ec675ace9191c9 | 594,304 |
def day_days(d1, d2):
"""
Returns total amount of days between days d1 and d2.
"""
return d2 - d1 | d271907df8f547733f1dfb212f1d6abbb2067462 | 594,305 |
def sort_dict(d: dict, number: bool = False) -> dict:
"""Sort a dict by keys"""
if number:
return dict(sorted(d.items(), key=lambda item: int(item[0])))
else:
return dict(sorted(d.items(), key=lambda item: item[0])) | 4a9eb8bbcb4a522287d3183187f258a28741bc3d | 594,310 |
def combined_prefix(cluster_bin_index, isoform_type, sample_name):
"""Return i{cluster_bin_index}_{isoform_type}_{sample_name}"""
assert isoform_type in ["HQ", "LQ", "ICE"]
return "i{i}_{t}_{s}".format(i=cluster_bin_index, t=isoform_type, s=sample_name) | c8ce9349f8ff0af11b97f744d8db207f576bb1e4 | 594,313 |
def adder_function_json(args):
"""Dummy function to execute returning a dict."""
loc, scale = args
return {'result': loc + scale} | 3b9d1fe0c63a78a6124f0c3de2005da2003e62ea | 594,314 |
import requests
import json
def png2latex(input_path, output_path):
"""
Calls the EqDecoder pipeline with a PNG image and returns JSON containing
the tokenized latex output from OpenNMT.
Args:
input_path: [String] -- in the form: /path/to/input/<filename>.png
output_path: [String] -- ... | ce2a0a9ce5890454cf3cc57722b1ea968c5d0e88 | 594,316 |
def slugify(name) -> str:
"""Return a slugified version of the name."""
return f'#{name.lower().replace(" ", "-").replace("(", "").replace(")", "")}' | 6902f4f47d39597117d074df3b07e65866c8454f | 594,318 |
def get_last_date_of_a_month(date):
"""
Given date, returns the last day of the same month as date.
i.e. if given 15 Jan it would return 31 Jan.
"""
start_month = date.month
next_try = date
while next_try.shift(days=1).month == start_month:
next_try = next_try.shift(days=1)
retur... | a112135e7c711d897ce71007905ae1b8a1cd8d9c | 594,320 |
def _ensure_value(namespace, name, value):
"""Force empty namespace attribute to specified value."""
if getattr(namespace, name, None) is None:
setattr(namespace, name, value)
return getattr(namespace, name) | 60b438d3a6b67d135ff11330c8a1dee23aa262c2 | 594,321 |
def calc_sides(tile: list) -> list:
"""Compute the sides of each tile, returned in a N W S E order."""
return [
tile[0],
"".join([line[-1] for line in tile]),
"".join(reversed(tile[-1])),
"".join([line[0] for line in reversed(tile)]),
] | 80ef30f1b53cc2105cc90d6ca0bafffd1afbca19 | 594,329 |
def is_leaf_node(dt, node_index):
"""Checks if node at node_index is a leaf node to a DecisionTree
Args:
dt (sklearn.DecisionTree): decision tree to be examined
node_index (int): index of node in dt
Returns:
bool : whether node at index is a leaf node in dt
"""
return (dt.c... | 6dac90e9c2ab705a2932c3bcaeb205f15623d941 | 594,330 |
def count_chars(text: str, char_to_count: str) -> int:
"""Count the number of times that 'char_to_count' is found in the 'text'."""
count = 0
for char in text:
if char == char_to_count:
count += 1
return count | 23b8f95a6e82086b7cd8e85002d15c671f476d16 | 594,333 |
def openconfig_to_cisco_af(value):
"""Translate openconfig AF name to Cisco AFI name."""
if ":" in value:
value = value.split(":")[1]
mapd = {
'IPV4_UNICAST': "ipv4 unicast",
'IPV6_UNICAST': "ipv6 unicast",
'IPV4_LABELED_UNICAST': "ipv4 unic... | 2811f061f4a00f63e73289d97fac659df06793de | 594,335 |
import hashlib
def hash256(s: bytes) -> bytes:
"""
two rounds of sha256
:param s: data
:return: hashed data
"""
return hashlib.sha256(hashlib.sha256(s).digest()).digest() | f5b962d89328df5a423820f7171ef4705df2d3c7 | 594,336 |
def sizeof_fmt(num, suffix='B', longsuffix=True, usespace=True, base=1024):
""" Returns a string representation of the size ``num``.
- Examples:
>>> sizeof_fmt(1020)
'1020 B'
>>> sizeof_fmt(1024)
'1 KiB'
>>> sizeof_fmt(12011993)
'11.5 MiB'
>>> sizeof_fmt(123456789)
'117.7 MiB'
... | 192809ce48ccdbeeb657ad0be60414664fc60544 | 594,338 |
def getType(item) :
"""Attempt to determine what type of value a string represents"""
item = item.strip()
if not item : return "NULL"
if item[0] == "$": return "$"
if item.strip("0123456789,.") : return "STR"
return "NUM" | 423fbef0922339c469b313ba76ef7e6c43b3c9d7 | 594,339 |
def PyDateTime_GET_YEAR(space, w_obj):
"""Return the year, as a positive int.
"""
return space.int_w(space.getattr(w_obj, space.newtext("year"))) | b3f0b929ea69e56695d735818a37366197507d06 | 594,341 |
def remove_indices(indices, inds_to_be_rm):
"""
Convert some bound indices to free ones.
The conversion goes as: inds_to_be_rm[i] -> -1 - i
Args:
indices ([int]): list in which the conversion is to be done
inds_to_be_rm ([int]): list of the indices to be made free in order
Return:... | 6149f5641fcd9974ba54aae3168312b2fbbf7aab | 594,343 |
import torch
def gaussian_kernel(x, sigma=4):
"""Gaussian distance kernel.
Args:
x (Tensor): difference between two input features.
sigma (float): standard deviation of the gaussian kernel.
Returns:
The Gaussian kernel for features `x` and standard deviation `sigma`.
"""
return torch.exp(- (x ... | 3445b9ef1316692347eca77d1deab6704d5ab6d6 | 594,344 |
import requests
def get_user_data(username):
"""
Downloads the content of a user profile.
:param username: The user whose profile to retrieve.
:return: html of the user profile
"""
address = 'http://archiveofourown.org/users/' + username + '/profile'
r = requests.get(address)
return r.... | 7230d413f5abfe8d4be1b6333b2ec31ea7924a46 | 594,347 |
def _word_wrap(string, max_length=0):
"""wrap long strings to be no longer than max_length."""
if max_length <= 0:
return string
return '\n'.join([string[i:i + max_length] for i in
range(0, len(string), max_length)]) | f35890b38eb2b871249fbc960486e271397cb419 | 594,349 |
def getArraySize(arr):
""" Return size in bytes of numpy array """
nbytes = arr.dtype.itemsize
for n in arr.shape:
nbytes *= n
return nbytes | 4e7310ad2e93724903def2fe35311817c628c67b | 594,356 |
import math
def cone(individual, position, height, width):
"""The cone peak function to be used with scenario 2 and 3.
:math:`f(\mathbf{x}) = h - w \sqrt{\sum_{i=1}^N (x_i - p_i)^2}`
"""
value = 0.0
for x, p in zip(individual, position):
value += (x - p)**2
return height - wi... | 02ed317b900b34e7d9dee1847a164df9a54417e6 | 594,357 |
def get_file_contents(filename):
"""Returns file content as string."""
with open(filename, 'r') as srcfile:
return srcfile.read() | 5417b3301fe48b72c45172ec88a4f0cd8b2f3006 | 594,364 |
from typing import Iterable
def count(data: Iterable) -> dict:
"""Counts number of occurrences for each item in list."""
return {el: list(data).count(el) for el in set(data)} | 2866af3b0865c92d7e6bab555273034102ebbef1 | 594,367 |
def add_suffix_to_file_name(file_name, suffix=None):
"""Adds the specified suffix, if any, either to the end of the specified
file_name; or, if the file_name has an "extension" starting with a dot ('.'),
then just in front of the dot.
"""
result = file_name
if suffix:
ext_index = str(fil... | ba0641f4f998550bcc2905d64084aca7ead4bfcb | 594,375 |
import re
def remove_urls(text):
"""Remove urls from a string"""
clean = re.compile('https?://\S+?(?=~)')
return re.sub(clean, '~', text) | e47145587e8f12262f0e8dcb4ccc2f8991f47cf9 | 594,380 |
from base64 import urlsafe_b64encode
def encode_payload(payload: str) -> str:
""" Encode payload with URL-safe base64url. """
result: bytes = urlsafe_b64encode(payload.encode())
return result.decode() | a46fa46c85e4e68e677ace40461ce2b00259ec69 | 594,381 |
def settings_name(value):
"""Makes a capitalized name from an option flag."""
return value.lstrip('-').replace('-', '_').upper() | c97739d85d0826d3066a6573badf124c2dd5298e | 594,385 |
def get_package_version_key(pkg_name, pkg_version):
"""Return unique key combining package name and version."""
return pkg_name + '@' + pkg_version | 275349e48bf436c2f592a009c59385afcefd84b1 | 594,386 |
def diff_action(diff):
"""Return 'add', 'replace', or 'delete' based on action represented by
difference tuple `d`. Append "_rule" if the change is a Selector.
"""
if "replace" in diff[-1]:
result = "replace"
elif "add" in diff[-1]:
result = "add"
elif "delete" in diff[-1]:
... | d8a955d024576dac16ba1270b6b4fca2e844bd1a | 594,390 |
def known_devtypes() -> list:
"""Returns the list of known dev types"""
return(['cumulus', 'eos', 'iosxe', 'iosxr', 'ios', 'junos-mx', 'junos-qfx',
'junos-qfx10k', 'junos-ex', 'junos-es', 'linux', 'nxos', 'sonic',
'panos']) | c492bfae8bc844edf91eceaeb7dfba8be7877294 | 594,391 |
def serialize_addresses(multipart_address):
"""Get the addresses from the address segment of a multipart message.
:param multipart_address: A list representing the address part of a
multipart message (including an empty delimiter).
:returns: The list of non-empty addresses.
"""
return [x fo... | ec9a31723f03aa3a7bfa4d7e9262f7885bab8887 | 594,397 |
def _region_by_region_type(all_forecasts):
"""Pick out all regions represented in all_forecasts.
Order by region_type (A regions first) and descending region_id."""
regions_and_type_dict = {}
for f in all_forecasts:
if f.region_type_name not in regions_and_type_dict.keys():
regions_... | 43423f03b6c0ae555c10adc9222f7e1e5ebf2222 | 594,398 |
def _convert_counts_logits_to_mean_disp(total_count, logits):
"""NB parameterizations conversion - Copied over from scVI
:param total_count: Number of failures until the experiment is stopped.
:param logits: success logits.
:return: the mean and inverse overdispersion of the NB distribution.
"""
... | a619936d1091340264aaed7f17e997fa1868bb23 | 594,401 |
def shift_rows(state):
"""
Section 5.1.2: ShiftRows() Transformation
!!! FUN FACT ALERT !!!
Rotating a row by one position to the left is equivalent to polynomial
multiplication by {01}x^3 + {00}x^2 + {00}x^1 + {00}x^0, modulo x^4 + 1
>>> shift_rows(b"ABCDefghIJKLmnop")
bytearray(b'AfKpeJoDInChmBgL')... | 76228e0c8dc3f9c980b497bad3d6b1ceabf49c3c | 594,403 |
def sidak(alpha_orig, p_values):
"""
Sidak correction.
en.wikipedia.org/wiki/%C5%A0id%C3%A1k_correction
Parameters
----------
alpha_orig : float
alpha value before correction
p_values: list[float]
p values resulting from all the tests
Returns
-------
alpha_corr... | 6b1dcf17a53e08462a7dd4ca00c63b11bb3139ca | 594,408 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.