content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def is_xml_response(req):
"""Returns True when the request wants an XML response, False otherwise"""
return "Accept" in req.headers and "application/xml" in req.accept | 643e42ab57fe612de4f7e7121477b4574971992b | 406,372 |
def build_pubmed_url(pubmed_id) -> str:
"""
Generates a Pubmed URL from a Pubmed ID
:param pubmed_id: Pubmed ID to concatenate to Pubmed URL
:return: Pubmed URL
"""
return "https://pubmed.ncbi.nlm.nih.gov/" + str(pubmed_id) | 5794fbec75de0451547d6f0570bb89964026c394 | 5,081 |
import requests
def image_exists_on_dockerhub(image_name: str, image_tag: str) -> bool:
"""
Given an image name and image_tag, check if it is
publicly-accessible on DockerHub.
Based on the code from this blog post:
* htttps://ops.tips/blog/inspecting-docker-image-without-pull/
:param image_name: Name of an image, such as ``continuumio/miniconda3``
:param image_tag: Tag for the image, such as ``4.8.2``
:Example:
.. code-block:: python
# should be True
image_exists_on_dockerhub("continuumio/miniconda3", "4.8.2")
# should be False
import uuid
image_exists_on_dockerhub(str(uuid.uuid4()), "0.0.1")
"""
url = (
"https://auth.docker.io/token?scope=repository:"
f"{image_name}:pull&service=registry.docker.io"
)
res = requests.get(url=url)
res.raise_for_status()
token = res.json()["token"]
res = requests.get(
url=f"https://registry-1.docker.io/v2/{image_name}/manifests/{image_tag}",
headers={
"Accept": "application/vnd.docker.distribution.manifest.v2+json",
"Authorization": f"Bearer {token}",
},
)
return res.status_code == 200 | 989214d56a2a4635759c1bc6fc821e63a2e28718 | 90,734 |
def calculate_cbar_dims(img_width, img_figsize, img_height):
"""
Helper for plot_topomap_3d_brain when plotting multiple views and using the
matplotlib backend. Calculates the colorbar width and height to be placed
correctly.
Parameters:
img_width: matplotlib.figure.Figure
Number of brain images to include horizontally.
img_figsize: int
Total height/width of the image in inches (square image).
img_height: int
Number of brain images to include vertically.
Returns:
cbar_width: float
Width of colorbar in matplotlib units.
cbar_height: float
Height of colorbar in matplotlib units.
"""
cbar_adjustments_table = {1: [1.365, 1.43],
2: [0.689, 0.71],
3: [0.611, 0.57],
4: [0.559, 0.50],
5: [0.494, 0.45],
6: [0.455, 0.40],
7: [0.429, 0.38]}
cbar_adjustments = cbar_adjustments_table[img_width]
cbar_height = img_figsize * img_width * cbar_adjustments[0]
cbar_width = img_figsize * img_width * cbar_adjustments[1]
return cbar_width, cbar_height | 60f8c668f7e3ae04d6943e1a2ecd974dbba0bb07 | 159,906 |
def fibonacci2(number: int) -> int:
"""
Generate the fibonacci number for n
Utilizes caching to mimic literal memoization, has lower recursive limit...
0, 1, 1, 2, 3, 5, 8, 13, .... 0 = 0 , 1 = 1, 3 = 2, etc
:param number: iteration of the Fibonacci sequence
:return: Fibonacci number
"""
if number < 2:
return number
return fibonacci2(number - 1) + fibonacci2(number - 2) | ba32daf9b9b56faecda305f50d9e8f5cb7e4c1cb | 635,802 |
import math
def get_learning_rate(lr_schedule,
tot_epoch,
cur_epoch):
""" Compuate learning rate based on the initialized learning schedule,
e.g., cosine, 1.5e-4,90,6e-5,150,0 -> ('cosine', [1.5e-4,90,6e-5,150,0]).
Args:
lr_schedule: the learning schedule specified in args.py
tot_epoch: the total epoch
cur_epoch: the current (float) epoch
"""
# cosine
lr_mtd = lr_schedule[0]
# 90, 150
ep_list = lr_schedule[1][1::2]
# 1.5e-4,6e-5,0
lr_list = lr_schedule[1][::2]
assert len(ep_list) + 1 == len(lr_list)
for start, end, lr in zip([0] + ep_list,
ep_list + [tot_epoch],
lr_list):
if start <= cur_epoch < end:
if lr_mtd == 'cosine':
return lr * (math.cos((cur_epoch - start) / (end - start) * math.pi) + 1) / 2
elif lr_mtd == 'const':
return lr
else:
raise TypeError('Invalid learning method {}'.format(lr_mtd))
raise TypeError('Invalid learning schedule {}'.format(lr_schedule)) | a6ee1d202d846094243baa120f1486e33016a174 | 636,900 |
import string
def populate_cypher_query_template_with_values_in_dict(cypher_query_template, dictionary):
"""Populates and Returns a user provided Cypher query with values plucked from a `dictionary`.
Args:
cypher_query_template (:obj:`string.Template`): string.Template to populate with values.
dictionary (:obj:`dict`): dict of form { "$"-based substitution: value to be passed to string.Template }.
Return:
query (:obj:`str`): Input `cypher_query_template` returned with values passed to "$"-based substitutions present.
"""
if type(cypher_query_template) != string.Template:
raise TypeError('cypher_query_template parameter must be string.Template.')
if type(dictionary) != dict:
raise TypeError('dictionary parameter must be dict.')
query = cypher_query_template.substitute(dictionary)
return query | bcb2e11350e15e9da39df88259b38800855f3e57 | 499,244 |
def imap(imap, vmin=None, vmax=None, cmap='YlGnBu_r', length_unit='cm'):
"""
Convenience base function to plot any IntensityMap2D instance
Parameters
----------
ratemap : IntensityMap2D
Intensity map to plot
cmap : Colormap or registered colormap name, optional
Colormap to use for the plot.
length_unit : string, optional
The length unit to add to the axis labels. If None, no length unit is
printed.
Returns
-------
See `IntensityMap2D.plot`.
"""
axes, cbar = imap.plot(cmap=cmap, vmin=vmin, vmax=vmax,
#edgecolor='face',
)
#cbar.solids.set(edgecolor='face')
range_ = imap.range_
axes.set(xticks=range_[0], yticks=range_[1])
if length_unit is None:
axes.set(xlabel=r"$x$",
ylabel=r"$y$")
else:
axes.set(xlabel=r"$x \ / \ \mathrm{{{}}}$".format(length_unit),
ylabel=r"$y \ / \ \mathrm{{{}}}$".format(length_unit))
return axes, cbar | fbc19e21f7740bb2965f99398090eb24929b4e52 | 646,498 |
import json
def load_from_json(filepath):
""" Load json file from filepath into a dictionary
:param filepath:
:return: python dictionary
"""
data = dict()
with open(filepath) as data_file:
data = json.load(data_file)
return data | 4943a9719feac01f42000ea3f4b2f2240ad8acaa | 602,921 |
import torch
def collate_fn(task_list):
"""Custom collate function to batch tasks together into single tensors.
Args:
task_list: a list of tasks, where each task is a dictionary as returned by the
__getitem__ method of the dataset object
Returns:
batch: a dictionary with keys 'cond', 'pool', 'pool_labels', 'query', 'query_labels'.
The value of 'cond' is an array of shape (batch_size), the value of 'pool' is a
tensor of shape (batch_size, pool_size, embedding_size), the value of 'pool_labels'
is a tensor of shape (batch_size, pool_size), the value of 'query' is a tensor of
shape (batch_size, query_set_size, embedding_size), and the value of 'query_labels'
is a tensor of shape (batch_size, query_set_size)
"""
cond = [s['cond'] for s in task_list]
batch = {'cond': cond, 'pool': None, 'pool_labels': None, 'query': None, 'query_labels': None}
keys = ['pool', 'pool_labels', 'query', 'query_labels']
for key in keys:
tensor_list = [s[key] for s in task_list]
stacked = torch.stack(tensor_list, dim=0)
batch[key] = stacked
batch['pool_labels'] = batch['pool_labels'].long()
batch['query_labels'] = batch['query_labels'].long()
return batch | 2cae401001145e5d7b8489f7499a7b781be35a90 | 344,929 |
def compare_acl(acl1, acl2):
"""
Compares two ACLs by comparing the role, action and allow setting for every ACE.
:param acl1: First ACL
:type acl1: dict with role, action as key and allow as value
:param acl2: Second ACL
:type acl2: dict with role, action as key and allow as value
:return: true if equal
:rtype: bool
"""
if not acl1 and not acl2:
return True
if (not acl1 and acl2) or (acl1 and not acl2):
return False
keys1 = acl1.keys()
keys2 = acl2.keys()
if len(keys1) != len(keys2):
return False
for key in keys1:
if key not in keys2:
return False
if acl1[key] != acl2[key]:
return False
return True | 4e38bb1a0dabe58401898a804bc5d3054861df97 | 663,923 |
def check_now_deleted(page):
"""Returns true if the page is deleted"""
# simple check for any content, does catch blanked pages though
return not page.text | 9e48fbca1a8b08f26deb2651d979c13c9d09dadf | 509,876 |
import re
def check_element_symbol(name, symbol):
"""
Checks if symbol is valid for the element
:param name: Element name
:param symbol: Validated symbol
:return: True if symbol is valid, False otherwise
"""
# valid symbol has exactly 2 chars
if not len(symbol) == 2 or not symbol.istitle():
return False
symbol_in_name_re = re.compile(r'.*{0}.*{1}.*'.format(symbol[0], symbol[1]), re.I)
if symbol_in_name_re.match(name):
return True
else:
return False | 3fe6d9405bc72ad1280b6a59a52edbd9f3eadfed | 275,085 |
import requests
def __create_auth_github_session(cfg, session=None):
"""Create and return GitHub session authorized with token in configuration object"""
session = session or requests.Session()
token = cfg["github"]["token"]
def token_auth(req):
req.headers["Authorization"] = f"token {token}"
return req
session.auth = token_auth
return session | 2708543b99c013b31558838df3e4861288888b6c | 91,966 |
def intersection_count_to_boundary_weight(intersection_count: int) -> int:
"""
Get actual weight factor for boundary intersection count.
>>> intersection_count_to_boundary_weight(2)
0
>>> intersection_count_to_boundary_weight(0)
1
>>> intersection_count_to_boundary_weight(1)
2
"""
if not isinstance(intersection_count, int):
intersection_count = intersection_count.item()
assert isinstance(intersection_count, int)
if intersection_count == 0:
return 1
if intersection_count == 1:
return 2
if intersection_count == 2:
return 0
raise ValueError(f"Expected 0,1,2 as intersection_count. Got: {intersection_count}") | 34303e1200db250236c950ec1c21d0dd7b27800d | 167,679 |
def formatUintHex64(value):
"""
Format an 64 bits unsigned integer.
"""
return u"0x%016x" % value | af82b7b6dd138333f09cf93e9d7990be286333fd | 688,266 |
def listFromFile(fileName):
"""Read in a file; return a list of its lines. Ignore blank lines."""
lines = []
with open(fileName, 'r') as inF:
line = inF.readline()
while (line):
line = line.rstrip()
if (len(line)):
lines.append(line)
line = inF.readline()
return lines | 63ba94bd18b6401d2f3b0aee7e06a543fc530105 | 491,326 |
import json
def validate_file(file_name):
"""File validation.
Create/Open File, return list of dicts
"""
try:
with open(file_name,'r'):
print('-- Opening file... \'' + file_name + '\'!!')
with open(file_name,'r') as fread:
all_events = json.load(fread)
return all_events
except IOError:
print('-- File does not exist...')
print('-- Creating and using file \'' + file_name + '\'!')
temp = []
with open(file_name,'w') as fwrite:
json.dump(temp, fwrite)
return temp | 2da8ea3148ee63ef8689b270eb5645b1257baabc | 372,746 |
from typing import FrozenSet
from typing import List
def get_profit(solution: FrozenSet[int], profit: List[float]):
"""
Calculates and returns total profit of given knapsack solution
:param solution: Knapsack solution consisting of packed items
:param profit: profit of items
:return: Total profit of given knapsack solution
"""
return sum(profit[item - 1] for item in solution) | c7c359582446908535964d8c6d4b45dac6b0f6af | 271,472 |
import re
def space_in_tables(filestr):
"""
Add spaces around | in tables such that substitutions $...$ and
`...` get right.
"""
pattern = r'^\s*\|.+\| *$' # table lines
table_lines = re.findall(pattern, filestr, re.MULTILINE)
horizontal_rule = r'^\s*\|[-lrc]+\|\s*$'
inserted_space_around_pipe = False
for line in table_lines:
if not re.search(horizontal_rule, line, flags=re.MULTILINE) \
and (re.search(r'[$`]\|', line) or re.search(r'\|[$`]', line)) \
and line.count('|') > 2:
# Found $|, |$, `|, or |` in table line, insert space
line_wspaces = re.sub(r'([$`])\|', r'\g<1> |', line)
line_wspaces = re.sub(r'\|([$`])', r'| \g<1>', line_wspaces)
filestr = filestr.replace(line, line_wspaces)
inserted_space_around_pipe = True
return filestr, inserted_space_around_pipe | c45dd26dd329e587e92e6df494ab04e8fddaf3c9 | 368,311 |
def str_to_bool(text):
"""
Parses a boolean value from the given text
"""
return text and text.lower() in ["true", "y", "yes", "1"] | af7a303de0a923f3a171898204c2b2a656d094f2 | 280,767 |
def _as_inline_code(text):
"""Apply inline code markdown to text
Wrap text in backticks, escaping any embedded backticks first.
E.g:
>>> print(_as_inline_code("foo [`']* bar"))
`foo [\\`']* bar`
"""
escaped = text.replace("`", r"\`")
return f"`{escaped}`" | 52b01b0e6eeb30ea7845c19006375d6c04748770 | 100,710 |
def top_level_files(project):
"""
Given a project, return only the top-level files -
useful for generating table-of-contents, etc
"""
return project.files.filter(parent__isnull=True) | d9a9d45a59d4dcad91c0c1b354ea5784e3ad27aa | 335,290 |
def VerboseCompleter(unused_self, event_object):
"""Completer function that suggests simple verbose settings."""
if '-v' in event_object.line:
return []
else:
return ['-v'] | e536e221f8f3465f72071d969b11b6623359cf58 | 7,342 |
from typing import Callable
import math
def _geometric_binary_search(
func: Callable[[float], float],
target: float,
iterations: int = 24,
reverse: bool = False
) -> float:
"""Perform a binary search using geometric centers.
Do a binary search to find the value ``n`` that makes the function ``func``
return ``target`` when ``n`` is used as the argument. By default, it is
assumed that smaller values of ``n`` will cause ``func`` to produce smaller
outputs. If smaller values of ``n`` produce larger outputs, set ``reverse``
to True.
This implementation of binary search uses the geometric mean instead of the
arithmetic mean to determine the center of the search space. This is
because the values that are being searched are weighted towards zero.
:param func: A Callable which accepts a float and returns a float. This
must be a one-to-one function.
:param target: A float representing the target output which we are trying
to make func produce.
:param iterations: An integer representing the number of iterations to run
the binary search. The default of 24 should be sufficient for most
applications.
:param reverse: A bool representing the relationship between the input and
output values of func.
:return: A float representing value n which makes the function func produce
target when called as its argument.
"""
lower_bound = 2 ** -iterations
upper_bound = 2 ** iterations
assert lower_bound <= upper_bound
for _ in range(iterations):
guess = math.sqrt(lower_bound * upper_bound)
answer = func(guess)
if (not reverse and answer > target) or (reverse and answer < target):
upper_bound = guess
else:
lower_bound = guess
return math.sqrt(lower_bound * upper_bound) | fa61dd9f1129474d43915f47344005a7eda0aa96 | 33,147 |
def ticket_matuation_to_dict(mutation: str, meta_data: dict):
"""
Used in run_mutations to create a dict from. In order to
Takes one mutation line of an IPFS batch
Returns structured dictionary.
-> INDEX of dataframe / database
'statehash_tx': -> hash / receipt of state or mutation(n)
'previous_statehash': -> hash / receipt of state or mutation(n-1)
'input_message' : -> value inputted in message input (could be privId or eventId)
'transition_type': -> type of mutation (w or f)
'transition_id': -> id of the mutation
'block_height': -> blockheight of the block anchoring the mutation.
'block_timestamp': -> timestamp of the block anchorring the mutation.
'transaction_hash': -> hash of the blockchain transaction that anchorred the tx.
'IPFS_hash': -> hash of the IPFS file that contains the mutation
"""
m = list(mutation.split(","))
output_dict = {
'statehash_tx': m[0],
'previous_statehash': m[1],
'transition_type': m[2],
'transition_id': m[3],
'input_message': str("null"),
'block_height': meta_data["block_height"],
'block_timestamp': meta_data["block_timestamp"],
'transaction_hash': meta_data["transaction_hash"],
'IPFS_hash': meta_data["IPFS_hash"]
}
return output_dict | 7df04b269c5b18c93cfb2281f099afb44ccdfaf0 | 163,707 |
def make_title(title):
"""Create a underlined title with the correct number of =."""
return "\n".join([title, len(title)*"="]) | 9e2b9cc2816563d1ca1ede04db479c806d76ae52 | 509,056 |
import ntpath
def path_leaf(path):
"""
Extract the file name from a path.
If the file ends with a slash, the basename will be empty,
so the function to deal with it
Parameters
----------
path : str
Path of the file
Returns
-------
output : str
The name of the file
"""
head, tail = ntpath.split(path)
output = tail or ntpath.basename(head)
return output | 58930f081c2366b9084bb279d1b8b267e5f93c96 | 705,086 |
import typing
def build_issue_doc(org:str, repo:str, title:str, text:typing.List[str]):
"""Build a document string out of various github features.
Args:
org: The organization the issue belongs in
repo: The repository.
title: Issue title
text: List of contents of the comments on the issue
Returns:
content: The document to classify
"""
pieces = [title]
pieces.append(f"{org.lower()}_{repo.lower()}")
pieces.extend(text)
content = "\n".join(pieces)
return content | 56bebe316a7a8787c954eb5e74cc1b0e79f26714 | 104,074 |
def cipher(text, shift, encrypt=True):
"""
Function to encipher or decipher the string by using different shift number.
Parameters
----------
text : string
A string that you wish to encipher or decipher.
shift : integer
An integer that you wish to shift.
encrypt : boolean
A boolean that you would like to encrypt string or not.
Returns
-------
string
The text after being encrypted or decrypted
Example
-------
>>> from cipher_wl2788 import cipher_wl2788
>>> text = "happy"
>>> shift = 1
>>> cipher_wl2788.cipher(text, shift, encrypt = True)
'ibqqz'
"""
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
new_text = ''
for c in text:
index = alphabet.find(c)
if index == -1:
new_text += c
else:
new_index = index + shift if encrypt == True else index - shift
new_index %= len(alphabet)
new_text += alphabet[new_index:new_index+1]
return new_text | be24472672cb8ac4f9e582ea367f639f9709fb93 | 616,022 |
def filter_by_total_count(feature_table_df, sum_axis=1):
"""
Remove samples that have total counts <= 5 (R complains if total count <= 5)
Inputs
- feature_table_df: feature table in pandas DataFrame
- sum_axis: axis to sum over.
Do axis=0 if sample as columns, taxa/ASV as rows (index)
Do axis=1 if sample as rows (index), taxa/ASV as columns
Default option assumes sample as row (index), taxa/ASV as columns
"""
row_sum = feature_table_df.sum(sum_axis)
to_keep = row_sum > 5
filtered_df = feature_table_df.loc[to_keep, ]
return filtered_df | d8d7f0ada2f5b09eb509060ddc0b1d69f215db8b | 511,845 |
import time
def retry(predicate_task, timeout_sec=30, every=0.05, msg='Timed out retrying'):
"""
Repeat task every `interval` until it returns a truthy value or times out.
"""
begin = time.monotonic()
threshold = begin + timeout_sec
while True:
res = predicate_task()
if res:
return res
elif time.monotonic() < threshold:
time.sleep(every)
else:
raise TimeoutError(msg) | b31479765cadd35d69c5c69c55bd791a29c49c5d | 507,979 |
def checksum(number):
"""Calculate the checksum. A valid number should have a checksum of 1."""
check = 0
for n in number:
check = (2 * check + int(10 if n == 'X' else n)) % 11
return check | 8ada40ca46bc62bbe8f96d69528f2cd88021ad6a | 707,437 |
def row_describes_data(row):
"""
Returns True if this appears to be a row describing data, otherwise False.
Meant to be used in conjunction with filter to prune out those rows
that don't actually describe data, such as empty strings or decorations
that delimit headers from actual data (i.e. '+----|----|-----+')
"""
if row:
if row.startswith('+') and row.endswith('+'):
return False
return True
return False | fa30057cc4098c0d51ec528c1032ef62d7b6fa5a | 457,512 |
def compute_resolution(time_grid):
"""
Compute the resolution given the time grid at which measurements are made.
:param time_grid: The time grid on which the sample is taken.
:return delta: the resolution
"""
count = len(time_grid)
delta = 0
for i in range(len(time_grid) - 1):
diff = time_grid[i + 1] - time_grid[i]
delta += diff
delta = delta/count
return delta | d63ac2b2a5c33b8c0b2cf7490554392f35b1b4c4 | 543,481 |
def gcd(x: int, y: int) -> int:
"""
Euclidean GCD algorithm (Greatest Common Divisor)
>>> gcd(0, 0)
0
>>> gcd(23, 42)
1
>>> gcd(15, 33)
3
>>> gcd(12345, 67890)
15
"""
return x if y == 0 else gcd(y, x % y) | 8e8f51f703085aabf2bd22bccc6b00f0ded4e9ca | 673,381 |
def parse_arguments(parser):
"""Read user arguments"""
parser.add_argument('--path_model',
type=str, default='Model/weights.01.hdf5',
help='Path to the model to evaluate')
parser.add_argument('--path_data', type=str, default='data/data_test.pkl',
help='Path to evaluation data')
parser.add_argument('--path_dictionary', type=str, default='data/dictionary.pkl',
help='Path to codes dictionary')
parser.add_argument('--batch_size', type=int, default=32,
help='Batch size for initial probability predictions')
# parser.add_argument('--id', type=int, default=0,
# help='Id of the patient being interpreted')
args = parser.parse_args()
return args | 2a313a9db899231a4138512967b36b3f1f5027ee | 250,819 |
def validate_padding(value):
"""Validates and format padding value
Args:
value: `str` padding value to validate.
Returns:
formatted value.
Raises:
ValueError: if is not valid.
"""
padding = value.upper()
if padding not in ['SAME', 'VALID']:
raise ValueError('Padding value `{}` is not supported, '
'expects `SAME`\`VALID`'.format(value))
return padding | b80ff3728c9f63f0729391033c05d1ebfa0198d9 | 152,754 |
import re
def solve_status_str(hdrlbl, fmtmap=None, fwdth0=4, fwdthdlt=6,
fprec=2):
"""Construct header and format details for status display of an
iterative solver.
Parameters
----------
hdrlbl : tuple of strings
Tuple of field header strings
fmtmap : dict or None, optional (default None)
A dict providing a mapping from field header strings to print
format strings, providing a mechanism for fields with print
formats that depart from the standard format
fwdth0 : int, optional (default 4)
Number of characters in first field formatted for integers
fwdthdlt : int, optional (default 6)
The width of fields formatted for floats is the sum of the value
of this parameter and the field precision
fprec : int, optional (default 2)
Precision of fields formatted for floats
Returns
-------
hdrstr : string
Complete header string
fmtstr : string
Complete print formatting string for numeric values
nsep : integer
Number of characters in separator string
"""
if fmtmap is None:
fmtmap = {}
fwdthn = fprec + fwdthdlt
# Construct a list specifying the format string for each field.
# Use format string from fmtmap if specified, otherwise use
# a %d specifier with field width fwdth0 for the first field,
# or a %e specifier with field width fwdthn and precision
# fprec
fldfmt = [fmtmap[lbl] if lbl in fmtmap else
(('%%%dd' % (fwdth0)) if idx == 0 else
(('%%%d.%de' % (fwdthn, fprec))))
for idx, lbl in enumerate(hdrlbl)]
fmtstr = (' ').join(fldfmt)
# Construct a list of field widths for each field by extracting
# field widths from field format strings
cre = re.compile(r'%-?(\d+)')
fldwid = []
for fmt in fldfmt:
mtch = cre.match(fmt)
if mtch is None:
raise ValueError("Format string '%s' does not contain field "
"width" % fmt)
else:
fldwid.append(int(mtch.group(1)))
# Construct list of field header strings formatted to the
# appropriate field width, and join to construct a combined field
# header string
hdrlst = [('%-*s' % (w, t)) for t, w in zip(hdrlbl, fldwid)]
hdrstr = (' ').join(hdrlst)
return hdrstr, fmtstr, len(hdrstr) | 89d322be134e11bc7d47f3efecbc888ffc7472f5 | 255,983 |
def join_all(domain, *parts):
"""
Join all url components.
Example::
>>> join_all("https://www.apple.com", "iphone")
https://www.apple.com/iphone
:param domain: Domain parts, example: https://www.python.org
:param parts: Other parts, example: "/doc", "/py27"
:return: url
"""
l = list()
if domain.endswith("/"):
domain = domain[:-1]
l.append(domain)
for part in parts:
for i in part.split("/"):
if i.strip():
l.append(i)
url = "/".join(l)
return url | e2c308c615802ae119ab409b1b73d94c0f29e793 | 121,139 |
def format_raw(results):
"""Mate a formatted string for logging/printing from results of
analyze_raw_batch"""
msg = ""
msg += "AbsError: {:0.5E} +- {:0.5E}\n".format(*(results[0]))
msg += "EhfError: {:0.5E} +- {:0.5E}\n".format(*(results[1]))
msg += "IdemEror: {:0.5E} +- {:0.5E}\n".format(*(results[2]))
msg += "OccError: {:0.5E} +- {:0.5E}\n".format(*(results[3]))
return msg | 67f7738968fa1f387ae85ea73fbb8020ccc2de2c | 207,781 |
import time
def gen_id() -> str:
"""generate a fresh reminder id"""
# id is set according to the current unix time
return f'cli-reminder-{time.time()}' | 17a5f6928093ed93f0ff958aaecac41cce443569 | 360,195 |
def json_get(obj, member, typ, default=None):
"""Tries to get the passed member from the passed JSON object obj and makes
sure it is instance of the passed typ.
If the passed member is not found the default is returned instead.
If the typ is not matched the exception ValueError is raised.
"""
if not isinstance(obj, dict):
raise ValueError('the passed JSON is not a dict')
value = obj.get(member, default)
if not isinstance(value, typ):
raise ValueError(f'{member} is not a {typ.__name__}')
return value | f56f45b4922253d44672ca5e0c2903ef81f78fc9 | 206,873 |
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
#return None if there is less or equal to one element in the given array
if len(ints) <= 1:
return None
#initialize the minimun and maximum as the first element of the array
smallest_num = ints[0]
largest_num = ints[0]
for num in ints:
#find the smallest element
if num < smallest_num:
smallest_num = num
#find the largest element
if num > largest_num:
largest_num = num
return smallest_num, largest_num | 5afe2bc788c9a571e31c53a547c12106b4c64861 | 256,524 |
import binascii
def to_bin(x):
"""hex to bin"""
return binascii.unhexlify(x) | 54d448648cc8f3067d72568884332d1a537f67f7 | 481,321 |
def force_array(val):
"""Returns val if it is an array, otherwise a one element array containing val"""
return val if isinstance(val, list) else [val] | f26535484658d5c4832ba03e6a65cbef8143505a | 299,820 |
def some(seq, func):
"""
Description
----------
Return True if some value in the sequence satisfies the predicate function.\n
Returns False otherwise.
Parameters
----------
seq : (list or tuple or set or dict) - sequence to iterate\n
func : callable - predicate function to apply each iteration
Returns
----------
bool - True if some value satisfies the predicate function, False otherwise
Example
----------
>>> lst = ['', 0, None, 1000]
>>> some(lst, bool)
-> True
"""
if not isinstance(seq, (list, tuple, set)):
raise TypeError("param 'seq' must be a list, tuple, or set")
if not callable(func):
raise TypeError("param 'func' must be a callable")
for item in seq:
if func(item):
return True
return False | 1390864f74cb36015c924e4e137bdfe2002f579b | 480,278 |
import string
def isPunct (s):
"""Determine if a character is punctuation.
Params: s (string) a single character (len(s) == 1)
Returns: (bool) is this a punctuation character?
"""
if s in string.punctuation:
return True
else :
return False | aecee86fe23b43333664e5ac4790d74d9c828a62 | 345,863 |
def strip_api(server_url):
"""
Strips "api/" from the end of ``server_url``, if present
>>> strip_api('https://play.dhis2.org/demo/api/')
'https://play.dhis2.org/demo/'
"""
if server_url.rstrip('/').endswith('api'):
i = len(server_url.rstrip('/')) - 3
return server_url[:i]
return server_url | 0dd7b93b70209d3b0b6e6b5294eb5e2fdcbc3c95 | 144,801 |
def calc_specifity(df):
"""df contains the confusion_matrix
as pandas DataFrame
"""
fp = df.loc["yes", "no"]
tn = df.loc["no", "no"]
return tn / (tn + fp) | dcca603f0a761088e772233bc71720ce9e5f47e6 | 147,616 |
def is_attr_true( element, name ):
"""Read a name value from an element's attributes.
The value read from the attribute list must be either 'true' or
'false'. If the value is 'false', zero will be returned. If the
value is 'true', non-zero will be returned. An exception will be
raised for any other value."""
value = element.nsProp( name, None )
if value == "true":
return 1
elif value == "false":
return 0
else:
raise RuntimeError('Invalid value "%s" for boolean "%s".' % (value, name)) | db9cd0f23c6283bbb5f9317acb584f62f54c8119 | 531,585 |
def coerce_enum(value, cls):
"""Attempt to coerce a given string or int value into an Enum instance."""
if isinstance(value, int):
value = cls(value)
elif isinstance(value, str):
value = cls[value]
return value | 4eaf7f7a2624d940002c2946cb36d8f92d968ed9 | 81,727 |
def FindClientNode(mothership):
"""Search the mothership for the client node."""
nodes = mothership.Nodes()
for n in nodes:
if n.IsAppNode():
return n
return None | e54ae3ce093d2b8547e505de3ee97b50cddcd3f5 | 508,933 |
import ast
def str2dict(d_s):
"""Convert string to dictionary
:d_s: Dictionary string
:returns: Evaluated dictionary
"""
return ast.literal_eval(d_s) | 959da3c3197b5f8338cc33a7d9998303c50dd424 | 30,260 |
def _julian_day(date):
"""
Calculate the Julian day from an input datetime.
Parameters
----------
date
A UTC datetime object.
Note
----
Algorithm implemented following equations from Chapter 3 (Algorithm 14):
Vallado, David 'Fundamentals of Astrodynamics and Applications', (2007)
Julian day epoch is: noon on January 1, 4713 BC (proleptic Julian)
noon on November 24, 4714 BC (proleptic Gregorian)
"""
year = date.year
month = date.month
day = date.day
hour = date.hour
minute = date.minute
second = date.second
# January/February correspond to months 13/14 respectively
# for the constants to work out properly
if month < 3:
month += 12
year -= 1
B = 2 - int(year/100) + int(int(year/100)/4)
C = ((second/60 + minute)/60 + hour)/24
JD = (int(365.25*(year + 4716)) + int(30.6001*(month+1)) +
day + B - 1524.5 + C)
return JD | b94c70e6c9bb9db8348c9f744c3b499e6e4e5be2 | 409,725 |
def scaleto255(value):
"""Scale the input value from 0-100 to 0-255."""
return max(0, min(255, ((value * 255.0) / 100.0))) | fdf0ba0717df4c85fc055c1b8bc2590a22c4bd09 | 688,538 |
def get_enum_of_value(enum, val):
"""
checks, if a value is in an enum, and if true, returns value
:param enum: enum to search in
:param val: key or value to search for
:return: boolean if found, enum_of_val
"""
if val in enum._value2member_map_:
return True, enum(val)
elif val in enum.__members__:
return True, val, enum[val]
else:
return False, None | aba96d12ad30d7fa377bf757e138c0a2c4dee148 | 430,746 |
import ast
def _mcpyrate_attr(dotted_name, *, force_import=False):
"""Create an AST that, when compiled and run, looks up an attribute of `mcpyrate`.
`dotted_name` is an `str`. Examples::
_mcpyrate_attr("dump") # -> mcpyrate.dump
_mcpyrate_attr("quotes.lookup_value") # -> mcpyrate.quotes.lookup_value
If `force_import` is `True`, use the builtin `__import__` function to
first import the `mcpyrate` module whose attribute will be accessed.
This is useful when the eventual use site might not import any `mcpyrate`
modules.
"""
if not isinstance(dotted_name, str):
raise TypeError(f"dotted_name name must be str; got {type(dotted_name)} with value {repr(dotted_name)}")
if dotted_name.find(".") != -1:
submodule_dotted_name, _ = dotted_name.rsplit(".", maxsplit=1)
else:
submodule_dotted_name = None
# Issue #21: `mcpyrate` might not be in scope at the use site. Fortunately,
# `__import__` is a builtin, so we are guaranteed to always have that available.
if not force_import:
mcpyrate_module = ast.Name(id="mcpyrate")
else:
globals_call = ast.Call(ast.Name(id="globals"),
[],
[])
if submodule_dotted_name:
modulename_to_import = f"mcpyrate.{submodule_dotted_name}"
else:
modulename_to_import = "mcpyrate"
import_call = ast.Call(ast.Name(id="__import__"),
[ast.Constant(value=modulename_to_import),
globals_call, # globals (used for determining context)
ast.Constant(value=None), # locals (unused)
ast.Tuple(elts=[]), # fromlist
ast.Constant(value=0)], # level
[])
# When compiled and run, the import call will evaluate to a reference
# to the top-level `mcpyrate` module.
mcpyrate_module = import_call
value = mcpyrate_module
for name in dotted_name.split("."):
value = ast.Attribute(value=value, attr=name)
return value | 16ab9893075caccf5808a1ce7926bc266394a979 | 74,687 |
def inventory_report(products):
"""
Takes a list of Acme products and prints a summary
Summary will incldue:
* Number of unique product names
* Average price
* Average weight
* Average flammability
"""
def most_common(lst):
"""
Returns most common item in a list
"""
return max(set(lst), key=lst.count)
count = float(len(products))
unique = len(set([prod.name for prod in products]))
avg_price = sum([prod.price for prod in products]) / count
avg_weight = sum([prod.weight for prod in products]) / count
avg_flammability = sum([prod.flammability for prod in products]) / count
print ('Number of Unique Product Names: %d' % unique)
print ('Most Popular Product: %s' %
most_common([prod.name for prod in products]))
print ('Average Price: %.2f' % avg_price)
print ('Average Weight: %.2f' % avg_weight)
print ('Average Flammability: %.2f' % avg_flammability) | 5a0668567ff28531e25d52238c9bd130293f5d7c | 167,759 |
def first_line(s):
"""Returns the first line of a multi-line string"""
return s.splitlines()[0] | 4c56d40e5f310a77ea3b193b740e578b0597fc00 | 548,857 |
import six
def str_to_intfloat(s):
"""Convert str to int or float.
Args:
s (:obj:`str`):
String to convert to float if it has a period or int if not.
Returns:
:obj:`int` or :obj:`float`
"""
if isinstance(s, six.string_types):
if "." in s and s.replace(".", "").isdigit():
return float(s)
if s.isdigit():
return int(s)
return s | 969506d86dd6454906ab208bb531ca8d5e0f7a52 | 351,525 |
def round_to_base (value, base=1):
"""
This method expects an integer or float value, and will round it to any
given integer base. For example:
1.5, 2 -> 2
3.5, 2 -> 4
4.5, 2 -> 4
11.5, 20 -> 20
23.5, 20 -> 20
34.5, 20 -> 40
The default base is '1'.
"""
return int(base * round(float(value) / base)) | c34bfb7e73624ce7f8652aed146218f0b6a86489 | 611,509 |
def divide_chunks(a_list, n):
"""Divide a list into chunks of size n.
:param a_list: an entry list.
:param n: size of each chunk.
:return: chunks in a list object.
"""
return [a_list[i:i + n] for i in range(0, len(a_list), n)] | a5ad354d4d7b2b974b4b3eace6b9c78edc1c4dfb | 619,523 |
def has_table(table_name, db_engine):
"""
Checks if a table with table_name is in the database
:param table_name: Name of the table that needs to be checked
:param db_engine: Specifies the connection to the database
:return: True if table with table_name is in the database, False otherwise
"""
if '.' in table_name: # received schema.table_name
return db_engine.has_table(table_name.split('.')[1], schema=table_name.split('.')[0])
else: # received plain table_name
return db_engine.has_table(table_name) | c42056e5a94cca5f088630beba6c3b89f8ff54d8 | 493,034 |
def dict_to_fun(dictionary):
"""
Wraps a function around a dictionary.
Parameters
----------
dictionary: a dict
Returns
-------
f: a function
f(a,b,c,...) == X if and only if dictionary[(a,b,c,...)] == X
"""
if callable(dictionary):
return dictionary
else:
return lambda *keys: dictionary[keys] | 6c4afe1d781f16a16820058330fe647ac91ad702 | 56,765 |
def merge_rows(list_1, list_2, key):
""" Merges two lists of dicts based on key in dicts
Args:
list_1(list[dict(),]): A list of dictionaries
list_2(list[dict(),]): A list of dictionaries
key(string): key using which lists would be merged
Returns:
List of dictionaries updated after merging two lists
"""
merged = dict()
for row in list_1 + list_2:
if row[key] in merged:
merged[row[key]].update(row)
else:
merged[row[key]] = row
return list(merged.values()) | 3cf813988a5b4bb0dc0cf933e56fe35e3e1f0c2f | 271,925 |
import itertools
def ndgrid_inds(sz):
"""
Return a sequnce of tuples of indices as if generated by nested comprehensions.
Example:
ndgrid_inds((ni,nj))
Returns the same sequence as
[(i,j) for i in range(ni) for j in range(nj)]
The iterates are always tuples so
ndgrid_inds(4)
returns
[(0,), (1,), (2,), (3,)]
"""
return itertools.product(*map(range, sz)) | c62cd2450ebb52bb4ed9ce359335dc367542bb33 | 90,904 |
import functools
import warnings
def deprecated(reason):
"""
This is a decorator which can be used to mark function as deprecated. It
will result in a warning being emitted when the function is used.
:param reason: a reason as a string
:return: decorated function
"""
def deprecated_decorator(func):
@functools.wraps(func)
def new_func(*args, **kwargs):
warnings.simplefilter("always", DeprecationWarning)
warnings.warn(
u"{0} is deprecated. {1}".format(func.__name__, reason),
category=DeprecationWarning,
stacklevel=2,
)
return func(*args, **kwargs)
return new_func
return deprecated_decorator | 1b1644fbfad94561bce78c47e8fc2f294f99335f | 581,977 |
def _fill_deque_by_initial_value(
deque_obj, initial_value, buffer_size):
"""
Fill the deque object with the initial value.
Parameters
----------
deque_obj : collections.deque
The deque object to add to.
initial_value : int or float
Initial value to be referenced.
buffer_size : int
Buffer size to handle in the plot.
Returns
-------
deque_obj : collections.deque
Deque object after adding data.
"""
if len(deque_obj) != 0:
return deque_obj
while len(deque_obj) < buffer_size:
deque_obj.append(initial_value)
return deque_obj | fef8fb44412fe0b56999ffa1d9e73c1848e58ee8 | 615,416 |
def to_iso_format(
date_time):
"""
Return a string representing the date and time in ISO 8601 format,
YYYY-MM-DD HH:MM:SS.mmmmmm or, if microsecond is 0, YYYY-MM-DD HH:MM:SS
If utcoffset() does not return None, a 6-character string is appended,
giving the UTC offset in (signed) hours and minutes:
YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM or, if microsecond is 0
YYYY-MM-DD HH:MM:SS+HH:MM
"""
return date_time.isoformat(sep=" ") | 41fcc983707874da2bac3407f5f3bfdb8e9807b8 | 690,287 |
from typing import List
from pathlib import Path
def get_filenames(mockname: str) -> List[str]:
"""
scans all headers in test/mocks/{mockname}, return corresponding file names
Args:
mockname: string, mock directory name
Returns:
List of file name for the headers in test/mock/{mocksname}
"""
dir = Path("test/mocks/{}/".format(mockname))
filenames = list(map(str, dir.glob('*.h')))
return filenames | 4c47b1a3364cac702bc2d3b86b2a027754dd19a5 | 383,791 |
import re
def get_certificate_and_private_key(pem_file_path): # noqa: D205,D400
"""Return a dictionary containing the certificate and private key extracted from the given pem
file.
"""
lines = open(pem_file_path, 'rt').read()
certificate = re.findall(
re.compile("(-*BEGIN CERTIFICATE-*\n(.*\n)*-*END CERTIFICATE-*\n)", re.MULTILINE),
lines)[0][0]
private_key = re.findall(
re.compile("(-*BEGIN PRIVATE KEY-*\n(.*\n)*-*END PRIVATE KEY-*\n)", re.MULTILINE),
lines)[0][0]
return {"certificate": certificate, "privateKey": private_key} | d9967f8405928aff2c579af0614987d395dd8b55 | 458,297 |
def C2F(C):
"""Convert Celcius to Fahrenheit"""
return 1.8 * C + 32 | e09f7415a2c509d8cb2d07d4c0d8e667f94e3c7d | 643,725 |
def expand_indent(line):
"""
Return the amount of indentation.
Tabs are expanded to the next multiple of 8.
>>> expand_indent(' ')
4
>>> expand_indent('\\t')
8
>>> expand_indent(' \\t')
8
>>> expand_indent(' \\t')
8
>>> expand_indent(' \\t')
16
"""
result = 0
for char in line:
if char == '\t':
result = result / 8 * 8 + 8
elif char == ' ':
result += 1
else:
break
return result | 79addc10c91b58d1f83e373971ee62b691c56c15 | 578,903 |
def list_daily_cases(list_of_cumulative_cases):
"""
Given a list of cumulative cases, this function makes and returns a list of
daily cases.
"""
daily_list = [0]
for i in range(1, len(list_of_cumulative_cases)):
N_daily_case = list_of_cumulative_cases[i] - list_of_cumulative_cases[i - 1]
daily_list.append(N_daily_case)
return daily_list | 287d01b2c7a2a8764289c1f5f2e65372fedc35b5 | 629,710 |
import collections
def DictFilter(alist, bits):
"""Translates bits from EDID into a list of strings.
Args:
alist: A list of tuples, with the first being a number and second a string.
bits: The bits from EDID that indicate whether each string is supported by
this EDID or not.
Returns:
A dict of strings and bools.
"""
d = collections.OrderedDict()
for x, s in alist:
d[s] = bool(bits & x)
return d | d314fdb4c1fd34ae9974f63d64495b8cafefbef5 | 46,630 |
import math
def KeplerSolve(M: float, e: float) -> float:
"""Solves Kepler's equation inverse problem for elliptical orbits.
Args:
M (float): mean anomaly
e (float): eccentricity
Returns:
float: eccentric anomaly
"""
if not 0 < e < 1:
raise ValueError("Eccentricity of elliptical orbit required in range (0, 1)")
# find E such that M = E - e*sin(E)
E = M
while not math.isclose(M, E - e * math.sin(E)):
E = E - (E - e * math.sin(E) - M) / (1 - e * math.cos(E))
# E = M + e * math.sin(E)
return E | 45dca9264039ce0db3da2a755ff1e933edc3250d | 526,748 |
def factorial(number):
"""
This method calculates the factorial of the number
"""
result = 1
for index in range(1,number+1):
result *= index
return result | a182f4fe68e76182bf17e5f9d7701e9004593ecb | 303,537 |
import json
def open_locale_file(fname):
"""Opens a locale file"""
with open(fname) as json_file:
return json.load(json_file) | 903414bddf5335d5a1d1b51e835d59cc5df0b06b | 641,121 |
def no_date_x_days_before_date_to_check(date_to_check, datelist, min_gap):
"""
Returns true if datelist contains a date less than or equal to min_gap days before date_to_check. Checked.
Ignores dates that are greater than or equal to date_to_check.
"""
for previous_date in datelist:
if previous_date >= date_to_check:
continue
if (date_to_check - previous_date).days <= min_gap:
return False
return True | 9abf0a2ffaa0ea9b9a098981f3eba521325cc7b2 | 532,176 |
def filter_on_cdr3_length(df, max_len):
"""
Only take sequences that have a CDR3 of at most `max_len` length.
"""
return df[df['amino_acid'].apply(len) <= max_len] | abe853dd0a5baeb3a178c41de9b15b04912e2033 | 35,494 |
def divup(x: int, y: int) -> int:
"""Divide x by y and round the result upwards."""
return (x + y - 1) // y | 5fa0ede218aa30bb58eadaedf32da0fd853664f7 | 689,473 |
import json
def convert_array_in_json(array):
"""
Converter
Return an array in a json
"""
# Return array in json
lists = array.tolist()
return json.dumps(lists) | cc4272f5b026010f3ba1ea2eaf0f277efe85be7b | 496,894 |
import sqlite3
def get_connection(DB_FILENAME):
"""
Opens the connection to the database file at DB_FILENAME.
Args:
DB_FILENAME (str): path to the database file
Returns:
CONNECTION (object):
"""
CONNECTION = sqlite3.connect(DB_FILENAME)
return CONNECTION | 900abca088500256ac93502975c065c8b08dc4da | 313,338 |
import re
def is_pep440_canonical_version(version):
"""
Determine if the string describes a valid PEP440 canonical version specifier.
This implementation comes directly from PEP440 itself.
:returns: True if the version string is valid; false otherwise.
"""
return re.match(
(
r'^([1-9][0-9]*!)?'
r'(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|rc)(0|[1-9][0-9]*))?'
r'(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?$'
),
version
) is not None | 29518b9a3289d7c1552d675d297e263d9e5255e6 | 394,385 |
def image_size(size):
"""
Determine the image size of the images to be displayed in GUI
The original width to height ratio will be preserved.
Max width/height is set to be 300, and the other dimension will be
adjusted accordingly.
Args:
size (list): Original image size
Returns:
new_size (list): New image size suitable for GUI
"""
l_max = max(size)
if l_max > 300:
num = l_max/300
else:
num = 1
w = round(size[0] / num)
h = round(size[1] / num)
new_size = [w, h]
return new_size | 37a20efbfdcf1dca52a3b5b49fedc8b019db0fe6 | 222,268 |
def is_iterable(obj):
"""
Test if an object is iterable.
:param obj: The object to test.
:return: True if the object is iterable, False otherwise.
"""
# noinspection PyBroadException
try:
_ = iter(obj)
return True
except:
return False | 9427fe56b8a354f12c9b0773a4ba434578265bae | 114,447 |
def file_lines(f):
"""Read lines from a file (f) into a list."""
try:
f = open(f)
except TypeError:
# probably already a file.
pass
with f:
lines = f.readlines()
lines = [line.strip() for line in lines]
return lines | f7077f0be665abb1d636c25ef58a68f05ffd0a16 | 328,526 |
def get_contents_lektor_file(filepath):
"""Returns contents of contents Lektor file as string"""
with open(filepath, "r") as file:
contents = file.readlines()
return "".join(contents) | f265525cccbbc602bdef1a89ff0bca558edccb10 | 596,551 |
def find_index(x, value):
"""
並不限定 x 的單調性與重複性,因為它僅僅是找這個元素的指標。
因此,可能有多個元素,也可能沒有元素。
:param x: [3,5,1,2,3,5,1,20,2,38]
:param value: 5
:return: [1, 5]
"""
temp = [] # 給接下來多個元素位址的暫存空間
for i in range(len(x)):
if x[i] == value:
temp.append(i)
return temp | 2effc0767075b21c21daf0ddaa0eaddc02a4b8b7 | 504,554 |
def t_iso(M):
""" Isolation disruption timescale (2-body evaporation)"""
return 17. * (M / 2E5) | 92c7978643e2c2c1f4b3f6b1a1f85f8912d35ced | 529,604 |
def precision_at_k(vanilla_topk, fair_topk):
"""
calculate precision @ K
:param vanilla_topk: top K nodes in vanilla mining result
:param fair_topk: top K nodes in debiased mining result
:return: precision @ K
"""
topk = set(fair_topk)
groundtruth = set(vanilla_topk)
return len(topk.intersection(groundtruth)) / len(topk) | 073abf75d0a66d492541d13c799b67c1b09662f8 | 10,478 |
def data_context_config_dict_with_datasources(data_context_config_with_datasources):
"""Wrapper fixture to transform `data_context_config_with_datasources` to a json dict"""
return data_context_config_with_datasources.to_json_dict() | 4c8166e5711d6d444b465758dc91e10e42ad45cb | 337,000 |
def valid1(s, c, low, high):
"""
Returns True or False depending on whether the number of occurences of the character `c`
in the string `s` is between the integers `low` and `high` inclusive
"""
return low <= s.count(c) <= high | 744f2486ea8fe1340f82f9e35994368f307235ba | 598,027 |
def update_pos(pos1,pos2):
"""
Get the coordinate of the bounding box containing two parts
:param pos1: Coordinate of the first part.
:param pos2: Coordinate of the second part.
:return: Coordinate of the bounding box containing the two parts
"""
x1 = min(pos1[0],pos2[0])
y1 = min(pos1[1],pos2[1])
x2 = max(pos1[2],pos2[2])
y2 = max(pos1[3],pos2[3])
return (x1,y1,x2,y2) | db671fb75640436852e96e86b3af96985e52e605 | 633,889 |
def get_terminal_subgraph(g):
"""
Return the subgraph induced by terminal nodes in g
:param g:
:return:
"""
terminals = {node for node, d in g.nodes(data=True) if 'nt' not in d}
return g.subgraph(terminals).copy() | dfef760209436efdea0b219dd6d452f153b8d5a7 | 579,177 |
def _contains_sample(pairs_list, sample):
"""Returns pairs_list that contains the sample"""
pairs_list_f = [x for x in pairs_list
if sample in [x[0][0], x[1][0]]]
return pairs_list_f | 5731e15326596a824f1e35f31244a35dde371dc5 | 551,586 |
import itertools
def knapsack_without_repetition(capacity, values, weights=None):
"""
Find the optimal set of items with values and weights, to fill a knapsack
to maximal capacity.
The knapsack has a capacity which limits our choice of items in such a way
that the sum of the items' weights can not exceed the knapsack capacity.
Parameters
----------
capacity : int
An integer specifying the total capacity of the knapsack.
values : iterable
An iterable containing the value of each of the items.
weights : iterable
An iteratble containing the weight of each of the items.
Returns
-------
ietrable : Indices of the items contained in the maximal value knapsack.
numeric : The value of the maximal value knapsack.
Algorithmic details
-------------------
Memory: O(W * n)
Time: O(W * n)
where W is the capacity of the knapsack and n is the number of items.
Examples
--------
>>> knapsack_without_repetition(5, [100, 100, 1], [10, 10, 1])
(1, [2])
>>> knapsack_without_repetition(20, [100, 100, 1], [10, 10, 1])
(200, [0, 1])
References
----------
[1] http://algorithmics.lsi.upc.edu/docs/Dasgupta-Papadimitriou-Vazirani
.pdf#page=171&zoom=auto,-255,792
[2] https://en.wikipedia.org/wiki/Knapsack_problem
"""
# If no weights are specified, we set weights equal to values
if not weights:
weights = values.copy()
# Make sure that the input is reasonable
if len(values) != len(weights):
msg = 'Size of values and weights iterables should be equal'
raise ValueError(msg)
# Create dp-table and list for retrieving the items chosen.
number_of_items = len(values)
table = [[0 for item in range(number_of_items + 1)]
for knapsack_weight in range(capacity + 1)]
previous = dict()
# Calculate maximal value knapsack
product = itertools.product(range(1, number_of_items + 1),
range(1, capacity + 1))
for item, knapsack_weight in product:
# Get value and weight of current item
item_value = values[item - 1]
item_weight = weights[item - 1]
# Set current knapsack equal to previous knapsack (not containing
# current item)
table[knapsack_weight][item] = table[knapsack_weight][item - 1]
previous[(knapsack_weight, item)] = (knapsack_weight, item - 1)
# Check if possible to add current item to the knapsack
if knapsack_weight - item_weight >= 0:
item_added = (table[knapsack_weight - item_weight][item - 1] +
item_value)
# If adding the current item to the knapsack will not increace the
# knapsack value, we continue without adding it
if item_added <= table[knapsack_weight][item]:
continue
# Add current item to knapsack
table[knapsack_weight][item] = item_added
previous[(knapsack_weight, item)] = (knapsack_weight -
item_weight, item - 1)
# Retrieve the content og the maximal value knapsack by backtracking
content = []
weight, item = capacity, number_of_items
while weight != 0 and item != 0:
previous_weight, previous_item = previous[(weight, item)]
# Add 'item - 1' to content if it was added in the dp-table.
if previous_weight < weight:
content.append(item - 1)
weight, item = previous_weight, previous_item
# Get maximal value
max_value = table[capacity][number_of_items]
return max_value, sorted(content) | b468386d8bd80c6c25f30dcec3f5feded3e38c7d | 422,664 |
def f10(x):
"""
Desc:
定义激活函数 f
Args:
x —— 输入向量
Returns:
(实现阶跃函数)大于 0 返回 1,否则返回 0
"""
if x>0:
return 1
else:
return 0 | 16843ba1940b5542a0d052938c8314bd28da51a9 | 444,639 |
def getint(string):
"""Try to parse an int (port number) from a string."""
try:
ret = int(string)
except ValueError:
ret = 0
return ret | 93ad70e59aa3d264b3215892cf3178d9ab3d8065 | 97,112 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.