content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import sys
import functools
import signal
def timeout(max_running_time):
"""Test method decorator that fails the test if it executes longer
than |max_running_time| seconds.
It exists to terminate tests in case of deadlocks. There's a high chance that
process is broken after such timeout (due to hanging deadl... | f3f8c55aaea56d0dcf99f666e6f441373b9eff23 | 29,144 |
def z_minus_its_reciprocal(z: complex) -> complex:
"""
The function z - 1/z.
I define this function explicitly because it plays an important role in the model.
Furthermore, we also want to plot it and test it.
Note: I do not handle the case of zero (or infinite) argument here.
Args:
z... | 46de97ee9c628faf5fe626108af801827e2dfc8f | 29,145 |
import subprocess
def run_test(cfg):
""" Runs `npm test` from the correct cwd and returns the return code. """
return subprocess.call(['npm', 'test'],
cwd=cfg.get('Directories', 'test_cwd')) | 11a118c875b8354eb0b887e1149268a8438f2e0b | 29,146 |
from typing import List
def split_str(data_str: str) -> List[str]:
"""
Split a string into a list of strings. The string will be split at ',' or '\n' with '\n' taking precedence.
:param data_str: A string to be split.
:return: List[str]
"""
if '\n' in data_str:
return list(str(data_str... | 450b301f2b696e2240f9bb8fe49def815c59478d | 29,147 |
def findAttrInAttributes(klass, classAttr):
"""Find classAttr in WorkflowAttributes of klass."""
for attr in klass.attributes:
if attr.classAttr == classAttr:
return attr | 0ecf387b24af116e5d4a038d2788f4dab8a4aeeb | 29,148 |
def remove_zp_cluster(clusters):
""" 移除clusters中的零指代
"""
clusters_wo_zp = list()
for cluster in clusters:
cluster_wo_zp = list()
for sloc, eloc in cluster:
if eloc - sloc > 0:
cluster_wo_zp.append([sloc, eloc])
if len(cluster_wo_zp) > 1:
cl... | 13ee735f911e52302c34c46a2df66ef320a3f507 | 29,149 |
def cumulative_discounted_rewards(trajectories):
"""calculate the cumulative rewards for the given trajectories
1. input: a list of trajectories is a list of tuples, one tuple being comprised of the following values, IN ORDER:
1. current state (s)
2. action agent chooses (a)
3. reward (r... | 897b08144093fd1e6bd1c6fd05db0f49be487a17 | 29,150 |
def file_util_read_byte(path):
"""读取二进制文件(byte)"""
with open(path, 'br') as f:
rst_bytes = bytes()
for line in f:
rst_bytes += line
return rst_bytes | eda93cffa54a7a7bdbf617954866bd5cbabdcc64 | 29,151 |
import os
def get_problems(fname="problem_names.txt"):
"""
Get the list of problems in `fname`.
:param fname: The name of the file that has problems.
"""
if os.path.exists(fname):
with open(fname, "r") as problem_file:
raw = problem_file.readlines()
return list(map... | 3b70822bf5ae4aae924b4fce6570c832f576d882 | 29,153 |
def tokenization(tweet):
"""
DESCRIPTION:
Tokenizes a tweet into words
INPUT:
tweet: a tweet as a python string
OUTPUT:
list of tweet's tokens (words)
"""
return list(tweet.split()) | 60c59fdbe775ea8178b3f2c4de6657e3fedd776a | 29,155 |
def tree_named(tree):
"""single node tree fixture - where the node has the service_name field filled out"""
list(tree.values())[0].service_name = 'dummy'
return tree | fe5d1c10004035343498c2eb413f010baeb458e5 | 29,157 |
import time
def tic():
"""start = tic()
start tictoc timer
start - time in seconds
"""
global _tic
_tic = time.time()
return _tic | 85f4e6ccbae8ecccf761e8474d42cb12fcc7466c | 29,158 |
import numpy
def radians_angles_average(x: numpy.ndarray) -> float:
"""
Calculates the average between radian angles.
:param x: numpy array of degree angles in range (0, :math:`2\pi`) or (:math:`-\pi`, :math:`\pi`).
:return: the average.
"""
n = x.size
return numpy.arctan2((1 / n) * numpy... | 87ffa9c968c72f7246bd93b9766d4702a48276d6 | 29,159 |
import sys
import argparse
import os
def get_args(argv):
"""
get args using argparse.ArgumentParser ArgumentParser
e.g: argparse https://docs.python.org/3/library/argparse.html
jumeg wrapper for <mne.io.read_raw_bti>
https://martinos.org/mne/stable/generated/mne.io.read_raw_bti.html#mne.io.read_... | 50830fd4107a333945fb99558444cd0becbad791 | 29,160 |
def ps_probs(feedback_table, confidence, action):
"""
Returns the probability that an action is optimal based off of previous feedback and given the confidence in the
feedback.
"""
# The following is a pretty arbitrary way to prevent overflow, it also artificially limits how much feedback
... | 46e3556d57b07ea1a8c43e02d58f5de08522cea8 | 29,162 |
import re
def _clean_multirc_inputs(dataset_name, text):
"""Removes HTML markup from Multi-RC task input text."""
if dataset_name == "super_glue/multirc":
# Remove HTML markup.
text = re.sub(r"<br>", " ", text.decode("utf-8"))
text = re.sub(r"<(/)?b>", " ", text)
return text | 71d0999ddb9a3942e6d53473c534d55924a0aaa1 | 29,165 |
def is_complex_parsing_required(value):
"""
Determine if the string being parsed requires complex parsing.
Currently, this is solely determined by the presence of a colon (:).
Args:
value (str):
A string that will be parsed.
Returns:
bool:
Flag value to indic... | b5b13eb6f8a28d69a2a069fa8228ace0e842873b | 29,166 |
def is_xxx_exist(data):
"""用来判断com_manage函数中,得到的whois信息是否包含xxx标志,若包括则需要重新发送"""
if data.find("\"xxx\"") != -1 and data.find("\"=xxx\"") != -1:
return True
else:
return False | e23d995e18d2c604e3d587ba1784bc0717f135e4 | 29,168 |
def merge_nodeproviders(*nodeproviders):
"""
Create a term-mixed NodeProvider from multiple instances.
"""
# General checks.
if len(nodeproviders) == 0:
return None
elif len(nodeproviders) == 1:
return nodeproviders[0]
if not len(set(type(np) for np in nodeproviders)) == 1:
... | b67e44d293ce0d6da1bcc600b6f3c81d50f4b8f0 | 29,170 |
import inspect
def ismethod(func):
""" Is func a method?
Note that this has to work as the method is defined but before the class is
defined. At this stage methods look like functions.
"""
signature = inspect.signature(func)
return signature.parameters.get('self', None) is not None | bbc971ae9ccde0c44e12e89027cd7180bfeac178 | 29,171 |
def getPrefix(netmask):
"""
Get the CIDR prefix representing the netmask.
:param netmask: Netmask to convert to CIDR
:type netmask:
:returns: CIDR prefix representing the netmask
:rtype: int
"""
return sum([bin(int(x)).count('1') for x in netmask.split('.')]) | ed721e171d76236d13a67c7f3ea164c996171a4b | 29,172 |
def rolling_mean(ts, window):
"""Calculate rolling mean of time series.
Uses pandas.DataFrame.rolling() to calculate rolling mean
of a given window size.
If more than one column of data in ts, returns rolling mean
using given window size for each column of data.
Returns nans for times before fi... | 8cd2933b1a9c285666a62a5edacae8477dec1d3d | 29,173 |
def X1X2_to_Xs(X1, X2):
"""Convert dimensionless spins X1, X2 to symmetric spin Xs"""
return (X1+X2)/2. | 9938f188d766d7895986b8796bb8eeeafe3b5b7d | 29,174 |
def confirm_new_game():
"""
Specialized input to ask confirmation about starting a new game.
:return: The user confirmation
:rtype: bool
"""
print("") # Empty line for aesthetical purposes
acceptable = set(["Y", "YES", "N", "NO"])
choice = ""
while choice not in acceptable:
... | 6285e6d9250bfb814db71ab237e33884823b7096 | 29,175 |
def repeat(l, n):
""" Repeat all items in list n times
repeat([1,2,3], 2) => [1,1,2,2,3,3]
http://stackoverflow.com/questions/24225072/repeating-elements-of-a-list-n-times
"""
return [x for x in l for i in range(n)] | 0a27596da9ef804a8a5badc0a0111b56c937aa35 | 29,178 |
import torch
def vec2mat0(vec):
"""Vector dim comes first, unlike v2m"""
return torch.unsqueeze(vec, 1) | e2d444b2772c092bb0375b6612b56d6b82a160f0 | 29,179 |
def roman_to_int(s):
"""
:type s: str
:rtype: int
"""
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
if len(s) == 1:
return roman_dict[s[0]]
# atleast 2 len
converted_int = 0
prev_item = -1
for idx, item in enumerate(s):
if prev_i... | b3cbe5ee251d9b6cbb909f45562677deb0839bb2 | 29,181 |
from typing import IO
import requests
def download_file(url: str) -> IO:
"""Download a remote file.
Parameters
----------
url: string
Request URL.
Returns
-------
io.BytesIO
"""
r = requests.get(url, stream=True)
r.raise_for_status()
return r.raw | 85c1e885573bee2619a473a2d9954781d46d3f9d | 29,182 |
import torch
def logit(p, a=torch.tensor(0.0), b=torch.tensor(1.0)):
"""
for scalar parameters with bounded support (no gaps)
basically a logit transform
"""
return torch.log(p - a) - torch.log(b - p) | 2efd8cb775f987c9dcd09c3c964bf85a76ad72a8 | 29,183 |
from typing import List
from typing import Union
def append_case_sink_edges(edge_list:List[tuple], exposed_ids:List[int],
matching_ratio:Union[int, str],
matching_ratio_dic:Union[dict, None])->List[tuple]:
"""Append edges to edge_list which the exposed to the sink... | dd64ca1bdfcecb1ef02bf2e6abe66db8ac5d04c9 | 29,184 |
def bytes2bin(bites, sz=8):
"""Accepts a string of ``bytes`` (chars) and returns an array of bits
representing the bytes in big endian byte order. An optional max ``sz`` for
each byte (default 8 bits/byte) which can be used to mask out higher
bits."""
if sz < 1 or sz > 8:
raise ValueError("... | 249bef3ef240f63273853ede0b820a9b59b935de | 29,185 |
def find_degree_info(soup):
"""Find degree info in parsed html text"""
degree = None
doc = ["PhD", "Assistant Professor"]
bs = ["B.A.", "BA", "B.S.", "BS", "Student", "Undergraduate"]
ms = ["M.S.", "Graduate Student", "MS", "Adjunct Instructor", "Associate Instructor"]
mba = ["MBA", "M.B.A"]
... | 66df8f331df4f883bba4194d9ed584748ccd516a | 29,187 |
def validate(state):
""" dict |-> bool
This predicate function takes a state dict and returns a bool
which is True if the state is valid and False if it is not valid
This does not check options, only if the state itself is consistent."""
return False | df9924e12a9797c2e89ee770286da894a5abf993 | 29,189 |
def multi_install(
pyenv, sequence, *, index_url="", pre=False, user=False, upgrade=False
):
"""
一次安装包名列表 sequence 中所有的包。
注意:如果 sequence 中有一个包不可安装(没有匹配的包等原因),那sequence中所有的
包都不会被安装,所以不是必须的情况下尽量不用这个函数来安装。
"""
return pyenv.install(
*sequence, pre=pre, user=user, index_url=index_url, upg... | fdd71b443f5054224226b1943b94b5066e3c6bec | 29,190 |
import os
import shutil
def setup_report_directory(directory):
"""Create an empty report directory."""
if os.path.exists(directory):
shutil.rmtree(directory)
os.makedirs(directory)
return directory | 0080208da6d48ed382e770f5732f61b49a6330a1 | 29,191 |
import os
def files():
"""return a list of `~/Library/LaunchAgents/*.plist` files"""
path = os.path.expanduser("~/Library/LaunchAgents")
if not os.path.exists(path):
return []
result = []
for root, dirs, files in os.walk(path):
plistfiles = list(
filter(lambda f: os.pat... | d4718db9e622c24100884a0b41c0bdf405337dca | 29,192 |
def get_cols_and_rows(payoff_entries):
"""Determine how many columns and rows the output plot should have based on
how many parameters are being swept."""
# make a list of the lengths of each parameter list that are more than one
# value for that parameter
lengths = [len(x) for x in payoff_entries ... | 2ae73cf52cb68e7688816254e21d71b1747caa22 | 29,193 |
def get_filename(name):
"""Return filename for astrocats event."""
return name.replace('/', '_') + '.json' | e12598b6ca16299fd939bd3cfb619882bb50145c | 29,194 |
def read_hex_digit(char: str) -> int:
"""Read a hexadecimal character and returns its positive integer value (0-15).
'0' becomes 0, '9' becomes 9
'A' becomes 10, 'F' becomes 15
'a' becomes 10, 'f' becomes 15
Returns -1 if the provided character code was not a valid hexadecimal digit.
"""
i... | 071445b3c0ec7a5392a7b5b0b354b4d3c59a3687 | 29,195 |
import base64
def rest_md5_to_proto(md5):
"""Convert the REST representation of MD5 hashes to the proto representation."""
return base64.b64decode(md5) | 64889241492ea5265c50b4ef95d55e864544d904 | 29,197 |
from pathlib import Path
def get_timestep(path):
"""
Get the timestep from a filename.
"""
path = Path(path)
fname = path.stem
tstep = fname.split('.')[-1]
return int(tstep) | f5eb746e06a6411008e609333cef8feb3250077c | 29,199 |
def find_bit_ranges(bit_str: str):
""" returns [(1/0, msb, lsb)]"""
if len(bit_str) == 0: return []
if len(bit_str) == 1: return [(int(bit_str), 0 , 0)]
ranges = []
lsb = 0
val = bit_str[-1]
for ii, cc in enumerate(reversed(bit_str)):
if ii == lsb: continue
if cc != val:
ranges.append((int(val), ii-1, lsb... | 2502283bfcdcbd6b0662a782aab0f802db8cb480 | 29,200 |
import math
def log_base(i, base):
"""Integer -> integer log_base.
"""
# Add a small epsilon since log() has a slight error and int() truncates,
# to avoid errors on powers of base.
if i == 0:
return 0
return int(math.log(i, base) + 0.00000000000001) + 1 | 6eda6e30a6d8aaa63e04130655e89cca55fa1d26 | 29,201 |
import itertools
def largest_group(iterable, key):
"""
Find a group of largest elements (according to ``key``).
>>> s = [-4, 3, 5, 7, 4, -7]
>>> largest_group(s, abs)
[7, -7]
"""
it1, it2 = itertools.tee(iterable)
max_key = max(map(key, it1))
return [el for el in it2 if key(el) =... | 3b3ead0361f3c1cc94bad8e8fdf3bddd73c36bb7 | 29,204 |
import jinja2
def render_template(env: jinja2.Environment, template: str, **context):
"""Render the given template with an additional context being made available in it."""
return env.get_template(template).render(**context) | 99c71c306ee088e70a5168b4237709c4c71e8e80 | 29,205 |
def abg(hm, hp):
""" Calculate alpha, beta and gamma for first and second derivative approximation """
a1 = -hp/(hm*(hm+hp))
g1 = hm/(hp*(hm+hp))
b1 = -a1-g1
a2 = 2/(hm*(hm+hp))
g2 = 2/(hp*(hm+hp))
b2 = -a2-g2
return a1, a2, b1, b2, g1, g2 | 54b7b198d6b5bd9948e7abd7870589cbc4b8dcbf | 29,208 |
from typing import Tuple
import subprocess
import re
def get_active_window_info_wayland() -> Tuple[str, str]:
"""Retrieve active window class and active window title on Wayland.
Inspired by https://gist.github.com/rbreaves/257c3edfa301786e66e964d7ac036269
Returns:
Tuple(str, str): window class, ... | f06ecce611bed08d8105b982238f2624fde7fb68 | 29,210 |
def remove_non_ascii(text: str) -> str:
""" Removes non ascii characters
:param text: Text to be cleaned
:return: Clean text
"""
return ''.join(char for char in text if ord(char) < 128) | 94a003856809eb740b5c85af094095acb2e07dad | 29,211 |
def get_embedding_matrix(model):
"""Calculate 3 embedding matrix for bert model
@param model: (BertForSequenceClassification) bert model to extract embedding matrix
@return word_emb: (torch.tensor) word embedding
@return pos_emb: (torch.tensor) position embedding
@return sent_emb: (torch.tensor... | 6cbb464ce93efce71f6d385d4b2e1ffacc976f32 | 29,212 |
def group_by_keys(dict_list, keys):
"""
>>> data = [
... {'a': 1, 'b': 2},
... {'a': 1, 'b': 3}
... ]
>>> group_by_keys(data, ['a', 'b'])
{(1, 2): [{'a': 1, 'b': 2}], (1, 3): [{'a': 1, 'b': 3}]}
"""
groups = {}
for d in dict_list:
value = tuple((d[k] for k in keys... | 425d223eff828e24ebdab4900c0c461868228eb4 | 29,213 |
def avg_bound(bounds):
"""A simple average of those bounds that are set"""
count = 0
bound_sum = 0
if bounds.has_upper_bound_success:
count += 1
bound_sum += bounds.upper_bound_success
if bounds.has_upper_bound_failure:
count += 1
bound_sum += bounds.upper_bound_failu... | 85dcfe845bd717eebfbebed5668a499c96cfdf35 | 29,214 |
import re
def split_args(args):
"""Parse and split arguments."""
return [a.strip('"-') for a in re.findall(r'[^\s\"]+|".+"', args)] | 765b10b6a2603843cda4a57264ac0f02359050e3 | 29,216 |
import time
def find_info(j, find_min=False, num_allowed=-1, num_sqr_end=-1, find_input=False):
"""
This function gets:
j - index of an input/output file
It returns the riddle's solution:
matchsticks - a Boolean array indexed 0 - 23 which represents the current matc... | de0a6bb269ad93ee0178d3a6f11278f5c3457b95 | 29,217 |
def _ParseSigsetT(sigset):
"""Parse a rendered sigset_t value.
This is the opposite of the Linux kernel's fs/proc/array.c:render_sigset_t
function.
@type sigset: string
@param sigset: Rendered signal set from /proc/$pid/status
@rtype: set
@return: Set of all enabled signal numbers
"""
result = set(... | 0168c50cbe138814449dee454170b89fc37cc6d5 | 29,218 |
import json
def _format(dictionary):
"""Pretty format a dictionary
Format a dictionary object into a well formatted JSON string
:param dictionary Dictionary object to be pretty formatted
:return String with a pretty format of a dictionary or JSON document
"""
return json.dumps(dictionary, e... | 7686d9bbf75f6e33a60ae28b302a2fa2c3d02f64 | 29,219 |
import functools
import ctypes
def hash_code(text: str) -> int:
"""Implements Java's hashCode in Python.
Ref: https://stackoverflow.com/a/8831937
"""
return functools.reduce(lambda code, char: ctypes.c_int32(31 * code + ord(char)).value, list(text), 0) | eadda940e3b2d63b8ff83f74816024160334288f | 29,220 |
def ask_yes_no(prompt="[y/n] :", default="y", valid=["y", "n"]):
"""Display a yes/no question and loop until a valid answer is entered
Keyword Arguments:
prompt {str} -- the question message (default: {'[y/n] :'})
default {str} -- the default answer if there is no answer (default: {"y"})
... | f46dcd6ed7fefcb38c4bc5307b49cf59e0c813b4 | 29,221 |
def _process_line(request: dict, cost_price_delta: int):
"""The function that builds out the report line by line"""
asset = request["asset"]
created = request["created"]
try:
qty = int(asset["items"][0]["quantity"]) # [0] to filter out irrelevant skus
except IndexError:
# to handl... | f650dd5cc7592f700e9b3aa9824b8d79679e4bbb | 29,222 |
import socket
def iptoint(ip_v4: str) -> int:
"""
Convert an ip address to an integer.
Adopted from http://goo.gl/AnSFV
:param ip_v4: IPv4 address
:returns: int of IPv4 hex
"""
return int(socket.inet_aton(ip_v4).hex(), 16) | bcdad9f575ee4bb33bb4716f95eb8a4124824fe7 | 29,223 |
def pack_x_y_sample_weight(x, y=None, sample_weight=None):
"""Packs user-provided data into a tuple."""
if y is None:
return (x,)
elif sample_weight is None:
return (x, y)
else:
return (x, y, sample_weight) | d2a7aafff2073a17632ac858fe40093389494af2 | 29,224 |
import struct
def long_long_int(value):
"""Decode a long-long integer value
:param bytes value: Value to decode
:return tuple: bytes used, int
:raises: ValueError
"""
try:
return 8, struct.unpack('>q', value[0:8])[0]
except TypeError:
raise ValueError('Could not unpack da... | 76e36535f382eb6e143b0d1f2f17102a8a9b886f | 29,225 |
import re
def regex(pattern):
"""
Compile a case-insensitive pattern.
"""
return re.compile(pattern, re.I) | b30c594fc9d4134bf464d010d085bf8eb59157fc | 29,226 |
import ast
def make_attr_call(attr1, attr2, args=None):
"""
flor._attr1_._attr2_(arg)
"""
if args is None:
return ast.Call(
func=ast.Attribute(
value=ast.Attribute(
value=ast.Name('flor', ast.Load()),
attr=attr1,
... | 1b2b839ab8e76730d33405782283b2fbc6e326d3 | 29,229 |
import os
import logging
import pickle
def load_pickled_model(filename):
"""
Purpose:
Load a model that has been pickled and stored to
persistance storage into memory
Args:
filename (String): Filename of a pickled model (.pkl)
Return:
model (Pickeled Object): Pickled mo... | 15d366d4b6f610ea6f46a94f2140c8df5db5448b | 29,230 |
def assign_assumed_width_to_national_roads_from_file(x, flat_width_range_list, mountain_width_range_list):
"""Assign widths to national roads assets in Vietnam
The widths are assigned based on our understanding of:
1. The class of the road which is not reliable
2. The number of lanes
3. The terrain... | 83d408813057ff9b8a03ab9cb745ed7299be602c | 29,231 |
def formation_temperature(surface_temperature, gradient, depth):
"""
Calculates formation temperature based on a gradient.
Parameters
----------
surface_temperature : float
Surface temperature (deg F or deg C)
gradient : float
Temperature gradient (degF/ft or degC/m)
depth :... | 13b55f67810775cbdd531036bb40780a4138af0a | 29,232 |
def cassini_instrument():
"""CIRS instrument API output."""
return {
'id': -82898,
'name': 'CASSINI_CIRS_RAD',
} | a871a3560bcbf56b9b524bafa95a834093d04ee0 | 29,233 |
def fn_url_p(fn):
"""check if fn is a url"""
url_sw = ['http://', 'https://', 'ftp://', 'ftps://']
for u in url_sw:
try:
if fn.startswith(u):
return(True)
except:
return(False)
return(False) | 0d56366d055b985bb819e0516c63acd117f371fd | 29,234 |
import pickle
import base64
def ObjectFromBase64EncodedString(EncodedObject):
"""Generate Python object from a bas64 encoded and pickled
object string.
Arguments:
str: Base64 encoded and pickled object string.
Returns:
object : Python object or None.
"""
return None if ... | ff82b5e3a130e563a11ed7ccfa4ce80b257b4ada | 29,235 |
import os
def is_plain_file(path):
"""**is_plain_file(path)** -> return True if the file at path is a plain file
* path: (string) path to check
<code>
Example:
is_plain_file('/etc/passwd')
Returns:
True
</code>
"""
return os.path.isfile(path) | 1f4cb257ee30b5291915b12ea9b23617271fe869 | 29,236 |
def insertion_sort(A):
"""Sort list of comparable elements into nondecreasing order."""
for i in range(1, len(A)):
value = A[i]
hole = i
while hole > 0 and A[hole-1] > value:
A[hole] = A[hole-1]
hole -= 1
A[hole] = value
return A | 467f22572c775472d018f234be51d6ffb8effde2 | 29,237 |
def find_one_possible_value(sorted_values, all_matching_indices):
"""Return the value that has only one element."""
for key, value in all_matching_indices.items():
if len(value) == 1:
sorted_values[key] = value[0]
return value[0] | 6ab3c7fee44fec1ca091cfbfa84f36c124632c9c | 29,239 |
def v3_matrix_from_string(matrix_string):
"""Convert string-based rows of numbers to list of lists.
Turning everything into a list comprehension
"""
return [
[float(n) for n in row_string.split()]
for row_string in matrix_string.splitlines()
] | 34bfc01415338f68d6f736e375ee51795a804ef5 | 29,240 |
def all_awards_are_reviewed(request):
""" checks if all tender awards are reviewed
"""
return all([award.status != "pending" for award in request.validated["tender"].awards]) | 325fb138db00b8696fa424b2a4c95e1378ddd667 | 29,241 |
def _knapsack(weights, capacity):
"""
Binary knapsack solver with identical profits of weight 1.
Args:
weights (list) : list of integers
capacity (int) : maximum capacity
Returns:
(int) : maximum number of objects
"""
n = len(weights)
# sol... | 158e96376bc3e7a60bbb24111b4b26636aaa86d5 | 29,242 |
import random
def reduce_branch_length(size):
""" Reduce the branch by a random length of 60-95% """
factor = round(random.uniform(0.6, 0.95), 2)
return size * factor | 52b14fe1007616badbaa95ffaebca0f4314cb21d | 29,243 |
def explode():
"""This route is going to exception. Used for testing 500 page."""
return 1/0 | 70470176ec69c862e2d59a41fd90d3a32ed17102 | 29,244 |
def get_layer_save_path(layer):
"""Get custom HoudiniLayerInfo->HoudiniSavePath from SdfLayer.
Args:
layer (pxr.Sdf.Layer): The Layer to retrieve the save pah data from.
Returns:
str or None: Path to save to when data exists.
"""
hou_layer_info = layer.rootPrims.get("HoudiniLayerI... | 16e20d0bcedf9717bb60af400548308ff05b0570 | 29,245 |
def prepare_mdtau(nrot, jobs):
"""
Returns what mdtau should be set to based on the number of hindered rotors and
inserts MdTau into the joblist if need be
"""
mdtau = None
if nrot > 0 and '1dTau' in jobs:
mdtau = '1'
if nrot > 1:
mdtau = '2'
if nrot > ... | cd05dc6aa6569efc7087d1769270910d1cf0bf2c | 29,247 |
from typing import List
from typing import Any
from typing import Iterator
from typing import Tuple
import itertools
def pairwise(s: List[Any]) -> Iterator[Tuple[Any, Any]]:
"""
Iterates over neighbors in a list.
s -> (s0,s1), (s1,s2), (s2, s3), ...
From https://stackoverflow.com/a/5434936
"""
... | 58bbd84005b8caef2535cf3477f8745d511b5a0b | 29,249 |
import os
def get_sensor_path(sensor_path):
"""Gets the path to look for a sensor JSON file
Args:
sensor_path (str): the directory to look in
Returns:
str: the full path to the sensor JSON file
"""
return os.path.join(sensor_path, "calibrated_sensor.json") | 738423a4c9a3f8bb11d431754d4a326b5d22cb23 | 29,252 |
def int_to_hexcolor(num: int, *mode: str):
"""Convert int to hex color
arg:
num: int (base=10)
return:
hexcolor string like 'ffba78'
"""
blue = num % 16**2
num = int(num / 16**2)
green = num % 16**2
num = int(num / 16**2)
red = num % 16**2
color = {'r': red, 'g': ... | 06c709e3840a07c3c7e641ff9b1b8d011da54a43 | 29,253 |
def _znode_to_class_and_name(znode):
"""
Local helper function that takes a full znode path that returns it in the
service_class/service_name format expected in this module
"""
znode = znode.split("/")
znode.pop(0)
return (znode[0], znode[1]) | 7039b35227d967978c073a41fa044a75c4a1670d | 29,258 |
def orbresurrect(orb):
"""Restore previous orb position variables"""
return orb.resurrect() | 50167fbafabcc864c79e0997c4687f05baab84c5 | 29,259 |
def byteToInt(byte):
"""
byte -> int
Determines whether to use ord() or not to get a byte's value.
"""
if hasattr(byte, 'bit_length'):
# This is already an int
return byte
return ord(byte) if hasattr(byte, 'encode') else byte[0] | a4fe2eab760b5b5792d633a78f4bdd5378719bb7 | 29,260 |
import argparse
def parse_args():
"""
pass
"""
parser = argparse.ArgumentParser(__doc__)
parser.add_argument('--model_name_or_path', type=str, default='plato-mini',
help='The path or shortcut name of the pre-trained model.')
parser.add_argument('--seed', type=int, defau... | 57f9b236362bd7bd3fb1b4cd271fd51bd61e6858 | 29,262 |
def _get_cat_formulae(mpt):
""" Retrieve categories and respective formulae
Parameters
----------
mpt : MPT
model
"""
values = []
for _, value in mpt.formulae().items():
values.append(" + ".join(value))
return values | b40c60d10be4724eec32ed2d164b09fc722a7bed | 29,264 |
def meta_REstring(REstr): # generic
""" get meta information of the RapidEye file name
Parameters
----------
REstr : string
filename of the rapideye data
Returns
-------
REtime : string
date "+YYYY-MM-DD"
REtile : string
tile code "TXXXXX"
REsat : string
... | d325034dd8dc7e7033387e22796b1449ba14d4dc | 29,265 |
def rest(s):
"""Return all elements in a sequence after the first"""
return s[1:] | 268d56ff3a24b3a5c9b1e4b1d1ded557afcdce8c | 29,266 |
def representationB(model):
""" An alternative representation of the model. """
result=''
for partition,weight in model.items():
if result!='':
result += '+'
l = [''.join((chr(65+read_ind) for read_ind in hap)) for hap in partition if len(hap)]
if weight!=1:
r... | 9c2d09a690a19d9c336831461f7d41479734797e | 29,269 |
def sort_string(s):
"""
:param s: string, ex: 'apple'
:return: string, sorted by a,b,c,d,e... ex: 'aelpp'
"""
sort_s = ''
for ch in sorted(list(s)):
sort_s += ch
return sort_s | 8b4760977ea59275c92b4307666a6ec8ab36e030 | 29,271 |
def get_title_from_vuln(vuln):
"""
Returns CVE ID from vulnerability document
When there is no title, returns "No-title" string
"""
return vuln.get('title', "No-Title") | 3c81cd0a873015d8e3d5a96819a7608dbfd8330f | 29,272 |
import json
from datetime import datetime
def get_user_insert(user, event):
"""
Gets all insertion data for a single user
Parameters
----------
user: dict
Dictionary object of a Twitter user
event: str
Event name of query the user was retrieved from
Returns
-------
... | 8c9a269fb7fd349d26899f63af5f8415b7d86210 | 29,273 |
def parse_number_input(user_input):
"""Converts a string of space-separated numbers to an array of numbers."""
lst_str = user_input.strip().split(' ')
return list(map(int, lst_str)) | 5e03156c79814a7916d78203749cfd82ab6b98d5 | 29,275 |
import argparse
import pathlib
def parse_args(parser: argparse.ArgumentParser):
"""
Parse CLI arguments to control the prediction.
:param parser: Argument parser Object.
:return: CLI Arguments object.
"""
parser.add_argument(
"input",
type=pathlib.Path,
help="Path to t... | 583766506d45335e9ab2cfa6d954a67838e79087 | 29,276 |
def _is_finite(constraints):
"""
Return ``True`` if the dictionary ``constraints`` corresponds to
a finite collection of ordered multiset partitions into sets.
If either ``weight`` or ``size`` is among the constraints, then
the constraints represent a finite collection of ordered multiset
parti... | 5802604f8a338b8e0c7b5a99e63661637350371f | 29,277 |
import math
def atanh(x):
"""Get atanh(x)"""
return math.atanh(x) | b721fd642ac99dd7e790db4baa73792333d7af7c | 29,278 |
def get_strata(creel_run):
"""Given a creel_run, return a list of tuples that represent the rows
in the Strata table - each row contains the strata label, and foreign
keys to the corresponding creel_run, season, space, daytype, period and
fishing mode.
Arguments:
- `creel_run`: An FN011 creel_r... | 845295eb27b1951e8cc90971419583fc41231b0f | 29,279 |
from datetime import datetime
from dateutil.tz import tzlocal
import pytz
def timestamp_to_datetime(timestamp):
"""Converts timestamp to datetime string."""
timeUTC = datetime.utcfromtimestamp(timestamp)
timeLocal = pytz.utc.localize(timeUTC).astimezone(tzlocal())
return timeLocal.strftime("%Y-%m... | 59f410f72beced48792fb4c40796da7393285c28 | 29,280 |
def create_service(ctx, name, args=None):
""" Create service with args if required. """
smgr = ctx.getServiceManager()
if args:
return smgr.createInstanceWithArgumentsAndContext(name, args, ctx)
else:
return smgr.createInstanceWithContext(name, ctx) | 6d1b1908c3c1a7d64c34d9fc83a7843905da7a87 | 29,281 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.