content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def request_nwis(site, service, start_date, end_date):
"""Request stream gauge data from the USGS NWIS.
Args:
site (str):
a valid site is 01585200
service (str):
can either be 'iv' or 'dv' for instantaneous or daily data.
start_date (str):
should take ... | 51,300 |
def concat_train_val(train_df, val_df):
"""Utility function to concatenate the train and validation set, while maintaining globally unique ids."""
# increment id tags
max_article_id = train_df['Article_ID'].max() + 1
max_ner_tag_id = train_df['NER_Tag_ID'].max() + 1
increment_article_id = partial(in... | 51,301 |
def drop_project_by_id(project_id: int):
"""Drop a project.
---
tags:
- project
parameters:
- name: project_id
in: path
description: The identifier of a project
required: true
type: integer
format: int32
"""
project = manager.cu_authenticated_... | 51,302 |
def setup_default_logging():
"""
Set up root logger so all inherited loggers get console for free.
Args:
logger:
Returns:
"""
global _logger
logging.basicConfig(stream=sys.stderr, format=_logging_format_simple, level=_logging_default_level)
# so that the logger for this file... | 51,303 |
def speedUpPlot(save,x,y):
"""Use this function to make speed up plots"""
plt.close('all') #close other plots
fig, ax = plt.subplots(ncols=1,nrows=1)
ax.set_xlim([8e4,1e7])
line1 = ax.semilogx(x,y,marker='o',linestyle="solid",color='#d95f02')
ax.set_ylabel('speedup')
ax.set_xlabel('grid size... | 51,304 |
def frequencyToMidi(frequency):
"""
Convert a given frequency in Hertz to its corresponding MIDI pitch number (60 = Middle C)
"""
return int(round(69 + 12 * math.log(frequency / 440.0, 2))) | 51,305 |
def lower(value): # Only one argument.
"""Converts a string into all lowercase
How to Use
{{ value|lower|lower|.... }}
"""
return value.lower() | 51,306 |
def export(options, service):
""" main export method: export any number of indexes """
start = options.kwargs['start']
end = options.kwargs['end']
fixtail = options.kwargs['fixtail']
once = True
squery = options.kwargs['search']
squery = squery + " index=%s" % options.kwargs['index']
i... | 51,307 |
def stdp2rbp_non_linear_calcium(*args, **kwargs):
"""Rate-based plasticity from STDP using the non linear calcium model.
Same arguments as ~cbsp.population_1.non_linear_calcium(u, v, w0, seed)
Returns:
float: the population average change of synapse strength at time point 0
"""
w_rec, ... | 51,308 |
def close_connection(sock):
"""Close an open connection of a socket.socket() object."""
sock.close() | 51,309 |
def create_RevPAR(dataframe):
"""Calculate revpar from answer_num_rooms converted to supply of
room nights divided by answer_ann_revenue"""
dataframe['CREATED_revpar'] = dataframe['ANSWER_ann_revenue'].astype(float)/(dataframe['ANSWER_num_rooms'].astype(float)*365)
return dataframe | 51,310 |
def get_find_response_normal_field_dict(model):
"""
:param model:
:return:
"""
normal_fields = get_normal_field_list_by_model(model) # 普通字段
find_response_allow_fields = {}
for normal_field in normal_fields:
response_key = newbee_model.get_attr_by_model_field_key(model, normal_fiel... | 51,311 |
def test_quadbin_tochildren(quadbin, resolution, children):
"""Computes children for quadbin"""
result = run_query(f'SELECT QUADBIN_TOCHILDREN({quadbin},{resolution})')
assert result[0][0] == children | 51,312 |
def get_locale_directory(project, locale):
"""
Get path to the directory with locale files.
Args:
project: Project instance
locale: Locale instance
Returns:
Dict with directory name and path as keys.
"""
path = get_repository_path_master(project)
for root, dirnames... | 51,313 |
def create_inputs_file(args):
"""
Create the inputs.yaml file for the ACCESS Variant calling pipeline (modules 3 + 4)
:param args: argparse.ArgumentParser object
"""
validate_args(args)
if args.pairing_file_path:
pairing_df = pd.read_csv(
args.pairing_file_path, sep="\t", co... | 51,314 |
def update(dt):
"""
Update game. Called once per frame.
dt is the amount of time passed since last frame.
If you want to have constant apparent movement no matter your framerate,
what you can do is something like
x += v * dt
and this will scale your velocity based on time. Extend as necess... | 51,315 |
def predict():
"""Return Cell with Summary"""
global CLEAN_SUMMARY
global model
summary = CLEAN_SUMMARY
in_count = None
out_count = None
logger.info('Received Text Input')
if request.method == 'POST':
out = request.form['rawtext']
# preprocess text
... | 51,316 |
def id_generator(N=10):
"""
Generator a random string of characters.
"""
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) | 51,317 |
def transform_covariance(cov_in, transform):
"""
Apply a given transform to a covariance matrix.
:param cov_in: Covariance matrix
:param transform: The transform that will be applies
:returns: The transformed covariance matrix
"""
# Converting the Quaternion to a Rotation Matrix first
#... | 51,318 |
def delete_vocabulary(vid):
"""
Delete an existing vocabulary
:return:
"""
try:
vocs.delete_vocabulary(vid)
except IndexError:
raise APIError('Ontology URI not found')
except vocs.UnknownVocabulary, e:
raise NotFound(e.message)
__analyse_vocabularies([vid])
_... | 51,319 |
def available_kurucz_models():
"""These hard-code the available Kurucz models, as present on Nov 22, 2019 on
'http://kurucz.harvard.edu/grids/grid'"""
import numpy as np
T_a = np.concatenate((np.arange(3500,13250,250),np.arange(13000,1000,51000)))
logg_a = np.arange(0,5.5,0.5)
Z_a = np.round(np.... | 51,320 |
def draw_skill_prices(
T,
J,
pi_fun='pi_fixed',
low=-0.2,
high=0.2,
const=[0.0, 0.05]
):
""" Draws initial skill prices and simulates random prices changes.
With the normalization of wages in task 1 to zero, some parts
of this function are redundent. However, the way this function is... | 51,321 |
def test_ArrayStore_get_view():
"""Tests for ArrayStore class.get_view()."""
sample = np.random.uniform(-1, 1, size=100)
arraystore = carma.dArrayStore(sample, False)
arr = arraystore.get_view(False)
assert arr.flags['OWNDATA'] is False
np.testing.assert_allclose(arr.flatten(), sample) | 51,322 |
def sibor_level(bot, update):
""" Get Latest SIBOR """
bot.sendMessage(update.message.chat_id, text='Let me ask the GAHMEN...',
parse_mode='HTML')
bot.sendChatAction(update.message.chat_id, action=ChatAction.TYPING)
final_string = finance.get_sibor()
final_string += "\nWa Why So ... | 51,323 |
def deal_with_categorical(feasible_values, one_hot_values):
""" function to do the one hot encoding of the categorical values """
index = np.argmax(one_hot_values)
#index = one_hot_values.argmax()
return feasible_values[int(index)] | 51,324 |
def pretty_size(n, pow=0, b=1024, u='B', pre=[''] + [p + 'i' for p in 'KMGTPEZY']):
""" origin: https://stackoverflow.com/a/31178618 """
pow, n = min(int(m_log(max(n * b ** pow, 1), b)), len(pre) - 1), n * b ** pow
return "%%.%if %%s%%s" % abs(pow % (-pow - 1)) % (n / b ** float(pow), pre[pow], u) | 51,325 |
def test_listing_parse_html(app_context, listing, listing_html):
"""Test parsing HTML for listings"""
listing = model.Listing.query.get(listing)
assert listing.bedrooms == None
assert listing.bathrooms == None
listing.parse_html(listing_html)
assert listing.bedrooms == 1
assert listing.bathr... | 51,326 |
def launch_container(container, **kwargs):
"""
Launch a specific container
:param container:
:return: the container ID
"""
# Build the container if it doesn't exist
logger.info("Building %s container..." % container)
client.images.build(path='../%s' % container,
t... | 51,327 |
def collatz_function(n):
"""
This function, collatz function, takes a number n and the entire part on the division
with 2 if n is even or 3*n+1 is n is odd.
"""
if n % 2 == 0:
return n//2
else:
return 3*n+1 | 51,328 |
def atk_card(msg):
"""Socket for attacking card update"""
gameid = msg["gameid"]
card = msg["card"]
gameLst[gameid].atk_card = card
gameLst[gameid].update()
print(gameLst[gameid].serialize()) | 51,329 |
def has_enabled_clear_method(store):
"""Returns True iff obj has a clear method that is enabled (i.e. not disabled)"""
return hasattr(store, 'clear') and ( # has a clear method...
not hasattr(store.clear, 'disabled') # that doesn't have a disabled attribute
or not store.clear.disabled
) | 51,330 |
def _parser():
"""Take care of all the argparse stuff.
:returns: the args
"""
parser = argparse.ArgumentParser(description="Arxiv Text-To-Speach")
parser.add_argument('arxivID', help='Arxiv Identifier')
parser.add_argument('-o', '--output', default=False,
help='Output Fi... | 51,331 |
def get_module_for_handler(handler_name):
"""
Gets the module for a handler using naming convention. First the name of the handler is capitalized and appended by the
string "Handler". Then it is converted from camel to snake case to get the name of the module that will be loaded. Raises an
ImportError e... | 51,332 |
def create_model(activations_outfeed_queue, gradient_accumulation_steps_per_replica):
""" Create the model using the Keras Model class.
Outfeed the activations for a single layer.
"""
input_layer = keras.layers.Input(shape=(28, 28, 1), dtype=tf.float32, batch_size=32)
x = keras.layers.Flatten()... | 51,333 |
def del_vpc(ec2, vpcid):
""" Delete the VPC """
vpc_resource = ec2.Vpc(vpcid)
try:
print("Removing vpc-id: ", vpc_resource.id)
vpc_resource.delete(
# DryRun=True
)
except boto3.exceptions.Boto3Error as e:
print(e)
print("Please remove dependencies and delete VPC manually.... | 51,334 |
def main():
"""
end-to-end classification
"""
binary = True # binary or multi-class classification.
args = ArgParser.parse_args()
input_path = args.input
graph_filename = args.graph
prod_data_dir = args.output
flag = args.flag
clf_opt = args.clf_opt
exp_id = a... | 51,335 |
def project_config(opts):
"""Template of project_config.yaml
Args:
opts: mapping parameters as dictionary
Returns:
str: file content as string
"""
template = get_template("project_config")
return template.safe_substitute(opts) | 51,336 |
def _make_dense_split(quantile_accumulator_handle, stats_accumulator_handle,
stamp_token, next_stamp_token, multiclass_strategy,
class_id, feature_column_id, l1_regularization,
l2_regularization, tree_complexity_regularization,
... | 51,337 |
def test_contact_for_password_reset():
"""Test that if there is no mailserver configured, users should contact admins"""
app = create_ctfd()
with app.app_context():
register_user(app, name="user1", email="user@user.com")
with app.test_client() as client:
forgot_link = "http://lo... | 51,338 |
def destroy_instance(instance_alias, user, core_identity_uuid):
"""
NOTE: Argument order changes here -- instance_alais is used as the first argument to make chaining this taks easier with celery.
"""
from service import instance as instance_service
try:
celery_logger.debug(
"des... | 51,339 |
def load_data(dataset='cifar10', batch_size=128, num_workers=4):
"""
Loads the required dataset
:param dataset: Can be either 'cifar10' or 'cifar100'
:param batch_size: The desired batch size
:return: Tuple (train_loader, test_loader, num_classes)
"""
print('==> Preparing data..')
transf... | 51,340 |
def do_network_private(client, args):
""" Make a virtual network private """
net = client.networks.perform_action(args.id, 'private')
utils.print_dict(net) | 51,341 |
def get_auth_from_netrc(hostname):
"""Try to find login auth in ``~/.netrc``. Return ``(user, pwd)`` tuple. """
try:
auth = netrc(file=NETRC)
except IOError as cause:
if cause.errno != errno.ENOENT:
raise
return None, None
username, _, password = auth.hosts.get(hostn... | 51,342 |
def _add_rows_by_count(df, amount, count, alloc_id, constraint, stuff=False):
"""
Add rows to a table so that the sum of values in the `count` column
is increased by `amount`.
Parameters
----------
df : pandas.DataFrame
amount : float
Amount by which to increase sum of `count` colum... | 51,343 |
def rot2(theta, deg=True):
"""returns 2D rotation matrix :math:`R \in SO(2)` to rotate a vector/point in a
plane in counter-clockwise direction
Parameters
----------
theta : float
the angle of rotation
deg : bool
``True`` = degree (default), ``False`` = radians
Returns
... | 51,344 |
def coin_flip(prob):
"""
Return the outcome of a biased coin flip.
Args:
prob: the probability of True.
Returns: bool
"""
return prob > 0 and torch.rand(1).item() < prob | 51,345 |
def _pair_exp_cov(X, Y, span=180):
"""
Calculate the exponential covariance between two timeseries of returns.
:param X: first time series of returns
:type X: pd.Series
:param Y: second time series of returns
:type Y: pd.Series
:param span: the span of the exponential weighting function, def... | 51,346 |
def _protected_division(x1, x2):
"""Closure of division (x1/x2) for zero denominator."""
with np.errstate(divide='ignore', invalid='ignore'):
return np.where(np.abs(x2) > 0.001, np.divide(x1, x2), x1) | 51,347 |
def test_cli_description(cli):
"""Verify providing a description works correctly."""
res = cli.invoke(build_magic, ['--description', 'This is a test', 'echo hello world'])
out = res.output
assert res.exit_code == ExitCode.PASSED
assert 'Starting Stage 1 - This is a test' in out | 51,348 |
def api_version(request):
"""Fixture for parameterizing API tests based on the API version."""
yield request.param | 51,349 |
def warn_tex(warning_name: str, extra_info: str='') -> None:
"""Run warn() with `tex = True`. This is useful for shorthand, e.g., `import warn_tex as warn`.
See warn() documentation for full description.
Args:
warning_name (str): Key from the "warnings" object in messages.json
extra_info (s... | 51,350 |
def get_config(client, config_type, basefolder="/config"):
"""
Return an object that can be used to push/pull configurations inside
an etcd database.
Examples:
import etcd3
import etcdgo
client = etcd3.Etcd3Client()
# push a json configuration inside database
... | 51,351 |
def get_file_attribute_dtypes(filename):
# type: (str) -> Dict[str, str]
"""
Get the dtypes of the attributes of the file
:param filename:
:return:
"""
with h5py.File(filename, 'r') as infile:
return {key: type(value).__name__ for key, value in infile.attrs.items()} | 51,352 |
def default_input_format(content_type='application/json', apply_globally=False, api=None):
"""A decorator that allows you to override the default output format for an API"""
def decorator(formatter):
formatter = hug.output_format.content_type(content_type)(formatter)
if apply_globally:
... | 51,353 |
def popargs(*args, **kwargs):
"""A decorator for _cp_dispatch
(cherrypy.dispatch.Dispatcher.dispatch_method_name).
Optional keyword argument: handler=(Object or Function)
Provides a _cp_dispatch function that pops off path segments into
cherrypy.request.params under the names specified. The dispa... | 51,354 |
def to_pass(line):
"""
Replace a line of code with a pass statement, with
the correct number of leading spaces
Arguments
----------
line : str, line of code
Returns
----------
passed : str, line of code with same leading spaces
but code replaced with pass statemen... | 51,355 |
def reverse_sort_C(C, sorted_index):
"""
Perform the reverse of sort described in sort_by_sorted_index, on rows in a numpy array.
Args:
C (numpy.array): array with C.shape[0] = len(sorted_index)
sorted_index (list of ints): desired order for rows of C
"""
m,n = C.shape
C_new = numpy.zeros(C.shape)
for i in... | 51,356 |
def test_set_checkpoint(local_config):
"""Test the set_checkpoint() API."""
manager = StateManager(local_config)
manager.set_checkpoint("148429-4", "default", "DONE")
assert getattr(manager._persistor, "_sc", 0) == 1
assert getattr(manager._persistor, "_gph", 0) == 0
assert getattr(manager._pers... | 51,357 |
def auto_reconnect_connection(func):
"""
Attempt to safely reconnect when an error is hit that resembles the
bouncer disconnecting the client due to a timeout/etc.
"""
@wraps(func)
def inner(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except Except... | 51,358 |
def test_insertBefore_with_valid_inputs():
"""To test insertBefore with valid inputs."""
lst = LinkedList()
lst.append('apple')
lst.append('cucumber')
lst.append('date')
lst.append('elderberry')
lst.insertBefore('cucumber', 'banana')
assert lst.head.val == 'apple'
assert lst.head._ne... | 51,359 |
def windices_of_references(string, sen_dict):
"""
returns a list of word/sentence indices for all coreferences to
the given string in sen_dict.
returns [(0,0,0)] if there were no coreferences found.
"""
indices = []
coreferences = coreferences_for(string, sen_dict)
if not coreferences:
... | 51,360 |
def iptables_insert_rule(chain, src=None, dest=None, target=None):
"""Insert a new rule in the chain
"""
if not chain:
raise ValueError("Invalid chain")
if not target:
raise ValueError("Invalid target")
if not (src or dest):
raise ValueError("Need src, dest, or both")
ar... | 51,361 |
def radius(x,y,z,xa,ya) :
"""
Compute distances between the control points (x,y) and a potential center (xa, ya)
in UTM coord, and sort the results depending on the elevation
of the control points (z)
Parameters
----------
x,y,z : UTM coordinates and Elevation of the control point
... | 51,362 |
def exportNotesUI():
"""
Lets user pick a directory and exports Notes to it.
"""
w = QWidget()
NotesPath = str(QFileDialog.getExistingDirectory(w, "Pick Notes Folder"))
if NotesPath:
exportedDecks = exportAllNotes(NotesPath)
if exportedDecks:
w.show()
show... | 51,363 |
def test_runs03():
"""runs"""
args = '{} --seed 4 --length 300 --text_width 50 --num_words 3 {}'
out = getoutput(args.format(prg, const))
expected = open('test-outs/const.seed4.width50.len300.words3').read()
assert out.rstrip() == expected.rstrip() | 51,364 |
def send_email(subject, message, to):
"""
Sends an email
"""
logging.info(
"Sending email with subject {subject} to {to}: {message}"
.format(subject=subject, to=to, message=message))
if settings.EMAIL_SENDING:
from_addr = "montage@meedan.com".format(
appid=set... | 51,365 |
def remove_labels(data):
"""
Keep only sqrt(n) of the real labels. To find the others, use k=sqrt(sqrt(n))
nearest neighbors from the labels we know, and use the mode.
"""
# "Remove" labels
# lost_idx = np.random.choice(
# len(data.y_train), size=int(len(data.y_train) - np.sqrt(len(data.y... | 51,366 |
async def async_setup(hass, config):
"""Set up the Ais Files platform."""
# register services
@asyncio.coroutine
async def async_transfer_file(call):
if "path" not in call.data or "name" not in call.data:
return
await _async_transfer_file(hass, call.data["path"], call.data["... | 51,367 |
def expand(curr_state: State, params: FindPathParams) -> Iterable[Identifier]:
"""
Expand a state into it's children states
"""
per_agent_expansion = []
for agent in curr_state.identifier.actual:
agent: Agent
# if an agent is colliding, expand it fully
if curr_state.collisi... | 51,368 |
def start_reactor(
appname,
soft_file_limit,
gc_thresholds,
pid_file,
daemonize,
cpu_affinity,
logger,
):
""" Run the reactor in the main process
Daemonizes if necessary, and then configures some resources, before starting
the reactor
Args:
... | 51,369 |
def SSDR(poses, rest_pose, num_bones, sparseness=4, max_iterations=20):
"""
Computes the Smooth Skinning Decomposition with Rigid bones
inputs: poses |num_poses| x |num_verts| x 3 matrix representing coordinates of vertices of each pose
rest_pose |num_verts| x 3 numpy matrix... | 51,370 |
def string_permutations(test_list, list_to_permutate):
"""Takes a list and a set, and returns a list of all the permutations as strings"""
str_perms = [list(permutation) for permutation in itertools.permutations(list_to_permutate)]
return [str(test_list + str_perm) for str_perm in str_perms] | 51,371 |
def main():
"""plot pwm weights
"""
# args
tfmodisco_file = sys.argv[1]
metacluster_name = sys.argv[2]
pattern_name = sys.argv[3]
plot_prefix = sys.argv[4]
background_freq = 0.25 # keep it simple
# read in tfmodisco file, plot both fwd and reverse
# any trimming??
with ... | 51,372 |
def to_cols(d):
"""Make a square matrix with columns equal to 'd'.
>>> print ker.to_cols(np.array([1,2,3,4]))
[[1 1 1 1]
[2 2 2 2]
[3 3 3 3]
[4 4 4 4]]
"""
return np.tile(d.reshape(len(d), -1), (1, len(d))) | 51,373 |
def captured_sensor(hass):
"""Create a captured today ArloSensor."""
data = _get_named_tuple({"captured_today": [0, 0, 0, 0, 0]})
return _get_sensor(hass, "Captured Today", "captured_today", data) | 51,374 |
def create_icon_axes(fig, ax_position, lw_bars, lw_grid, lw_border, rgrid):
"""
Create a polar axes containing the matplotlib radar plot.
Parameters
----------
fig : matplotlib.figure.Figure
The figure to draw into.
ax_position : (float, float, float, float)
The position of the ... | 51,375 |
def load_product_details():
"""Fetch product details, if we don't already have them."""
from product_details import product_details
if not product_details.last_update:
from django.core.management import call_command
log.info('Product details missing, downloading...')
call_command('... | 51,376 |
def baseline_multiclass(train_data, train_labels, test_data, test_labels, args):
"""Train various classifiers to get a baseline."""
clf, train_accuracy, test_accuracy, train_f1, test_f1, exec_time = [], [], [], [], [], []
clf.append(sklearn.neighbors.KNeighborsClassifier(n_neighbors=15, n_jobs=8))
clf.a... | 51,377 |
def zeno_data(word: str)->[str]:
"""returns all available zeno data"""
result = [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None]
for pos in range(zeno.nrows):
if (word == zeno.cell(pos,0).value):
result[0] = zeno.cell(pos,1).value #sfi
... | 51,378 |
def transfer():
"""Logic for transferring $$"""
data = decode_url(request.get_data().decode())
otheruser = data.get("name", None)
amount = data.get("amount", None)
if not (otheruser and get_user(otheruser)):
return index(f"Other user is not found")
if not request.cookies.get("userID"):
... | 51,379 |
def get_object_detection_by_id(odid: int) -> Optional[ObjectDetection]:
"""
Gets an object detection by id.
:param odid: The object detection's id.
:return: An object detection or None.
"""
try:
return ObjectDetection.objects.get(id=odid)
except ObjectDetection.DoesNotExist:
... | 51,380 |
def activar_entidad(id_entidad):
"""Estable una entidad como inactiva."""
from cacao_accounting.contabilidad.registros.entidad import RegistroEntidad
from cacao_accounting.database import Entidad
REGISTRO = RegistroEntidad()
TRANSACCION = obtener_registro_desde_uuid(tabla=Entidad, uuid=id_entidad)
... | 51,381 |
def trans_expected(clr, chromosomes, chunksize=1000000, use_dask=False):
"""
Aggregate the signal in intrachromosomal blocks.
Can be used as abackground for contact frequencies between chromosomes.
Parameters
----------
clr : cooler.Cooler
Cooler object
chromosomes : list of str
... | 51,382 |
def exp_trans(base=None, **kwargs):
"""
Create a exponential transform class for *base*
This is inverse of the log transform.
Parameters
----------
base : float
Base of the logarithm
kwargs : dict
Keyword arguments passed onto
:func:`trans_new`. Should not include
... | 51,383 |
def broadcastable_to_str(b):
"""Return string representation of broadcastable."""
named_broadcastable = {
(): "scalar",
(False,): "vector",
(False, True): "col",
(True, False): "row",
(False, False): "matrix",
}
if b in named_broadcastable:
bcast = named_b... | 51,384 |
def write_urls(dir_: Path, urls: List[str]) -> None:
"""
Writes the given urls to the urls.txt.
:param dir_:
:param urls:
:return:
"""
url_list = dir_ / 'urls.txt'
url_list.write_text('\n'.join(urls)) | 51,385 |
def avg_weapon_count_character(db):
"""Returns the average number of weapons per character from MongoDB
database.
Args:
db (pymongo.database.Database): MongoDB database
Returns:
(float) Average number of weapons per character
"""
agg_dict = [
{
"$lookup":
... | 51,386 |
def partition(sort_list, low, high):
"""
All the elements smaller than the pivot
will be on the left side of the list
and all the elements on the right side
will be greater than the pivot.
"""
i = (low - 1)
pivot = sort_list[high]
for j in range(low, high):
if sort_list[j] ... | 51,387 |
def main():
"""
A simple test program to check order of accuracy in space for a simple test problem
"""
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 4 # frequency for the test value
# create list o... | 51,388 |
def sanitize_for_serialization(obj: Dict[str, Any]) -> Dict[str, Any]:
"""Return object sanitized for serialization.
May be used with a V1alpha1Workflow to sanitize it
back to the original state (i.e. per manifest).
"""
from argo.workflows.client import ApiClient
cl = ApiClient()
return cl... | 51,389 |
def is_valid_degree_sequence(deg_sequence, method='hh'):
"""Returns True if deg_sequence is a valid degree sequence.
A degree sequence is valid if some graph can realize it.
Parameters
----------
deg_sequence : list
A list of integers where each element specifies the degree of a no... | 51,390 |
def actor_critic(env, estimator_policy, estimator_value, num_episodes, discount_factor=1.0):
"""
Actor Critic Algorithm. Optimizes the policy
function approximator using policy gradient.
Parameters
----------
env: object
OpenAI environment.
estimator_policy: object
Policy Fun... | 51,391 |
def readMatSubfile(main_datafile, filename, header_list, args_dict):
"""
"""
value_separator = ','
comment_types = ['#', '!']
mat_subfile_enum = dataobj.SubfileMatEnum()
path = os.path.join(main_datafile.root, filename)
root = main_datafile.root
header1 = 'None'
header2 = 'None'
... | 51,392 |
def get_vpc_id(ec2, subnet_id: str = None) -> str:
"""Returns VPC ID that should be used for deployment."""
if subnet_id:
vpc_id = Subnet.get_by_id(ec2, subnet_id).vpc_id
else:
default_vpc = Vpc.get_default_vpc(ec2)
if not default_vpc:
raise ValueError('Default VPC not fo... | 51,393 |
def _get_dates(request):
"""Obtain the start and end dates."""
today = date.today()
date_start = request.POST.get('date_start')
if not date_start:
date_start = today - timedelta(days=1)
else:
date_start = datetime.strptime(date_start, '%Y-%m-%d').date()
date_end = request.POST.ge... | 51,394 |
def Test(argv, need_right_bracket):
"""The test/[ builtin.
The only difference between test and [ is that [ needs a matching ].
"""
if need_right_bracket:
if not argv or argv[-1] != ']':
util.error('[: missing closing ]')
return 2
del argv[-1]
w_parser = _StringWordEmitter(argv)
b_pars... | 51,395 |
def cli_argument(context, argument, value):
"""Add command line argument."""
context.arguments.extend(["--" + argument, value]) | 51,396 |
def show_images(images, cols = 1, titles = None):
"""Display a list of images in a single figure with matplotlib.
Parameters
---------
images: List of np.arrays compatible with plt.imshow.
cols (Default = 1): Number of columns in figure (number of rows is
set to np... | 51,397 |
def detect_model(items: numpy.ndarray) -> int:
"""Detects which logistic model an item matrix fits into.
:param items: an item matrix
:return: an int between 1 and 4 denoting the logistic model of the given item matrix
"""
a, b, c, d = _split_params(items)
if any(d != 1):
return 4
... | 51,398 |
def split_value(input_val) -> (typing.Union[dict, list], typing.Union[dict, list]):
"""Split input_val into data for params.yaml and zntrack.json
Parameters
----------
input_val: dict
A dictionary of shape {_type: str, value: any} from ZnJSON
Returns
-------
params_data: dict|list
... | 51,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.