content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _is_reparse_point(path):
"""
Returns True if path is a reparse point; False otherwise.
"""
result = win32file.GetFileAttributesW(path)
if result == -1:
return False
return True if result & 0x400 else False | 74,500 |
def test__handle_added(create_event_v2):
""" Test the cray.cfs.operator.events.session_events._handle_added method """
with patch.object(CFSSessionController, '_create_k8s_job') as cfs_job:
with patch('cray.cfs.operator.cfs.sessions.update_session_status'):
with patch.object(CFSJobMonitor, '... | 74,501 |
def test_session():
"""
Session class tests
"""
user_id = "test_id"
secret = "test_secret"
session = Session(user_id, secret)
# Session not expired
assert False is session.is_expired()
# Unseal a session
assert True is session.is_sealed()
session.unseal()
assert False i... | 74,502 |
def unifi():
"""Returns the latest version available for unifi products."""
expression = r"UniFi Cloud Key firmware (.*)<\/td>"
browser = create_headless_firefox_browser()
cloud_key_url = "https://www.ui.com/download/unifi/unifi-cloud-key"
browser.get(cloud_key_url)
html = browser.page_source
... | 74,503 |
def test_get_lol_users_with_winrate_enabled():
"""
Tests that getting a users with winrate enabled returns true
"""
users = get_lol_users_with_winrate_enabled()
for user in users:
found = True
for e_user in mock_users()[1:]:
if e_user.discord_id == user.discord_id:
... | 74,504 |
def check_participant(request):
"""Check and add participant if not exist
Args:
request ([Request]): Django request object with expected key and value data
Returns:
[HttpResponse]: Http response message
"""
if not request.method =='POST':
return HttpResponseNotAllowed(['POST'... | 74,505 |
def print_and_save_accs(logger, model_name, dsname, accs, nnotzero, neuron_type='all_neurons', c=None):
"""get and print/log accuracy string"""
acc_string = get_and_save_accuracy_string(logger, model_name, dsname, accs, neuron_type)
print('%s train/val/test accuracy w/ %s'%(acc_string, neuron_type))
if c is not... | 74,506 |
def update_cluster_config(cluster_id):
"""update cluster config.
Supported fields: ['os_config', 'package_config', 'config_step']
"""
data = _get_request_data()
return utils.make_json_response(
200,
cluster_api.update_cluster_config(
cluster_id, user=current_user, **data... | 74,507 |
def ms_hybrid_allocate():
"""
test case Custom Op with functions written in Hybrid DSL about math functions and allocate
"""
np.random.seed(10)
input_x = np.random.normal(0, 1, [4, 4]).astype(np.float16)
input_y = np.random.normal(0, 1, [4, 4]).astype(np.float16)
test = TestMsHybridDSL(allo... | 74,508 |
def _get_modules():
"""
INTERNAL: Enumerate process modules
"""
module = idaapi.module_info_t()
result = idaapi.get_first_module(module)
while result:
yield module
result = idaapi.get_next_module(module) | 74,509 |
def do_encode(clip: vs.VideoNode)-> None:
"""Compression with x26X"""
if not os.path.isfile(JPBD.output):
print('\n\n\nVideo encoding')
bits = clip.format.bits_per_sample
x265_cmd = f'x265 -o {JPBD.output} - --y4m' + ' '
x265_cmd += f'--csv {JPBD.name}_log_x265.csv --csv-log-leve... | 74,510 |
def check_result_exists(modelrun_name, sector_model_name, decision_iteration, result_file_name):
""" Check if a certain result file was generated a modelrun
"""
config_dirname = os.path.join(NISMOD_DIR, 'results')
results_folder = os.path.join(
config_dirname,
modelrun_name,
sect... | 74,511 |
def make_babies(parents, size=10000):
"""Create a new population by randomly selecting two parents and
randomly selecting the character from a parent for each position."""
children = []
for i in range(size):
p1, p2 = random.sample(parents, 2)
children.append(''.join([p1[i] if random.rand... | 74,512 |
def data_quality_log_and_estimate(log_fpath, metric_fpath, bad_files,
duplicate_frames, total_frames, intensities,
differences, density_mean, fourier_valid,
config):
"""Write results from data validation to a txt l... | 74,513 |
def lowess(x, w, x0, kernel=epanechnikov, l=1, robust=False):
"""
Locally linear regression with the LOWESS algorithm.
Parameters
----------
x: float n-d array
Values of x for which f(x) is known (e.g. measured). The shape of this
is (n, j), where n is the number the dimensions of t... | 74,514 |
def main():
"""Main function."""
game = gg.Game()
# Set the attributes of the game to make it your own
game.name = "Mr. Borjon's Most Awesomest Gamest: Flak"
game.images_dir = 'example_pics'
game.splash_image = 'splash.bmp'
game.player_image = 'guy.gif'
game.enemy_image = 'face.gif'
... | 74,515 |
def make_app():
""" Function for creating the server instance """
app = web.Application()
app.on_startup.append(on_startup)
app.add_routes(ROUTER)
return app | 74,516 |
def market_timing(ticker, dt, timing='EOD', tz='local') -> str:
"""
Market close time for ticker
Args:
ticker: ticker name
dt: date
timing: [EOD (default), BOD]
tz: conversion to timezone
Returns:
str: date & time
Examples:
>>> market_timing('7267 J... | 74,517 |
def plus(cell1, cell2, back_val):
"""Moves forward between two cells.
Requires a third cell, though truly only requires the value of that the
form takes at the cell.
"""
(x1, y1), val1 = cell1
(x2, y2), val2 = cell2
# back_val, val1 + val2, val form an arithmetic progression
val = 2 * (... | 74,518 |
def _CopyRuntime2015(target_dir, source_dir, dll_pattern):
"""Copy both the msvcp and vccorlib runtime DLLs, only if the target doesn't
exist, but the target directory does exist."""
for file_part in ('msvcp', 'vccorlib', 'vcruntime'):
dll = dll_pattern % file_part
target = os.path.join(target_dir, dll)
... | 74,519 |
def get_bool_symbols(a_boolean):
"""
:param a_boolean: Any boolean representation
:return: Symbols corresponding the to the
True or False value of some boolean representation
Motivation: this is reused on multiple occasions
"""
if a_boolean:
return "✅"
return "❌" | 74,520 |
def rc_int(index, r0, m):
"""ported from MATLAB
function that takes a matrix and performs a Gaussian integral
over the row and column specified by index and returns
a new matrix. Tested against maple integration.
"""
r = sqrt(2 * pi / m[index, index]) * r0
# remove columns and rows from m... | 74,521 |
def show(config_path: str = typer.Option(CONFIG_PATH, "--config", "-c")):
"""
Print the current config file
"""
# Print out the config file
cfg = read_config(config_path=config_path)
default_section = cfg["DEFAULT"]
header = ["Section", "Name", "Value"]
aligns = ["l", "l"]
data = [... | 74,522 |
def show(img, title):
"""easily display an image for debugging"""
if isinstance(img, Image.Image):
img = np.array(img)
_, _, n_channels = img.shape
# print("img max before flatten: ", np.max(img[:, :, 0:3]))
if n_channels > 3:
# print("flattening alpha")
# print("alpha m... | 74,523 |
def _sort_yaml_first(item_1: _pytest.nodes.Item, item_2: _pytest.nodes.Item) -> int:
"""Sort yaml item first vs module at or below yaml parent directory."""
path_1 = Path(item_1.fspath)
path_2 = Path(item_2.fspath)
if path_1 == path_2 or path_1.suffix == path_2.suffix:
return 0
if path_2.suf... | 74,524 |
def test_big_download3():
"""A test with attribute specific value"""
pass | 74,525 |
def lat_lon_kml(row_iter: Rows) -> Iterable[LL_Text]:
"""
>>> data= [['-76.33029518659048', '37.54901619777347', '0']]
>>> list(lat_lon_kml( data ))
[('37.54901619777347', '-76.33029518659048')]
"""
return (pick_lat_lon(*row) for row in row_iter) | 74,526 |
def generate_test(coding="cp1252"):
""" """
l = []
for c in chars:
try:
c2 = c.encode(coding)
x1 = str(c2).replace("b'", "'", 1).replace("'", "")
l.append(x1)
except UnicodeEncodeError as e:
pass
out = "".join(l)
print(f'char * text = ... | 74,527 |
def rodogram(x, lag=1, win_size=5, win_geom="square", **kwargs):
"""
Calculate moveing window rodogram with specified
lag for array.
Parameters
----------
x : array like
Input array
lag : int
Lag distance for variogram, defaults to 1.
win_size : int, optional
... | 74,528 |
def test_download_editable_pep660_basic(tmpdir, script, with_wheel):
"""
Test 'pip download' of an editable pep 660 project.
It must *not* call prepare_metadata_for_build_editable.
"""
project_dir = _make_project(tmpdir, BACKEND_WITH_PEP660, with_setup_py=False)
reqs_file = tmpdir / "requirement... | 74,529 |
def load_schema(schema_id: str,
version:Optional[str]=None):
"""
Schema functionality adopted from https://github.com/scikit-hep/pyhf/blob/master/src/pyhf/utils.py
"""
global SCHEMA_CACHE
if not version:
version = SCHEMA_VERSION
try:
return SCHEMA_CACHE[f'{SCHEMA... | 74,530 |
def initexceptions(space):
"""NOT_RPYTHON"""
__doc__ = \
"""Python's standard exception class hierarchy.
Before Python 1.5, the standard exceptions were all simple string objects.
In Python 1.5, the standard exceptions were converted to classes organized
into a relatively flat hierarchy. String-based standard ex... | 74,531 |
def returner(x):
"""
Create a function that takes any arguments and always
returns x.
"""
def func(*args, **kwargs):
return x
return func | 74,532 |
def is_iterable_type(tp: type) -> bool:
"""
Test if the given type is iterable.
Some examples of iterable type hints are:
Iterable[str]
Collection[str]
Mapping[str, int]
Sequence[str]
List[str]
Set[str]
Dict[str, int]
Generator[str, int, int]... | 74,533 |
def get_unique_characters(rows, min_count=2):
"""Given a bunch of text rows, get all unique chars that occur in it."""
def char_iterator():
for row in rows.values:
for char in row:
yield str(char).lower()
return [
c for c, count
in Counter(char_iterator()... | 74,534 |
def test_setext_headings_extra_26():
"""
Test case extra 26: SetExt heading string ending with a raw html block.
"""
# Arrange
source_markdown = """really, <there it='is'>
---"""
expected_tokens = [
"[setext(2,1):-:3::(1,1)]",
"[text(1,1):really, :]",
"[raw-html(1,9):th... | 74,535 |
def get_main_window():
"""Acquire Maya's main window"""
from Qt import QtWidgets
if self._parent is None:
self._parent = {
widget.objectName(): widget
for widget in QtWidgets.QApplication.topLevelWidgets()
}["MayaWindow"]
return self._parent | 74,536 |
def build_data_type_name(sources, properties, statistic, subtype=None):
"""
Parameters
----------
sources: str or list[str]
type(s) of astrophysical sources to which this applies
properties: str or list[str]
feature(s)/characterisic(s) of those sources/fields to
which the st... | 74,537 |
def build_domain_chaindict(domlist):
"""
Build the diction of min and max residue sequence numbers for each
chain in the supplied domain decompositions (list of PTDomain objects).
Parameters:
domlist - list of PTDomain objects represetning a domain decomp.
Return value:
... | 74,538 |
def machineCostPerH(fixed, operating):
"""
fixed = fixed costs
operating = operating costs
"""
return {'Machine cost per H': [fixed + operating]} | 74,539 |
def expand_symbols(text):
"""
expand symbols in text
"""
text = re.sub("\;", ",", text)
text = re.sub("\:", ",", text)
text = re.sub("\-", " ", text)
text = re.sub("\&", "and", text)
return text | 74,540 |
def _sqlite_format_dtdelta(connector, lhs, rhs):
"""
LHS and RHS can be either:
- An integer number of microseconds
- A string representing a datetime
- A scalar value, e.g. float
"""
if connector is None or lhs is None or rhs is None:
return None
connector = connector.strip()
... | 74,541 |
def get_conv(outfile):
"""
Helper function to get the convergence info from SCF loops
Args:
outfile (str): output file to parse
Returns:
returns convergence info (change in energy between SCF steps) as a
single list (flattened across outer scf loops).
"""
out = Cp2kOutpu... | 74,542 |
def run_server():
"""run server"""
if SERVICE.server_running:
return
python_path = settings.DEFAULT_INTERPRETER.path
if not python_path:
raise errors.InterpreterNotFound("interpreter path not found")
# find `activate` file path
activate_path = interpreter.find_activate(python_... | 74,543 |
def totext(self):
"""Returns row data in tab-delimited text format."""
words = []
column_index = 0
for column in self.columns:
if column['type'].startswith('bit'):
column_index += 1
for bitcolumn in column['columns']:
words.append(format(self[column_index]... | 74,544 |
def fit_density(density, wi, fraction_fit=1., return_xy=False):
"""Fit average density curve from a set of density samples.
This is an easier interface than mft.fit_density
Parameters
----------
density : list of ndarray
Density from leftmost front to right over multiple snapshots.
wi ... | 74,545 |
def assert_almost_equal(
actual: numpy.float64, desired: numpy.float64, err_msg: Literal["orth.legendre(0)"]
):
"""
usage.scipy: 1
"""
... | 74,546 |
def is_in_0_1(value, value_label):
""" Checks if a value is within [0, 1]
Arguments:
value: the value to check
value_label: a name for the value to check
Raises:
ValueError: if `value` is not a number or not in [0, 1]
"""
if not isinstance(value, numbers.Number):
ra... | 74,547 |
def test_unpaired_prefix_asterisk_without_space_is_literal(text):
"""An unpaired asterisk at the beginning of the line, without a space
after it, is considered literal.
"""
formatted = Formatted.from_input_line(text)
assert text.strip() == formatted.to_weechat() | 74,548 |
def priter(self, **kwargs):
"""Prints solution summary data.
APDL Command: PRITER
Notes
-----
Prints solution summary data (such as time step size, number of
equilibrium iterations, convergence values, etc.) from a static or full
transient analysis. All other analyses print zeros for the d... | 74,549 |
def make_socket(address, ssl_context=None):
"""Creates a new listening socket bound to the interface, socket or file
descriptor indicated by the address parameter.
To bind to a port on an interface:
To listen for http traffic on localhost port 8080:
make_socket('http://localhost:8080')
T... | 74,550 |
def create_connection(db_file):
"""
create a database connection
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print(e)
return conn | 74,551 |
def new_from_user_input(user_input: Dict[str, Any]) -> "EthereumNetwork": # noqa: C901
"""Create a new EthereumNetwork model from user input
Args:
user_input: User dictionary input (assumed already passing create_ethereum_interchain_schema)
Returns:
Instantiated EthereumNetwork client
R... | 74,552 |
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
"""Set up MyQ from a config entry."""
opp.data.setdefault(DOMAIN, {})
websession = aiohttp_client.async_get_clientsession(opp)
conf = entry.data
try:
myq = await pymyq.login(conf[CONF_USERNAME], conf[CONF_PASSWORD], webse... | 74,553 |
def run_fa2transfac(args):
"""Calculate transfac from fasta files."""
if args.weighting and args.weight_dir is None:
raise ValueError(
"Sequence weighting is selected but the directory containg this data (--weight_dir) is missing!")
fa2transfac(args) | 74,554 |
def handle_pose(output, input_shape):
"""
Handles the output of the Pose Estimation model.
Returns ONLY the keypoint heatmaps, and not the Part Affinity Fields.
From: https://docs.openvinotoolkit.org/latest/_models_intel_human_pose_estimation_0001_description_human_pose_estimation_0001.html
Inputs
... | 74,555 |
def load_metadata_from_youtube(video_id, request):
"""
Get metadata about a YouTube video.
This method is used via the standalone /courses/yt_video_metadata REST API
endpoint, or via the video XBlock as a its 'yt_video_metadata' handler.
"""
metadata = {}
status_code = 500
if video_id a... | 74,556 |
def delete_files(ctx, project_id, paths, throw_on_error):
"""Delete QFieldCloud project files."""
log(f'Deleting project "{project_id}" files…')
paths_result = ctx.obj["client"].delete_files(project_id, paths, throw_on_error)
if ctx.obj["format_json"]:
print_json(paths_result) | 74,557 |
def format_date(val, fmt='%m-%d-%Y'):
"""
Transform the input string to a datetime object
:param val: the input string for date
:param fmt: the input format for the date
"""
date_obj = None
try:
date_obj = datetime.strptime(val, fmt)
except Exception as exc:
log.warning... | 74,558 |
def gaussian(x, ampl, center, dev):
"""Computes the Gaussian function.
Parameters
----------
x : number
Point to evaluate the Gaussian for.
a : number
Amplitude.
b : number
Center.
c : number
Width.
Returns
-------
float
Value of the spec... | 74,559 |
def choix_repas(num_choix=4):
"""
Choix d'un repas en utilisant les dictionnaires
"""
choix = {1: pizza, 2: nuggets, 3: quiche, 4: courgettes}
return choix.get(num_choix, 4)() | 74,560 |
def listToGrid(box, l):
"""
:summary: Writes a permutation from a list to a grid
:param QGroupBox box: group box containing the grid to write to
:param list l: the permutation to write to the grid
"""
lView = [0 if i is None else i + 1 for i in l]
layout = box.layout()
positions = [(i,j... | 74,561 |
def is_valid_id(id_: str) -> bool:
"""If it is not nullptr.
Parameters
----------
id_ : str
Notes
-----
Not actually does anything else than id is not 0x00000
Returns
-------
bool
"""
return not id_.endswith("0x0000000000000000") | 74,562 |
def mtx_gauss_vectors (Omega, i, omega):
"""
Computes the transformation matrix from the orbital plane coordinate
system to the ecliptic system being the sun at the center
Its column vectors (P,Q,R) are the Gauss vectors
It is equivalent and the U matrix:
Rz_3d(-Omega).dot(Rx_3d(-i)).do... | 74,563 |
def scoring_handler(request):
"""
Renders a random AbsoluteScoringTask for testing.
"""
if request.method == "POST":
try:
score = int(request.POST['score'])
if score != -1:
user = request.user
task_id = request.POST['task_id']
... | 74,564 |
def computeOmegaAndOmegaDotTrajectory(QT, QdT, QddT):
"""Extracting/converting omega and omegad (trajectories)
from trajectories of Q, Qd, and Qdd.
"""
assert ((len(QT.shape) >= 1) and
(len(QT.shape) <= 2)), "QT has invalid number of dimensions!"
assert ((len(QdT.shape) >= 1) and
(le... | 74,565 |
def toggle_protection(entry):
"""Toggle 'protected'"""
entry.protected = not entry.protected
entry.save() | 74,566 |
def async_is_zwave_js_migrated(hass):
"""Return True if migration to Z-Wave JS is done."""
zwave_js_config_entries = hass.config_entries.async_entries("zwave_js")
if not zwave_js_config_entries:
return False
migrated = any(
config_entry.data.get("migrated") for config_entry in zwave_js_... | 74,567 |
def _screwdriver_as_gripper_changetype(process, beam_id):
# type: (RobotClampAssemblyProcess, str) -> None
""" Function invoked by user to change gripper type.
Sub function that handles using screwdriver as gripper.
beam_attribute 'gripper_type' and 'gripper_id' will be changed.
"""
# List out... | 74,568 |
def clear_portchannel_configuration(dut_list, thread=True, cli_type=""):
"""
Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com)
:param dut_list:
:param thread: True (Default) / False
:return:
"""
dut_li = list(dut_list) if isinstance(dut_list, list) else [dut_list]
[out, exceptions] =... | 74,569 |
def device_array_like(ary, stream=0):
"""Call cuda.devicearray() with information from the array.
"""
return device_array(shape=ary.shape, dtype=ary.dtype,
strides=ary.strides, stream=stream) | 74,570 |
def get_limit_from_tag(tag_parts):
"""Get the key and value from a notebook limit tag.
Args:
tag_parts: annotation or label notebook tag
Returns (tuple): key (limit name), values
"""
return tag_parts.pop(0), tag_parts.pop(0) | 74,571 |
def group_by_node(notifications, limit=15):
"""Take list of notifications and group by node.
:param notifications: List of stored email notifications
:return:
"""
emails = NotificationsDict()
for notification in notifications[:15]:
emails.add_message(notification['node_lineage'], notifi... | 74,572 |
def _normalize_distribution(distribution):
"""Check whether probability distribution sums to 1"""
distribution = _check_all_zero(distribution)
distribution = distribution / distribution.sum()
return distribution | 74,573 |
def ldescent(A, B):
"""
Return a non-trivial solution to `w^2 = Ax^2 + By^2` using
Lagrange's method; return None if there is no such solution.
.
Here, `A \\neq 0` and `B \\neq 0` and `A` and `B` are square free. Output a
tuple `(w_0, x_0, y_0)` which is a solution to the above equation.
E... | 74,574 |
def PackLikelihoodDataStructuresAsArrays(pairKeys, rholms_intpDictionaryForDetector, rholmsDictionaryForDetector,crossTermsForDetector, crossTermsForDetectorV):
"""
Accepts list of LM pairs, dictionary for rholms against keys, and cross terms (a dictionary)
PROBLEM: Different detectors may have different t... | 74,575 |
def skew(outer, inner, maxrows=-1):
"""
Compute the Schur expansion of a skew Schur function.
Return a linear combination of partitions representing the Schur
function of the skew Young diagram ``outer / inner``, consisting
of boxes in the partition ``outer`` that are not in ``inner``.
INPUT:
... | 74,576 |
def test_intersect(doc_setup):
"""Test intersect matcher."""
doc = doc_setup
space = MentionNgrams(n_min=1, n_max=3)
tc: TemporarySpanMention
# Match any span that contains "apple"
matcher0 = RegexMatchSpan(
rgx=r"apple", search=True, full_match=True, longest_match_only=False
)
... | 74,577 |
def R(u):
""" Strong form residual """
return div(grad(u)) | 74,578 |
def _tocomplex(arr):
"""Convert its input `arr` to a complex array.
The input is returned as a complex array of the smallest type that will fit
the original data: types like single, byte, short, etc. become csingle,
while others become cdouble.
A copy of the input is always made.
Parameters
... | 74,579 |
def update(request):
"""Update account details."""
account = _get_account(request.token)
if not account:
return False, _NO_ACCOUNT
if request.playstore_url:
account.playstore_url = request.playstore_url
if request.appstore_url:
account.appstore_url = request.appstore_url
... | 74,580 |
def test_get_cv_folds_series(colors):
""" Test splitting into folds with a pandas series
"""
# this change from the test above is to make the tests work
expected_output = pd.Series([1, 1, 0, 0, 1, 0, 0, 1, 0])
actual_output = ml_utils.get_cv_folds(colors, num_splits=2)
np.testing.assert_arr... | 74,581 |
def save_graphml(G, filepath=None, gephi=False, encoding="utf-8"):
"""
Save graph to disk as GraphML file.
Parameters
----------
G : networkx.MultiDiGraph
input graph
filepath : string
path to the GraphML file including extension. if None, use
default data folder + graph... | 74,582 |
def residue(b, a, tol=1e-3, rtype='avg'):
"""Compute partial-fraction expansion of b(s) / a(s).
If `M` is the degree of numerator `b` and `N` the degree of denominator
`a`::
b(s) b[0] s**(M) + b[1] s**(M-1) + ... + b[M]
H(s) = ------ = ------------------------------------------
... | 74,583 |
def getShapeProfiles(nr=50):
"""
Returns the shape profiles for magnetic field to use.
"""
global a, B0, Rp
r = np.linspace(0, a*1.05, nr)
rG_R0, G_R0 = r, B0 * np.ones(r.shape)
#rDelta, Delta = r, np.linspace(0, 0.05*a, nr)
rkappa, kappa = r, np.linspace(1, 1.4, nr)
rdelta, delt... | 74,584 |
async def aio_s3_object_uri(
aio_s3_bucket_name, aio_s3_key, aio_s3_uri, aio_s3_object_text, aio_s3_bucket, aio_aws_s3_client
) -> str:
"""s3 object data is PUT to the aio_s3_uri"""
resp = await aio_aws_s3_client.put_object(
Bucket=aio_s3_bucket_name,
Key=aio_s3_key,
Body=aio_s3_obje... | 74,585 |
def test_get_rows_is_slice():
"""Assert that a slice of rows is returned."""
atom = ATOMClassifier(X_idx, y_idx, index=True, random_state=1)
assert len(atom._get_rows(index=slice(20, 100, 2))) == 40 | 74,586 |
def put_saved_command(request):
"""
:param request:
:return:
"""
response = {"errors": 0,
"saved": []}
if request.method == "POST":
plugin_data = {"id": request.POST.get("Name"),
"Name": request.POST.get("Name"),
"PluginName"... | 74,587 |
def main():
"""
Main function
Main function that joins the bitcoin and dark web data
"""
# Create Spark session
appName = "DarkCoinJoin"
master = config.spark["MASTERIP"]
spark = SparkSession.builder \
.appName( appName ) \
.config( "spark.cassandra.connection.host", config.cassandra["HOSTS"] ) \
... | 74,588 |
def get_nb_all_agents():
"""Get quota of all available agents.
Returns
--------
dict
Mapping between agent type and quota of this agent type.
"""
return dict(db.session.query(
Quota.type, Quota.maximum_quota
).all()) | 74,589 |
def Percent(numerator, denominator):
"""Convert two integers into a display friendly percentage string.
Percent(5, 10) -> ' 50%'
Percent(5, 5) -> '100%'
Percent(1, 100) -> ' 1%'
Percent(1, 1000) -> ' 0%'
Args:
numerator: Integer.
denominator: Integer.
Returns:
string formatted result.
"... | 74,590 |
def dataset_to_dataloader(dataset=None, num_workers=1, batch_size=32, shuffle=True, pin_memory="auto"):
"""
Returns batch of img, speed, target_vec, mask_vec
"""
if pin_memory == "auto":
pin_memory = True if torch.cuda.is_available() else False
if dataset is None:
dataset = ... | 74,591 |
def dump_tabulate(dtype, data, metric, file=None, echo_dart=False):
""" Dumps a non-graphframe """
from tabulate import tabulate
def _get_dataframe(x):
import hatchet as ht
return x.dataframe if isinstance(x, ht.graphframe.GraphFrame) else x
_functors = {
"html": lambda x: _g... | 74,592 |
def bin_count(dump_class:dumpFile,axis,number_of_bins,overlap_proportion = 0.0)-> pd.DataFrame:
"""
given a dumpFile class axis number_of_bins and overlap this will make a list of how
many atoms are in the given area
number_of_bins[int] = the number of bins
overlap_proportion[float] = proportional ... | 74,593 |
def fetch_dataset(url, filename, max_retries=4, retry_delay=60):
"""Retrieve a dataset from a URL.
:param url: The URL to retrieve the dataset from.
:type url: str
:param filename: The filename to retrieve.
:type filename: str
:param max_retries: The maximum number of retries.
:type max_ret... | 74,594 |
def force_update(bot, trigger):
"""Force an update of the target Sphinx object inventory.
In lieu of restarting the bot or waiting for the next automatic refresh
(every 24 hours), a bot admin can force an immediate update.
"""
bot.reply("Attempting to update Sphinx objects.")
update_sphinx_obje... | 74,595 |
def f_macd(close_prices, window_slow, window_fast, window_signal):
"""Calculates moving average convergence divergence (MACD)
Args:
close_prices (list of float): A list of close prices for each period.
window_slow (int): The moving window to take averages over for the slow MACD period.
... | 74,596 |
def generate_circle(n):
"""
Generates 'n' images of randomly generated circles
Saves it to a subdirectory within the DATA_DIR
@param: n: int
@return: None
"""
# Padding for filenames
padding = len(str(n))
for i in range(n):
# Generate a random radius
r = randint(5,... | 74,597 |
def get_logger(
name: str,
console_level: int = int(os.getenv("COMPSYN_LOG_LEVEL", logging.INFO)),
log_file: Union[str, Path, None] = os.getenv("COMPSYN_LOG_FILE", None),
file_level: int = logging.DEBUG,
) -> logging.Logger:
"""
Wrapper for setting up and getting logger
"""
if not n... | 74,598 |
def test_get_fields_by_parcel_no_result_example(client):
"""Test get_fields_by_parcel no results"""
parcel = 'ABCDEFG'
response = client.simulate_get(
'/page/get_fields_by_parcel_example',
params={'parcel':parcel, 'returnGeometry':False})
assert response.status_code == 200
content ... | 74,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.