content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def addsParallelTrack(Area, initPoint, alt):
"""
Adds mission to perform Parallel Track across specified area.
"""
dFSA = 30 # Functional Search Area (m)
cmds = vehicle.commands
print ( " Clear any existing commands")
cmds.clear()
print ( " Define/add new commands.")
# Add... | 5,340,300 |
def longest_substring_using_lists(s: str) -> int:
"""
find the longest substring without repeating characters
644 ms 14.3 MB
>>> longest_substring_using_lists("abac")
3
>>> longest_substring_using_lists("abcabcbb")
3
>>> longest_substring_using_lists("bbbbb")
1
>>> longest_subst... | 5,340,301 |
def tensorflow_custom_preprocessing_example():
"""Example usage to get face embeddings from cropped image of human face"""
import numpy as np
from tensorflow.keras.preprocessing import image
image_preprocessor = create_preprocessing_model()
embeddings_model = VGGFace(model="senet50", pooling="avg",... | 5,340,302 |
def getuserobj(user_id=None):
"""
登录查询用户是否存在的专用接口函数
:param user_id: 用户id(username)
:return: if exit: return 用户对象
else return None
"""
dbobj = connectMysql.connectMysql()
if user_id is '' or user_id is None:
dbobj.close_db()
return None
else:
userdata ... | 5,340,303 |
def _parse_track_df(df: pd.DataFrame, track_id: int, track_name: str, track_comment: str,
data_year: int) -> dict:
"""
parses track data
:param df: data representing a track
:param track_id: track id
:param track_name: track name
:param track_comment: track comment
:param... | 5,340,304 |
def parse_tileset(
tileset: TileSet
) -> Tuple[Mapping[Axes, int], TileCollectionData]:
"""
Parse a :py:class:`slicedimage.TileSet` for formatting into an
:py:class:`starfish.imagestack.ImageStack`.
Parameters:
-----------
tileset : TileSet
The tileset to parse.
Returns:
... | 5,340,305 |
def travis():
"""
Add a .travis.yml file to run dialog flow tests
"""
cfg.travis() | 5,340,306 |
def test_walk(setup_groups):
"""Test the ``GroupPathX.walk()`` function."""
group_path = GroupPathX()
assert [c.path for c in sorted(group_path.walk())] == [
"a",
"a/b",
"a/c",
"a/c/d",
"a/c/e",
"a/c/e/g",
"a/f",
] | 5,340,307 |
def pad_sents(sents, pad_token):
""" Pad list of sentences(SMILES) according to the longest sentence in the batch.
@param sents (list[list[str]]): list of SMILES, where each sentence
is represented as a list of tokens
@param pad_token (str): padding token
@returns sen... | 5,340,308 |
def bicubic_interpolation_filter(sr):
"""Creates a bicubic interpolation filter."""
return _interpolation_filter(sr, cv2.INTER_CUBIC) | 5,340,309 |
def prepareTrainingData(imgs, pathOut, psfStats, imgInBitDepth, samplesPerImg, cameraResolution):
"""
Prepare raw images to train the CNN for MTF estimation.
:param imgs: Array of raw 1-channel images.
:param pathOut: Path to the destination TFRecord file.
:param psfStats: Real PSF images with corre... | 5,340,310 |
def is_receive_waiting():
"""Check to see if a payload is waiting in the receive buffer"""
#extern RADIO_RESULT radio_is_receive_waiting(void);
res = radio_is_receive_waiting_fn()
# this is RADIO_RESULT_OK_TRUE or RADIO_RESULT_OK_FALSE
# so it is safe to evaluate it as a boolean number.
return (... | 5,340,311 |
def wait(game):
"""Do nothing."""
outputter.display_game_text('You doze off for a while. Nothing happens.') | 5,340,312 |
def test_cli():
"""Test the main CLI command."""
runner = CliRunner()
result = runner.invoke(cli.main)
assert result.exit_code == 0
assert "Show the version and exit." in result.output
assert "Show this message and exit." in result.output | 5,340,313 |
def _validate_matching_filter_data_type(part_types, filters: List[type(Filter)]) -> None:
""" Validate that the filters passed are matching to the partitions'
listed datatypes, otherwise throw a ValueError.
This includes validating comparisons too.
Args:
part_types (dict): A dictionary of all ... | 5,340,314 |
def residual_block(
x,
filters: int,
weight_decay: float,
*,
strides: typing.Union[int, typing.Tuple[int, int]],
dilation: typing.Union[int, typing.Tuple[int, int]],
groups: int,
base_width: int,
downsample,
use_basic_block: bool,
use_cbam: bool,
cbam_channel_reduction: i... | 5,340,315 |
def trace_downstream_main(in_features, in_fdr_raster, out_feature_class, surface_raster=None):
""" Trace downstream from input features, using the flow direction raster
returning polyline of the trace.
"""
try:
arcpy.env.overwriteOutput = True
# Get information about flow raster.
... | 5,340,316 |
def vacancy_based_on_freq(service,duration,frequency,earliest,latest,local_timezone):
"""
Check vacant timeslot with the user inputed duration for the frequency/week the user inputed.
service: get authentication from Google
duration: the length of the new event (int)
frequency: number of days i... | 5,340,317 |
def run_grid_search(fixed_height, threshold, net_weight, net_thresh, stroke_width_thresh, text_height_thresh,
text_line_percentage):
"""
Run a grid search on different hyperparameters to find the best setting for detecting headings on a page.
:param fixed_height: All images should be sca... | 5,340,318 |
def show(vol_path):
""" Execute qemu-img show inside a container, direct mapping the volume """
name = "qemu-img"
image = "breqwatr/qemu-img:latest"
path = Path(vol_path)
vol_abspath = path.absolute().__str__()
run = f"qemu-img info {vol_abspath}"
mount = f"-v {vol_abspath}:{vol_abspath}"
... | 5,340,319 |
def load_extensions():
"""
NOTE: This code is a copy of the code in econ_platform_core.extensions.__init__.py.
I will need to figure out how to make this function not use the current directory.
TODO: Merge this function with the one in econ_platform_core.
Imports all *.py files in this directory ... | 5,340,320 |
def byte_list_to_nbit_le_list(data, bitwidth, pad=0x00):
"""! @brief Convert a list of bytes to a list of n-bit integers (little endian)
If the length of the data list is not a multiple of `bitwidth` // 8, then the pad value is used
for the additional required bytes.
@param data List of bytes.... | 5,340,321 |
def admin_not_need_apply_check(func):
"""
admin用户不需要申请权限检查
"""
@wraps(func)
def wrapper(view, request, *args, **kwargs):
if request.user.username == ADMIN_USER:
raise error_codes.INVALID_ARGS.format(_("用户admin默认拥有任意权限, 无需申请"))
return func(view, request, *args, **kwargs)... | 5,340,322 |
def modify_client_properties(ResourceId=None, ClientProperties=None):
"""
Modifies the properties of the specified Amazon WorkSpaces clients.
See also: AWS API Documentation
Exceptions
:example: response = client.modify_client_properties(
ResourceId='string',
ClientProperti... | 5,340,323 |
def add_alias(alias_name, font_name):
"""Add an alias for a font family name.
e.g. add_alias('fixed', 'Monotype')
"""
global aliases
aliases[alias_name] = font_name | 5,340,324 |
def check_args_preproc(args):
"""Ensure preprocessor parser arguments are valid."""
check_args_common(args)
if args.ecmwf_dir:
args.ggam_dir = args.ecmwf_dir
args.ggas_dir = args.ecmwf_dir
args.spam_dir = args.ecmwf_dir
# Limit should either be all zero or all non-zero.
li... | 5,340,325 |
def parse_headers(header_list):
"""
Convert headers from our serialized dict with lists for keys to a
HTTPMessage
"""
header_string = b""
for key, values in header_list.items():
for v in values:
header_string += \
key.encode('utf-8') + b":" + v.encode('utf-8')... | 5,340,326 |
def _rrv_add_ ( s , o ) :
"""Addition of RooRealVar and ``number''
>>> var = ...
>>> num = ...
>>> res = var + num
"""
if not isinstance ( o , val_types ) : return NotImplemented
if isinstance ( o , _RRV_ ) and not o.isConstant() : o = o.ve ()
elif hasattr ( o , '... | 5,340,327 |
def stations_by_distance(stations, p):
"""This module sorts stations by distance and returns a
list of (station, town, distance) tupules."""
from haversine import haversine, Unit #import haversine function from library
list_station_dist = [] #initiates list to store stations and distance
... | 5,340,328 |
def create_SHA_256_hash_of_file(file):
"""
Function that returns the SHA 256 hash of 'file'.\n
Logic taken from https://www.quickprogrammingtips.com/python/how-to-calculate-sha256-hash-of-a-file-in-python.html
"""
sha256_hash = hashlib.sha256()
with open(file, "rb") as f:
# Read and upda... | 5,340,329 |
def partition_average(partition):
"""Given a partition, calculates the expected number of words sharing the same hint"""
score = 0
total = 0
for hint in partition:
score += len(partition[hint])**2
total += len(partition[hint])
return score / total | 5,340,330 |
def set_params(config):
"""Configure parameters based on loaded configuration"""
params = {
'path': None,
'minio': None,
'minio_access_key': None,
'minio_secret_key': None,
'minio_secure': True,
'minio_ca_certs': None,
'minio_bucket': 'catalogue',
... | 5,340,331 |
def encrypt(source, destination, key_pair_name):
"""Encrypts a file or directory."""
try:
encrypt_wrapper(source, destination, key_pair_name)
cleanup(destination)
except Exception as e:
print(f"Error: {e}")
cleanup(destination) | 5,340,332 |
def trigger(work):
"""
Call to trigger a LP
"""
global _event
old = _event
_event = AsyncResult()
old.set(work) | 5,340,333 |
def post_stop_watch():
"""
This method change watcher status to true and return -> "watching": false
"""
url = common.combine_url(
config.INGESTION_AGENT_URL,
config.INGESTION_WATCHER_STATUS,
config.INGESTION_STOP_WATCHER,
)
resp = base_requests.send_post_request(url)
... | 5,340,334 |
def flush():
"""Drop all collections in the database."""
if os.environ.get('FLASK_ENV', 'development') == 'production':
print('You should not flush the database in production.')
return
client = MongoClient(
host=os.environ.get('MONGO_HOST'),
port=int(os.environ.get('MONGO_PO... | 5,340,335 |
def combine_grad_fields(field1, field2):
"""
Combines two gradient fields by summing the gradiends in every point.
The absolute values of each pixel are not interesting.
Inputs:
- field1: np.array(N, M) of Pixels.
- field2: np.array(N, M) of Pixels.
Output:
- out_field: np.a... | 5,340,336 |
def plot_time_speed(ax, path):
"""
Makes speed plot
:param ax: axes
:param path: path, contains trajectory items
:return:
"""
if len(path['items']) > 0:
velocities = [item['length'] / item['duration'] * 3600 for item in path["items"]]
times = [item['duration'] for item in pat... | 5,340,337 |
def start_queue_manager(hostname, portnr, auth_code, logger):
"""
Starts the queue manager process.
"""
p = Process(target=_queue_manager_target, args=(hostname, portnr, auth_code, logger))
p.start()
for i in range(10):
time.sleep(2)
if get_event_queue(hostname, portnr, auth_code... | 5,340,338 |
def rm(service, key):
"""
Remove a node.
The node is identified by a given KEY, which can be either the node's ID or
its name.
"""
try:
service.delete(key)
click.echo('The node was removed correctly.')
except Exception as e:
click.echo('Unable to remove the node:\n'... | 5,340,339 |
def edit_module_form(request, module_id):
"""
Only the instructor who is the creator of the course to which this module belongs can access this.
"""
course = Module.objects.get(moduleID=module_id).getCourse()
if request.user.role != 1 or (course.instructorID.userID != request.user.userID):
c... | 5,340,340 |
async def test_app_created_then_show_wait_form(
hass, app, app_oauth_client, smartthings_mock):
"""Test SmartApp is created when one does not exist and shows wait form."""
flow = SmartThingsFlowHandler()
flow.hass = hass
smartthings_mock.apps.return_value = []
smartthings_mock.create_app.re... | 5,340,341 |
def test_dewpoint_specific_humidity_old_signature():
"""Test dewpoint from specific humidity using old signature issues specific error."""
p = 1013.25 * units.mbar
temperature = 20. * units.degC
q = 0.012 * units.dimensionless
with pytest.raises(ValueError, match='changed in 1.0'):
dewpoint_... | 5,340,342 |
def r2(y_true, y_pred):
"""
:math:`R^2` (coefficient of determination) regression score function.
Best possible score is 1.0, lower values are worse.
Args:
y_true ([np.array]): test samples
y_pred ([np.array]): predicted samples
Returns:
[float]: R2
"""
return r2_... | 5,340,343 |
def add_message_event(proto_message, span, message_event_type, message_id=1):
"""Adds a MessageEvent to the span based off of the given protobuf
message
"""
span.add_time_event(
time_event=time_event.TimeEvent(
datetime.utcnow(),
message_event=time_event.MessageEvent(
... | 5,340,344 |
def passstore(config, name):
"""Get password file"""
return config.passroot / name | 5,340,345 |
def test_plugin_class():
"""If a plugin class is passed to find_plugin(), it shoud be returned back."""
plugin = pybtex.plugin.find_plugin("pybtex.database.input", 'bibtex')
plugin2 = pybtex.plugin.find_plugin("pybtex.database.input", plugin)
nose.tools.assert_equal(plugin, plugin2) | 5,340,346 |
def scan_code(job_id):
"""
Do all the heavy lifting... Query the Org for all the Apex Classes and build the Symbol Table
"""
# Load the job from the database
job = models.Job.objects.get(pk=job_id)
job.status = 'Processing'
job.save()
try:
# Init the scan job and run
sc... | 5,340,347 |
def _get(url, **fields):
"""Get a GroupMe API url using urllib3.
Can have arbitrary string parameters
which will be part of the GET query string."""
fields["token"] = login.get_login()
response = HTTP.request("GET", GROUPME_API + url, fields=fields)
# 2XX Success
if 200 <= response.status <... | 5,340,348 |
def init_cluster():
"""
Initialise Cluster
:return:
"""
#using default username/password to login first, create new admin user base on provided value, then delete admin
api = ApiResource(server_host=cmx.cm_server, username="admin", password="admin")
api.create_user(cmx.username, cmx.password... | 5,340,349 |
def change_instance_type_instancecmd(params, hostname, new_instance_name):
""" change the instance type of a specified instance to a new one """
instance = convert_host_name_to_instance(hostname)
instance.modify_attribute(DryRun=params.aws_dryrun,
Attribute='instanceType',
... | 5,340,350 |
def coord_shell_array(nvt_run, func, li_atoms, species_dict, select_dict,
run_start, run_end):
"""
Args:
nvt_run: MDAnalysis Universe
func: One of the neighbor statistical method (num_of_neighbor_one_li,
num_of_neighbor_one_li_simple)
li_atoms: Atom grou... | 5,340,351 |
def qa():
"""
QA server settings
"""
env.hosts = ['ombu@qa.ombuweb.com']
env.host_type = 'staging'
env.user = 'ombu'
env.host_webserver_user = 'www-data'
env.host_site_path = '/vol/main/foo/bar'
env.base_url = 'http://qa.ombuweb.com'
# DB settings
env.db_db = 'foo'
env.d... | 5,340,352 |
def get_events(number):
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
... | 5,340,353 |
def plot_transactions_ts(transactional_df, frequency="M", aggregation="n_purchases", reg=False, black_friday_dates=None, plot_black_friday=False, plot_normal_only=False, **kwargs):
"""
plota a evolucao das compras no tempo
black_friday_dates:: list of datetime.date
"""
# preventing unwnated modific... | 5,340,354 |
def generate_token(public_id):
"""
Simple token generator returning encoded JWT
:param public_id: unique string user identification
:return JWT: authorization token for given public_id
"""
# if User.query.filter_by(public_id=public_id).one_or_none() is None:
# return jsonify(404, "ID unver... | 5,340,355 |
def test_sanitizing_1d():
"""Test if dataset cleanup gives expected results."""
a = np.arange(10).astype(object)
a[4:6] = None
b = np.arange(10).astype(complex)
b[4] = np.nan
a_clean = np.hstack((a[:4], a[5:]))
b_clean = np.hstack((b[:4], b[5:]))
dd = DataDict(
a=dict(values=a)... | 5,340,356 |
def get_user_permission_all_url_list(user_id):
"""
获取用户全部权限 url list
:param user_id: 用户id
:return:
"""
logging.info('get_user_permission_all_url_list')
try:
user_permission_list = db_get_user_permission_all_list(user_id)
permission_url_list = list()
for user_permissio... | 5,340,357 |
def plot_predicted_data(training_actual_df, predicted_df, date_col, actual_col,
pred_col=PredictionKeys.PREDICTION.value, prediction_percentiles=None,
title="", test_actual_df=None, is_visible=True,
figsize=None, path=None, fontsize=None,
... | 5,340,358 |
def make_plot(x_vals, yVals, title, xLabel, yLabel, style, newFig=False, logX=False, logY=False):
"""Plots x_vals vs. yVals with supplied titles and labels."""
if newFig:
pylab.figure()
pylab.title(title)
pylab.xlabel(xLabel)
pylab.ylabel(yLabel)
pylab.plot(x_vals, yVals, style)
if l... | 5,340,359 |
def CheckTreeIsOpen(input_api, output_api, url, closed, url_text):
"""Similar to the one in presubmit_canned_checks except it shows an helpful
status text instead.
"""
assert(input_api.is_committing)
try:
connection = input_api.urllib2.urlopen(url)
status = connection.read()
connection.close()
... | 5,340,360 |
def tnr_ecma_st(signal, fs, prominence=True):
"""Computation of tone-to-noise ration according to ECMA-74, annex D.9
for a stationary signal.
The T-TNR value is calculated according to ECMA-TR/108
Parameters
----------
signal :numpy.array
A stationary signal in [Pa].
fs : intege... | 5,340,361 |
def set_seed(seed, config = None):
"""
set initial seed for reproduction
"""
if config is None:
raise ValueError("config should not be None")
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
... | 5,340,362 |
def pop_legacy_palette(kwds, *color_defaults):
"""
Older animations in BPA and other areas use all sorts of different names for
what we are now representing with palettes.
This function mutates a kwds dictionary to remove these legacy fields and
extract a palette from it, which it returns.
"""
... | 5,340,363 |
def trace_dot(X, Y):
"""Trace of np.dot(X, Y.T).
Parameters
----------
X : array-like
First matrix
Y : array-like
Second matrix
"""
return np.dot(X.ravel(), Y.ravel()) | 5,340,364 |
def main():
"""Continuum normalize a fits file interactively."""
args = _parser()
data = fits.getdata(args.fitsname)
hdr = fits.getheader(args.fitsname)
print(data)
print(type(data))
print(data.shape)
if isinstance(data, fits.fitsrec.FITS_rec):
wave = data.field(0)
flux ... | 5,340,365 |
def branches(verbose=False):
"""Show the list of revisions that have more than one next revision."""
a = get_alembic()
print_stdout = a.config.print_stdout
get_revision = a.script_directory.get_revision
for r in a.branches():
print_stdout(r.cmd_format(verbose, include_branches=True, includ... | 5,340,366 |
async def handle_waste_view(ack, body, client, view):
"""Process input from waste form"""
logger.info("Processing waste input...")
logger.info(body)
raw_leaders = view['state']['values']['input_a']['leader_names']['selected_options']
leader_list = [" - " + n['value'] for n in raw_leaders]
regula... | 5,340,367 |
def random_superposition(dim: int) -> np.ndarray:
"""
Args:
dim: Specified size returns a 2^dim length array.
Returns:
Normalized random array.
"""
state_vector = np.random.standard_normal(dim).astype(complex)
state_vector += 1j * np.random.normal(dim)
state_vector /= np.lina... | 5,340,368 |
def predict(dag_model: Dag, test_data: Tensor) -> MultitaskMultivariateNormal:
"""
Can use this little helper function to predict from a Dag without
wrapping it in a DagGPyTorchModel.
"""
dag_model.eval()
with no_grad(), fast_pred_var():
return dag_model(test_data) | 5,340,369 |
def edit_skill():
"""Edit a skill entry in the skills table for a certain user. """
id = request.form['id']
skill_level = request.form['skill_level']
skills.update({'skill_level': skill_level}, id=id)
return good_json_response('success') | 5,340,370 |
async def hello(ctx):
"""Say hello to the bot""" # the command description can be supplied as the docstring
await ctx.send(f"Hello {ctx.author}!") | 5,340,371 |
def oais_process_transfer(uuid, accession_id='', archivematica_id=None):
"""Mark the transfer in progress.
This function should be called if the transfer is processing. See
:py:func:`invenio_archivematica.tasks.oais_start_transfer`.
The signal
:py:data:`invenio_archivematica.signals.oais_transfer_... | 5,340,372 |
def is_catalogue_link(link):
"""check whether the specified link points to a catalogue"""
return link['type'] == 'application/atom+xml' and 'rel' not in link | 5,340,373 |
def morlet_window(width: int, sigma: float) -> np.ndarray:
"""
Unadjusted Morlet window function.
Parameters
----------
width : integer (positive power of 2)
Window width to use - power of two as window of two corresponds to Nyquist rate.
sigma : float
Corresponds to the freque... | 5,340,374 |
def tfidfvec():
"""
中文特征值化
:return: None
"""
c1, c2, c3 = cutword()
print(c1, c2, c3)
tf = TfidfVectorizer()
data = tf.fit_transform([c1, c2, c3])
print(tf.get_feature_names())
print(data.toarray())
return None | 5,340,375 |
def resolve_guid(guid, suffix=None):
"""Resolve GUID to corresponding URL and return result of appropriate
view function. This effectively yields a redirect without changing the
displayed URL of the page.
:param guid: GUID value (not the object)
:param suffix: String to append to GUID route
:re... | 5,340,376 |
def _is_array(obj: Any) -> bool:
"""Whether the object is a numpy array."""
return isinstance(obj, np.ndarray) | 5,340,377 |
def has_ao_1e_int_overlap(trexio_file) -> bool:
"""Check that ao_1e_int_overlap variable exists in the TREXIO file.
Parameter is a ~TREXIO File~ object that has been created by a call to ~open~ function.
Returns:
True if the variable exists, False otherwise
Raises:
- Exception from ... | 5,340,378 |
async def get_non_existent_ids(collection, id_list: Sequence[str]) -> Set[str]:
"""
Return the IDs that are in `id_list`, but don't exist in the specified `collection`.
:param collection: the database collection to check
:param id_list: a list of document IDs to check for existence
:return: a list ... | 5,340,379 |
def create_source_fc(header):
"""
Creates :class:`parser.file_configuration_t` instance, configured to
contain path to C++ source file
:param header: path to C++ source file
:type header: str
:rtype: :class:`parser.file_configuration_t`
"""
return file_configuration_t(
data=he... | 5,340,380 |
def check_freq(var: xr.DataArray, freq: str, strict: bool = True):
"""Raise an error if not series has not the expected temporal frequency or is not monotonically increasing.
Parameters
----------
var : xr.DataArray
Input array.
freq : str
The temporal frequency defined using the Pandas... | 5,340,381 |
def prune(valid_cols, new_item_set, search_space):
""" prune invalid combination of columns
Args:
--------
valid_cols: existing valid column list
new_item_set: item set to be merged
search_space: the search space that stores possible candidates
Returns:
--------
"""
if len(valid_cols) == 0:
return
for s... | 5,340,382 |
def StorageFlatten(cache_line_size, create_bound_attribute=False):
"""Flatten the multi-dimensional read/write to 1D.
Parameters
----------
cache_line_size: int
The size of CPU cache line.
create_bound_attribute:
Whether to create bound attributes.
Returns
-------
fp... | 5,340,383 |
def wrap(node):
"""Stringify the parse tree node and wrap it in parentheses if it might be
ambiguous.
"""
if isinstance(node, (IntNode, CallNode, SymbolNode)):
return str(node)
else:
return "(" + str(node) + ")" | 5,340,384 |
def _ParseProjectNameMatch(project_name):
"""Process the passed project name and determine the best representation.
Args:
project_name: a string with the project name matched in a regex
Returns:
A minimal representation of the project name, None if no valid content.
"""
if not project_name:
retu... | 5,340,385 |
def assign_variables(assignment_expressions, df, locals_dict, df_alias=None, trace_rows=None):
"""
Evaluate a set of variable expressions from a spec in the context
of a given data table.
Expressions are evaluated using Python's eval function.
Python expressions have access to variables in locals_d... | 5,340,386 |
def ResetAnalysisForANewAnalysis(master_name,
builder_name,
build_number,
build_completed=False,
pipeline_status_path=None,
current_version=None):
"""Res... | 5,340,387 |
def getCharts(dmldata: bytearray) -> list:
"""Get DrawingML object from clipboard"""
stream = io.BytesIO(dmldata)
with zipfile.ZipFile(stream, "r") as z:
with z.open("[Content_Types].xml") as f:
tree = ET.fromstring(f.read())
part_names = []
for link in tree.findal... | 5,340,388 |
def docker():
"""Docker utilities."""
pass | 5,340,389 |
def explore_validation_time_gap_threshold_segments(participant_list, time_gap_list = [100, 200, 300, 400, 500, 1000, 2000], prune_length = None,
auto_partition_low_quality_segments = False):
"""Explores different threshiold values for the invalid time gaps in the Segments ... | 5,340,390 |
def convolve_design(X, hrf, opt=None):
"""convolve each column of a 2d design matrix with hrf
Args:
X ([2D design matrix]): time by cond, or list of onsets
hrf ([1D hrf function]): hrf
opt: if onset case, provides n_times and tr for
interpolation
Returns:
[conv... | 5,340,391 |
def relax_incr_dimensions(iet, **kwargs):
"""
Recast Iterations over IncrDimensions as ElementalFunctions; insert
ElementalCalls to iterate over the "main" and "remainder" regions induced
by the IncrDimensions.
"""
sregistry = kwargs['sregistry']
efuncs = []
mapper = {}
for tree in ... | 5,340,392 |
def _get_lspci_name(line):
"""Reads and returns a 'name' from a line of `lspci` output."""
hush = line.split('[')
return '['.join(hush[0:-1]).strip() | 5,340,393 |
def dumps_bytes(obj):
"""
Serialize ``obj`` to JSON formatted ``bytes``.
"""
b = dumps(obj)
if isinstance(b, unicode):
b = b.encode("ascii")
return b | 5,340,394 |
def get_child_right_position(position: int) -> int:
"""
heap helper function get the position of the right child of the current node
>>> get_child_right_position(0)
2
"""
return (2 * position) + 2 | 5,340,395 |
def remove_files() -> None:
"""Function that deletes multiple files when called during exit operation.
Warnings:
Deletes:
- all ``.lock`` files created for alarms and reminders.
- ``location.yaml`` file, to recreate a new one next time around.
- ``meetings`` file, to... | 5,340,396 |
def convert_paragraphs_to_s2orc(paragraphs: List, old_to_new: Dict) -> List[Dict]:
"""
Convert paragraphs into S2ORC format
"""
# TODO: temp code to process body text into S2ORC format. this includes getting rid of sub/superscript spans.
# also combining fig & table spans into ref spans.
... | 5,340,397 |
def get_feature_set_details(shape_file_path):
""" This function gets the shape type of the shapefile and make a list
of fields to be added to output summary table based on that shape type """
try:
# Checking for geometry type
feat_desc = arcpy.Describe(shape_file_path)
arcpy.AddMes... | 5,340,398 |
def test_create_order(mocker, expected_response, expected_data, client) -> None:
"""Test the create_order of the sync client"""
mocker.patch("requests.Session.request", return_value=expected_response)
actual_data = client.create_order(pair_id=1, amount=100, kind="buy", price=100)
assert actual_data ==... | 5,340,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.