content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
|---|---|---|
def recipe_is_complete(r):
"""Return True if recipe is complete and False otherwise.
Completeness is defined as the recipe containing a title and instructions.
"""
if ('title' not in r) or ('instructions' not in r):
return False
if (r['title'] is None) or (r['instructions'] is None):
return False
return True
|
78242642b97dbb8e051f74c64b9ef742eff196a1
| 64,948
|
def geom(xs, p):
"""Geometric probability mass function. x=number of desired
Bernoulli trials, p=Success probability of a single Bernoulli
trial. Returns: Probability that the x's trial is the first
success"""
if any(xs<1) or p<0 or p>1: raise ValueError('function not defined')
return ((1-p)**(xs-1)) * p
|
a71057337b6e62042ab67d6bcd166a16d51ce0b9
| 64,955
|
from pathlib import Path
import gzip
def untar(source: Path, verbose=False) -> Path:
"""
Desc: creates a file with the same extension as the
file contained within the zipped archive and
then writes the contents from the zipped file
into the new file created
Args:
source - Path object for the source from
where the files needs to be fetched
verbose - Let the method know if you want to
see progress messages
Returns: Path object for the uncompressed file
"""
if verbose: print(f'source:{source}')
dest_file = source.parent/source.stem
if dest_file.exists(): dest_file.unlink()
if not dest_file.exists():
if verbose: print("extracting..")
dest_file.touch()
with gzip.open(source, "rb") as file:
for line in file:
dest_file.write_bytes(line)
#dest_file.close()
if verbose: print('File extracted successfully.')
return dest_file
|
221c7119456630222e408407540428c7de2507e7
| 64,959
|
import random
def generate_list(list_size, element_min, element_max):
"""Generates a list contianing list_size elements.
Each element is a random int between or equal element_min
and element_max"""
sequence = [random.randint(element_min, element_max)
for num in range(list_size + 1)]
return sequence
|
37cd37625ba102082d0b366a9a661295d518af68
| 64,960
|
def is_gzip_file(filename):
"""Returns ``True`` if :obj:`filename` is a GZIP file."""
return filename.endswith(".gz")
|
0a485dc25ebe28d23f8293815940dcddef35c417
| 64,961
|
def get_icd9_descript_path(data_dir):
"""Get path of icd9 description file."""
return '{}/{}'.format(data_dir, 'phewas_codes.txt')
|
2a32f66af3c57b7c93a9e281371c0c74a8f75465
| 64,964
|
def createHeader(ordinal):
"""Creates the header text for each seperate subexcercise"""
print("")
print("---", ordinal, " program---")
print("")
return 0
|
f1c49d7252c52651824ce590fbdfd09601b132ec
| 64,965
|
import requests
def fetch_gutenberg_book(id: str) -> str:
"""Fetch a book from Gutenberg, given its ebook id."""
url = "https://www.gutenberg.org/ebooks/{}.txt.utf-8".format(id)
response = requests.get(url)
response.raise_for_status()
return response.text
|
f0c6d8d3099e08f05b00940c85c4872894406e41
| 64,969
|
import torch
def smooth(x, span):
"""
Moving average smoothing with a filter of size `span`.
"""
x = torch.nn.functional.pad(x, (span//2, span//2))
x = torch.stack([torch.roll(x, k, -1) for k in range(-span//2, span//2+1)]).sum(dim=0) / span
return x
|
494590de72e78fcbeb11bacf9214bee4ba6efcf3
| 64,972
|
import random
from typing import List
def generate_seeds(rng: random.Random, size: int) -> List[int]:
"""Generates list of random seeds
:param random.Random rng: random number generator
:param int size: length of the returned list
:return: list of random seeds
:rtype: List[int]
"""
seeds = [rng.randint(0, 2**32 - 1) for _ in range(size)]
return seeds
|
2e8a66745086c55c142877de2d3422b9eab9f160
| 64,976
|
from typing import List
from typing import Dict
def finalise_squad_data_list(squad_data_list: List, version: str='') -> Dict:
"""Convert a SQuAD data list to SQuAD final format"""
return {
'data': squad_data_list,
'version': version
}
|
72caf6d8f0c3c6d17c88767d4cceea28534bd4a8
| 64,977
|
def true_filter(test): # pylint: disable=unused-argument
"""Simply return True regardless of the input.
Designed to be used with `get_best_filter` where no filtering is desired;
intended to have same effect as `IsParticle` function defined in
dataclasses/private/dataclasses/physics/I3MCTreePhysicsLibrary.cxx
Parameters
----------
test
Returns
-------
True : bool
"""
return True
|
a7e3e983f133f946c2232e84e29435bd43d12dca
| 64,982
|
from typing import List
from typing import Dict
def _mock_translate_response(
target_language: str, source_language: str, model: str, values: List[str],
) -> List[Dict[str, str]]:
"""
A simulated response for the Google Translate Client get_languages() call
https://github.com/googleapis/python-translate/blob/master/google/cloud/translate_v2/client.py
Args:
target_language: The language to translate to (ignored in mock response)
source_language: The language to translate from
model: The model used by the google client for language detection
values: The values to detect the language for
Returns:
A list of JSON responses per input value
"""
if sum(len(value) for value in values) > 100000:
raise RuntimeError("User Rate Limit Exceeded")
translated_values = {
"cheddar cheese": "fromage cheddar",
"ground beef": "boeuf haché",
"skim milk": "lait écrémé",
"whole chicken": "poulet entier",
"bacon": "Bacon",
"american cheese": "Fromage Américain",
"roast beef": "rôti de bœuf",
"boneless chicken breasts": "poitrines de poulet désossées",
"swiss cheese": "fromage suisse",
}
mock_response = []
for value in values:
if source_language is None:
mock_response.append(
{
"translatedText": translated_values[value],
"detectedSourceLanguage": "en",
"model": model,
"input": value,
}
)
else:
mock_response.append(
{"translatedText": translated_values[value], "model": model, "input": value}
)
return mock_response
|
7b47fb6cc7ca5dafce444072bbedc29f641a2a05
| 64,991
|
def get_first_data_row(sheet):
""" Find first row in the excel with data (company numbers)
Args:
sheet: worksheet object
Returns:
first row with data
"""
for row in range(1, sheet.max_row):
if str(sheet['A' + str(row)].value).isnumeric():
return row
return 1
|
49135b47b1aadfc6bcfbd302dfe14bdb7d1f2cfd
| 64,996
|
def get_elements(filename):
""" get elements from file, each line is an element """
elements = list()
with open(filename, 'r') as f:
lines = f.readlines()
return [e.rstrip() for e in lines]
|
9482655c3dba061160fc2cea135e7492d6465dba
| 64,998
|
def _get_end_nodes(graph):
"""Return list of nodes with just one neighbor node."""
return [i for i in graph.nodes() if len(list(graph.neighbors(i))) == 1]
|
5cfb4abcf9323255aa18183e0fb06d668e8131dd
| 64,999
|
def pyname_to_xmlname(name):
"""
Convert a Python identifier name to XML style.
By replacing underscores with hyphens:
>>> pyname_to_xmlname('some_name')
'some-name'
"""
return name.replace('_', '-')
|
4b950faea8577bfde818afa561dd22aded2f18f4
| 65,003
|
def armstrongNumber(num):
"""assumes num is an int
returns a boolean, True if num is an armstrong number, else False.
An armstrong number = sum of digits ** number of digits
e.g. 371 = 3**3 + 7**3 + 1**3
"""
digit_sum = 0
for digit in str(num):
digit_sum += int(digit) ** 3
return num == digit_sum
|
519812a5dd4612c1127225c66be0790e4576eb45
| 65,009
|
def is_windows(repository_ctx):
"""Returns true if the execution platform is Windows.
Args:
repository_ctx: the repository_ctx
Returns:
If the execution platform is Windows.
"""
os_name = ""
if hasattr(repository_ctx.attr, "exec_properties") and "OSFamily" in repository_ctx.attr.exec_properties:
os_name = repository_ctx.attr.exec_properties["OSFamily"]
else:
os_name = repository_ctx.os.name
return os_name.lower().find("windows") != -1
|
a5bb926198d3aac3f1a81591785e11327dd3e97f
| 65,015
|
def init_enemy_size(data):
"""
Initializes enemy size dictionary
:param data:
:return: Enemy size dictionary
"""
snakes = data['board']['snakes']
size_dict = {snake['id']: len(snake['body']) for snake in snakes}
#print('Initialized size_dict')
return size_dict
|
caa9df938ed61cbede5bdf0f76c1058fd2a56c6a
| 65,030
|
def calculate_predicted_value(independent_variable, coefficient):
"""Returns the predicted value for a given input and coefficient"""
return independent_variable * coefficient
|
3012eb88264462df58d5c32d00f5f877207e7c48
| 65,031
|
import string
import random
def gen_random_str(length: int, chars: str='uld', *, prefix: str='', suffix: str='') -> str:
"""生成随机字符串
Args:
length: 字符串总长度
chars: 使用的字符种类:'u' - 大写字母,'l' - 小写字母,'d' - 数字
prefix: 字符串前缀
suffix: 字符串后缀
"""
random_part_len = length - len(prefix + suffix)
if random_part_len < 0:
raise ValueError('Invalid length')
if random_part_len == 0:
return prefix + suffix
population = ''
if 'u' in chars:
population += string.ascii_uppercase
if 'l' in chars:
population += string.ascii_lowercase
if 'd' in chars:
population += string.digits
if not population:
raise ValueError('Invalid chars')
elements = random.choices(population, k=random_part_len)
return prefix + ''.join(elements) + suffix
|
a09e4b3df1df4b8e390e0ceafa198a3d11f8be2e
| 65,047
|
import math
def get_sd(mean, grade_list):
"""Calculate the standard deviation of the grades"""
stan_dev = 0 # standard deviation
sum_of_sqrs = 0
for grade in grade_list:
sum_of_sqrs += (grade - mean) ** 2
stan_dev = math.sqrt(sum_of_sqrs / len(grade_list))
return stan_dev
|
216c7704152c7f0cb79109730805740578d648d0
| 65,050
|
def file_path_to_chars(file_path):
"""Return the characters in a file at the given path."""
with open(file_path, 'rb') as f:
return [chr(b) for b in f.read()]
|
d0352ec9451d93338214a09a9904ef373135f147
| 65,051
|
import re
def get_mfc_requirements(msg):
""" Get set of revisions required to be merged with commit """
requirements = set()
lines = msg.split('\n')
for line in lines:
if re.match('^\s*(x-)?mfc(-|\s+)with\s*:', line, flags=re.IGNORECASE):
pos = line.find(':')
line = line[pos+1:]
revisions = re.split('[, ]+', line.strip())
for rev in revisions:
if rev.startswith('r'):
rev = rev[1:]
requirements.add(rev)
return requirements
|
1fd9ca26e4bec401908c639d18e2ad61acda2c41
| 65,053
|
import logging
def filter_keys(d, fn, log_warn=False):
"""Return a copy of a dict-like input containing the subset of keys where fn(k) is truthy"""
r = type(d)()
for k, v in d.items():
if fn(k):
r[k] = v
elif log_warn:
logging.warning(f"filtered bad key: {k}")
return r
|
9880ee040673f2c7c0ba44875d72ce3e45fc9bfd
| 65,061
|
from typing import Optional
from typing import Any
from typing import OrderedDict
def collection_gen(resources: list, topic_uri: str, uri: str, members: bool=False) -> Optional[Any]:
"""
Generate an OrderedDict for a IIIF Presentation API collection from
a list of manifest Ordered Dicts (with @type, @id, and label),
setting the @id of the Collection based on the annotation 'creator'.
:param resources: List of IIIF Presentation API Ordered Dicts
:param topic_uri: id of the topic
:param uri: base URI where the collection can be retrieved
:param members: Boolean to set whether to use members or manifests. Members
would allow Collections to be part of the Collection.
:return: OrderedDict for IIIF Collection
"""
if resources and topic_uri and uri:
at_id = uri # + 'topic/?topic=' + topic_uri
coll = OrderedDict()
coll['@context'] = 'http://iiif.io/api/presentation/2/context.json'
coll['@id'] = at_id
coll['@type'] = 'sc:Collection'
coll['label'] = ' '.join(['IDA Topic Collection for', topic_uri.split('/')[-1]])
if members:
coll['members'] = [r for r in resources]
else:
coll['manifests'] = [r for r in resources]
return coll
else:
return None
|
0123fd946efd4b67da13402fdad1a370ade07377
| 65,063
|
def count_linear(model,output_size):
"""count FLOPs of linear layer
:param model: model object
:param output_size: integer output size of the model
:returns: FLOPs of linear layer
"""
input_size=model.rnn.hidden_layer_sizes[-1]
return input_size*output_size*2
|
4f6729df546cb29afbbd5f610fbbe59095794597
| 65,064
|
def ask_correct_or_jump(folder_path_project: str, list_file_path_long: list) -> bool:
"""ask to test again or skip project
Args:
folder_path_project (str): project folder_path
list_file_path_long (list): list of file_path who has path_lenght above max_path
Returns:
bool: True if choose skip
"""
msg_project_header = f'\nProject: {folder_path_project}\n'
question = \
'\nThis files are with MAX_PATH above the limit allowed.\n' + \
'Edit the name of folders and files to reduce its lenght.\n\n' + \
'1 - Test again (default)\n' + \
'2 - Skip project\n\n'
print(msg_project_header)
for file_path_long in list_file_path_long:
print('- ' + file_path_long)
print(question)
answer = input('Choose an option: ')
if answer == '' or answer == '1':
choose_jump = False
return choose_jump
else:
choose_jump = True
return choose_jump
|
0419cbb536435b811fca520121ef25e73b96b91b
| 65,066
|
import torch
def matern12(r):
"""Matern 1/2 function"""
return torch.exp(-r)
|
015efb840b4ef249561b359703195677bc4d1390
| 65,070
|
import csv
def read_in_data_from_file (environment, pathname):
"""
Open file and read data into list of lists
Parameters
----------
environment : list of lists
the datastructure into which the content of the input file is read.
pathname : string
represents the file name including the path if its not in the current
working directory.
Returns
-------
environment : list of list
each element in environment contains one complete row of input file.
"""
f = open(pathname, newline='')
reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)
for row in reader:
rowlist = []
for value in row: # A list of value
rowlist.append(value)
environment.append(rowlist)
f.close()
return environment
|
2bbd16c638f3f2100143a653831f09371b6827cf
| 65,072
|
import itertools
def padIterable(iterable, padding, count):
"""
Pad C{iterable}, with C{padding}, to C{count} elements.
Iterables containing more than C{count} elements are clipped to C{count}
elements.
@param iterable: The iterable to iterate.
@param padding: Padding object.
@param count: The padded length.
@return: An iterable.
"""
return itertools.islice(
itertools.chain(iterable, itertools.repeat(padding)), count)
|
793cf523f5f29c4e1ca0b37cb10f314f1cd903fa
| 65,073
|
def union_overlapping(intervals):
"""Union any overlapping intervals in the given set."""
disjoint_intervals = []
for interval in intervals:
if disjoint_intervals and disjoint_intervals[-1].overlaps(interval):
disjoint_intervals[-1] = disjoint_intervals[-1].union(interval)
else:
disjoint_intervals.append(interval)
return disjoint_intervals
|
946e095d219282c4091cf037a78a7d238cc566a8
| 65,077
|
import math
def dist(*args):
"""Calculates the Euclidean distance between two points. Arguments are of the form
dist(x1,y1,x2,y2)
dist(x1,y1,z1,x2,y2,z2)"""
if len(args) == 4:
return math.sqrt(
sum([(a - b) ** 2 for a, b in zip(args[:2], args[2:])]))
else:
assert (len(args) == 6)
return math.sqrt(
sum([(a - b) ** 2 for a, b in zip(args[:3], args[3:])]))
|
dfa0e5bf0ae002c682d14804260347f0626af68e
| 65,079
|
def assign_subtasks(total_num, num_tasks=2):
"""
Split the task into sub-tasks.
Parameters:
-----------
total_num: int
Total number of the task to be split.
num_tasks: int
The number of sub-tasks.
Returns:
--------
subtask_ids: list of list
List of the list of ids. Eg.
[[0, 1], [2, 3, 4]]
"""
subtasks = []
num_per_task = total_num // num_tasks
for i in range(num_tasks):
if i < num_tasks-1:
ids = list(range(i*num_per_task, (i+1)*num_per_task, 1))
else:
ids = list(range(i*num_per_task, total_num))
subtasks.append(ids)
return subtasks
|
ec6246f3b47e99d55e0502fe1165dcb232d8acef
| 65,080
|
def horner( x, *poly_coeffs ):
""" Use Horner's Scheme to evaluate a polynomial
of coefficients *poly_coeffs at location x.
"""
p = 0
for c in poly_coeffs[::-1]:
p = p*x + c
return p
|
236352cb4ae6de13cf8fe6ddfad782af4aba1c6b
| 65,083
|
def get_submatrix(matrices, index, size, end_index=None):
"""Returns a submatrix of a concatenation of 2 or 3 dimensional
matrices.
:type matrices: Variable
:param matrices: symbolic 2 or 3 dimensional matrix formed by
concatenating matrices of length size
:type index: int
:param index: index of the matrix to be returned
:type size: Variable
:param size: size of the last dimension of one submatrix
:type end_index: int
:param end_index: if set to other than None, returns a concatenation of all
the submatrices from ``index`` to ``end_index``
"""
if end_index is None:
end_index = index
start = index * size
end = (end_index + 1) * size
if matrices.ndim == 3:
return matrices[:, :, start:end]
elif matrices.ndim == 2:
return matrices[:, start:end]
else:
raise ValueError("get_submatrix() requires a 2 or 3 dimensional matrix.")
|
2331456bf2418a02f69edf330207ce9faf3ee2b7
| 65,086
|
def stringtodigit(string: str):
"""
attempts to convert a unicode string to float or integer
:param str string: String to attempt conversion on
:return:
"""
try:
value = float(string) # try converting to float
except ValueError:
try:
value = int(string) # try converting to int
except ValueError:
value = string # otherwise keep as unicode
return value
|
acf53b4f799eb202e0d4d6f664c842d61b6afc26
| 65,091
|
def pad(region, margins):
"""
Pad region according to a margin
:param region: The region to pad
:type region: list of four floats
:param margins: Margin to add
:type margins: list of four floats
:returns: padded region
:rtype: list of four float
"""
out = region[:]
out[0] -= margins[0]
out[1] -= margins[1]
out[2] += margins[2]
out[3] += margins[3]
return out
|
a56085f5e42122307cd4236d051447c66aaa68f9
| 65,093
|
import string
def get_available_letters(letters_guessed):
""" letters_guessed: list (of letters), which letters have been
guessed so far
Returns: string (of letters), comprised of letters that represents
which letters have not yet been guessed.
"""
lo, g = string.ascii_lowercase, letters_guessed
return lo if g == '' else ''.join([c for c in lo if c not in g])
|
e7eb61eeab6be37286e6ab39ff07bc3bfa3041ea
| 65,094
|
def to_seconds(time_obj):
""" Convert a RationalTime into float seconds """
return time_obj.value_rescaled_to(1)
|
80c19f24870d5f3b95f263906ec9e106330015a4
| 65,101
|
def selection_sort(some_list):
"""
https://en.wikipedia.org/wiki/Selection_sort
Split the list into a sorted/unsorted portion. Go through the list from left to right, starting with position 0 in
the unsorted portion. When we find the minimum element of the unsorted portion, swap it to the end of the sorted
list portion.
O(N^2)
"""
iters = 0
for i in range(0, len(some_list) - 1):
iters += 1
min_index = i # Always reset min for each loop
for j in range(i + 1, len(some_list)):
iters += 1
if some_list[j] < some_list[min_index]:
min_index = j
if min_index != i:
some_list[i], some_list[min_index] = some_list[min_index], some_list[i]
return iters, some_list
|
47bb82584e87cd3f00d3a276d0d64682b00e46cb
| 65,107
|
def pretty_exception(err: Exception, message: str):
"""Return a pretty error message with the full path of the Exception."""
return "{} ({}.{}: {})".format(message, err.__module__, err.__class__.__name__, str(err))
|
0dfabae14bdf1df4073248e25b1e3d74573c1aed
| 65,109
|
from pathlib import Path
def home_directory() -> str:
"""
Return home directory path
Returns:
str: home path
"""
return str(Path.home())
|
8c9c1ccccfc547a26794e5494975e27cde4e73ef
| 65,110
|
def _get_image_type_from_array(arr):
"""Find image type based on array dimensions.
Raises error on invalid image dimensions.
Args:
arr: numpy array. Input array.
Returns:
str. "RGB" or "L", meant for PIL.Image.fromarray.
"""
if len(arr.shape) == 3 and arr.shape[2] == 3:
# 8-bit x 3 colors
return 'RGB'
elif len(arr.shape) == 2:
# 8-bit, gray-scale
return 'L'
else:
raise ValueError(
'Input array must have either 2 dimensions or 3 dimensions where the '
'third dimension has 3 channels. i.e. arr.shape is (x,y) or (x,y,3). '
'Found shape {}.'.format(arr.shape))
|
cf3b8aa43a8dc35c000c7a6f5d68eae6ae96a418
| 65,118
|
def get_label_instances(response, target):
"""Get the number of instances of a target label."""
for label in response['Labels']:
if label['Name'] == target:
return len(label['Instances'])
|
ec0b24fac803148ea8e9b0e07d854d0ec953c63f
| 65,123
|
def is_remote(path):
"""Determine if a uri is located on a remote server
First figures out if there is a ':' in the path (e.g user@host:/path)
Then looks if there is a single @ in part preceding the first ':'
:param path: uri/path
:type path: str
:return: True if path points to remote server, False otherwise
:rtype: bool
"""
dot = path.split(":")[0]
at = dot.split("@")
if len(at) == 1:
return False
return True
|
979acfc548f5d550d249fceadad6f9ece4f40035
| 65,124
|
import logging
def log_data_summary(X, Y):
"""Sanity check that logs the number of each class.
Args:
X (np.ndarray): Data set
Y (np.ndarray): Labels
Returns:
None
"""
N_total = Y.size
N_1 = Y.sum()
N_0 = N_total - N_1
logging.info("{:d} total examples. {:.1f} % of training set is 1.".format(
N_total, 100 * float(N_1) / float(N_total)
))
return None
|
3c706b1609791882a1e54a46c38dc1fa7c5678d9
| 65,126
|
def get_xml_attributes(node):
"""Return the xml attributes of a node as a dictionary object"""
attr = {}
for k, v in node._get_attributes().items():
attr[k] = v
return attr
|
8bb013818ed9bba5c4b73d662c4ad11c6dae05e6
| 65,132
|
def max_returns(prices):
"""
Calculate maxiumum possible return in O(n) time complexity
Args:
prices(array): array of prices
Returns:
int: The maximum profit possible
"""
if len(prices) < 2:
return 0
min_price_index = 0
max_price_index = 0
current_min_price_index = 0
for i in range(1, len(prices)):
# current minimum price
if prices[i] < prices[current_min_price_index]:
current_min_price_index = i
# current max profit
if prices[i] - prices[current_min_price_index] > prices[max_price_index] - prices[min_price_index]:
max_price_index = i
min_price_index = current_min_price_index
max_profit = prices[max_price_index] - prices[min_price_index]
return max_profit
|
08bc3e900818f0f93927c2e70fa8a38d83a91393
| 65,133
|
def RemoveSlash( dirName ):
"""Remove a slash from the end of dir name if present"""
return dirName[:-1] if dirName.endswith('/') else dirName
|
0eabb5d82c3419caccde674fbae150d852e94fb0
| 65,134
|
def to_bool(val):
"""
Copied from
https://github.com/python-attrs/attrs/blob/e84b57ea687942e5344badfe41a2728e24037431/src/attr/converters.py#L114
Please remove after updating attrs to 21.3.0.
Convert "boolean" strings (e.g., from env. vars.) to real booleans.
Values mapping to :code:`True`:
- :code:`True`
- :code:`"true"` / :code:`"t"`
- :code:`"yes"` / :code:`"y"`
- :code:`"on"`
- :code:`"1"`
- :code:`1`
Values mapping to :code:`False`:
- :code:`False`
- :code:`"false"` / :code:`"f"`
- :code:`"no"` / :code:`"n"`
- :code:`"off"`
- :code:`"0"`
- :code:`0`
:raises ValueError: for any other value.
.. versionadded:: 21.3.0
"""
if isinstance(val, str):
val = val.lower()
truthy = {True, "true", "t", "yes", "y", "on", "1", 1}
falsy = {False, "false", "f", "no", "n", "off", "0", 0}
try:
if val in truthy:
return True
if val in falsy:
return False
except TypeError:
# Raised when "val" is not hashable (e.g., lists)
pass
raise ValueError("Cannot convert value to bool: {}".format(val))
|
24c1ea4fa76b6ac6752d1255c0dc8203b406ca45
| 65,136
|
import requests
def generic_request(method, url, **kwargs):
"""An alias for requests.request with handling of keystone authentication tokens.
:param method: The HTTP method of the request
:param url: The url to request
:param **kwargs: The keyword arguments defined below as well
as any additional arguments to be passed to the
requests.request call
:return: A request for the given url
:Keyword Arguments:
* token:
A token to be put into the X-Auth-Token header of the request
"""
auth_token = kwargs.pop('token', None)
if auth_token:
headers = kwargs.pop('headers', {})
headers['X-Auth-Token'] = auth_token
kwargs['headers'] = headers
return requests.request(method, url, **kwargs)
|
e7e2493fee6a76430984492880283f1e0dbbcd19
| 65,139
|
def backoff_constant(n):
"""
backoff_constant(n) -> float
Constant backoff implementation. This returns the constant 1.
See ReconnectingWebSocket for details.
"""
return 1
|
345ab3c2c0147a4f102e9518cb4022b55ef9cb7c
| 65,140
|
import re
def find_num_inquiries(Aop, parameters_size):
"""
Find the number of parameter inquiries. Parameter inquiries may not be the
same as the length of parameters array. The "parameter size" is the product
of the "number of the parameter inquiries" and the "number of the
parameters of the operator".
"""
# Get number of parameters that the linear operator Aop defined with
num_operator_parameters = Aop.get_num_parameters()
# Find the number of inquiries based on the number of parameters
# and the length (size) of the parameters array (or scalar)
if num_operator_parameters == 0:
# No parameters given. There is only one inquiry to be computed
num_inquiries = 1
elif parameters_size < num_operator_parameters:
message = """Not enough parameters are provided. The given parameter
size is %d, which should be larger than %d, the number of
parameters of the linear operator.""" % (
parameters_size, num_operator_parameters)
raise ValueError(re.sub(' +', ' ', message.replace('\n', '')))
elif parameters_size % num_operator_parameters != 0:
message = """Parameters size (given %d) is not an integer-multiple of
%d, the number of the parameters of the linear operator.
""" % (parameters_size, num_operator_parameters)
raise ValueError(re.sub(' +', ' ', message.replace('\n', '')))
else:
# parameters size should be an integer multiple of num parameters
num_inquiries = int(parameters_size / num_operator_parameters)
return num_inquiries
|
6699cc72fdddcedeb923368db62a31c869d371d5
| 65,142
|
import time
def collect_host_processes(processes, done_functs=()):
"""Returns a summary of return codes for each process after
they are all finished.
done_functs: iter of functs
Each function in done_functs will be executed with the args (processes, p)
where p is the process that has just completed and processes is the list
of remaining processes still (possibly) running.
"""
summary = {}
processes = processes[:]
while len(processes) > 0:
time.sleep(10)
for p in processes:
if p.exitcode is not None:
summary[p.name] = p.exitcode
processes.remove(p)
for f in done_functs:
f(processes, p)
break
return summary
|
4e600079750357851a0675e742dfc9ba14efc7b9
| 65,145
|
def format_number(number, num_decimals=2):
"""
Format a number as a string including thousands separators.
:param number: The number to format (a number like an :class:`int`,
:class:`long` or :class:`float`).
:param num_decimals: The number of decimals to render (2 by default). If no
decimal places are required to represent the number
they will be omitted regardless of this argument.
:returns: The formatted number (a string).
This function is intended to make it easier to recognize the order of size
of the number being formatted.
Here's an example:
>>> from humanfriendly import format_number
>>> print(format_number(6000000))
6,000,000
> print(format_number(6000000000.42))
6,000,000,000.42
> print(format_number(6000000000.42, num_decimals=0))
6,000,000,000
"""
integer_part, _, decimal_part = str(float(number)).partition('.')
negative_sign = integer_part.startswith('-')
reversed_digits = ''.join(reversed(integer_part.lstrip('-')))
parts = []
while reversed_digits:
parts.append(reversed_digits[:3])
reversed_digits = reversed_digits[3:]
formatted_number = ''.join(reversed(','.join(parts)))
decimals_to_add = decimal_part[:num_decimals].rstrip('0')
if decimals_to_add:
formatted_number += '.' + decimals_to_add
if negative_sign:
formatted_number = '-' + formatted_number
return formatted_number
|
9048a53c239072f1b21b2eb4e6446ae631ea4ace
| 65,150
|
from typing import Iterable
from typing import List
from typing import Any
def unique(iterable: Iterable) -> List[Any]:
"""Return a list of all unique elements in iterable.
This function preserves order of elements.
Example:
.. code-block:: python3
unique([3, 2, 1, 1, 2]) -> [3, 2, 1]
"""
seen = set()
f = seen.add
return list(x for x in iterable if not (x in seen or f(x)))
|
ca982d339e99caf6f04ac8d89ba9ac09313e18b5
| 65,153
|
import collections
def dict_to_class(dobj):
"""Convert keys of a dict into attributes of a class.
"""
Dclass = collections.namedtuple('Dclass', dobj.keys())
return Dclass(**dobj)
|
ede87edf15a11036679eaf066acbadcc1423f3ef
| 65,164
|
def getDistance(x1, y1, x2, y2):
"""
Using the standard distance Formula
**2 is to perform square operation
**5 is to perform square root operation
"""
return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
|
783196001758dc8b052547459b56b33cc3773c10
| 65,166
|
from typing import Tuple
def decode_fault(tup: Tuple[int, ...]) -> str:
"""Decode faults."""
faults = {
13: "Working mode change",
18: "AC over current",
20: "DC over current",
23: "F23 AC leak current or transient over current",
24: "F24 DC insulation impedance",
26: "F26 DC busbar imbalanced",
29: "Parallel comms cable",
35: "No AC grid",
42: "AC line low voltage",
47: "AC freq high/low",
56: "DC busbar voltage low",
63: "ARC fault",
64: "Heat sink tempfailure",
}
err = []
off = 0
for b16 in tup:
for bit in range(16):
msk = 1 << bit
if msk & b16:
msg = f"F{bit+off+1:02} " + faults.get(off + msk, "")
err.append(msg.strip())
off += 16
if not err:
return ""
return ", ".join(err)
|
66399148fef9706db7b51a1d1ea8eecebccdbb88
| 65,168
|
def normalize_job_id(job_id):
"""Convert the job id into job_id, array_id."""
return str(int(job_id)), None
|
1573a8db5fa0ea84bf6ef8062bcfaf92d6a504ac
| 65,169
|
def to_bool(s: str) -> bool:
"""
Converts the given string to a boolean.
"""
return s.lower() in ('1', 'true', 'yes', 'on')
|
3d694f37927caf25d5af579d6d78168b21e99ea7
| 65,170
|
def calculateIoU(startX_, startY_, endX_, endY_, x1, y1, x2, y2):
"""
Calculate the intersection over union (IoU) score for two bounding boxes.
:param startX_: Upper left x coordinate of the first object detection.
:param startY_: Upper left y coordinate of the first object detection.
:param endX_: Lower right x coordinate of the first object detection.
:param endY_: Lower right y coordinate of the first object detection.
:param x1: Upper left x coordinate of the second object detection.
:param y1: Upper left y coordinate of the second object detection.
:param x2: Lower right x coordinate of the second object detection.
:param y2: Lower right y coordinate of the second object detection.
"""
x_left = max(startX_, x1);
y_top = max(startY_, y1);
x_right = min(endX_, x2);
y_bottom = min(endY_, y2);
if x_right < x_left or y_bottom < y_top:
return 0.0
intersection_area = (x_right - x_left) * (y_bottom - y_top);
bb1_area = (endX_ - startX_) * (endY_ - startY_);
bb2_area = (x2 - x1) * (y2 - y1);
iou = intersection_area / (bb1_area + bb2_area - intersection_area);
return iou
|
d682b16593daef33d841f5dc84f16cd2bddc35a0
| 65,172
|
import torch
def accuracy_fn(y_true, y_pred):
"""Calculates accuracy between truth labels and predictions.
Args:
y_true (torch.Tensor): Truth labels for predictions.
y_pred (torch.Tensor): Predictions to be compared to predictions.
Returns:
[torch.float]: Accuracy value between y_true and y_pred, e.g. 78.45
"""
correct = torch.eq(y_true, y_pred).sum().item()
acc = (correct / len(y_pred)) * 100
return acc
|
6ca674aac03b153a2608e8a2e5d3abfce1bbc6d2
| 65,177
|
def compute_p_r_f1(gold_tuples, pred_tuples):
"""
Compute Precision/Recall/F1 score for the predicted tuples.
Parameters
----------
gold_tuples : set
Set of gold-standard 4-tuples.
pred_tuples : set
Set of predicted 4-tuples.
Returns
-------
scores : tuple
A 3-tuple containing (precision, recall, f1).
"""
precision = float(len(gold_tuples & pred_tuples)) / len(pred_tuples)
recall = float(len(gold_tuples & pred_tuples)) / len(gold_tuples)
f1 = 2.0 * precision * recall / (precision + recall)
return precision, recall, f1
|
6ebfee38ed3532c4657fefe8d4499dd28b595593
| 65,180
|
def twos_complement(val: int, bits: int) -> int:
"""
returns the two's complement
of the integer passed in.
bits arg needed to determine the first bit
"""
if (val & (1 << (bits - 1))) != 0:
val = val - (1 << bits)
return val
|
072a453cb25ffa49679ac3895337a1b0dfa773c8
| 65,183
|
def query(db, query_statement):
"""
执行查询语句,并返回结果
:param db: 数据库实例
:param query_statement: 查询语句
:return: 查询结果
"""
cursor = db.cursor() # 获得游标
cursor.execute(query_statement)
result = cursor.fetchall()
return result
|
4950ecf3b15c6d1b0a46b2310bd003b3b4bce01d
| 65,184
|
def _remove_atom_numbers_from_distance(feat_str):
"""
Remove atom numbers from a distance feature string.
Parameters
----------
feat_str : str
The string describing a single feature.
Returns
-------
new_feat : str
The feature string without atom numbers.
"""
# Split the feature string in its parts
parts = feat_str.split(' ')
# Glue the desired parts back together
new_feat = parts[0]
for nr in [1,2,3,5,6,7,8]:
new_feat += ' '+parts[nr]
return new_feat
|
95daddf73364d3fb619c7fbba0ac2d57a3680952
| 65,190
|
def table_delta(first_summary, second_summary):
"""
A listing of changes between two TableSummarySet objects.
:param first_summary: First TableSummarySet object
:param second_summary: Second TableSummarySet object
:return: Change in number of rows
"""
differences = []
for first, second in zip(first_summary, second_summary):
diff = first.number_of_rows - second.number_of_rows
differences.append(diff)
return differences
|
96c3931e4891c14a3d0f84a87abbec2ab85bf48d
| 65,192
|
def cdata_section(content):
"""
Returns a CDATA section for the given ``content``.
CDATA sections are used to escape blocks of text containing characters which would
otherwise be recognized as markup. CDATA sections begin with the string
``<![CDATA[`` and end with (and may not contain) the string
``]]>``.
"""
if content is None:
content = ''
return "<![CDATA[%s]]>" % content
|
f3cd615deb5b558d1318ef7174612d2f5a67e95e
| 65,196
|
def combine_options(options=None):
""" Returns the ``copy_options`` or ``format_options`` attribute with spaces in between and as
a string. If options is ``None`` then return an empty string.
Parameters
----------
options : list, optional
list of strings which is to be converted into a single string with spaces
inbetween. Defaults to ``None``
Returns
-------
str:
``options`` attribute with spaces in between
"""
return " ".join(options) if options is not None else ""
|
86f508aa2dba4f0db1b2824ff525f987cff3db24
| 65,197
|
def _dd_id_to_b3_id(dd_id):
# type: (int) -> str
"""Helper to convert Datadog trace/span int ids into B3 compatible hex ids"""
# DEV: `hex(dd_id)` will give us `0xDEADBEEF`
# DEV: this gives us lowercase hex, which is what we want
return "{:x}".format(dd_id)
|
fffa8b2e46796cf154197c9f311e0aeba62d0d0a
| 65,199
|
def noneOrValueFromStr(s):
"""Return `None` if `s` is '' and the string value otherwise
Parameters
----------
s : str
The string value to evaluate
Return
------
`None` or the string value
"""
r = None if not s or not s.strip() or s.upper() == 'NONE' else s
return r
|
ad50b520249f42c9567e02514c7760af881e1bcc
| 65,202
|
def calcular_moles(presion: float, volumen: float, temp_celsius: float) -> float:
""" Ley de los gases ideales
Parámetros:
presion (float): Presión del gas, en Pascales
volumen (float): Volumen del gas, en litros
temp_celsius (float): Temperatura del gas, en grados centígrados o Celsius
Retorno:
float: Número de moles del gas con dos cifras decimales.
"""
temp_kelvin = temp_celsius + 273.15
volumen = volumen / 1000
n = (presion * volumen) / (8.314 * temp_kelvin)
return round(n, 2)
|
a81edeeed6dc771f852c76fd2c967258bb751afe
| 65,205
|
def test_create_dataframe(df, column_names):
"""
Test if the DataFrame contains only the columns that you specified as the second argument.
Test if the values in each column have the same python type
Test if there are at least 10 rows in the DataFrame.
:param df:
:param column_names:
:return: true of false
"""
# The DataFrame contains only the columns that you specified as the second argument.
df_column_names = df.columns.tolist()
set_df_column = set(df_column_names)
set_column = set(column_names)
if set_df_column != set_column:
return False
# The values in each column have the same python type
for i in range(len(list(df.dtypes))):
for j in range(list(df.count())[i]):
if type(df.iloc[j, i]) != type(df.iloc[0, i]):
return False
# There are at least 10 rows in the DataFrame.
if df.shape[0] < 10:
return False
return True
|
cacd0b1a6766f0440edec5ac6198337c56e7d365
| 65,206
|
import click
def good(text: str) -> str:
"""Styles text to green."""
return click.style(f"INFO: {text}", fg="green", bold=True)
|
08e3da017d944fdb5b86c2e92b79ac9dc798b6a6
| 65,219
|
def get_jaccard_score(a, s):
"""
Function that computes the jaccard score between two sequences
Input: two tuples; (start index of answer, length of answer). Guaranteed to overlap
Output: jaccard score computed for the two sequences
"""
a_start = a[0]
a_end = a[0]+a[1]-1
start = s[0]
end = s[0]+s[1]-1
pred_ids = set(range(start, end+1))
label_ids = set(range(a_start, a_end+1))
jacc = len(pred_ids.intersection(label_ids)) / len(pred_ids.union(label_ids))
return jacc
|
c395ff7ab685e19ee893bc90ea2b6baf85efa21d
| 65,221
|
import re
def _words_matcher(words):
"""Construct a regexp that matches any of `words`"""
reg_exp = "|".join("{}".format(word) for word in words)
return re.compile(reg_exp, re.I)
|
efdf898e3ab1c648e3c86edaac524d21dfb3d7cf
| 65,223
|
import math
def phi(x):
"""Cumulative distribution function for the standard normal distribution
Taken from python math module documentation"""
return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
|
5c2b65dfa33c1f7c4cacabba98b3abaede26a059
| 65,227
|
from typing import List
def output_lines_to_code_block(output_lines: List[str]) -> List[str]:
"""Translate the output of a help command to a RST code block."""
result = (
[".. code-block::", ""]
+ [" " + output_line for output_line in output_lines]
+ [""]
)
result = [line.rstrip() for line in result]
return result
|
b1660049717fc3d52c418f4154bb8e8f3336e239
| 65,228
|
def cal_anomaly_Y(df, df_ref):
"""
Calculates yearly averaged temperature anomaly (departure) from the reference period.
Parameters:
- df: DataFrame from which anomaly is calculated
- df_ref: DataFrame of the reference period
Returns:
- df_Y: yearly averaged anomaly
- df_ref_Y: yearly averaged reference temperatures
"""
# reference frame (just a number now)
df_ref_Y = df_ref['value'].mean()
# plotting frame:
df_Y = df.resample('AS').mean() # this will fill incomplete years into complete ones and place the mean into the first day of the year
# calculate anomaly:
df_Y['value'] -= df_ref_Y
return df_Y, df_ref_Y
|
f05b01cc33f7d9bb1fb702bf3cfce56dbe403000
| 65,229
|
def formatted_bytes(bytes_number):
"""
Given a number of bytes, return a string with a nice format
"""
if bytes_number >= 1024 ** 4:
return f"{bytes_number / 1024 ** 4:.1f} TB"
if bytes_number >= 1024 ** 3:
return f"{bytes_number / 1024 ** 3:.1f} GB"
if bytes_number >= 1024 ** 2:
return f"{bytes_number / 1024 ** 2:.1f} MB"
if bytes_number >= 1024:
return f"{bytes_number / 1024:.1f} kB"
else:
return f"{bytes_number:.0f} bytes"
|
2da92ca3ac6c0f91655d4843c9cb532ed78a5ab1
| 65,230
|
def format_dword(i):
"""Format an integer to 32-bit hex."""
return '{0:#010x}'.format(i)
|
c3cab18aa7dc3ac4b8cbcc6282b06839aab0bb7b
| 65,233
|
def is_derived_node(node):
"""
Returns true if this node is derived (i.e. built).
"""
return node.has_builder() or node.side_effect
|
619000446328a693eec4bb0f027eb183bccd42c6
| 65,236
|
import itertools
import re
def remove_control_chars(s):
"""Remove control characters
Control characters shouldn't be in some strings, like channel names.
This will remove them
Parameters
----------
s : str
String to check
Returns
-------
control_char_removed : str
`s` with control characters removed.
"""
control_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0))))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
control_char_removed = control_char_re.sub('', s)
return control_char_removed
|
f4d35822d4dc9e9a32bdcfe797a4133d9695fb3e
| 65,237
|
def good_box(sudoku_board, row_num, col_num, num):
"""
Checks to make sure that a given "box" in a sudoku board is possible if an
int num is placed into that "box"
"""
boxes = [sudoku_board[3 * i: 3 * (i + 1), 3 * j: 3 * (j + 1)] for i in range(3) for j in range(3)]
if num not in boxes[(row_num // 3) * 3 + (col_num // 3)]:
return True
return False
|
4a49adeeb60f9581b973d10740b1040d17ad293e
| 65,240
|
def get_documents(cls, ids):
"""Returns a list of ES documents with specified ids and doctype
:arg cls: the class with a ``.search()`` to use
:arg ids: the list of ids to retrieve documents for
"""
ret = cls.search().filter(id__in=ids).values_dict()[:len(ids)]
return list(ret)
|
85d84315d70c70b029d1de83862b71611b05d4f6
| 65,241
|
import torch
def to_ca_mode(logits: torch.Tensor, ca_mode: str = "1/2/3") -> torch.Tensor:
"""
Converts the logits to the ca_mode.
Args:
logits (torch.Tensor): The logits.
ca_mode (str): The cornu ammoni division mode.
Returns:
torch.Tensor: The corrected logits.
"""
# 0: bg, 1: dg, 2: ca1, 3: ca2, 4: ca3, 5: sub
if not ca_mode:
# Whole hippocampus
_pre = logits[:, :1, :, :, :]
_in = torch.sum(logits[:, 1:, :, :, :], dim=1, keepdim=True)
return torch.cat([_pre, _in], dim=1)
elif ca_mode == "1/2/3":
# identity
return logits
elif ca_mode == "1/23":
# ca1; ca2+ca3
_pre = logits[:, :3, :, :, :]
_in = logits[:, 3:4, :, :, :] + logits[:, 4:5, :, :, :]
_post = logits[:, 5:, :, :, :]
return torch.cat([_pre, _in, _post], dim=1)
elif ca_mode == "123":
# ca1+ca2+ca3
_pre = logits[:, :2, :, :, :]
_in = logits[:,
2:3, :, :, :] + logits[:,
3:4, :, :, :] + logits[:,
4:5, :, :, :]
_post = logits[:, 5:, :, :, :]
return torch.cat([_pre, _in, _post], dim=1)
else:
raise ValueError(
f"Unknown `ca_mode` ({ca_mode}). `ca_mode` must be 1/2/3, 1/23 or 123"
)
|
151a420764d37a7b4b50acfeb86979c9d03a6f83
| 65,243
|
def round_half(x):
"""Rounds a floating point number to exclusively the nearest 0.5 mark,
rather than the nearest whole integer."""
x += 0.5
x = round(x)
return x-0.5
|
26fa072decf8b66a8a8ab54821d8cc297e311051
| 65,250
|
from typing import Dict
from typing import Optional
from typing import Iterable
def get_attrib_value(attribs: Dict[str, str],
name: str,
ns: str,
value_prefixes: Optional[Iterable[str]] = None) -> Optional[str]:
"""
Retrieves the value of an attribute from a dict of `etree.Element` attributes based on its name
and namespace. The value could be prefixed by any string so it has to be provided in order to
not be considered in the returned value.
:param attribs:
:param name:
:param ns: namespace
:param value_prefixes:
:return:
"""
value_prefixes = value_prefixes or []
result = attribs.get(f'{{{ns}}}{name}')
if result is None:
return
for value_prefix in value_prefixes:
if result.startswith(value_prefix):
result = result[len(value_prefix):]
break
return result
|
97aa9d0fabdd66732fe3be033add2009e4be32ab
| 65,253
|
def tokens_ready(setcookies, tokens):
"""check if all required tokens are present in set-cookies headers"""
if setcookies == None or tokens == None:
return False
_tokens = tokens[:]
for tk in setcookies:
if tk in _tokens:
_tokens.remove(tk)
if len(_tokens) == 0:
return True
return False
|
b290bc15223d878891aea14dea1d448d25fe0061
| 65,257
|
def convert_16bit_pcm_to_byte(old_value: int) -> int:
"""Converts PCM value into a byte."""
old_min = -32768 # original 16-bit PCM wave audio minimum.
old_max = 32768 # original 16-bit PCM wave audio max.
new_min = 0 # new 8-bit PCM wave audio min.
new_max = 255 # new 8-bit PCM wave audio max.
byte_value = int((((old_value - old_min) * (new_max - new_min)) /
(old_max - old_min)) + new_min)
return byte_value
|
29af84a0e86b23ec66558faeebb091432feef02a
| 65,259
|
def _files_header_size_calc(files, farc_type):
"""Sums the size of the files header section for the given files and farc_type data."""
size = 0
for fname, info in files.items():
size += len(fname) + 1
size += farc_type['files_header_fields_size']
return size
|
683edc524a2f353cae8c974f5c72616bddafa27a
| 65,263
|
def _feet_to_meters(length):
"""Convert length from feet to meters"""
return length * 2.54 * 12.0 / 100.0
|
bde2dc9201d8b50b831334fee2f44ea7310057ca
| 65,265
|
def flatten(list_a: list):
"""Problem 7: Flatten a Nested List Structure,
Parameters
----------
list_a : list
The input list
Returns
-------
flat : list
The flattened input list
Raises
------
TypeError
If the given argument is not of `list` type
"""
if not isinstance(list_a, list):
raise TypeError('The argument given is not of `list` type.')
flat = []
for x in list_a:
if isinstance(x, list):
# If element x is a list then the initial list should be
# extended by the elements of list x
flat.extend(flatten(x))
else:
# Otherwise a single element is appended
flat.append(x)
return flat
|
ec229c1dcfd575b7dd0fd50f45bc6faa1f52af08
| 65,269
|
def sigmoid_derivative(x):
"""Derivative to the Sigmoid function"""
return x * (1 - x)
|
58d9f70d54d64b72a22834ffae61b8722e3f343b
| 65,272
|
def split_df_into_chunks(df, n_chunks):
"""
Split passed DataFrame into `n_chunks` along row axis.
Parameters
----------
df : DataFrame
DataFrame to split into chunks.
n_chunks : int
Number of chunks to split `df` into.
Returns
-------
list of DataFrames
"""
chunks = []
for i in range(n_chunks):
start = i * len(df) // n_chunks
end = (i + 1) * len(df) // n_chunks
chunks.append(df.iloc[start:end])
return chunks
|
314fc463100e739d3c20a1edb9e9f5699591ae98
| 65,273
|
def replace_at(string,old,new,indices):
"""Replace the substring "old" by "new" in a string at specific locations
only.
indices: starting indices of the occurences of "old" where to perform the
replacement
return value: string with replacements done"""
if len(indices) == 0: return string
indices = sorted(indices)
s = string[0:indices[0]]
for i in range(0,len(indices)-1):
s += string[indices[i]:indices[i+1]].replace(old,new,1)
s += string[indices[-1]:].replace(old,new,1)
return s
|
a136b498a627aba3ebdf6ed3c339a272c88dd3e3
| 65,277
|
def get_sort_params(input_params, default_key='created_at',
default_dir='desc'):
"""Retrieves sort keys/directions parameters.
Processes the parameters to create a list of sort keys and sort directions
that correspond to the 'sort_key' and 'sort_dir' parameter values. These
sorting parameters can be specified multiple times in order to generate
the list of sort keys and directions.
The input parameters are not modified.
:param input_params: webob.multidict of request parameters (from
masakari.wsgi.Request.params)
:param default_key: default sort key value, added to the list if no
'sort_key' parameters are supplied
:param default_dir: default sort dir value, added to the list if no
'sort_dir' parameters are supplied
:returns: list of sort keys, list of sort dirs
"""
params = input_params.copy()
sort_keys = []
sort_dirs = []
while 'sort_key' in params:
sort_keys.append(params.pop('sort_key').strip())
while 'sort_dir' in params:
sort_dirs.append(params.pop('sort_dir').strip())
if len(sort_keys) == 0 and default_key:
sort_keys.append(default_key)
if len(sort_dirs) == 0 and default_dir:
sort_dirs.append(default_dir)
return sort_keys, sort_dirs
|
6e79ea2c03eb3fa12086e6740b4860069be22fe5
| 65,278
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.