content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def nested_sum(t):
"""Computes the total of all numbers in a list of lists.
t: list of list of numbers
returns: number
"""
total = 0
for nested in t:
total += sum(nested)
return total | 44d9fa3e0a6011c74f23a002e86bef13b0c52e72 | 32,634 |
def oscar_calculator(wins: int) -> float:
""" Helper function to modify rating based on the number of Oscars won. """
if 1 <= wins <= 2:
return 0.3
if 3 <= wins <= 5:
return 0.5
if 6 <= wins <= 10:
return 1.0
if wins > 10:
return 1.5
return 0 | 31350d7ab5129a5de01f1853588b147435e91ab2 | 675,299 |
def decode_MAC(MAC_address):
"""
Returns a long int for a MAC address
@param MAC_address : like "00:12:34:56:78:9a"
@type MAC_address : str of colon separated hexadecimal ints
@return: long int
"""
parts = MAC_address.split(':')
if len(parts) == 6:
value = 0
for i in range(6):
shift = 8... | 6a4b2500ee438710781e8ac9906ee17738ed3c8b | 295,702 |
import operator
import importlib
def load(path):
"""
Loads a module member from a lookup path.
Paths are composed of two sections: a module path, and an attribute path,
separated by a colon.
For example::
>>> from pgshovel.utilities import load
>>> load('sys:stderr.write')
... | eaa1534384d2bef079e8ba57ee93d1cfaed827af | 436,234 |
def calculateHorizontalForce(qwind, span):
"""
:param qwind: Obciążenie wiatrem prostopadłe do lini cięgna [N/m]
:param span: Rozpiętość pozioma cięgna (długość w rzucie "z góry") [m]
"""
return (qwind * span) / 2 | 51040df0f170704e0d19bdfb273aecfc96551a4c | 548,378 |
def shorten(text, length, add="..."):
"""Shortens the provided text if it's longer than the length.
If it's longer, add is appended to the end."""
if text is None:
return ""
shortened = text[:length - len(add)]
if shortened != text:
return shortened + add
return shortened | 16850aff41e4c7f292a6ad9335d31cc378726206 | 169,331 |
def is_private(obj):
"""Return True if object is private."""
if obj is not None:
return isinstance(obj, str) and obj.startswith('_') | 648c0b765c4f96f7687d97a6ec18779778642648 | 624,981 |
import torch
def torch_transform(g, a, normals=None):
""" Applies the SE3 transform
Args:
g: SE3 transformation matrix of size ([1,] 3/4, 4) or (B, 3/4, 4)
a: Points to be transformed (N, 3) or (B, N, 3)
normals: (Optional). If provided, normals will be transformed
Returns:
... | b069587880ba832d6e00ec1f099eac02d1b1f929 | 484,938 |
import sqlite3
def connect_evals(fname):
"""Opens exclusive connection to a sqlite3 database.
Parameters
----------
fname : `str`
file name of sqlite3 database
Returns
-------
connection : `sqlite3.Connection`
Connection object to a sqlite database
"""
conn = sqli... | 87cc66b42a011da27ebf7db085c72912504e8264 | 194,001 |
def cast_image(image, dtype):
"""Casts an image into a different type
# Arguments
image: Numpy array.
dtype: String or np.dtype.
# Returns
Numpy array.
"""
return image.astype(dtype) | ad34f24d2ca6525c4dab19fc62c59e3e2f4aaee3 | 497,124 |
from typing import Mapping
from typing import Any
def find_renamed(items_before: Mapping[Any, Any], items_after: Mapping[Any, Any]):
"""
Split before/after mappings into added/removed/renamed
Rename detection is based on the mapping keys (e.g. uuids)
"""
uuids_before = {uuid for uuid in items_bef... | 420cfe482c901e5118dad430d736e688bd5745f9 | 160,740 |
def H(path):
"""Head of path (the first name) or Empty."""
vec = [e for e in path.split('/') if e]
return vec[0] if vec else '' | da618dfe64ed6b30b23ddb9d528458e80e7a8708 | 584,944 |
def recast_to_supercell(z, z_min, z_max):
"""Gets the position of the particle at ``z`` within the simulation
supercell with boundaries ``z_min`` y ``z_max``. If the particle is
outside the supercell, it returns the position of its closest image.
:param z:
:param z_min:
:param z_max:
:retur... | 2d144a656a92eaf3a4d259cf5ad2eadb6cfdf970 | 534 |
def _kafka_parse_broker(broker):
"""
`broker` is a string of `host[:port]`, return a tuple of `(host, port)`
"""
host_and_port = broker.split(":")
host = host_and_port[0]
port = "9092"
if len(host_and_port) == 2:
port = host_and_port[1]
return (host, port) | f738137fa50f66e58736e0cfb200860f6cd8411b | 286,330 |
def _convert_method_arg(method):
"""
Convert argument `method` to a function that can be called after
resampling or reindexing a DataFrame. If `method` is a string such
as 'ffill' or 'bfill' then it will be converted to a function. Otherwise
if `method` is itself a callable function, then it will be... | 3d7897ff82d0fde788c34756ebd8737736d7f4e8 | 597,817 |
def add_to_list(a_list: list, element: object):
"""
Attempts to append element to a list. If already contained,
returns 0. Else 1.
"""
if element not in a_list:
a_list.append(element)
return 1
return 0 | a6490d0cbdd9a422a491906413046bce27dd6855 | 92,590 |
def splitDataSet(dataSet, axis, value):
"""
按照给定特征划分数据集
:param dataSet: 待划分的数据集
:param axis: 划分数据集的特征的维度
:param value: 特征的值
:return: 符合该特征的所有实例(并且自动移除掉这维特征)
"""
retDataSet = []
for featVec in dataSet:
if featVec[axis] == value:
reducedFeatVec = featVec[:axis] # 删掉这一维... | 3cfddeeec479e369b35fd4910e2a7cd6e0e7d2f7 | 692,533 |
from typing import Dict
from typing import Any
from typing import Tuple
from typing import Optional
def deconstruct_entry(ServiceNowCMDBContext: Dict[str, Any]) -> Tuple[str,
Optional[str],
... | bbaf018fac969ceb6b753ea0f8429254ca6daf3a | 241,619 |
def get_max_row_column(train, val, test):
"""Returns the total number of rows, columns from train, validation and test arrays in COO form."""
r = max(max(train[:, 0]), max(val[:, 0]), max(test[:, 0])).astype(int) + 1
c = max(max(train[:, 1]), max(val[:, 1]), max(test[:, 1])).astype(int) + 1
return r, c | 43f07cc68f5b4dcee2503ffb0d704ad599407efd | 643,847 |
from typing import Union
def manipulate_reward(shift: Union[int, float], scale: Union[int, float]):
"""Manipulate reward in every step with shift and scale.
Args:
shift: Reward shift.
scale: Reward scale.
Return:
Manipulated reward.
"""
if shift is None:
shift = 0... | a486f32dc07b92ac4204a39cdcd86e96fa1810e6 | 556,752 |
def print_summary(api, campaign_id):
"""Print a campaign summary."""
summary = api.campaigns.summary(campaign_id=campaign_id)
print("Campaign Summary:")
print(f"\tName: {summary.name}")
print(f"\tStatus: {summary.status}")
print(f"\tLaunch Date: {summary.launch_date}")
print(f"\tCompleted D... | 66b2e41d06db64ba79a3b9b5bcb6f4265995cab7 | 495,911 |
def separate_ctrlpts_weights(ctrlptsw):
""" Divides weighted control points by weights to generate unweighted control points and weights vector.
This function is dimension agnostic, i.e. control points can be in any dimension but the last element of the array
should indicate the weight.
:param ctrlpts... | c283a6ae3e9ad7642ebe78d5ca1756757e988eaf | 189,881 |
def _MakeSampleSeconds(sample_times):
"""Helper to convert an array of time values to a tr157 string."""
deltas = [str(int(round(end - start))) for start, end in sample_times]
return ','.join(deltas) | 63a0eb16f100fea6ce589cbe8b94896796470abb | 248,963 |
def add_permission_request(response, original_message):
"""
Changes the response card to ask for location permissions and adds to the
output speech to alert user to enable location settings for app.
"""
permission_card = {
"type": "AskForPermissionsConsent",
"permissions": [
... | abeff68c7c704dc94beee3c4d416436fe0d24ecc | 460,612 |
from typing import Optional
from typing import Dict
from typing import Any
from typing import Iterable
def get_value(dictionnary: Optional[Dict[str, Any]],
key_list: Iterable[str]) -> Any:
"""Get nested value from Dict. Returns None if one of the keys is absent"""
if dictionnary is None:
... | 67f9a5e800b0235ae93878f5d86edfc09afdbf5f | 552,284 |
import yaml
def load_yaml(yaml_path):
"""Load the yaml|json file
Returns:
A dict which contains the config info
"""
with open(yaml_path, 'r') as f_config:
config_dict = yaml.full_load(f_config)
return config_dict | d6f2b02aedd98cc13b49aae676596d945d7a3c98 | 313,260 |
def either(a, b):
"""
:param a: Uncertain value (might be None).
:param b: Default value.
:return: Either the uncertain value if it is not None or the default value.
"""
return b if a is None else a | 3fd2f99fa0851dae6d1b5f11b09182dbd29bb8c1 | 709,371 |
import operator
def most_recent_assembly(assembly_list):
"""Based on assembly summaries find the one submitted the most recently"""
if assembly_list:
return sorted(assembly_list, key=operator.itemgetter('submissiondate'))[-1] | 1d7ecf3a1fa862e421295dda0ba3d89863f33b0f | 4,327 |
def canonicalize(uncanonical):
"""
takes a stitch invention and permutes the #i indices
such that forall j and k, if j<k then the first instance of #j always comes before the first instance of #k
"""
res = uncanonical
i = 100
while i >= 0:
res = res.replace('#'+str(i), f'#_#_{i}#_#_'... | fdeccc95dd61d4973b623665d4b45098a37eeed6 | 144,029 |
import socket
def free_port() -> int:
"""
Return free port on the localhost.
Returns
-------
int
Free port number on the localhost.
"""
sock = socket.socket(socket.AF_INET, type=socket.SOCK_STREAM)
sock.bind(("localhost", 0))
port: int
_, port = sock.getsockname()
... | 014440699686f00322a2dd1466b9df7ad3b6c649 | 398,124 |
def get_collection_keys(cleaned_zot_files):
"""
Gets the collection (folder) id keys for each entry in the cleaned Zotero files
"""
col_keys = []
if 'collections' in cleaned_zot_files['data'].keys():
if len(cleaned_zot_files['data']['collections']) > 1:
for i in cleaned_zot_files... | 52274c04a3c9ec0e9218914a36fdd33418e4aaa6 | 657,846 |
def rho2_rho1(M1, gamma):
"""Density ratio across a normal shock (eq. 3.53)
:param <float> M1: Mach # before the shock
:param <float> gamma: Specific heat ratio
:return <float> Density ratio r2/r1
"""
n1 = (gamma + 1.0) * M1 ** 2
d1 = 2.0 + (gamma - 1.0) * M1 ** 2
return n1 / d1 | d61eaee3d66e5478a5db93bde784c510ce9137a4 | 618,164 |
import itertools
def labeledBeamerFrames(pdfInfos):
"""Given a PDFInfos object, detect whether the PDF contains beamer
\frame{}s with [label=name]s. For every named frame, return a
pair (name, list_of_pages) in a list. If the PDF does not contain
corresponding named link targets (with names like 'na... | 332fb3eb1717a27dc1d90f65c8bf317c7f580acb | 454,866 |
def adjust_asymp_with_chronic(asymp_column, chronic_column):
"""
Remove asymptomatic flag for people with chronic disease
Parameters
----------
asymp_column : A boolean array storing people with asymptomatic infection
chronic_column : A boolean array storing people with chronic diseas... | 7848b09c36ee183e6a884647326822ab6f254ac5 | 634,021 |
from typing import Callable
import functools
def cached_property(func: Callable) -> property:
"""Customized cached property decorator
Args:
func: Member function to be decorated
Returns:
Decorated cached property
"""
return property(functools.lru_cache(None)(func)) | ff40239f95825d8a3acb6090ffc28dd479d727f8 | 139,679 |
def dfdb(B, E):
"""
B is the base
E is the exponent
f = B^E
partial df/dB = E * B**(E-1)
"""
out = E * (B**(E-1))
return out | 89047a198028320ecd2cbfac26064db6af8a784b | 39,008 |
def check_keys(in_dict):
"""Checks which keys are present within the input dictionary
This function looks within the input dictionary and checks
which keys are contained within it. Then, with these
keys, it generates a list containing these keys and
returns this list as output.
Parameters
... | e38c1853b2a73a35c5b615e35980e2b6921825a4 | 642,860 |
def _GetClearedFieldsForUrlRewrite(url_rewrite, field_prefix):
"""Gets a list of fields cleared by the user for UrlRewrite."""
cleared_fields = []
if not url_rewrite.pathPrefixRewrite:
cleared_fields.append(field_prefix + 'pathPrefixRewrite')
if not url_rewrite.hostRewrite:
cleared_fields.append(field_p... | bc0a4e3e068ebcdcf96b5e6f5cb6cdc0facd02e2 | 219,973 |
def xl_col_to_name(col, col_abs=False):
"""Convert a zero indexed column cell reference to a string.
Args:
col: The cell column. Int.
col_abs: Optional flag to make the column absolute. Bool.
Returns:
Column style string.
"""
col_num = col
if col_num < 0:
rais... | 11ebb0e82847e5a1cddeace375a5a0cc3f30bf1b | 660,410 |
import torch
def is_gpu_available() -> bool:
"""Check if GPU is available
Returns:
bool: True if GPU is available, False otherwise
"""
return torch.cuda.is_available() | a56cdd29dfb5089cc0fc8c3033ba1f464820778a | 674,458 |
def _get_in_response_to(params):
"""Insert InResponseTo if we have a RequestID."""
request_id = params.get('REQUEST_ID', None)
if request_id:
return {
'IN_RESPONSE_TO': request_id,
**params,
}
else:
return params | 8179ea86346d8eb13d1613fc43e875d2ab9cc673 | 385,220 |
def RoundUpRestricted(in_value:int, given_dim:int =100, isBidrectional:bool =True):
"""
This function return the smallest value that satisfies the rule [in_value % (given_dim * dimension_multiplier) = 0]
:param in_value:int: given value
:param given_dim:int=100: desired step size
:param ... | 79cda7b977420cc0678e4e1eaa36cb43e2ccef47 | 336,622 |
from pathlib import Path
import hashlib
def get_binary_hash(path: Path) -> str:
"""Return the MD5 hash of the given file."""
hasher = hashlib.md5()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hasher.update(chunk)
return hasher.hexdigest() | 610ebcb981696637ec7df5dc8bf9825779d52e9f | 439,929 |
import six
def merge(*dictionaries):
"""Recursively merge one or more dictionaries together.
Conflict resolution:
- Dictionary values are recursively merged.
- List values are added together.
- Sets are combined with `__or__` (equivalent of set.union).
- Everything else, the r... | d3c52a3bdb1331c8e1e0801079d6b19f8c18153a | 353,352 |
def link_easy(sid):
"""
Creates an html link to a dataset page in Easy.
:param sid: a dataset id
:return: link to the page for that dataset
"""
prefix = 'https://easy.dans.knaw.nl/ui/datasets/id/'
return '<a target="_blank" href="{}{}">{}</a>'.format(prefix, sid, sid) | f329ac256e459bf79572b8686a1b6be003efccae | 695,279 |
def shorten_str(text: str, width: int = 30, suffix: str = "[...]") -> str:
"""Custom string shortening (`textwrap.shorten` collapses whitespace)."""
if len(text) <= width:
return text
else:
return text[: width - len(suffix)] + suffix | 9b41b35222bdbdc528ab64aae05bb52851561ebb | 604,503 |
def index_dictionary(dictionary: dict, n=0):
"""Get the value given a dictionary and an index. Raises an IndexError if out of bounds."""
if n < 0:
n += len(dictionary)
for i, key in enumerate(dictionary.keys()):
if i == n:
return dictionary[key]
raise IndexError('ERROR: Index... | b1871701c0890c18e95f9c0aa3a6cdebd51ce03a | 297,812 |
def _title_to_snake(src_string):
"""Convert title case to snake_case."""
return src_string.lower().replace(" ", "_").replace("/", "-") | ff0e56d48be19ed1ab7404978acf1eef146dcdf3 | 540,121 |
def distance(point1, point2):
"""Return the calculated distance between the points.
Manhattan distance.
"""
x0, y0 = point1
x1, y1 = point2
return abs(x1 - x0) + abs(y1 - y0) | d99157e3f661035772330e92b0e19df2d6d6cc40 | 370,304 |
def _zone(index):
"""Chooses a GCP zone based on the index."""
if index < 6:
return 'us-central1-a'
elif index < 12:
return 'us-east1-b'
elif index < 18:
return 'us-east4-c'
elif index < 24:
return 'us-west2-a'
else:
raise ValueError('Unhandled zone index') | 9d5a86ce022530e59301f82e73cf3bc90cf6df87 | 657,809 |
import sympy
def integer_partitions(target, nb_ele):
"""
return all possible ways to sum to target using nb_ele, allowing 0 to be one of the element
for example, integer_partitions(4, 2) returns
([0,4], [4,0], [1,3], [3,1], [2,2])
"""
if target == 0:
return [[0] * nb_ele]
ans = [... | 248c21e4031bcad66f0f39f0751775aad0e309d1 | 252,047 |
from datetime import datetime
def parse_time(x):
"""Extract hour, day, month, and year from time category."""
DD = datetime.strptime(x, "%Y-%m-%d %H:%M:%S")
time = DD.hour
day = DD.day
month = DD.month
year = DD.year
return time, day, month, year | d7ad14106b08d3f39767db8fe00f34fec4290a9d | 192,335 |
def _transform_opt(opt_val):
"""Transform a config option value to a string.
If already a string, do nothing. If an iterable, then
combine into a string by joining on ",".
Args:
opt_val (Union[str, list]): A config option's value.
Returns:
str: The option value converted to a stri... | 2ade412fda106122e2d170fdd7ae819c47997b4f | 553,672 |
def get_texture_type(dimensions):
"""Get texture type by dimensionality."""
assert 1 <= dimensions <= 3
return eval('GL_TEXTURE_{}D'.format(dimensions)) | d730e55fe0df79dc645d3170a514a040e50f4546 | 462,104 |
import csv
def rows_in_csv(filename):
"""Helper function to quickly count the number of rows in the passed csv
file."""
with open(filename, encoding="UTF8", mode="rt") as f:
reader = csv.reader(f)
count = 0
for _ in reader:
count += 1
return count - 1 | 955dbe18ea92e0df76b749ec707d86e9b8dcd94c | 179,547 |
import re
def clean_regex(text):
"""
Clean contraction from the text
Parameters
----------
text: string
Text lines of string
Return
------
string
Cleaned contraction
"""
clean_dict = {
r"i'm": r"i am",
r"he's": r"he is",
r"she's... | 107df5223360573c4d33193b1ae5c7f24ce2cc42 | 260,607 |
def get_cluster_proportions(adata,
cluster_key="cluster_final",
sample_key="replicate",
drop_values=None):
"""
Input
=====
adata : AnnData object
cluster_key : key of `adata.obs` storing cluster info
sample_key :... | fd0b50d9b07b62441a4f45bb93aacd7bb0360b66 | 457,971 |
import decimal
def create_update_item_input(item):
"""Return input for DynamoDB `update_item()` operation on `item` setting
`isRecent` to `1`.
Parameters
----------
item : dict
DynamoDB `Deal` item to update
Returns
-------
dict
Input for DynamoDB `update_item` operat... | f1af37865ea3934b927247c5bc7f35b156db461c | 344,654 |
def application(environ, start_response):
"""Serve the button HTML."""
with open('wsgi/button.html') as f:
response_body = f.read()
status = '200 OK'
response_headers = [
('Content-Type', 'text/html'),
('Content-Length', str(len(response_body))),
]
start_response(status, ... | 97f1f793f234dbd3c29e9c4a791a224ba32c984b | 707,586 |
def get_input(prompt):
"""Modified raw input that requires a non-empty response."""
res = None
while not res:
res = input(prompt)
return res | ed15f5b39de0f16477ba2091574812c8a9e6ee75 | 445,601 |
def getType(item) :
"""Attempt to determine what type of value a string represents"""
item = item.strip()
if not item : return "NULL"
if item[0] == "$": return "$"
if item.strip("0123456789,.") : return "STR"
return "NUM" | 423fbef0922339c469b313ba76ef7e6c43b3c9d7 | 594,339 |
def is_skill(pos):
"""
Takes some string named pos ('QB', 'K', 'RT' etc) and checks
whether it's a skill position (RB, WR, TE).
"""
return pos in ['RB', 'WR', 'TE'] | 4f41be47ecd75528f86c73c16a08a0308f7616d6 | 372,733 |
def get_modified_files_list(diff):
"""Get list of modified or newly added files list"""
file_list = []
for file in diff["files"]:
if file["status"] == "modified" or file["status"] == "added":
file_list.append(file["filename"])
return file_list | 9219d0e4f41ee9aa9b64e0a9867a6a90c679dc02 | 82,836 |
def _as_list(list_str, delimiter=','):
"""Return a list of items from a delimited string (after stripping whitespace).
:param list_str: string to turn into a list
:type list_str: str
:param delimiter: split the string on this
:type delimiter: str
:return: string converted to a list
:rtype... | 2cfa1939fd3964a7282254cb80a7b1bb4a48b7b0 | 313,474 |
import requests
import json
def custom_ws_perm_maker(user_id: str, ws_perms: dict):
"""
Returns an Adapter for requests_mock that deals with mocking workspace permissions.
:param user_id: str - the user id
:param ws_perms: dict of permissions, keys are ws ids, values are permission. Example:
{... | 86837c953dafd6b96f70de79c64ce72b6997e0cc | 658,328 |
def get_nested_answers(nested_questions):
"""Takes a list of question-sets; returns a list of answers."""
return [question['answers']
for qset in nested_questions
for question in qset['questions']] | ce96953bd114bc814d72ec01caf625810b02096f | 405,666 |
import torch
def square_distance(xyz1, xyz2):
"""
Compute the square of distances between xyz1 and xyz2.
Parameters
----------
xyz1 : torch.tensor [B, C, N]
xyz tensor
xyz2 : torch.tensor [B, C, M]
xyz tensor
Return
------
distances : torch.tesnor [B, N, M]
... | 741b91bd51d111d3831a8139dc5e8a425b8571e0 | 432,021 |
import bisect
def find_lt(array, x):
"""Find rightmost value less than x.
Example::
>>> find_lt([0, 1, 2, 3], 2.5)
2
**中文文档**
寻找最大的小于x的数。
"""
i = bisect.bisect_left(array, x)
if i:
return array[i - 1]
raise ValueError | 7cde3a9e5a5c899d1c9fedc9ec5aa20705f7bd26 | 140,640 |
def jaccard(graph, lda_topics):
"""
Builds a function to estimate Jaccard Similarity w.r.t. intermediary topics (from topic graph) in lda_topics.
"""
Q_it = set(x[0] for x in lda_topics if graph.has_node(x[0]) and graph.node[x[0]]['is_intermediary'])
def jaccard_similarity(P):
if not P or n... | d33f0d2b72c2e76fd681a30655bfb07ae48d88a5 | 390,643 |
def extractDidParts(did):
"""
Parses and returns a tuple containing the prefix method and key string contained in the supplied did string.
If the supplied string does not fit the pattern pre:method:keystr a ValueError is raised.
:param did: W3C DID string
:return: (pre, method, key string) a tuple... | e106f197321e0686a5091ba03681f1e2a9752ba4 | 549,985 |
def IsTryJobResultAtRevisionValid(result, revision):
"""Determines whether a try job's results are sufficient to be used.
Args:
result (dict): A dict expected to be in the format
{
'report': {
'result': {
'revision': (dict)
}
}... | 1515c82d2673139fb0fec01e662ca62057f715de | 83,503 |
def plato_to_sg(deg_plato):
"""
Degrees Plato to Specific Gravity
:param float deg_plato: Degrees Plato
:return: Specific Gravity
:rtype: float
The simple formula for S.G. is:
:math:`\\text{SG} = 1 + 0.004 \\times \\text{Plato}`
The more precise calculation of SG is:
:math:`\\te... | 135d9a5cf0c982ae71c158997b1182ab8b627609 | 233,420 |
def identify_cat_con(df,threshold=0.05):
"""
Heuritic identification of continuous and categorical data
Parameters:
-----------
df: pd.DataFrame
threshold: float, [0,1], default=0.05
Ratio of unique values vs total number of values
Returns:
--------
con_data: list of col... | 5a3e1a7343f21c8e51d2f2a343002f2914d1fedc | 430,690 |
def get_digit(number, digit):
""" Given a number, returns the digit in the specified position, for an out of range digit returns 0 """
digit_sum = 0
for i in range(digit): # Accumulate all the other digits and subtract from the original number
digit_sum += number - ((number // 10**(i+1)) * 10**(i+1... | 67ba5dbffb0ad5bdf2a8f7d59970428a1195e868 | 591,139 |
from io import StringIO
def configObj2Str(cobj):
"""Dump a Configobj instance to a string."""
outstr = StringIO()
cobj.write(outstr)
return outstr.getvalue() | c71f47f5b6b1e4641b7c07091ce98dc665aa9edf | 306,402 |
def parse_logs_align_isize(fname):
"""Parse _isize_table.txt
Inputs: fname - filename of table
Returns: data - dictionary of insert size data
"""
data = {'percent': {}, 'readcnt': {}}
with open(fname, 'r') as f:
file_data = f.read().splitlines()[2:]
for l in file_data:
... | 28043418fabf9a4a0f515aa00ba556ff91fd0165 | 235,354 |
def parse_description(description):
"""Return the parameter name and unit from the parameter description
:param description: A description containing a parameter name and unit
:type description: string
:returns: Name and units of a parameter
:rtype: tuple
>>> description = "Temperature, water,... | 471ae0af756ed8bfaa052acb0422c80733911572 | 544,303 |
def PROP_GEOMETRICA_ESTADIO_I(H, B_F, B_W, H_F, A_SB, ALPHA_MOD, D):
"""
Esta função calcula as propriedades geométricas no estádio I.
Entrada:
H | Altura da viga | m | float
B_F | Base de mesa superior da seção | m | float... | 72f7872c8958c40dea76bccaca6c0cf2779d35dd | 543,762 |
import io
def remove_multiple_newlines_in_txt(txt: str) -> str:
""" This function will remove multiple, sequential newlines in text (str) data.
:param txt: a str containing the text to be cleaned.
:return: a str containing the text with multiple, sequential newlines removed.
"""
clean_txt = ''
... | 9b1be808c4253b0f2b58b1985b10417a65b7cdeb | 45,184 |
def count_params(model):
"""
Count number of trainable parameters in PyTorch model
"""
num_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
return num_params | fe6505100a8ffeb5365d96eb21656cc30b8777d8 | 457,663 |
def countif(n, func):
"""
return number of items in n having a non-zero return from func
"""
n = [1 for i in n if (func(i))]
return sum(n) | afd95d4e6d0838f0e11c373ab46f5b08db4f5b77 | 250,404 |
def zigzag(value: int) -> int:
"""Zig-zag encode a parameter to turn signed ints into unsigned ints.
Zig-zag encoding is required by Geometry commands that require parameters,
and the number of parameters will be (number_of_commands * number_of_arguments).
For more information about this technique, che... | 1bd49a0955493360423cb32a19e4ff6cf8fc80ca | 449,617 |
def split_int(i, p):
"""
Split i into p buckets, such that the bucket size is as equal as possible
Args:
i: integer to be split
p: number of buckets
Returns: list of length p, such that sum(list) = i, and the list entries differ by at most 1
"""
split = []
n = i / p # min ... | 2aedf0a008d91f1635aa1117901ae525fbdb7d7e | 681,234 |
def quantile(x, percentile):
"""
Returns value of specified quantile of X.
:param list or tuple x: array to calculate Q value.
:param float percentile: percentile (unit fraction).
:return: Q value.
:rtype: int or float
:raise ValueError: when len of x == 0
"""
if x:
p_idx = ... | c14e3271e1bf0d361de34a58179f1a4a5d428e40 | 277,209 |
def set_car(pair, val):
"""Set car of the pair."""
pair.car = val
return pair | d50f0b3719bc12f41ef9ca41a3ceeb467d7d4526 | 497,524 |
def maybe_single(sequence):
"""
Given a sequence, if it contains exactly one item,
return that item, otherwise return the sequence.
Correlary function to always_iterable.
>>> maybe_single(tuple('abcd'))
('a', 'b', 'c', 'd')
>>> maybe_single(['a'])
'a'
"""
try:
(single,) ... | 65685fa1e58d265638fdbff7fa002062e74ed0b0 | 286,106 |
def _make_unique(key, val):
"""
Make a tuple of key, value that is guaranteed hashable and should be unique per value
:param key: Key of tuple
:param val: Value of tuple
:return: Unique key tuple
"""
if type(val).__hash__ is None:
val = str(val)
return key, val | 65d746276f635c129aa0a5aeb9b9f467453c0b2a | 708,533 |
def has_relative_protocol(uri):
"""Return True if URI has relative protocol '//' """
start = uri[:2]
if start == '//':
return True
return False | 40c37b5f7ec6ea6de2ed02b742b2f2d0b149bc32 | 654,118 |
def diameter(d_2):
"""Calculate internal diameter at the start angle.
:param d_2 (float): diameter of the impeller at section 2 [m]
:return d (float): diameter [m]
"""
d = round(1.1 * d_2, 3)
return d | b2fe808e0cd9aee81bfe29d7fb35f643710e5a43 | 128,390 |
import time
import random
def _generate_name(name):
"""
Generate names for tested objects where you can probably tell at a glance
which objects were created by which executions of the unittests.
"""
return 'test-%s-%s-%s' % (time.strftime('%Y%m%d%H%M%S'),
random.randi... | 7a182f3f810e9391c3290b0d283164afaf1fe5f0 | 315,524 |
import socket
def is_open_port(port):
"""
Check if a port is open (listening) or not on localhost.
It returns true if the port is actually listening, false
otherwise.
:param port: The port to check.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex... | 4eb8f52744cc7f330dd101b613d5db4ab8d0d0fc | 700,661 |
def are_all_strings_in_text(text, list_of_strings):
"""
:param text: output from convert_pdf_to_text
:type text: list of str
:param list_of_strings: a list of strings used to identify document type
:type list_of_strings: list of str
:return: Will return true if every string in list_of_strings is... | a4ef6a2067e85fdc97c767881f26f9188c1f55ef | 598,173 |
def words_and_tags_from_wsj_tree(tree_string):
"""Generates linearized trees and tokens from the wsj tree format.
It uses the linearized algorithm described in https://arxiv.org/abs/1412.7449.
Args:
tree_string: tree in wsj format
Returns:
tuple: (words, linearized tree)
"""
stack, tags, words = ... | e3871547254d33d5ab99cf1ec685b291db620a0f | 596,515 |
def pyx_is_cplus(path):
"""
Inspect a Cython source file (.pyx) and look for comment line like:
# distutils: language = c++
Returns True if such a file is present in the file, else False.
"""
for line in open(path, 'rt'):
if line.startswith('#') and '=' in line:
splitted = ... | d8ad5c7884453a5dc3cec6b340d8fa5ac3094cb3 | 30,006 |
import copy
def hill_climb(nsteps, start_node, get_next_node):
"""Modular hill climbing algorithm.
Example:
>>> def get_next_node(node):
... a, b = random.sample(range(len(node)), 2)
... node[a], node[b] = node[b], node[a]
... plaintext = decrypt(node, ciphertext)
... | 1474cd2eb150295b18282d8cf651b2d38277e836 | 445,335 |
import pickle
def get_byte_length(value):
"""Return the byte length of the pickled value."""
return len(pickle.dumps(value)) | 855c0fc26267babcbf2e0f79f6fc4c7ba84cd886 | 331,335 |
def dot_product(d1, d2, default_value=0):
"""Calcualte the dot product for the intersection of two dictionary objects.
If the key does not exist in d2, default_value is used instead.
"""
return sum(map(lambda x: float(d1[x]) * float(d2.get(x, default_value)), d1.keys())) | 144dd4bbd5ebac8bcafe316bcecba53516f840a5 | 389,189 |
def editable(el):
"""
Return editable part of UML element.
It returns element itself by default.
"""
return el | 5686e9eef8ba3e7bc10539d9b3494faa8e1130d4 | 188,983 |
def get_available_metrics() -> list:
"""Get list of available metrics."""
metrics = [
"NSE",
"MSE",
"RMSE",
"KGE",
"Alpha-NSE",
"Pearson r",
"Beta-NSE",
"FHV",
"FMS",
"FLV",
"Peak-Timing",
]
return metrics | f872fa5411b2038ee2ccdd153508fd7d0acabdc5 | 593,576 |
def is_collection(obj):
"""
Return whether the object is a array-like collection.
"""
for typ in (list, set, tuple):
if isinstance(obj, typ):
return True
return False | 291fefe89accb27ba029d9ff195806df8f55f19d | 239,385 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.