content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def __mode2offset(voxel_size, mode='c'):
"""Modes
'c': center
'b': boundary
"""
if mode == 'c':
return voxel_size / 2
elif mode == 'b':
return 0
else:
raise NotImplementedError(f"Unknown offset mode{mode}") | 9bc8ab87e0e60820290d745daf94cf420852d7e0 | 110,432 |
def word(l, h):
"""
Given a low and high bit, converts the number back into a word.
"""
return (h << 8) + l | 32f938fe6a95cb353db7ede14c0a25ecdc19521a | 110,435 |
def fut_has_callback(fut, callback):
"""
Look at the callbacks on the future and return ``True`` if any of them
are the provided ``callback``.
"""
if not fut._callbacks:
return False
for cb in fut._callbacks:
if type(cb) is tuple and cb:
cb = cb[0]
if cb == ... | f850ede1dab02715ae9988800209436be3a48b7f | 110,436 |
def parse_length(text):
""" Parses a file length
>>> parse_length(None)
-1
>>> parse_length('0')
-1
>>> parse_length('unknown')
-1
>>> parse_length('100')
100
"""
if text is None:
return -1
try:
return int(text.strip()) or -1
except ValueError:
... | 925156cab95c5312d441b87165a795dd8a19a919 | 110,441 |
import string
import random
def generate_random_string(
length=25, allowed_chars=string.ascii_letters + string.digits
):
"""
Generate a random string.
:param length: The length of the desired string
:type length: int
:param allowed_chars: The set of allowed characters
:type allowed_chars:... | 2f33997f2d167bba461ee2102e4cccbceebd19fa | 110,442 |
def K(eps):
""" Rayleigh complex dielectric factor
This is basically the K complex factor that defines the Radar dielectric
factor |K|**2. It is useful in Rayleigh theory to define absorption cross
section from its imaginary part
Parameters
----------
eps : complex
nd array of compl... | 545c853edad55ffa05a8e0ba6ca828683522e47e | 110,444 |
def get_pos_from_nltk_tagged_sents(o) :
""" Converts NLTK's tagged sentences into list of list of
universal pos tags."""
r = []
for s in o : # loop through every sentence
pos = []
for w in s : # loop through every token
pos.append(w[1]) # get the pos tag
r.append(... | 8b9faaae4d02b8093a44a69be22175a3cd1e3bb1 | 110,445 |
def modify_spec(config):
"""modify spec values with the sampled config values."""
for key, param in config.items():
if key not in ["steps", "mlflow", "spec"]:
config["spec"].settings[key].value = param
return config | fca88ba490b68c9848beb0d9f423eb9304bd450f | 110,449 |
from typing import Set
def slate_teams(slate: dict) -> Set[str]:
"""Gets teams on given slate
Args:
slate (dict): the slate document
Returns:
Set[str]
"""
return set([sp['team'] for sp in slate['slatePlayers']]) | 96efae352a7094a1c0e7d339386b53adfe135ca4 | 110,453 |
def calculate_field_width(grid):
"""Given a grid with width and height, what should the fixed width of fields be for printing"""
return max(len(str(grid.width)), len(str(grid.height))) | 1bd8fa638f7da255f148b30169e5a63344944881 | 110,458 |
def convertToURL( cPathname ):
"""Convert a Windows or Linux pathname into an OOo URL."""
if len( cPathname ) > 1:
if cPathname[1:2] == ":":
cPathname = "/" + cPathname[0] + "|" + cPathname[2:]
cPathname = cPathname.replace( "\\", "/" )
cPathname = "file://" + cPathname
return cP... | 0ee15a355041c34a7ba0d93cb28dfe64d5d49ef0 | 110,460 |
def set_difference(in_this_set1, but_not_in_this_set2):
"""**set_difference(in_this_set, but_not_in_this_set)** -> Returns the elements that are in the set1 but not on the set2
<code>
Example:
set_difference(set([1, 2, 3, 4]), set([2, 3]))
Returns:
set([1, 4])
</code>
"""
s1 = ... | 78684ae462f80ceaa735784290bfd8555e659b94 | 110,466 |
import random
import string
def generate_test_cases(pattern, length, k):
"""
Generates <k> test cases with text of length <length> containing <pattern>
Args:
pattern (str): A pattern within the text.
length (int): The length of the pattern
k (int): The number of test cases
Re... | 62be3b9e400e2dd84bdd9c74fe12ddf5fed231b6 | 110,470 |
def cleanup_labels(np_data, labels):
"""
Make sure there's the right number of labels. Including making new ones
from scratch if there aren't any
"""
if labels is not None:
if len(labels) != np_data.shape[1]:
err_text = (
'Number of labels, {}, does not match '
... | 8d914a032e7165b4a0a8a9ac621a03b33d9df62d | 110,471 |
def create_warning(scrub_id, file, line, description, tool, priority='Low', query='', suppress=False):
"""This function creates an internal representation of a warning t be used for processing.
Inputs:
- id: Finding identifier of the format <tool><count> [string]
- file: Absolute path to the so... | f03722a1703a24d1ae90b013a661dc9b82945aa9 | 110,476 |
def alcohol_by_volume_alternative(og, fg):
"""
Alcohol by Volume Alternative Calculation
:param float og: Original Gravity
:param float fg: Final Gravity
:return: Alcohol by Volume decimal percentage
:rtype: float
Alternate Formula:
A more complex equation which attempts to provide gr... | 3fc2cc54b91a08ecc3da46f1eecaf802105bf164 | 110,478 |
from typing import List
import calendar
def get_days_of_week(first_day: int = calendar.MONDAY) -> List[str]:
"""Returns a list of ordered days, starting with the specified day."""
calendar.setfirstweekday(first_day)
return (list(calendar.day_name[calendar.firstweekday():])
+ list(calendar.day_... | 6e3feb090b0ee9243ea4a917d10003e84b916225 | 110,483 |
import re
def parse_host_interfaces(hifs):
"""
parse host interfaces
Support 3 formats:
1. Legacy format (non multi-dut): vlan_index
2. new format (multi-dut): dut_index.vlan_index,dut_index.vlan_index
3. new format (multi-dut): dut_index.vlan_index@ptf_port_index,dut_index.vlan_index@ptf_por... | ba1719684463979663d039e144143c2a8cf64fdd | 110,485 |
def default_message()->str:
"""
Returns a default message
"""
return "Seems I do not understand since i only speak 0 and 1.\n\
Just in case, if you need any help, just type 'python main.py [KEYWORD]' on your terminal." | e435febb65cb505106b1e9669cebc5447d20e49b | 110,489 |
def getRawInput(display):
"""
Wrapper around raw_input; put into separate function so that it
can be easily mocked for tests.
"""
return input(display) | 1e5a3e7ca7b416401e4d48b0d424277784eeb974 | 110,495 |
def getcheckinterval(space):
"""Return the current check interval; see setcheckinterval()."""
return space.wrap(space.sys.checkinterval) | 80a29b5c342f6c1fd9be55e6ed2024c6484674bf | 110,496 |
def wooqi(request):
"""
Check if the test is runned with wooqi
"""
return request.config.getoption("--wooqi") | 6d0abcbae0cb32233651dad8f75f3519e8ca4476 | 110,497 |
def lettergrade(value):
"""
Maps grade point average to letter grade.
"""
if value > 3.85:
return 'A'
elif value > 3.5:
return 'A-'
elif value > 3.15:
return 'B+'
elif value > 2.85:
return 'B'
elif value > 2.5:
return 'B-'
elif value > 2.15:
... | 149c6e29a54b199747cf64fe58f28561dda005f3 | 110,503 |
from typing import Union
import math
def _float_to_json(value) -> Union[None, str, float]:
"""Coerce 'value' to an JSON-compatible representation."""
if value is None:
return None
if isinstance(value, str):
value = float(value)
return str(value) if (math.isnan(value) or math.isinf(va... | b1ef0c7af5754d56435ac2f7b8116f03dd4502d9 | 110,504 |
def collatz_sequence(num):
"""collatz sequence - start with positive integer. If it's even, next term
is n/2, otherwise (3n + 1). 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1.
Always ends in 1. This will return [num, n2, n3, n4, ... , 1]
"""
foo = [num]
temp = num
while temp != 1:
if temp % 2 =... | d03c1b3b3de149090e5c79bfe1e589476486c271 | 110,506 |
def make_oh_cols_names(cat_cols_names, categories):
"""
Build names for OneHot encoded categories.
"""
assert(len(cat_cols_names) == len(categories))
oh_names = []
for col_name, col_cats in zip(cat_cols_names, categories):
for cat in col_cats:
oh_names.append(col_name + "_" +... | a9568bda3d5b8e1625e97668db5dee43a41fa3d9 | 110,509 |
def szuszik(a, b):
"""
Szuszik's pairing algorithm is a map from a pair of natural numbers to a unique
natural number.
$\\mathcal{N}\times\\mathcal{N}\\mapsto N$.
Args:
a: int
first integer
b: int
second integer
Returns:
int
Szuszi... | 8eb23ed6f064bcf95327613e95acc21d05a1da2a | 110,511 |
import urllib.request, urllib.error, urllib.parse, socket
def internet_access(timeout=1):
"""Return True if internet is on, else False."""
try:
# Check google.com with numerical IP-address (which avoids
# DNS loopup) and set timeout to 1 sec so this does not
# take much time (google.co... | 6881299f490da708f170f1f659d2f4b6a0ac78df | 110,519 |
def intersect_lines(p1, p2, p3, p4):
"""
Calculates intersection point between two lines defined as (p1, p2)
and (p3, p4).
Args:
p1: (float, float)
Point 1 as (x, y) coordinates.
p2: (float, float)
Point 2 as (x, y) coordinates.
p3: ... | f4e4cb6bc2826b83a2e82df3cb8510fec5cb52e1 | 110,523 |
from typing import Tuple
def get_data_rules(config: dict) -> Tuple[list, list, list, list]:
"""
Uses date configuration to determine which columns are of numeric, date,
categorical type as well as what should be dropped.
Args:
config (dict): Data Configuration
Returns:
Tuple[list... | 7019d357f361838dc00607121715bf5a49c2c378 | 110,527 |
import itertools
def read_metadata(filename, skip, treename):
""" Read the metadata csv file and return values ad a dictionary
"""
temptreedict = {}
with open(filename, 'r') as f:
result = itertools.islice(f, skip, None)
for line in result:
ll = line.strip().split(",")
... | ccf8522afa42d08c3cfd9bcdf868955ab5700677 | 110,528 |
from typing import List
def removeStringEndings( originalText:str, endingsList:List[str] ) -> str:
"""
Go through the given list of endings (in order)
and remove any endings from the end of the string.
"""
newText = originalText
for ending in endingsList:
if newText.endswith( endin... | b1452f656547277e642cd84cd47256fda736e43a | 110,529 |
from pathlib import Path
def _load(exclude_past_answers=False):
"""
Load the full corpus from file,
"""
pkg = Path(__name__).resolve()
path_data = pkg.parent / "mordle" / "data" / "wordle-corpus.txt"
with open(path_data, "r") as f:
lines = f.readlines()
result = [line.strip() for ... | 12baa4eb4eaec03b8fbff460d7588517effe6321 | 110,531 |
def _format_files(files):
"""Format the Mordor files data for display."""
return [
(f"({file['file_type']}) {file['file_path'].split('/')[-1]}", file["file_path"])
for file in files
] | 540993a54debe03d5aad298581c6df0c74fbc80e | 110,532 |
def valid_event(event: list):
"""
Filter out some events that don't provide meaningful information.
The HTML PBP has 8 columns:
['#', 'Per', 'Str', 'Time:El', 'Event', 'Description', 'AWAY On Ice', 'HOME On Ice']
:param event: list of stuff in pbp
:return: boolean
"""
return event[0] ... | c1e32b5abcffa07abf84800596f7ff38795532b0 | 110,539 |
def remove_duplicates(package_leaflets):
"""
Keep only leaflets with unique product_name.
If there is already the leaflet with same product_name - skip this leaflet
:param package_leaflets: array of processed leaflets
:return: array of unique leaflets
"""
# save only leaflets with unique ... | f141b458d98ff497b659fb12eadfe34608d2146c | 110,540 |
import random
def create_nodes(n=300, seed=None):
"""Sample $n$ nodes uniformly at random in the unit square. Each of
the nodes comes with a random time sampled uniformly from [0, n].
# Arguments
n: number of nodes to be sampled
seed: seed for the randomness
# Result
lists ts, ... | 404927bca419eeb45e0340d296802e84d37a9e5a | 110,543 |
def set_bits_high(bits_to_set_high: int, bitwise_data: int):
"""
This function will set bits high based on `bits_to_set_high` in `bitwise_data`;
:param bits_to_set_high: A integer representing the bits to set high in `bitwise_data`
:param bitwise_data: A integer representing the data from which to set b... | d912b7b9a7ad505c4786d738710573b42758ce46 | 110,546 |
import re
def get_dtm_from_backup_name(fname):
"""
Returns the date time string from our automated backup filenames
"""
p = re.compile(r"^db\-v[^_]+_(?P<dtm>[\d\-_]+).*\.dump$")
m = p.search(fname)
if m:
label = m.groups("dtm")[0]
date = label.split("_")[0]
time = label... | 80a089bd43eadfab666e2b791dabfcce113c45e5 | 110,549 |
def annotations_with_overlaps_with_clip(df, begin, end):
"""Determine if any rows overlap with current segment
Args:
df: A dataframe containing a Raven annotation file
begin: The begin time of the current segment (unit: seconds)
end: The end time of the current segment (unit: se... | 12fc08b2c2fc056829d9207abe4c9e76739b7d1e | 110,552 |
def all_bits_for_opcodes(instructions):
""" Returns bit numbers occupied by any opcode of at least one of the
instructions.
"""
return instructions[0].opcode_bits.union(
*[i.opcode_bits for i in instructions[1:]]
) | 53f174f447477a50510d35de6f7562b029a39719 | 110,555 |
import struct
def get_uint16(s: bytes) -> int:
"""
Get unsigned int16 value from bytes
:param s: bytes array contains unsigned int16 value
:return: unsigned int16 value from bytes array
"""
return struct.unpack('H', s)[0] | 268308b8427389195ed2090c602859b3fb2582f5 | 110,556 |
def applies(inverter, section):
"""Returns whether the inverter applies for given configuration section."""
if 'IP address' not in section or not section['IP address']:
return True
if section['IP address'] == inverter.addr[0]:
return True
return False | f8a551307e3bd2c1fadaca88964a3a7e12e13669 | 110,558 |
def _content_length(line):
"""Extract the content length from an input line."""
if line.startswith(b'Content-Length: '):
_, value = line.split(b'Content-Length: ')
value = value.strip()
try:
return int(value)
except ValueError:
raise ValueError("Invalid Co... | bbb03c475fa71d3b70bbfd5ce15af7de502b18a2 | 110,563 |
def add_ordinal(num):
"""Returns a number with ordinal suffix, e.g., 1st, 2nd, 3rd.
Args:
num (int): a number
Returns:
(str): a number with the ordinal suffix
Examples:
>>> add_ordinal(11) == '11th'
True
>>> add_ordinal(132) == '132nd'
True
"""
... | 8a6fc3b4d8fe3dc76dcd6c35ed29fde29b82e0a2 | 110,564 |
def GEOMETRIC_PROPERTIES_0(COORDINATES, ELEMENTS, SECTIONS, I_ELEMENT, AUX_2):
"""
This function assigns the bar element's geometric propertiest of the I_ELEMENT element TYPE_ELEMENT = 0 (Frame element).
Input:
COORDINATES | Coordinates properties | Py Numpy array... | 0971c28d04af0b2e71aacdf7fcb3bf217f3c9ae2 | 110,565 |
def get_column(name: str, worksheet) -> int:
"""Search a row of cells for the string.
Args:
name: The text to search for
columns: The list or generator of columns in the excel sheet
Returns:
Either returns the column number or returns 0 if no column matched the name
"""
fo... | 6f76c7ee6cba495a74965d69ae1cde4338e78e37 | 110,568 |
import string
def sanitize_word(word):
"""
Sanitize unicode word for use as filename
Ascii letters and underscore are kept unchanged.
Other characters are replaced with "-u{charccode}-" string.
"""
allowed_chars = string.ascii_letters + '_'
def sanitize_char(char):
if char in all... | 86b14ed754b39e7bb05594441af9734a3b958b1d | 110,572 |
import re
def add_hl_to_url(url):
""" A function that adds or change language query to english for the given url. """
# Note: Used it before is_playlist_url() or is_video_url().
# Why we need this? For consistency when scraping the information embeded on the page.
# Because youtube support different l... | 7d25e538b2b101b7864f4209dbfa3d90ac820070 | 110,573 |
from typing import Callable
from typing import Any
import click
def _get(func: Callable, pred: Callable, no_error: bool = False) -> Any:
"""
Retrieve the first instance from `func` that matches `pred`.
"""
value = next((elm for elm in func() if pred(elm)), None)
if value or no_error:
retur... | 7823ff5f7e288b844cd2d73462d3a09f3caafa51 | 110,574 |
from typing import Optional
def try_get_only_key_from_collection(collection: Optional[dict]) -> Optional[str]:
"""
3 scenarios:
1 - dict is None or empty -> return None
2 - dict has exactly one item, return its key
3 - dict has more than one item, raise exception
"""
if collection is None ... | de2a4fd161fd1ffc612c36b1d292930b95ca697c | 110,575 |
import math
def get_width(length, full_width):
"""
Returns the number of bits used by Minecraft to represent indices into a
list of the given length.
"""
width = int(math.ceil(math.log(length, 2)))
if width < 4:
return 4
elif width > 8:
return full_width
else:
... | f46891ee00db894ebcaf97a58960516e239a8259 | 110,577 |
def read_docs_file(filepath):
"""Read a docs file.
Arguments
filepath -- path to the docs file to read
Returns
filestring -- string read from the file
"""
with open(filepath, encoding='utf-8') as docs_file:
return docs_file.read() | 4f70adc3167625615446844dd525e17450831cc9 | 110,581 |
import socket
import time
def wait_for(ip, port, timeout, _type='tcp'):
"""Wait for service by attempting socket connection to a tuple addr pair.
:param ip: str. an IP address to test if it's up
:param port: int. an associated port to test if a server is up
:param timeout: int. timeout in number of s... | 507f046d0516ce862b547dcef74ab901bd38fdf6 | 110,582 |
def checkInputDir(inputDir):
"""
function to set the default value for inputDir
Args:
inputDir: String of the path to the directory where the binaries are stored
Returns:
String representation of the path to the input directory
"""
if inputDir is None:
return "input-bi... | f167c353a83f429308a1d8f1bc92d4581ca4014e | 110,583 |
def _h5_moments_to_dict(h5obj, fmd):
"""
Convert gamic HDF5 moment Dataset and attached Attributes to a dictionary.
"""
d = fmd.get_metadata('default')
d['valid_min'] = h5obj.attrs['dyn_range_min']
d['valid_max'] = h5obj.attrs['dyn_range_max']
d['standard_name'] = h5obj.attrs['moment']
d... | 81648e585443d677fe0e506377b6a8c0e016c3f1 | 110,584 |
def parsing_name_file(filename):
"""
Parse the name of the data file to extract l and set number.
"""
str1 = filename.split("t")
str2 = str1[1].split("l")
str3 = str2[1].split(".")
str4 = str3[0][1:]
str5 = '0.'+ str4
nset = int(str2[0])
nl = float(str5)
ret... | 130f2616fb36c5f62e2c327fe951b6a0bd9243a3 | 110,586 |
def get_filelines(filename):
""" Returns a list of all stripped non-empty lines in filename in order
"""
print("Parsing SSM file %s" % filename)
with open(filename, 'r') as read_file:
filelines = read_file.readlines()
filelines = [line.strip() for line in filelines if len(line.strip()) > 0]
... | e7fd828c130e16715bf0496d9d4e2610fae4b491 | 110,590 |
def jac_shape(n_ant, n_chan, n_dir):
"""Calculate the jacobian matrix shape based
on the given data dimensions."""
return (n_chan * n_ant * (n_ant - 1),
2 * n_chan * n_dir * n_ant) | 1d182880366c7371ff65137622d6341fbc4321da | 110,591 |
def rsc_to_geotransform(rsc_data, half_shift=True):
"""Convert the data in an .rsc file to a 6 element geotransform for GDAL
See here for geotransform info
https://gdal.org/user/raster_data_model.html#affine-geotransform
NOTE: `half_shift` argument is because gdal standard is to
reference a pixel b... | 08de8f0994cf47f6f288143422441de146634b8e | 110,592 |
def expected_future_worth(x, percent_return=0.07, years=20, annual_payment=None):
"""
estimate the future value of a current investment given the percent rate of return,
number of years, and optional annual payment amount
:param x: the present value of your account
:param percent_return: the marke... | 1cea7263a3a890d401a9e1c736ffbc7755edcece | 110,598 |
def resolve_attr(attr_name, dct, mro):
""" Resolve an attribute from a MRO
If the attribute is not present anywhere, None is returned
Parameters:
attr_name: The name of the attribte to resolve
dct: The dictionary of the most derived class body
mro: The C3 lineari... | ddf3f8d5054cade0e75e7adde10c4c783c6cc0eb | 110,599 |
def union_favourites_and_cards(favourites, cards):
"""
Function to unite user's favourites cards with a queryset of cards
"""
# Using sets due to the fact that time complexity is O(1)
# to check that an element is in the set
favourites_set = set()
resulting_cards = cards.all()
for f... | f525ac54ff44cfe4ec610f9de1174025faa857f0 | 110,600 |
def get_latitude_direction(latitude_degrees):
"""
Returns the direction for the given latitude degrees.
:param latitude_degrees: The degrees (not minutes) as an integer.
:return: String containing the possible latitude directions (N, S).
"""
if latitude_degrees is None:
raise ValueError(... | 71a61a0335765dfedac93107ace64ed1102239b7 | 110,607 |
def mergeInterval(intervals, h=1):
"""
Merge intervals that are less or equal than "h" hours away from each other
(e.g., for h=1, intervals [1,3] and [4,5] need to be merged into [1,5])
"""
intervals_merged = []
current_iv = None
for iv in intervals:
if current_iv is None:
... | 98ee1801ba04d4e1525c12e166005f6089b84b57 | 110,613 |
def to_metric(amount, unit):
"""
Used to convert common (amount, unit) pairs to metric versions, e.g.,
(5, 'GALLON') -> (18.9270589, 'LITER')
"""
if unit == 'POUND':
kgs = (amount * 0.45359237, 'KILOGRAM')
if kgs[0] < 1.0:
return (kgs[0] * 1000, 'GRAM')
return kgs... | 02012f202f4f7f29fabd18a855fc0af1ec08ac76 | 110,615 |
def find_dict_if_matched_key_val(dict_tmp, key, value):
"""
check if a key/value pair match in a given dictionnary
Parameters
----------
dict_tmp: (dict) the dictionnary to be tested
key: (str) a key string to look for in dict_tmp
value: (object) any python object
Returns
-------
... | 19ffd46451021ebfbc665ef4fd815c1d3f8175f7 | 110,617 |
import typing
def compute_prefixes(strings: typing.Iterable[str]):
"""Given an iterable of strings, returns a dict of unique shorter prefixes.
Note in case of collision, the string is not included in the results, eg.:
$> compute_prefixes(["foo", "foobar"])
{"foobar": "foob"}
"""
prefixes = {... | e4e8bb03ce07d0a823087bb4ef768306990238f7 | 110,627 |
def log_line() -> str:
"""
A simple reuseable log line string.
"""
line = (
'77.179.66.156 - - [07/Dec/2016:10:34:43 +0100] "GET /favicon.ico HTTP/1.1" '
'404 571 "http://localhost:8080/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) '
'AppleWebKit/537.36 (KHTML, like Gecko) C... | ff5a03192509325e27b85be0ca052a3614f33960 | 110,628 |
import fnmatch
def _expand_wildcard_method_list_items(base_class_methods, test_methods):
"""Updates any entries in a test/skip method list with wildcards
Adds list entries for each test method that matches a wildcard entry, then
removes all wildcard entries after expanding. Additionally, any duplicate
... | f7c6093cdc82beaa663d1f9f805c16a031757b32 | 110,630 |
def count(coll):
"""
Returns the number of items in the collection. Also works on strings.
"""
if hasattr(coll, "__len__"):
return len(coll)
n = 0
for _ in coll:
n += 1
return n | 13f9b7c73b65165d4b14c06e3bee63f0e603d599 | 110,640 |
def is_packed_layout(layout):
"""Check if layout is packed layout"""
if layout == "NCHW":
return False
if "n" in layout and "c" in layout:
return True
return False | ef3c02ea56684938c894323bbd35c350fe79b01a | 110,647 |
def MaximumElementSize( C_B_Array, C_B_eff_Array, Frequency ):
"""
<description> <reference>
Developer: Christoph Winter ( christoph.winter@tum.de )
:param C_B_Array: 1D list of floats
:param C_B_eff_Array: 1D list of floats
:param Frequency: 1D list of floats
:return: dictionary with the f... | f6f3275429591cb2689da796859b817ea4520adc | 110,659 |
def is_camel_case_with_acronyms(s: str):
"""
Checks if the string passed is Camel Case (with capitalised acronyms allowed).
:param s: string to check
:return: true if the name looks cool as Class name.
"""
return s != s.lower() and s != s.upper() and "_" not in s and s[0].upper() == s[0] | c9eac5dfc21e11a9645415c5343f9211f003919f | 110,666 |
def raw_tmp(raw_clean_detrend):
"""Return an unmodified copy of the `raw_clean_detrend` fixture.
This is run once per NoisyChannels test, to keep any modifications to
`raw_tmp` during a test from affecting `raw_tmp` in any others.
"""
raw_tmp = raw_clean_detrend.copy()
return raw_tmp | c5b7ea0808e9d1b684334d5361637b294da9aaf2 | 110,667 |
def ana_dyads(connectivity):
"""
Calculate proportion symmetric dyads (PTCMUT), asymmetric dyads (PTCASY) and mutuality index (RHO2).
"""
nodes = connectivity.shape[0]
mutual_d = 0
asym_d = 0
out_degrees = []
# count out_degree connections per individual and mutual and asymmetrix co... | 208e9fd75eebf67fb6655f7a66b50ac234c3baae | 110,668 |
def name_in_initials(name):
"""John Doe -> J. Doe"""
name = name.split()
first_name = name[:-1]
last_name = name[-1]
name = [n[0] + "." for n in first_name]
name.append(last_name)
return " ".join(name) | 1a1f5d66d824f5cbd752d875ac415e13fcbf3488 | 110,671 |
def coeff_size(degree):
""" Size of the full coefficient array. """
return ((degree + 2)*(degree + 1))//2 | 3f430d708f82d9b6c6b9f20c572b650645fd2897 | 110,672 |
def is_product_bookable(
product_code: str,
availability: bool,
durability: int,
) -> bool: # noqa E125
"""Checks if a product is available for booking
"""
# Quick and dirty check
if availability and durability ... | dbbece8846ffa59b4cb4b55caff059493aea82db | 110,691 |
def check_desired_parameters(desired_port: dict, port_results: dict) -> bool:
"""
Check if port meets given desired parameters and if then yes return True or else return False.
:param desired_port: Desired parameters that port should meet
:param port_results: Parameters of specific port found by scan
... | d73aae9a08cf82caa85af11125f1da9362464ed3 | 110,692 |
def colnames_to_yeo_7(colnames: list, order: bool = True) -> list:
"""
takes a list of colnames in the brainnetome format/naming and converts them to yeo_7 regions
Examples:
>>> print(colnames_to_yeo_7(["108_110", "1_2", "200_218", "148_140"]))
>>> print(colnames_to_yeo_7(["108_110", "1_2", "200_218", "148_140"],... | eeac8f08c8ff2f9308c9c608fb1c74d5f5bb0387 | 110,693 |
def _get_sort_and_permutation(lst: list):
"""
Sorts a list, returned the sorted list along with a permutation-index list which can be used for
cursored access to data which was indexed by the unsorted list. Nominally for chunking of CSR
matrices into TileDB which needs sorted string dimension-values for... | 16f3097697517911cdbd78cd70bcf383e1be4eca | 110,694 |
def _get_optimized_params(params, n_cameras, n_points):
""" Parse optimization results to camera params and 3D points"""
camera_params = params[: n_cameras * 6].reshape((n_cameras, 6))
points_3d = params[n_cameras * 6 :].reshape((n_points, 3))
return camera_params, points_3d | 09c9e8e3ff245f8bc2495ee978ee39d2b6a0acc6 | 110,695 |
def hex_line8(chunk):
"""Create 8 bit hex string from bytes in chunk"""
result = ' '.join([
'%02x' % part
for part in chunk])
return result.ljust(16 * 3 - 1) | b469c34518779f90fee0f82a3b58a9e8acf3bc14 | 110,699 |
def tensor_size_bytes(tensor, unit='MB'):
"""
Get the size of the tensor in bytes, or a unit that's multiple of bytes
:param tensor: the pytorch tensor
:param unit: GigaBytes or GB (assumes GB=1e9 Bytes), MegaBytes or MB (assumes MB=1e6 Bytes),
KiloBytes or KB (assumes KB=1e3 Bytes), Bytes or B
... | f8d68b99597b2bcfb90ff18f7f1d9f9b02478de1 | 110,700 |
import bisect
def FindLatestProfile(target, versions):
"""Find latest profile that is usable by the target.
Args:
target: the target version
versions: a list of versions
Returns:
latest profile that is older than the target
"""
cand = bisect.bisect(versions, target) - 1
if cand >= 0:
ret... | dd8b3d80c03bb40712de750804261f33f56f00ca | 110,703 |
import re
def parser_regex(regex, group, ignorecase=False):
"""
Recovers the group from a regex and returns it
:param regex: regex
:param group: the group to recover
:param ignorecase: False by default
:return: the group obtained.
"""
if ignorecase:
return lambda x: re.search(r... | 53c21362c5b1ad9d28a21a58c24bf3e588006a33 | 110,706 |
def dict_to_seconds(dict_duration):
"""
Convert a Replicon API duration dict to an integer of the total seconds
"""
seconds = 0
seconds += int(dict_duration['hours']) * 60 * 60
seconds += int(dict_duration['minutes']) * 60
seconds += int(dict_duration['seconds'])
return seconds | ca6fdd11b1cdb367a66df05b7b934f0ad0166d38 | 110,708 |
def is_callable(attribute, instance=None):
"""Check if value or attribute of instance are callable."""
try:
if instance:
return callable(getattr(instance, attribute))
else:
return callable(attribute)
except AttributeError:
return False | 852198540a9889a23fb33e8fb00fec499a5104ea | 110,713 |
import torch
def ones_like(tensor: torch.Tensor) -> torch.Tensor:
"""
Use clone() + fill_() to make sure that a ones tensor ends up on the right
device at runtime.
"""
return tensor.clone().fill_(1) | 5a60923377953aca21690fd4a4b8fdad8bf1105a | 110,714 |
def get_error_description(code: int) -> str:
"""
Получение описания ошибки.
:param code: Код ошибки
:return: Описание ошибки
"""
errors = {
-100: 'Заданный MFN вне пределов БД',
-101: 'Ошибочный размер полки',
-102: 'Ошибочный номер полки',
-140: 'MFN вне предел... | 56b68e58698e93c681cd7dd3d537b3a3270fb3e8 | 110,716 |
from datetime import datetime
def pytime_to_datetime(pytime):
"""
Function to convert a PyTime object to a datetime object.
"""
dt1 = datetime(year=pytime.year, month=pytime.month, day=pytime.day, hour=pytime.hour, minute=pytime.minute)
return dt1 | 17fd4a5a1263cd3e1de1cd3c128f18cce1ba0778 | 110,717 |
from typing import Union
from pathlib import Path
def bump_version(path: Union[str, Path]) -> Path:
"""Bumps the version number for a path if it already exists
Example::
bump_version("folder/new_file.json") == Path("folder/new_file.json)
bump_version("folder/old_file.json") == Path("folder/o... | 11b8e518d7cdbfbf0084f180e721d29723d4c71b | 110,723 |
def is_command(meth):
""" Return True if method is an exposed Lua command """
return getattr(meth, '_is_command', False) | f761f083aaabd8525bb01d495abaf43e59d50218 | 110,726 |
import typing
import enum
def _separate(values: typing.Iterable[typing.Any], sep: str = ":") -> str:
"""Separate a sequence by a separator into a single string."""
parts: typing.List[str] = []
for value in values:
if value is None:
parts.append("null")
elif isinstance(value, en... | 25efb3e8894e06a6a226313c9b8cd70c7c9a6048 | 110,727 |
def get_campaigns(api, assessment_id=""):
"""Return a dictionary containing all campaigns.
When called with a blank string for the assessment_id, the default value,
all campaigns in all assessments will be returned. If an assessment_id is
provided, then only the campaigns for that assessment will be re... | 4fe0904c7be69d673bb0cf2a62b76892218b6c6c | 110,728 |
def maskname_normalize(s):
"""
@param s (str): Mask name with or without the prefix "MP_". Case insensitive.
@return (str): "MP_..."
"""
s = s.upper()
if s.startswith("MP_"):
return s
else:
return "MP_" + s | e45013568c2cc149ceefa495deed9c90e1afbfac | 110,729 |
def broadcasted_shape(*shapes):
"""
Computes the resulting broadcasted shape for a given set of shapes.
Uses the broadcasting rules of NumPy. Raises an exception if the shapes do
not broadcast.
"""
dim = 0
for a in shapes:
dim = max(dim, len(a))
S = ()
for i in range(-dim,0... | dd7ff5f56cd4ef51e4483895e1f8d7b00b9421ea | 110,730 |
def cummulative_continuation(df_delta,initial_value):
"""From a DataFrame with columns consisting of time series with a
common datetime index, returns column-wise cummulative sums
starting from an initial value(s).
Parameters
----------
df_delta : DataFrame
A DataFrame with time series ... | 6b53aa8742a03a73780b07931e4f29d333ee3e15 | 110,732 |
def bu8(u):
"""Convert an 8-bit integer to bytes.
Example:
bu8(0x12) == b'\x12'
"""
return bytes([u]) | c524fc9c9dae01640e65f7bcdf632c5389533e51 | 110,734 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.