content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _get_org_detail_page(api_client, org):
"""Helper method to dry up repeated calls to org detail page"""
url = f'/api/organizations/{org.slug}/'
response = api_client.get(url)
assert response.status_code == 200
return response.json() | ef05ff36f07fb2e23dd2179e046a7d7a51b21cdc | 680,029 |
def _get_thresholds(xmltree):
"""This is basically the same as px.getConstantThresholds, but with the
added ability to get linear thresholds as well.
"""
thresholds = {}
for criterion in xmltree.findall('.//criterion') :
criterion_id = criterion.get('id')
xml_thresholds = criterion.f... | 1bd69dc5519656c66c0b53182e9e01fcfcf599c1 | 680,030 |
def _divide_with_ceil(a, b):
"""
Returns 'a' divided by 'b', with any remainder rounded up.
"""
if a % b:
return (a // b) + 1
return a // b | 345e3ba6631d686379e405fc205ac6620dcf7562 | 680,031 |
def isCST(foraValue):
"""returns whether a foraValue is a constant"""
return foraValue.implVal_.isCST | bf0e17665cc40e3be8b983f4cf2e9360768e5df6 | 680,032 |
def filter_tagged_articles(articles, tagged_articles):
"""
Filter out those named entity tagged articles from the NLP pipeline which also appear in the evaluation set.
:param articles: List of articles.
:type articles: list
:param tagged_articles: List of tagged articles.
:type tagged_artic... | 3d6cdf3f6464df92f1b1e063c5f1956e849c0c71 | 680,033 |
def update_max_accel(driver, ma):
"""
Updates the max accel of the driver
:param driver: driver
:param ma: new max accel
:type driver: DriverProfile
:return: updated driver profile
"""
return driver.update_max_accel(ma) | 3424893a64c37d51c3fca1f99d6bc37689108c95 | 680,034 |
def castlingmove(movetuples):
"""Determine if we have a tuple of tuples or just a simple move."""
if isinstance(movetuples[0], tuple) and isinstance(movetuples[1], tuple):
return True
else:
return False | e84e90d7bbb30b692fb3624baf5a43354a23338c | 680,035 |
from typing import Sequence
from typing import Hashable
def confusion_dict(fits, labels, classes: Sequence[Hashable]):
"""
Generate a confusion matrix in dictionary representation,
counting the classification error by category.
:param fits:
:param labels:
:param classes:
:return:
"""
... | abe7c97e97056cdfdd7d4181f02b2fad84821768 | 680,037 |
def make_args_string(args_dict):
"""
- args_dict: dict, the dictionary of local variable to value such as returned by locals()
RETURN: string, all arguments in a string
"""
return ", ".join(
[f"{k}={repr(v)}" for k, v in reversed(list(args_dict.items()))]) | 2213410e6d6a89e270576b2da3011f57096fd58d | 680,038 |
def color_percents(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
if val == 100:
color = 'green'
elif val >= 99:
color = 'greenyellow'
elif val >= 95:
color = 'yellow'
else:
... | 5961a0786f4973213cdef5b22a0c34edcbc44d54 | 680,039 |
def readable_size(i, snapshot=False):
"""
Pretty-print the integer `i` as a human-readable size representation.
"""
degree = 0
while i > 1024:
i = i / float(1024)
degree += 1
scales = ["B", "KB", "MB", "GB", "TB", "EB"]
if snapshot:
return f"{i:+.2f}{scales[degree]:>5... | d15a58ee7c6fdb13f50408de479aae6d1001f43d | 680,040 |
def get_gaze_in_frame(gaze_series, width, height):
"""Calculate location of gaze corresponding to the video frame coordinate
:param gaze_series: all gazes in the video frame
:param width: width of the video frame
:param height: height of the video frame
:return x_img_coor: x coordinate of the gaze... | b7adb1f6a953aeef3cb004aac8dde92956c11a9d | 680,041 |
def is_prime(number):
"""判断一个数是否为素数"""
if number < 2:
return False
# 中间整数
number_center = int(number / 2)
# 最小数只能为2以上
start = 2
# 是否为素数
prime_status = True
# 循环整除中间数以下的数字
while start <= number_center:
if number % start == 0:
prime_status = False
... | 6225dd5b8721279c664a03eddcb8893fa735ee01 | 680,042 |
def num_explicit_hydrogens(a):
""" Number of explicit hydrodgens """
return a.GetNumExplicitHs() | a6364c2515f3f32da3ca0c7ec9ad4a2a4c82eca0 | 680,043 |
def get_projects(conn, scenario_id, subscenarios, col, col_value):
"""
Get projects for which the column value of "col" is equal to "col_value".
E.g. "get the projects of operational type gen_commit_lin".
:param conn: database connection
:param subscenarios: Subscenarios class objects
:param col... | 52d022b3e1862d66decc08fa4a687a141953898f | 680,044 |
def introspection_query(description: bool = True) -> str:
"""
Return a generic introspection query to be used by GraphQL clients.
Args:
description: If ``True`` the query will require descriptions.
Returns:
Canonical introspection query
"""
return """
query IntrospectionQu... | 26bf135d045071b14c77f41e9d37c1c33fe23605 | 680,045 |
def flatten_strokes(strokes):
"""
Flatten a list of strokes. Add stroke state in the process.
For each point j, the stroke state is a tuple (pj, qj, rj) where:
* pj=1 indicates the point is not the end of a stroke.
* qj=1 indicates the point is the end of a stroke (but not the end of the drawin... | ecd1828ff013283486253b2a4dd73cc4cd3ef549 | 680,046 |
import time
def retry_on_exception(num_retries, base_delay=0, exc_type=Exception):
"""If the decorated function raises exception exc_type, allow num_retries
retry attempts before raise the exception.
"""
def _retry_on_exception_inner_1(f):
def _retry_on_exception_inner_2(*args, **kwargs):
... | 4283b97b002971fc61bde2050c34c272b93219c5 | 680,047 |
def get_raw_data(x_norm, min_val, max_val):
"""
Get raw data from the normalized dataset
"""
x = x_norm * (max_val - min_val) + min_val
return x | 5a41b2fc4c22b050ad56a36455ca3e2d37a379f4 | 680,048 |
import os
def supports(fn, d):
"""Return True if fn has a supported extension"""
return os.path.splitext(fn)[-1] in [".bb", ".bbclass", ".inc"] | f198a8746a7fee52946844d6f79462bc318c6e3f | 680,049 |
def log_add(a, b):
"""add `a` and `b` and send message to logger."""
return a + b | 428fda3450d209977241051519300a639b790201 | 680,050 |
import torch
def optimizer_factory(optimizer_name, optimizer_params, trainable_params):
"""
creates one of a few optimizers. we return None if we are unable to create
the requested optimizer
"""
if optimizer_name == 'SGD':
l_rate = optimizer_params['learning_rate']
mome... | e413b7303b5167a62742aa557acbe755443473d8 | 680,051 |
import os
import zipfile
def create_zip_archive(source_folder: str, archive_name: str, target_folder: str):
"""
Create ZIP archive named <archive_name> in <target_folder> from folder <source_folder>
:param source_folder: source folder
:type source_folder: str
:param archive_name: name of result a... | f9f6717244249e47dc32ccd65839a1903425a47a | 680,052 |
def find_peaks_above_min_height(x, size, min_height, max_num):
"""
Find all peaks above MIN_HEIGHT
"""
i = 0
n_peaks = 0
ir_valley_locs = [] # [0 for i in range(max_num)]
while i < size - 1:
if x[i] > min_height and x[i] > x[i-1]: # find the left edge of potential peaks
... | 4834eddf87c733ed549770cbcb7cba092bcb9e63 | 680,053 |
import copy
import torch
def get_printoptions() -> dict:
"""
Returns the currently configured printing options as key-value pairs.
"""
return copy.copy(torch._tensor_str.PRINT_OPTS.__dict__) | 4d5bea94df1cabb99be851c7451defe2beba18d9 | 680,055 |
import numpy
def float_less_or_equal(lhs, rhs, **kwargs):
"""Determine float A is less than or equal to B using numpy.isclose().
Use numpy.isclose() to determine if A and B are equal
with default tolerance.
Args:
lhs, rhs (float): values that need to be compared
kwargs: kwargs fo... | c0eff957a0d233824181ac5e2627a584d549d57d | 680,056 |
def get_reverse_bit_string(number: int) -> str:
"""
return the bit string of an integer
>>> get_reverse_bit_string(9)
'10010000000000000000000000000000'
>>> get_reverse_bit_string(43)
'11010100000000000000000000000000'
>>> get_reverse_bit_string(2873)
'10011100110100000000000000000000'
... | 4ae321e00433f7e11d44383546946713231f1bc1 | 680,057 |
def get_cavity_phases(fn):
""" Given an OPAL input file, extract phi1, phi2, phi3, phi4 (rad) """
with open (fn, 'r') as f:
getvars = {'t_offset': None,
'dphi': None,
'phi_correction': None,
'phi0': None,
'phi1': None,
... | 8c3574836bb7dee52aa5b41228325a6bfdeac701 | 680,058 |
def get_words(directory_name: str, language: str) -> list:
"""Returns a list of words found in the file"""
file_name = directory_name + '/word-list.' + language + '.txt'
word_list_file = open(file_name, 'r', encoding='utf8')
word_list = []
for line in word_list_file:
word_list.append(str... | 2eb33931a710d361a1ef69153166c00a17980f42 | 680,059 |
def load_diachronic_dataset(datapath="data/nytimes_dataset.txt", start_date="2019-01-01", end_date="2020-12-31"):
"""
Read in a diachronic dataset with "%Y-%m-%d\tsentence" per line
Inputs:
- datapath [str]: path to a dataset with tab-separated dates (in the same format as start/end_date)
... | 55913646163e5557b3c2b0dbccc72a5c7cc9c46e | 680,061 |
import argparse
def parse_arguments(*arg):
"""
--start
--stop
--restart
--time 13h24m23s
--after 360s
--repeat 4
"""
parser = argparse.ArgumentParser()
parser.add_argument("--start",
help="Start daemon",
action="store_true")
... | c9205b74f0c0ff47604225aace529c0da7e1eeb1 | 680,062 |
def get_issue_fields(jdownloader, custom_fields_api_address):
"""
Posts a request using an instance of JiraDownloader and returns the fields
of the Jira instance. For Jira fields, they are returned as-is (e.g. name), while
the custom fields are renamed (e.g. custom2442 is replaced by its name in lower case
without... | 45332f71912be930960e9eb3e49b095dd1bb3bf6 | 680,063 |
import requests
def make_request(url, headers=None):
"""
make an http request
"""
r = None
try:
r = requests.get(url, headers=headers)
except Exception as e:
raise e
return r | 9e7cfbc8941e983d968c2ba0515a0ce5db856400 | 680,064 |
import numpy
def init(img, _blk_size, _Beta_Kaiser):
"""该函数用于初始化,返回用于记录过滤后图像以及权重的数组,还有构造凯撒窗"""
m_shape = img.shape
m_img = numpy.zeros(m_shape, dtype=float)
m_wight = numpy.zeros(m_shape, dtype=float)
K = numpy.matrix(numpy.kaiser(_blk_size, _Beta_Kaiser))
m_Kaiser = numpy.array(K.T * K) ... | 186b4c67c1f2588b26bd165c0495b4f403fe1a4f | 680,065 |
def _is_ascii(text):
"""
Args:
text (str): Text to check.
Returns:
bool: whether or not the text can be encoded in ascii.
"""
return all(ord(char) < 128 for char in text) | 8fbdf88451665403d972f174b144796cf216690e | 680,066 |
import math
def attacker_success_probability(q: float, z: int):
"""
Compute the probability of an attacker to create a longer trusted chain
:param q: probability the attacker finds the next block
:param z: number of blocks behind
:return: probability the attacker will ever catch up from z blocks b... | 0636b86b7a4ec6cf8b619590773e992c56fceb3f | 680,067 |
import os
def get_embedded_lib_path() -> str:
"""Return path of embedded libraries."""
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "embedded") | 568c7010bb53f08f409ff4ecac954315de9b888f | 680,068 |
from torch import optim
from functools import partial
def get_optimizer(optimizer):
"""
Returns an optimizer according to the passed string.
:param optimizer: The string representation of the optimizer. eg. 'adam' for Adam etc.
:return: The proper nn.optim optimizer.
"""
_optim_dict = {'adam': partial(optim.Ad... | d7e30de7e7d19dbef3c2fd6475895b213913af4c | 680,069 |
import logging
def is_valid_dataset(platform):
"""Filters out datasets that can't be used because it is missing required data
such as the release date or an original price. Other required data includes
the name and abbreviation of the platform.
"""
if 'release_date' not in platform or not platfor... | 715187e707e6e070bb170ebceedd5e05bd9124c9 | 680,070 |
def parse_tickers(tickers):
"""accepts tickers string input i.e. 'GOOG,AAPL,MSFT'
and outputs tickers list ['GOOG','AAPL','MSFT']"""
num_commas = tickers.find(',')
tickers = tickers.rsplit(',',num_commas+1)
return tickers | 5eb9be6ea51df6ecac1b64ab38553d583d5d7ed9 | 680,072 |
def homeolog_ratio_and_weighting(chr_group):
""" Extract pairing fidelity values encoded on each chromosome to obtain a mean for the individual.
:param chr_group holds a single chromosome group, e.g. 'A8A8a8a8'
:type chr_group: str
"""
mei_cost = int(chr_group[1]) + int(chr_group[3]) + int(chr_group... | f7d5d3f9e0b800c94c1983ca3aa49c943059494c | 680,073 |
from datetime import datetime
def _zulu_to_epoch_time(zulu_time: str) -> float:
"""Auxiliary function to parse Zulu time into epoch time"""
epoch = datetime(1970, 1, 1)
time_as_date = datetime.strptime(zulu_time, "%Y-%m-%dT%H:%M:%SZ")
return (time_as_date - epoch).total_seconds() | ea5ca60979f5c9f10f5a1a9d00e733de06f20a55 | 680,074 |
import functools
def compose(*functions):
"""
Compose functions.
"""
return functools.reduce(lambda f, g: lambda x: g(f(x)), functions,
lambda x: x) | 5e8ee44e0833388f7e136095ca63c8538e9827e4 | 680,075 |
def _find_closest_year_row(df, year=2020):
"""Returns the row which is closest to the year specified (in either direction)"""
df = df.copy()
df['year'] = df['year'].sort_values(ascending=True)
return df.loc[df['year'].map(lambda x: abs(x - 2020)).idxmin()] | 30f254ef97e70907d8b1e7d05eeeda15151b95ea | 680,078 |
def _list(element):
"""
Function to work with list
"""
print("This object is a dictionary. Here are all elements.")
for i in range(len(element)):
print(f"{i+1}) {element[i]}")
choice = int(input("Type the humber of the element: "))
return element[choice-1] | 5d29b1ccd3280f287a3869793f1407bafeebdede | 680,079 |
def build_k_dataset(object_file, words_size):
"""Process triples into a dataset."""
entity_id = {}
relation_id = {}
triples = []
j, k = words_size, 0
_ = 0
total = 17
done = 0
with open(object_file) as of:
for i, line in enumerate(of):
line = line.split()
... | dfd4c36080adfa0fc065fa2be2c394e9e2789f98 | 680,080 |
def get_archive_subdir(header):
"""
Builds a subdirectory name for a file within the archive based on header keywords.
Args:
header (:obj:`astropy.io.fits.Header`): FITS header of the file to put into the archive.
Returns:
:obj:`str`: Subdirectory under the archive root to place the ... | 3b601ce08c4e0bcb752b2d0888f70deb3e43983a | 680,081 |
from pathlib import Path
def _validate_magics_flake8_warnings(actual: str, test_nb_path: Path) -> bool:
"""Validate the results of notebooks with warnings."""
expected_out = [
f"{str(test_nb_path)}:cell_3:6:21: E231 missing whitespace after ','",
f"{str(test_nb_path)}:cell_3:11:10: E231 missin... | 3fc22ee0011ffa874d29a0b1d3b140052e502195 | 680,082 |
import inspect
def allows_unknown_args(command):
"""Implements really simple argument injection for unknown arguments.
Commands may add an optional argument called "unknown args" to
indicate they can handle unknonwn args, and we'll pass the unknown
args in.
"""
info = dict(inspect.getmembers(... | 8c9c57a096f2a799107b270a866d3048f3118b89 | 680,083 |
import re
def _fullmatch(pattern, text, *args, **kwargs):
"""re.fullmatch is not available on Python<3.4."""
match = re.match(pattern, text, *args, **kwargs)
return match if match.group(0) == text else None | 0e005cad29dfe836f7bdeb01bf140e4ed2c49b6e | 680,084 |
def fixChars(text:str) -> str:
"""Fixes \\xa0 Latin1 (ISO 8859-1), \\x85, and \\r, replacing them with space"""
text = text.replace(u'\xa0', u' ')
text = text.replace(u'\x85', u' ')
text = text.replace(u'\r', u' ')
return text | 2620a88e71641cb4863b914e9d913fb6247a3364 | 680,085 |
def get_metadata_value(structure_list, desc_metadata):
"""Retrieve a given metadata from a list of structures from the descriptor key"""
desc_metadata_list = []
for structure in structure_list:
desc_metadata_value = structure.info['descriptor'][str(desc_metadata)]
desc_metadata_list.append(... | f14f5003cb31a576808b625403368a8b2ba59509 | 680,087 |
import os
import csv
def get_lines_from_file(path):
"""Get CSV Data as Python List
:param path: path for driving_log.csv
:return lines: csv data list
"""
error_txt = "{} does not exist!!".format(path)
assert os.path.exists(path), error_txt
lines = []
with open(path) as ... | 935233c792b882975fadf088de98b64b5bd0e3dd | 680,088 |
import os
def has_gpu():
""" check where has a nvidia gpu """
ret = os.popen("nvidia-smi -L 2>/dev/null").read()
return ret.find("GPU") != -1 | 2334076d0e6eeaadd55a90b8cfd8685197eebce8 | 680,089 |
import ntpath
import posixpath
def to_posix(path):
"""
Return a path using the posix path separator given a path that may contain
posix or windows separators, converting "\\" to "/". NB: this path will
still be valid in the windows explorer (except for a UNC or share name). It
will be a valid path... | 6e11d24beda6316168462220a771ce90369e8eb0 | 680,090 |
def get_fusion_major_key(fusion_major_soup):
"""
:param fusion_major_soup:
Saint.soup_jar['융합전공']
:return:
"""
label = fusion_major_soup.find('label', text='융합전공')
return label.get('f') | 04e9b7dc2d090bcfa339f1c56edfc846edd9575b | 680,091 |
def getScreenHeight():
"""A stub implementation of the xbmcgui getScreenHeight() function"""
return 1080 | a8d64d3a81dcbc36e95e57968dc4408301918dcb | 680,092 |
def SafeToMerge(address, merge_target, check_addresses):
"""Determine if it's safe to merge address into merge target.
Checks given address against merge target and a list of check_addresses
if it's OK to roll address into merge target such that it not less specific
than any of the check_addresses. See descrip... | 152f4a52cdb03adcd86ff2f03578f15a9aa31f37 | 680,093 |
import string
def fmt_to_name(format_string, num_to_name):
"""Try to map a format string to a single name.
Parameters
----------
format_string : string
num_to_name : dict
A dictionary that maps from an integer to a column name. This
enables mapping the format string to an integer... | 3f8edb995c08a36e262aeaf8c9b5728c9c286db6 | 680,094 |
import re
def _replacestrings(source):
"""Strip string lookup table (list) and replace values in source."""
match = re.search(r'var *(_\w+)\=\["(.*?)"\];', source, re.DOTALL)
if match:
varname, strings = match.groups()
startpoint = len(match.group(0))
lookup = strings.split('","')... | 4f839a39b82a17e5c73d577677e1e2f9c82659f0 | 680,095 |
def PNT2QM_Tv4(XA,chiA):
""" TaylorT2 2PN Quadrupole Moment Coefficient, v^4 Timing Term.
XA = mass fraction of object
chiA = dimensionless spin of object """
return -10.*XA*XA*chiA*chiA | c9cbd371eea8c0838c1fc77906754a10e7a92092 | 680,096 |
def index() -> str:
"""
Creates a route to return the note that connection is established.
:return: connection status
"""
try:
return "Connection established"
except:
return "There was a problem loading the app" | ffd6933978c36029a3a1b3e041e5592c554c4093 | 680,097 |
import requests
import json
def get_recent_gameweek_id():
"""
Get's the most recent gameweek's ID.
"""
data = requests.get('https://fantasy.premierleague.com/api/bootstrap-static/')
data = json.loads(data.content)
gameweeks = data['events']
for gameweek in gameweeks:
if gameweek... | 8bd4f3a23fbe2281bc6bd8eb65ea7da541064dcf | 680,098 |
import argparse
def parser_arguments():
""" parseaza argumentele primite la rularea programului """
args = argparse.ArgumentParser()
args.add_argument('path',
type=str, help="unde cautam")
args.add_argument('pattern',
type=str, help="tiparul de gasit")
a... | 09078c9f6229e945c248bd7513cec10fa81b7116 | 680,099 |
import requests
def get_students_registered_for_class(url, username, password, crn, term):
""" Grabs the students registered for a course in a particular term
Uses an API like
https://boomi.som.yale.edu:9090/ws/rest/subscribers/klj39/CourseRoster/
Arguments:
url {string} -- API URL, e... | ccd905bba80bc6bac4ab5d310b18274971716fbd | 680,100 |
def computeEER(rates, withthresh=0):
"""Computes equal error rates from the list of (true pos, false pos) values.
If withthresh is true (not the default), then returns (eer, index at which eer occurs)."""
det, fpos = zip(*rates)
fpos = map(float, fpos)
npos = [1.0-f for f in fpos]
difs = [(abs(d... | 062e5c475023a7d359eb9debbf815344055f0568 | 680,101 |
def is_nonAA(residue):
"""
Parameters
----------
residue : a residue from a protein structure object made with PDBParser().
Returns
-------
Boolean
True if residue is hetero or water, False otherwise.
"""
residue_id = residue.get_id()
hetfield = residue_id[0]
return ... | f79ad24fa1e759998ad24c01e226f22e1ed03567 | 680,102 |
import sys
def main(argv=sys.argv):
"""
Args:
argv (list): List of arguments
Returns:
int: A return code
Does stuff.
"""
print(argv)
return 0 | b61ee77cbbdc643b85192e754273647dc95acef9 | 680,103 |
import string
import random
def key_generator(size=6, chars=string.ascii_uppercase + string.digits):
"""
Generates random strings for things that need keys. Allows variable size and character lists, if desired.
NOT CRYPTOGRAPHICALLY SECURE
:param size: Size of the key to generate
:param ch... | b1f0beb2286841734145d97c6ce4f51ec8cce5e7 | 680,104 |
def all_columns(df, names):
"""
Test if df has all columns
"""
array = [name in df.columns for name in names]
return sum(array) == len(array) | 46d954e21492bbb56bc5eae78c14caa0510aa37a | 680,105 |
import json
import os
def create_frequency_map_policy(min_freq, max_freq, frequency_map, use_env=False):
"""Create a frequency map to be consumed by the frequency map agent.
Arguments:
min_freq: Floor frequency for the agent
max_freq: Ceiling frequency for the agent
frequency_map: Dictionary mapp... | 24ed5f4fc7d269e49d4590252555222af31c98c9 | 680,106 |
def format_repeats(file):
"""
Deal with the repeating blocks in the model
by keeping track of the encompassed rows and
multiplying them before appending.
"""
ret = []
while True:
try:
l = next(file).lstrip().replace('\n','')
except StopIteration:
break... | 1edcaf10005f7ad9528fc4434029fe711c13b3e2 | 680,107 |
from typing import Union
def convert_memory_limit(memory: Union[str, int]) -> int:
"""Converts a provided memory limit with optional units into
its equivalent in bytes.
Args:
memory: String or integer representation of memory limit.
Returns:
The provided memory in bytes.
"""
... | 2a0357cfee8c8124c99735d4ea814fa86ca0a3cd | 680,108 |
import hashlib
def hash_level(level: str) -> str:
"""
Used in:
- downloadGJLevel22.php
"""
data = ''
l = len(level) // 40
for i in range(40):
data += level[i * l]
return hashlib.sha1(bytes(data + 'xI25fpAapCQg', 'utf-8')).hexdigest() | 09fb92ea0b6c7b213bdb14324e0e4127e0b5f98a | 680,109 |
def centroid_atmList(atmList):
"""Get centroid for list of atoms."""
i, x, y, z = 0, 0, 0, 0
for atm in atmList:
x += atm["x"]
y += atm["y"]
z += atm["z"]
i += 1
return x/i, y/i, z/i | b25af20d470246130990add7add974bdac72c951 | 680,110 |
import os
import time
def loggers(args):
"""Training and test loggers from input arguments"""
os.makedirs(args.log_dir, exist_ok=True)
training_log = open(os.path.join(args.log_dir, 'training.csv'), 'w')
testing_log = open(os.path.join(args.log_dir, 'test.csv'), 'w')
print('%s,%s,%s,%s'% ('index... | 8be9633c2c5eb413914308dace36ddcf35600850 | 680,111 |
def right(i,j,table):
"""Return the product to the right"""
product = 1
for num in range(4):
if j+num>19: product*=1
else: product *= int(table[i][j+num])
return product | 2317c35f9c5bf43256b317a49f6eba81f15b51d9 | 680,112 |
def gpsToMjd (gps):
"""
The BBH sims are given a time in gps seconds.
This is seconds since 0:0:0 6-Jan-1980 and as of 2016 is 17 seconds ahead of UTC
We take this zeropoint time to be MJD= 44244.0.
This routine corrects for the 17 seconds, which means it becomes progressively
less accuate as the date move... | ecc0e39947ed7137990a1b756fdbaa4dc0266377 | 680,114 |
def _process_parameters(parameters):
"""
Run over the parameters are extract parameter and column name. This function deals with figuring out if a
requested parameter also has a user defined output name.
.. note::
Function for internal use!
:param parameters: list of tuples or strings cont... | 2005c1841bbad5c1ac48f37b365102d04adf41ae | 680,115 |
def default_score_transfer_function(x: float) -> float:
"""
A quadratic transfer function.
:return: max(0.0, x^2)
"""
return max(0.0, x ** 2) | 28574822136a8d3439fc922e067b3bd16f5e0940 | 680,116 |
import configparser
def import_test_configuration(config_file):
"""
Read the config file regarding the testing and import its content
"""
content = configparser.ConfigParser()
content.read(config_file)
config = {}
config['gui'] = content['simulation'].getboolean('gui')
config['max_step... | 04ab5c49ffb4b44e4bce7c2bc96b6ea76407316c | 680,117 |
def solve_modular_equation(a, b, c):
"""
Find solution of ax % b = c (a and b relative primes, ie assume gcd(a, b) == 1)
pow(a, -1, mod=b) computes the modular multiplicative inverse for python >= 3.8
"""
return (pow(a, -1, mod=b) * c) % b | ee2cc41ae8347f448e5eac1542c49d0e29bec84c | 680,118 |
import argparse
import pathlib
def create_parser():
"""Create parser object"""
parser = argparse.ArgumentParser(
description='Create an MMD xml file from an input netCDF file.'
)
# Add to parse a whole server?
parser.add_argument(
'-i', '--input', type=str,
help='Input fil... | ce2f33ba049ec791880bebf472955a2dd678296a | 680,119 |
def get_place(city, country):
"""Join city and country args."""
city = str(city).replace(' ', '%20')
country = str(country)
return f"{city},{country}" | 956ecb687806faa2df6596b394ab95e052015623 | 680,120 |
def manual_parse(input_msg, options=None, func_on_inp=None):
"""
when the script couldn't parse a field, ask a person
:param input_msg: explain about the field
:param options: the options of the field. for convenience matters.
:return:
"""
if options:
err_msg = 'Invalid input. pleas... | e53f494db6ed1a546e1ac18ecc85157536961390 | 680,121 |
import requests
from bs4 import BeautifulSoup
def fetch_pkg_version(pkg_url: str) -> str:
"""
Find the version of package documentation
:param pkg_url: Full URL of package documentation
:return: version string of the package requested
"""
# fetch the page and parse version
page = requests... | 1c003678caed66d891844a5ddf093d7ebaba4512 | 680,122 |
def get_param(param, arguments, default=None):
"""
Get parameter from list of arguments. Arguments can be in following format:
['--parameter', 'param_value'] or ['--parameter=param_value']
Args:
param (str): Name of parameter
arguments (list): List of arguments from CLI
default ... | 1dddce2639d563de6bb9177d1fc0a87b22ee7b52 | 680,123 |
def vowelsRemover(words):
"""This function takes in a string
and returns a string back without vowels"""
m_vowels = ['a', 'e', 'i', 'o', 'u']
m_temp = ""
for letter in words:
if letter.lower() not in m_vowels:
m_temp += letter
return m_temp | 2d6b3f05e3f6d5eb2e9a5be2bb602d6825bff56d | 680,124 |
import string
import random
def random_id(size=8, chars=string.ascii_letters + string.digits):
"""Generates a random string of given size from the given chars.
@param size: The size of the random string.
@param chars: Constituent pool of characters to draw random characters from.
@type size: number
@type cha... | ccc89ef294e0d55f701bb678b3d2804ed78ec835 | 680,125 |
def type_of_exception(exception_object):
"""Get the type of an exception object as a string or None"""
if isinstance(exception_object, Exception):
return str(exception_object.__class__.__name__) | 2cdf774fce1c2bb57a86d7ddbf0feddabdb82d26 | 680,126 |
from sys import stdout
def prompt(text):
"""Writes a prompt message and returns the user's answer"""
stdout.write(text)
return input() | 63f0fd418f0a09c29bd8b504a9908fcbe1f89122 | 680,127 |
def generate_bins() -> list:
"""
Generate color bins.
:return: List of bins
"""
h_bins = [(x / 10.0, (x + 1) / 10.0) for x in range(0, 10)]
h_bins[-1] = (h_bins[-1][0], 1.1)
s_bins = [(0.0, 0.333), (0.333, 0.666), (0.666, 1.1)]
l_bins = [(0.0, 0.333), (0.333, 0.666), (0.666, 1.1)]
bi... | fa207596bc915f83145964d6a07b5140fb021e5d | 680,128 |
def intermediate_text_filename_generation(cote, lang):
"""
Generate the name of a given intermediate text
cote : the cote
lang : the language to look for to create the texts. Must follow the Code convention ("f","l","t" or "a")
Return : str
"""
lang_dict = {"f":"fr","a":"de","t":"it","l":"la... | 9375d651cc4ea40dbb572237b93421dfbfcba1ac | 680,129 |
def dlr_del_dgw(client_session, dlr_id):
"""
This function deletes a default gw to one dlr
:param dlr_id: dlr uuid
"""
# get a template dict for the dlr routes
dlr_static_route_dict = client_session.extract_resource_body_example('routingConfig', 'update')
# add default gateway to the create... | 0b9a5c23ecde889a7b2d3012e2062d2dbbad6da0 | 680,131 |
def run_parallel_python(model_script, model_object_name, sample, dict_kwargs=None):
"""
Method needed by ``RunModel`` to execute a python model in parallel
"""
_ = sample
exec('from ' + model_script[:-3] + ' import ' + model_object_name)
if dict_kwargs is None:
par_res = eval(model_obje... | 0b82f85746ba65007b6e5d229839c87e0d845042 | 680,132 |
def create_thumbnail(image):
"""创建缩略图"""
return image.thumbnail((128, 128)) | b61ff9b71733146e68027c740c319106ae86116f | 680,133 |
def next_cma(new_value, list_len, old_cma):
""" Calculate next cumulative moving average
'list_len' is the length of the currently being averaged list before adding the new value
"""
return (new_value + list_len * old_cma) / (list_len + 1) | a21791ac76f856881c0a9a869b3d7bbe8d0af6f9 | 680,134 |
def rubygems_api_url(name, version=None):
"""
Return a package API data URL given a name, an optional version and a base
repo API URL.
For instance:
>>> url = rubygems_api_url(name='turbolinks', version='1.0.2')
>>> assert url == 'https://rubygems.org/api/v2/rubygems/turbolinks/versions/1.0.2.j... | fe65efd39f4b1707588d1dc419fcc570070f6289 | 680,135 |
def __read_csv_2(csvdata):
"""Load data from CSV file without headers, that the first column is for PV, like:
PV,machine=xxx,elemIndex=xxx,elemPosition=xxx,elemName=xxx,elemHandle=xxx,elemField=xxx,elemType=xxx, tag1,tag2,tag3
the last one are all tags.
Parameters
----------
csvdata : list
... | 3b79fceb4e9b1556f8bd8954bf51baf82438f0d3 | 680,136 |
def prob(G, datapoint):
"""
Parameters
----------
G : pgmpy BayesianModel
A Bayesian network (with learned parameters).
datapoint : dict
One observation from the dataset indexed by the variables names.
Returns
-------
prob : float
The probability of observing tha... | c7258cc7655774359d93c490effae2e0cd203b90 | 680,137 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.