content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_add_edge_known_nodes(test_graph):
"""Test add an edge."""
test_graph[2].add_edge('A', 'B')
assert test_graph[2].graph['A'] == {'B'} | 5,292,300 |
def generate_html(d: List[Dict[str, Union[str, bool]]]) -> str:
"""
Pass in a dict with a list of rows to include in a formatted table. This will return the HTML for the table.
:param d:
:return:
html: HTML formatted table
"""
if not d:
return
pd.set_option("display.max_colw... | 5,292,301 |
def flip_random_flippable(reconstructed_edges: List[Edge],
initial_weight: int) -> Union[int, None]:
"""
Flips a random flippable edge in the provided solution.
Args:
initial_weight: - Initial solution weight.
reconstructed_edges: - List of single solution edges pr... | 5,292,302 |
def merge_gifs(in_gifs, out_gif):
"""Merge multiple gifs into one.
Args:
in_gifs (str | list): The input gifs as a list or a directory path.
out_gif (str): The output gif.
Raises:
Exception: Raise exception when gifsicle is not installed.
"""
import glob
try:
... | 5,292,303 |
def split(data_dir):
"""
Create three splits from the processed records. The files should be moved to new folders in the
same directory. This folder should be named train, val and test.
args:
- data_dir [str]: data directory, /home/workspace/data/waymo
"""
# Split the data present... | 5,292,304 |
def _de_bruijn(k: int, n: int) -> typing.List[int]:
"""Generate a De Bruijn sequence.
This is a piece of mathematical heavy machinery needed for O(1) ctz on
integers of bounded size. The algorithm is adapted from chapter 7 of
Frank Ruskey's "Combinatorial Generation".
Args:
k: The number o... | 5,292,305 |
def run_pt_stream(data_map: dict, features: List[str], session: str, feature_column_names: List[str], time_column_name: str, speed: float=1.0, smoothing_factor: float=0.1, title: str=''):
"""Displays an animation of features synchronized across time. Helpful for comparing feature changes over time compared to annotati... | 5,292,306 |
def do_mobilenet_unet_training(n_classes=None, epochs=5, verify_dataset=True, batch_size=2,
steps_per_epoch=512, val_steps_per_epoch=512, optimizer_name='adam', ):
"""
TODO detail this
Mobile net works only on 224 x 224
This uses the external repo: https://github.com/... | 5,292,307 |
def preprocess_data(x):
"""Preprocess data. Ensure x is 2d ndarray, and scale so that the mean absolute
amplitude of each column is one.
:param x: ndarray, shape (n_samples,) or (n_samples, n_features)
:returns: float ndarray, shape (n_samples, n_features)
"""
x = np.array(x, dtype=np.float64)... | 5,292,308 |
def left_edge_vertical_ids(shape):
"""Link IDs of left edge vertical links.
Parameters
----------
shape : tuple of int
Shape of grid, given as (rows, columns) of nodes.
Returns
-------
ndarray :
Link IDs of left edge vertical links. Length is
(rmg.number_of_rows - 1... | 5,292,309 |
def guess_dim_transition_linebyline(filename):
"""get number of histogram bins from transition matrix file (one line per entry!!!)"""
#print "Reading...", filename
with open(filename,"r") as f:
count = 0
for line in f: # skip lines starting with #
if not line.startswith("#"):
... | 5,292,310 |
def test_find_by_id(session):
"""Assert that find account bcol id mapping by ID contains all expected elements."""
account_bcol_id = AccountBcolId.find_by_id(200000000)
assert account_bcol_id
assert account_bcol_id.id == 200000000
assert account_bcol_id.account_id == 'PS12345'
assert account_bco... | 5,292,311 |
def deduplicate(new_data: List[Dict]) -> List[Dict]:
""" Checks for duplicates and omits them """
old_data = load_data()
data = []
for new in new_data:
if all(new['tweet_id'] != old[2] for old in old_data):
data.append(new)
return data | 5,292,312 |
def identify_necessary_covariates(dependents, definitions):
"""Identify covariates necessary to compute `dependents`.
This function can be used if only a specific subset of covariates is necessary and
not all covariates.
See also
--------
respy.likelihood._compute_x_beta_for_type_probability
... | 5,292,313 |
def delete_event(current_user, event_id):
"""
Deleting a User Event from the database if it exists.
:param current_user:
:param event_id:
:return:
"""
try:
int(event_id)
except ValueError:
return response('failed', 'Please provide a valid Event Id', 400)
user_event = ... | 5,292,314 |
def _file_name_to_target_times(downsized_3d_file_name):
"""Parses file name for target times.
:param downsized_3d_file_name: See doc for `find_downsized_3d_example_file`.
:return: first_target_time_unix_sec: First target time in file.
:return: last_target_time_unix_sec: Last target time in file.
:r... | 5,292,315 |
def make_meeting():
""" Generate a new dummy meeting and save it. """
meeting = frappe.get_doc({
"doctype": "Meeting",
"title": "Test Meeitng",
"status": "Planned",
"date": "2017-07-20",
"from_time": "09:00",
"to_time": "09:30",
"minutes": [
{
"description": "Test minute 1",
"status": "Open",... | 5,292,316 |
def get_configuration_file():
"""ensure yml file exist at $HOME and providing file path and name."""
if not os.path.isfile(HOME_CONFIGURATION):
copyfile(DEFAULT_CONFIGURATION, HOME_CONFIGURATION)
return HOME_CONFIGURATION | 5,292,317 |
def set_autoreload(reload_type: T.Optional[int] = None):
"""Global imports setting.
Parameters
----------
reload_type: {0, 1, 2} or None
(default None)
- **0**) Disable automatic reloading.
- **1**) Reload all modules imported with %aimport
before executing the... | 5,292,318 |
def test_authorize_scalar_attribute_eq(post_fixtures):
"""Test authorization rules on a relationship with one object equaling another."""
# Object equals another object
Oso.load_str(
"""
allow(actor: test_app2::User, "read", _: test_app2::Post{created_by: actor, access_level: "private"});
... | 5,292,319 |
def load_template(template_file_path):
"""
Load a Jinja2 template and return it
Args:
template_file_path (str): path to the Jinja2 template file
Returns:
Template: contains jinja2 template
"""
return Template(open(template_file_path).read()) | 5,292,320 |
def main():
"""main function
"""
# should atually check first if we run qstat at all
try:
res = subprocess.check_output(['qstat', '--version'], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
is_pbspro = False
else:
if 'PBSPro' in res.decode():
... | 5,292,321 |
def calc_categorical_median(x):
"""this function fill the missing values of total_bedrooms based upon categories of ocean_proximity"""
unique_colums_ocean_proximity=x['ocean_proximity'].unique()
for i in unique_colums_ocean_proximity:
median=x[x['ocean_proximity']==i]['total_bedrooms'].median()
... | 5,292,322 |
async def test_if_action(hass, calls):
"""Test for firing if action."""
assert await async_setup_component(hass, automation.DOMAIN, {
automation.DOMAIN: {
'trigger': {
'platform': 'event',
'event_type': 'test_event',
},
'condition': [{
... | 5,292,323 |
def stop():
"""Stops PostgreSQL."""
sudo('service postgresql stop') | 5,292,324 |
def template_used(response, template_name):
"""Asserts a given template was used (with caveats)
First off, this is a gross simplification of what the Django
assertTemplateUsed() TestCase method does. This does not work as a
context manager and it doesn't handle a lot of the pseudo-response
cases.
... | 5,292,325 |
def about(version, program='M_Spec'):
"""
shows program information, author, copyright, version
:param version: version of main script
:param program: default: 'M_Spec', alternative: 'M_Calib'
"""
font = ('Helvetica', 12)
sg.Window(program, [[sg.Text(program, font=('Helvetica', 20))],... | 5,292,326 |
def applyAnimationForOneFile(animPath, destinationFolder, rigPath):
"""
Given the path of an animation file, a rig file, and a destination folder,
applies the animation to the rig using references and parent constraints
and saves the resulting file to the destination folder using the name
rig_with_... | 5,292,327 |
def _sign_trace(s11, s22, s33):
"""Calculate sign of trace. Sign of 0 is set to 1.
Parameters
----------
s11: array_like
Component 11 of 3D tensor.
s22: array_like
Component 22 of 3D tensor.
s33: array_like
Component 33 of 3D tensor.
Returns
-------
numpy.nd... | 5,292,328 |
def read2dlv(filename):
"""Read LabView 2D array and return as numpy array.
Big-endian version.
"""
if isinstance(filename, str):
f = open(filename, 'rb')
else:
f = filename
dims = np.fromstring(f.read(8), dtype=np.dtype('>u4'))
ccd_temp = np.fromstring(f.read(), dtype=np.dt... | 5,292,329 |
def main():
""" main function """
pages = [
Daa(),
BeamNG(),
Cosmoteer(),
Mythologic(),
ProjectZomboid(),
RedditRimWorld(),
RedditUnixporn(),
RedditVim(),
RedditWebdev(),
HackerNoon(),
Freecodecamp()
]
news = News(pages)
news.start() | 5,292,330 |
def test_get_next_interval_weeks_specific_days():
"""Test that we can get the next due date from an interval, frequency, days, and base."""
today = (
datetime.now().astimezone().replace(hour=9, minute=30, second=0, microsecond=0)
)
base_time = time(hour=9, minute=30)
# Start from Monday
... | 5,292,331 |
def ensure_remote(ctx, param, value):
""" Ensure --remote is used. """
# pylint: disable=unused-argument
if value and ctx.params.get('remote') == (None, None):
raise click.BadParameter('Invalid without "-r" / "--remote" option')
return value | 5,292,332 |
def main():
"""
Perform the encryption using the machine from file named MACHINE_FILENAME
and the message from file named MSG_FILENAME. If MODE is 'e', encrypt;
otherwise, decrypt.
"""
prompt = 'Enter the name of the file that contains the enigma machine: '
enigma_file = open(get_valid_filen... | 5,292,333 |
def edit_draft_service(draft_id):
"""
Edit a draft service
:param draft_id:
:return:
"""
updater_json = validate_and_return_updater_request()
update_json = validate_and_return_draft_request()
page_questions = get_request_page_questions()
draft = DraftService.query.filter(
D... | 5,292,334 |
def is_lisp_like(view):
""" Check for a lisp like file using the current language/syntax setting """
return get_dialect(view) != '' | 5,292,335 |
def _execute(cls, app_engine: AppKernelEngine, provisioner_method: Callable, model_class: Model):
"""
The main view function for flask routes.
:param app_engine: the app engine instance
:param provisioner_method: the method on our service object which will be executed by the Flask reflection
:param ... | 5,292,336 |
def get_all_mask_volumes():
"""
Purpose:
Returns all masks for dataset in a single numpy array of 32 bit floats.
Shape will be 259x240x240x155x1
"""
all_patient_paths = get_each_hgg_folder()
# preallocate empty np array to hold all the masks
# dim 0 -> each patie... | 5,292,337 |
def prepare_training_data(sessions):
"""
Convert extracted session into training data
:param sessions: list of sessions
:return:
"""
purchase_sessions = []
abandon_sessions = []
for s in sessions:
# check that purchase action occurs after add action
if Actions.purchase... | 5,292,338 |
def nx_to_graph_data_obj_simple(G, partial_charge=False):
"""
Converts nx graph to pytorch geometric Data object. Assume node indices
are numbered from 0 to num_nodes - 1. NB: Uses simplified atom and bond
features, and represent as indices. NB: possible issues with
recapitulating relative stereoche... | 5,292,339 |
def test_server_exclusion_by_project(network_ids):
"""
Exclude servers using regular expressions.
"""
check = OpenStackControllerCheck("test", {
'keystone_server_url': 'http://10.0.2.15:5000',
'ssl_verify': False,
'blacklist_project_names': ["blacklist*"]
}, {}, instances=com... | 5,292,340 |
def del_dir(path):
"""Recursively delete directory path and all its contents
"""
if os.path.isdir(path):
for file in os.listdir(path):
X = os.path.join(path, file)
if os.path.isdir(X) and not os.path.islink(X):
del_dir(X)
else:
tr... | 5,292,341 |
def after_replace(func, target=None):
"""Request `func` be invoked as `func(self, old)` when `model` is about to
replace an older version of itself. Alternatively when applied to a
collection, request `func(key, old, new)` be invoked.
::
@acid.events.after_replace
def after_replace(sel... | 5,292,342 |
def add_prefix_to_fname(original_fname, prefix):
"""Add a prefix to a given filename.
Examples:
>>> add_prefix_to_fname("data.tif", "London")
"London_data.tif"
"""
file_dir = os.path.dirname(original_fname)
file_basename = os.path.basename(original_fname)
new_basename = "_".join... | 5,292,343 |
def modul(iterand, niterand = 100):
""" A function which allows you to easily check how a for loop is
% progressing by displaying iterand iff it is evenly divided by niterand
Parameters
------------------
iterand:
niterand:
Returns
------------------
Prints iterand if ni... | 5,292,344 |
def construct_sequence(seq_dict):
"""Construct RnaSequence from dict of {pos:residue}.
seq_dict -- dictionary of {position: residue}
Checks whether the first residue is 0. Checks whether all residues
between min and max index are present. No checking on validity of
residue symbols.
"""
... | 5,292,345 |
def _cauchy_ ( self , mu , gamma ) :
"""Generate Cauchy random numbers
- rely on the distribution of the ratio for two Gaussian variables
- see https://en.wikipedia.org/wiki/Cauchy_distribution
"""
g1 = self.gauss ( 0.0 , 1.0 )
while abs ( g1 ) < _fmin : g1 = self.gauss ( 0.0 , 1.0 )
g2 = ... | 5,292,346 |
def aes_mix_column(ctx: typer.Context,
num_traces: int = opt_num_traces,
plot_traces: int = opt_plot_traces):
"""Capture AES traces. Fixed key, Random texts. 4 sets of traces. Mix Column HD CPA Attack.
Attack implemented by ChipWhisperer:
Repo: https://github.com/newaet... | 5,292,347 |
def test_gps_sla_domain_list_when_invalid_input(client, requests_mock, object_type, show_cluster_slas_only,
limit, exception, error):
"""Tests rubrik_gps_sla_domain_list when inputs are invalid."""
from RubrikPolaris import rubrik_gps_sla_domain_list
raw_resp... | 5,292,348 |
def get_group_cpu_name(ifamily, category, device):
"""
Abstract layer to group i3, i5, i7 families.
:param ifamily: which series of cpu we want to group
:param category: category to make sure the input is processor
:param device: device to check
:return: grouped device name
"""
ifamily_... | 5,292,349 |
def main(args: Union[argparse.Namespace, DictConfig, Dict], seed: int = 123):
"""
Fn to initialize the LitniningModul, LightningTrainer
for train , validation & evaluation.
Training, validaiton and evaluation is controled by a .yaml config file
To see an exmaple config file see `main.yaml`.
To ... | 5,292,350 |
def test_to_msw_id_case_insensitive() -> None:
"""Test if resolving works even if case does not match"""
res = spot.to_msw_id("carcavelos")
assert res == 912, \
"to_msw_id() return expected {} but returned {}".format(912, res) | 5,292,351 |
def median(values):
"""Return median value for the list of values.
@param values: list of values for processing.
@return: median value.
"""
values.sort()
n = int(len(values) / 2)
return values[n] | 5,292,352 |
def remove_default_create_options(options):
""" Return only non default create options """
_options = options.copy()
for opt in IPSET_DEFAULT_CREATE_OPTIONS:
if opt in _options and \
IPSET_DEFAULT_CREATE_OPTIONS[opt] == _options[opt]:
del _options[opt]
return _options | 5,292,353 |
def _grid_3d(dx, dy, dz, order):
"""Generate 3D structured grid."""
# Internal functions
def meshgrid(x, y, z, indexing="ij", order=order):
X, Y, Z = numpy.meshgrid(x, y, z, indexing=indexing)
return X.ravel(order), Y.ravel(order), Z.ravel(order)
def mesh_vertices(i, j, k):
retu... | 5,292,354 |
def fix_log(folder: str):
"""Упорядочить даты создания лог файлов"""
regex = re.compile(r'^.*\[(?P<index>\d+)\].*$')
folder = pathlib.Path(folder)
files = list(str(x) for x in folder.glob('*.txt'))
for file in sorted(files, key=lambda x: int(regex.match(x).groupdict()['index'])):
pathlib.Pat... | 5,292,355 |
def title_keywords(title):
"""Given a title, returns every author assigned keyword"""
q = """ SELECT GROUP_CONCAT(keyword)
FROM OriginalKeywords
WHERE ArticleID='{t}'""".format(t=title)
curr.execute(q)
return curr.fetchall()[0][0].split(',') | 5,292,356 |
def collate_fn(batch, transforms):
"""Collate function to be passed to the PyTorch dataloader.
Parameters
----------
batch : list
Uncollated batch of size `batch_size`.
device : str or torch.device
Current working device.
transforms : callable
Transformations to be appli... | 5,292,357 |
def visualize_data(data_dir, X, y, n_classes, output_dir, log):
"""
Data visualization.
Args:
data_dir: Look for the sign names file here.
X: Data values.
y: Data labels.
n_classes: Number of output classes.
output_dir: Save visualization plots to this location.
... | 5,292,358 |
def persistence_function_from_model(model, G_interlayer, layer_vec=None, N=None, T=None, Nt=None):
"""
Returns a function to calculate persistence according to a given multilayer model
:param model: network layer topology (temporal, multilevel, multiplex)
:param G_interlayer: input graph containing all... | 5,292,359 |
def sanitizer(name):
"""
Sanitizes a string supposed to be an entity name. That is,
invalid characters like slashes are substituted with underscores.
:param name: A string representing the name.
:returns: The sanitized name.
:rtype: str
"""
return name.replace("/", "_") | 5,292,360 |
def fget_wcs(fitsfile_path):
"""Get the World coordinate system (wcs) from the fits header for plotting.
Parameters
==========
fitsfile_path: str
The input fits path
Return
======
wcs: `astropy.wcs.wcs.WCS`
Image coordinates in WCS format
"""
hdu = fits.getheade... | 5,292,361 |
def is_repository_setup():
"""Indicates if base repository is setup or not.
"""
return repository_cache.get_value() is not None | 5,292,362 |
def ISURL(value):
"""
Checks whether a value is a valid URL. It does not need to be fully qualified, or to include
"http://" and "www". It does not follow a standard, but attempts to work similarly to ISURL in
Google Sheets, and to return True for text that is likely a URL.
Valid protocols include ftp, http,... | 5,292,363 |
def transaction_class(cls):
"""
Return the associated transaction class for given versioned SQLAlchemy
declarative class or version class.
::
from sqlalchemy_continuum import transaction_class
transaction_class(Article) # Transaction class
:param cls: SQLAlchemy versioned decla... | 5,292,364 |
def check_scaling_parameter(value):
"""Check that the scaling parameter value is valid.
Valid scaling parameter value is:
scaling_parameter > 0
:param value: scaling parameter value.
:type value: float
"""
if not value > 0:
raise ParametersFileErrorInvalidScalingParameter(value) | 5,292,365 |
def get_comp_choice():
"""
This function randomly generates a number between 1 up to and including
the max number of options. If base, it should be 3. If expanded, it
will depend on the number of options and logic you have created.
Returns the integer "chosen" by the computer/randomizer.
"""
... | 5,292,366 |
def test_plant_traits():
"""Test module plant_traits.py by downloading
plant_traits.csv and testing shape of
extracted data has 136 rows and 31 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = plant_traits(test_path)
try:
assert x_train.shape == (136, 31)
except:
shutil.rmtree(te... | 5,292,367 |
def _GenerateRootGradle(jinja_processor):
"""Returns the data for the root project's build.gradle."""
variables = {'template_type': 'root'}
return jinja_processor.Render(_JINJA_TEMPLATE_PATH, variables) | 5,292,368 |
def measure_display_label(src_type):
"""update label upon modification of Radio Items"""
source_label, measure_label = get_source_labels(src_type)
source_unit, measure_unit = get_source_units(src_type)
return 'Measured %s (%s)' % (measure_label, measure_unit) | 5,292,369 |
def only_choice(values):
"""Apply the only choice strategy to a Sudoku puzzle
The only choice strategy says that if only one box in a unit allows a certain
digit, then that box must be assigned that digit.
Parameters
----------
values(dict)
a dictionary of the form {'box_name': '123456... | 5,292,370 |
def cancel_all_open_orders(exchs):
"""
gets and then cancels all open orders on all exchanges
:param exchs: set of exchanges
:return:
"""
try:
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(get_all_open_orders(exchs))
loop.run_until_complete(futur... | 5,292,371 |
def change_to_data_directory(path):
"""chdir so that the current working directory is path"""
try:
os.chdir(path)
except OSError as e:
sys.stderr.write("could not chdir into directory '%s' with errno=%d in call to make_and_change_to_data_directory"%(path,e.errno))
raise
return | 5,292,372 |
def get_xml_storage_model():
"""
Return the configured xml storage model class using apps.get_model()
"""
app, model = acs_settings.XML_STORAGE_MODEL.split(".")
return apps.get_model(
app_label=app,
model_name=model
) | 5,292,373 |
def _get_deployments_digest_by_uid(uid):
""" Get list of deployments for a reference designator; return digests.
(See also event_tools.py, get_deployment_events. Supports asset management Deployment tab.)
"""
results = []
try:
# Get vocabulary dictionary once.
vocab_dict = get_vocab(... | 5,292,374 |
def layout_arc_with_drc_exclude(
cell, layer, drc_layer, center, r, w, theta_start, theta_end, ex=None, **kwargs
):
""" Layout arc with drc exclude squares on sharp corners"""
dpoly = layout_arc(cell, layer, center, r, w, theta_start, theta_end, ex, **kwargs)
dpoly.layout_drc_exclude(cell, drc_layer, ex... | 5,292,375 |
def create_fake_user():
"""
Generate new user and saves to database
"""
user = User.objects.create(username=faker.first_name_male())
return user | 5,292,376 |
def control_brightness(how, level):
"""Control brightness level."""
_change_brightness(how, level)
_send_notification()
return 0 | 5,292,377 |
def has_negative_control(cmd):
"""Return whether a command has negatively controlled qubits."""
return get_control_count(cmd) > 0 and '0' in cmd.control_state | 5,292,378 |
def qg8_graph_load(filename: str):
""""
Load a QG8 graph from file chunk by chunk
"""
f = qg8_file_open(filename, QG8_MODE_READ)
if f is None:
return None
graph = qg8_graph([]) # create empty graph object
i = qg8_file_iterator(f)
while qg8_file_has_next(i): # EOF check
... | 5,292,379 |
def all_reduce(tensor, op=dist.ReduceOp.SUM, group=dist.group.WORLD):
"""
Reduces the tensor data across all machines in such a way that all get
the final result.
After the call the returned tensor is going to be bitwise
identical in all processes.
Arguments:
tensor (Tensor): Input of ... | 5,292,380 |
def _get_stock_ledger_entries(filters):
"""
Get data from Stock Ledger Entries with the following fields:
(1) date, (2) item_code, (3) actual_qty, (4) qty_after_transaction,
(5) project, (6) stock_uom, (7) item_name
:param filters:
:return: Stock Ledger Entries
"""
item_code = filters.ge... | 5,292,381 |
def parse(tokens):
"""Parses the infix permission ``tokens`` into a postfix instruction list.
:param tokens: The token list produced by :func:`~pwh_permissions.tokenise`
:type tokens: ``list``
:return: The token list in postfix notation
:rtype: ``list``
"""
result = []
stack = []
bu... | 5,292,382 |
def _set_search_path(db, conn_db):
"""
pg_restore does not restore the original search_path variable of the
database, which can cause issues with extensions. This function obtains
the original search path and sets it as the search path of the restored
database
https://www.postgresql.org/message... | 5,292,383 |
def load_config(path, dry_run, extras):
"""
load a source file into a dictionary keeping only names that are uppercase and don't start with _
provides some default/initial options and handles missing options.
:param str path: path to the configuration file
:param bool dry_run: if True don't make c... | 5,292,384 |
def roots_legendre_interval(n, a, b):
"""
Computes the sample points and weights for Gauss-Legendre quadrature
on interval `[a, b]`.
The sample points are the roots of the n-th degree Legendre polynomial
`P_n(x)`. These sample points and weights correctly integrate
polynomials of degree `2n - 1... | 5,292,385 |
def get_physical_dependencies(obj: str, lib: str, include_self: bool, job: Optional[IBMJob]=None, verbose: bool=False) -> List[Tuple[str, str, str]]:
"""Get the dependencies for a given physical file object
Args:
obj (str): Object name of the physical file
lib (str): Library name of the physica... | 5,292,386 |
def git_uncommited_changes():
"""
Returns True if the current git branch has uncommitted changes.
"""
p = subprocess.Popen(
['git', 'status'],
)
returncode = p.wait()
return (returncode is not 0) | 5,292,387 |
def register_graphql_schema(graphql_schema):
"""
Register a GraphQL schema class for inclusion in NetBox's GraphQL API.
"""
registry['plugins']['graphql_schemas'].append(graphql_schema) | 5,292,388 |
def compute_counters(data):
"""
Returns the number of times a separator is in each line.
"""
counters = np.zeros((len(data), len(SEPARATORS)))
for i, line in enumerate(data):
counters[i] = [get_character_count(line, sep) for sep in SEPARATORS]
return counters | 5,292,389 |
def mishActivation(x):
""" Mish Activation Function """
return x * tf.math.tanh(tf.math.softplus(x)) | 5,292,390 |
def test_package_d():
"""The package tested contains several decorators."""
path = os.path.join(ASSETS_DIRECTORY, "module_d")
capture = CaptureStdOut()
with capture:
create_report(path)
assert capture.content == """Name Docstrings Missed Covere... | 5,292,391 |
def MagneticDipoleWholeSpace(
XYZ, srcLoc, sig, f, moment, fieldType="b", mu_r=1, eps_r=1, **kwargs
):
"""
Analytical solution for a dipole in a whole-space.
The analytical expression is given in Equation 2.57 in Ward and Hohmann,
1988, and the example reproduces their Figure 2.2.
TODOs:
... | 5,292,392 |
def read_netcdf(path, zvar=None, extent='all', coarsen=1, return_topo=True,
return_xarray=False, verbose=False):
"""
:Input:
- *path* (str) - Path to the file to read, or url to remote file,
or a key into the topotools.remote_topo_urls dictionary.
- *zvar* (str) - variable to... | 5,292,393 |
def make_pretty(wb: openpyxl.Workbook):
"""Applies styles to the given workbook to make it prettier.
This function knows about some XLSForm column names and row types, and
formats them appropriately. It also adds color to highlight the group
structure of the file.
"""
for sheet in wb:
f... | 5,292,394 |
def quantize(v, unit):
"""Quantize value `v` to a multiple of `unit`. When `unit` is an integer,
the return value will be integer as well, otherwise the function will
return a float.
Parameters
----------
v : ndarray or number
Number to be quantized
unit : number
The quantiz... | 5,292,395 |
def _dynamic_rnn_tbe():
"""DynamicRNN TBE register"""
return | 5,292,396 |
def next(dist, median, d1, d2, p, N):
"""
INPUT
dist: distance matrix
median: list of integers for selected vertices
d1: list of nearest facility for each vertex
d2: list of second nearest facility
p: number of facilities to locate
N: number of vertices on the nextwork
OU... | 5,292,397 |
def stop():
"""
Stop the currently running recipe.
:return:
object
response
One of:
ok
error
message
Only present if response is "error" and there is a message to present to the user.
"""
recipes.stop()
return jsonify({... | 5,292,398 |
def visualize_scheduled_protocols():
"""
Function for visualizing the temporal scheduling of a repeater protocol under different path lengths, resource
counts, and link lengths
:return: None
"""
# Iterate over path length
max_num_nodes = 6
max_num_resources = 8
link_lengths = range(5... | 5,292,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.