content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_filename_safe_string(string, max_length=146):
"""
Converts a string to a string that is safe for a filename
Args:
string (str): A string to make safe for a filename
max_length (int): Truncate strings longer than this length
Warning:
Windows has a 260 character length lim... | 5b7815c092d566e875cdda4466f716d48ed62671 | 691,295 |
def is_user_active(user_obj):
"""
Helps to find user is active or not.
Returns boolean value True or False
:param user_obj: user queryset of User model
:return: boolean value
"""
if user_obj.is_active:
return True
return False | 1008ab560600803988b32b40ca9c861df0b15ce3 | 691,297 |
from datetime import datetime
def format_datetime(timestamp):
"""Format a timestamp for display."""
return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M') | f841d74e381f4524a7fc428feb4111eb5f282538 | 691,298 |
def read_monoisotopic_mass_table(input_file):
"""
Given a tab-separatedd input file with amino acids (as capital letters)
in the first column, and molecular weights (as floating point numbers)
in the second column - create a dictionary with the amino acids as keys
and their respective weights as values.
"""
... | b14c3353a4a71b23e540f041abc170dc6b2f6942 | 691,299 |
from typing import Mapping
def _mapping2list(map: Mapping):
"""Converts a mapping to a list of k1.lower():v1.lower(), k2:v2, ..."""
return [f"{str(key).lower()}:{str(value).lower()}" for key, value in map.items()] | 7cee135c883ce1ff8dcb48103d1718e4bc76ab25 | 691,301 |
def GetBlockIDs(fp):
"""
Get the information about each basic block which is stored at the end
of BBV frequency files.
Extract the values for fields 'block id' and 'static instructions' from
each block. Here's an example block id entry:
Block id: 2233 0x69297ff1:0x69297ff5 static instructio... | 7434d30db1dfb4ce34469e9c900a6a80cb487bd7 | 691,306 |
import functools
def lcm(l):
"""least common multiple of numbers in a list"""
def _lcm(a, b):
if a > b:
greater = a
else:
greater = b
while True:
if greater % a == 0 and greater % b == 0:
lcm_ = greater
break
... | 219eb5bbb50ec6f23979db489f42a86b4feef3cc | 691,307 |
def map_value(value, inmin, inmax, outmin, outmax):
"""Map the value to a given min and max.
Args:
value (number): input value.
min (number): min input value.
max (number): max input value.
outmin (number): min output value.
outmax (number): max output value.
Return... | c44e1c16589e86835321ae883724e514f0a043d1 | 691,312 |
from datetime import datetime
def to_timestamp(date):
"""Convert string to UNIX timestamp."""
ts = datetime.strptime(date, '%Y-%m-%dT%H:%M:%SZ').timestamp()
return ts | b33e3297739acb4b5ed73ab4a09526f7b2bf8778 | 691,316 |
from pathlib import Path
def get_n_bytes(file: Path, n):
"""
Return the first n bytes of filename in a bytes object. If n is -1 or
greater than size of the file, return all of the file's bytes.
"""
with file.open("rb") as in_file:
return in_file.read(n) | 4f791ef60393190b6d367271d21b2f07cdd007c1 | 691,317 |
def _partial_fn(fn, *args, **kwargs):
"""Partial apply *args and **kwargs after the shape, dtype, key args."""
# Dummy value here is so that we can use lax.switch directly.
def f(shape, dtype, key, _):
return fn(shape, dtype, key, *args, **kwargs)
return f | a0f1d0fa86f7dd4a1ad6c7241a03895966b6725a | 691,320 |
def accuracy(y_hat, y):
"""Get accuracy."""
return (y_hat.argmax(axis=1) == y).mean().asscalar() | 9c63e1d8b7e06dc278b2965abb3931cd0f6208c7 | 691,321 |
def get_velocity_line(pt, vx, vy):
"""get line slope and bias from a start point and x, y change velocity,
y = slope*x + bias
"""
slope, bias = None, None
if vx != 0:
slope = vy / vx
bias = pt[1] - slope * pt[0]
return slope, bias | 4b32259c245f056881743f108ff617c2c49ac49c | 691,331 |
def omrs_datetime_to_date(value):
"""
Converts an OpenMRS datetime to a CommCare date
>>> omrs_datetime_to_date('2017-06-27T00:00:00.000+0000') == '2017-06-27'
True
"""
if value and 'T' in value:
return value.split('T')[0]
return value | f3728a47b64781842ce353aacec70b0cfe104f2c | 691,333 |
def default(default_value, force=False):
"""
Creates a function which allows a field to fallback to a given default
value.
:param Any default_value: The default value to set
:param bool force: Whether or not to force the default value regardless of a
value already being prese... | c6a56d976131e9d712e63b73ac09ddb6b0acedc6 | 691,334 |
def filter_d(mzs, rts, ccss, data):
"""
filter_d
description:
a helper function for filtering data
given M/Z, RT, CCS ranges and a DataFrame containing data,
find and returns all data within that range.
* CCS tolerance is absolute in this case, NOT a percentage *
parameters:
... | 065f27bed9d5b04dcd1eaa6b48b8466c6847d540 | 691,335 |
from typing import List
def flatten(lst: List) -> List:
"""Flatten a list.
"""
return [item for sublist in lst for item in sublist] | 58ce2d954bd80b9a8a60f2eb20803761a5ef8052 | 691,337 |
def make_hit(card, cards, deck):
"""
Adds a card to player's hand
"""
if card in deck:
cards.append(card)
deck.remove(card)
return cards | 2420676fa793d07ee2674d2870428eeb6d580a97 | 691,338 |
import math
def Expectation(Ra, Rb):
""" Calculates the 'Expectation' value following the original formula """
return 1.0 / (1 + math.pow(10, -((Ra - Rb) / 8))) | c7675790f49155e29fe857ee1ea7924e7227d5fd | 691,340 |
from typing import Optional
import pathlib
def _log_figure_path(path: Optional[pathlib.Path]) -> Optional[pathlib.Path]:
"""Adds a suffix to a figure path to indicate the use of a logarithmic axis.
If the path is None (since figure should not be saved), it will stay None.
Args:
path (Optional[pa... | 381bde67a89f0f61d7bdb9a9f2ea033664e6fab0 | 691,342 |
def label(self):
"""
Returns:
label (string): name for the hazard category
"""
try:
value = self._label
except AttributeError:
value = None
return value | 0cc08e0b62420f9eb92da64b4636191c72306091 | 691,344 |
def group(n, lst, discard_underfull = False):
"""Split sequence into subsequences of given size. Optionally discard or
include last subsequence if it is underfull
"""
out = []
for i in range(0, len(lst), n):
out.append(lst[i:i+n])
if discard_underfull and len(out[-1]) < n:
out.p... | 5d96885b92b0f470239723554eed14fe276644c0 | 691,348 |
from typing import Optional
def fancy_archetype_name(position: str, archetype: str) -> Optional[str]:
"""
If given a non-goalie position and a string 'passer', 'shooter', or 'deker' (case insensitive), returns a string corresponding
to proper name per rulebook. Returns None otherwise.
"""
position... | fcca0505f722856037274a22ac0c47e6c8baff4f | 691,349 |
from bs4 import BeautifulSoup
def is_single_media(text):
"""
Judge whether the paragraph is an single media.
:param text: one paragraph string.
:return: bool.
"""
soup = BeautifulSoup(text, 'lxml')
# ONE <a> tag here, return True
if soup.select('a'):
anchor = soup.select('a')... | 3256778f9668ad432b8f0a6e0e620ac49761dafc | 691,350 |
def center_low_freq_2d(x):
"""Be x a multidimensional tensor. Along the last two dimensions reorder the
vector.That is, for the last dimension assume we have
[x_0, x_1, ..., x_{n-1}]. Reorder the tensor along the given
dimesion as:
- if n is even:
[x_{n/2}, x_{n/2+ 1}, ..., x_{n-1}, x_0, x_2, .... | 918b23a407dc76d3743160559ded64528e5b29c0 | 691,351 |
from typing import Dict
from typing import Any
def validObject(object_: Dict[str, Any]) -> bool:
"""
Check if the Dict passed in POST is of valid format or not.
(if there's an "@type" key in the dict)
:param object_ - Object to be checked
"""
if "@type" in object_:
return T... | 6c40ad1cef0a8f056d2e00c9a7632108bfd2f506 | 691,353 |
def none_if_invalid(item):
"""
Takes advantage of python's 'falsiness' check by
turning 'falsy' data (like [], "", and 0) into None.
:param item: The item for which to check falsiness.
:return: None if the item is falsy, otherwise the item.
"""
return item if bool(item) else None | d19476af100d85590d6357ad8677cbaca18e26b4 | 691,356 |
def makeIterable(item):
"""
Takes as argument or an iterable and if it's not an iterable object then it
will return a listiterator.
"""
try:
iterable = iter(item)
except TypeError:
iterable = iter([item])
return iterable | 5ec952ed2f1c9b0761aa5396a57da6271c7cd6dd | 691,359 |
def geometrical_spreading(freq, dist, model="REA99"):
"""
Effect of geometrical spreading.
Args:
freq (array):
Numpy array of frequencies for computing spectra (Hz).
dist (float):
Distance (km).
model (str):
Name of model for geometric attenuation... | cb03585fc855b8ec565bcc25c37073ec9fd0f1c8 | 691,360 |
import unicodedata
def _is_punctuation(char):
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anyways, f... | ac4eeeeceba447f85cb61d792237c930d9c131f9 | 691,361 |
def glue_pair(code1, code2):
"""Glue two pieces of code."""
return code1 + code2 | 030af6fdb333fd8927c3af192e7563d1e285eaad | 691,364 |
def cleanList(aList):
"""
Returns aList with any duplicates removed
"""
return list(set(aList)) | ab8eaa8556bf868beb32100ad5897302d9551eda | 691,365 |
def collapse_list(the_list):
""" Collapses a list of list into a single list."""
return [s for i in the_list for s in i] | 4a693970ce2bf7baa4a43bef6c3778d2381a2487 | 691,367 |
from functools import reduce
def bytes_to_int(bytes):
"""
Convert bytes to integer
Args:
bytes(bytes): bytes to be converted
Returns:
int
Examples:
>>> bytes_to_int(b'\xde')
222
"""
return reduce(lambda s, x: (s << 8) + x, bytearray(bytes)) | e771a3ebd4d90d524e48f34ab0fe51e7f6babf90 | 691,368 |
def format_git_describe(git_str, pep440=False):
"""format the result of calling 'git describe' as a python version"""
if git_str is None:
return None
if "-" not in git_str: # currently at a tag
return git_str
else:
# formatted as version-N-githash
# want to convert to ve... | 38f5c4787d91e4abc2771499e9f62703fa2a3150 | 691,375 |
import requests
def image_metrics(ID, filename):
"""
GET image metrics from server
Args:
ID (str): user name
Returns:
r7.json() (dict): Dictionary containing the image metrics
example: outdict = {
"timestamp": ...,
... | 9d3f6ea202006f9c53f54e242a805f07eb34e35e | 691,376 |
import re
def email_finder(text):
"""returns emails found inside a given text"""
email_finder = re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}')
mo = re.findall(email_finder, text)
return mo | c3a7b04a80936db59a78eec44c146e410ba00124 | 691,377 |
def getservbyname(servicename, protocolname=None): # real signature unknown; restored from __doc__
"""
getservbyname(servicename[, protocolname]) -> integer
Return a port number from a service name and protocol name.
The optional protocol name, if given, should be 'tcp' or 'udp',
otherwise any ... | b0e583205ee1954c7a9b178f0f3e68f05511144c | 691,378 |
def _isValidOpcodeByte(sOpcode):
"""
Checks if sOpcode is a valid lower case opcode byte.
Returns true/false.
"""
if len(sOpcode) == 4:
if sOpcode[:2] == '0x':
if sOpcode[2] in '0123456789abcdef':
if sOpcode[3] in '0123456789abcdef':
return Tru... | dee516c1765aedfc9f7c0044cde29495d54f81f5 | 691,379 |
import six
import re
def is_valid_mac(address):
"""Return whether given value is a valid MAC."""
m = "[0-9a-f]{2}(:[0-9a-f]{2}){5}$"
return (isinstance(address, six.string_types)
and re.match(m, address.lower())) | 12d84e3e18bf51a48270639e59a3c4ce39d58e84 | 691,388 |
def group_by_clauses(selectable):
"""Extract the GROUP BY clause list from a select/query"""
return selectable._group_by_clauses | ce639e2acf78ead54f7f43ec91298dc95cfd0f27 | 691,390 |
def format_nmmpmat(denmat):
"""
Format a given 7x7 complex numpy array into the format for the n_mmp_mat file
Results in list of 14 strings. Every 2 lines correspond to one row in array
Real and imaginary parts are formatted with 20.13f in alternating order
:param denmat: numpy array (7x7) and com... | a39dfac693e4acd7632deebef416d27cf18df71e | 691,392 |
def _set_default_application(application_id: int, type_id: int) -> int:
"""Set the default application for mechanical relays.
:param application_id: the current application ID.
:param type_id: the type ID of the relay with missing defaults.
:return: _application_id
:rtype: int
"""
if applic... | 5a162670c144cd37299caf728ca8cb4da87d9426 | 691,395 |
def arb_func(arg):
"""Arbitrary function just returns input."""
return arg | e09e2bc688d0d9c2c2f0cc5cfa8ae6ec4e5eadfb | 691,396 |
def str2bool(str):
"""
Converts a string to a boolean value. The conversion is case insensitive.
:param str: string to convert.
:type str: string
:returns: True if str is one of: "yes", "y", "true", "t" or "1".
:rtype: bool
"""
return str.lower() in ("yes", "y", "true", "t", "1... | 95ad6a99e004e304a160e4edb9bc57bec22bf3d8 | 691,398 |
def get_pixel_info(local_info, d_behind, obs_range, image_size):
"""
Transform local vehicle info to pixel info, with ego placed at lower center of image.
Here the ego local coordinate is left-handed, the pixel coordinate is also left-handed,
with its origin at the left bottom.
:param local_info: lo... | a0aaa8accdbb9bab6102b9f8e9895986376c594e | 691,402 |
def _joinNamePath(prefix=None, name=None, index=None):
"""
Utility function for generating nested configuration names
"""
if not prefix and not name:
raise ValueError("Invalid name: cannot be None")
elif not name:
name = prefix
elif prefix and name:
name = prefix + "." + ... | fb26dc39ded907cefc1a319d6d0692e67f8c5007 | 691,404 |
import datetime
import time
def convert_to_seconds(minutes):
"""
Return minutes elapsed in time format to seconds elapsed
:param minutes: time elapsed
:return: time elapsed in seconds
"""
if minutes == '-16:0-':
return '1200' # Sometimes in the html at the end of the game the ti... | 5d841de245cc6790a9a9d15c998406927ffda5a6 | 691,407 |
def parse_typename(typename):
"""
Parse a TypeName string into a namespace, type pair.
:param typename: a string of the form <namespace>/<type>
:return: a tuple of a namespace type.
"""
if typename is None:
raise ValueError("function type must be provided")
idx = typename.rfind("/")
... | 7770939cbe7d6e7afabb8e0679380836977f17aa | 691,412 |
from typing import Tuple
def min_or_max_index(L: list, minimum: bool) -> Tuple[int, int]:
""" If the Boolean parameter refers to True
the function returns a tuple containing the minimum and its index;
if it refers to False,
it returns a tuple containing the maximum and its index
>>> min_or_max_ind... | e2f0f572f248fec946690cc586bd4faf326aa699 | 691,414 |
def get_from_cache(key, default_value=None, ctx=None):
"""Returns value from the context cache.
:param str key: String with the key.
:param obj default_value: Optional default value, if the
key is not found inside the cache this value will be
returned, defaults to None.
:param obj ctx: ... | 4a63525802b7076e5b196269c3fc43fd198039ff | 691,416 |
def is_number(word):
""" Function that returns 'NUM' if a shipo word is a number or False if not
:param word: a word to be evaluated
:type word: str
:returns: 'NUM' if a shipo word is a number or False if not
:rtype: str
:Example:
>>> import chana.ner
>>> c... | 45daa79eff17c93e201b03082bbea3c05c383d33 | 691,418 |
from typing import Dict
from typing import Any
import uuid
def make_test_experiment_config(config: Dict[str, Any]) -> Dict[str, Any]:
"""
Create a short experiment that based on a modified version of the
experiment config of the request and monitors its progress for success.
The short experiment is cr... | 72ee62a9b6fa977aaff6f0621e18e0cdb0a8a0bb | 691,419 |
def operation_jnz(register, register_check, jump_by):
"""Jump operation. Jump if register_check is not 0."""
if register.get(register_check, register_check) != 0:
return jump_by | bfeca2efbb7389c21749497db73e624d37faef62 | 691,420 |
from typing import List
def increment_index(index: List[int], dims: List[int]) -> bool:
"""Increments an index.
Args:
index: The index to be incremented.
dims: The dimensions of the block this index is in.
Returns:
True iff the index overflowed and is now all zeros again.
"""... | 833e0baa9c29348067102ef6fe530e45b91ff988 | 691,421 |
def add_up_errors(list_keyerror):
"""
#################################################################################
Description:
Adds in one string the given keyerrors from the list of keyerrors
#################################################################################
:param list_ke... | 62e61fa97dc3bfcd5f62d312d3f573a730479dde | 691,424 |
import random
def _create_list_of_floats(n):
"""Create a list of n floats."""
list = []
for _ in range(n):
list.append(random.random() * 100)
return list | bbade853b1fd091aa157ac81d6ee3b636f723a7b | 691,425 |
def counts_in_out_packets(packets):
"""
Counts the number of packets in & out in the array packets
@param packets is a list of packets, structured as follows: `[(time, direction)]`
@return tuple `(num_packets_in, num_packets_out)`
"""
packets_in, packets_out = [], []
for val in packets:
... | c60186ba48764e019204d2088ea554fffb999f7b | 691,426 |
from typing import Tuple
from datetime import datetime
def getStartDatetime(start: str, days: Tuple) -> datetime:
""" obtain starting datetime from json input
:param start: string representation of the day and time
:param days: a tuple of 3 characters representation of day
:return : datetime instanc... | e4ffdc7743700914fbb3bd677ddc8ecef0fe16a4 | 691,428 |
def mod(a,b):
"""Return the modulus of a with respect to b."""
c = int(a/b)
result = a - b*c
return result | 7f0b961fcd6b83071d66e2cdbb8f5e1f08e0542a | 691,432 |
from typing import Sized
from typing import Iterable
from typing import Mapping
import six
def is_listy(x):
"""Return True if `x` is "listy", i.e. a list-like object.
"Listy" is defined as a sized iterable which is neither a map nor a string:
>>> is_listy(["a", "b"])
True
>>> is_listy(set())
... | ca8f1d6b025990e9083f94ecf0f9e4ec9b168876 | 691,433 |
import pickle
def read_pickle(relnm):
""" Read serialized object from pickle on disk at relnm
Args:
relnm (str) : Relative name/path to pickled object
Returns:
obj (`:obj: unpickled object`)
"""
with open(relnm, 'rb') as f:
obj = pickle.load(f)
print('Loaded object ... | ee9572c38c0c5c18d308c07ef4bad9410ce4048a | 691,434 |
def parse_key_value_config(config_value):
""" Parses out key-value pairs from a string that has the following format:
key: value, key2: value, key3: value
:param string config_value: a string to parse key-value pairs from
:returns dict:
"""
if not config_value:
return {}
... | f00c79d85e71364db58bfb5b91fb2b8654ebe75c | 691,436 |
def fileno(fil):
"""Return the file descriptor representation of the file.
If int is passed in, it is returned unchanged. Otherwise fileno()
is called and its value is returned as long as it is an int
object. In all other cases, TypeError is raised.
"""
if isinstance(fil, int):
return ... | 983243c11a3264c77752a2da5a1d3d33279814ce | 691,439 |
def _count_submissions(conductors):
""" From array of conductors, accumulate submission count. """
return sum(c.num_cmd_submissions for c in conductors) | 9ae42a47fa0284fe28fff572dafad5f601e6bd56 | 691,445 |
def get_headers(oauth_token: str) -> dict:
"""Common headers for all requests"""
return {
'Authorization': f'OAuth {oauth_token}'
} | 285f88b6268f50209432698a12ba2b4b57ecd1ee | 691,446 |
def find_diff(g, start):
"""
g -> Graph of states of nibbles
start -> Starting configuration
Find all possible differentials given a start configuration. The function
returns a tuple containing:
1. the number of rounds
2. a list of all possible end states (second-last round)
3. a list o... | 74f24be96f057e2810fed6de6bb7753be31092d5 | 691,450 |
def sg_to_plato(sg):
"""
Specific Gravity to Degrees Plato
:param float sg: Specific Gravity
:return: Degrees Plato
:rtype: float
:math:`\\text{Plato} = \\frac{\\big(\\text{SG} - 1\\big) \\times 1000}{4}`
The more precise calculation of Plato is:
:math:`\\text{Plato} = -616.868 + 111... | cf689927fb64d5a9108b28626dd324982c0ce776 | 691,451 |
from typing import List
from typing import Dict
from typing import Tuple
def replace_variables(
sentence: List[str], sentence_variables: Dict[str, str]
) -> Tuple[List[str], List[str]]:
"""
Replaces abstract variables in text with their concrete counterparts.
"""
tokens = []
tags = []
for ... | 4a5111c209a4faf03b96c920af113d086d0c970f | 691,452 |
def num_patches(output_img_dim=(3, 256, 256), sub_patch_dim=(64, 64)):
"""
Creates non-overlaping patches to feed to the PATCH GAN
(Section 2.2.2 in paper)
The paper provides 3 options.
Pixel GAN = 1x1 patches (aka each pixel)
PatchGAN = nxn patches (non-overlaping blocks of the image)
Image... | 612fc2a5de8e560d6b6d79a4db27484e3ea36de0 | 691,456 |
def poly2(x,C0,C1,C2):
"""
Calculate a polynomial function of degree 2 with a single variable 'x'.
Parameters
----------
x : numeric
Input variable.
C0, C1, C2 : numeric
Polynomial coefficients
Returns
-------
numeric
Result of the polynomial function.
... | a37c6bfa7bedef4f24791e802a5a50b651956094 | 691,460 |
import csv
def load_data(dataset_path):
"""
Extracts the relevant data from the dataset given.
Returns {lang: {gloss: [transcription,]}}.
Asserts that there are no entries with unknown or no transcriptions.
"""
data = {} # lang: {gloss: [transcription,]}
with open(dataset_path) as f:
reader = csv.reader... | d7bd2fa760dbb8ec70135eca0e27473baef69213 | 691,461 |
def get_bonds_of_molecule(molecule):
"""
It returns the atom's indexes for all bonds of a molecule.
:param molecule: Mol object with the ligand (Rdkit)
:return: list of tuples with the indexes for each bond
"""
bonding_idx = []
for bond in molecule.GetBonds():
bonding_idx.append((bon... | 5eecdb40b31c1bd32f966594999a029ac75a6347 | 691,465 |
def fahr_to_celsius(fahr):
""" Convert Fahrenheit to Celsius (F-32) + 5/9 """
result_in_celsius = (fahr - 32) + 5/9
return result_in_celsius | 09601a064da209e64d9652be0e7b5fab01cd0038 | 691,466 |
def format_stats(stats: dict) -> str:
"""Prepares stats for logging."""
return ", ".join([f"{k}: {v} commits" for k, v in stats.items()]) | 8c554012e7ff2db2ba6394dcb87541ab668ed31c | 691,468 |
def grandchildren_with_tag(child,tagnames):
"""Return children of child that have tag names in
the given set of tag names"""
ret=[]
for grandchild in child.iterchildren():
if grandchild.tag in tagnames:
ret.append(grandchild)
pass
pass
return ret | 1121345abab69f67abde0ee2b6e4629e71034c61 | 691,469 |
from typing import Counter
def calculate_gc_content1(sequence):
"""
Receives a DNA sequence (A, G, C, or T)
Returns the percentage of GC content (rounded to the last two digits)
"""
counts = Counter(sequence.upper())
gc_content = counts.get("G", 0) + counts.get("C", 0)
at_content = counts.... | acebad90e15a69d9ab52c32826e132e466f926b6 | 691,471 |
def bfalist(self, area="", lab="", **kwargs):
"""Lists the body force loads on an area.
APDL Command: BFALIST
Parameters
----------
area
Area at which body load is to be listed. If ALL (or blank), list
for all selected areas [ASEL]. If AREA = P, graphical picking is
enabl... | acecc25b0f337fae3e39d93682b2c9233630b354 | 691,472 |
from typing import Optional
def parse_float(value: bytes) -> Optional[float]:
"""
Convert bytes to a float.
Args:
value: A bytes value to be converted to a float.
Returns:
A float if the bytes value is a valid numeric value, but
``None`` otherwise.
"""
try:
re... | 2ccf0e19e3b2168750892ef7a675dced438ce4a6 | 691,473 |
def trim_to_peak(peaks, troughs):
"""
Trims the peaks and troughs arrays such that they have the same length
and the first peak comes first.
Args:
peaks (numpy array): list of peak indices or times
troughs (numpy array): list of trough indices or times
Returns:
peaks (n... | 908547e34238fb68576481414df98183b329553e | 691,475 |
def find_all_conditions(path: str) -> set:
"""
Find all unique conditions in given training data file.
:param path: Path to training data.
:return: Set of all the unique available conditions in the file.
"""
cond = set()
with open(path) as f:
for line in f:
split = line.s... | 0e3b355342b1f1a5e95f5fa6d2c6c6fa67f1231f | 691,477 |
def body_mass_index(weight: float, height: float) -> float:
"""Returns body mass index
Parameters
----------
weight
weight in kg
height
height in cm
Returns
-------
float
body mass index
"""
return round(weight / (height / 100) ** 2, 1) | bd05ae4accd4dee5c9839ca950df0c1da5a646db | 691,481 |
def separate_files_and_options(args):
"""
Take a list of arguments and separate out files and options. An option is
any string starting with a '-'. File arguments are relative to the current
working directory and they can be incomplete.
Returns:
a tuple (file_list, option_list)
"""
f... | eae2de9cb93308b78ddf279304a73c6c5e1070e2 | 691,482 |
def search_fields_to_dict(fields):
"""
In ``SearchableQuerySet`` and ``SearchableManager``, search fields
can either be a sequence, or a dict of fields mapped to weights.
This function converts sequences to a dict mapped to even weights,
so that we're consistently dealing with a dict of fields mappe... | ee2150aa62b0897c77e20e99b15ee6d0138e293b | 691,489 |
import functools
import time
def to_timestamp_property(func_to_decorate):
""" A decorator for properties to convert the property value from a
datetime to a timestamp. """
@functools.wraps(func_to_decorate)
def wrapper(instance, value):
""" Closure that converts from datetime to timestamp. """
... | 04a6776284b739d06fbff9620072c91e8ba84c64 | 691,494 |
def format_kmer(seqid, start):
"""
prints out a header with 1-based indexing.
>>> format_kmer('chr3', 1000)
'chr3_1001'
"""
return "%s_%i" % (seqid, start + 1) | 2d2dcd2c00b14e68f5f7a095120ec9c1b4c45a20 | 691,496 |
def find_undefined_value(cbf_handle):
"""Given a cbf handle, get the value for the undefined pixel."""
cbf_handle.find_category(b"array_intensities")
cbf_handle.find_column(b"undefined_value")
return cbf_handle.get_doublevalue() | 9e53dd7ebac6f711e02e1cf77f1d2553a09d9c3b | 691,498 |
import inspect
def args_to_kwargs(tool, args):
"""Use inspection to convert a list of args to a dictionary of kwargs.
"""
argnames = list(inspect.signature(tool).parameters.keys())[1:] # get list of argsnames and remove self
kwargs = {argnames[i]: arg for i, arg in enumerate(args)}
return kwargs | 7b3a8c022bb504348b2564d7ae4f683aa891604e | 691,499 |
from typing import Optional
import re
def guess_wapi_version(endpoint: str) -> Optional[float]:
"""Guess WAPI version given endpoint URL"""
match = re.match(r".+\/wapi\/v(\d+\.\d+)$", endpoint)
return float(match.group(1)) if match else None | 8bc35926d2317916c10e71f1997a9f2dbac047de | 691,500 |
def message_prefix(file_format, run_type):
"""Text describing saved case file format and run results type."""
format_str = ' format' if file_format == 'mat' else ' format'
if run_type == ['PF run']:
run_str = run_type + ': '
else:
run_str = run_type + ':'
return 'Savecase: ' + file_... | 4e08d6aa39f2dc7eeee80250219887c03751fc72 | 691,501 |
from pathlib import Path
def modified_after(first_path: Path, second_path: Path):
"""Returns ``True`` if first_path's mtime is higher than second_path's mtime.
If one of the files doesn't exist or is ``None``, it is considered "never modified".
"""
try:
first_mtime = first_path.stat().st_mtim... | e3628e63f0ed1d220702aa618cf18732077942cf | 691,502 |
import math
def get_from_decomposition(decomposition):
"""Returns a number from a prime decomposition"""
result = 1
for key in decomposition:
result *= math.pow(key, decomposition[key])
return result | ed66dda787f22306643fda8e2ff497b4f2e820cb | 691,510 |
def compute_tolerance(baseline: float, abstol: float, reltol: float) -> float:
""" Computes effective tolerance from a baseline value and relative and absolute tolerances.
:param baseline: the input value
:param abstol: absolute tolerance
:param reltol: relative tolerance
:return: tolerance to use ... | 35c8ccef3b1c330d59aa3e55940f390b414fccca | 691,511 |
def vhdl_bit_name(reg_name, bit_name, number):
"""
Returns a string with a VHDL constant delaration of a bit name and it's
associted number.
"""
return "constant {}_{} : integer := {};\n".format(reg_name, bit_name, number) | f31585c9b019a2398a5d10620af5137f5aeb3de2 | 691,517 |
def getClikedPos(pos, rows, width):
""" Get the col and row of the cliked Spot """
gap = width // rows
y, x = pos
row = y // gap
col = x // gap
return row, col | bf2aaf95bcbce3d71ae6e51b02e2a7f7f694b49f | 691,521 |
def sum2(n):
"""
Take an input of n and return the sum of the numbers from 0 to n
"""
return (n * (n + 1)) / 2 | 10a10f276eaed6894470624c4d7460cdbf057906 | 691,522 |
def find_unique(lst: list) -> list:
"""Find the unique numbers in a list."""
return [i for i in lst if lst.count(i) < 2] | 3a40cf7caa076238a128cee2292d5ddde5970edb | 691,525 |
def generate_placeholder(length, width):
"""
Generate "(%s, %s, %s, ...), ..." for placing parameters.
"""
return ','.join('(' + ','.join(['%s'] * width) + ')' for _ in range(length)) | 28ff2ba22f1bcfcef796f724a878c4e2c7764983 | 691,528 |
def get_caption(attributes, feature, label, group=None):
"""Construct caption from plotting attributes for (feature, label) pair.
Parameters
----------
attributes : dict
Plot attributes.
feature : str
Feature.
label : str
Label.
group : str, optional
Group.
... | 5597ff8ab392a3a2db89752f87c4228a49c6069e | 691,531 |
def get_user_email(user_profile):
"""Get user e-mail address or the default address if user profile does not exist."""
# fallback address
default_email = 'bayesian@redhat.com'
if user_profile is not None:
return user_profile.get('email', default_email)
else:
return default_email | ded1e83507d979751ffb26cf2b0f272e5540c234 | 691,532 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.