content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_openapi_description(endpoint: str, method: str) -> str:
"""Fetch a description from the full spec object."""
return openapi_spec.openapi()["paths"][endpoint][method.lower()]["description"] | a2c2565732372945e985ffb5395d4f2e29f2ce94 | 3,612,800 |
from operator import concat
def union(coords_list):
"""
Combine the given coordinates by collecting the unique, sorted coordinate values in each dimension.
Arguments
---------
coords_list : list
List of :class:`Coordinates`.
Returns
-------
coords : :class:`Coordinates`
... | 9c4215691edcc65458679e90d5a7de477d8fdf26 | 3,612,801 |
def DrawGeometryAddVertexBuffers(builder, vertexBuffers):
"""This method is deprecated. Please switch to AddVertexBuffers."""
return AddVertexBuffers(builder, vertexBuffers) | eb3138c48866b1b9a432b5531c38702e1bc04dcc | 3,612,802 |
from typing import List
from typing import Dict
def get_audio_features_dictionary(tracks: List) -> Dict:
"""Short summary.
Parameters
----------
tracks : List
Description of parameter `tracks`.
Returns
-------
Dict
Description of returned object.
"""
LIMIT = 100... | 47cc34fd5ae9eb6532be1d2cc6a5dd7b43f6aadc | 3,612,803 |
import time
def run_ntp(temps, tous):
""" Fonction qui permet de lancer le test NTP
Paramètres : temps, un int et tous un boolean
Return : un tuple de int, (nb_test, test_ok)
"""
# Initialisation des variables
sec = 0
num_lines = 0
thread_time = temps
test_ok = 0
nb_tes... | 3bde1ac4d45ef21ae5207a84b12a4169b91d3f28 | 3,612,804 |
import numpy
def get_scan_info(tod=None, az=None, ctime=None):
"""
Analyze az info (for tod, or pass in an az and ctime).
Returns a struct with results.
"""
if az is None:
az = tod.az
if ctime is None:
ctime = tod.ctime
output = moby2.libactpol.analyze_scan(
numpy.... | 0a897f75738ded5bb0d3bcecd933d397dbc323fc | 3,612,805 |
def __update_categorical(self, condition, values):
"""
Returns an updated version of this column.
All entries for which the corresponding **condition** is True,
are updated using the corresponding entry in **values**.
Args:
condition (Boolean column): Condition according to which the updat... | 687409871a5d7beb972c18fb91ccc23df2d67a2c | 3,612,806 |
def epsilon_greedy(epsilon=None):
"""An epsilon-greedy distribution."""
def sample_fn(key: Array, preferences: Array, epsilon=epsilon):
return distrax.EpsilonGreedy(preferences, epsilon).sample(seed=key)
def probs_fn(preferences: Array, epsilon=epsilon):
return distrax.EpsilonGreedy(preferences, epsilon... | 1d8b282ad0fe32f3c765dc6716d75ef675807869 | 3,612,807 |
def cosine_similarity(topics, segmented_topics, per_topic_postings, measure, gamma, num_docs):
"""
This function calculates the indirect cosine measure. Given context vectors
_ _ _ _
u = V(W') and w = V(W*) for the word sets of a pair S_i = (W', W*) indirect
... | 51811eedff7c8717684b43242a0394a0d1e32323 | 3,612,808 |
def REPLACE(
old_text: func_xltypes.XlText,
start_num: func_xltypes.XlNumber,
num_chars: func_xltypes.XlNumber,
new_text: func_xltypes.XlText
) -> func_xltypes.XlText:
"""REPLACE replaces part of a text string, based on the number of
characters you specify, with a different text ... | e1831b11dfadddaad34707b47d0d2e9801ad8d21 | 3,612,809 |
from typing import List
def _remove_duplicate_paths(
path_list: List[ShortestPath]
) -> List[ShortestPath]:
"""Remove each duplicated path from the given list and return a new path
list."""
# Map each unique path to its stringified action list.
unique_path = {}
for path in path_list:
#... | d3cd37781f7a2ba1446b13de4fa63fa5b62096ce | 3,612,810 |
from re import A
def link_other(label, url, path, wrapper=SPAN, **kwargs):
"""
Only wrap label in anchor if given target URL, ``url``, does not match the
``path``. Given a label, this function will match the page URL against the
path to which the anchor should point, and generate the anchor element
... | 9b33e9c773614e315b7059d611d3fa5c3b40c404 | 3,612,811 |
import os
def report_to_github(repo, pull_request, sha, suite, docs):
"""
Report test results to Github
:param repo: repo name
:param pull_request: pull request number
:param sha: pull request SHA
:param suite: Test suite
:param docs: documentation of statuses
:return: nothing
... | f1bca631d9544cbbd548da2eda977605b7c05d52 | 3,612,812 |
def _moon_ul_alt(observer, moon, t):
"""Returns the altitude of the moon's upper limb in degrees when seen from
observer at terrestrial time t.
Calculates the moon's apparent semidiameter from the location of
``observer``
"""
moon_distance = observer.at(ts.tt(jd=t)).observe(moon).apparent(... | e040141f0820fa910767b0d171e6e6bc5b89c2d8 | 3,612,813 |
def sort_files(curr_dir: str):
"""Setting up drift evaluation settings.
Function for setting up drift evaluation settings like output
filename, getting file lists etc.
Parameters
----------
curr_dir : str
Returns
-------
measlist : list of str
"""
curr_dir = DirPerkeo(cu... | c32df1c9aff9f0a57e9ec176ff27a47d03290d69 | 3,612,814 |
def fisher_exact_test(c1, c2, c3, c4) -> StructExpression:
"""Calculates the p-value, odds ratio, and 95% confidence interval with Fisher's exact test for a 2x2 table.
Examples
--------
.. doctest::
>>> hl.eval_expr(hl.fisher_exact_test(10, 10,
... 10,... | 51d3f442fcd90a35d0ce76358c008ab403ac3317 | 3,612,815 |
def SBHostOS_ThreadDetach(*args):
"""SBHostOS_ThreadDetach(thread_t thread, SBError err) -> bool"""
return _lldb.SBHostOS_ThreadDetach(*args) | 56e418de056ed88e1f5f9fbfbb7f8bb2d9ef2a28 | 3,612,816 |
def Columns(objects):
"""Returns a padded Urwid Columns object that is left aligned."""
# Objects is a list of widgets. Widgets may be optionally specified
# as a tuple with ('weight', weight, widget) or (width, widget).
# Tuples without a widget have a weight of 1."""
return urwid.Padding(Tab... | efcad138bf6fd74368bad15237de880490e5b279 | 3,612,817 |
def splitall(path):
"""
Split a path to a list.
Example:
>>>splitall('/public/home/user/code')
['public','home','user','code']
"""
allparts = []
while True:
path, p1 = op.split(path)
if not p1:
break
allparts.append(p1)
allparts = allparts... | 51d7f427d691eb8ad8e6304b5ffa1225926ca749 | 3,612,818 |
def _insert_entry_node(entry_node, way_nodes):
""" insert node reference in the correct position of way_nodes """
insert_position = _find_insert_position(entry_node, way_nodes)
way_nodes.insert(insert_position, entry_node)
return way_nodes | 13c8d9f5c228a173747386d06dc5700a30d53d1a | 3,612,819 |
def diff_hostlogg(params1, params2):
"""Differnece in parameters when param2teff changes bu +100"""
rvs = [0]
gammas = [0]
s1 = combine_spectrum(params1, params2, rvs, gammas, plot=False).squeeze()
params_new = [params1[0], params1[1]+0.5, params1[2]]
s2 = combine_spectrum(params_new, params2, r... | 98984e22e2ad6c57f00f0be8dbb83afe4c66fb51 | 3,612,820 |
import types
def task__iso_digest() -> types.TaskDict:
"""Compute the SHA256 digest of the ISO."""
return helper.Sha256Sum(
input_files=[ISO_FILE],
output_file=config.BUILD_ROOT/'SHA256SUM',
task_dep=['_iso_build']
).task | e99952b85a5361f4e2ba2a6bdb3202ab698ed0b8 | 3,612,821 |
def scenario_folder(model_code, scenario):
"""
Path to the folder of the given scenario.
:param model_code: code of the model
:param scenario: name of the scenario
"""
return model_folder(model_code) + scenario + _SEP | 3327cdc8d2acc0aa9969089ecfc58edecfb36def | 3,612,822 |
def make_grid_2d(numPix, deltapix, subgrid_res=1):
"""
creates pixel grid (in 2d arrays of x- and y- positions)
default coordinate frame is such that (0,0) is in the center of the coordinate grid
:param numPix: number of pixels per axis
:param deltapix: pixel size
:param subgrid_res: sub-pixel ... | 1572b14580369ac7e6ebc85486c462f17555faa3 | 3,612,823 |
def asNormalizedJSON(value):
"""Answer the value as normalized object, where all values are converted into
base objects, dict, list and string.
>>> src = dict(aa='bb', cc=[1,2,3,4], dd=dict(ee=123, ff='ABC'), gg={3,4,5,5,6,6,7,7})
>>> result = asNormalizedJSON(src)
>>> sorted(result.keys())
['a... | 6e4e6c11b459a50e4a3ca731b76d2742d7b3b5a7 | 3,612,824 |
def months_of_buffer():
"""
Real Name: Months of Buffer
Original Eqn: INTEG ( Income-Expenses, Initial Buffer)
Units: Months
Limits: (None, None)
Type: component
Subs: None
This is the stock at any given time of the money in the bank, or remaining
familial goodwill, etc.
"""... | a724777233ab914a08155eb7f3ea9dc19ae0c163 | 3,612,825 |
import os
def test_recwalk():
""" aux: test recwalk() """
def list_paths_posix(recwalk_result):
""" helper function to convert all paths to relative posix like paths (to ease comparison) """
return [auxf.path2unix(os.path.join(os.path.relpath(x, pardir),y)) for x,y in recwalk_result]
indir... | eac0985e0f25b15e8d70c649768bfa305e3fd088 | 3,612,826 |
def format_trim_dims(data, dim=None, seed=0,
encode=encode_aa_seq_atchley,
count=encode_count_binary):
""" Fill in the zeros or trim extra dimensions
Args: (x, c, y) and the expected dimension
Returns: (xs, cs, ys)
"""
if dim is no... | a7b9edfa47c6e5543819d889f8057bbda4186c57 | 3,612,827 |
def RimportLibrary(lib_name):
""" Helper function to import R libraries
using the rpy2 binder
"""
if not rpackages.isinstalled(lib_name):
base.source("http://www.bioconductor.org/biocLite.R")
biocinstaller = rpackages.importr("BiocInstaller")
biocinstaller.biocLite(lib_name)
... | fa05ae8742342e114e9694df5fc1f2394d3731aa | 3,612,828 |
def to_ea(seg, off):
"""
Return value of expression: ((seg<<4) + off)
"""
return (seg << 4) + off | 8955a6f7874e9ffbe5fd9b4f1d075cc7f3836488 | 3,612,829 |
def tf(seconds):
"""
Formats time in seconds to days, hours, minutes, and seconds.
Parameters
----------
seconds : float
The time in seconds.
Returns
-------
str
The formatted time.
"""
days = seconds // (60*60*24)
seconds -= days * 60*60*24
hours = sec... | 22649dd1bd74cc08d73c5cd43b1b96658a3bcb3a | 3,612,830 |
def is_prime(n):
"""
Returns True if `n` is a prime number.
Uses a sieve based approach.
"""
if n < 2:
return False
ps = primes()
p = next(ps)
while p * p <= n:
if n % p == 0:
return False
p = next(ps)
return True | f051aee956072a3c48ffad011cfff78e28e6e52f | 3,612,831 |
def validate_sampleSet(queryDict):
"""
validate the sampleSet input.
returns a boolean isValid and a text string for error message, None if input passes validation
Note: Input length willl not be validated since maxLength has been specified in the form.
"""
logger.debug("sample_validator.valida... | 34890fc0f55c16003eca4f389fb4519ef4699d17 | 3,612,832 |
import pathlib
def run(file_path):
"""Runs the file path as a M# application"""
def interpret(file):
if pathlib.Path(file).suffix is not ".m#":
raise
source = ""
with open(file, 'r') as stream:
for content in stream:
content = content.lower().s... | f42a8532ba2f6a1402e3dcee7eb87b96fd28b78b | 3,612,833 |
def greyed(color, colorDict=None):
"""Convert color code '#RRGGBB' and '#RRGGBBAA' to a grey color
(R, G, B, A).
It also supports RGB(A) from uint8 in [0, 255], float in [0, 1], and
QColor as color argument.
:param str color: The color to convert
:param dict colorDict: A dictionary of color na... | c356e822e994b2a8c10e6c5b1076adff9638dc60 | 3,612,834 |
def cbow_batch(centers, contexts, num_tokens, dtype, index_dtype):
"""Create a batch for CBOW training objective."""
contexts_data, contexts_row, contexts_col = contexts
centers = mx.nd.array(centers, dtype=index_dtype)
contexts = mx.nd.sparse.csr_matrix(
(contexts_data, (contexts_row, contexts_... | 54ef4f1261e00e53091fa9993c3de972e3daf931 | 3,612,835 |
from typing import Tuple
def handle_data(data: str) -> Tuple[str, str, str] or None:
"""
Cleansing of data from the port
:param data: line from Serial port
:return: None
"""
if data not in ['', None]: # data can be empty string quite often
data = data.rstrip()
try:
... | d6d32190393731bc1adaeebeab0b9ecad15fc039 | 3,612,836 |
import pkg_resources
import os
import sys
def is_distribution_editable(name):
"""Is distribution an editable install?"""
distribution = pkg_resources.get_distribution(name)
return any(
os.path.isfile(
os.path.join(location, distribution.project_name + '.egg-link'),
)
fo... | 130e2902de9c4b24ef3345215392ccf84c87c11b | 3,612,837 |
import typing
def compute_average_pose(poses: typing.Iterable[Transform]) -> Transform:
"""
Given a collection of poses, find the average pose
:param poses: A collection of Transform objects to average
:return: The average pose, as a Transform
"""
pose_data = [(pose.location, pose.rotation_qua... | a3651f66fa2079dc23820ef357aaa9fc8ebfefdd | 3,612,838 |
import tqdm
def predict_tile(model,
raster_path=None,
numpy_image=None,
patch_size=400,
patch_overlap=0.05,
iou_threshold=0.15,
return_plot=False):
"""For images too large to input into the model, predict_tile cuts... | aaf81d4d44fb870da8cd02d619858706cc5fbc50 | 3,612,839 |
import json
import click
def process_keyfile(ctx, param, value):
"""Read keyfile and load JSON."""
if value is not None:
try:
auth_info = json.load(value)['twitter']
except:
click.echo('A valid JSON keyfile is required!')
raise
return auth_info
e... | 18909434dfc636cd26ddfeba93970465a82d3e7c | 3,612,840 |
def login_link(request):
"""
This assumes your login link is the Shibboleth login page for your server
and uses the 'target' url parameter.
"""
full_path = quote(request.get_full_path())
login = reverse('shibboleth:login')
ll = "%s?target=%s" % (login, full_path)
return {'login_link': ll... | 5350745584f0c1499e4066759293a0e3e9d0c742 | 3,612,841 |
def gui_browse(type, heading, shares="files", mask="", enablemultiple=False):
"""
Let user select something filesystem related (depends on "type")
"""
dialog = xbmcgui.Dialog()
return dialog.browse(type, heading, shares, mask, enablemultiple) | 9c1b46f4966981934f5424f317f009bd35b942a1 | 3,612,842 |
def score_all(subject_list, goal):
"""
Subject_list can either be a normal list or a tuple list.
Return a dictionary of each subject as a tuple list paired up with its score.
"""
if type(subject_list[0]) is list:
subject_list = tuple(tuple(subject) for subject in subject_list)
ret = ... | 0c00151c508d77a1e0617b52301d1bf757d7887b | 3,612,843 |
from matplotlib.colors import LinearSegmentedColormap as LSC
def splot_rgb_lines(path_evr = None,
elements = [[],[],[]],
orbs = [[],[],[]],
labels = ['','',''],
ax = None,
skipk = None,... | ac73d0577a55a1cd98dd946728f8e0fdf22af350 | 3,612,844 |
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar."""
assert dateIsBefore(year1, month1, day1, year2, month2, day2)
days = 0
while dateIsBefore(... | 7095a6ca1e43f2bd5f2cd60083ca371b0fc3575f | 3,612,845 |
import time
def exif_info2time(ts):
"""
changes EXIF date ('2005:10:20 23:22:28') to number of seconds since 1970-01-01
Borrowed from http://code.activestate.com/recipes/550811-jpg-files-redater-by-exif-data/
"""
tpl = time.strptime(ts + "UTC", "%Y:%m:%d %H:%M:%S%Z")
return time.mktime(tpl) | e4da5adfba9c0ee2abb6349f0291263ae996dde8 | 3,612,846 |
from typing import List
import sys
def _MakeServerArgs(channel: communication.Channel,
interface: interface_registry.Interface) -> List[str]:
"""Returns the args to run the unprivileged server command."""
named_flags = [
"--unprivileged_server_pipe_input",
str(channel.pipe_input.S... | f79499e371c3f259511d0f89c67399017cb9cb71 | 3,612,847 |
def ellipse_from_second_moments(image, labels, indexes, wants_compactness = False):
"""Calculate measurements of ellipses equivalent to the second moments of labels
image - the intensity at each point
labels - for each labeled object, derive an ellipse
indexes - sequence of indexes to process
... | 252d8d4b41511425f72e598bba8a68d0b97624a9 | 3,612,848 |
def get_pager(config, logger):
"""Get the pager"""
pager = config.get_config('pager')
if not pager:
logger.log('No pager configured!')
return None
return pager | fa7bb606ae6d63dba1f65f398ddc748cd8551a39 | 3,612,849 |
import requests
from bs4 import BeautifulSoup
def get_list():
"""
Get the poet list
"""
url = HOME_PAGE + "zhongguoshiren"
response = requests.get(url)
response.encoding = "UTF-8"
text = response.text
soup = BeautifulSoup(text, "lxml")
div_list = soup.find_all("div", class_="font... | ebb462e4ab4be336dab84f8a038426bd63184307 | 3,612,850 |
def get_data_from_file(market,
interval=var.default_interval,
exchange='bittrex',
filetype='csv'):
"""
Gets data from file.
Args:
- market: str with market.
- interval: str with time between measures.
Empty for default_int... | 13223ec5cc1ec28853e7e4b5c71f7a6a8e8b0daa | 3,612,851 |
def plot_kmeans(n, km_psd, f_idx, X, y_pred, raw=False, std=True):
""" plot k-means clusters """
spin_range = n.metadata['spindle_analysis']['spin_range']
n_clusters = km_psd.cluster_centers_.shape[0]
centroids = km_psd.cluster_centers_
if n_clusters == 2:
fig, axs = plt.subplots(1... | d502ab640e533ce69cba51ee1e5e227b93843eda | 3,612,852 |
def process_dssp_df(df: pd.DataFrame) -> pd.DataFrame:
"""
Processes a DSSP DataFrame to make indexes align with node IDs
:param df: pd.DataFrame containing the parsed output from DSSP.
:type df: pd.DataFrame
:return: pd.DataFrame with node IDs
:rtype: pd.DataFrame
"""
# Convert 1 lett... | 00664f11d9c4b386cf7aa35a501a4b4341c27f65 | 3,612,853 |
def basic_animation(frames=100, interval=30):
"""Plot a basic sine wave with oscillating amplitude"""
fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
x = np.linspace(0, 10, 1000)
def init():
line.set_data([], [])
return line,
def ... | 3f60865003875431d3649b53b4df674e26cf1dc7 | 3,612,854 |
from functools import reduce
from operator import add
def sum_node_list(node_list):
"""Custom sum func to avoid creating redundant nodes in Python sum func."""
node_list = [n for n in node_list if n is not None]
if node_list == []:
return None
return reduce(add, node_list) | 4daffb4c70cc599daa4e656686a969b58dd16ef0 | 3,612,855 |
def generate_name():
"""
Wrapper to fetch the latest source, parse it for adjectives and names,
and then generating a random name in the Docker container style.
Parameters
----------
Returns
-------
str
A name for a Docker container.
"""
source = _fetch_latest_source()
... | 11f65c92be8856bd954d79027c2ce205371ab0cb | 3,612,856 |
def find_account(account):
"""
Function that finds an account name and returns the account
"""
return Credential.find_by_account(account) | c080b21a087f7693947e1fd5d23a10312435505f | 3,612,857 |
def checkIfTitleExists(title):
""" Checks if an item exists with the same unique title in db """
results = session.query(CategoryItem).filter_by(title=title).all()
return len(results) > 0 | 520eb9b7a0344e61b7282a1f6667a947c875f7c3 | 3,612,858 |
def conv2d(x, filters, shape, padding="same", strides=(1, 1), activation="relu"):
"""
2D Convolutional layers with Batch Normalization
Arguments:
x: Keras layer, the input to the feature map
filters: Int representing the number of filters to use
shape: Tuple with two integer val... | e28669c6066967d0e2f28b919e93aaf439b494f5 | 3,612,859 |
def writeBpImage(fname,image):
"""
Writes an image to a file with specified name.
name: base name of image file; e.g., "tpgp"
image: the image
"""
fileName = fname+".dat"
aos = ArrayOutputStream(fileName)
aos.writeFloats(image)
aos.close()
return image | 033fd5257c6ae8b787bee154938b7d2dad309472 | 3,612,860 |
import logging
def GroupByID(gff_data):
"""
Group GFF features into subsets based on ID
Grouping is based on the ID attribute, which is assumed
to be of the form '<prefix>:<name>:<index>' (e.g.
'CDS:YEL0W:3').
Consecutive features are determined to belong to the same
gene if they have th... | 91caf0d2927a922dd78b5267282639289ea8bcf0 | 3,612,861 |
def _clean_error_msg(self, msg):
"""converts a Powershell CLIXML message to a more human readable string
"""
# TODO prepare unit test, beautify code
# if the msg does not start with this, return it as is
if type(msg) == bytes and msg.startswith(b"#< CLIXML\r\n"):
# for proper xml, we need to... | eab1769795e01128b417940914e87cd5cd34cf90 | 3,612,862 |
import inspect
def cls(cls):
"""return a string with class name, description and attrs+methods+properties tables"""
module = inspect.getmodule(cls)
fullname = "`%s.%s`" % (module.__name__, cls.__name__)
doc = readme_md.doc(cls)
title = " - ".join(filter(None, [fullname, doc]))
attrs = readme_m... | 050331b04e4c2ea4b3f1ae5d1403b23355d0ded9 | 3,612,863 |
import os
import json
def parse_arguments(root_dir):
""" Parse arguments from JSON parameter files.
Args:
root_dir: string: path to the directory containing the JSON files.
Returns:
namedtuple: hyperparameters.
namedtuple: evaluation parameters.
namedtuple: environment parameters... | 912e110705e4151c7d12f5c6e71bd7139e3a3134 | 3,612,864 |
def spherical_harmonic(theta, phi, m=0, n=0):
"""Spherical harmonic of order `m` and degree `n`.
.. note:: The degree `n` is often denoted `l`.
.. seealso:: :func:`scipy.special.sph_harm`
"""
return sph_harm(m, n, phi, theta).real | 3bc1b60ea3487af28a3850af4ad47780a6547a7e | 3,612,865 |
import string
import random
def random_string(length: int = 12) -> str:
"""Generate a random string of fixed length."""
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length)) | 425c74f76e696843c5bbf337cc25ba72999dc6c7 | 3,612,866 |
def axis_lw():
"""Line width of the axes
"""
return 0.6 | 5e5c3d37dae10ef83b89b0493e897d769119fdea | 3,612,867 |
from typing import Optional
from typing import Callable
def color_lerp(
color1: 'Color',
color2: ColorInput,
space: str,
out_space: str,
progress: Optional[Callable[..., float]],
hue: str,
premultiplied: bool
) -> InterpolateSingle:
"""Color interpolation."""
# Convert to the colo... | f29a0b963b95edad9404dbda6cdbc42c44cdaa32 | 3,612,868 |
async def place_control_rod(key: str, rod_number: int):
"""
Use your key and rod number to place given rod
"""
commander = next(filter(lambda c: c.uuid == key, commanders), None)
reactor = next(filter(lambda r: r.uuid == key, reactors), None)
if commander and reactor:
result = reactor.ad... | 108d27ec03efa4ad1f1ec926b15e0cf8d311a20f | 3,612,869 |
def game_from_team_name(games, team_name, verbose=False):
"""
rn just takes in 1 game => double header issue for mlb
"""
for game in games:
teams = teams_from_game(game)
if team_name in teams:
if verbose:
print(f"found {team_name} game")
return gam... | 15f7394bb42ed3719c7b98d6a847926a53ab7ac5 | 3,612,870 |
from twisted.internet import reactor
def define(host, port, database, word):
"""Look up a word using a dict server"""
d = defer.Deferred()
factory = DictLookupFactory("define", (database, word), d)
reactor.connectTCP(host, port, factory)
return d | 06712d6199e31951f0f6f1275fcd66dee9511057 | 3,612,871 |
from typing import Optional
def three_station_network_model(alpha1=0, alpha6=0,
mu1=1, mu2=1, mu3=1, mu4=1, mu5=1, mu6=1,
cost_per_buffer=np.ones((6, 1)),
initial_state=np.zeros((6, 1)),
cap... | 813734f187d8e2ca7529eadb540bee82ac331400 | 3,612,872 |
import torch
import time
import os
import pickle
def train(args, train_dataset, val_dataset, model, model_name):
"""
Parameters
----------
args : arguments
train_dataset : dataloader (dataloader for the validation/test dataset).
val_dataset : dataloader (dataloader for the validation/test data... | 30b66dc9a9a754e256792c3774c04909a01c3fee | 3,612,873 |
import sys
import glob
def getActivePorts():
""" find the open ports - main part of the code from:
http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python
"""
if sys.platform.startswith('win'):
candidatePorts = ['COM' + str(i + 1) for i in range(256)]
elif sys.... | 94ec67d9d863c96dcfca09154cf2ccf3969816ee | 3,612,874 |
def squares_in_rectangle(length, width):
"""This function is the solution to the Codewars Rectangle into Squares Kata
that can be found at:
https://www.codewars.com/kata/55466989aeecab5aac00003e/train/python."""
if length == width:
return None
squares = []
while length > 0 and width > ... | e0e32e2803ca752a24adf4cce353bf6cc49d4c08 | 3,612,875 |
import urllib
def response_to_bytes(resp):
"""
:param resp: urllib.classified_request.Response instance
:return: bytes of response
"""
header_dict = dict(resp.info())
if isinstance(resp, urllib.error.HTTPError):
header_dict["Status"] = '{} {}'.format(resp.code, resp.msg)
headers_by... | 4875a6e45dfbd05ce078c7ced52fcc6ba768b014 | 3,612,876 |
def build_fpn_mask_graph(rois, feature_maps,
image_shape, pool_size, num_classes):
"""Builds the computation graph of the mask head of Feature Pyramid Network.
rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
coordinates.
feature_maps: List of featur... | 3ecfe5ccd1d73803a15d4acbf20044cfd4e238a3 | 3,612,877 |
def proc_kl(rv, kl, tarray, p, toplevel_arrays):
"""Handle a table spec keylist, modifying rv in place; returns target"""
c = rv
if len(kl) == 0:
return c
# all entries except last must be dicts
for i in kl[:-1]:
if i in c:
if type(c[i]) not in [dict, list]:
... | 1c41110fb08f6ae52eceb747dea60b4aaf8ff0f1 | 3,612,878 |
import os
import pkg_resources
def locate_config_file():
""" Return a path to a config to use accoding to standard preference rules """
print(f"Checking if ${LOCAL_CONFIG} is a file")
if os.path.isfile(LOCAL_CONFIG):
return LOCAL_CONFIG
if os.path.isfile(HOME_DIR_CONFIG):
return HOME_... | 8587dfa351de5acb5d3d67b5b2d1764a8ee7c34c | 3,612,879 |
import os
def display_text(text:str, size:int, color:tuple = (27, 34, 77), antialias:int = 1, fontpath:str = os.path.join('Assets', 'PoetsenOne-Regular.ttf'), background:bool=False, background_color:tuple = (255, 255, 255), **kwargs) -> pygame.Surface:
"""Displaying text
Args:
text (str): The text th... | 09761a4c99639c035354a32c5d50f0fa85498706 | 3,612,880 |
def relative_power_sqi(nn_intervals,freqs=None,pows=None,f_min=0.04,f_max=0.15):
"""
Compute the relative power with respect to the total power of the examined band.
The function mimics features obtaining from the frequency domain of HRV.
Main inputs are frequencies and power density - compute by using
... | f4a77ceb89bce4503c5f64e1f35bc13ec98dc47e | 3,612,881 |
import healpy as hp
def make_hpx_to_wcs_mapping(hpx, wcs):
"""Make the mapping data needed to from from HPX pixelization to a
WCS-based array
Parameters
----------
hpx : `~fermipy.hpx_utils.HPX`
The healpix mapping (an HPX object)
wcs : `~astropy.wcs.WCS`
The wcs mappin... | b45264534b571ce9b4ba2344e5a05849c0d049e5 | 3,612,882 |
def simulate_round(grid: list[list[int]]) -> tuple[list[list[int]], int, bool]:
"""Simulate a single round.
* First, the energy level of each octopus increases by 1.
* Then, any octopus with an energy level greater than 9 flashes. This
increases the energy level of all adjacent octopuses by 1, includ... | 11bd7e9a221501b6366af5cf625fdfd59e2bda06 | 3,612,883 |
def keep_node_permissive(data):
"""Return true for all nodes.
Given BEL graph :code:`graph`, applying :func:`keep_node_permissive` with a predicate on the nodes iterable
as in :code:`filter(keep_node_permissive, graph)` will result in the same iterable as iterating directly over a
:class:`BELGraph`
... | 425ebf20686ea309e542b82b2fbbe7aa81cccb63 | 3,612,884 |
def probability_to_internal(external_values, constr):
"""Reparametrize probability constrained parameters to internal."""
return external_values / external_values[-1] | 0aaf19d5c2fd56e8e4277729a2a14cf5828bbf47 | 3,612,885 |
import platform
def get_os():
"""Get system name.
Returns:
str: The system/OS name.
e.g.:
``Linux`` or ``Windows``.
"""
return platform.system().lower() | 5dd7c30ce53422180e9c75d4aff7912c887cb3e4 | 3,612,886 |
def vdcnn(embedding_size, maxlen, max_features,
filter_nr, kernel_size, repeat_block, dense_size, repeat_dense, output_size, output_activation,
max_pooling, mean_pooling, weighted_average_attention, concat_mode,
dropout_embedding, conv_dropout, dense_dropout, dropout_mode,
conv_k... | 5a47bfb5346c60b8130fc2cd3fa3d3dba6255e8f | 3,612,887 |
import math
def angle(p0: Point, p1: Point, p2: Point) -> float:
"""
p1 is the center point; result is in degrees
"""
a = (p1.x-p0.x)**2 + (p1.y-p0.y)**2
b = (p1.x-p2.x)**2 + (p1.y-p2.y)**2
c = (p2.x-p0.x)**2 + (p2.y-p0.y)**2
return round(math.acos( (a+b-c) / math.sqrt(4*a*b) ) * 180/math.... | 04ae60218578949f6c98611e6dd00510ecdd2816 | 3,612,888 |
def get_source_parser(type_source):
"""
Возвращает класс-парсер кода
:param type_source: тип парсера
:return: класс
"""
dict_source_parser = {
'python': PythonSourceParser
}
assert type_source in dict_source_parser, \
'type_source must be in ({0})'.format(', '.join(dict_s... | 4c92d21e518807ec586e4ae24fd45c09453c3cd9 | 3,612,889 |
def prepGeoJSON(geojson):
"""Loads GeoJSON into the mander library for accelerate processing later.
Parameters:
geojson -- The GeoJSON to load
Returns:
A string that can be passed in lieu of the original GeoJSON to take
advatange of internal processing that has already been done.
"""
re... | 1d0ea9880e5f5b0459a46c848c4e0265c29a6173 | 3,612,890 |
from typing import List
def get_reserves() -> List[int]:
"""
Returns how many token_a and token_b tokens are in the pool.
:return: a list of 2 ints, the value in the first index is reserve of token_a and the second value is the reserve of token_b
"""
return [get(SUPPLY_KEY + TOKEN_A).to_int(), ge... | d2c5c9c88428e6d9b38aedeb63611207ec9ae132 | 3,612,891 |
def walk_values(hive, key_name, value_filter_regex = None, valuetypes = None, autoexpand = False):
"""
>>> list(walk_values(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\DrWatson", r"^(cr|dump)"))
[('DumpSymbols', 0, 4), ('DumpAllThreads', 1, 4), ('CreateCrashDump', 1, 4), ('CrashDumpType', 1, 4)]
>>> list... | 57a2b803c9a9e36a98b6b766c151d9a6d99f2f22 | 3,612,892 |
def viz_view(view, ax=None, row_names=None, col_names=None, **kwargs):
"""Order rows according to clusters and draw line between clusters.
Visualize this using imshow with two colors only.
"""
# Get data restricted to current view's outputs
data_dict = get_view_data(view)
data_arr = np.array(da... | 73032b490a522a0b8b01a11f8b729f96a1188886 | 3,612,893 |
def local_push(tx, rpc_user=None, rpc_password=None):
""" Pushes a bitcoin transaction to the network using a local rpc server.
:param tx: transaction to be pushed.
:type tx: hex str
:param rpc_user: rpc user (could be set in bitcoin.conf).
:type rpc_user: str
:param rpc_password: rpc password ... | 3be0b7cd803d97e53bad7a1869eb479cdceac877 | 3,612,894 |
def grib_index_get_long(indexid,key):
"""
@brief Get the distinct values of the key in argument contained in the index. The key must belong to the index.
This function is used when the type of the key was explicitly defined as long or when the native type of the key is long.
\b Examples: \ref... | 4acf9cb3abbaf76c306daa08f5d8932d97392412 | 3,612,895 |
def get_action_spec():
"""Get the specs of the tensors expected by ``step(action)`` of the
environment.
Note: you need to finish all the config for environments and
TrainerConfig.random_seed before using this function.
Returns:
nested TensorSpec: a spec that describes the shape and dtype o... | df397aac28840805b12f790698119191eda245b4 | 3,612,896 |
import os
import sys
import subprocess
import io
def run_notebook(nb_path, tmp_path, env=os.environ, kernel=None):
"""Execute a Jupyter notebook via nbconvert and collect output.
Modified from
https://blog.thedataincubator.com/2016/06/testing-jupyter-notebooks/
Parameters
----------
nb_path ... | 6c3c3bd4795042fcf377ab456cee4c9483c48d0c | 3,612,897 |
def get_mx_hosts(domain):
"""Get all domain names for servers in MX records"""
return [x.exchange for x in resolver.query(domain, 'MX')] | 467367eb5b9ff68be6c51e39e9808c44843414f0 | 3,612,898 |
def post_data(sensor_data):
"""POST to /sensorData
Experimental dev feature which uses timely-beliefs
to create and save the data structure.
"""
beliefs = SensorDataSchema.load_bdf(sensor_data)
response, code = save_to_db(beliefs)
response.update(type="PostSensorDataResponse")
return re... | 422c6a8acf026c317f5d4d431a0c143e54cb9828 | 3,612,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.