content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def mlist(self, node1="", node2="", ninc="", **kwargs):
"""Lists the MDOF of freedom.
APDL Command: MLIST
Parameters
----------
node1, node2, ninc
List master degrees of freedom from NODE1 to NODE2 (defaults
toNODE1) in steps of NINC (defaults to 1). If NODE1 = ALL
(defaul... | 611cd462d34cd4de0e34cb262549fc6cff40127d | 11,292 |
def formatstr(text):
"""Extract all letters from a string and make them uppercase"""
return "".join([t.upper() for t in text if t.isalpha()]) | 749aeec962e3e39760c028bfb3e3a27ad8c10188 | 11,294 |
def form2_list_comprehension(items):
"""
Remove duplicates using list comprehension.
:return: list with unique items.
"""
return [i for n, i in enumerate(items) if i not in items[n + 1:]] | 02d095c86de1b7d52d53cdb4bfe77db08523ea3a | 11,296 |
def calcMass(volume, density):
"""
Calculates the mass of a given volume from its density
Args:
volume (float): in m^3
density (float): in kg/m^3
Returns:
:class:`float` mass in kg
"""
mass = volume * density
return mass | 38f0ef780704c634e572c092eab5b92347edccd3 | 11,297 |
def rescale(arr, vmin, vmax):
""" Rescale uniform values
Rescale the sampled values between 0 and 1 towards the real boundaries
of the parameter.
Parameters
-----------
arr : array
array of the sampled values
vmin : float
minimal value to rescale to
vmax : float
... | d6debc0eeccd9fe19ed72d869d0de270559c9ce8 | 11,298 |
import socket
def check_port_occupied(port, address="127.0.0.1"):
"""
Check if a port is occupied by attempting to bind the socket
:return: socket.error if the port is in use, otherwise False
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((address, port))
ex... | 5919e228c835ceb96e62507b9891c6a1ce5948fa | 11,301 |
import csv
def write_rows(rows, filename, sep="\t"):
"""Given a list of lists, write to a tab separated file"""
with open(filename, "w", newline="") as csvfile:
writer = csv.writer(
csvfile, delimiter=sep, quotechar="|", quoting=csv.QUOTE_MINIMAL
)
for row in rows:
... | 41e04ee6203baf7db2d08722aed76dfacbc9e838 | 11,309 |
def HKL2string(hkl):
"""
convert hkl into string
[-10.0,-0.0,5.0] -> '-10,0,5'
"""
res = ""
for elem in hkl:
ind = int(elem)
strind = str(ind)
if strind == "-0": # removing sign before 0
strind = "0"
res += strind + ","
return res[:-1] | 325ddfcb2243ce9a30328c5b21626a4c93a219de | 11,313 |
from typing import List
def should_expand_range(numbers: List[int], street_is_even_odd: bool) -> bool:
"""Decides if an x-y range should be expanded."""
if len(numbers) != 2:
return False
if numbers[1] < numbers[0]:
# E.g. 42-1, -1 is just a suffix to be ignored.
numbers[1] = 0
... | fcd5a8e027120ef5cc52d23f67de4ab149b19a2c | 11,316 |
def zyx_to_yxz_dimension_only(data, z=0, y=0, x=0):
"""
Creates a tuple containing the shape of a conversion if it were to happen.
:param data:
:param z:
:param y:
:param x:
:return:
"""
z = data[0] if z == 0 else z
y = data[1] if y == 0 else y
x = data[2] if x == 0 else x
... | 2477976f795f5650e45214c24aaf73e40d9fa4eb | 11,317 |
def gen_anonymous_varname(column_number: int) -> str:
"""Generate a Stata varname based on the column number.
Stata columns are 1-indexed.
"""
return f'v{column_number}' | f0e150300f7d767112d2d9e9a1b139f3e0e07878 | 11,318 |
def create_city_map(n: int) -> set:
"""
Generate city map with coordinates
:param n: defines the size of the city that Bassi needs to hide in,
in other words the side length of the square grid
:return:
"""
return set((row, col) for row in range(0, n) for col in range(0, n)) | fd30b936647bae64ccf2894ffbb68d9ad7ec9c6b | 11,320 |
def nullable(datatype):
"""Return the signature of a scalar value that is allowed to be NULL (in
SQL parlance).
Parameters
----------
datatype : ibis.expr.datatypes.DataType
Returns
-------
Tuple[Type]
"""
return (type(None),) if datatype.nullable else () | fe5935d1b4b1df736933455e97da29a901d6acb1 | 11,322 |
from typing import Dict
def make_country_dict(
csv_file:str = 'data/country_list.csv') -> Dict[str, str]:
"""Make a dictionary containing the ISO 3166 two-letter code
as the key and the country name as the value. The data is read
from a csv file.
"""
country_dict = {}
with open(csv_fi... | 0334a2b2c918f407d1df682f56c14943f1e66c43 | 11,325 |
from typing import List
def get_reputation_data_statuses(reputation_data: List) -> List[str]:
"""
collects reported statuses of reputation data
Args:
reputation_data: returned data list of a certain reputation command
Returns: a list of reported statuses
"""
reputation_statuses = [sta... | 2c41344f2970243af83521aecb8a9374f74a40ac | 11,328 |
def is_number(val):
"""Check if a value is a number by attempting to cast to ``float``.
Args:
val: Value to check.
Returns:
True if the value was successfully cast to ``float``; False otherwise.
"""
try:
float(val)
return True
except (ValueError, TypeErr... | 89728d3d199c3ef5885529da5a2d13dd94fa590f | 11,329 |
def format_rfc3339(datetime_instance):
"""Formats a datetime per RFC 3339."""
return datetime_instance.isoformat("T") + "Z" | ad60a9e306e82554601efc1ae317296a59b009b0 | 11,331 |
def get_metadata_keys(options):
""" Return a list of metadata keys to be extracted. """
keyfile = options.get("keyfile")
if (keyfile):
with open(keyfile, "r") as mdkeys_file:
return mdkeys_file.read().splitlines()
else:
return None | 2451d54ae49690691e5b0ce019178fd119e3d269 | 11,332 |
def _remove_self(d):
"""Return a copy of d without the 'self' entry."""
d = d.copy()
del d['self']
return d | a80eca3886d0499d1871998501c19e9cdae93673 | 11,338 |
def deltanpq(phino, phinoopt=0.2):
"""Calculate deltaNPQ
deltaNPQ = (1/phinoopt) - (1/phino)
:param phino: PhiNO
:param phinoopt: Optimum PhiNO (default: 0.2)
:returns: deltaNPQ (float)
"""
return (1/phinoopt) - (1/phino) | 34d44a732bd87eb78e8ddee92b4555bea67789be | 11,339 |
def opt_in_argv_tail(argv_tail, concise, mnemonic):
"""Say if an optional argument is plainly present"""
# Give me a concise "-" dash opt, or a "--" double-dash opt, or both
assert concise or mnemonic
if concise:
assert concise.startswith("-") and not concise.startswith("--")
if mnemonic:
... | 17333a2a526799d6db5e78746d3ecb7111cd8cd6 | 11,343 |
def split_by_unicode_char(input_strs):
"""
Split utf-8 strings to unicode characters
"""
out = []
for s in input_strs:
out.append([c for c in s])
return out | 290bb5ec82c78e9ec23ee1269fe9227c5198405e | 11,347 |
def get_lr(optimizer):
"""get learning rate from optimizer
Args:
optimizer (torch.optim.Optimizer): the optimizer
Returns:
float: the learning rate
"""
for param_group in optimizer.param_groups:
return param_group['lr'] | fc8293cc29c2aff01ca98e568515b6943e93ea50 | 11,358 |
def find_changes(vals, threshold=None, change_pct=0.02, max_interval=None):
"""Returns an array of index values that point at the values in the 'vals'
array that represent signficant changes. 'threshold' is the absolute amount
that a value must change before being included. If 'threshold' is None,
'c... | e6c66d3636f80ee310dcb7ae790bb30a27598aaa | 11,366 |
def data_value(value: str) -> float:
"""Convert to a float; some trigger values are strings, rather than
numbers (ex. indicating the letter); convert these to 1.0."""
if value:
try:
return float(value)
except ValueError:
return 1.0
else:
# empty string
... | 24087c1733be5932428a63811abbb54686836036 | 11,370 |
from typing import Tuple
import logging
async def mark_next_person(queue_array: list) -> Tuple[list, int]:
"""Mark next person in the queue (transfers current_turn to them).
Parameters
----------
queue_array : list
This array represents the queue
Returns
-------
Tuple[list, int]
... | e792dbf2ac10f44bda53a6429ba43180bdefd144 | 11,371 |
from typing import Dict
from typing import Any
def map_key(dictionary: Dict, search: Any) -> Any:
"""Find and return they key for given search value."""
for key, value in dictionary.items():
if value == search:
return key
return None | c9e200bb352b68c7468ae0511f11f7eff5e46b52 | 11,379 |
def get_requirements(filename):
"""
Get requirements file content by filename.
:param filename: Name of requirements file.
:return: Content of requirements file.
"""
return open("requirements/" + filename).read().splitlines() | 3dab39352bb69798e076a9d97077902580f50640 | 11,380 |
def is_operator(token):
"""Checks if token is an operator '-+/*'."""
return token in '-+/*' | 24b57d2a299df263c900cc94e2e18a9fc7d026b1 | 11,382 |
def add_date_end(record: dict):
"""
Function to make ``date_end`` ``date_start`` if ``measure_stage`` is "Lift"
Parameters
----------
record : dict
Input record.
Returns
-------
type
Record with date_end changed conditionally, or original record.
"""
if record... | 67f6ae063aabdf7a7d456ed0ce9660a75b37b6c2 | 11,385 |
def multy(b: int) -> int:
"""2**b via naive recursion.
>>> multy(17)-1
131071
"""
if b == 0:
return 1
return 2*multy(b-1) | 272cd138de2209093c0a32e1c7b2f1c08d0dc2be | 11,386 |
def get_ens(sets):
"""
Puts all entities appeared in interpretation sets in one set.
:param sets: [{en1, en2, ...}, {en3, ..}, ...]
:return: set {en1, en2, en3, ...}
"""
ens = set()
for en_set in sets:
for en in en_set:
ens.add(en)
return ens | 7f5b59d6f5786ee9506bda72a4ee3f8cdf787c33 | 11,387 |
def is_in_group(user, group_name):
"""
Check if a user in a group named ``group_name``.
:param user User:
The auth.User object
:param group_name str:
The name of the group
:returns: bool
"""
return user.groups.filter(name__exact=group_name).exists() | 25e51e483b0c18c03f8e897725f07e9e63cc160a | 11,389 |
def strip_email(s: str) -> str:
"""
Filter which extracts the first part of an email to make an shorthand
for user.
:param s: Input email (or any string).
:type s: str
:return: A shorthand extracted.
:rtype: str
"""
return s.split('@', 1)[0] | 36ea94b9eb12e0e64b78965c66233578790e6a13 | 11,395 |
def name_item_info(mosaic_info, item_info):
"""
Generate the name for a mosaic metadata file in Azure Blob Storage.
This follows the pattern `metadata/quad/{mosaic-id}/{item-id}.json`.
"""
return f"metadata/quad/{mosaic_info['id']}/{item_info['id']}.json" | db78eb175f6530ace2037ed89cb090591c82147f | 11,396 |
def ptfhost(testbed_devices):
"""
Shortcut fixture for getting PTF host
"""
return testbed_devices["ptf"] | 25fdbc9520c4cda9719887ff213ccb2b88918dcc | 11,397 |
from datetime import datetime
def add_current_time_to_state(state):
"""Annotate state with the latest server time"""
state['currentTime'] = datetime.now().timestamp()
return state | f61fa2d7b127fbebb22fc277e16f2f79cdd4acd3 | 11,398 |
import re
def normalize_rgb_colors_to_hex(css):
"""Convert `rgb(51,102,153)` to `#336699`."""
regex = re.compile(r"rgb\s*\(\s*([0-9,\s]+)\s*\)")
match = regex.search(css)
while match:
colors = map(lambda s: s.strip(), match.group(1).split(","))
hexcolor = '#%.2x%.2x%.2x' % tuple(m... | e3650f525d1d9c1e7bbf7d5b4161712a7439b529 | 11,401 |
def shape_to_spacing(region, shape, pixel_register=False):
"""
Calculate the spacing of a grid given region and shape.
Parameters
----------
region : list = [W, E, S, N]
The boundaries of a given region in Cartesian or geographic
coordinates.
shape : tuple = (n_north, n_east) or... | bc943f55330c17295bdb078d732c6ebc9f8cecfe | 11,410 |
import math
def choose_grid_size(train_inputs, ratio=1.0, kronecker_structure=True):
"""
Given some training inputs, determine a good grid size for KISS-GP.
:param x: the input data
:type x: torch.Tensor (... x n x d)
:param ratio: Amount of grid points per data point (default: 1.)
:type rati... | 1d3e30a6b7b419a1e2fcdc245830aa00d1ba493d | 11,411 |
def parameter_tuple_parser(parameter_tuple, code_list, relative_base):
"""
Accepts parameter_tuple, code_list, and relative_base. Returns parameter for use in intcode operation.
"""
if parameter_tuple[0] == 0:
return code_list[parameter_tuple[1]]
elif parameter_tuple[0] == 1:
retur... | f869240666f2adca0551a3620644023b88930a5a | 11,417 |
def _compute_padding_to_prevent_task_description_from_moving(unfinished_tasks):
"""Compute the padding to have task descriptions with the same length.
Some task names are longer than others. The tqdm progress bar would be constantly
adjusting if more space is available. Instead, we compute the length of th... | 82a2fffa0a35036901affe11fdf98d875445ffea | 11,420 |
import math
def float_in_range(value: float, lower: float, upper: float) -> bool:
"""Checks if a float is within a range.
In addition to checking if lower < value < upper, checks if value is close to the end points;
if so, returns True. This is to account for the vageries of floating point precision.
... | e971c082e8019f545c9ccc1024f37d3bab61b64e | 11,421 |
def flat_list(source):
"""Make sure `source` is a list, else wrap it, and return a flat list.
:param source: source list
:returns: flat list
"""
if not isinstance(source, (list, tuple)):
source = [source]
r = []
list(map(lambda x: r.extend(x)
if isinstance(x, (list, tuple))
... | d118388794cdef72200ad43ab88d9f964b633851 | 11,426 |
def git_ref_from_eups_version(version: str) -> str:
"""Given a version string from the EUPS tag file, find something that
looks like a Git ref.
"""
return version.split("+")[0] | c6a429878c2150ce58b262e9f1fb187226336b0b | 11,427 |
def collapse(iter_flow_result:dict)->list:
""" Return iter_flow dict result as a single flat list"""
nested_lists = [iter_flow_result[k] for k in iter_flow_result.keys()]
flat_list = [item for sublist in nested_lists for item in sublist]
return(flat_list) | ada0d654ed36df8168b4835fbde3b91b7f56fb72 | 11,431 |
from typing import Union
from pathlib import Path
def relative_to(
path: Union[str, Path], source: Union[str, Path], include_source: bool = True
) -> Union[str, Path]:
"""Make a path relative to another path.
In contrast to :meth:`pathlib.Path.relative_to`, this function allows to keep the
name of th... | 26caa33770617361406915c9b301b5fe1a0ba9ef | 11,437 |
def get_creds(filename):
"""
Read credentials from a file. Format is:
URL
USERNAME
PASSWORD
Parameters
----------
filename: string
path to the file with the credentials
Returns
-------
list as [URL, USERNAME, PASSWORD]
"""
f = open(filename, "r")
lines =... | 7b308a2e140a809e0bb11804750370bb4326796d | 11,441 |
def uri_base(uri):
"""
Get the base URI from the supplied URI by removing any parameters and/or fragments.
"""
base_uri = uri.split("#", 1)[0]
base_uri = base_uri.split("?", 1)[0]
return base_uri | 8655b8717261dcd419f1c3ac0153ec51d348ca57 | 11,443 |
def sequalsci(val, compareto) -> bool:
"""Takes two strings, lowercases them, and returns True if they are equal, False otherwise."""
if isinstance(val, str) and isinstance(compareto, str):
return val.lower() == compareto.lower()
else:
return False | 5e96233ead44608ce70ad95e936c707af8bcb130 | 11,444 |
def n_rots(request):
"""Number of rotations in random layer."""
return request.param | 93d55281a83be9e4acba951d1de8a9e7d5081182 | 11,445 |
from typing import Any
def try_to_cuda(t: Any) -> Any:
"""
Try to move the input variable `t` to a cuda device.
Args:
t: Input.
Returns:
t_cuda: `t` moved to a cuda device, if supported.
"""
try:
t = t.cuda()
except AttributeError:
pass
return t | 9b6643f169c1eb8fc65de8b1bff55668f8cba950 | 11,446 |
def group(seq, groupSize, noneFill=True):
"""Groups a given sequence into sublists of length groupSize."""
ret = []
L = []
i = groupSize
for elt in seq:
if i > 0:
L.append(elt)
else:
ret.append(L)
i = groupSize
L = []
L.appe... | a7314803cb3b26c9bd69a2dbc2c0594181085c2c | 11,451 |
def not_safe_gerone(a, b, c):
"""
Compute triangle area from valid sides lengths
:param float a: first side length
:param float b: second side length
:param float c: third side length
:return: float -- triangle area
>>> not_safe_gerone(3, 4, 5)
6.0
"""
p = (a+b+c)/2
return ... | 499cf398158d170363ea22096b44ea16e402a23a | 11,465 |
def sqs_lookup_url(session, queue_name):
"""Lookup up SQS url given a name.
Args:
session (Session) : Boto3 session used to lookup information in AWS.
queue_name (string) : Name of the queue to lookup.
Returns:
(string) : URL for the queue.
Raises:
(boto3.ClientError):... | 4f7bfb98d10a372b3b07f270e2a25e3227732f41 | 11,474 |
def get_government_factions(electoral_term):
"""Get the government factions for the given electoral_term"""
government_electoral_term = {
1: ["CDU/CSU", "FDP", "DP"],
2: ["CDU/CSU", "FDP", "DP"],
3: ["CDU/CSU", "DP"],
4: ["CDU/CSU", "FDP"],
5: ["CDU/CSU", "SPD"],
... | cfd502f81ebb0536432da4974ab9f25724dc83df | 11,475 |
def VectorVector_scalar(vectorA, vectorB):
""" N diemnsional. Return a float as a scalar resulting from vectorA * vectorB"""
result = 0
for i in range(0, len(vectorA)):
result += vectorA[i] * vectorB[i]
return result | c7f0448a05573b8ddba63ed7a8262072ffcda38f | 11,476 |
def eval_shift_distance(shift, reg_matches):
"""
Compute the distance in characters a match has been shifted over.
"reg_matches" is the set of regular matches as returned by find_regular_matches().
The distance is defined as the number of characters between the shifted match
and the closest regula... | aceb705d0f89cacb6f7738667e6dfaf803bed85c | 11,478 |
def get_common_basename(paths):
""" Return common "basename" (or "suffix"; is the last component of path)
in list "paths". Or return None if all elements in paths do not share a common last
component. Generate an error if any path ends with a slash."""
if len(paths) == 0:
return None
# get... | e2189244ef556038caea24ba6aa85792f34868db | 11,479 |
def contains_all_required_firewalls(firewall, topology):
"""
Check that the list of firewall settings contains all necessary firewall settings
"""
for src, row in enumerate(topology):
for dest, col in enumerate(row):
if src == dest:
continue
if col == 1 an... | a4dbbb5833909e816c5b7568cf75da68c06d9e4c | 11,487 |
def _get_upload_headers(first_byte, file_size, chunk_size):
"""Prepare the string for the POST request's headers."""
content_range = 'bytes ' + \
str(first_byte) + \
'-' + \
str(first_byte + chunk_size - 1) + \
'/' + \
str(file_size)
return {'Content-Range': content... | 3ccfec747ce8f8f31b97489005b1ac421f7c9024 | 11,490 |
def format_uptime(uptime_in_seconds):
"""Format number of seconds into human-readable string.
:param uptime_in_seconds: The server uptime in seconds.
:returns: A human-readable string representing the uptime.
>>> uptime = format_uptime('56892')
>>> print(uptime)
15 hours 48 min 12 sec
"""
... | a6a4544b6754113d0c5ed13a18838770448be6a8 | 11,495 |
def chunker(arrays, chunk_size):
"""Split the arrays into equally sized chunks
:param arrays: (N * L np.array) arrays of sentences
:param chunk_size: (int) size of the chunks
:return chunks: (list) list of the chunks, numpy arrays"""
chunks = []
# sentence length
sent_len = len(arrays[0])... | 42a6867464e32d59a50927e8e88d067fc86f4fa1 | 11,497 |
import requests
import json
def get_device_response(ctx):
"""Return the deserialized JSON response for /stat/device (devices)"""
r = requests.get(
ctx.obj["URL"] + "stat/device",
verify=ctx.obj["VERIFY"],
cookies=ctx.obj["COOKIES"],
)
return json.loads(r.text) | a763e3a5aedb0b2124244424f44fe7aa56bb8963 | 11,500 |
import math
def calculate_ransac_iterations(min_points_per_sample, outlier_rate, desired_success_probability):
"""Estimates how many RANSAC iterations you should run.
Args:
min_points_per_sample: Minimum number of points to build a model hypothesis.
outlier_rate: Float, 0-1, how often outlier... | cafca93f052770f695f90d5f37e088e880fd0c45 | 11,506 |
def generate_graph(data, course_to_id):
"""
Method to read the JSON and build the directed graph of courses (= DAG of course IDs)
The graph is represented in an adjacency list format
:return: A graph in adjacency list format, with vertices as course IDs and directed edges implying prerequisite relation
:rtype: L... | 0a6fe305e39bd812e000a1d22d2374636a7900b2 | 11,513 |
from typing import Optional
import math
def round_for_theta(
v: float,
theta: Optional[float]
) -> float:
"""
Round a value based on the precision of theta.
:param v: Value.
:param theta: Theta.
:return: Rounded value.
"""
if theta is None:
return v
else:
... | ef6d18df588df8a80be9dc6c9b7f9104e3109d69 | 11,514 |
from typing import List
def split_badge_list(badges: str, separator: str) -> List[str]:
"""
Splits a string of badges into a list, removing all empty badges.
"""
if badges is None:
return []
return [badge for badge in badges.split(separator) if badge] | 6dc53d45cc8390422e5a511e39475ae969bf37c9 | 11,516 |
def column(matrix, col):
"""Returns a column from a matrix given the (0-indexed) column number."""
res = []
for r in range(len(matrix)):
res.append(matrix[r][col])
return res | f5214b5a41bf265f6892fdfd9422061b02f61c63 | 11,523 |
import re
def parse_scenario_gtest_name(name):
"""Parse scenario name to form acceptable by gtest"""
# strip
name = name.strip()
# space and tab to _
name = name.replace(" ", "_").replace("\t", "_")
# remove dots. commas
name = re.sub('[^a-zA-Z_]+', '', name)
# make lower
name = na... | faca8406a6b033536c3f9e0da21d9dc818fd2a7e | 11,524 |
import json
def load_json(filepath):
"""Load a json file.
Args:
filepath (str): A path to an input json file.
Returns:
dict: A dictionary data loaded from a json file.
"""
with open(filepath, 'r') as f:
ret = json.load(f)
return ret | c64fec0c861d223e28001051906e32d3aa9ffc7a | 11,525 |
def statement(prop, value, source):
"""
Returns a statement in the QuickStatements experted format
"""
return "LAST\t{}\t{}\tS854\t\"{}\"".format(prop, value, source) | 2c0b6ea8f757c8586ca462d85fca3b9d281adb26 | 11,529 |
import json
def get_config_db_json_obj(dut):
"""
Get config_db content from dut
Args:
dut (SonicHost): The target device
"""
config_db_json = dut.shell("sudo sonic-cfggen -d --print-data")["stdout"]
return json.loads(config_db_json) | 92920197b2056d889ffb76ff66e01061f0654032 | 11,530 |
def check_sender(tx: dict, sender: str) -> bool:
"""
:param tx: transaction dictionary
:param sender: string containing sender's address
:return: boolean
"""
if tx["events"][0]["sub"][0]["sender"][0]["account"]["id"] == sender:
return True
return False | 785c8453b876a2ca2b14f374836987c77a01f882 | 11,534 |
def is_prime_det(n):
"""
Returns <True> if <n> is a prime number, returns <False> otherwise. It
uses an (optimized) deterministic method to guarantee that the result
will be 100% correct.
"""
# 2 and 3 are prime numbers
if (n <= 3):
return (n > 1)
# Corner cases to speed up the ... | 65ee46364510f45485c7d95ee0973d42ebc81d34 | 11,535 |
def zippify(iterable, len=2, cat=False):
"""
Zips an iterable with arbitrary length pieces
e.g. to create a moving window with len n
Example:
zippify('abcd',2, cat=False)
--> [('a', 'b'), ('b', 'c'), ('c', 'd')]
If cat = True, joins the moving windows together
... | def01ff9f940009f80c312fe9ee07b282733d99b | 11,540 |
def sanitize_int(value):
"""
Sanitize an input value to an integer.
:param value: Input value to be sanitized to an integer
:return: Integer, or None of the value cannot be sanitized
:rtype: int or None
"""
if isinstance(value, str):
try:
return int(value)
except... | 5c0481c0c7414f5fdba946f66346b3233ffe6644 | 11,542 |
def _get_dir_names(param):
"""Gets the names of the directories for testing the given parameter
:param param: The parameter triple to be tested.
:returns: A list of directories names to be used to test the given
parameter.
"""
return [
'-'.join([param[0], str(i)])
for i in ... | 8ef2ad44127402987a26ec0bc6bfffc372f3c64d | 11,548 |
def bool_converter(value: str) -> bool:
"""
:param value: a string to convert to bool.
:return: False if lower case value in "0", "n", "no" and "false", otherwise, returns the value returned
by the bool builtin function.
"""
if value.lower() in ['n', '0', 'no', 'false']:
return False
... | 10251dfbb0200297d191dce1eb20237aed9e5ac9 | 11,550 |
def heat_stor(cp, spm, tdif):
"""
Calculate the heat storage
Args:
cp: specific heat of layer (J/kg K)
spm: layer specific mass (kg/m^2)
tdif: temperature change (K)
"""
return cp * spm * tdif | 397736e091a2cea09328cbf7f6e81c99db6fe384 | 11,551 |
from typing import Any
from typing import Optional
from typing import IO
import yaml
def dump_yaml(data: Any, stream: Optional[IO[str]] = None) -> Optional[str]:
"""Dump YAML to stream or return as string."""
if stream is not None:
return yaml.safe_dump(data, stream, default_flow_style=False)
else... | 7ff998722e5d7754f83e960127bbed39d4a8d728 | 11,552 |
def get_link_to_referenced_comment(subreddit_name, user_note):
"""Extracts the id of the comment referenced by the usernote and formats it as a reddit-internal link"""
link_code_segments = user_note['l'].split(',')
if len(link_code_segments) == 3:
submission_id = link_code_segments[1]
commen... | cb41189bc05962e37fdf91aa3e5c53c64acb9400 | 11,553 |
def _detects_peaks(ecg_integrated, sample_rate):
"""
Detects peaks from local maximum
----------
Parameters
----------
ecg_integrated : ndarray
Array that contains the samples of the integrated signal.
sample_rate : int
Sampling rate at which the acquisition took place.
... | ab9dd461f65095f048942ab8b8c069c456ea4933 | 11,554 |
import itertools
def normalise_text(text):
"""
Removes leading and trailing whitespace from each line of text.
Removes leading and trailing blank lines from text.
"""
stripped = text.strip()
stripped_lines = [line.strip() for line in text.split("\n")]
# remove leading and trailing empty li... | 52ab40cfa4c39ed194fa71aa28d70f5fa737d70c | 11,560 |
import sqlite3
def sqlite3get_table_names(sql_conn: sqlite3.Connection):
"""For a given sqlite3 database connection object, returns the table names within that database.
Examples:
>>> db_conn = sqlite3.connect('places.sqlite')\n
>>> sqlite3get_table_names(db_conn)\n
['moz_origins', 'm... | 0cb1ba2ba475268d39fef8bdbe044436f51c4f07 | 11,563 |
from typing import List
from typing import Any
def sort(xs: List[Any]) -> List[Any]:
"""
Sort the list `xs` with the python `sort` function
and return the sorted function. The given list is not modified.
Parameters
----------
xs
A list.
Returns
-------
xs_sorted
... | 706190a533c19b6a7ea4baf540823ca73406560b | 11,566 |
import pickle
def read_solver(filename):
"""
This function reads a .pk1 file.
Parameters:
filename (str): A file name or path to file excluding file extension.
Returns:
Content of the loaded .pk1 file.
"""
try:
file = open(filename+'.pk1', 'rb')
except IOError:
... | da7bcfb75af1edde3d43091fdbc5c1829c13e5e0 | 11,570 |
import inspect
def get_argument_help_string(param: inspect.Parameter) -> str:
"""Get a default help string for a parameter
:param param: Parameter object
:type param: inspect.Parameter
:return: String describing the parameter based on the annotation and default value
:rtype: str
"""
help_... | 7381591ce45591bf1aef62280fc4b98e57969576 | 11,573 |
def nested_select(d, v, default_selected=True):
"""
Nestedly select part of the object d with indicator v. If d is a dictionary, it will continue to select the child
values. The function will return the selected parts as well as the dropped parts.
:param d: The dictionary to be selected
:param v: Th... | 84aa16adfb324fef8452966087cbf446d57893d2 | 11,575 |
def is_trans(reaction):
"""Check if a reaction is a transporter."""
return len(reaction.metabolites) == 1 | a0b9be30b4a88156e7a89cf48b8ecb76345e4cab | 11,578 |
def format_tile(tile, tile_format, format_str='{x} {y} {z}'):
"""Convert tile to necessary format.
Parameters
----------
tile: pygeotile.tile.Tile
Tile object to be formatted.
tile_format: str
Desired tile format. `google`, `tms`, or `quad_tree`
format_str: str
String to... | e7ce2653f49f0c535bb3ea0a0c4bec3b48a74331 | 11,579 |
def percent(a, b):
"""
Given a and b, this function returns a% of b
"""
return (a/100)*b | d8adae353bb1b7aba6eb0149af065182bf752449 | 11,580 |
import math
def filter_none(mongo_dict):
"""Function to filter out Nones and NaN from a dict."""
for key in list(mongo_dict.keys()):
val = mongo_dict[key]
try:
if val is None or math.isnan(val):
mongo_dict.pop(key)
except Exception:
continue
... | 6853a7153f98466dc00d262bfaf4a63db1b0cd5c | 11,581 |
import re
def fetch_geneid(fn):
"""
fetch gene id from GTF records
gene_id "FBgn0267431"; gene_name "Myo81F"; gene_source "FlyBase"; gene_biotype "protein_coding";
"""
assert isinstance(fn, str)
ps = fn.split(';')
dn = {}
for i in fn.split(';'):
if len(i) < 8: # shortest field
... | c3ddb9c5c820799800131c6e11dc2ef91d4556c1 | 11,587 |
def fieldsMatch(f0, f1):
"""
Checks whether any entry in one list appears in a second list.
"""
for f in f0:
if f in f1: return True
return False | 172772fca613fe97e32bb6860c3bd217b643fe2d | 11,588 |
def list_to_str(lst):
"""convert list/tuple to string split by space"""
result = " ".join(str(i) for i in lst)
return result | 1e6c59f834b98b1d49ca1c0919d2d976fd1de1de | 11,589 |
def extract_bias_diagonal(module, S, sum_batch=True):
"""Extract diagonal of ``(Jᵀ S) (Jᵀ S)ᵀ`` where ``J`` is the bias Jacobian.
Args:
module (torch.nn.Conv1d or torch.nn.Conv2d or torch.nn.Conv3d): Convolution
layer for which the diagonal is extracted w.r.t. the bias.
S (torch.Ten... | b2f8aaefa22d1ae915c59f80f98341059a4d1ad3 | 11,590 |
from gzip import GzipFile
from typing import Any
import json
def gzip_load_var(gzip_file:str) -> Any:
"""
Load variable from .json.gz file (arbitrary extension!)
Parameters
----------
gzip_file : str
Filename containing the gzipped JSON variable
Returns
-------
var : Any
... | b9f6fbad33b40bb18a1418f3134b0889d5344183 | 11,595 |
def category_table_build(osm_table_name, categorysql):
"""
Returns an SQL OSM category table builder
Args:
osm_table_name (string): a OSM PostGIS table name
Returns:
sql (string): a sql statement
"""
sql = ("INSERT INTO category_%s (osm_id, cat) "
"SELECT DISTINCT o... | 147812bb68845e3fd0dca7e805f610d26428eac3 | 11,601 |
def count_helices(d):
"""Return the helix count from structure freq data."""
return d.get('H', 0) + d.get('G', 0) + d.get('I', 0) | 8469adabac42937009a1f8257f15668d630a7ca8 | 11,603 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.