content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def parse_degrees(coord):
"""Parse an encoded geocoordinate value into real degrees.
:param float coord: encoded geocoordinate value
:return: real degrees
:rtype: float
"""
degrees = int(coord)
minutes = coord - degrees
return degrees + minutes * 5 / 3
|
c2c37d8770da2d6c8241dfcc7b0c9c7d889e65e0
| 337,452 |
def reshape_nd(data_or_shape, ndim):
"""Return image array or shape with at least ndim dimensions.
Prepend 1s to image shape as necessary.
>>> reshape_nd(numpy.empty(0), 1).shape
(0,)
>>> reshape_nd(numpy.empty(1), 2).shape
(1, 1)
>>> reshape_nd(numpy.empty((2, 3)), 3).shape
(1, 2, 3)
>>> reshape_nd(numpy.empty((3, 4, 5)), 3).shape
(3, 4, 5)
>>> reshape_nd((2, 3), 3)
(1, 2, 3)
"""
is_shape = isinstance(data_or_shape, tuple)
shape = data_or_shape if is_shape else data_or_shape.shape
if len(shape) >= ndim:
return data_or_shape
shape = (1,) * (ndim - len(shape)) + shape
return shape if is_shape else data_or_shape.reshape(shape)
|
c71796635a6d97c746eae1554a3e3a123c19f4df
| 506,690 |
import json
def post_json(client, url, json_dict):
""" Send dict to url as json """
return client.post(
url,
data=json.dumps(json_dict),
content_type='application/json'
)
|
087de58fa306a1bf710b3e0be2f71144df2d8562
| 168,800 |
import requests
def send_get_request(seq_id: str) -> requests.Response:
"""send_get_request
Simple function to send get request for sequence metadata, having this as a function makes
testing of different responses easier
Args:
seq_id: (str) sequence id to retrieve metadata for
Returns:
(requests.Response): CRAM metadata endpoint response object
"""
return requests.get(
url=f"https://www.ebi.ac.uk/ena/cram/sequence/{seq_id}/metadata",
)
|
ae3df53c129a050ab699c6b8efd1f7b13cba4189
| 149,921 |
import requests
def get_page(url):
"""
Download a web page and returns it.
Args:
url (str): target webpage url
Returns:
html (str): page html code
"""
# request HTML page
response = requests.get(url)
html = response.text
return html
|
4360be62a4de5aac8b897b726980386ecb8f1112
| 394,937 |
from typing import List
def common_words(sentence1: List[str], sentence2: List[str]) -> List[str]:
"""
Input: Two sentences - each is a list of words in case insensitive ways.
Output: those common words appearing in both sentences. Capital and lowercase
words are treated as the same word.
If there are duplicate words in the results, just choose one word.
Returned words should be sorted by word's length.
"""
common = []
lower_sentence1 = [word.lower() for word in sentence1]
lower_sentence2 = [word.lower() for word in sentence2]
for word in lower_sentence1:
if word in lower_sentence2:
common.append(word)
return sorted(list(set(common)), key=len)
pass
|
0002b28f2b4722c7554487db737327e333fbde54
| 626,879 |
def Storeligandnames(csv_file):
"""It identifies the names of the ligands in the csv file
PARAMETERS
----------
csv_file : filename of the csv file with the ligands
RETURNS
-------
lig_list : list of ligand names (list of strings)
"""
Lig = open(csv_file,"rt")
lig_aux = []
for ligand in Lig:
lig_aux.append(ligand.replace(" ","_").replace("\n","").lower())
return lig_aux
|
dc4510a4ea946eaf00152cb445acdc7535ce0379
| 199 |
import math
def present_value_csv(key, val, values_with_ci):
""" Turns a value into a state where it can be presented in a CSV file,
including its confidence interval if the column it appears in has
confidence intervals somewhere in it.
"""
if key in values_with_ci:
ciDown, ciUp = val.ci()
if math.isnan(ciDown):
return '%f,%f,%f' % (val.value(), val.value(), val.value())
else:
return '%f,%f,%f' % (val.value(), ciDown, ciUp)
else:
return str(val)
|
ebfac0668ed9e10dcd71a6ce2a458854626e0e08
| 172,931 |
import logging
def restore_from_checkpoint(sess, saver, checkpoint_file_path):
"""
Restore session from checkpoint files.
Args:
sess: TensorFlow Session object.
saver: TensorFlow Saver object.
checkpoint_file_path: The checkpoint file path.
Return:
True if restore successfully and False if fail
"""
if checkpoint_file_path:
logging.info(
"Restore session from checkpoint: {}".format(checkpoint_file_path))
saver.restore(sess, checkpoint_file_path)
return True
else:
logging.error("Checkpoint not found: {}".format(checkpoint_file_path))
return False
|
a6a7b45b601ea8c6763b3c8fa24462f8eedd53b0
| 597,249 |
def is_leap (year):
"""
Checks whether a year is a leap-year or not.
IF the year is divisible by 4 it is a leap year,
unless it is divisible by 100, unless it is also divisible
by 400.
2000 = leap-year: divisible by 4, 100, and 400 - 400 makes it leap
1900 = non-leap : divisible by 4, 100, not 400
2004 = leap-year: divisible by 4, not 100 or 400
"""
leap = False
if year % 4 == 0 :
leap = True
if year % 100 == 0 and year % 400 != 0 :
leap = False
return leap
|
e157547b8d3575c7a97513efd69fc8e7a07b2675
| 436,750 |
def total_points(min_x, max_x, points_per_mz):
"""
Calculate the number of points for the regular grid based on the full width at half maximum.
:param min_x: the lowest m/z value
:param max_x: the highest m/z value
:param points_per_mz: number of points per fwhm
:return: total number of points
:rtype: int
"""
if min_x > max_x:
raise ValueError("min_x > max_x")
if min(min_x, max_x, points_per_mz) <= 0:
raise ValueError("all inputs must be greater than 0")
return int((max_x - min_x) * points_per_mz) + 1
|
e0680e386559a9603b3b23b9627bd8648b23e65a
| 702,052 |
def clean_name(value):
""" remove bad character from possible file name component """
deletechars = r"\/:*%?\"<>|'"
for letter in deletechars:
value = value.replace(letter, '')
return value
|
2d9678b4994b85d7b01c91dbf02c87759610e688
| 283,747 |
def escape_char(string):
"""
Escape special characters from string before passing to makefile.
Maybe more characters will need to be added.
"""
string = string.replace("'", "\\'") # escape '
string = string.replace('"', '\\"') # escape "
string = string.replace("\n", "\\n") # escape \n
return string
|
b6d97d082fab31ae7c8026be6d99948e0b1040ba
| 466,966 |
def get_missing_columns(data, columns, category_column):
"""
Returns all of the given columns that are not in the given dataframe.
Parameters
----------
columns : List[str]
the columns to look for
category_column : str
the category column to look for, or None if there is no category column
being used
Returns
-------
missing : List[str]
a list of the missing columns
"""
data_columns = set(data.columns)
if not category_column is None:
columns = columns + [category_column]
missing = []
for col in columns:
if not col in data_columns:
missing.append(col)
return missing
|
c6e7682aa4b9ed0078b6273938533df973cc668f
| 145,600 |
from random import randint
def random_pick(board, available_nodes):
"""
Offers a node at random.
"""
index = randint(0, len(available_nodes) - 1)
return index
|
746567fe4b66a9b111a24d6ce6823357c8dc290d
| 514,711 |
def bps_to_mbps(value):
"""Bits per second to Mbit/sec"""
return round(int(value) / (1000**2), 3)
|
156fb45a16f102235b40d9e026b9ae5f62dc6514
| 228,990 |
def moment(f, pmf, center=0, n=1):
"""
Return the nth moment of `f` about `center`, distributed by `pmf`.
Explicitly: \sum_i (f(i) - center)**n p(i)
Note, `pmf` is the joint distribution. So n=1 can be used even when
calculating covariances such as <xx> and <xy>. The first would actually
be a 2nd moment, while the second would be a mixed 1st moment.
Parameters
----------
f : array-like
The numerical values assigned to each outcome of `p`.
pmf : array-like
The pmf for a distribution, linear-distributed values.
center : float
Calculate a centered moment.
n : int
The moment to calculate.
"""
return ((f - center)**n * pmf).sum()
|
bfd5f3d149b232c99b4fc5cd0aa799a05a93a7ee
| 314,227 |
from typing import Sequence
def _get_needed_orders(rdt_maps: Sequence[dict], feed_down: int) -> Sequence[int]:
"""Returns the sorted orders needed for correction, based on the order
of the RDTs to correct plus the feed-down involved and the order of the
corrector, which can be higher than the RDTs in case one wants to correct
via feeddown."""
needed_orders = set()
for rdt_map in rdt_maps:
for rdt, correctors in rdt_map.items():
# get orders from RDTs + feed-down
for fd in range(feed_down+1):
needed_orders |= {rdt.order + fd, }
# get orders from correctors
for corrector in correctors:
needed_orders |= {int(corrector[1]), }
return sorted(needed_orders)
|
77775574d9085ef58f4924a4e99c3b89af049f04
| 445,560 |
def get_luid(my_fn,
frame_label,
lemma,
pos):
"""
Given a frame, lemma, and pos
try to retrieve the lu identifier.
:param my_fn: loaded framenet using NLTK's FrameNetCorpusReader
:param str frame_label: a frame label
:param str lemma: a lemma, e.g., election
:param str pos: a FrameNet part of speech tag, e.g., N (see validation_utils.POS for the full set)
:return: the lu identifier or None if not found
"""
lu_ids = set()
target = f'{lemma}.{pos.lower()}'
for lu_id, lemma_pos in my_fn.lu_ids_and_names().items():
if lemma_pos == target:
lu = my_fn.lu(lu_id)
frame = lu.frame
if frame.name == frame_label:
lu_ids.add(lu_id)
if len(lu_ids) >= 2:
target_lu_id = None
reason = f'{lemma}.{pos.lower()} found in multiple frames (lu ids are {lu_ids}'
elif len(lu_ids) == 1:
target_lu_id = list(lu_ids)[0]
reason = 'succes'
else:
target_lu_id = None
reason = f'no lu id found matching {lemma}.{pos.lower()}'
return target_lu_id, reason
|
d0c493e53bba887a39449451415019458d6621b9
| 351,527 |
def get_label_yml(label):
"""Get yml format for label
Args:
label (dict): dictionnary if labels with keys color, name and description
as strings, possibly empty
Returns:
str: yml formatted dict, as a yml list item
"""
text = f' - name: "{label["name"]}"\n'
text += f' color: "{label["color"]}"\n'
text += f' description: "{label["description"]}"\n'
return text
|
be4564dd1865191d02f6d4d5fc929ae1ba21618f
| 302,703 |
from typing import List
def diagonal_difference(size: int, matrix: List[List[int]]) -> int:
"""
>>> diagonal_difference(3, [[11, 2, 4], [4, 5, 6], [10, 8, -12]])
15
"""
# prim_diag = sec_diag = 0
# for i in range(size):
# prim_diag += matrix[i][i]
# sec_diag += matrix[-i-1][i] # matrix[i][(size-1)-i]
indexes = enumerate(range(size-1, -1, -1))
diagonals = zip(*((matrix[i][i], matrix[i][s]) for i, s in indexes))
prim_diag, sec_diag = map(sum, diagonals)
ret = abs(prim_diag - sec_diag) # type: ignore
return ret
|
1987c8396402d91398c9f8d4424a11583255ed32
| 162,626 |
def find_by_uuid(_list: list, uuid: str):
"""
Finds a user in a leaderboard by their uuid
:param (list) _list: The leaderboard list
:param (str) uuid: Player's UUID
:returns (int) i: Placing of a user in the leaderboard
"""
for i, dic in enumerate(_list):
if dic['uuid'] == uuid:
return i
return -1
|
54b5bca4e67e0fc1c2af34f1f8060f582f7c3e08
| 366,095 |
import torch
def encode_batch(batch, tokenizer, max_seq_length, return_tokens=False):
"""
Tokenize and encode the given input; stack it in a batch with fixed length
according to the longest sequence in the batch.
Return a tuple. If asked to return tokens, return the encoded batch and a nested
list of the tokenized texts. Otherwise, just return the batch.
"""
# Truncate input based on the sequence length
# before stacking as a batch
# Also return a boolean array indicating which tokens are masked
encoded_texts = []
for text in batch:
encoded_text = torch.tensor(tokenizer.encode(text))[:max_seq_length]
encoded_texts.append(encoded_text)
encoded_batch = torch.nn.utils.rnn.pad_sequence(encoded_texts, batch_first=True)
if return_tokens:
tokens = [tokenizer.tokenize(text) for text in batch]
return encoded_batch, tokens
else:
return (encoded_batch,)
|
20397b9ac8013646a7bca3da2fff7dfa569113f6
| 259,168 |
import csv
def file_to_position_depths(file_path):
"""Get the position and depths from one file. Read into memory as a dictionary with (lat, lon) as the key and depth
as the value."""
# create the dictionary
result = {}
# read the position and depth data from the input csv file
with open(file_path) as csvfile:
contents = csv.reader(csvfile)
next(contents)
count = 1
# print progress
for line in contents:
if count % 100_000 == 0:
print(count)
count += 1
# get the latitude, longitude and depth from the row in the file
_, lat, long, depth = line
lat_long = (float(lat), float(long))
# if the depth is empty, then continue
if depth == '':
continue
result[lat_long] = float(depth)
return result
|
461b9eac168795e4259f38800caa9c29fe620dec
| 688,518 |
import torch
def get_loss_and_grads(model, train_x, train_y, flat=True, weights=None, item_loss=True,
create_graph=False, retain_graph=False):
"""Computes loss and gradients
Apply model to data (train_x, train_y), compute the loss
and obtain the gradients.
Parameters
----------
model : nn.Module
Neural network. We assume the model has a criterion attribute
train_x : torch.Tensor
Training inputs
train_y : torch.Tensor
Training targets
Returns
----------
loss
torch.Tensor of size (#params in model) containing the loss value
if flat=True, else a single float
gradients
torch.Tensor of size (#params in model) containing gradients w.r.t.
all model parameters if flat=True, else a structured list
"""
model.zero_grad()
if weights is None:
weights = model.parameters()
out = model(train_x)
else:
out = model.forward_weights(train_x, weights)
loss = model.criterion(out, train_y)
grads = torch.autograd.grad(loss, weights, create_graph=create_graph,
retain_graph=retain_graph)
if flat:
gradients = torch.cat([p.reshape(-1) for p in grads])
loss = torch.zeros(gradients.size()).to(train_x.device) + loss.item()
else:
gradients = list(grads)
if item_loss:
loss = loss.item()
return loss, gradients
|
7abb2a9758ac641c5303583e2609407e84d8f91f
| 136,928 |
def partition_nodes(ilist,bitpos):
"""return a tuple of lists of nodes whose next bit is zero, one or
a letter (others)"""
zeros = []
ones = []
others = []
zero = '0'
one= '1'
for inst in ilist:
bit = inst.ipattern.bits[bitpos]
if bit.value == zero:
zeros.append(inst)
elif bit.value == one:
ones.append(inst)
else:
others.append(inst)
return (ones,zeros,others)
|
2f8ce1a85d18497512dac4708291d8c94fac7b87
| 125,799 |
def copyfragment(fragment0,newobj):
"""Copy the data in a fragment to another object.
The data in the source fragment 'fragment0' is copied to the
target object 'newobj', and 'newobj' is returned. 'newobj'
should be a fragment object or some subclass of fragment (such
as a 'program' object).
copyfragment can be used to 'mutate' a fragment into (for
example) a program object."""
# Copy attribute data
for item in fragment0.attributes():
newobj[item] = fragment0.get_attribute(item)
# Copy tables
for tbl in fragment0.tables():
newobj.addtable(tbl)
# Copy keytexts
for i in range(0,fragment0.nkeytexts()):
keytext = fragment0.keytext(i)
newobj.addkeytext(keytext.name(),
keytext.junk_text(),
keytext.message())
# Try to copy other attributes that fragment subclasses
# have (such as keywords)
try:
for line in fragment0.keywords():
newobj.addkeyword(line)
except AttributeError:
# Either the source or target doesn't support
# keyword storage
pass
# Return the populated object
return newobj
|
3d1cf53584052af2aefd283137909e6e3b5b8c35
| 52,944 |
def model_to_dict(model, exclude=None):
"""
Extract a SQLAlchemy model instance to a dictionary
:param model: the model to be extracted
:param exclude: Any keys to be excluded
:return: New dictionary consisting of property-values
"""
exclude = exclude or []
exclude.append('_sa_instance_state')
return {k: v for k, v in model.__dict__.items() if k not in exclude}
|
9500f5deb7be839196586ec27b4c785be9c9dcc2
| 189,348 |
def factorial(integer: int) -> int:
"""Return the factorial of a given integer.
Args:
integer (int): the integer whose factorial is going to be calculated
Returns:
int: the factorial of the provided integer
"""
if integer in {0, 1}:
return 1
return integer * factorial(integer - 1)
|
4d6457f5c3651d21ba6d831956e26e7522de553a
| 588,679 |
def add_team_position_column(df):
"""Add 'team_position' column to DataFrame."""
tp_pat = r'\w{2,3}\s-\s[A-Z,]+'
tp_sr = df['player'].str.findall(tp_pat)
tp_lst = [tp[0] for tp in tp_sr]
df.insert(1, 'team_position', tp_lst)
return df
|
0517f2f6b49fe26d4794406bd4d7145af2b62998
| 351,382 |
from typing import List
from typing import Dict
def find_values(item, keys: List[str]) -> Dict:
"""Find values for keys in item, if present.
Parameters
----------
item : Any
Any item
keys : List[str]
Keys whose value to retrieve in item
Returns
-------
Dict
Mapping of key -> value for keys found in item.
Raises
------
ValueError
If one key is found whose value is a tuple, list or dict.
"""
if isinstance(item, (list, tuple)):
values = {}
for it in item:
values.update(find_values(it, keys))
return values
elif isinstance(item, dict):
values = dict()
for key, value in item.items():
if key in keys:
if isinstance(value, (list, tuple, dict)):
raise ValueError(f"Cannot find value for '{key}'. Type must be literal but got {type(value)}")
values[key] = value
else:
values.update(find_values(value, keys))
return values
else:
return {}
|
bab4c8a9695113390654e4eaf971559a98f4eb71
| 695,223 |
def bytes_to_bits(num_bytes: int) -> int:
"""
Converts number of bytes to bits.
:param num_bytes: The n number of bytes to convert.
:returns: Number of bits.
"""
return num_bytes * 8
|
fab0ab0edee6565a6d76803239ffcff8931c5ffd
| 518,628 |
import requests
def is_darksky_quota_error(err):
"""Return Tre if input 'err' is a DarkSky quota error, else False"""
tf = False
if isinstance(err, requests.exceptions.HTTPError):
resp = err.response
if resp.status_code == 403 and 'darksky' in resp.url:
tf = True
return tf
|
5c6689580370b765d6fdfac884691dccac6768ac
| 641,486 |
def _extract_options(line_part):
"""Return k/v options found in the part of the line
The part of the line looks like k=v,k=v,k=2 ."""
result = {}
pairs = line_part.split(",")
for pair in pairs:
if "=" not in pair:
continue
parts = pair.split("=")
key = parts[0].strip()
value = parts[1].strip()
result[key] = value
return result
|
39089175a9f62655e7b60682792b0c7fa99a9f7d
| 232,953 |
def fill_with(array, mask, fill):
"""fill an array where mask is true with fill value"""
filled = array.copy()
filled[mask] = fill
return filled
|
c7090511bc6dde523b3a88e9d97ec2b97235116e
| 250,037 |
def remove_packaging(symbol: str):
"""Remove package names from lisp such as common-lisp-user::
Args:
symbol (str): string to have package name striped
Returns:
str: symbol input with package name removed (if present)
"""
split_symbol = symbol.split('::')
return symbol if len(split_symbol) == 1 else split_symbol[1]
|
c1cc0b050d62cd5a5782360223ea426850620277
| 133,985 |
import inspect
def get_custom_class_mapping(modules):
"""Find the custom classes in the given modules and return a mapping with class name as key and class as value"""
custom_class_mapping = {}
for module in modules:
for obj_name in dir(module):
if not obj_name.endswith("Custom"):
continue
obj = getattr(module, obj_name)
if inspect.isclass(obj):
custom_class_mapping[obj_name] = obj
return custom_class_mapping
|
c9682ee84c64019a17c5b4b1f3e12cba71e1463e
| 654,356 |
def get_text(value):
"""Get text from langstring object."""
return value["langstring"]["#text"]
|
1efaa8e2d5d06cb622227e75955cf2411c5079eb
| 504,936 |
def ffmt(number: float) -> int|float:
"""
convert float to int when there are no decimal places.
:param number float: The float
:rtype int|float: The return number.
"""
if int(number) == number:
return int(number)
return number
|
68b9507d847047182b71a24c05efd00513623e47
| 541,960 |
from typing import Sequence
from typing import Any
def _get_cont_out_labels(network_structure: Sequence[Sequence]) -> Any:
"""
Compute the contracted and free labels of `network_structure`.
Contracted labels are labels appearing more than once,
free labels are labels appearing exactly once.
Computed lists are ordered according to int and ASCII ordering
for integer and string values, with first entries in each list
being ordered integer labels followed by ASCII ordered string
labels.
Returns:
cont_labels, out_labels: The contracted and free labels
of `network_structure`.
"""
flat_labels = [l for sublist in network_structure for l in sublist]
out_labels = [l for l in flat_labels if flat_labels.count(l) == 1]
int_out_labels = sorted([o for o in out_labels if not isinstance(o, str)
])[::-1]
# pylint: disable=unnecessary-lambda
str_out_labels = sorted([o for o in out_labels if isinstance(o, str)],
key=lambda x: str(x))
cont_labels = []
for l in flat_labels:
if (flat_labels.count(l) > 1) and (l not in cont_labels):
cont_labels.append(l)
int_cont_labels = sorted([o for o in cont_labels if not isinstance(o, str)])
# pylint: disable=unnecessary-lambda
str_cont_labels = sorted([o for o in cont_labels if isinstance(o, str)],
key=lambda x: str(x))
return int_cont_labels, str_cont_labels, int_out_labels, str_out_labels
|
f749b67789a00fe1cf0b2491a0a476d3882de9be
| 698,114 |
from pathlib import Path
import binascii
def calculate_file_crc32(filename, block_size=1024 * 16):
"""
Calculate the crc32 of the contents of a given file path.
:type filename: str or Path
:param block_size: Number of bytes to read at a time. (for performance: doesn't affect result)
:return: String of hex characters.
:rtype: str
"""
m = 0
with Path(filename).open("rb") as f:
while True:
d = f.read(block_size)
if not d:
break
m = binascii.crc32(d, m)
return f"{m & 0xFFFFFFFF:08x}"
|
c9120fe8e7ce3bf50e7fcb289d78e6615045bb06
| 439,901 |
from bs4 import BeautifulSoup
import requests
def url_to_soup(url: str) -> BeautifulSoup:
"""URLからBeautifulSoupのオブジェクトを作る
Args:
url(str): 変換したいURL
Returns:
:obj:`bs4.BeautifulSoup` : BeautifulSoupのオブジェクト
"""
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
return soup
|
7c5b8a542086758cd1318a34e56e708e926e96a7
| 326,800 |
def format_gerald_header(flowcell_info):
"""
Generate comment describing the contents of the flowcell
"""
# I'm using '\n# ' to join the lines together, that doesn't include the
# first element so i needed to put the # in manually
config = ['# FLOWCELL: %s' % (flowcell_info['flowcell_id'])]
config += ['']
config += ['CONTROL-LANE: %s' % (flowcell_info['control_lane'],)]
config += ['']
config += ['Flowcell Notes:']
config.extend(flowcell_info['notes'].split('\r\n'))
config += ['']
for lane_number in sorted(flowcell_info['lane_set']):
lane_contents = flowcell_info['lane_set'][lane_number]
for lane_info in lane_contents:
config += ['Lane%s: %s | %s' % (lane_number,
lane_info['library_id'],
lane_info['library_name'])]
config += ['']
return "\n# ".join(config)
|
0035925bd70cb15d724785b0350beabe54f04073
| 462,131 |
from typing import Union
from typing import List
from typing import Any
import math
def rewrite_inf_nan(
data: Union[float, int, List[Any]]
) -> Union[str, int, float, List[Any]]:
"""Replaces NaN and Infinity with string representations"""
if isinstance(data, float):
if math.isnan(data):
return 'NaN'
if math.isinf(data):
return ('+' if data > 0 else '-') + 'inf'
return data
elif isinstance(data, list):
return [rewrite_inf_nan(item) for item in data]
else:
return data
|
14d202feb1098fefd9bcb215d9e19355bd236750
| 208,917 |
def _get_subsection_of_block(usage_key, block_structure):
"""
Finds subsection of a block by recursively iterating over its parents
:param usage_key: key of the block
:param block_structure: block structure
:return: sequential block
"""
parents = block_structure.get_parents(usage_key)
if parents:
for parent_block in parents:
if parent_block.block_type == 'sequential':
return parent_block
else:
return _get_subsection_of_block(parent_block, block_structure)
|
4a0e6d614ec9e5827d15203e9d0e9ff25824a351
| 335,009 |
def sortPkgObj(pkg1 ,pkg2):
"""sorts a list of yum package objects by name"""
if pkg1.name > pkg2.name:
return 1
elif pkg1.name == pkg2.name:
return 0
else:
return -1
|
5d6004588a076eb599d815ff0da2df9afc44e7ed
| 414,651 |
import math
def distance(point_one, point_two):
"""Calculates the Euclidean distance from point_one to point_two
"""
return math.sqrt((point_two[0] - point_one[0]) ** 2 + (point_two[1] - point_one[1]) ** 2)
|
92fe5b28046f6eb96fa6552e750ca62010d700da
| 685,918 |
def positive_sum(arr):
"""Return the sum of positive integers in a list of numbers."""
if arr:
return sum([a for a in arr if a > 0])
return 0
|
30467034bdf7548f24e0f519f70b8d2a6cdedcf5
| 60,596 |
def fetch_remote_data(db, data_length, uuids):
""" Fetch VM data from the central DB.
:param db: The database object.
:type db: Database
:param data_length: The length of data to fetch.
:type data_length: int
:param uuids: A list of VM UUIDs to fetch data for.
:type uuids: list(str)
:return: A dictionary of VM UUIDs and the corresponding data.
:rtype: dict(str : list(int))
"""
result = dict()
for uuid in uuids:
result[uuid] = db.select_cpu_mhz_for_vm(uuid, data_length)
return result
|
17933bd99b409fd7787f63858c077abd4daf1202
| 155,417 |
def modpow(k, n, m):
""" Calculate "k^n" modular "m" efficiently.
Even with python2 this is 100's of times faster than "(k**n) % m",
particularly for large "n".
Note however that python's built-in pow() also supports an optional 3rd
modular argument and is faster than this.
"""
ans = 1
while n:
if n & 1:
ans = (ans*k) % m
k = (k*k) % m
n >>= 1
return ans
|
bbe8de33ea07053956b15288f780491c8d24eea2
| 373,862 |
from typing import List
def write_floats_10e(vals: List[float]) -> List[str]:
"""writes a series of Nastran formatted 10.3 floats"""
vals2 = []
for v in vals:
v2 = '%10.3E' % v
if v2 in (' 0.000E+00', '-0.000E+00'):
v2 = ' 0.0'
vals2.append(v2)
return vals2
|
7e2f9b1a9e4560d3d9194c18601d22a57ed0811e
| 30,782 |
def get_player_id(first_name, last_name, team):
"""
Returns a custom player ID of first initial + last name + team
i.e. for Tom Brady in New England that is T.Brady-NE
"""
if (team == None):
team = 'None'
return first_name[0] + "." + last_name + "-" + team
|
d44e1275b722e06d63166a750c88a7863246d9ab
| 132,190 |
def read_metadata(metadata_file_fp):
"""Read metadata into dictionary.
"""
metadata = {}
with open(metadata_file_fp) as metadata_file_f:
for line in metadata_file_f:
line = line.strip().split('\t')
sample_id = line[0]
if sample_id not in metadata:
metadata[sample_id] = line[1:]
else:
raise ValueError("Duplicate samples: %s" % sample_id)
return metadata
|
e1c4f4e2101cf6fca960158b63d10950c469f751
| 512,536 |
def get_milliseconds(time_sec: float) -> int:
"""
Convertit un temps en secondes sous forme de float en millisecondes
sous forme d'un int.
Args:
time_sec: Le temps en secondes.
Returns:
Le temps en millisecondes.
"""
assert isinstance(time_sec, float)
return int(round(time_sec * 1000))
|
4a3c15f926b9faf5934ece8069cdd4651d2efd9c
| 277,704 |
def extract_individual_data(data):
"""
Separate data into different array for each individual
"""
ids = set(data[:,1])
id_A = min(ids)
id_B = max(ids)
dataA = data[data[:,1] == id_A, :]
dataB = data[data[:,1] == id_B, :]
# print(np.shape(dataA))
return dataA, dataB
|
dd04100bfd5e375736a1219e248741ddd9efeaad
| 168,730 |
def reorder_exons(exon_ids):
"""
Reorder exons if they were out of order.
Parameters:
exon_ids (list of str): List of exons 'chrom_coord1_coord2_strand_exon'
Returns:
exons (list of str): List of same exon IDs ordered based on strand
and genomic location
"""
strand = exon_ids[0].split('_')[-2]
coords = [int(i.split('_')[-4]) for i in exon_ids]
exons = sorted(zip(exon_ids, coords), key=lambda x: x[1])
exons = [i[0] for i in exons]
if strand == '-':
exons.reverse()
return exons
|
d3f52a24d4da1a05a1deceaf38927622c141a9ad
| 27,161 |
import importlib
def get_module_element_from_path(opath):
""" Retrieve an element from a python module using its path <package>.<module>.<object>.
This can be for example a global function or a class.
Args:
opath: Object path
Returns:
Module object
"""
module, oname = opath.rsplit('.', 1)
mod = importlib.import_module(module)
return getattr(mod, oname)
|
fa4d11fee4be5eac12ada83e4820b014591a00cc
| 316,618 |
def texture_profile(df_soils):
"""
Assign mean texture profile for soil categories.
- Cl: clay
- SiCl: silty clay
- SaCl: sandy clay
- ClLo: clay loam
- SiClLo: silty clay loam
- SaClLo: sandy clay loam
- Lo: loam
- SiLo: silty loam
- SaLo: sandy loam
- Si: silt
- LoSa: loamy sand
- Sa: sand
Parameters
----------
df_soils : pd.DataFrame
Returns
-------
df_texture : pd.DataFrame
"""
df_texture = df_soils.groupby(['texture', 'depth_category']).mean()
df_texture = df_texture[['sand', 'silt', 'clay',
'OM', 'dbthirdbar', 'th33', 'th1500']]
df_texture.OM = df_texture['OM']/100
df_texture.th33 = df_texture['th33']/100
df_texture.th1500 = df_texture['th1500']/100
return df_texture
|
a9fe7f8e59e4334df654d6e6d3dbcbfc56cee7aa
| 273,477 |
import random
def randomize_strata(n_items, group_ids, seed=None):
"""Perform stratified randomization.
Maps a number of items into group ids by dividing the items into strata of
length equal to the number of groups, then assigning the group ids randomly
within each strata. If the number of items do not divide the number of groups
equally, the remaining items are assigned to groups randomly (with equal
probability of assignment in each group).
Example: randomize_strata(12, [1, 2, 3]) yields a list of 12 group ids, each
1, 2, or 3. There are (3!)^4 = 6^4 = 1296 possible outcomes as there are 12 /
3 = 4 strata, and within each strata there are 3! = 6 different ways to assign
the items into groups. Therefore, the first 3 items of the list (that is,
positions 0, 1, and 2) can be mapped only to the 3!=6 different mappings:
[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] or [3, 2, 1].
Args:
n_items: (int) Number of items to assign to groups.
group_ids: A list of group ids that are typically integers or strings, but
can be of any type.
seed: (int) Random seed, applied to a local instance of class random.Random;
if not specified, the global random instance is used instead.
Returns:
A list of length n_items, consisting of the group ids whose positions in the
list correspond to the items.
"""
if seed is None:
random_sampler = random.sample
else:
random_sampler = random.Random(seed).sample
n_groups = len(group_ids)
n_strata = n_items // n_groups
groups = []
for _ in range(n_strata):
groups.extend(random_sampler(group_ids, n_groups))
remaining = n_items - len(groups)
if remaining > 0:
groups.extend(random_sampler(group_ids, remaining))
return groups
|
0f830a9171837f3022ea131036ef8f498fdaffba
| 454,386 |
def strike_through(text: str) -> str:
"""Returns a strike-through version of the input text"""
result = ''
for c in text:
result = result + c + '\u0336'
return result
|
a178dd99d124f537bc98bcf36cdc0690862fb0bd
| 663,271 |
import math
def get_simple_distance(coords1, coords2):
"""
Calculates the simple distance between two x,y points
:param coords1: (Tuple) of x and y coordinates
:param coords2: (Tuple) of x and y coordinates
:return: (float) The distance between the two points
"""
return math.sqrt((coords1[0]-coords2[0])**2 + (coords1[1]-coords2[1])**2)
|
504ccd5d5d30bf1cebba2bc23644136767ccd46c
| 399,336 |
def load_smarts_fdef(fname):
""" Load custom feature definitions from a txt file. The file must contain a
SMARTS string follwed by the feature name. Example:
# Aromatic
a1aaaaa1 Aromatic
a1aaaa1 Aromatic
Lines started with # are considered as comments
Parameters
----------
fname: str
Name of the file containing the smarts feature definitions
Returns
-------
features: dict
Dictionary which keys are SMARTS strings and values are feature names
"""
features = {}
# Load custom features file
with open(fname, "r") as file:
for line in file:
if line[0] == "#" or line[0] == '\n':
continue
line = line.split(' ')
feat_def = line[0]
feat_name = line[1].rstrip()
features[feat_def] = feat_name
return features
|
c629b4ebde56c906e80a1599ea58e13c99578ae6
| 339,900 |
def get_eps(dist, x):
"""Z = (X - mu) / sigma."""
return (x - dist.loc) / dist.scale
|
882208f782e7c30075d40c79cec6ea62310fa0fe
| 329,311 |
def capture_group(s):
"""
Places parentheses around s to form a capure group (a tagged piece of
a regular expression), unless it is already a capture group.
"""
return s if (s.startswith('(') and s.endswith(')')) else ('(%s)' % s)
|
17da31a3403522fe0f852ca64684c1b5ea8d315c
| 490,693 |
def index_select_multidim_nojit(input, indices):
"""
Like torch.index_select, but on multiple dimensions,
on first dimensions only (0, 1, ...)
NB: Clamp indices if out of range
@param input tensor of size (n_1, .., n_k, ...u)
@param indices tensor of integers of size (...v, k)
@return tensor of size (...v, ...u)
"""
n = indices.size()[-1]
input_size = input.size()
tpl = tuple(
indices[...,i].clamp(0, s-1)
for i, s in enumerate(input_size[:n])
)
return input[(*tpl, ...)]
|
7d778d31ac87aafc326bb2930e6d8db5873c91a7
| 232,964 |
def lcs_recursive(s1, s2):
"""
Given two strings s1 and s2, find their longest common subsequence (lcs).
Basic idea of algorithm is to split on whether the first characters of
the two strings match, and use recursion.
Time complexity:
If n1 = len(s1) and n2 = len(s2), the runtime is O(2^(n1+n2)).
The depth of the recursion is at most n1+n2, by alternately
removing the first letter of s1, then s2, then s1, and so on.
One function call makes at most two subsequent recursive calls,
so the total number of calls is at most 2^(recursion depth),
or 2^(n1+n2).
This bound is also the time complexity of the brute force approach
of enumerating all 2^n1 subsequences of s1 and all 2^n2 subsequences
of s2, and comparing all (2^n1)*(2^n2) pairs.
Space complexity:
As noted above, the recursion depth is at most n1+n2, which is
achieved in the worst case of an empty lcs, so the space complexity
is Omega(n1+n2).
"""
if len(s1)==0 or len(s2) == 0:
return ""
if s1[0] == s2[0]:
#If 1st character is the same, it is part of the
#longest common subsequence.
return s1[0] + lcs_recursive(s1[1:],s2[1:])
#If 1st characters are different, need to consider two cases
seq1 = lcs_recursive(s1, s2[1:])
seq2 = lcs_recursive(s1[1:], s2)
#Return whichever sequence is longer
return seq1 if len(seq1) > len(seq2) else seq2
|
45ce789716d4f6194b89efa1745ee7587c17179b
| 204,772 |
def word_capital(text):
"""
Capitalizes the first character of each word, it converts a string into
titlecase by making words start with an uppercase character and keep the
remaining characters.
"""
if text and len(text) > 0:
return ' '.join([s[0].upper() + s[1:] for s in text.split(' ') if len(s) > 0])
else:
return text
|
fbb20324204f62344af5b76f74fad98810f6fee0
| 19,346 |
def add_log_parser_arguments(parser):
"""Add log arguments to command line parser.
Defines the following command line arguments:
--log: path to log file (if any)
-v: verbosity level. More => more verbose log messages.
Args:
parser (argparse.ArgumentParser): parser to add arguments to.
Returns:
parser (argparse.ArgumentParser): parser with log arguments added.
"""
parser.add_argument(
'--log',
nargs='?',
default=None,
help='Path to log file.'
)
parser.add_argument(
'-v',
action='count',
default=0,
help='Verbosity of log messages.'
)
return parser
|
5b083364262f836247fda4a8e89e4dfc5f3a2335
| 478,631 |
def format_variant(variant):
"""
Return None for null variant and strips trailing whitespaces.
Parameters
----------
variant : str, optional.
HGVS_ formatted string.
Returns
-------
str
"""
if variant is None:
return variant
return variant.strip()
|
f88050c62c8efd1798f1ea909f366e38544ae7b6
| 451,845 |
def get_all_image_class_ids(self):
""" Retrieves class ids for every image as a list (used as inputs for BalancedBatchSampler)"""
return [image_info['class_id'] for image_info in self.image_infos.values()]
|
26bbe7f6b9e8474ce16e499300ae7fccb66600e1
| 134,036 |
def HasRootMotionBone(obj, rootBoneName):
"""
Returns True if the root bone is named @rootBoneName
@obj (bpy.types.Object). Object.type is assumed to be 'ARMATURE'
@rootBoneName (string). Name of the root motion bone to compare with
"""
bones = obj.data.bones
for bone in bones:
#print(bone.name, len(bone.children), bone.parent)
if (bone.parent is None) and (bone.name==rootBoneName):
return True
return False
|
d58a61fb7902d5f6e7303de099db7e665d5d2508
| 92,184 |
def check_template_sample(template_object, sample_set):
"""
check_template_sample checks if a template has a sample associated in the samples/ folder
Args:
template_object: the template dict to check, which got parsed from the file content
sample_set: set of sample kinds (string) built by build_sample_set
Raises:
yaml.YAMLError if the input template or any sample file is not a valid YAML file
Returns:
Boolean - True if a sample was found for this template, False otherwise.
"""
# retrieve the template kind
template_kind = template_object["spec"]["crd"]["spec"]["names"]["kind"]
sample_found = template_kind in sample_set
# if not, error out
if not sample_found:
print("No sample found for template {}".format(template_kind))
return sample_found
|
547a9240b06b943a578e773b020b8701fb75278e
| 181,774 |
def read_dict(filename, div='='):
"""Read file into dict.
A file containing:
foo = bar
baz = bog
results in a dict
{
'foo': 'bar',
'baz': 'bog'
}
Arguments:
filename (str): path to file
div (str): deviders between dict keys and values
Returns:
(dict) generated dictionary
"""
d = {}
with open(filename, 'r') as f:
for line in f:
key, val = line.split(div)
d[key.strip()] = val.strip()
return d
|
26bc9ec287d8e338cd7a5fef3a9f0de49ebf6138
| 673,856 |
import re
def chuvaSateliteONS(nomeArquivo):
"""
Lê arquivos texto com chuvas verificadas por satélite. Estes arquivos são disponibilizados
pelo ONS.
Argumento
---------
nomeArquivo : caminho completo para o arquivo de chuvas verificada por satélite.
Retorno
-------
Listas simples com longitudes, latitudes e chuvas. Estas listas precisam ser
tratada caso se deseje utilizar modelos de mapa tipo 'contornos'. Recomenda-se utilizar o tipo
de mapa 'xy' para este tipo de dado.
"""
# Listas para acomodares os dados a serem lidos do arquivo txt do ONS.
chuva = []
lons = []
lats = []
try:
with open(nomeArquivo, 'r') as f:
for line in f:
#nomePosto = line[0:10] # Uso futuro
valores = line[10:]
tmp = re.findall(r'[-+]?\d*\.\d+|\d+', valores)
lons.append(float(tmp[1]))
lats.append(float(tmp[0]))
chuva.append(float(tmp[2]))
except:
raise NameError('Erro ao tentar abrir/acessar arquivo: {}'.format(nomeArquivo))
return lons, lats, chuva
|
6254962976cb04c2eecf5aceaef45d4566cadfd9
| 79,415 |
import re
def strip_variable_text(rdf_text):
"""
Return rdf_text stripped from variable parts such as rdf nodeids
"""
replace_nid = re.compile('rdf:nodeID="[^\"]*"').sub
rdf_text = replace_nid('', rdf_text)
replace_creation = re.compile('<ns1:creationInfo>.*</ns1:creationInfo>', re.DOTALL).sub
rdf_text = replace_creation('', rdf_text)
replace_pcc = re.compile('<ns1:packageVerificationCode>.*</ns1:packageVerificationCode>', re.DOTALL).sub
rdf_text = replace_pcc('', rdf_text)
return rdf_text
|
2c4ac4aa5d6dca534f03e501398863445c8977ea
| 451,159 |
def resize(bbox, in_size, out_size):
"""Resize bouding boxes according to image resize operation.
Parameters
----------
bbox : numpy.ndarray
Numpy.ndarray with shape (N, 4+) where N is the number of bounding boxes.
The second axis represents attributes of the bounding box.
Specifically, these are :math:`(x_{min}, y_{min}, x_{max}, y_{max})`,
we allow additional attributes other than coordinates, which stay intact
during bounding box transformations.
in_size : tuple
Tuple of length 2: (width, height) for input.
out_size : tuple
Tuple of length 2: (width, height) for output.
Returns
-------
numpy.ndarray
Resized bounding boxes with original shape.
"""
if not len(in_size) == 2:
raise ValueError("in_size requires length 2 tuple, given {}".format(len(in_size)))
if not len(out_size) == 2:
raise ValueError("out_size requires length 2 tuple, given {}".format(len(out_size)))
bbox = bbox.copy()
x_scale = out_size[0] / in_size[0]
y_scale = out_size[1] / in_size[1]
bbox[:, 1] = y_scale * bbox[:, 1]
bbox[:, 3] = y_scale * bbox[:, 3]
bbox[:, 0] = x_scale * bbox[:, 0]
bbox[:, 2] = x_scale * bbox[:, 2]
return bbox
|
621eb71ad28eecab3d80131b4b429f35ec8b4a13
| 341,703 |
def remote_nodes(graph):
""" Return remote nodes
Remote nodes are isolated nodes that are not connected to anything
:param graph:
:return:
"""
return [u for u in graph.nodes() if len(list(graph.neighbors(u))) == 0]
|
af05c209cde7bb8f9a2e498ea0b4150debfaa245
| 563,886 |
def DecodeContent(data: bytes):
"""Convert utf-8 encoded bytes to a string."""
unpadded = data.rstrip(b"\00")
content = unpadded.decode("utf-8", "strict")
return content
|
387de22ba6d70da36085457d7ebc3cbb332e0ca4
| 410,882 |
def hyphen_last(s):
"""Converts '-foo' to 'foo-', so that 'foo-' comes after 'foo'
which is useful for sorting."""
if s.startswith('-'):
return s[1:] + '-'
return s
|
b791ac758eb5a9e6949a83576a2fa19c09154324
| 135,352 |
def get_line_list(path) -> list:
"""
Returns a file as a list of lines.
"""
return path.read_text().splitlines()
|
c1ef2c648dc0ede205d96db857eb221505035bc8
| 188,000 |
from io import StringIO
def ase_to_xyz(atoms, comment="", file=True):
"""Convert ASE to xyz
This function is useful to save xyz to DataFrame.
"""
xyz = StringIO()
symbols = atoms.get_chemical_symbols()
natoms = len(symbols)
xyz.write("%d\n%s\n" % (natoms, comment))
for s, (x, y, z) in zip(symbols, atoms.positions):
xyz.write("%-2s %22.15f %22.15f %22.15f\n" % (s, x, y, z))
if file:
return xyz
else:
return xyz.getvalue()
|
dcacdb5550c1cea2706190912556d84acae0094d
| 43,446 |
def get_isa_field_name(field):
"""
Return the name of an ISA field. In case of an ontology reference, returns
field['name'].
:param field: Field of an ISA Django model
:return: String
"""
if type(field) == dict:
return field['name']
return field
|
79480fb09a1f2a717d1c54472748207b8bf3f6f3
| 653,176 |
def run_program(codes, noun = None, verb = None):
"""
>>> run_program([1, 0, 0, 0, 99])
[2, 0, 0, 0, 99]
>>> run_program([2, 3, 0, 3, 99])
[2, 3, 0, 6, 99]
>>> run_program([2, 4, 4, 5, 99, 0])
[2, 4, 4, 5, 99, 9801]
>>> run_program([1, 1, 1, 4, 99, 5, 6, 0, 99])
[30, 1, 1, 4, 2, 5, 6, 0, 99]
"""
ip = 0
prog = codes.copy()
prog[1] = noun if noun != None else prog[1]
prog[2] = verb if verb != None else prog[2]
while prog[ip] != 99:
if prog[ip] == 1:
prog[prog[ip+3]] = prog[prog[ip+1]] + prog[prog[ip+2]]
elif prog[ip] == 2:
prog[prog[ip+3]] = prog[prog[ip+1]] * prog[prog[ip+2]]
ip += 4
return prog
|
a016feacf662f3e8f0b53659ff7d317e9bc2eb31
| 200,678 |
def f4(x):
"""Evaluate the estimate x**4+x**3+x**2+x."""
return x*(x*(x*x+x)+x)+x
|
6a5e258d77992e8c15a6dddb04627a7d5c8467d9
| 16,278 |
def is_valid_port(port):
"""Check if given port is valid"""
return(0 <= int(port) <= 65535)
|
5318f312573f68e364a4e8b80a92af4038f5bdf1
| 405,739 |
def check_in(position, info_pos_line_pairs):
"""
Check if position corresponds to the starting position of a pair in info_pos_line_pairs
(return pair if found, empty list otherwise)
:param position: list
:param info_pos_line_pairs: list of lists
:return: list
"""
# pos_pair form: [info, [in_line_position_1, line_number_1], [in_line_position_2, line_number_2]]
for i in info_pos_line_pairs:
if position[0] == i[1][0] and position[1] == i[1][1]:
return i
return []
|
26231ec22468e6fccd14d55b30b818a8c1773b78
| 685,235 |
def in_permissions(permissions, value):
"""
Given a permissions mask, check if the specified permission value is within those permissions.
:param permissions: permissions set as integer mask
:param value: permission value to look for
:type permissions: int
:type value: int
:return: is value in permissions?
"""
return bool(permissions & value)
|
50a4a0db406c24799caf17e0f109a82a480ea100
| 570,812 |
def ret_start_point(pn: str, keyword: bytes):
"""
1) return cid and tid from this example line
CALLID[3] TID[3756] IJ T2M 0x63621040->0x65cf6450(avformat-gp-57.dll!avformat_open_input+0x0)
2) for now, this function is case sensitive
"""
with open(pn, 'rb') as f:
lines = f.readlines()
for line in lines:
if keyword in line and b"0x0" in line:
cid = int(line.split(b"CALLID[")[1].split(b"]")[0])
tid = int(line.split(b"TID[")[1].split(b"]")[0])
return cid, tid
raise Exception("Cannot find the starting function from the trace file")
|
435fa2f5a65b93ca427d6afb0b1e817f44bfef10
| 76,758 |
def get_diff(url, client):
"""Uses client to return file diff from a given URL."""
return client.get(url)
|
e2fce7d01f4eee2e806393c865e54dd5ffe1a339
| 54,174 |
def write_tag_file_text(tags, delimiter="\n"):
"""
Write the text entries for a lit of tags.
Parameters
----------
tags: list
delimiter: str
Returns
-------
text: str
"""
text = ""
for t in tags:
text += f"{t}{delimiter}"
return text
|
1a7a7133a672d9183361813dde38e8819755b76c
| 443,185 |
def kl_div(mean, logvar):
"""Computes KL Divergence between a given normal distribution
and a standard normal distribution
Parameters
----------
mean : torch.tensor
mean of the normal distribution of shape (batch_size x latent_dim)
logvar : torch.tensor
diagonal log variance of the normal distribution of shape (batch_size x latent_dim)
Returns
-------
loss : torch.tensor
KL Divergence loss computed in a closed form solution
"""
batch_loss = 0.5 * (mean.pow(2) + logvar.exp() - logvar - 1).mean(dim=0)
loss = batch_loss.sum()
return loss
|
39fc74df4190a023e5b03132cd3102dc562a0401
| 659,646 |
import math
def get_page_total(total_number, per_page_number):
"""
Given a total page number and number of items per page, calculate the page total
Parameters
----------
total_number: int
Total number of pages
per_page_number: int
Number of items per page
Returns
-------
Integer representing the total number of pages
"""
return int(math.ceil(float(total_number)/per_page_number))
|
99e50a600051090db233b50081f52942d4938713
| 507,530 |
import collections
def combine_dicts(dict_list):
"""Combines the dictionaries in dict_list.
Args:
dict_list: A list of dicts. Each dict maps integers to lists.
Returns:
combined: A dict that has for every key the 'combined' values of all dicts
in dict list that have that key. Combining the values for a key amounts to
concatenating the corresponding lists.
"""
combined = collections.defaultdict(list)
for d in dict_list:
for k, v in d.items():
combined[k].extend(v)
return combined
|
197636dca7070c6aba53ad3e1f32d0f7db8d545e
| 256,100 |
def split_evr(version):
"""
Return a tuple of epoch, version, release from a version string
"""
if '~' in version:
epoch, version = version.split('~', 1)
else:
epoch, version = ('0', version)
release = None
if '-' in version:
version, release = version.rsplit('-', 1)
else:
version, release = (version, None)
return epoch, version, release
|
9e437c473b3fb0275f62b5fbf9dad64058d56b50
| 50,146 |
def bytes_coutwildrnp_zip(path_coutwildrnp_zip):
"""The zip file's bytes"""
with open(path_coutwildrnp_zip, 'rb') as src:
return src.read()
|
bd62d1ce2a2b20570ca45a8361e5ddb19c269725
| 543,419 |
def get_partial_index(df, start=None, end=None):
"""Get partial time index according to start and end
Parameters
----------
df: pd.DatFrame or pd.Series
start: str, optional, e.g., '2000-01-01'
end: str, optional, e.g., '2017-08-31'
Returns
-------
pd.DatetimeIndex
"""
if start is not None:
df = df.loc[df.index >= start]
if end is not None:
df = df.loc[df.index <= end]
return df.index
|
17b2426ae29eb5ba9a10a1d672bc9b954c69f504
| 628,006 |
def read_lines(filename):
"""Read all lines from a given file."""
with open(filename) as fp:
return fp.readlines()
|
f3005b1e1bc8a98fe543a1e364eec70ad4d85188
| 678,789 |
def is_valid_read(read):
"""Check if a read is properly mapped."""
if (read.mapping_quality >= 20 and read.reference_end and read.reference_start):
return True
return False
|
1ad54406c86a5375b880d6cc00afad3a173fda58
| 642,079 |
def sum_arithmetic_sequence(a_n: int) -> int:
"""
Returns 1 + 2 + ... + a_n.
>>> sum_arithmetic_sequence(4)
10
>>> sum_arithmetic_sequence(5)
15
"""
return int((a_n * (a_n + 1)) / 2)
|
1a70e88c5defe674dc0bf3067252b6133148584e
| 200,762 |
def IncludeCompareKey(line):
"""Sorting comparator key used for comparing two #include lines.
Returns the filename without the #include/#import prefix.
"""
for prefix in ('#include ', '#import '):
if line.startswith(prefix):
return line[len(prefix):]
return line
|
85f3cf7f4cdd3910e78a0239d9c3c566447869d5
| 569,128 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.