content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Tuple
from typing import Any
def concatenate_and_process_data(
data_consent: pd.DataFrame,
data_noconsent: pd.DataFrame,
conversion_column: str = CONVERSION_COLUMN,
drop_columns: Tuple[Any, ...] = DROP_COLUMNS,
non_dummy_columns: Tuple[Any, ...] = NON_DUMMY_COLUMNS
) -> Tuple[pd... | 57c84f0b406750b40161bb7f5ed19c5f2cd509e8 | 7,096 |
def plot(nRows=1, nCols=1, figSize=5):
"""
Generate a matplotlib plot and axis handle
Parameters
-----------------
nRows : An int, number of rows for subplotting
nCols : An int, number of columns for subplotting
figSize : Numeric or array (xFigSize, yFigSize). The size of each axis.
"""... | a0ec25fa932933f717ef9a576d0f80d531865aad | 7,097 |
def make_rate_data(grp, valuevars, query="none == 'All'", data=ob):
"""Filters, Groups, and Calculates Rates
Params:
grp [list]: A list detailing the names of the variables to group by.
valuevars [list]: A list detailing the names of the quantitative
variable summarise and calculate... | 8342d5b20f7020a97f283ce80b04b92b42476862 | 7,098 |
def test_compare_sir_vs_seir(sir_data_wo_policy, seir_data, monkeypatch):
"""Checks if SEIR and SIR return same results if the code enforces
* alpha = gamma
* E = 0
* dI = dE
"""
x_sir, pars_sir = sir_data_wo_policy
x_seir, pars_seir = seir_data
pars_seir["alpha"] = pars_sir["gamma"] ... | d70b841b23af6883a14bb1c97f31f3e24ae7fd4d | 7,099 |
def login(client, username='', password=''):
"""
Log a specific user in.
:param client: Flask client
:param username: The username
:type username: str
:param password: The password
:type password: str
:return: Flask response
"""
user = dict(login=username, password=password)
... | c0a9ac806fc0f1b55ebc76f5f50aa4b8e71436c4 | 7,100 |
def func(x, params):
"""The GNFW radial profile.
Args:
x (:obj:`np.ndarray`): Radial coordinate.
params (:obj:`dict`): Dictionary with keys `alpha`, `beta`, `gamma`, `c500`, and `P0` that defines
the GNFW profile shape.
Returns:
Profile (1d :obj:`np.ndarray`).
... | a7510bdcc7e5938ece6d888620372f95d013a114 | 7,101 |
def _readFromSettings(self, key):
"""Loads the settings object associated with the program and
returns the value at the key."""
COMPANY, APPNAME, _ = SELMAGUISettings.getInfo()
COMPANY = COMPANY.split()[0]
APPNAME = APPNAME.split()[0]
settings = QtCore.QSettings(COM... | a96b7b14789bb848fe288e419b1b9ff8c9b35db8 | 7,103 |
import logging
def is_statu(search_data):
"""
判断是否有参数,且为正常还是停用
:param search_data:
:return:
"""
logging.info('is_statu')
if search_data:
if search_data == '正常':
return '1'
elif search_data == '停用':
return '0'
else:
return search_d... | b9bcc643f2bb73fd692017cf5ff1dee23d528a8f | 7,106 |
def get_mysql_exception(errno, msg, sqlstate=None):
"""Get the exception matching the MySQL error
This function will return an exception based on the SQLState. The given
message will be passed on in the returned exception.
The exception returned can be customized using the
mysql.connector.cust... | 4ce4ae51a9a87b2a303aca4de5ac238fc6adf115 | 7,107 |
from typing import List
def get_image_resize_transform_steps(config, dataset) -> List:
"""
Resizes the image to a slightly larger square.
"""
assert dataset.original_resolution is not None
assert config.resize_scale is not None
scaled_resolution = tuple(
int(res * config.resize_scale) ... | d3c1ddd5a072efc853cc7967b70f2e98011d31a4 | 7,109 |
def get_page_title(page_src, meta_data):
"""Returns the title of the page. The title in the meta data section
will take precedence over the H1 markdown title if both are provided."""
return (
meta_data['title']
if 'title' in meta_data and isinstance(meta_data['title'], str)
else get_... | e9fc19f9bc1d615c2ba8b4210f9be5212c282e53 | 7,110 |
def saveReplayBuffer():
"""
Flush and save the contents of the Replay Buffer to disk. This is
basically the same as triggering the "Save Replay Buffer" hotkey.
Will return an `error` if the Replay Buffer is not active.
"""
return __createJSON("SaveReplayBuffer", {}) | 4be684acb7751ee6c78825a3e8c702db1b5d18f2 | 7,113 |
import base64
import json
def view_or_basicauth(view, request, test_func, realm = "", *args, **kwargs):
"""
This is a helper function used by both 'logged_in_or_basicauth' and
'has_perm_or_basicauth' that does the nitty of determining if they
are already logged in or if they have provided proper http-... | e3bca2ba1f0bf2a82105e7a530bb0ce05f324898 | 7,114 |
def _subtract_background_one_line(data_line, e_off, e_lin, e_quad, width):
"""
Subtract background from spectra in a single line of the image
Parameters
----------
data_line : ndarray
spectra for one line of an image, size NxM, N-the number of
pixels in the line, M - the number of ... | 10c9928b1e9d576e404ee82a028394381963472f | 7,115 |
def clean_principals_output(sql_result, username, shell=False):
"""
Transform sql principals into readable one
"""
if not sql_result:
if shell:
return username
return [username]
if shell:
return sql_result
return sql_result.split(',') | 313d04aef55c7fd689605a19d22c801123624a51 | 7,116 |
def matchesType(value, expected):
"""
Returns boolean for whether the given value matches the given type.
Supports all basic JSON supported value types:
primitive, integer/int, float, number/num, string/str, boolean/bool, dict/map, array/list, ...
"""
result = type(value)
expected = expecte... | 24949f01a1bc3ae63a120d91549ae06ba52298a8 | 7,117 |
def csv_logging(record):
"""generate output in csv format"""
csv_record = ('{ts},{si},{di},{sp},{dp},{t},"{p}",{h},{v},"{ha}",'
'"{k}","{e}","{m}","{c}"')
if 'hassh' in record:
hasshType = 'client'
kexAlgs = record['ckex']
encAlgs = record['ceacts']
macAlgs ... | 53fdbc8e634162199cec94d7cb1a7b737f08310f | 7,118 |
import itertools
from typing import Counter
def get_top_words(keywords):
"""
Orders the topics from most common to least common for displaying.
"""
keywords = itertools.chain.from_iterable(map(str.split, keywords))
top_words = list(Counter(keywords))
return top_words | 307a5a0e0e900e411097a84d19daf0ca7187c9bc | 7,121 |
def obj_prop(*args, **kwargs):
"""
Build an object property wrapper.
If no arguments (or a single ``None`` argument) are suppled, return a dummy property.
If one argument is supplied, return :class:`AttrObjectProperty` for a property with a given name.
Otherwise, return :class:`MethodObjectProp... | 9b2e7e28c7b68cafdcd39a447a5dcb15c493e399 | 7,124 |
from typing import Iterable
def _check_name(name: str, invars: Iterable[str]) -> str:
"""Check if count is valid"""
if name is None:
name = _n_name(invars)
if name != "n":
logger.warning(
"Storing counts in `%s`, as `n` already present in input. "
'... | 1dd4fce937e9a48a64147b9c4a03f713e7f7c433 | 7,126 |
def get_documents(corpus_tag):
"""
Returns a list of documents with a particular corpus tag
"""
values = db.select("""
SELECT doc_id
FROM document_tag
WHERE tag=%(tag)s
ORDER BY doc_id
""", tag=corpus_tag)
return [x.doc_id for x in values] | 933dd00e76475fbd14e4cd8b3dff9e918d98ff46 | 7,127 |
def draw_with_indeces(settings):
"""
Drawing function that displays the input smiles string with all atom indeces
"""
m = Chem.MolFromSmiles(settings['SMILESSTRING'])
dm = Draw.PrepareMolForDrawing(m)
d2d = Draw.MolDraw2DSVG(350,350)
opts = d2d.drawOptions()
for i in range(m.GetNumAtoms(... | b32b7031e97c264630e0cf6024c60b7eb87c6ff9 | 7,128 |
from app.extensions.celerybackend import models
from app.extensions.logger.models import Log
from app.modules.auth.models import User
from app.utils import local
def get_main_page_info():
"""获取首页统计信息
:return info: Dict 统计信息
"""
task_cnt = models.Tasks.objects(time_start_... | 5a8c67dcafd0f822102f89195726cb7648b136fb | 7,129 |
def get_tablenames(cur):
""" Conveinience: """
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
tablename_list_ = cur.fetchall()
tablename_list = [str(tablename[0]) for tablename in tablename_list_ ]
return tablename_list | 311335c38d9ea19396da3292513e3e1d7bd5caf0 | 7,130 |
import urllib
def reverse_geocode(userCoords):
"""
Returns the city, state (or equivalent administrative region), and country
that the specified point is in
userCoords is a tuple: (latitude, longitude)
"""
lat, lng = userCoords
latlng = "{0},{1}".format(lat, lng)
data = urllib.parse.ur... | b38d9585033c012ea6a90a14f2f321a538b42e86 | 7,131 |
def match_red_baselines(model, model_antpos, data, data_antpos, tol=1.0, verbose=True):
"""
Match unique model baseline keys to unique data baseline keys based on positional redundancy.
Ideally, both model and data contain only unique baselines, in which case there is a
one-to-one mapping. If model con... | 83c7d5cc371593ad694fa81e56be6e1034bd693f | 7,132 |
def _choose_random_genes(individual):
"""
Selects two separate genes from individual.
Args:
individual (np.array): Genotype of individual.
Returns:
gene1, gene2 (tuple): Genes separated by at least another gene.
"""
gene1, gene2 = np.sort(np.random.choice(len(individual), size=... | 08555dd3b3f1a04bbd93290fb9c60c37acc3583b | 7,133 |
import types
def incomplete_sample_detection(device_name):
"""Introspect whether a device has 'incomplete sample detection', described here:
www.ni.com/documentation/en/ni-daqmx/latest/devconsid/incompletesampledetection/
The result is determined empirically by outputting a pulse on one counter and
... | 52fac104ba408273c7876de0c37a62bc6548b7b6 | 7,134 |
def diag_numba(A, b):
""" Fill matrix A with a diagonal represented by vector b.
Parameters
----------
A : array
Base matrix.
b : array
Diagonal vector to fill with.
Returns
-------
array
Matrix A with diagonal filled.
"""
for i in range(b.shape[0]):
... | 7eb722eaea9e932c7e7d0f3c52b40d224c7152cc | 7,135 |
def get_symminfo(newsymms: dict) -> str:
"""
Adds text about the symmetry generators used in order to add symmetry generated atoms.
"""
line = 'Symmetry transformations used to generate equivalent atoms:\n'
nitems = len(newsymms)
n = 0
for key, value in newsymms.items():
sep = ';'
... | 2b3fdeebac85ea3329839406e611ba051f45ddce | 7,136 |
import random
def get_random_sequences(
self, n=10, length=200, chroms=None, max_n=0.1, outtype="list" # noqa
):
"""
Return random genomic sequences.
Parameters
----------
n : int , optional
Number of sequences to return.
length : int , optional
Length of sequences to re... | ac6c33de8d333b3998d5e1b4d20dd2780745f9db | 7,137 |
def get_sampleentropy(data):
"""Sample entropy, using antropy.sample_entropy, in the ML and AP directions. """
x, y = np.array(data[4]), np.array(data[5])
sample_entropy_ML = ant.sample_entropy(x)
sample_entropy_AP = ant.sample_entropy(y)
return sample_entropy_ML, sample_entropy_AP | d69d86de426bf4c7c9110d71a1a3c386a1d042d8 | 7,138 |
def from_json(filename, columns=None, process_func=None):
"""Read data from a json file
Args:
filename: path to a json file
columns (list, optional): list of columns to keep. All columns are kept by default
process_func (function, optional): A callable object that you can pass to proces... | 489603ff61c0a5aaa5012770d7c7649141002027 | 7,139 |
def render_content(tab):
"""
This function displays tabs based on user selection of tab
"""
if tab == 'tab-2':
return filter_based_recommendation.TAB2_LAYOUT
return choice_based_recommendation.CHOICE_BASED_RECOMMENDATION_LAYOUT | 085e17b401b52de4b2ff8b11765a798586832cf8 | 7,140 |
import requests
def course(name, reviews = False):
"""
Get a course.
Parameters
----------
name: string
The name of the course.
reviews: bool, optional
Whether to also return reviews for the course, specifically reviews for
professors that taught the course and have th... | 969c2a94ecf1bfad227279ba3475772a45939848 | 7,141 |
def task(weight=1):
"""
Used as a convenience decorator to be able to declare tasks for a TaskSet
inline in the class. Example::
class ForumPage(TaskSet):
@task(100)
def read_thread(self):
pass
@task(7)
def create_thr... | 9a5af6cb9dabe73a5c08c8938b438b74881f9f26 | 7,142 |
from datetime import datetime
def generate_age(issue_time):
"""Generate a age parameter for MAC authentication draft 00."""
td = datetime.datetime.now() - issue_time
age = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
return unicode_type(age) | 3164ee1422b5eafd56dee0b0e73183fc64d14597 | 7,143 |
def _bqm_from_1sat(constraint):
"""create a bqm for a constraint with only one variable
bqm will have exactly classical gap 2.
"""
configurations = constraint.configurations
num_configurations = len(configurations)
bqm = dimod.BinaryQuadraticModel.empty(dimod.SPIN)
if num_configurations =... | 149967077070e71eae66dc5521dfbae479645eda | 7,144 |
import paramiko
import traceback
import traceback
def _ssh(server):
"""
SSH into a Server
"""
remote_user = server.remote_user
private_key = server.private_key
if not private_key or not remote_user:
if remote_user:
return {"result": "Critical. Missing Private Key",
... | e54e72c8c4bff8deeac0e29a57393860954b299c | 7,145 |
from typing import Dict
from typing import List
from typing import Any
from typing import Tuple
def _create_group_codes_and_info(
states: pd.DataFrame,
assort_bys: Dict[str, List[str]],
contact_models: Dict[str, Dict[str, Any]],
) -> Tuple[pd.DataFrame, Dict[str, Dict[str, Any]]]:
"""Create group code... | 6acac718aa639e9584dbc5d7cb7d601731aa674e | 7,146 |
def quiver_plotter(X, Y, Z, plot_range=None, mes_unit='', title='', x_label=r'$x$', y_label=r'$y$', show_plot=True, dark=False):
"""
Generates a plot of some vector fields.
Parameters
----------
X : numpy.ndarray
Matrix with values for the first axis on all the rows.
Y : numpy.ndarray
... | 55a0c5768ce2827c851abf468030824ee9a1411e | 7,147 |
def get_attr(item, name, default=None):
"""
similar to getattr and get but will test for class or dict
:param item:
:param name:
:param default:
:return:
"""
try:
val = item[name]
except (KeyError, TypeError):
try:
val = getattr(item, name)
except... | 0c68c7e54ef901e18a49d327188f29f72f54da01 | 7,148 |
def float2(val, min_repeat=6):
"""Increase number of decimal places of a repeating decimal.
e.g. 34.111111 -> 34.1111111111111111"""
repeat = 0
lc = ""
for i in range(len(val)):
c = val[i]
if c == lc:
repeat += 1
if repeat == min_repeat:
return float(val[:i+1] + c * 10)
else... | 07fc521e877387242a1e6cf951a6d5cbdc925aaf | 7,149 |
def load_array_meta(loader, filename, index):
"""
Load the meta-data data associated with an array from the specified index
within a file.
"""
return loader(filename, index) | e53ed1d795edf2285b3eca333a7650a378c26b9a | 7,150 |
def viterbi_value(theta: np.ndarray, operator: str = 'hardmax') \
-> float:
"""
Viterbi operator.
:param theta: _numpy.ndarray, shape = (T, S, S),
Holds the potentials of the linear chain CRF
:param operator: str in {'hardmax', 'softmax', 'sparsemax'},
Smoothed max-operator
... | 7b1c37143c05f400cc910e07c97e51d4d3788ca9 | 7,151 |
def pack32(n):
"""Convert a Python int to a packed signed long (4 bytes)."""
return pack('<i', n) | 0caebee4af80c4defb75ed8512cb2d5d13cd7ede | 7,152 |
def run_rollout(
policy,
env,
horizon,
use_goals=False,
render=False,
video_writer=None,
video_skip=5,
terminate_on_success=False,
):
"""
Runs a rollout in an environment with the current network parameters.
Args:
policy (Rollout... | 52324d72a80aea83b667faa08e6e95c561311ee5 | 7,153 |
from typing import Union
from typing import Type
from typing import List
from typing import Optional
from typing import Dict
from typing import Any
from typing import cast
def create_test_client(
route_handlers: Union[
Union[Type[Controller], BaseRouteHandler, Router, AnyCallable],
List[Union[Type... | f110972c735e9ad81eca1f267651e97732d6e37c | 7,154 |
def queue_tabnav(context):
"""Returns tuple of tab navigation for the queue pages.
Each tuple contains three elements: (tab_code, page_url, tab_text)
"""
counts = context['queue_counts']
request = context['request']
listed = not context.get('unlisted')
if listed:
tabnav = [('nomina... | 6f3777ce46f09a6946ba66755a3ae27eda126da5 | 7,155 |
def _plot_feature_correlations(ax, correlation_matrix, cmap="coolwarm", annot=True, fmt=".2f", linewidths=.05):
"""
Creates a heatmap plot of the feature correlations
Args:
:ax: the axes object to add the plot to
:correlation_matrix: the feature correlations
:cmap: the color map
... | c7835c743552eec6beb3441bc324c2192d4db9d7 | 7,156 |
import tempfile
import copy
def graphviz_visualization(activities_count, dfg, image_format="png", measure="frequency",
max_no_of_edges_in_diagram=100000, start_activities=None,
end_activities=None, soj_time=None, font_size="12",
bgcolo... | f04bd9e0f076887072805f57d260310f309547fd | 7,157 |
from scipy.interpolate import RegularGridInterpolator
def sig_io_func(p, ca, sv):
# The method input gives control over how the Nafion conductivity is
# calculated. Options are 'lam' for laminar in which an interpolation is
# done using data from [1], 'bulk' for treating the thin Nafion shells the
#... | 3a51f6899d9d8792378d0870fa56f15172e1d6cc | 7,158 |
def srwl_opt_setup_cyl_fiber(_foc_plane, _delta_ext, _delta_core, _atten_len_ext, _atten_len_core, _diam_ext, _diam_core, _xc, _yc):
"""
Setup Transmission type Optical Element which simulates Cylindrical Fiber
:param _foc_plane: plane of focusing: 1- horizontal (i.e. fiber is parallel to vertical axis), 2-... | 45cd80cc3dee7e9ab61311e7bbc574722feadb49 | 7,159 |
from enum import Enum
def __create_menu_elements() -> Enum:
"""Create Menu Elements.
:return: Menu elements as an enum in the format KEY_WORD -> Vales(char, KeyWord)
"""
menu_keys = ["MAIN_MENU", "PROFILE", "CLEAN_TIME", "READINGS", "PRAYERS", "DAILY_REFLECTION", "JUST_FOR_TODAY",
"L... | 4407da506b681b124975827d94471e58089452a5 | 7,160 |
import math
def solve(coordinates):
"""
알고리즘 풀이 함수 : 두 점의 최단거리를 구해주는 함수
:param coordinates: 좌표들
:return: 두 점의 최단거리
"""
n = len(coordinates)
x_coordinates = [coordinate[0] for coordinate in coordinates]
y_coordinates = [coordinate[1] for coordinate in coordinates]
middle_point = (su... | fc6594e45537cf07bac870b6f932b00dd59d57bd | 7,161 |
def get_cache_key(account, container=None, obj=None):
"""
Get the keys for both memcache and env['swift.infocache'] (cache_key)
where info about accounts, containers, and objects is cached
:param account: The name of the account
:param container: The name of the container (or None if account)
:... | d46270d33fcbaecc0bf1886965ac1b1771a3fc8d | 7,162 |
def arctan(x):
"""Returns arctan(x)"""
if type(x) in (float,_numpy._numpy.float64): x = _numpy._numpy.array([x])
a = abs(x)
r = arctan_1px( a - 1. )
f = arctan_series( a )
eps = _numpy._numpy.finfo(1.).eps
g = arctan_series( 1. / maximum( 0.125, a ) )
g = 0.5 * _numpy._numpy.pi - g
j... | 6bb5f45115abd34bc7ba7892fac28eb397a131f6 | 7,164 |
def uniform_dist(low, high):
"""Return a random variable uniformly distributed between `low` and `high`.
"""
return sp_uniform(low, high - low) | e4520ee4a5a44c33fe565788b4d576a35f4c3430 | 7,165 |
import re
from typing import MutableMapping
def flatten(dictionary, parent_key=False, separator='_'):
"""
Turn a nested dictionary into a flattened dictionary
:param dictionary: The dictionary to flatten
:param parent_key: The string to prepend to dictionary's keys
:param separator: The string use... | 45131797a602c4fcb9f40f275d755c068b1baa83 | 7,166 |
def format_sec_to_hms(sec):
"""Format seconds to hours, minutes, seconds.
Args:
sec: float or int
Number of seconds in a period of time
Returns: str
Period of time represented as a string on the form ``0d\:00h\:00m``.
"""
rem_int, s_int = divmod(int(sec), 60)
h_int, m_int,... | aa2cc5d6584cdebf4d37292435ecd46bb6adc4a4 | 7,167 |
def one_hot_encode(data):
"""turns data into onehot encoding
Args:
data (np.array): (n_samples,)
Returns:
np.array: shape (n_samples, n_classes)
"""
n_classes = np.unique(data).shape[0]
onehot = np.zeros((data.shape[0], n_classes))
for i, val in enumerate(data.astyp... | 58602ffa7d5964bfbb4b8457f698aad800cb3298 | 7,168 |
def is_number(input_str):
"""Check if input_str is a string number
Args:
input_str (str): input string
Returns:
bool: True if input_str can be parse to a number (float)
"""
try:
float(input_str)
return True
except ValueError:
return False | d22fe852a15e3d926cffb36ea3d8a235592ea62a | 7,169 |
def impute_between(coordinate_a, coordinate_b, freq):
"""
Args:
coordinate_a:
coordinate_b:
freq:
Returns:
"""
metrics = discrete_velocity(coordinate_a, coordinate_b)
b, d, sec = metrics['binning'], metrics['displacement'], metrics['time_delta']
if b != 'stationar... | 208729df0bd701302103a30e01e0cbdc5208f118 | 7,170 |
def seq(fr,to,by):
"""An analogous function to 'seq' in R
Parameters:
1. fr: from
2. to: to
3. by: by (interval)
"""
if fr<to:
return range(fr,to+abs(by),abs(by))
elif fr>to:
if by>0:
aseq = range(fr,to-by,-1*by)
else:
aseq = range(fr,... | 39b7878f81e93c137eed1e435e438b1645b09f9f | 7,171 |
def _get_config_from_context(ctx):
"""
:param ctx:
:return:
:rtype: semi.config.configuration.Configuration
"""
return ctx.obj["config"] | c085f69fd87ad5f72c8453e6f01771d943b2c481 | 7,172 |
def _invert_options(matrix=None, sparse=None):
"""Returns |invert_options| (with default values) for a given |NumPy| matrix.
See :func:`sparse_options` for documentation of all possible options for
sparse matrices.
Parameters
----------
matrix
The matrix for which to return the options... | 0625b86038c29dbf0e6db4e87b9e76de05bce426 | 7,173 |
def get_Carrot_scramble(n=70):
""" Gets a Carrot-notation scramble of length `n` for a Megaminx. Defaults to csTimer's default length of 70. """
return _UTIL_SCRAMBLER.call("util_scramble.getMegaminxCarrotScramble", n).replace('\n','').replace(' ',' ').replace(' ',' ') | 8155294b86f9d5cbe756f7476afb952446603d8c | 7,175 |
def convex_env_train(Xs, Ys):
"""
Identify the convex envelope on the set of models
from the train set.
"""
# Sort the list in either ascending or descending order of the
# items values in Xs
key_X_pairs = sorted(Xs.items(), key=lambda x: x[1],
reverse=False) # this... | e9a9dd4a56bddd01ae1e071003ea8412b075b9de | 7,176 |
def randthresh(Y,K,p=np.inf,stop=False,verbose=False,varwind=False,knownull=True):
"""
Wrapper for random threshold functions (without connexity constraints)
In: Y (n,) Observations
K <int> Some positive integer (lower bound on the number of null hypotheses)
p ... | d42a9c4ddd27c3ad462d6a447b779db700a58976 | 7,177 |
import gc
def referrednested(func, recurse=True): #XXX: return dict of {__name__: obj} ?
"""get functions defined inside of func (e.g. inner functions in a closure)
NOTE: results may differ if the function has been executed or not.
If len(nestedcode(func)) > len(referrednested(func)), try calling func().... | 357fde8030423690a5ae2f8ebcf42c7e86337d2a | 7,178 |
from typing import Dict
from typing import Any
from typing import Tuple
def format_organizations_output(response: Dict[str, Any], page_number: int, limit: int) -> Tuple[list, int]:
"""
Formatting list organizations command outputs.
Args:
response (Dict[str,Any): The response from the API call.
... | 6eee18e58fd8b6fdba50f995df060689bdb63ef2 | 7,179 |
def which_db_version(cursor):
"""
Return version of DB schema as string.
Return '5', if iOS 5.
Return '6', if iOS 6 or iOS 7.
"""
query = "select count(*) from sqlite_master where name = 'handle'"
cursor.execute(query)
count = cursor.fetchone()[0]
if count == 1:
db_version ... | 07b1dbcea3fb4bf65bba5c578257440d39b6784c | 7,180 |
def gaussian_total_correlation(cov):
"""Computes the total correlation of a Gaussian with covariance matrix cov.
We use that the total correlation is the KL divergence between the Gaussian
and the product of its marginals. By design, the means of these two Gaussians
are zero and the covariance matrix of... | 93b52d075cba08c58067f7e2c6b76e8c5b06fa76 | 7,182 |
def S3list(s3bucket, fdate, instrm, network='OKLMA'):
"""
get list of files in a s3 bucket for a specific fdate and instrument (prefix)
fdate: e.g. '2017-05-17'
instrm: e.g. 'GLM'
"""
prefix = {'GLM': 'fieldcampaign/goesrplt/GLM/data/L2/' + fdate + '/OR_GLM-L2-LCFA_G16',
'LIS': 'fi... | afe77daf5b78545ae89a555064511c3be19947f0 | 7,183 |
def formatted_karma(user, activity):
"""
Performs a karma check for the user and returns a String that's already formatted exactly like the usual response of the bot.
:param user: The user the karma check will be performed for.
:return: A conveniently formatted karma
check response.
"""
resp... | fa130f6bd64763200ed76a9284f9e83c686b7fb7 | 7,184 |
import collections
def extras_features(*features):
"""
Decorator used to register extras provided features to a model
"""
def wrapper(model_class):
# Initialize the model_features store if not already defined
if "model_features" not in registry:
registry["model_features"] ... | 03ff8f6fe9d020b55f416468cceacf0f163ec102 | 7,185 |
def setFeedMoleFraction(H2COxRatio, CO2COxRatio):
"""
set inlet feed mole fraction
"""
# feed properties
# H2/COx ratio
# H2COxRatio = 2.0
# CO2/CO ratio
# CO2COxRatio = 0.8
# mole fraction
y0_H2O = 0.00001
y0_CH3OH = 0.00001
y0_DME = 0.00001
# total molar fractio... | 82d368cd84a06a29663aee4c04a0505dba7536bb | 7,186 |
def format(message, *args, **kwargs):
"""Shortcut for :class:`tossi.Formatter.format` of the default registry.
"""
return formatter.vformat(message, args, kwargs) | 9d32c6a7497ffaa9b0da592f2c5ad828f22cf294 | 7,187 |
from django.http.request import QueryDict
def reverse_url(url_name,id,request):
"""
编辑标签返回当前页
:param url_name:
:param id:
:param request:
:return:
"""
path = request.get_full_path()
query_dict_obj = QueryDict(mutable=True)
query_dict_obj['next'] = path
encode_url = query_dict_obj.urlencode()
prefix_path... | 3453fed5717c2d3a335554e0b02965be8b3c04d0 | 7,188 |
from typing import Dict
from typing import List
def add_default_to_data(data: Dict[str, object], schema: SchemaDictType) -> Dict[str, object]:
"""Adds the default values present in the schema to the required fields
if the values are not provided in the data
"""
# add non as defaults to the field ... | 58b460eebb675457ed7832b4e211b72e2b018d03 | 7,189 |
import re
def repeating_chars(text: str, *, chars: str, maxn: int = 1) -> str:
"""Normalize repeating characters in `text`.
Truncating their number of consecutive repetitions to `maxn`.
Duplicates Textacy's `utils.normalize_repeating_chars`.
Args:
text (str): The text to normalize.
c... | 9dc326947a900d3531dcd59bf51d5c3396a42fea | 7,190 |
import io
import csv
def export_data_csv():
""" Build a CSV file with the Order data from the database
:return: The CSV file in StringIO
"""
result = query_order.get_all_orders()
output = io.StringIO()
writer = csv.writer(output)
line = ['Numéro de commande', 'Date', 'Montant total', '... | 5839542a1ef366a63850d04909080b8bca8d4714 | 7,191 |
import re
def findurls(s):
"""Use a regex to pull URLs from a message"""
regex = r"(?i)\b(((https?|ftp|smtp):\/\/)?(www.)?[a-zA-Z0-9_.-]+\.[a-zA-Z0-9_.-]+(\/[a-zA-Z0-9#]+\/?)*\/*)"
url = re.findall(regex,s)
return [x[0] for x in url] | 801947e893a23a4e440c8e5fc838d6aa89671e0c | 7,192 |
def collide_rect(left, right):
"""collision detection between two sprites, using rects.
pygame.sprite.collide_rect(left, right): return bool
Tests for collision between two sprites. Uses the pygame.Rect colliderect
function to calculate the collision. It is intended to be passed as a
collided call... | 2111b4d6298cc435d61e12f301d5373cc07c54ff | 7,193 |
from typing import Callable
def get_minhash(
doc: str,
normalization_func: Callable,
split_method: str,
ngram_size: int,
ngram_stride: int,
num_minhashes: int,
random_seed: int,
) -> LeanMinHash:
"""Returns a minhash fingerprint for the given document.
Args:
doc (str):
... | 7f9340885a8ec3b9eba85f627550ed9d8f2df6c1 | 7,195 |
import re
def tokenize(text):
"""
Function:
tokenize: This function splits text into words and return the root form of the words
Args:
text(str): the message
Return:
lemm(list of str): a list of the root form of the message words
"""
# Normalizing text (a-zA-Z0-9 ma... | 4ee5cf7bad56f565c211824b1a5838d732cbeab5 | 7,196 |
import pickle
def displayRandomForest():
"""Run displayRandomForest"""
executionStartTime = int(time.time())
# status and message
success = True
message = "ok"
plotUrl = ''
dataUrl = ''
# get model1, var1, pres1, model2, var2, pres2, start time, end time, lon1, lon2, lat1, lat2, nSamp... | a77cce60947d553a870f636fcfc8e3b282b69eea | 7,197 |
def get_reports(request):
"""
Get a list of all :model:`reporting.Report` entries associated with
an individual :model:`users.User` via :model:`rolodex.Project` and
:model:`rolodex.ProjectAssignment`.
"""
active_reports = []
active_projects = (
ProjectAssignment.objects.select_relate... | dc622daf0303e6137a36962db45655de1c43deb2 | 7,198 |
import json
def create_response(key, value):
"""Return generic AWS Lamba proxy response object format."""
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({key: value})
} | 9236a9e4504e6fbebe841b8cc6b6ad4602dae463 | 7,199 |
import io
import torch
def load_image_buffer_to_tensor(image_buf, device):
"""Maps image bytes buffer to tensor
Args:
image_buf (bytes buffer): The image bytes buffer
device (object): The pytorch device object
Returns:
py_tensor tensor: Pytorch tensor
"""
image = Image.op... | 43740d2f9b7eec64f54111e85e0a54787afc8100 | 7,200 |
def alpha2tand(freq, a, b, n):
"""Convert Halpern's 'a' and 'b' from an absorption coefficient
of the form `a*freq**b` to a (frequency-dependent) loss tangent.
Parameters
----------
freq : numpy array or float
The frequency (Hz) (or frequencies) at which to calculate the loss
tangen... | 2acf658e7d18a0e115ba557698cc4efd591ed26d | 7,201 |
def convert_path_to_pixels(path):
"""
Purpose:
---
This function should convert the obtained path (list of tuples) to pixels.
Teams are free to choose the number of points and logic for this conversion.
Input Arguments:
---
`path` : [ list ]
Path returned from task_4a.find_path() function.
Returns:
... | a50557f252d43f9c3df1b3781c1203dd518d3797 | 7,202 |
def uniform_prob(*args, prob=None, inside=None, pscale=1.):
""" Uniform probability function for discrete and continuous vtypes. """
# Detect ptype, default to prob if no values, otherwise detect vtype
assert len(args) >= 1, "Minimum of a single positional argument"
pscale = eval_pscale(pscale)
use_logs = ... | 75cd547fc2845cb94f5733310be0d7761ba379fb | 7,203 |
import glob
def obtenerListaArchivos(path: str):
""" genera una lista de los archivos alojados en str """
lista = glob.glob(path, recursive=True)
return lista | 3b9582dbf086a2af673cc75277041f32d001e215 | 7,204 |
def is_equal_to(amount: float) -> Predicate:
"""Says that a field is exactly equal to some constant amount."""
return is_nearly_equal_to(amount, tolerance=0, taper=0) | c2c9b795d7bb089834e8e11e980b9d794e69d97a | 7,205 |
def load_yaml(fname):
"""Load a YAML file."""
yaml = YAML(typ="safe")
# Compat with HASS
yaml.allow_duplicate_keys = True
# Stub HASS constructors
HassSafeConstructor.name = fname
yaml.Constructor = HassSafeConstructor
with open(fname, encoding="utf-8") as conf_file:
# If config... | 957a5d171568592da89cfa58a69c746ffcf67d33 | 7,207 |
def unmix_cvxopt(data, endmembers, gammaConst=0, P=None):
"""
******************************************************************
unmix finds an accurate estimation of the proportions of each endmember
Syntax: P2 = unmix(data, endmembers, gammaConst, P)
This product is Copyright (c) 2013 University o... | d529b412afde7a7eb35a02d5d039ec271285829f | 7,208 |
import logging
def _accumulate_reward(
timestep: dm_env.TimeStep,
episode_return: float) -> float:
"""Accumulates rewards collected over the course of an episode."""
if timestep.reward and timestep.reward != 0:
logging.info('Reward: %s', timestep.reward)
episode_return += timestep.reward
if ti... | 8f96e9a5bbeb4babfd43283b6da8a7984e53f02b | 7,209 |
def unsafe_load(stream):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
Resolve all tags, even those known to be
unsafe on untrusted input.
"""
return load(stream, UnsafeLoader) | ff74beb13746504508832cc9b658a8faf672d2ca | 7,210 |
import pickle
def load_tl_gan_model():
"""
Load the linear model (matrix) which maps the feature space
to the GAN's latent space.
"""
with open(FEATURE_DIRECTION_FILE, 'rb') as f:
feature_direction_name = pickle.load(f)
# Pick apart the feature_direction_name data structure.
featu... | aeb0bd329e4c9f8c91ded7c80385c30e1fb69773 | 7,211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.