content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def list_dataset_contents(datasetName=None, nextToken=None, maxResults=None, scheduledOnOrAfter=None, scheduledBefore=None):
"""
Lists information about data set contents that have been created.
See also: AWS API Documentation
Exceptions
:example: response = client.list_dataset_contents(
... | 5,328,000 |
def test_app_creation():
"""
Test if a Flask-Philo_Core app is created properly
"""
# check that raises error if not settings file is provided
with pytest.raises(ConfigurationError):
init_app(__name__)
with patch.dict(
os.environ, {
'FLASK_PHILO_SETTINGS_MODULE': 'c... | 5,328,001 |
def django_db_setup(django_db_setup, django_db_blocker):
"""Set up the database for tests that need it"""
with django_db_blocker.unblock():
user_one = User.objects.create_user(
email='user_one@example.com',
password='test_123'
)
Token.objects.create(user=user_one... | 5,328,002 |
def get_sample_eclat(name):
"""Read a tweet sample from a sample file and return it in a format eclat
can process.
"""
sampleFile = open(name)
X = []
Y = []
line = sampleFile.readline()
while line != '':
row = line.split()
Y.append(int(row[0]))
... | 5,328,003 |
def test_object_names_tables(sdc_builder, sdc_executor, gcp, table_name):
"""
Create data using Google BigQuery client with specific table names
and then check if Google BigQuery origin receives them using wiretap.
The pipeline looks like:
google_bigquery >> wiretap
"""
pipeline_builder... | 5,328,004 |
def process_songs(spark, df, output_data):
"""Process Data Frame with raw songs data using Spark and create Songs dimensional table stored in S3"""
print('Processing songs...')
# Define schema for the Songs table. Schema also could be inferred implicitly
# but defining it manually protects us from wro... | 5,328,005 |
def test_dmd_computation():
""" Check all variants of DMD on a toy problem
"""
for exact in [True, False]:
for total in [True, False]:
yield check_kdmd_computation_simple, exact, total | 5,328,006 |
def viz():
"""check queenbee is flying"""
click.echo("""
.' '. __
viiiiiiiiiiiiizzzzzzzzz! . . . . (__\_
. . . -{{_(|8)
' . . ' ' . . ' (__/
""") | 5,328,007 |
def get_model():
"""Summary
"""
download_and_extract_tar(
'http://download.magenta.tensorflow.org/models/nsynth/wavenet-ckpt.tar') | 5,328,008 |
def submission_storage_path(instance, filename):
"""
Function DocString
"""
string = '/'.join(['submissions', instance.submission_user.user_nick, str(instance.submission_question.question_level), str(instance.submission_question.question_level_id)])
string += '/'+datetime.datetime.now().strftime... | 5,328,009 |
def distance_to_center(n):
"""Return Manhattan distance to center of spiral of length <n>."""
dist = distances_to_center()
for _ in range(n - 1):
next(dist)
return next(dist) | 5,328,010 |
def detect_tachycardia(heart_rate, age):
"""
This function makes best guess as to whether tachycardia is being exhibited
:param float heart_rate: heart rate in bpm
:param int age: age of user/patient
:return ble tachycardia: whether or not tachycardia detected
"""
import logging as log
... | 5,328,011 |
def test_seed_consistency(n, d, r, D_):
""" Seed consistency checker: verify that using the same seed gives the
same result, and different seeds give different results. Could make this
a fuzzy test by generating random values for other parameters. """
seed1, seed2 = 25, 23857235
instances = []
m... | 5,328,012 |
async def _assert_preconditions_async(preconditions: List[List[Contract]],
resolved_kwargs: Mapping[str, Any]) -> Optional[BaseException]:
"""Assert that the preconditions of an async function hold."""
exception = None # type: Optional[BaseException]
# Assert the prec... | 5,328,013 |
def moveGeneratorFromStrList (betaStringList, string_mode = True):
""" generate the final output of move sequence as a list of dictionary.
Input :
['F5-LH', 'F5-RH', 'E8-LH', 'H10-RH', 'E13-LH', 'I14-RH', 'E15-LH', 'G18-RH']
Length of the list: how many moves in this climb to the target hold. Targe... | 5,328,014 |
def main_mix(args):
"""Render the final mix into a single bitstream file from ordered
track list using pydub.
Computes the output file for end-to-start feature matching mixing
algorithm used in farmers manual's guest mix @sorbierd 2017
"""
from pydub import AudioSegment
# f = open('trk_seq_... | 5,328,015 |
def add_upstream_ids(table_a, id_a, table_b, id_b, upstream_ids_col):
"""note upstream ids
"""
db = pgdata.connect()
schema_a, table_a = db.parse_table_name(table_a)
schema_b, table_b = db.parse_table_name(table_b)
# ensure that any existing values get removed
db.execute(
f"ALTER TAB... | 5,328,016 |
def generateVtBar(row):
"""生成K线"""
bar = VtBarData()
symbol, exchange = row['symbol'].split('.')
bar.symbol = symbol
bar.exchange = exchangeMapReverse[exchange]
if bar.exchange in ['SSE', 'SZSE']:
bar.vtSymbol = '.'.join([bar.symbol, bar.exchange])
else:
bar.vt... | 5,328,017 |
def index_with_links():
"""post request that the form link uses
"""
db = sqlite3.connect('link_shortner.db')
c = db.cursor()
link = request.forms.get('link')
generated_id = gen_id()
#row = db.execute('SELECT * from links where link_id=?', generate_id).fetchone()
c.execute("INSERT... | 5,328,018 |
def SinGAN_generate(Gs, Zs, reals, styles, NoiseAmp, opt, in_s=None, scale_v=1, scale_h=1, n=0, gen_start_scale=0, num_samples=10):
"""
Generate image with the given parameters.
Returns:
I_curr(torch.cuda.FloatTensor) : Current Image
"""
#if torch.is_tensor(in_s) == False:
if in_s is Non... | 5,328,019 |
def divide_blend(img_x: np.ndarray, img_y: np.ndarray) -> np.ndarray:
"""
Blend image x and y in 'divide' mode
:param img_x: input grayscale image on top
:param img_y: input grayscale image at bottom
:return:
"""
result = np.zeros_like(img_x, np.float_)
height, width = img_x.shape
f... | 5,328,020 |
def table_to_bipartite_graph(
table: Tabular,
first_part_col: Hashable,
second_part_col: Hashable,
*,
node_part_attr: str = "part",
edge_weight_attr: str = "weight",
first_part_data: Optional[RowDataSpec] = None,
second_part_data: Optional[RowDataSpec] = None,
first_part_name: Option... | 5,328,021 |
def init_wavefunction(n_sites,bond_dim,**kwargs):
"""
A function that initializes the coefficients of a wavefunction for L sites (from 0 to L-1) and arranges
them in a tensor of dimension n_0 x n_1 x ... x n_L for L sites. SVD
is applied to this tensor iteratively to obtain the matrix product state.... | 5,328,022 |
def num_channels_to_num_groups(num_channels):
"""Returns number of groups to use in a GroupNorm layer with a given number
of channels. Note that these choices are hyperparameters.
Args:
num_channels (int): Number of channels.
"""
if num_channels < 8:
return 1
if num_channels < 3... | 5,328,023 |
def response_message(status, message, status_code):
"""
method to handle response messages
"""
return jsonify({
"status": status,
"message": message
}), status_code | 5,328,024 |
def glDrawBuffers( baseOperation, n=None, bufs=None ):
"""glDrawBuffers( bufs ) -> bufs
Wrapper will calculate n from dims of bufs if only
one argument is provided...
"""
if bufs is None:
bufs = n
n = None
bufs = arrays.GLenumArray.asArray( bufs )
if n is None:
... | 5,328,025 |
def black_check(context):
"""Check if code is properly formatted using black"""
context.run("black --check *.py tests src") | 5,328,026 |
def compare_rendered(obj1, obj2):
"""
Return True/False if the normalized rendered version of
two folium map objects are the equal or not.
"""
return normalize(obj1) == normalize(obj2) | 5,328,027 |
def handle_chosen_inline_result(bot, update, session, user):
"""Save the chosen inline result."""
result = update.chosen_inline_result
splitted = result.result_id.split(':')
# This is a result from a banned user
if len(splitted) < 2:
return
[search_id, file_id] = splitted
inline_qu... | 5,328,028 |
async def _get_device_client_adapter(settings_object):
"""
get a device client adapter for the given settings object
"""
if not settings_object.device_id and not settings_object.id_scope:
return None
adapter = adapters.create_adapter(settings_object.adapter_address, "device_client")
ad... | 5,328,029 |
def is_reserved(word):
"""
Determines if word is reserved
:param word: String representing the variable
:return: True if word is reserved and False otherwise
"""
lorw = ['define','define-struct']
return word in lorw | 5,328,030 |
def launch_from_openmpi(config: Union[str, Path, Config, Dict],
host: str,
port: int,
backend: str = 'nccl',
seed: int = 1024,
verbose: bool = True):
"""A wrapper for colossalai.launch for OpenMPI... | 5,328,031 |
def test_client_index_year():
"""
Test retrieving list of indices for a given year.
"""
index_list = openedgar.clients.edgar.list_index_by_year(1994)
result = len(index_list)
expected = 119
assert_equal(result, expected) | 5,328,032 |
def verify_figure_hash(name, figure=None):
"""
Verifies whether a figure has the same hash as the named hash in the current hash library.
If the hash library does not contain the specified name, the hash is added to the library.
Parameters
----------
name : string
The identifier for the... | 5,328,033 |
def x_span_contains_y(x_spans, y_spans):
"""
Return whether all elements of y_spans are contained by some elements of x_spans
:param x_spans:
:type x_spans:
:param y_spans:
:type y_spans:
"""
for i, j in y_spans:
match_found = False
for m, n in x_spans:
i... | 5,328,034 |
def test_cray_config_list(cli_runner):
""" Test `cray init` for creating the default configuration """
runner, cli, _ = cli_runner
result = runner.invoke(cli, ['config', 'list', '--quiet'])
assert result.exit_code == 0
res = json.loads(result.output)
assert res.get('configurations')
active =... | 5,328,035 |
def parse_args():
"""Parse arguments and return them
:returns: argparse object
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-c',
'--config',
help='configuration file',
required=True)
return parser.parse_args() | 5,328,036 |
def log(fn):
"""
logging decorator for the for the REST method calls. Gets all important information
about the request and response, takes the time to complete the calls and writes it
to the logs.
"""
def wrapped(self, *args):
try:
start = time()
ret = fn(self, *a... | 5,328,037 |
def deal_line(text_str1, text_str2, para_bound=None):
"""行合并和段落拆分"""
global result_text
text_str2 = text_str2.strip()
len_text_str2 = len(text_str2)
if len_text_str2 > 3 and len(set(text_str2)) == 1: # 处理 ***** 这类分割线
st = list(set(text_str2))[0]
# new_file.write(' ' + st * 24 +... | 5,328,038 |
def interpreter_loop(namespace={}, debug=False, rpn_class=RPN, rpn_instance=None):
"""run an interactive session"""
if rpn_instance is None:
rpn_instance = rpn_class(namespace)
while True:
try:
print
print rpn_instance
words = raw_input('> ')
... | 5,328,039 |
def process_swiss(cfg, interpolation, country_mask, out, latname, lonname):
"""
Process "Swiss National Emission Inventory" created by Meteotest Inc.
"""
if cfg.add_total_emissions:
total_flux = {}
for var in cfg.species:
var_name = cfg.in2out_species.get(var, var)
... | 5,328,040 |
def resized_image(image: np.ndarray, max_size: int) -> np.ndarray:
"""Resize image to feature_process_size."""
h, w = image.shape[:2]
size = max(w, h)
if 0 < max_size < size:
dsize = w * max_size // size, h * max_size // size
return cv2.resize(image, dsize=dsize, interpolation=cv2.INTER_... | 5,328,041 |
def load_folder_list(args, ndict):
"""
Args:
dict : "name_run" -> path
"""
l = []
for p in ndict:
print("loading %s" % p)
l.append(load_pickle_to_dataframe(args, p))
d = pd.concat(l)
d = d.sort_values("name_run")
print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%... | 5,328,042 |
def show_categorical(df, target=None, sharey=False, figsize=(17, 2), ncols=5):
"""
Display histograms of categorical features
If a target list is provided, their histograms will be excluded
"""
if target is None:
target = []
if ncols <= 1:
ncols =5
print( "Number... | 5,328,043 |
def charge_initial():
"""
Not currently in use, parking spot id gets passed in and it carries over
and passes it into the stripe charge view.
"""
spot_id = int(request.args.get('id'))
spot = AddressEntry.query.get(spot_id)
return render_template('users/charge_initial.html', key=stripe_keys['... | 5,328,044 |
def read_csv_from_file(file):
"""
Reads the CSV data from the open file handle and returns a list of dicts.
Assumes the CSV data includes a header row and uses that header row as
fieldnames in the dict. The following fields are required and are
case-sensitive:
- ``artist``
- ``song`... | 5,328,045 |
def findOutliers(time, flux, gap=None,
threshold_sigma=4,
precision_days=0.0205,
maxClusterLen = 2
):
"""
Identify single point outliers.
Preserves consecutive outliers, and those that are evenly spaced in
time. This protects short dur... | 5,328,046 |
def identify_denonavr_receivers():
"""
Identify DenonAVR using SSDP and SCPD queries.
Returns a list of dictionaries which includes all discovered Denon AVR
devices with keys "host", "modelName", "friendlyName", "presentationURL".
"""
# Sending SSDP broadcast message to get devices
devices ... | 5,328,047 |
def get_index_settings(index):
"""Returns ES settings for this index"""
return (get_es().indices.get_settings(index=index)
.get(index, {}).get('settings', {})) | 5,328,048 |
def test_environ() -> None:
"""Test environ."""
orig_expected = dict(os.environ)
override = {"TEST_PARAM": "override", "new_param": "value"}
override_expected = dict(orig_expected)
override_expected.update(override)
assert os.environ == orig_expected, "validate original value"
with environ... | 5,328,049 |
def test_backend_validate_incorrect_package(endpoint_url, iam_auth, product):
"""
Test POST /backend/validate with an incorrect product
"""
wrong_product = copy.deepcopy(product)
wrong_product["package"]["height"] += 100
res = requests.post(
"{}/backend/validate".format(endpoint_url),... | 5,328,050 |
def register(app: Flask) -> NoReturn:
"""
Registers all views blueprints.
:param: app Flask application.
:return:
"""
from . import auth
app.register_blueprint(auth.bp_auth) | 5,328,051 |
def make_hashkey(seed):
"""
Generate a string key by hashing
"""
h = hashlib.md5()
h.update(six.b(str(seed)))
return h.hexdigest() | 5,328,052 |
async def report(database, year, month, limit):
"""Get a report."""
matches_query = """
select count(*) as count
from matches
where extract(year from played)=:year and extract(month from played)=:month
"""
players_query = """
select count(distinct players.user_id) as coun... | 5,328,053 |
def compose_ntx_graph(input_file=None, delimiter=None, weighted=None):
"""
This function creates a networkx graph from provided file
:param input_file: Input file path
:param delimiter: separator for the column of the input file
:param weighted: Simple yes/no if the input file is weighted or not
... | 5,328,054 |
def test_algorithms():
"""Test detection/deblending/measurement algorithms if installed"""
compare_sep()
compare_sep_multiprocessing() | 5,328,055 |
def dy3(vector, g, m1, m2, L1, L2):
"""
Abbreviations
M = m0 + m1
S = sin(y1 - y2)
C = cos(y1 - y2)
s1 = sin(y1)
s2 = sin(y2)
Equation
y3' = g*[m2 * C * s2 - M * s1] - S*m2*[L1 * y3^2 * C + L2*y4^2]
-----------------------------------------------------------... | 5,328,056 |
def plotCurve():
"""Plot enhancement vs intensity at given wavelength."""
import setup as st
from scipy.linalg import norm
# Initialization
ksi = (-9.1+0.35j)*1e-19 #2e-19
#aryIntensity = np.array([0.08, 0.18, 0.4, 0.8, 1.65, 8, ])# 1400 nm
aryIntensity = np.linspace(0.08, 8, 100) ... | 5,328,057 |
def test_properties_facade_prefix_not_string():
"""
Test setting up a facade with a prefix that is not a string.
"""
# Arrange
config_map = {"property": "2"}
application_properties = ApplicationProperties()
application_properties.load_from_dict(config_map)
# Act
raised_exception = ... | 5,328,058 |
async def test_expired_token_exception(event_loop, v2_server):
"""Test that the correct exception is raised when the token is expired."""
async with v2_server:
v2_server.add(
'api.simplisafe.com', '/v1/api/authCheck', 'get',
aresponses.Response(text='', status=401))
asyn... | 5,328,059 |
def getType(resp: falcon.Response, class_type: str, method: str) -> Any:
"""Return the @type of object allowed for POST/PUT."""
for supportedOp in get_doc(resp).parsed_classes[class_type]["class"].supportedOperation:
if supportedOp.method == method:
return supportedOp.expects.replace("vo... | 5,328,060 |
def handle_command(command, channel):
"""
Receives commands directed at the bot and determines if they
are valid commands. If so, then acts on the commands. If not,
returns back what it needs for clarification.
"""
response = "Not sure what you mean. Use the *" + EXAMPLE_COMMAND + \
... | 5,328,061 |
def do_server_remove_network_service(client, args):
""" Remove network role from a system VM """
kwargs = {}
kwargs['proto'] = args.proto
if args.port and args.port > 0:
kwargs['port'] = args.port
roles = client.guests.perform_action(args.id, 'remove-network-service',
... | 5,328,062 |
def _patch_setuptools():
"""Patch ``setuptools`` to address known issues.
Known issues:
* In some PyPy installs, the ``setuptools.build_py.build_package_data()``
method depends on the ``convert_2to3_doctests`` being set on an instance
of ``setuptools.dist.Distribution``, but it is unset. We han... | 5,328,063 |
def texWinToolCtx(*args, **kwargs):
"""
This class creates a context for the View Tools track, dolly, and box zoomin the texture window.
Flags:
- alternateContext : ac (bool) [create,query]
Set the ALT+MMB and ALT+SHIFT+MMB to refer to this context.
- boxzoo... | 5,328,064 |
def tokenize(source: str):
"""parce the source of a program and return a generator of tokens"""
i = 0
line = 1
col = 1
while i < len(source):
if source[i].isspace(): # parse whitespace
while i < len(source) and source[i].isspace():
if source[i] == "\n":
... | 5,328,065 |
def print_info(cbf_path):
"""Print out a load of data held in the CBF file.
This is by no means a full list of the data contained in the file, it's
mainly for debugging and development purposes. The data that will be
printed is the following:
- The number of categories and the name of each category... | 5,328,066 |
def full_data_numeric():
"""DataFrame with numeric data
"""
data_dict = {'a': [2, 2, 2, 3, 4, 4, 7, 8, 8, 8],
'c': [1, 2, 3, 4, 4, 4, 7, 9, 9, 9],
'e': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
df = pd.DataFrame(data_dict)
return df | 5,328,067 |
def fix(x):
"""
Replaces spaces with tabs, removes spurious newlines, and lstrip()s each
line. Makes it really easy to create BED files on the fly for testing and
checking.
"""
s = ""
for i in x.splitlines():
i = i.lstrip()
if i.endswith('\t'):
add_tab = '\t'
... | 5,328,068 |
def get_collect_method(collect_method_name):
"""Return the collect method."""
try:
collect_method = CollectMethod.get(name=collect_method_name)
except ValueError:
raise RuntimeError(f'Collect Method {collect_method_name} not found!')
return collect_method | 5,328,069 |
def TriangleBackwardSub(U,b):
"""C = TriangleBackwardSub(U,b)
Solve linear system UC = b
"""
C = solve(U,b)
return C | 5,328,070 |
def test_binance_query_balances_unknown_asset(function_scope_binance):
"""Test that if a binance balance query returns unknown asset no exception
is raised and a warning is generated. Same for unsupported asset."""
binance = function_scope_binance
def mock_unknown_asset_return(url): # pylint: disable=... | 5,328,071 |
def test_sample_categorical_copy():
"""Check the random variable sampling results after schedule copy"""
n = 100
sch = tir.Schedule(elementwise, seed=42, debug_mask="all")
candidates = [1, 2, 3, 4]
probs = [0.1, 0.2, 0.3, 0.4]
rv_decisions = []
for _ in range(n):
rv = sch.sample_cate... | 5,328,072 |
def main():
""" main """
my_logfile = 'logs/awsbuild.log'
my_region = 'us-east-1'
#my_vpc = 'vpc-xxx'
my_tag = 'momo-us-east-1'
# setup logging
log_formatter = logging.Formatter("%(asctime)s %(filename)s %(name)s %(levelname)s %(message)s")
root_logger = logging.getLogger()
file_han... | 5,328,073 |
def petsc_to_stencil(x, Xh):
""" converts a numpy array to StencilVector or BlockVector format"""
x = x.array
u = array_to_stencil(x, Xh)
return u | 5,328,074 |
def index_internal_txs_task(self) -> Optional[int]:
"""
Find and process internal txs for monitored addresses
:return: Number of addresses processed
"""
with contextlib.suppress(LockError):
with only_one_running_task(self):
logger.info("Start indexing of internal txs")
... | 5,328,075 |
def make_lagrangian(func, equality_constraints):
"""Make a Lagrangian function from an objective function `func` and `equality_constraints`
Args:
func (callable): Unary callable with signature `f(x, *args, **kwargs)`
equality_constraints (callable): Unary callable with signature `h(x, *args, **... | 5,328,076 |
def render_task(task: todotxt.Task, namespace: argparse.Namespace, level: int = 0) -> str:
"""Render one task."""
indent = (level - 1) * " " + "- " if level else ""
rendered_task = colorize(reference(task, namespace), namespace)
rendered_blocked_tasks = render_blocked_tasks(task, namespace, level)
... | 5,328,077 |
def ungroup(expr):
"""Helper to undo pyparsing's default grouping of And expressions,
even if all but one are non-empty.
"""
return TokenConverter(expr).addParseAction(lambda t: t[0]) | 5,328,078 |
def main():
"""Train ensemble model.
"""
# construct the argument parse and parse the arguments
args = argparse.ArgumentParser()
args.add_argument("-o", "--output", required=True, help="path to output directory")
args.add_argument("-m", "--models", required=True, help="path to output models dire... | 5,328,079 |
def remove_tmp_directories():
"""
remove tmp directories submitted in tmp_directories
Returns:
True
"""
for tmp_dir in tmp_directories:
os.remove(tmp_dir)
return True | 5,328,080 |
def get_actual_type(arg_type: Type, kind: int,
tuple_counter: List[int]) -> Type:
"""Return the type of an actual argument with the given kind.
If the argument is a *arg, return the individual argument item.
"""
if kind == nodes.ARG_STAR:
if isinstance(arg_type, Instance):
... | 5,328,081 |
def trigger_write_PART(code, args, text, raw):
"""
ID: PART
Decription: Triggered when the bot write a PART, so that we can unhook
database from that channel.
Format: part <channel>
"""
del code.chan[args[1]]
del code.logs['channel'][args[1]]
del ... | 5,328,082 |
def cmd():
"""
run from cmd
:return:
"""
args = parser.parse_args()
command = args.command
# init workspace for gerapy
if command == 'init':
init(args.folder)
# generate code according to configuration
elif command == 'generate':
generate(args.project)
# debug... | 5,328,083 |
def test_qnn_legalize():
"""Test directly replacing an operator with a new one"""
def before():
x = relay.var("x", shape=(1, 64, 56, 56), dtype='int8')
y = relay.qnn.op.requantize(x,
input_scale=1,
input_zero_point=0,
... | 5,328,084 |
def load(data, schema, yamlLoader=yaml.UnsafeLoader):
"""
Loads the given data and validates it according to the schema provided.
Data must be either JSON or YAML, it must be a dictionary, a path, or a string of JSON.
Schema must be JSON, it must be a dictionary, a path, or a string of JSON.
"""
... | 5,328,085 |
def calculate_slice_rotations(im_stack: np.ndarray, max_rotation:float = 45) -> List[float]:
"""Calculate the rotation angle to align each slice so the
objects long axis is aligned with the horizontal axis.
Parameters
----------
im_stack : np.ndarray
A stack of images. The images should be ... | 5,328,086 |
def vocab_count(corpus, min_count=5, outdir='output', bindir=''):
"""Run GloVe's vocab_count."""
outdir = Path(outdir)
outdir.mkdir(exist_ok=True)
vocab = outdir / VOCAB_FNAME
cmd = os.path.join(bindir, 'vocab_count')
cmd += f' -min-count {min_count}'
cmd += f' < {corpus} > {vocab}'
ru... | 5,328,087 |
def calc_rest_interval(data):
"""
SubTool for Investigate: after median_deviation filters through all the
points run entropy on the remaining non_rest points. This will filter the
close but could still be rest points.
"""
lst, rest = median_deviation(data)
average = median(data)
st_entr... | 5,328,088 |
def get_objanno(fin_anno, godag, namespace='all'):
"""Get annotation object"""
fin_full = get_anno_fullname(fin_anno)
return get_objanno_factory(fin_full, godag=godag, namespace=namespace) | 5,328,089 |
def delete_library_block(usage_key, remove_from_parent=True):
"""
Delete the specified block from this library (and any children it has).
If the block's definition (OLX file) is within this same library as the
usage key, both the definition and the usage will be deleted.
If the usage points to a d... | 5,328,090 |
def create_table_descriptives(datasets):
"""Merge dataset descriptives."""
df = pd.concat(
[pd.read_json(ds, orient="index") for ds in datasets],
axis=0
)
df.index.name = "dataset_name"
return df | 5,328,091 |
def test_character_start():
"""
Test that password doesn't starts with special characters.
"""
assert validate_if("!éáíúópaodsipas") == False | 5,328,092 |
def timeLimit(seconds: int) -> Generator[None, None, None]:
"""
http://stackoverflow.com/a/601168
Use to limit the execution time of a function. Raises an exception if the execution of the
function takes more than the specified amount of time.
:param seconds: maximum allowable time, in seconds
... | 5,328,093 |
def test_ap_blacklist_all(dev, apdev, params):
"""Ensure we clear the blacklist if all visible APs reject"""
hapd0 = hostapd.add_ap(apdev[0], {"ssid": "test-open", "max_num_sta": "0"})
hapd1 = hostapd.add_ap(apdev[1], {"ssid": "test-open", "max_num_sta": "0"})
bss0 = hapd0.own_addr()
bss1 = hapd1.ow... | 5,328,094 |
def get_ngram_universe(sequence, n):
"""
Computes the universe of possible ngrams given a sequence. Where n is equal to the length of the sequence, the resulting number represents the sequence universe.
Example
--------
>>> sequence = [2,1,1,4,2,2,3,4,2,1,1]
>>> ps.get_ngram_universe(sequence, 3)
64
"""
# if... | 5,328,095 |
def adjust_spines(ax, spines, points_outward=10):
"""
Helps in re-creating the spartan style of Jean-luc Doumont's graphs.
Removes the spines that are not specified in spines, and colours the specified
ones in gray, and pushes them outside the graph area.
"""
for loc, spine in ax.spines.items():
if l... | 5,328,096 |
def as_nested_dict(
obj: Union[DictLike, Iterable[DictLike]], dct_class: type = DotDict
) -> Union[DictLike, Iterable[DictLike]]:
"""
Given a obj formatted as a dictionary, transforms it (and any nested dictionaries)
into the provided dct_class
Args:
- obj (Any): An object that is formatted... | 5,328,097 |
def twoindices_positive_up_to(n, m):
"""
build 2D integer indices up to n (each scanned from 0 to n)
"""
if not isinstance(n, int) or n <= 0:
raise ValueError("%s is not a positive integer" % str(n))
nbpos_n = n + 1
nbpos_m = m + 1
gripos = np.mgrid[: n : nbpos_n * 1j, : m : nbpo... | 5,328,098 |
def get_data_lists(data, MOT=False):
""" Prepare rolo data for SORT
Arguments:
data: config of the following form:
{
'image_folder': data_folder + 'images/train/',
'annot_folder': data_folder + 'annotations/train/',
'detected_folder': d... | 5,328,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.