content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def read_one(person_id):
"""
This function responds to a request for /api/people/{person_id}
with one matching person from people
:param person_id: Id of person to find
:return: person matching id
"""
# Get the person requested
person = Person.query.filter(Person.person_id ... | e3ddbecf9779fd032646c9e847785776b42a409d | 49,000 |
import numpy as np
def getPointsProjectedToPlane(pointsArray, planePosition, planeNormal):
"""
Returns points projected to the plane in world coordinate system and in the plane coordinate system,
and an array of booleans that tell if the point was above/below the plane.
pointsArray contains each point as a co... | 21a36e32230477d987ace80c9d8fdfd23fb3feee | 49,001 |
def diff_one_tc(x: int, y: int) -> int:
"""Compute x - y.
This problem has only one test case to make inspecting the specific error message
easier.
"""
return x - y | 96634c095af4dade2c158788f2b1af0728c0a23d | 49,002 |
from re import S
def reduce_rational_inequalities(exprs, gen, relational=True):
"""
Reduce a system of rational inequalities with rational coefficients.
Examples
========
>>> x = Symbol('x', real=True)
>>> reduce_rational_inequalities([[x**2 <= 0]], x)
Eq(x, 0)
>>> reduce_rational_i... | 909f233f644e40b23e2a22fc51e5230d21d950ca | 49,003 |
def read(string: str) -> dict:
"""Parse an ordered map file.
:arg string: Content of an ordered map file.
:returns: An ordered map.
"""
data = {}
for line in string.split('\n'):
if line and line[0] not in ('#', ' ', '\t', '\r'):
data = _merge(data, _deserialise(line))
r... | b20d5767995aad4bb110bf6bc3ef6b7885d2ecb6 | 49,004 |
def _generate_indicators(catalog, validator=None, only_numeric=False,
broken_links=False, verify_ssl=True,
url_check_timeout=1, broken_links_threads=1):
"""Genera los indicadores de un catálogo individual.
Args:
catalog (dict): diccionario de un data.js... | be7516ec0adf469b698b2271555282e6424d12af | 49,005 |
import numpy
def metric_weekday(weekday_1, weekday_2):
"""Calculate the distance between two weekdays as a positive integer.
:param weekday_1: A positive integer between 0 and 6
:param weekday_2: A positive integer between 0 and 6
:returns: The absolute valued distance between two weekdays
:rtype... | 71a0a5d5a5166458597e0007063a4c19e8f195a9 | 49,006 |
def apply_tweet_text_preprocessing(text: str) -> str:
"""Make Text Preprocessor object and apply some basic techniques to preprocess tweet text.
Args:
- text(str)
Returns:
- preprocessed_text(str)
Note:
- We opt for lemmatizing in this use case, just that the example output looks... | 11230c2a33719997b2315fcbdfc778db6d3b4f5d | 49,007 |
def addheader(datasets):
"""
The columns of the pandas data frame are numbers
this function adds the column labels
Parameters
----------
datasets : list
List of pandas dataframes
"""
header = get_header()
for i in range(0, len(datasets)):
datasets[i].columns = header... | 9e7ba2bbdca8ceaabdba1cd4f8647a78d0fd05d5 | 49,008 |
def gain_filt(b, a):
"""Step response from filter (used as initial conditions later)
Parameters
----------
b: ndarray
filter coefficients
a: ndarray
filter coefficients
Returns
-------
zi : ndarray
step response as a vector
"""
# max. length of coefficie... | e23cb2d572ee780b464e8537732d428440082d4f | 49,009 |
def vax_pacient(ime, priimek, cepivo):
"""Funkcija v bazi popravi podatek o cepljenu dolocenega pacienta. Ce osebe ni v bolnici, je nemoremo cepiti. Pravice ima samo zdravnik."""
return None | e9628a857fee3918b9ad3c6ed4293933c970e30c | 49,010 |
import pickle
def read_results_pickle(path):
"""Reads a resultset from a pickle file.
Parameters
----------
path : str
The file path from which results are read
Returns
-------
results : ResultSet
The read result set
"""
with open(path, 'rb') as pickle_file:
... | cf725e210637e73d19b1c1dce21aae48e99d4782 | 49,011 |
def get_sample_mean(values: list) -> float:
"""
Calculates the sample mean (overline x) of the elements in a list
:param values: list of values
:return: sample mean
"""
sample_mean = sum(values) / len(values)
return sample_mean | 182befe514f406340f0b1f37e892ad1add1f0ed2 | 49,012 |
def _encode_raw_complex(data, prm):
""" Encode raw complex data."""
payload, content_type = prm.encode_raw(data)
return ResultAlt(payload, identifier=prm.identifier,
content_type=content_type) | eb2bb0324c6311188dc817d1d02beb14891b2466 | 49,013 |
def polyfill_integers(generator, low, high=None, size=None, dtype="int32",
endpoint=False):
"""Sample integers from a generator in different numpy versions.
Parameters
----------
generator : numpy.random.Generator or numpy.random.RandomState
The generator to sample from. I... | b4061e8ec7cb9927bbe4fcce1c847aecdc10052b | 49,014 |
import os
def which(program):
"""This method is not my code, thanks to Jay http://stackoverflow.com/a/377028/248220"""
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return p... | 6c6419e8d6311fa4e1e31aa0f43669e62ee78462 | 49,015 |
def rotate(points, rot_vecs):
"""Rotate points by given rotation vectors.
Rodrigues' rotation formula is used.
Args:
points (array): points to rotate
rot_vecs (TYPE): rotation vector
Returns:
TYPE: rotated points
"""
theta = np.linalg.norm(rot_vecs, axis=1)[:, np.newax... | d9ee1909294ef0a4bed65076c6b59e2ae5cc24ec | 49,016 |
from typing import Optional
def sigU(backend: Optional[BackendType] = None,
dtype: Optional[DtypeType] = None) -> tn.Tensor:
"""
Pauli 'up' matrix.
Args:
backend: The backend.
dtype : dtype of data.
Returns:
U : The Pauli U matrix, a tn.Tensor.
"""
vals = [[0., 1],
[0... | 24c30dede5bca7d13914f1fcea41964a220550d7 | 49,017 |
def add_trapeziums(dfmmodel, principe_profielen_bov_df, principe_profielen_ben_df, closed=False):
"""Add trapezium profiles on branches with missing crosssections."""
#siebe 22-6-2021: nu twee dataframes: een voor bovenstrooms een voor benedenstoomse zijde tak
xs = dfmmodel.crosssections
for branch in x... | e4dd88ef18b9592b9539b14618342861be4d9ac6 | 49,018 |
def get_one_uniform_value(value_range_or_upper_bound, lower_bound=0):
"""
return a random value from a specified interval or [0, 1]
:param value_range_or_upper_bound: list or upper and lower limits or float of upper bound
:param lower_bound: float, lower limit
:return: single float value
"""
... | 15670fc685a74a2d2f1e4d8f4ed5494b05c5500e | 49,019 |
def efficientnet_b2c(in_size=(260, 260), **kwargs):
"""
EfficientNet-B2-c (like TF-implementation, trained with AdvProp) model from 'EfficientNet: Rethinking Model Scaling
for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, de... | 65b371db5995994cfcaf473c55a33f6401b05661 | 49,020 |
def tapis_user(token: str = Depends(tapis_token)):
"""Get Tapis user profile for the provided token."""
try:
t = _client(token)
except BaseTapyException as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token was not valid: {0}".format(exc... | d0d0ffb1fbca24fdeeb30071f4dfb3c2d6d8c657 | 49,021 |
import numpy
def get_device(arg=None):
"""Gets the device from ID arg or given chainer's.
:class:`~pycuda.gpuarray.GPUArray`.
Args:
arg: Value to specify a GPU device.
Returns:
Device object specified by given ``arg``.
The rule of device selection is following.
===========... | 32050a1ca6139167c77aebcce62ea3a2a4f49db0 | 49,022 |
def read_csv_into_df_with_header(csv: str):
"""
and also set datatimeindex csv has to have a column as 'DateTime'
Parameters
----------
csv :
Returns
-------
pd.DataFrame
"""
df = pd.read_csv(csv, na_values=['-9999'])
df['DateTimeIndex'] = pd.to_datetime(df['DateTime'])
... | 5e4fde4c353b0ccd230134c2c17b8f833c6763ea | 49,023 |
def find_node_named_graph(dataset, node):
"""
Search through each graph in a dataset for one node, when it finds it, returns the graph it is in
:param dataset:
:param node:
:return:
"""
if isinstance(node, rdflib.Literal):
raise RuntimeError("Cannot search for a Literal node in a dat... | d4366c09313d3fba90ba84e0ca9805689dc76bab | 49,024 |
def iqr(data_list):
""" Interquartile range of the data
Inputs:
data_list - a list of floats
Outputs:
val - The interquartile range of the data
"""
n = count(data_list)
cnt = n//2
if cnt ==0:
return 'NaN'
data_list.sort()
l_half = data_list[:cn... | 30e801164c6d0d07943276f58892c8ea1a3188df | 49,025 |
def _get_prediction(outputs):
"""Checks if multiple outputs were provided, and selects"""
if isinstance(outputs, (list, tuple)):
return outputs[0]
return outputs | f6565614c3d43ca15c1b52025469561fe61ae5ab | 49,026 |
def plot_gb_mean_errorbar(df_m, df_s):
"""
In:
df_m: results of df.groupby().mean() renamed to have mean in col names
df_s: result of df.groupby().std() renamed to have std in col names
Returns:
list of CustomVis objects
"""
# tog = df_m.join(df_s, lsuffix=" (mean)", rsu... | fc2f5f6702db5842ebef98a90865629d678409c3 | 49,027 |
import shlex
import os
import re
def Sync(skia_revision=SKIA_REV_DEPS, chrome_revision=CHROME_REV_LKGR,
fetch_target=DEFAULT_FETCH_TARGET,
gyp_defines=None, gyp_generators=None):
""" Create and sync a checkout of Skia inside a checkout of Chrome. Returns
a tuple containing the actually-obtained ... | 6c06a2b5f20283238f292f960fe592ad1499010b | 49,028 |
def bot_answer(user_input):
"""
This function checks if the user input exists
in the database and returns an answer. If the
user input does not exists, it searches for
for something similar to the user input and returns an answer.
"""
answer = switchboard.DB_getQanswer(user_input)
if ans... | 2b1edd6d7df7774184bcd8463629a1bf6befe1fd | 49,029 |
def _setTextContent(df, txt_id, txt_content):
"""
Set the arbitrary text content.
Args:
df: DataFrame-initial information.
txt_id: str-the text id.
txt_content: str-the text content.
Returns:
df_temp: DataFrame-information after updates.
"""
df_TextDa... | 7b9dcad59012a7b64fbd11ecb5ac85bd0d122dc8 | 49,030 |
import requests
def sheet(request, ally_id):
"""
Alliance sheet
"""
request_alliance = requests.get(GLOBAL_URL+f"/{ally_id}", headers=global_headers(request))
if request_alliance.status_code != 200:
return render_error(request_alliance)
return render(request, "alliance/sheet.html",{
... | 4c79fb99910e1070976fd5a57726449ae76b66a0 | 49,031 |
import math
def initWindKernel(direction, speed, c1):
"""
Function to generate the kernel for wind probabilities
to apply into the lattice transitions.
This version is for Moore's neighborhood only
parameters
----------
direction: int, float
Respect to a horizontal axis, the angl... | fff03981ccc730ecd6ec5ab793287ce356770fd5 | 49,032 |
import difflib
import pprint
def pprint_diff(first, second, first_name='first', second_name='second'):
"""Compare the pprint representation of two objects and yield diff lines."""
return difflib.unified_diff(
pprint.pformat(first).splitlines(),
pprint.pformat(second).splitlines(),
fromfile=first... | 5c88916b47cfa970d6ab15caa650540d2dab3c3b | 49,033 |
def declare_variable(name, shape, initializer):
"""Helper to create a variable."""
return tf.get_variable(name=name, shape=shape, initializer=initializer, dtype=tf.float32) | 0d0a99dca5e0cd4e33c2e540fcd88eb22b6b9bf6 | 49,034 |
from unittest.mock import patch
import os
def test_resume_module_build_failed_first_component(mock_config, tmpdir):
""" We test to resume the module build from the first failed component """
cwd = tmpdir.mkdir("workdir").strpath
rootdir = None
mock_cfg_path = get_full_data_path("mock_cfg/fedora-35-x86... | fe34673bd61d870a874b648937647fb569dce6ea | 49,035 |
def delete_live_instance(live_instance_id=None):
"""
Delete a live streaming instance
:param live_instance_id:
:return: boolean
"""
url = get_api_base() + '/livestream/%d' % live_instance_id
return RestClient.delete(url=url, headers=create_headers()) | 57aa52b3e636a15878c945a3aa163d4780f6cc72 | 49,036 |
import os
import math
import joblib
def load_data(train_size=10000, test_size=2000, load_challenge=False, create_matrices=False, generate_data=False,
create_pickle_file=True, mode="ltc", min_track_prior= 0.0):
""" Fixed Path Names """
data_folder = os.path.join(os.getcwd(), 'data/mpd.v1/data/')... | 9131dd3d66e521a0e00bd38e66374ac6bddb5051 | 49,037 |
def inc(i):
"""Increments number.
Simple types like int, str are passed to function by value (value is copied to new memory slot).
Class instances and e.g. lists are passed by reference."""
i += 1
return i | 2959f0a2d57891821a159a4a51c1b146c0cb0395 | 49,038 |
def test_linkedlist_bind():
"""Test monadic bind of LinkedList
Laws alone don't guarantee the desired behavior
"""
def f(x):
return Cons(x + 100, lambda: Cons(x + 200, lambda: Nil))
xs = Cons(10, lambda: Cons(20, lambda: Nil))
expected = Cons(
110,
lambda: Cons(
... | 73aa30e4c98fa8bdbe2725af2d3c7892bb6a0e88 | 49,039 |
def SoftmaxCrossEntropy(inputs, axis=1, normalization='FULL', **kwargs):
"""Compute the softmax cross entropy with given logits and one-hot labels.
**Type Constraints**: *float32*
Parameters
----------
inputs : sequence of Tensor
The inputs, represent [logits, labels].
axis : int, opti... | 7652e6fb561e1692fa2c82eb525d7a84fd4f2f34 | 49,040 |
def checkForDonorWithRegion(op, graph, frm, to):
"""
Confirm donor mask exists and is selected by a SelectRegion
:param op:
:param graph:
:param frm:
:param to:
:return:
@type op: Operation
@type graph: ImageGraph
@type frm: str
@t... | 640f55f23474456d1937719aef0a846cee9f2407 | 49,041 |
def is_symbolic_tensor(tensor):
"""Returns whether a tensor is symbolic (from a TF graph) or an eager tensor.
A Variable can be seen as either: it is considered symbolic
when we are in a graph scope, and eager when we are in an eager scope.
Arguments:
tensor: A tensor instance to test.
Returns:
Tru... | b1ae4102d877da3d00615f8649279a3adaaba190 | 49,042 |
def execute_overload_ceilometer(config, state, overloaded_host, vm_uuids):
"""Process an overloaded host: migrate the selected VMs from it.
Same as "execute_overload" except measures are collected by ceilometer.
:param config: A config dictionary.
:type config: dict(str: *)
:param state: A state ... | 1b0529a9cb48db8ea16bcb2f0ecc557832de5782 | 49,043 |
def simulate_lognormal(mu_lim, sigma_lim, count_lim):
"""Simulates log normal data of a specified size
Parameters
----------
mu_lim : list, float
The limits for selecting a mean for the log normal distributions
sigma_lim : list, float
The limits for selecting a standard deivation fo... | abf8f69ee16cf5d23b10b60ab5bee6d3d1b95715 | 49,044 |
import re
def extract_video_id(string):
"""Extract what looks like a YouTube video id from a string"""
if len(string) == 11:
return string
matches = re.search("v?=(.{11})", string)
if matches is not None:
return matches.group(1)
matches = re.search(r"youtu\.be/(.{11})", string)
... | 30b680f48b6e9101492e29ff76f5bed1703a37d2 | 49,045 |
def get_visible_cards(cards1, cards2):
"""Return a list of the intersection of cards1 and cards2; call only on
visible cards!"""
return [card for card in cards1 if card['name'] in names(cards2)] | 4728b942e9900c9810e8d1865143f38b4631dcc1 | 49,046 |
def phases_exponential_fit(phases_points, t, X, one_order):
"""
:Authors:
Chuankai Cheng <chuankai@usc.edu> and J. Cameron Thrash <thrash@usc.edu>
:License:
MIT
:Version:
1.0
:Date:
2021-03-17
:Repository: https://github.com/thrash-lab/sparse-growth-curve
"""
all_starting_time=phases_poi... | eb42c72792fc2c75bf93543fb1403a3a9b5b518d | 49,047 |
def ascii(value):
"""Return the string of value
:param mixed value: The value to return
:rtype: str
"""
return '{0}'.format(value) | 11cf1af6567c53a5583d8bdcb6da2431f6b79ba9 | 49,048 |
import time
import pickle
import os
import random
def run_experiment(params, rt_environment, trial_out_dir, n_generations=100,
save_results=False, silent=False, args=None):
"""
The function to run the experiment against hyper-parameters
defined in the provided configuration file.
... | c6f916f273c6ed4ba2087ef635ebf6ea6ac3102c | 49,049 |
def find_closest_date(date, list_of_dates):
"""
This is a helper function that works on Python datetimes. It returns the closest date value,
and the timedelta from the provided date.
"""
match = min(list_of_dates, key = lambda x: abs(x - date))
delta = match - date
return match, delta | 57f9ecbf764539fcea495057ba4b908df700b8db | 49,050 |
def FormatDateTime(duration):
"""Return RFC3339 string for datetime that is now + given duration.
Args:
duration: string ISO 8601 duration, e.g. 'P5D' for period 5 days.
Returns:
string timestamp
"""
# We use a format that preserves +00:00 for UTC to match timestamp format
# returned by containe... | 2511ec74047451de444de1a9719b6223f9e17e94 | 49,051 |
def is_depth(da, loc="any"):
"""Tell if a data array is identified as depths
Parameters
----------
da: xarray.DataArray
Return
------
bool
See also
--------
is_lon
is_lat
is_altitude
is_level
is_time
xoa.cf.CFCoordSpecs.match
"""
return xcf.get_cf_s... | 1173a05380c363de23c5cda1523cdbaadae6c29f | 49,052 |
def num_bits_64(i):
"""Counts the bits in a given integer.
>>> num_bits_64(7)
3
>>> num_bits_64(8)
1
>>> num_bits_64(0b1100110000000000000000000000000)
4
"""
# & here converts negative integers to unsigned representation first,
# so we get the correct number of bits.
return bin(i & BITS_64).count... | 14e63fdc57754f38be4b072f950743e25ee78b90 | 49,053 |
def replace_str_index(text, index=0, replacement=''):
"""
Utility function
:param text:
:param index:
:param replacement:
:return:
"""
return '%s%s%s' % (text[:index], replacement, text[index + 1:]) | a09aa93b6bb567731e77d5b7b91504cf88142fb5 | 49,054 |
import multiprocessing
import os
import subprocess
import glob
def multipart_upload(s3server, bucket, s3_key_name, tarball, mb_size):
"""Upload large files using Amazon's multipart upload functionality.
"""
cores = multiprocessing.cpu_count()
def split_file(in_file, mb_size, split_num=5):
pre... | 5446dec130e44949ccbbf0e0e4b0f5c66f135f11 | 49,055 |
import traceback
import time
def discover_channels(path, serial_number, callback, cancellation_token, channel_termination_token, logger):
"""
Scans for USB devices that match the path spec.
This function blocks until cancellation_token is set.
Channels spawned by this function run until channel_termination_to... | b069aad3705368fbc960acac16e66a05822fcd76 | 49,056 |
from datetime import datetime
def from_timestamp(timer: int) -> datetime.datetime:
"""
Converts timestamp to `datetime.datetime`
"""
return datetime.datetime.utcfromtimestamp(timer) | 060932589dc87795e324dfa96208745875c05932 | 49,057 |
from typing import Any
def arg(name: str, value: Any) -> str:
"""
>>> arg("x", 1)
'`x`: <builtins.int> 1'
"""
return f"{tick(name)}: {val(value)}" | 19d4e979aa86fdec0a5e69c972a9cc4b1c5c2226 | 49,058 |
from collections import Counter
def solve_part_one(id_list: list) -> int:
"""
Calculates the checksum for a list of IDs
:param id_list: Python list containing a list of ID strings
:return: Checksum as defined by the problem
"""
twos, threes = 0, 0
for id in id_list:
id_counter = C... | a4fe4d7b8205492e132175199121f3ed5a58b7b9 | 49,059 |
def search(lookup):
"""
Search for a reference on arXiv.org given a lookup string. Since the arXiv.org api can return mutiple references
for a single query, this function raises an error in the case that more than one reference was returned.
:param lookup: String with the lookup to search for on ar... | 3b9b9d5578d2a94fc9a5148b2eb7f4d1ac45f4fa | 49,060 |
def id_in_use(id_key, id_key_value, dict):
"""
Return true if an ID is already in use.
"""
for value in dict.values():
if value[id_key] == id_key_value:
return True
return False | c2f731396eecd8b58cfd381b06e9a7f127fe960a | 49,061 |
def is_prerelease(version_str):
"""
Checks if the given version_str represents a prerelease version.
"""
return any([c.isalpha() for c in version_str]) | c6454bb350b2c4e55dbc271f23253aa2e3472802 | 49,062 |
def _wrap_with_after(responder, action, action_args, action_kwargs, is_async):
"""Execute the given action function after a responder method.
Args:
responder: The responder method to wrap.
action: A function with a signature similar to a resource responder
method, taking the form ``... | e8351d6d46ea863f4c58761016e9cbf0ee64a3de | 49,063 |
def text_analysis(request: dict = Body(..., examples=analysis_examples),
#index: str = Path(default='country')
):
"""
The *analyze* endpoint allows you test out how your data will be analyzed and indexed.
The default behaviour is for your search terms to be analyz... | d03b54fb354c11adbb2d9c362ceea3b7d65171b1 | 49,064 |
import re
def class_name_to_resource_name(class_name: str) -> str:
"""Converts a camel case class name to a resource name with spaces.
>>> class_name_to_resource_name('FooBarObject')
'Foo Bar Object'
:param class_name: The name to convert.
:returns: The resource name.
"""
s = re.sub('(.)... | b0ac6692c441b0f4cfca4a9b680dc612552795f4 | 49,065 |
def datetime_to_date(dt, org):
"""
Convert a datetime to a date using the given org's timezone
"""
return dt.astimezone(org.timezone).date() | 92565cf65b0c485e6f8649a9a47619f516d0fd35 | 49,066 |
def raw_updates():
"""Test 5: Database Updates"""
connection = dbraw_engine.connect()
try:
num_queries = request.args.get('queries', 1, type=int)
if num_queries < 1:
num_queries = 1
if num_queries > 500:
num_queries = 500
worlds = []
rp = part... | c582fc5e76c9c137f31a64c38f050a2361264ca9 | 49,067 |
import numpy
def correlate(x1, x2, mode='valid'):
"""
Cross-correlation of two 1-dimensional sequences.
For full documentation refer to :obj:`numpy.correlate`.
Limitations
-----------
Input arrays are supported as :obj:`dpnp.ndarray`.
Size and shape of input arrays are supported to be eq... | ca0d71b6479eb0b62c98feb038a8b6525f8b92dd | 49,068 |
def virtual_machine_names_to_container_names(configuration):
"""
convert virtual machine names to container names using configuration
Args:
configuration: user final configuration
Returns:
list of container name in array
"""
return [
"{0}_{1}".format(
configu... | aba3ceab55d8af5041d6d784cea64a464b2d6bf5 | 49,069 |
def index():
"""For testing the application on the browser during development"""
return jsonify({'message': 'This is the home page'}) | e0898c8062a7677ae46cae4c76e01be5b4fb7327 | 49,070 |
import requests
def current_server_id() -> str:
"""Helper to get the current server id"""
rsp = requests.get("http://localhost:10000/api/servers")
if rsp.status_code != 200:
raise ValueError("Failed to fetch current server id")
return rsp.json()['current_server'] | 8ec4efcc0eeea0b5b62ce5446aece5abdf6fbd66 | 49,071 |
def get_pandas_read_csv_and_dropna_code():
"""
Get a simple code snipped that loads the adult_easy data and runs dropna
"""
code = cleandoc("""
import os
import pandas as pd
from mlinspect.utils import get_project_root
train_file = os.path.join(str(get_pr... | 9afc595cb206b2306bb8e0f6fce5aaaa6c0533fc | 49,072 |
def mean_std_cross_val_scores(model, X_train, y_train, **kwargs):
"""
Returns mean and std of cross validation
Parameters
----------
model :
scikit-learn model
X_train : numpy array or pandas DataFrame
X in the training data
y_train :
y in the training data
Retu... | 5d298927a54513448c5205b3013cda3352ffaa7e | 49,073 |
def needs_dataset(*names, default=None):
"""
Decorator for skipping methods when the needed atomic data is not available
"""
non_ion_datasets = ['abundance', 'ip', 'ioneq']
names = [f'_{n}' if n not in non_ion_datasets else f'{n}' for n in names]
def decorator(func):
@wraps(func)
... | a51c26102e88ed29f3ad8c07df88712d71aa52ad | 49,074 |
def linkcode_resolve(domain, info):
"""Oddly this function is required for the linkcode extension."""
if domain != "py":
return None
if not info["module"]:
return None
filename = info["module"].replace(".", "/")
return "https://github.com/farisachugthai/dynamic_ipython/%s.py" % file... | 6f4517a977b468847d1888eafeb5c3eb8698a160 | 49,075 |
import os
def get_name(main_title, folder, sep="_"):
""" Obtains the next valid name basd on given filename and count
Args:
main_title (str): Main portion to define naming scheme.
folder (str): Folder to be stored in. No '/' or '\' required.
sep (str): A separator between maint_title ... | e9519ef1626282e1a36e234b3cc57bed06b4ee7d | 49,076 |
def _read_airports_file(input_file=None):
"""Read the airports file."""
if input_file is None:
input_file = get_test_data('airport-codes.csv', as_file_obj=False)
df = pd.read_csv(input_file)
station_map = pd.DataFrame({'id': df.ident.values, 'synop_id': 99999,
'la... | 4647f4ac849d2596ad38190c0d3c95b8fc10174a | 49,077 |
from typing import List
from typing import Dict
def out_edge_node_mapper(
nodes: List[GraphVizNode]
) -> Dict[str, List[GraphVizNode]]:
"""
A function that maps a published topic to the publisher node
@params:
nodes: The list of nodes of the graph
@return: A dictionary where the key is t... | 90c3caa538a91f806b0e5d9b0b7b919f7e9a3bb3 | 49,078 |
def CircularHarmonicCaDihedralConstraints(a,b,c,d,value,tol):
"""
Returns properly formated string for declaring harmonic
dihedral angle constraints between CA carbons of resiedues
a, b, c and d at angle "value", and "tol" standard deviation.
Angles of 0 and 360 are treated as being next to each oth... | e48df4a25c27d7cf235623db9072b1d465d027c1 | 49,079 |
from sys import version_info
def decode_unicode_hook(json_pairs):
"""
Given json pairs, properly encode strings into utf-8 for general usage
:param json_pairs: dictionary of json key-value pairs
:return: new dictionary of json key-value pairs in utf-8
"""
if version_info >= (3, 0): # is 3.X
... | b7afc6507710b5452d889ed939a20ac56a8ab999 | 49,080 |
import torch
def create_sample(G, sample_size, z_size, seed):
"""
Create a sample.
returns
-------
A set saple z.
"""
torch.manual_seed(seed)
fixed_z = np.random.uniform(-1, 1, size=(sample_size, z_size))
fixed_z = torch.from_numpy(fixed_z).float()
if gpu_available:
... | 97decfa125743417c122b7c7ebdc719b1ba0478d | 49,081 |
def get_data_day(data: pd.DataFrame) -> np.array(int):
"""Get weekday/weekend designation value from data.
:param pd.DataFrame data: the data to get day of week from.
:return: (*np.array*) -- indicates weekend or weekday for every day.
"""
return data["If Weekend"] | 4b4cf9a4ad78970a1066626855d545f88b88bd34 | 49,082 |
def next_mesh_data_loader_uuid():
"""Return the next uuid of a mesh data loader."""
global mesh_data_loader_counter
mesh_data_loader_counter = (mesh_data_loader_counter + 1) % (1 << 60)
return mesh_data_loader_counter | e2f9550aeafa263e7d626591e9b487095e8427d2 | 49,083 |
def generate_emb_features(data, ft_model, window_size=5):
"""method for generating embeddings features
Args:
data: dict representation of conll file
ft_model: fasttext embeddings
window_size: how many neighbors to use
Returns:
dict: key: mention_id value: embedding_features... | 219b07fdf2a15bafb6ca554e11f8f77c908dee79 | 49,084 |
def log(input_t):
"""
Element-wise natural logarithm.
"""
return log_op(input_t) | 72f4f358715a5e83f826654d7702cbbc89d995f9 | 49,085 |
from typing import Dict
from typing import Any
from typing import Tuple
import json
def fetch_incidents(client: Client, last_run: Dict[str, Any], args: Dict[str, Any],
call_from_test=False) -> Tuple[dict, list]:
"""
This function is called for fetching incidents.
This function ... | a2e88693997013e15a4d1b8e0e3f6b6b169e419e | 49,086 |
def guess_gender(name):
"""
Given a person's name guess their gender.
Returns either ``'m'`` or ``'f'``.
"""
names = name.split()
if names[0] == 'Sankt':
first_name = names[1]
else:
first_name = names[0]
try:
return _GENDER_EXCEPTIONS[first_name]
except KeyEr... | ce8b3ae3bd188cd843e127246221d44e220e72ac | 49,087 |
def index():
"""Return the main page."""
restaurants = ["amelie_nyc", "lovemama_nyc", "upstate_nyc"]
return render_template("index.html", restaurants=restaurants) | a3c7c583acf154a5f792811ea652c2bc38d204b7 | 49,088 |
def stefan_boltzmann(radius, temperature):
"""Calculate the luminosity for a spherical blackbody following from
Stefan-Boltzmann.
Parameters
----------
radius: float
The radius of the sphere.
temperature: float
The temperature of the blackbody.
Returns
-------
lum: ... | 60f6452e25af443f2a8f1f94ec1408a833f5a818 | 49,089 |
def put_keys_in_numerical_order(keys):
"""
Takes a list of hookup keys in the format of prefix+number:revision and puts them in number order.
Returns the ordered list of keys
"""
keylib = {}
n = None
for k in keys:
colon = k.find(':')
for i in range(len(k)):
try:
... | 43807dc85b0485c6339697c45a19016b2dabeb25 | 49,090 |
def parse_input() -> list[int]:
"""
Parses the input and returns a list of depth measurements.
"""
with open(INPUT_FILE, "r") as f:
return [int(line) for line in f] | caed6904f676c25e07d2e2d29b427cf140625880 | 49,091 |
def apply_smoothing(image, kernel_size=5):
"""
kernel_size must be postivie and odd
"""
return cv2.GaussianBlur(image, (kernel_size, kernel_size), 0) | 65adc5abfc97c5c0a71a37ad12c8721bb0a38188 | 49,092 |
def convert_trie_to_flat_paths(trie, prefix=None):
"""Converts the directory structure in the given trie to flat paths, prepending a prefix to each."""
result = {}
for name, data in trie.iteritems():
if prefix:
name = prefix + "/" + name
if len(data) and not "results" in data:
... | 78313b1bfaad06c3364e78b8a0d460ba7aabec38 | 49,093 |
def build_cptp_data(db_path, db_name):
"""Builds training sets files for the SPMF library.
Training sets files created using the DB. A training set file in the format expected by the
java SPMF library: ' -1 ' between each number within a sequence and ' -2' to end a sequence
(see `SPMF/CPT+ docs <http:/... | 2cc5bd75c2ddc9a707284f79e8ad3417ebd01d73 | 49,094 |
def reflection_matrix(
point: np.ndarray,
normal: np.ndarray
) -> np.ndarray:
"""
Return matrix to mirror at plane defined by point and normal vector.
Reference: https://en.wikipedia.org/wiki/Transformation_matrix#Reflection_2
"""
normal = unit_vector(normal[:3])
M = np.identity(4)
... | 43ea429e1616c30a83de5c5428ecbf13106f576d | 49,095 |
def draw_hexagon(image=None, coordinates=None,
radius=None, thickness=None,
color_hex=None,
radius_dot=None, color_dot=None,
polygon_bool=None, draw_dots_bool=None):
"""
Generate a regular hexagon on a given image canvas with dots along the edge
:param image: Pillow/PIL Imag... | d2f89cafba758b2a1f398c314b288a802f919268 | 49,096 |
def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
"""
Compute the trimmed standard error of the mean.
This function finds the standard error of the mean for given
values, ignoring values outside the given `limits`.
Parameters
----------
a : array_like
array of value... | ae612ffe5a124ebfbb5df125e56db10c9b653665 | 49,097 |
def _parse_ligand_sdf(input_file):
"""
Function to parse a series of ligands - return RDKit mols.
:param input_file: the file to parse
:param input_type: the type of ligands
:return: the molecules parsed
"""
mols = Chem.SDMolSupplier(input_file)
return mols | 949d81a8224dd30a464ea1da1201457be9e6304e | 49,098 |
from typing import Union
from typing import Type
from typing import Dict
from typing import List
def get_anomalies_confidence_interval(
ts: "TSDataset",
model: Union[Type["ProphetModel"], Type["SARIMAXModel"]],
interval_width: float = 0.95,
in_column: str = "target",
**model_params,
) -> Dict[str,... | 2268fce74eeb57c99954cc33a6b4278badf2dcb9 | 49,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.