content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _create_array_rec(dimensions: int, sizes: list, initialization_value: int = 0) -> list:
"""Auxiliary recursive function for creating a new matrix consisting on lists of lists.
This method assumes that the parameters were previously validated.
:param int dimensions: the number of dimensions to create. ... | 37720873d6d0e65ea48ac95bd86e3a1924f7c92d | 655,700 |
def _extract(dct, keys):
""" Helper function to extract a list of keys from a dict and return these
in a new dict.
"""
tmp = {}
for key in keys:
try:
tmp[key] = dct.pop(key)
except KeyError:
pass
return tmp | 7a84561ec958896745bfdeeecf46440aea414986 | 655,703 |
def subtree_ids(treeview, x, level=0):
"""
Return a list of tuples containing the ids and levels for *x* and every element below it in the Treeview *treeview*.
The level of *x* is 0, children of *x* are 1, and so forth.
"""
id_list = list()
id_list.append((x, level))
for y in treeview.get_c... | b637a0bba5ca3aff9dfa1665984b7cd4cd56790d | 655,706 |
def get_interval(value, intervals):
"""
Returns the index of the interval the value lies in.
:param value: Value for which to find the interval.
:param intervals: List or tuple of interval with values which represent the upper boundary of each interval.
The first interval starts at 0 and ends ar th... | 1207fa3c07c03472d14b55b8c55ed8dc35502b1e | 655,710 |
def comma_code(items):
""" Combines list into a string of the form item1, item2, and item 3
Args:
items (list): List of strings
Returns:
string: list items combined into a string
"""
item_len = len(items)
if item_len == 0:
return ''
elif item_len == 1:
r... | b15f6d064648de5155732aa5e9d0ca2ec4979ba5 | 655,712 |
def ignore_escape(path: str) -> str:
"""
Escape a path appropriately for a docker ignore file.
"""
special_chars = "\\*?[]"
return "".join("\\" + ch if ch in special_chars else ch for ch in path) | 221f010eaf08782aa06bc718a96765635c696366 | 655,714 |
import time
def month_and_year_to_epoch(month_no, year):
""" Convert a month and year to the epoch time for the first second of
said month. """
month_str = str(month_no)
if len(month_str) == 1:
month_str = "0"+month_str
date_and_time = "01."+month_str+"."+str(year)+" 00:00:01"
pattern ... | 31541427f14aebe443abfa4910d409e36152899d | 655,719 |
import re
def executable_script(src_file, gallery_conf):
"""Validate if script has to be run according to gallery configuration
Parameters
----------
src_file : str
path to python script
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
... | 918e633634ee83e899992ced8ba0ba3a93a57531 | 655,724 |
from typing import Dict
from typing import Any
from typing import Sequence
def get_nested(data: Dict[str, Any], keys: Sequence[str]) -> Any:
"""
Get a value from a nested dictionary.
Args:
data (Dict[str, Any]): The dictionary to get the value from.
keys (Sequence[str]): The keys to get t... | 965b720cc3bb22d5fcd5fe9ba0565a3980ffe46f | 655,726 |
def to_int(text):
"""
extract digits from text
"""
return ''.join([char for char in text if char.isdigit()]) | c791dd4d2057d658ad96beeafd31e7e9767324ea | 655,727 |
def lerp(input1, input2, mask):
"""Lerp between two values based on a 0-1 mask value.
When mask is 0, return input1. When mask is 1, return input2.
Otherwise blend between the two."""
return ((1 - mask) * input1) + (mask * input2) | 4cc241659fa577b84fb0bed87a0d3f36643b7fb8 | 655,728 |
import time
def timeit(func):
"""Decorator to time a single run of a task"""
def wrapper(*arg, **kw):
t0 = time.time()
res = func(*arg, **kw)
t1 = time.time()
res.elapsed = (t1 - t0)
if not res.desc:
res.desc = func.__name__
return res
return wra... | aca09db65848d89e57c70068ef21a874b8d9a0fc | 655,730 |
def get_P_Elc_game_standby(P_Elc_game_standby_measured):
"""待機時の消費電力を計算する
Parameters
----------
P_Elc_game_standby_measured : float
待機時の平均消費電力(実測値), W
Returns
----------
P_Elc_game_standby : float
稼働時消費電力, W
"""
P_Elc_game_standby = P_Elc_game_standby_m... | efb5b7b0fed8b815e4cb7b2017f34f29e55d153f | 655,735 |
def norm1(x):
"""Normalize to the unit sphere."""
return x / x.square().sum(axis=-1, keepdims=True).sqrt().clamp(1e-12) | 43037999a96fc14e6d3fb801fd29a85b277c8988 | 655,736 |
from unittest.mock import Mock
def mock_config() -> Mock:
"""Returns the configuration mock object."""
mock_config = Mock()
mock_config.host = "mock_host"
mock_config.url = "mock_url"
mock_config.session.get = "mock_get"
mock_config.session.post = "mock_post"
return mock_config | 19bacfc45a21fab7c693f129123ac2bc1cacb744 | 655,738 |
def has_series(event) -> bool:
"""
Check if the event belongs to a series.
:param event:
:type event: dict
:rtype: bool
"""
return "series" in event and event["series"]["id"] | ef21a0a0800aa581e06c54e313c34dea977ae2ef | 655,743 |
def dd_start_value_map_nb(record, ts):
"""`map_func_nb` that returns start value of a drawdown."""
return ts[record['start_idx'], record['col']] | 0919da2945765d4f156401747a688f646fca2746 | 655,744 |
def bool_to_one_or_zero(value):
"""
Converts a boolean value into an integer
:param value: A boolean value
:type value: bool
:return: 1 or 0
:rtype: int
"""
return 1 if value else 0 | 9c4ab81998f6d11717bc375ae86ec221b5180ac7 | 655,745 |
def per_form_un(number):
"""
works out, for the lattice parameters of t-LLZO, defects per cubic cm
args:
number (float): defect per formula unit
returns:
per_cubic_cm: defect per cubic cm
"""
per_unit_cell = number * 8
per_cubic_angstrom = per_unit_cell / (13.003 * 13.003 * ... | 8ba9565b208346acd9c3a5801f4b6e94cfac89e4 | 655,746 |
import random
def find_trigram(vocab, pair=False):
"""Find random set of related words in the vocab dictionary.
If a valid pair is passed, return the third word in the trigram.
Otherwise, randomly choose and return a key pair from the dictionary.
"""
if pair in vocab:
return random.choice... | 69cf3ce9c78cb42280c60a9bf1e683c31d9e4731 | 655,747 |
def get_package_version(packages, package):
"""
Get version of installed package.
:param packages: installed packages and versions, keyed by package
name
:type packages: dict of str or unicode => str or unicode
:param package: Package name
:type package: str or unicode
:return: Package ... | 6dc3374d246d25124d8d9fb5098a0af5ac625e0e | 655,749 |
def get_means_of_booleans(data, boolean_cols):
""" Put boolean_cols of the data in a uniform format and
compute the mean per customer.
Parameters
----------
data: The DataFrame.
boolean_cols: array-like of column names with boolean values to
process.
Returns
-------
Dat... | 8bf9d213a53f6388444da1ffb6e3835bc67164f1 | 655,750 |
def get_lib_name(lib):
"""Returns the name of a library artifact, eg. libabc.a -> abc
Args:
lib (File): A library file
Returns:
str: The name of the library
"""
# NB: The suffix may contain a version number like 'so.1.2.3'
libname = lib.basename.split(".", 1)[0]
if libname... | 0f41fd3cfeb4b5a7f03fceeed0fc6fcea79b9b61 | 655,753 |
def calculate_avg_delay_wait(avg_delays):
"""
Calculate average delay or waiting value.
"""
avg_delays_dict = {}
for lambda_rate, avg_delay_list in avg_delays.items():
avg_value = sum(avg_delay_list) / len(avg_delay_list)
avg_delays_dict[lambda_rate] = avg_value
return avg_delays... | 88542ff894c17d4bd9be17dee606ec77adc9ed8d | 655,757 |
import struct
def bytes_to_int(byte_stream):
"""Convert bytes to integer"""
return struct.unpack(">L", byte_stream)[0] | a480466573f689706b6d5ae4049b7604f9f590ee | 655,759 |
def factorial(n):
""" Naive computation of factorial(n) with products. Not recursive."""
if n <= 0: return 1.0
else:
f = 1.0
for i in range(2, n+1):
f *= i
return float(f) | 320c1343688844a50b65c4e856eaeb6293c19758 | 655,762 |
import requests
import json
def get_pushshift_submissions(query, sub):
"""
Retrieves Reddit submissions matching query term over a given interval
Parameters
----------
query : str
Query term to match in the reddit submissions
sub : str
Submission match query
Returns
-------
... | 5f29854d90f0cd568cc525164ef25bbf6a2b2c50 | 655,765 |
def _test_rast(h):
"""Sun raster file"""
if h.startswith(b'\x59\xA6\x6A\x95'):
return 'rast' | 510b8088fd1aa29926fa8ec740241acc7643ed62 | 655,770 |
def filter_float(value):
"""
Filter given float value.
:param value: given value
:type value: float
:return: filtered version of value
"""
if isinstance(value, (float, int)):
return value
return None | 214c580029e2d6ffced2a035725c52619ff8ab5d | 655,774 |
def invert_for_next(current):
"""
A helper function used to invert
the orientation indicator of the
next panel based on the current panel
i.e. if a parent is horizontal a
child panel must be vertical
:param current: Current parent
orientation
:type current: str
:return: child... | e97ce13f368cdd795fec7e9f045a7f1a7892b35a | 655,775 |
def merge_station_subloc(station_dbase,station_subloc,default_z):
"""Merge BayDeltaSCHISM station database with subloc file, producing the union of all stations and sublocs including a default entry for stations with no subloc entry
Parameters
----------
station_dbase : DataFrame
This should... | adfd7435f326897aa99977630fe65d0d92c1a6aa | 655,776 |
def isWinner(data,c1,c2):
"""
This function takes the preference ranking data as an input parameter. It computes the
head to head winner for the two candidates that are passed into it as parameters.
If the first candidate passed as a paramter wins against the second candidate, then
the function will ... | 6fb1d6d245f6d1a43a9e7fa34e5779b065611458 | 655,778 |
def outgoing_synapses(q, N = None, rel='>',include_inferred=True):
"""
Get all the outgoing synapses from neurons in a QueryWrapper object.
Parameters
----------
q: query.QueryWrapper
The query to search for outgoing synapses
N: int or None
Filter for number of synapses (default... | 5e7a358b2f049e447e890f1dd66131cbf8869b3a | 655,780 |
def revertDateTimeToLongString(dt):
"""
Turns a date/time into a long string as needed by midas code.
"""
return str(dt).replace("-", "").replace(" ", "").replace("T", "").replace(":", "") | d87d440598d204d53d5b132cda1f329753bd3a5e | 655,783 |
def deny(user, record):
"""Deny access."""
return False | c0dba74b4a9bda8f05dbb17c2ef456b5d63026d3 | 655,784 |
import pathlib
def is_empty_dir(path: str) -> bool:
"""Checks if path is emptry directory
e.g
j.sals.fs.is_empty_dir("/home/rafy/empty_dir") -> True
j.sals.fs.is_empty_dir("/home/rafy") -> False
Args:
path (str): path to check if empty directory
Returns:
bool: True ... | 3c70a841f52e57f20e1db50f41529163e1500f1b | 655,786 |
import ast
def datAst(dat):
"""
Get the ast node of a DAT holding Python code
Args:
dat: the dat to analyze
Returns:
ast node of the DAT's text. Will be ast.Module at top
"""
return ast.parse(dat.text) | 6bb4994a4f05c1d813a29e916ebb22236ab808d6 | 655,787 |
def get_signature_algorithm(alg_type, alg_hash):
"""
Returns signature algorithm for ACM PCA
Args:
isEC: true if Elliptic Curve certificate
alg_type: Hash Algorithm from cryptography package to find
Raises:
ValueError: Algorithm type not supported
"... | 2c843a6eaf5f67088db774b190a9422f059b79c9 | 655,788 |
def frozen (db, user, date, order = '+') :
""" Get frozen freeze-records >= date. If some are found, the date
is frozen. By default the first record returned is the first
after date. But sometimes we want the *last* freeze record. Then
we can specify order = '-'.
"""
f = db.daily_rec... | 33d4e23996fff32308b22d30b5031fcefaaed569 | 655,789 |
def get_host(url):
"""
Given a url, return its scheme, host and port (None if it's not there).
For example:
>>> get_host('http://google.com/mail/')
http, google.com, None
>>> get_host('google.com:80')
http, google.com, 80
"""
# This code is actually similar to urlparse.urlsplit, but... | 510d7d3a23b8486d084079aa77780f86d10428df | 655,790 |
import time
def toJulian2(date):
"""
Converts date and time to Modified Julian Date.
Uses time functions. Note that date has to be in Python time format.
:return: Modified Julian Date
:rtype: float
"""
sec = time.mktime(date)
days = (sec - time.timezone) / 86400.0
jday = days + 40... | dbfa542e1fa0c09b7fb3b3b392f2acfe64b22ccd | 655,793 |
from typing import Optional
from typing import Union
import math
def calculate_gain(nonlinearity: str, param: Optional[Union[int, float]] = None):
"""
Return the recommended gain value for the given nonlinearity function.
The values are as follows:
================= =================================... | 8c80343f1435b7e3e84b83557cff8aa35443b326 | 655,804 |
def left_path_clear(Rover, safe_pixs=1500):
"""
Check if sufficient room on left.
Keyword arguments:
safe_pixs -- minimum number of pixels on left to deem left path clear
"""
nav_pixs_left = len(Rover.nav_angles_left)
return nav_pixs_left >= safe_pixs | 9072290c29b033df5409539171cd1110f48b23c0 | 655,806 |
def ligand_residue_vs_water_hbonds(hbonds, solvent_resn, ligand):
"""
Split hbonds into those involving residue and ligand directly and those
mediated by water molecules.
"""
ligand_residue_hbonds, water_hbonds = [], []
for hbond in hbonds:
frame_idx, atom1_label, atom2_label, itype = hb... | 9fcd571993e90f716f99e45611ddc1bdab694133 | 655,808 |
def stations_by_river(stations):
"""
Given list of stations, return a dict of all the stations on a river
"""
rivers = {}
for station in stations:
if station.river in rivers:
rivers[station.river].append(station)
else:
rivers[station.river] = [station]
ret... | f25b927559b5e2dd159d0ecb202be06ca6322de8 | 655,815 |
from typing import Dict
import pkg_resources
def get_current_environment_requirements() -> Dict[str, str]:
"""Returns a dict of package requirements for the environment that
the current python process is running in."""
return {
distribution.key: distribution.version
for distribution in pkg... | 0856e6ed89a236fe6d08a34f7e69e3490e236606 | 655,820 |
def take(dataset, num_examples=-1, **unused_kwargs):
"""Takes the first `num_examples` examples from the dataset.
This is done to simulate that the dataset is smaller than it actually is. The
result will be cached via `tf.data.Dataset.cache`. This ensures that the same
examples get repeated if `dataset` is st... | 3eab752c5550f2b5c37dc535f6c8599cb798ba6e | 655,823 |
def new_sharedStrings_text(db):
"""
Returns xl/sharedStrings.xml text
:param pylightxl.Database db: database contains sheetnames, and their data
:return str: xl/sharedStrings.xml text
"""
# location: xl/sharedStrings.xml
# inserts: sharedString_len, many_tag_si
xml_base = '<?xml versi... | ec0448cd02cf3b8c0f6949e6cf5b26b6d18b567d | 655,824 |
def derived_P_species(df_R, f_TDP):
"""
Calculate: Total P as the sum of TDP and PP
SRP as a function of TDP
for both the daily mass flux and the concentrations
Inputs: reach results dataframe; value to multiply TDP by to get SRP
Returns: dataframe of reach results, with ex... | 3c5193c38847421fcffbfbf367aa643ca817aeb6 | 655,826 |
def bp_star_rating(tot_group_rate, oa_reviews):
"""
Function to compute business review per star rating
star_rate = tot_group_rate / oa_reviews * 100%
"""
star_rate = (int(tot_group_rate) / int(oa_reviews)) * 100
m = round(star_rate, 2)
return m | d65af2443149e674ffe0c32200d0c4af4e60b2ab | 655,827 |
def clean_board(shipDict):
"""Takes the given dictionary and replaces the 0 values with a single
white space. This is to show a clean looking board
Args:
shipDict (DICT): A dictionary representing the battleship board
Returns:
DICT: A dictionary where all the 0 values have been replac... | 26bbadf27699a1e11617cb1b44f287a13530403d | 655,829 |
import re
from typing import OrderedDict
def parse_region(regstr):
"""
Parse the given region string into one of the following 4 cases:
1. annulus
2. pie (cxc)
3. pie + annulus (ftools/xmm)
4. other
For the first 3 cases, the return is a dictionary like:
{ 'shape': 'pie', 'xc': 55... | 072a6256f9130013bd94d076af1eed730e4feec5 | 655,831 |
def get_state_result(state):
"""Get result from Prefect state object."""
return state.result() | ed8545c5004eb789a59c65e799576046eef68c52 | 655,832 |
def multiFind(string,substring):
"""Return a list if integers indicating where the substring begins in the string.
Substrings are not allowed to overlap themselves:
multifind('pppp','pp') = [0,2]
If there are no matches, return []
"""
start = 0
indices = []
while True:
start ... | ba64aa1f915883010b5d3a879686bbaa633adf91 | 655,834 |
def permute_all_atoms(labels, coords, permutation):
"""
labels - atom labels
coords - a set of coordinates
permuation - a permutation of atoms
Returns the permuted labels and coordinates
"""
new_coords = coords[:]
new_labels = labels[:]
for i in range(len(permutation)):
new_... | ba8aa571afd9039725347a0b5a04885dfafb02b3 | 655,836 |
def github(path):
"""
:param path: relative (to the root) path of a file in the glottolog data repository
:return: URL to a file in Glottolog's data repository on GitHub
"""
return 'https://github.com/glottolog/glottolog/blob/master/{0}'.format(path) | a87c3003f22796c9e803456d1b93fe5de876d813 | 655,839 |
import re
def get_vocabs_from_string(string):
"""
Search in the string to find BODC vocabularies (P01, P06 etc.
Returns a dict where:
key = vocabulary
value = code
"""
result = re.findall('SDN:[A-Z0-9]*::[A-Z0-9]*', string)
vocabs = {}
for item in result:
spl... | 5bc5a2fa472f703291907b4c7322415128ebce9a | 655,841 |
def bezier_point(cps, t):
"""
Cubic Bezier curve interpolation
B(t) = (1-t)^3 * P0 + 3t(1-t)^2 * P1 + 3t^2(1-t) * P2 + t^3 * P3
"""
p = ((1 - t) ** 3) * cps[0, :]
p += 3 * t * ((1 - t) ** 2) * cps[1, :]
p += 3 * (t ** 2) * (1 - t) * cps[2, :]
p += (t ** 3) * cps[3, :]
return p | ca5644539ac0c239ce028f992a07965d92132b8c | 655,844 |
def process_tariff(utilityrate, tariff_dict, net_billing_sell_rate):
"""
Instantiate the utilityrate5 PySAM model and process the agent's rate json object to conform with PySAM input formatting.
Parameters
----------
agent : 'pd.Series'
Individual agent object.
Returns
-------
... | c75c6ef93aef23b666ce8eb8f2b2f88e28aac66d | 655,846 |
import re
def sanitize(instr, pattern=r'\W', replace=''):
"""Sanitize characters in string.
Default removes all non-alphanumeric characters.
"""
return re.sub(pattern, replace, instr) | 018522e508ec75d31bbedb1f85c496ec94dc0188 | 655,852 |
from typing import Any
def tuple_(obj: Any) -> tuple:
"""Converts any object to tuple. ``string`` to ``(string,)``."""
if isinstance(obj, str):
return obj,
try:
return tuple(obj)
except TypeError:
return obj, | d644bbc80763565c62641723a4cd0be578fb31b2 | 655,857 |
def get_gen_loss(crit_fake_pred):
"""
Return the loss of a generator given the critic's scores of generator's fake images.
:param crit_fake_pred: the critic's scores of the fake images
:return: gen_loss: a scalar loss value for current batch of generator
"""
gen_loss = -1 * crit_fake_pred.mean()... | 0a8964ce94f71fc3ff7e9f713c01aa84b53c651f | 655,859 |
def get_fully_qualified_name(func):
"""
gets the fully qualified name of given function.
it returns `module_name.function_name`.
for example: `pyrin.api.services.create_route`.
:param function func: function to get its fully qualified name.
it must be a stand-alone functi... | 6f1ea049d67ca665d1db60ba4c6f35894caa74b2 | 655,862 |
def get_tokens(sequences, lower=False, upper=False):
"""Returns a sorted list of all unique characters of a list of sequences.
Args:
sequences: An iterable of string sequences.
lower: Whether to lower-case sequences before computing tokens.
upper: Whether to upper-case sequences before computing tokens... | 251d53d8aa3662447f88dea8309d0612966679dd | 655,865 |
import hashlib
def sha256(fp_in, block_size=65536):
"""Generates SHA256 hash for a file
:param fp_in: (str) filepath
:param block_size: (int) byte size of block
:returns: (str) hash
"""
sha = hashlib.sha256()
with open(fp_in, 'rb') as fp:
for block in iter(lambda: fp.read(block_size), b''):
sh... | 6fcd85de1bc746aba7623e67f6b11dd9cb047582 | 655,869 |
import glob
def xpand(args):
"""
Expand command line arguments.
Arguments:
args: List of arguments.
Returns:
Expanded argument list.
"""
xa = []
for a in args:
g = glob.glob(a)
if g:
xa += g
else:
xa += [a]
return xa | 45f966aa200e58454b10b75c8834c0e5ec748943 | 655,870 |
def delete_srv6_behavior(database, key, grpc_address=None, grpc_port=None,
segment=None, action=None, device=None, table=None,
nexthop=None, lookup_table=None, interface=None,
segments=None, metric=None, fwd_engine=None,
... | 0eb7e7250a294877124217e42fc6d0362f2ba7c3 | 655,871 |
def format_days(days):
"""
Converts a list of tuples with a date into a list of tuples with a string
representation of the date
:param days: List of tuples from database with datetime in second position
:return: List of tuples as described above
"""
formatted = []
for day in days:
... | cd26e67346e97727091db7644080c5f107a4c59b | 655,872 |
def head_tail_middle(src):
"""Returns a tuple consisting of the head of a enumerable, the middle
as a list and the tail of the enumerable. If the enumerable is 1 item, the
middle will be empty and the tail will be None.
>>> head_tail_middle([1, 2, 3, 4])
1, [2, 3], 4
"""
if len(src) == 0:... | ce141ba969d50e94c1a6fb130bce7de9e7a5ff4f | 655,874 |
import json
def load_json(file):
"""Loads a JSON file and returns it as a dict"""
with open(file) as f:
return json.load(f) | d2e593c2d698223ad28103e4c1d7d91426137f53 | 655,876 |
def B2IQUV_TMS(B, sign_uv=1, sign_q=1):
"""Convert sky brightness matrix to I, Q, U, V"""
B11 = B[0, 0, :, :]
B12 = B[0, 1, :, :]
B21 = B[1, 0, :, :]
B22 = B[1, 1, :, :]
stokes = {}
stokes['I'] = (B11 + B22) / 2.
stokes['Q'] = sign_q * sign_uv * (B11 - B22) / 2.
stokes['U'] = sign_u... | 47088e1bcb4491fc3e51023412a7f8acae4e9ef1 | 655,878 |
def filter_tags(rules, tags=[]):
"""
Filter the rules object for rules that have a certain tag
:param rules: YARA rules JSON object
:param tags: the selected tags
:return: list of filtered rules
"""
filtered_rules = []
# Process the rules
for rule in rules:
for tag in tags:
... | f9ec475ebd4db54d9431760397597de8e5c5ee86 | 655,880 |
import codecs
import yaml
def parse_yaml_or_json(path):
"""
Return parsed YAML or JSON for a path to a file.
"""
with codecs.open(path, mode='r', encoding='utf-8') as infile:
doc = yaml.safe_load(infile)
return doc | 6902c3fcc67e636c35fc9576106943e8bd8d2541 | 655,883 |
def less_than(values, target_loc, puzzle_input):
"""if the first parameter is less than the second parameter, it stores 1 in
the target location. Otherwise it stores 0.
"""
if values[0] < values[1]:
puzzle_input[0, target_loc] = 1
else:
puzzle_input[0, target_loc] = 0
return puzz... | 32d118da27ecfbb18f127027d7c816b9697b6d60 | 655,886 |
def solution(resources, args):
"""Problem 6 - Version 1
Manually calculate the sum of squares and the square of the sum.
Parameters:
args.number The upper limit of the range of numbers to use
for the calculation (i.e. 1 to args.number)
Return:
(1^2 + 2^2 + ... | d6ead21ac352a96badcc54fe6471655b3d0c23cc | 655,892 |
def semester_year_to_term_key(semester, year):
"""
Convert semester and year to a 4-digit term number
"""
semester = str(semester).strip().lower()
return 1000 + int(year) % 100 * 10 + ["spring", "summer", "fall"].index(semester) * 2 + 4 | f76db3bbaf175c532e519d1edc49d58d2a341000 | 655,893 |
def message_with_line(cell, message, sourcepos=[[1, 1], [1, 1]]):
"""
Print 'message', along with some of the lines of 'cell'
"""
return f"{message}. Some relevant lines from the cell:\n\n{cell.lines(sourcepos)}" | 3fd9f336af1e90edd0937e8a9ac937e8e533966e | 655,895 |
import pathlib
from typing import Dict
import yaml
def config_parser(file_path: pathlib.Path) -> Dict[int, list]:
"""Opens and parses a `yaml` configuration file.
Uses [PyYAML](https://pyyaml.org) to parse the configuration file.
Args:
file_path (pathlib.Path): The path towards the user's
... | bc6a48e6ed685addc869752bce83cd2d13077188 | 655,896 |
from datetime import datetime
def _is_key_expired(key, expiration_in_days):
"""
Whether or not service account key is expired based on when it was created
and the current time.
Args:
key (dict): API return for a service key
.. code-block:: python
{
... | c0b8c7d06baa65a442830bd382ca78466c8c4ff6 | 655,897 |
def sharpe_calc(rtrn: float, risk: float, rf: float) -> float:
"""
Calculate the Sharpe Ratio assumed given continuously compounded return.
:param rtrn: Continuously compounded return.
:param risk: Standard deviation of portfolio.
:param rf: Risk free rate of return.
:return: Sharpe Ratio.
"... | 06d0503214e33cf07f1405d7bcce34331aad7e9a | 655,900 |
def _slice_support(the_slice, length):
"""Takes a slice and the length of an object; returns normalized version.
Specifically, corrects start and end for negative indices.
"""
start = the_slice.start
stop = the_slice.stop
step = the_slice.step or 1
#fill in missing values for start and end
... | 72026168b61d67ad4b13125c91326e19906c1608 | 655,901 |
import io
import difflib
def generate_or_check(manifest, args, path, func):
"""Generate/check a file with a single generator
Return True if successful; False if a comparison failed.
"""
outfile = io.StringIO()
func(manifest, args, outfile)
generated = outfile.getvalue()
existing = path.r... | 4d4f14551d68047cbe4e0c0e28b21e359d3824c8 | 655,903 |
def generate_df_subset(swc_df, vox_in_img_list):
"""Read a new subset of swc dataframe in coordinates in img spacing.
Parameters
----------
swc_df : pd.DataFrame
DataFrame containing information from swc file
vox_in_img_list: list
List of voxels
Returns
-------
df : :cl... | cf9a04c026d4793cf47074706083ec4f8be7dc00 | 655,905 |
def get_capi_link_library_name() -> str:
"""Gets the library name of the CAPI shared library to link against."""
return "NPCOMPPythonCAPI" | 0261e0293d4c541642d075dc08210ea3c35fcb1d | 655,910 |
import glob
import re
def _find_weights(ckpt_path, paths=None, start=0):
""" ckpt_path should be format string containing '{epoch}'
>>> paths = ['abc.01.ckpt', 'abc.05.ckpt', 'abc.best.ckpt']
>>> _find_weights('abc.{epoch}.ckpt', paths=paths)
[(0, 'abc.01.ckpt'), (4, 'abc.05.ckpt')
"""
if pat... | c3a0da1576edc11bc599c017225e8400a5521d7a | 655,912 |
import ast
def is_literal(node: ast.AST) -> bool:
"""
Checks for nodes that contains only constants.
If the node contains only literals it will be evaluated.
When node relies on some other names, it won't be evaluated.
"""
try:
ast.literal_eval(node)
except ValueError:
ret... | 87001f4e8112217f3d6552ad95c8417e01e0c9a3 | 655,914 |
def _format_pep_number(pep_number):
"""
The PEP number as a 4-digit string.
This is the format used by the URLs on python.org.
"""
return str(pep_number).rjust(4, '0') | 2fa00d3fafb2d4e7159a8e5d29f81f71b6352d1d | 655,918 |
import hashlib
def md5sum(fpath):
"""Compute the md5sum hash of the content of a given file."""
blocksize = 65536
hash_md5 = hashlib.md5()
with open(fpath, "rb") as f:
for block in iter(lambda: f.read(blocksize), b""):
hash_md5.update(block)
return hash_md5.hexdigest() | 312811fe577393120fb8b75cebdc6bc07d9c231d | 655,919 |
def clean_list(lst):
"""
Returns a new but cleaned list.
* None type values are removed
* Empty string values are removed
This function is designed so we only return useful data
"""
newlist = list(lst)
for i in lst:
if i is None:
newlist.remove(i)
if i == ""... | ab71627da03b515fee18c2f2bcc82b45cc0ec0a3 | 655,924 |
def compare_schemas(current: dict, old: dict) -> bool:
"""Returns true if schemas are functionally the same"""
return current == old | 6016a891b48479ef07111aacd2b68cee8be68f16 | 655,925 |
def _get_data(title, func, dest):
"""Populate dest with data from the given function.
Args:
title: The name of the data
func: The function which will return the data
dest: a dict which will store the data
Returns:
dest: The modified destination dict
"""
# Get inter... | d2d4c7374c7216a5150d92f13f3eb7d98391f721 | 655,927 |
def _isRunMaskDuplicate(run, lumis, runLumis):
"""
Test whether run and lumi is a subset of one of the
runLumi pairs in runLumis
:param run: integer run number
:param lumi: set of lumis
:param runLumis: list of dictionaries containing run and lumis
"""
for runLumi in runLumis:
if... | 4b17001087175db9325efaa7f7420bc75a6f1e61 | 655,933 |
def fill_zeros(s,n):
"""
Add zeros to a string s until
it reaches length n.
"""
while len(s) < n:
s= ''.join(('0',s))
return s | 0b25353954070668d4bdb3450287b2291008d019 | 655,934 |
from typing import Union
import json
def _parse_doc(doc: Union[str, dict]) -> dict:
"""Parse policy document if necessary.
Args:
doc: Policy document to parse.
Returns:
Parsed policy document.
"""
if isinstance(doc, (str, bytes)):
return json.loads(doc)
return doc | 84bcb1b5eb2d4d106c249f5354ff4eb64cdd85ef | 655,936 |
def reduceby(key, binop, seq, init):
""" Perform a simultaneous groupby and reduction
The computation:
>>> result = reduceby(key, binop, seq, init) # doctest: +SKIP
is equivalent to the following:
>>> def reduction(group): # doctest: +SKIP
... return reduce... | efe74c29ec31d26f8831bd672cc1c2271b1e931a | 655,937 |
def arrayRatio(numerator,denominator):
"""
Returns the average ratio of numerator to denominator. (e.g. Given
numerator ['123','456'] and denominator ['222','333'], returns 1.043...)
"""
lennum = len(numerator)
lenden = len(denominator)
lenlower = min(lennum,lenden) #finds list with less v... | f637ee30dd7bcfc308a0bc6ee3522d581b975fc0 | 655,944 |
def bubble_sort(arr):
"""
Performs a bubble sort algorithm
- Time complexity: O(n²)
Args:
arr (list): List to sort
Returns:
(list): Sorted list
"""
j = len(arr) - 1
while j >= 0:
i = 0
while i < j:
if arr[i] > arr[i+1]:
te... | 8660f757d282d99d7ded292bc2c526095ea74214 | 655,945 |
def undirected_edge_name(u, v) -> str:
"""
:return The name of an undirected edge as "(u,v)" with u <= v.
"""
u_i, v_i = int(u), int(v)
if u_i > v_i:
u_i, v_i = v_i, u_i
return f"({u_i},{v_i})" | 0ad35c9006ead67393839e6ad9186d01dddc7f7b | 655,946 |
def needed_to_tuple(var_full, needed):
"""Extract only needed variables to a new tuple."""
return tuple(var for var, n in zip(var_full, needed) if n) | 345717b31d54071b5943d55c51da8437a28dc55e | 655,950 |
from typing import List
def hex_to_rgb(value: str) -> List[float]:
"""Converts hex to normalized rgb colours
Args:
value (str): string of 6 characters representing a hex colour
Returns:
list[float]: rgb color list
"""
value = value.strip("#")
lv = len(value)
rgb_vals = tu... | 0f10086ba88e02a2f59f896c602584b4bef24d84 | 655,953 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.