content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import requests
def get_culprit_name(user_id):
"""
Takes the user_id and finds the human readable slack name
"""
url = "https://slack.com/api/users.info"
payload = dict(token=token, user=user_id)
r = requests.post(url, data=payload)
if r.status_code != 200:
print r.status_code,... | c2826423bf1189ac5bdf466237a373e9f883d337 | 76,211 |
def sniff(content):
"""Deduce the format (md|rst|txt) of a given string."""
markdown, restructuredtext = find_typical_markers(content)
markdown_points = sum(markdown.values())
restructuredtext_points = sum(restructuredtext.values())
if markdown_points == restructuredtext_points == 0:
return ... | 20b1effb4c8d1d483a79f23544b41890efeada41 | 76,214 |
def composeFileContent(fileName, dataFolder, defs):
"""获得 dataFolder 目录下的数据
Args:
fileName (String): 数据集和编号
dataFolder (String): 目录
defs (Defs)
Returns:
fileContent (Data): dataFolder目录下的数据
Test1:
fileName: "trn02"
dataFolder: "db/01"
"""
rssPat... | f16a4d7d8e991cd9605f00fb2945d2a02003bd8d | 76,215 |
import typing
def get_related_object_ids(
object_id: int,
include_previous_objects: bool,
include_measurements: bool,
include_samples: bool,
user_id: typing.Optional[int] = None
) -> typing.Tuple[typing.List[int], typing.List[int], typing.List[int]]:
"""
Get IDs of obje... | 9dcfe79c031ef9086dcb19ce970a48d3c80245b7 | 76,216 |
from typing import OrderedDict
import torch
def gradient_update_parameters(model,
loss,
params=None,
step_size=0.5,
first_order=False,
Gproj=True):
"""Update of the meta-parameters with one step of gradient descent on the
loss fu... | d76e02014f0cf26922b796b72757bc6829cc3f75 | 76,217 |
import time
def get_local_stamp():
"""产生毫秒级时间戳-本地时间
:return:
Examples:
| ${time_stamp}= | Get Utc Stamp |
=>
| ${time_stamp} = 1535596350000
"""
return str(int(round(time.time()) * 1000)) | 68fc419d79158286e82015374f1c7d1f2c102f91 | 76,218 |
def svn_wc_walk_entries2(*args):
"""
svn_wc_walk_entries2(char path, svn_wc_adm_access_t adm_access, svn_wc_entry_callbacks_t walk_callbacks,
void walk_baton,
svn_boolean_t show_hidden, svn_cancel_func_t cancel_func,
apr_pool_t pool) -> svn_error_t
"""
return apply(_wc.svn_wc_walk... | 30115bb482016d6ca6bbdca8da12d70c141c5707 | 76,220 |
def conv_vec_test(x_init, x_new, be):
""" A simple convergence test using vector values"""
convergence = be.empty((1, 1))
convergence[:] = be.sqrt(x_init * x_init)
# Avoids numerical error:
convergence[:] = max(1, convergence.get())
convergence[:] = be.absolute(x_new - x_init) / convergence
... | 4c5c91b317d2dbc0eeffcfa26096906fae6cc77e | 76,221 |
def wrap_module(statement, wool=None):
"""
Wrap the module statement for akka code generation.
:param statement: the module statement
:return: the wrapped module representation
"""
if wool is None:
wool = alpakka.WOOLS.default
return wool['module'](statement) | 4e0046dd130dc43347703005503d6fde6f787796 | 76,223 |
import json
def userregister(request):
"""
A registration form endpoint for registering and logging in.
This view will permit a user to register if their username is unique,
their password is not empty, and an email address is provided.
This view returns JSON, with a 'success' property if registr... | 6bb1826f82aa63f9a5270e6e230e9c5b9294a948 | 76,224 |
def dashboard_view(request):
""" render the admin dash if the user is logged in """
if 'Administrator' in request.user.groups.values_list('name', flat=True):
data = {}
data['schools'] = db_views.get_all_schools()
users = User.objects.filter(is_active=False)
userRequests = []
... | 79420190576bed466650629fb68b6995457ba446 | 76,225 |
from datetime import datetime
import pytz
def calibrate_day_of_week(timestamp, day_of_week):
"""
Adjusts the passed datetime to reflect the desired day of week. The
calibration chooses the requested day of week that is present in the
**week of the original datetime timestamp**. In the case of a Monday... | d2ffe75b9888e4115e5c2ceadca0afc284c6d8f5 | 76,227 |
def create_wordcloud(data, cmap=None, savefig=False, name=None, **kwargs):
""" Creates a wordcloud based on a text document
Parameters:
-----------
data : list, pandas series or dictionary
List of words, pandas series of messages
or dictionary that includes words with
frequ... | 078731c3a4a4f83de311e0ce2dec40edc28b1cf6 | 76,228 |
def _next_node_end(nodes_str: str) -> int:
"""
From a comma-sepparated list of newick-formatted nodes, return the final
position of the first one.
Examples:
'(A:1,(C[x],D))name:1.[c], (X,Y),,[xxx]' -> 23
'(X,Y),,[xxx]' -> 5
'[xxx]' -> 4
"""
nodes_str = nodes_str.strip(... | d2c14d71f428c86e941652abfc3d8d935a0a288f | 76,229 |
import warnings
def are_basal_rates_valid(start_times, rates, minutes_active):
""" Checks that scheduled basal rates are reasonable """
if any(value < 0 for value in rates):
warnings.warn(
"Error: data contains negative scheduled basal rates; stopping run"
)
return False
... | 5bc7aa35383dad8cdf98fb637dcb456a6421bb1e | 76,231 |
from typing import List
def conditional_gravity(is_half: bool, moment: str) -> List:
"""
:param is_half:
:param moment: str representation of moment
:return: empty list if its half court, else list of gravity values in list
"""
if is_half:
return calculate_gravity(flip_court(string2ar... | 3bef8b7e093baadf74b3bc9db2bf057bc813c995 | 76,232 |
def succ(B, T):
"""Return the successor of the tuple T over the base represented by B.
Returns None if T is the last tuple in the ordering.
See the library description for how base representations work."""
Tnew = T[:]
for i in range(len(B)):
# Increase the entry in position len(B)-i-1 if po... | 4cd072b762551887ee7f4ad64b0f7b574bd58eea | 76,233 |
def nms(bboxs, scores, thresh):
"""
The box should be [x1,y1,x2,y2]
:param bboxs: multiple bounding boxes, Shape: [num_boxes,4]
:param scores: The score for the corresponding box
:return: keep inds
"""
if len(bboxs) == 0:
return []
order = scores.argsort()[::-1]
keep = []
... | 8853f88c8435c6bc07642ed355d7a6d79a149608 | 76,234 |
def return_model_and_parameters():
"""Create and parameterize a dispatch model using default values"""
dm = model_control.DispatchModel()
control_parameters = {
"rolling_horizon": False,
"aggregate_input": False,
"countries": ['AT', 'BE', 'CH', 'CZ', 'DE', 'DK1', 'DK2', 'FR',
... | fa0a779b0fae2c0cab4635365dd5ee7c8e3cbc9e | 76,235 |
def plot_bipolar_switching_behaviour(
memristor_model,
voltage_signal_amplitude,
voltage_signal_frequency,
log_scale=True,
return_result=False,
):
"""Method to plot the DC bipolar switching behaviour of a given device.
Parameters
----------
memristor_model : memtorch.bh.memristor.Me... | 92f100a5f4497f9abe18f5bb82346ebf26154d8e | 76,236 |
def main():
"""
Request to API and insert data to DB
"""
#read_config
config = utils.read_config()
lineups_config = config['lineups']
# connect to db
db_url = config['db_url']
conn = utils.create_db_connection(db_url)
def get_lineup(fixture_id):
# get api response
... | 39e4d56b9cf5b562e4bb76e724d08e4368204268 | 76,237 |
def fit_model(ts, sc=None):
"""
Fits a GARCH(1, 1) model to the given time series.
Parameters
----------
ts:
the time series to which we want to fit a GARCH model as a Numpy array
Returns a GARCH model
"""
assert sc != None, "Missing SparkContext"
jvm = sc.... | a0cd63bc2b9be49a479d4bdc3b13a8bc39dfde5c | 76,238 |
import functools
def get_preprocess_fn(is_training, image_size=224):
"""Get function that accepts an image and returns a preprocessed image."""
# Disable test cropping for small images (e.g. CIFAR)
if image_size <= 32:
test_crop = False
else:
test_crop = True
return functools.partial(
data_uti... | 7baba7736fa73ed36334f78a6eb556e72bf2d28d | 76,239 |
from typing import Any
def boosting_mutation(pipeline: Pipeline, requirements, params, **kwargs) -> Any:
""" This type of mutation adds the additional 'boosting' cascade to the existing pipeline """
task_type = params.advisor.task.task_type
decompose_operations, _ = OperationTypesRepository('data_operati... | 210e08bf6d5b421df8a7c58e180b1327c67be824 | 76,240 |
def _validate_argument(arg, argname, valid_args):
"""
Validate interpolation method for quantile function.
"""
if arg not in valid_args:
msg = 'Invalid value for {} ({}). Must be on of {}.'
raise ValueError(msg.format(argname, arg, valid_args))
return arg | ef0f2a56b2253624f5f00b7d3183db3ba12bcece | 76,241 |
def get_language_distribution(client, db_name, lang_list):
"""Returns the distribution of tweets matching either
english, undefined or spanish.
Args:
client (pymongo.MongoClient): Connection object for Mongo DB_URL.
db_name (str): Name of database to query.
lang_list (li... | 1ebd70f4b43387da37038697891e1156f8dc0866 | 76,243 |
def channelwise_locally_connected2d(input, W, flip_filters=True):
"""
channelwise 2D convolution with unshared weights, no stride,
'same' padding, no dilation and no bias
"""
num_batch, input_channels, input_rows, input_cols = input.shape
num_filters, filter_rows, filter_cols, output_rows, outpu... | 430e33be5e58ac7038240afac5c0b365301aaa5f | 76,244 |
def pad_function(field, pad_to, keep_null):
"""Pads field to specified length."""
if isnull(field) or not str(field).strip():
if keep_null:
return None
else:
field = ''
return str(field).strip().zfill(pad_to) | 4f9bc4e1feb5c17e49f6ed66ce9b9952402a854b | 76,245 |
from typing import Dict
from typing import List
def load_revenue_table_from_db(session: Session) -> Dict[str, List[RevenueRate]]:
"""
Load Revenue Rates from database
:param session: SQLAlchemy database connection session
:return: Dict that maps level of service to a list of revenue rates
"""
... | d86aa1ef8101017a97f1594808a64b817b84ece5 | 76,246 |
def get_ymd(soup):
"""
Get the year, month and day from child tags
"""
day = extract_node_text(soup, "day")
month = extract_node_text(soup, "month")
year = extract_node_text(soup, "year")
return (day, month, year) | b56e4bc7ffffffe0de9d1ba6a6b09ea9259d5596 | 76,247 |
def reshape_FstatAtomsVector(atomsVector):
"""
Make a dictionary of ndarrays out of a atoms "vector" structure.
The input is a "vector"-like structure with times as the higher hierarchical
level and a set of "atoms" quantities defined at each timestamp.
The output is a dictionary with an entry for ... | ebd32adf3d30cc52097ab771eff8840dd0bf6012 | 76,248 |
import torch
def toy6():
""" 1D regression. Outputs are intentionally noisy. """
def f(x):
return 5 * np.cos(x / 1.7)
X_train = torch.tensor([-2.7, -2.3, -2, 2, 2.3, 2.7]).unsqueeze(1)
Y_train = f(X_train) + torch.tensor([0.4, 0.2, 0.7, -2.5, 0.6, 2.1]).unsqueeze(1)
X_train_min = [-3.0]
X_train_max = [3.... | 1d2527626954cd19edafb159829b70028ede0b92 | 76,249 |
def find_approximate_rt(peaklist, rt):
"""
Find a peak with the closest retention time if it's within a tolerance.
:param peaklist: list, of Peaks
:param rt: float, retention time to match to
:return: Peak, the peak matching the retention time within the tolerance, if any
"""
peaklist = [pea... | 4cc7e933b02892fd41ff250764b67e7b2a75ff6e | 76,250 |
def vzerog_vector(in21):
"""vzerog_vector(ConstSpiceDouble * in21)"""
return _cspyce0.vzerog_vector(in21) | 928d5ea12ed11d98f9ce7b7395cd370f5661daf5 | 76,251 |
import re
def dataset_labels(dataset):
"""
Returns a sorted list of label name
"""
labels = set([x[0] for x in dataset])
if all(re.match("^[0-9]+$", label) for label in labels):
# if all of the labels are integers, sort numerically
# maybe not super important, but it would be nicer... | 5b97eab5447bbf1c09af3887197077db99638ab6 | 76,252 |
def find_image_center(xsize,ysize):
"""
Find the pixel coordinates of the image center
"""
if xsize % 2 == 0:
cen_x = (xsize+1)/2.0
else:
cen_x = xsize/2.0
if ysize % 2 == 0:
cen_y = (ysize+1)/2.0
else:
cen_y = ysize/2.0
return (cen_x, cen_y) | 95b70c27352a514433be28fdd2ee1a42334cd183 | 76,253 |
import pdb
import tqdm
import torch
def do_pass_chunk_into_sentences(
data,
token_to_id,
char_to_id,
tag_to_id,
id_to_tag,
expressions,
train,
write_preds,
epoch,
val_or_test="val",
):
"""
Approximating document-level prediction by doing sentence-level prediction
in... | 13e8503dad77a9b4c35a34298386434f124b2f97 | 76,254 |
import yaml
def process_yaml(yaml_list):
""" . """
yaml_dict = dict()
for yaml_item in reversed(yaml_list):
yaml_dict.update(yaml.load(yaml_item))
return yaml_dict | ac05ed3044ec80f940f569a495f7b6be8681432e | 76,255 |
def typescript_proto_library_aspect_(target, ctx):
"""
A bazel aspect that is applied on every proto_library rule on the transitive set of dependencies
of a typescript_proto_library rule.
Handles running protoc to produce the generated JS and TS files.
"""
js_protoc_outputs = []
dts_outputs... | e5d750ec5aa79b1b56faeaf5502df99cf6ee8157 | 76,256 |
import socket
def in6_ptop(str):
"""
Normalizes IPv6 addresses provided in printable format, returning the
same address in printable format. (2001:0db8:0:0::1 -> 2001:db8::1)
"""
return inet_ntop(socket.AF_INET6, inet_pton(socket.AF_INET6, str)) | 96292ce102fd0783aa45997ae682ee2987946607 | 76,257 |
def process_quotes(s: str, **kwargs) -> str:
"""
Process quotes.
:param s: Latex string code
:return: String with "quotes"
"""
while True:
k = find_str(s, ['\\quotes{', '\\doublequotes{', '\\enquote{'])
if k == -1:
if kwargs.get('pb'): # Update progressbar
... | e906c4989fa4dc2e55c6b554e2e931f5fd09bde4 | 76,258 |
def resolve_addresses(user, useralias, to, cc, bcc):
""" Handle the targets addresses, adding aliases when defined """
addresses = {"recipients": []}
if to is not None:
make_addr_alias_target(to, addresses, "To")
elif cc is not None and bcc is not None:
make_addr_alias_target([user, user... | a0f2161b7a94d3a6ebfb38b755af307c957446e1 | 76,260 |
def variance_ub(data):
"""unbiased variance (divide by len-1, not just len)"""
length = len(data)
if length < 2: return 0.0
meanval = loc_sum(data)/float(length)
# compute standard deviation
ssq = 0.0
for val in data: ssq += val*val
val = (ssq - length*meanval*meanval)/(length-1.0)
... | 7094abc4a2cf13694a2794a2362c23f0cd8f154f | 76,261 |
def retrieve(model, primary_keys):
"""Try to retrieve an object from the repossitory."""
return model.repository.get(**primary_keys) | 114bbb5c06cc9e92c064652611a3b5e48b5b933b | 76,262 |
def part23_reg_matrix_tau(ind_mat, ut):
"""Partial temporal Laplacian regularization matrix following
Appendix B in [1].
References
----------
.. [1] Fick, Rutger HJ, et al. "Non-Parametric GraphNet-Regularized
Representation of dMRI in Space and Time", Medical Image Analysis,
2017.... | 8de2f21048f904c4a94798c92db8ae2d19c4f034 | 76,264 |
def draw_hangman(x):
"""
Creates a simple ASCII art of a hangman step by step from 0 to 10,
then returns it as a string.
:param x: current step
:type x: int
:return: simple ASCII art
:rtype: str
"""
if x == 0:
img = "\n"
img += " " + "—" * 15 + "\n"
img += " ... | bf15eba834049131ae81474d3a106beb400f6bcc | 76,265 |
def retrieve_content_type_header(request_property):
"""Retrieve Content-Type header from incoming request.
This function handles multiple spellings of Content-Type based on the presence of
the dash and initial capitalization in each respective word.
Args:
request_property (dict): incoming requ... | a501de5c2117c48eb39f9004d51876d75ad4386a | 76,267 |
import time
def helm_josep(Ybus, Yseries, V0, S0, Ysh0, pq, pv, sl, pqpv, tolerance=1e-6, max_coeff=30, use_pade=True,
verbose=False):
"""
Holomorphic Embedding LoadFlow Method as formulated by Josep Fanals Batllori in 2020
(----Without Slack Embedding and other tweaks----)
:... | b1b8fe344820a42bdf1294e497ab2f5809c391b2 | 76,268 |
def smoothing_function(x: float, a: float, b: float) -> float:
"""
Sigmoid smoothing function
https://en.wikipedia.org/wiki/Sigmoid_function
:param x: independent variable
:param a: fitting parameter 1
:param b: fitting parameter 2
:return: float between 0-1
"""
return 1 / (1 + ex... | efbd431752bc1fc096d24cb9b1a2200ec5da8a1b | 76,269 |
def FiLM_complex_layer():
"""multiply tensor to tensor"""
def func(args):
x, gamma, beta = args
shape = list(x.shape)
# avoid tile with the num of batch -> same for both tensors
shape[0] = 1
# avoid tile with the num of channels -> same for both tensors
shape[-1]... | 7744b91d7686777d950ac5b6f21475d7f3f35f99 | 76,270 |
import pickle
def solve(board):
"""
Tries to solve the sudoku by inserting values into free positions.
If no valid value can be found, backtrack into the stack's last value
by popping the stack.
By using a stack, the working of a recursive function is mimicked.
Parameters:
board (list): T... | ab26dbf28d72a729cd41ea9571bdf4eb500100ba | 76,271 |
from datetime import datetime
def n_days_ahead(start_datetime, days):
"""
Return a datetime that is start_datetime plus days into the future
"""
delta = datetime.timedelta(days = days)
return start_datetime + delta | 28b4436cd7494c3f756741bbc310e2e31b37ebf9 | 76,272 |
def get_data(dataset, num_points, dim, noise_std):
"""Main data-loading abstraction"""
if dataset.lower() == 'simple':
return generate_linear_data(num_points, dim, noise_std)
elif dataset.lower() == 'mnist':
return get_mnist_data(num_points, dim, noise_std)
elif dataset.lower() in ('nonc... | 039ad477ab3b5361e86eed37fff24c789f397098 | 76,273 |
from aiida.orm import load_node
from aiida.orm.nodes.data.folder import FolderData
import logging
def test_run(thirdorder_reap_code):
"""Run a calculation on the localhost computer.
Uses test helpers to create AiiDA Code on the fly.
"""
if not thirdorder_reap_code:
# get code
computer... | 0b1f467dcc1978e3339a3edd078edfc636793192 | 76,274 |
from typing import Tuple
def precession_angles(julian: np.ndarray) -> Tuple:
"""Return precession angles.
Parameters
----------
julian : np.ndarray
1-D array containing Julian times in the J2000 epoch.
Returns
-------
Tuple
Tuple containing precession angles in decimal ar... | 195f75e4e6ccbb34803f4f95442a3c1b79add174 | 76,276 |
import copy
def agent_remove_liq(params, substep, state_history, prev_state, policy_input):
"""
This function updates agent states when liquidity is removed in one asset.
If symmetric liquidity add is enabled additional calculations are made.
"""
asset_id = policy_input['asset_id'] # defines asse... | d83177a5d70910effb20af173c4961f4dc796fbc | 76,277 |
import itertools
def get_rot(slab):
"""
Gets the transformation to rotate the z axis into the miller index
"""
new_z = get_mi_vec(slab.miller_index)
a, b, c = slab.lattice.matrix
new_x = a / np.linalg.norm(a)
new_y = np.cross(new_z, new_x)
x, y, z = np.eye(3)
rot_matrix = np.array(... | 5b7dd7e0f8009dc24646b4bf7e43574d11f6214b | 76,278 |
def health_check():
"""
Sends "OK" on "/" endpoint as a Health check.
"""
return "OK" | 75882214faea621a5b066826b19be57a65617129 | 76,279 |
def is_dag(W):
"""Checks if the given matrix W encodes a DAG.
Args:
W: an adjacency matrix
Returns:
True if W encodes a DAG and false otherwise
"""
G = ig.Graph.Weighted_Adjacency(W.tolist())
return G.is_dag() | ced9efd9044f5b10c98a4a8ea6b5ff1bebc860f5 | 76,281 |
import socket
def get_ip():
"""This method returns the "primary" IP on the local box
(the one with a default route).
- Does NOT need routable net access or any connection at all.
- Works even if all interfaces are unplugged from the network.
- Does NOT need or even try to get anywhere else.
... | 3cc712baaa7006e9ebd17af4069e3f6a08e0518f | 76,283 |
def obj_is_a_dlst(obj):
"""
Indicates whether the given object is a dictionary, a list, a set or a
tuple.
Args:
obj: any object
Returns:
bool: True if the object's type is dict, list, set or tuple, False
otherwise.
"""
return isinstance(obj, _DLST) | ab7ac0fba701c4be6d4827c10e7ee1de509d5be3 | 76,284 |
def absent(name):
"""
Jenkins Throttle Category absence state method
:param name: category name
:returns: salt-specified state dict
"""
return _plugin_call(name, remove_throttle_groovy,
["REMOVED", "NOT PRESENT"],
{"categoryName": name}) | 1aa74e3bf7bca78eb9e5a5b81eb72e095739ac8f | 76,285 |
def parse_snap(sales):
"""Parses the SNAP values such that each store uses he SNAP value
relevant for the store. Removes the redundant SNAP columns
afterwards.
Args:
sales (pd.DataFrame): Dataframe including the sales.
Returns:
pd.DataFrame: Sales data with new SNAP value column.
... | 2a1fd80542d9191aba67db33b29b6c900468c074 | 76,286 |
from typing import List
from typing import Dict
def get_comp_links_by_grouping(
graph_traversal: GraphTraversalSource, grouping: str
) -> List[Dict[str, str]]:
""" Gets a list of component connection dictionaries. These describe all
source->stream->destination connections with the specified gr... | d22d16eb8e8e10307600ac4cb6a5426e1a664831 | 76,287 |
from re import X
def michell_centered_both(width=32, height=32, density=0.5, position=0.05):
"""A single force down at the center, with support from the side."""
# https://en.wikipedia.org/wiki/Michell_structures#Examples
normals = np.zeros((width + 1, height + 1, 2))
normals[round(position*width), round(heig... | 6bf0fa0df793a063fcb245b9aea1acec5f179fe7 | 76,289 |
def sizeof_fmt(num):
"""Human friendly file size"""
if num > 1:
exponent = min(int(log(num, 1024)), len(unit_list) - 1)
quotient = float(num) / 1024**exponent
unit, num_decimals = unit_list[exponent]
format_string = '{:>5.%sf} {}' % (num_decimals)
return format_string.for... | c5c8cde94f7b5c50681af279a597249b85dd9e87 | 76,290 |
def int_to_letter(i: int) -> str:
"""Converts an integer in range [0, 25] into a latter from 'A' to 'Z'.
Behavior is unspecified for other inputs!
"""
return chr(i + ord("A")) | 593896ad2b9ca3cfa592b87d6a04f7ffaaf7dd21 | 76,291 |
import urllib3
def getHttpStatus(proto,dubs,domain):
""" Gets the status code for the domain sent in
proto: http or https
domain: domain to resolve
"""
http = urllib3.PoolManager(cert_reqs='CERT_NONE')
status = 'N/A'
if dubs:
url = "{}://www.{}".format(proto, domain)
el... | 7553029d7f53b165a67fd809650335eee01970ac | 76,292 |
def flip_order(x):
"""
For e.g. reaction energies, the order of the reaction is arbitrary.
This tries to flip the order of the reactions one by one and selects
the order that maximises the likelihood.
"""
def get_nll(x):
"""
Returns the negative log-likelihood
"""
... | d87fdd4569c58738c6808f34b83942d929aa04e2 | 76,293 |
import tqdm
def simulate(agent, env, start=None, episodes=1_000_000):
"""
Simulate an agent in an environment over a number of episodes.
Args:
agent (object): an agent with an act(obs, reward, done) method.
env (object): an OpenAI Gym environment.
episodes (int): the number of epi... | d474101781b2283dd158920956633bcc47ac7e20 | 76,294 |
def normals(k_elem):
"""
OCTAVE CHECKED
Compute outward pointing normals at element faces
>>> normals(4)
array([[-1., -1., -1., -1.],
[ 1., 1., 1., 1.]])
"""
# K is the number of elements, derived from the grid info
# n_faces and n_fp are defined as global variables
n_f... | 856af217578f8292694f63402765a962b13a4bb8 | 76,296 |
import urllib
def read_s3_object(bucket, key):
"""
Method to read data from and S3 bucket.
.. note:: This method is used to read bootstrap
information, in order to license and
configure the firewall.
:param bucket:
:param key:
:return:
"""
# G... | 3290ab1efe285a9e44ec50a2f1d8bc419a701252 | 76,297 |
def _safe_div(a, b):
"""Divides two numbers, returns 0 if denominator is (close to) 0."""
return tf.where(tf.less(tf.abs(b), 1e-10), 0.0, a / b) | 227596ab2539793bb4b3313d7578c5eccf25f76d | 76,299 |
def build_text_row(node):
"""Build a row for translation tables with text."""
trans2word_data = get_word(node)
row_data = {'bhsa_node': node}
for transl, word_data in trans2word_data:
ref_tuple = tuple(word_data.get('eng_ref', ''))
row_data[f'{transl}'] = word_data.get('words', '')
... | 5fecbd51ad506957987e1043aaf482e9da65c9b7 | 76,300 |
import io
import warnings
def load_imgs_from_mibitiff(data_dir, mibitiff_files=None, channels=None, delimiter=None,
dtype='int16'):
"""Load images from a series of MIBItiff files.
This function takes a set of MIBItiff files and load the images into an xarray. The type used
to ... | 627980b645ed05a31b950b7f06102220cf68fd55 | 76,301 |
def _serialize_check_stats(check_stats, pandas_dtype=None):
"""Serialize check statistics into json/yaml-compatible format."""
def handle_stat_dtype(stat):
if pandas_dtype == PandasDtype.DateTime:
return stat.strftime(DATETIME_FORMAT)
elif pandas_dtype == PandasDtype.Timedelta:
... | 76935cfc9359697397a2d0f3717af6f00c5135b4 | 76,302 |
def concat_annotated(datadir):
"""
Concatenate all "annotated_df_*_parsed*.pkl" files in `datadir`.
The pkl's of the core team should end with "dedup.pkl", i.e. they should be deduplicated by the `parse_annotations.py` script.
The ze pkl's need not be deduplicated, as only notes that are not in the anno... | 4ac80d663f8b5eca244de001e3f6622bde4f7b4f | 76,303 |
def undistort_image(imagepath, calib_file, visulization_flag):
""" undistort the image and visualization
:param imagepath: image path
:param calib_file: includes calibration matrix and distortion coefficients
:param visulization_flag: flag to plot the image
:return: none
"""
mtx, dist = loa... | 9ee86589fb322d2d82fa7d3a32b6668ca2c6d929 | 76,304 |
def delete_participants():
"""
Deletes all participants, startlists and results. Categories stay.
Function is called by a javascript/jquery
"""
ParticipantModel.delete_all_rows()
StartlistModel.delete_all_rows()
StartlistNameModel.delete_all_rows()
message = "Deleted all participants, s... | 08bb207ec3fbf2cbafdf69cf70f498b1c2d796f1 | 76,305 |
def decode_hmm(length_sequence, centroids, appliance_list, states):
"""
Decodes the HMM state sequence
"""
power_states_dict = {}
hmm_states = {}
hmm_power = {}
total_num_combinations = 1
for appliance in appliance_list:
total_num_combinations *= len(centroids[appliance])
... | 75b4db1e9edf0de12adf4d28c105f63c5aa956cd | 76,306 |
def parse_rule(spec):
"""
Parse a rule together
:param spec
:return rule
"""
rule = netfilter.rule.Rule()
bits = split_words(spec)
pos = 0
while pos < len(bits):
# in iptables 1.4.3, negation moved before the match option
if bits[pos] == '!' and pos < len(bits) - 1:
... | 988d66f40bb941c147d4b2f8389ad43b403407e2 | 76,307 |
from typing import List
def create_images(length: int = 10) -> List[Image]:
"""
Generate list of dummy images
:param length: length of list
:return: list of dummy images
"""
return create_resource(resource_cls=Image, length=length) | c39088d385977191ccff613b9021fd49ed2b6d57 | 76,308 |
def display(args):
"""
Input: {
(host) - Internal web server host
(port) - Internal web server port
(wfe_host) - External web server host
(wfe_port) - External web server port
(extra_url) - extra URL
}
... | db3e869c5d20306c1aa1571222de21bea1128904 | 76,309 |
def _preprocess_data(train,validation, test, max_features=DEFAULT_MAX_FEATURES, max_len=DEFAULT_MAX_LENGTH):
"""
Prepare data sequentially to feed it to the neural network
:param train:
train data
:param test:
test data
:param max_features:
maximum number that sentence may co... | aaa53b86c92db54cee377a3ece945f25329c937f | 76,310 |
import random
import logging
def build_non_encapsulated_ip_packet(
rand_selected_interface,
ptfadapter,
rand_selected_dut,
tunnel_traffic_monitor
):
"""
Build the regular (non encapsulated) packet to be sent from T1 to ToR.
"""
tor = rand_selected_dut
_, server_ips = rand_select... | 7024850d45689dff086c025262a2a93699690866 | 76,311 |
def compute_cost(Z3, Y):
"""
Calcula la función de costo
Argumentos:
Z3 -- Salida del forward propagation (Salida de la última unidad LINEAR), de tamaño (6, Número de ejemplos)
Y -- placeholders con el vector de etiquetas "true", del mismo tamaño que Z3
Returns:
cost - Tensor de la fun... | 4215c4d0b8f062b9de6cb683717a95cbe2afa357 | 76,312 |
import ast
def convert_ast(tree, to_struct):
"""Convert from native nodes to Struct nodes if to_struct is
True; otherwise convert in the opposite direction.
"""
base = ast.AST if to_struct else AST
mapping = py_nodes if to_struct else native_nodes
seqtype = tuple if to_struct else list
... | 67dd217a25192203d6e2fb4bd80060c09d3647bc | 76,313 |
from typing import Dict
def set_entity_attribute(metric_uuid: MetricId, source_uuid: SourceId, entity_key: str, attribute: str,
database: Database) -> Dict:
"""Set an entity attribute."""
data_model = latest_datamodel(database)
reports = latest_reports(database)
data = SourceD... | b7afff2f0c70e8bedf927f0fd5a074f43a6dce38 | 76,314 |
def Conv(filters, kernel_size, input_shape, strides = (1, 1), padding = "SAME", activation = "none", name = "conv"):
"""ConvLayer
Parameters
----------
filters : {int-like, scalar} the number of filters
kernel_size : {tuple-like, vector_2} of shape (filter_col, filter_row), the size of sin... | 8c478adba6e62f234fce646ce02d3d840436b079 | 76,315 |
def explainexit(code):
"""return a message describing a subprocess status
(codes from kill are negative - not os.system/wait encoding)"""
if code >= 0:
return _("exited with status %d") % code
return _("killed by signal %d") % -code | 834fdbf40b9a3b9447f8589e2065e80d3085569b | 76,316 |
def seq_to_SX_matrix(seq):
"""
In many cases this is equivalent to cs.vertcat.
"""
n = len(seq)
# leading element:
e0 = SX(seq[0])
if e0.shape == (1, 1):
# we have a sequence of scalars and create a column vector
res = SX(n, 1)
for i, elt in enumerate(seq):
... | 741bab1c8fb9a91799a849695edd560d0109ea00 | 76,317 |
def api_stop_ap():
""" Generate an access point """
return jsonify(network.stop_hostapd()) | 8bb66eb3ce523dd1d81e1e20c68e91698a0a12e3 | 76,318 |
def app(fun, arg):
"""Apply function to argument and linearly reduce."""
if fun is TOP:
return fun
elif fun is BOT:
return fun
elif is_nvar(fun):
return APP(fun, arg)
elif is_ivar(fun):
return APP(fun, arg)
elif is_app(fun):
# Try to reduce strict binary f... | 966427c610c323f1b97961227435286e0692c9d3 | 76,319 |
def sort_by_abundance_usearch61(seq_path,
output_dir='.',
rev=False,
minlen=64,
remove_usearch_logs=False,
HALT_EXEC=False,
outp... | 12403c2cdaee2d647f8b16f73f1f9acefc1df555 | 76,320 |
def download():
"""Export a csv file of user's data"""
transactions = Transactions.query.filter_by(user_id=current_user.id).order_by(Transactions.date)
budgets = Budget.query.filter_by(user_id=current_user.id).order_by(Budget.id)
transactions_headers = [
'date',
'type',
'category... | f20d55e23268a3717c81e6d8ca3d671bf8443bbb | 76,321 |
import requests
import json
import time
def query_osm_data(query, fpath):
"""
Queries Overpass API for *query*.
Args:
query (str): The query to be passed to API
fpath (str): File path to write the API response
Returns:
None
"""
status = 0
try:
overpass_url... | f8bb5fb2867d487200276a99528f7d233d012c2e | 76,322 |
def _get_weighted_exceedance1d(x,numbins=10, defaultreallimits=None, weights=None):
"""
return emperical cdf from dataset x
Parameters:
x: 1d array of shape(n,)
prob: exceedance probability
return_index: boolean [default False], If true, will return the indices of sorted data to get ... | 26a2e796ca5c62de479f7aa7c2eb3e62c3211866 | 76,323 |
from typing import List
def sanitize_args(cmd: List[str]) -> List[str]:
""" Filter the command so that it no longer contains passwords
"""
sanitized = []
for idx, fieldname in enumerate(cmd):
def _is_password(cmdstr):
return 'wifi-sec.psk' in cmdstr\
or 'password' i... | bca8b5820198bf682de3c08bcbfd45ba61d961f4 | 76,324 |
import logging
def get_foods_for_day(session, date):
"""Gets the ww foods logged at the provided date
Args:
session (requests.Session) : An authenticated ww session
date (datetime.datetime): Date to retrieve
Returns:
(dict) ww food objects
"""
logging.info("Getting food fo... | 4fa9eea872d46033d1674f4c3b3246983b3dc93c | 76,325 |
import logging
def auto_start(config):
""" Connect to Moodle and create the course using command-line/config"""
logging.info("Logging into Moodle")
call = config.login_callable()
moodle = call()
moodle.cache = config.cache_location
course = moodle.course(config.course)
return moodle, cours... | b464450a0e580318ec5a1deae0e42df2fee613fa | 76,326 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.