content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_module_get_attr():
"""Test module getattr behavior."""
import CLR.System as System
int_type = System.Int32
assert is_clr_class(int_type)
module = System.Xml
assert is_clr_module(module)
with pytest.raises(AttributeError):
_ = System.Spam
with pytest.raises(TypeError)... | 5,319,400 |
def normalize_units(data):
"""Normalize units in datasets and their exchanges"""
for obj in data:
obj['unit'] = normalize_units_function(obj.get('unit', ''))
# for param in ds.get('parameters', {}).values():
# if 'unit' in param:
# param['unit'] = normalize_units_function(param['... | 5,319,401 |
def xvalBooklets(dfResp, dfObsResp, configObsList, configRespList):
"""
Cross-validates records for a booklet using data from a ready-made data frames. Returns a data frame containing
extracted responses from the response data table and the reconstructed responses from the observable
data, for selected ... | 5,319,402 |
def imap_any(conditions):
"""
Generate an IMAP query expression that will match any of the expressions in
`conditions`.
In IMAP, both operands used by the OR operator appear after the OR, and
chaining ORs can create very verbose, hard to parse queries e.g. "OR OR OR
X-GM-THRID 111 X-GM-THRID 22... | 5,319,403 |
def format_sources(sources):
"""
Make a comma separated string of news source labels.
"""
formatted_sources = ""
for source in sources:
formatted_sources += source["value"] + ','
return formatted_sources | 5,319,404 |
def test_method_post_not_allowed(flask_app, db_conn, api_version):
"""Test Depot ID not known yet.
Verify the version API does not support HTTP POST and returns HTTP 405 METHOD NOT ALLOWED.
"""
rv = flask_app.delete(url_for('{0}.version_api'.format(api_version)))
assert rv.status_code == 405
as... | 5,319,405 |
def update_dict_to_latex(update_dict, order):
"""Returns update dictionary and order as latex string."""
ret_val = "\\begin{eqnarray*}\n"
get_line = lambda obj: wrap_long_latex_line(latex_print(obj) + "\\\\\n")
for v in reversed(order):
ret_val += latex_print(v) + " &=& "
if isinstance(u... | 5,319,406 |
def setup_base_empty_grade_helper(user: User, unit: models.Unit) -> models.Grade:
"""
Helper method to setup an empty grade before sending a request to the grading
view.
"""
grade = models.Grade(user=user, unit=unit)
grade.status = "sent"
grade.score = None
grade.notebook = None
gra... | 5,319,407 |
def test_cql_filters_function_obj_args(cql_schemas, is_cql):
"""
Assertions for CQL function object arguments schema in OpenAPI 3.0 Document
:param cql_schemas: OpenAPI 3.0 Document schemas
:param is_cql: boolean value
"""
if is_cql:
# assertion for function Object Arguments
ass... | 5,319,408 |
def register_project(fn: tp.Callable = None):
"""Register new project.
Parameters
----------
call
This function will get invoked upon finding the project_path.
the function name will be used to search in $PROJECT_PATHS
"""
def _wrapper():
path = _start_proj_shell(fn.__n... | 5,319,409 |
async def uart_terminal():
"""This is a simple "terminal" program that uses the Nordic Semiconductor
(nRF) UART service. It reads from stdin and sends each line of data to the
remote device. Any data received from the device is printed to stdout.
"""
def match_nus_uuid(device: BLEDevice, adv: Adver... | 5,319,410 |
def tag_word_in_sentence(sentence, tag_word):
"""
Use regex to wrap every derived form of a given ``tag_word`` in ``sentence`` in an html-tag.
Args:
sentence: String containing of multiple words.
tag_word: Word that should be wrapped.
Returns:
: Sentence with replacements.
"""
... | 5,319,411 |
def test_remove_noise():
"""Test remove_noise on toy data"""
# Parameters for fake data
nfreq, npings, nrange_bins = 1, 10, 100
freq = np.arange(nfreq)
ping_index = np.arange(npings)
range_bin = np.arange(nrange_bins)
data = np.ones(nrange_bins)
# Insert noise points
np.put(data, 3... | 5,319,412 |
def get_content_type(response: 'Response') -> str:
"""Get content type from ``response``.
Args:
response (:class:`requests.Response`): Response object.
Returns:
The content type from ``response``.
Note:
If the ``Content-Type`` header is not defined in ``response``,
the... | 5,319,413 |
def _get_file_url_from_dropbox(dropbox_url, filename):
"""Dropbox now supports modifying the shareable url with a simple
param that will allow the tool to start downloading immediately.
"""
return dropbox_url + '?dl=1' | 5,319,414 |
def launch_coef_scores(args):
"""
Wrapper to compute the standardized scores of the regression coefficients, used when computing the number of
features in the reduced parameter set.
@param args: Tuple containing the instance of SupervisedPCABase, feature matrix and response array.
@return: The stan... | 5,319,415 |
def update(
configuration: dict, client: Any, issue: Any, issue_fields: dict, transition: str = None
) -> dict:
"""Updates a Jira issue."""
data = {"resource_id": issue.key, "link": f"{configuration.browser_url}/browse/{issue.key}"}
if issue_fields:
issue.update(fields=issue_fields)
if tra... | 5,319,416 |
def resolve_wishlist_from_user(user: "User") -> Wishlist:
"""Return wishlist of the logged in user."""
wishlist, _ = Wishlist.objects.get_or_create(user=user)
return wishlist | 5,319,417 |
def register_dat_matrix(file_path):
"""
Parse the registration matrix from the given file.
Parse the registration matrix from the given file in register.dat file format. See https://surfer.nmr.mgh.harvard.edu/fswiki/RegisterDat for the file format. The matrix encodes an affine transformation that can be ap... | 5,319,418 |
def lnprob(theta, phi_total_data, f_blue_data, err, corr_mat_inv):
"""
Calculates log probability for emcee
Parameters
----------
theta: array
Array of parameter values
phi: array
Array of y-axis values of mass function
err: numpy.array
Array of error value... | 5,319,419 |
def test_ascii():
"""Test ascii/unicode bar"""
# Test ascii autodetection
with closing(StringIO()) as our_file:
with tqdm(total=10, file=our_file, ascii=None) as t:
assert t.ascii # TODO: this may fail in the future
# Test ascii bar
with closing(StringIO()) as our_file:
... | 5,319,420 |
def test_delete():
"""
Test deleting [4, ] from the following tree:
4
/ \
2 5
/ \\ / \
1 3 6 7
\
8
Test deleting [1, 3] from the following tree:
6
/ \
4 7
/ \\ \
2 5 8
... | 5,319,421 |
def get_car_coordinates(list_points, x_points_traj, y_points_traj):
"""
input:
list_points - car config = phi(last point), length, width, l_base
x_points_traj, x_points_traj - current shifted position(center of back axis)
return:
car_coordinates - list(list)
len(car_coordinates) = 4
"""
list_point... | 5,319,422 |
def create_module(module_name):
"""Function for create a new empty virtual module and register it"""
module = module_cls(module_name)
setattr(module, '__spec__', spec_cls(name=module_name, loader=VirtualModuleLoader))
registry[module_name] = module
return module | 5,319,423 |
def test_generate_variant_json_items(MTParser, inserts):
""" Tests that variant JSON along with columns and facets are produced """
var_props, cols, facs = MTParser.generate_properties(inserts)
# check top level fields
assert var_props['CHROM']['title'] == 'Chromosome'
assert var_props['CHROM']['ty... | 5,319,424 |
async def dump(content: bytes,
filename: str) -> None:
""" Dump content to media file."""
async with aiofiles.open(filename, 'wb') as f:
await f.write(content) | 5,319,425 |
def _days_in_month(month_0: int, year: int) -> int:
""" Returns days in a month (0-indexed). Hope I got this right. """
if month_0 != 1:
return DAYS_IN_MONTH[month_0]
if (year % 4) == 0 and ((year % 100) != 0 or (year % 400) == 0):
return DAYS_IN_MONTH[month_0] + 1
return DAYS_IN_MONTH[... | 5,319,426 |
def create_otfeature( featureName = "calt",
featureCode = "# empty feature code",
targetFont = None,
codeSig = "DEFAULT-CODE-SIGNATURE" ):
"""
Creates or updates an OpenType feature in the font.
Returns a status message in form of a string.
"""
... | 5,319,427 |
def test_trotter_ansatzes_default_initial_params_iterations_2(
ansatz, trotter_algorithm, order, hamiltonian, atol):
"""Check that a Trotter ansatz with two iterations and default parameters
is consistent with time evolution with two Trotter steps."""
objective = HamiltonianObjective(hamiltonian)
... | 5,319,428 |
def test_grid_init(basic_grid):
"""
Test that the grid is properly initialized.
"""
bg = basic_grid
for r in range(bg.height):
for c in range(bg.width):
assert bg[r, c].size == 20
assert bg[r, c].red == 1
assert bg[r, c].green == 2
assert bg[... | 5,319,429 |
def plot_compare_table(image_list, method_list, color_list, compare_dict, fig_name="", fig_num=111):
"""绘制了对比表格."""
row_labels = image_list
# 写入值:
table_vals = []
for i in range(len(row_labels)):
row_vals = []
for method in method_list:
row_vals.append(compare_dict[method... | 5,319,430 |
def waiting():
"""
Show accounts waiting for approval.
"""
whitelist = Whitelist()
print(f"Accounts waiting for approval:")
for account in whitelist.accounts_waiting():
print(f"{account}") | 5,319,431 |
def wilson_ci(num_hits, num_total, confidence=0.95):
""" Convenience wrapper for general_wilson """
z = st.norm.ppf((1+confidence)/2)
p = num_hits / num_total
return general_wilson(p, num_total, z=z) | 5,319,432 |
def s3_download_default_artifact(s3: boto3.resources, bucket: str,
plan: str, branch: str,
hostname: str, port: int, username: str) -> None:
"""
Downloads build artifact for specific plan from default branch.
:param s3: s3 resource
:param... | 5,319,433 |
def convert_to_noun(word, from_pos):
""" Transform words given from/to POS tags """
if word.lower() in ['most', 'more'] and from_pos == 'a':
word = 'many'
synsets = wn.synsets(word, pos=from_pos)
# Word not found
if not synsets:
return []
result = derivational_conversion(word... | 5,319,434 |
def get_slug(obj, title, group):
"""
used to get unique slugs
:param obj: Model Object
:param title: Title to create slug from
:param group: Model Class
:return: Model object with unique slug
"""
if obj.pk is None:
obj.slug = slug_orig = slugify(title)
for x in itertools.count(1):
if not group.objects.fi... | 5,319,435 |
def insert_js_value(cur, jsval):
"""Create Node instances which are inaccessible as of now.
They exist only for the sake of phantoms, and get GCed when we delete phantoms.
"""
def insert_object(obj):
with cur.laying_out('object') as separate:
for key, value in obj.items():
... | 5,319,436 |
def create_link(url):
"""Create an html link for the given url"""
return (f'<a href = "{url}" target="_blank">{url}</a>') | 5,319,437 |
def cummean(x):
"""Return a same-length array, containing the cumulative mean."""
return x.expanding().mean() | 5,319,438 |
def cleanup_expired_jobs(db=None, project=None, max_expire_days=30):
"""Clean up database entries for expired job statuses.
Args:
db: Firestore db instance.
project: GCP project id.
max_expire_days: Maximum expire days for a job.
"""
if not db:
db = firestore.Client(project=project)
jobs_ref... | 5,319,439 |
def validity_range_contains_range(
overall_range: DateRange,
contained_range: DateRange,
) -> bool:
"""
If the contained_range has both an upper and lower bound, check they are
both within the overall_range.
If either end is unbounded in the contained range,it must also be unbounded
in the ... | 5,319,440 |
def find_reference_section_no_title_via_dots(docbody):
"""This function would generally be used when it was not possible to locate
the start of a document's reference section by means of its title.
Instead, this function will look for reference lines that have numeric
markers of the format 1., ... | 5,319,441 |
def get_syntax_errors(graph):
"""List the syntax errors encountered during compilation of a BEL script.
Uses SyntaxError as a stand-in for :exc:`pybel.parser.exc.BelSyntaxError`
:param pybel.BELGraph graph: A BEL graph
:return: A list of 4-tuples of line number, line text, exception, and annotations p... | 5,319,442 |
def run():
"""
If coins.txt has been modified, the new Coin objects will be used.
Otherwise, the previous Coin objects will be updated.
Returns:
None
"""
# TODO: read+write without opening file more than once.
# build a list of Coin objects from the coins.txt file
coins = creat... | 5,319,443 |
def generate_S_tau(t):
"""
Generates the S_tau matrix for a template
Args:
t (np.array): the template vector
Returns:
np.array: the S_tau matrix
"""
t_binning = unique_binning(t)
return generate_S_from_binning(t_binning) | 5,319,444 |
def create_neural_network(input_, output_, reservoir_, spectral_, sparsity_, noise_, input_scale, random_, silent_):
"""Create an Echo State Network.
:rtype: pyESN.ESN
:param input_: number of input units to use in ESN
:param output_: number of output units to use in ESN
:param reservoir_: numb... | 5,319,445 |
def validate_measure_for_asset_changes(asset_type: str, measure: str) -> str:
"""
Validates the range argument for asset changes command
:param asset_type: asset type argument passed by the user
:param measure: measure argument passed by the user
:return: measure if valid else raise ValueError
"... | 5,319,446 |
def update_event_consumer(self):
"""
This function is called when Consumer wants to update the `EventConsumer` doc on Producer
This overrides the frappe function:
frappe.event_streaming.doctype.event_producer.event_producer.EventProducer.update_event_consumer
We are patching this function to update the Con... | 5,319,447 |
def create_incident(**kwargs):
"""
Creates an incident
"""
incidents = cachet.Incidents(endpoint=ENDPOINT, api_token=API_TOKEN)
if 'component_id' in kwargs:
return incidents.post(name=kwargs['name'],
message=kwargs['message'],
statu... | 5,319,448 |
def harvey_two(frequency, tau_1, sigma_1, tau_2, sigma_2, white_noise, ab=False):
"""
Two Harvey model
Parameters
----------
frequency : numpy.ndarray
the frequency array
tau_1 : float
timescale of the first harvey component
sigma_1 : float
amplitude of the first har... | 5,319,449 |
def is_valid_combination( row ):
"""
Should return True if combination is valid and False otherwise.
Test row that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data to validate it.
"""
n = len(row)
if ... | 5,319,450 |
def gen_retrieval(t_all, t_mins, dxvec, drsq, center_ECEF, stations_ECEF,
dt_rms, min_stations=5, max_z_guess=25.0e3):
""" t_all is a N_stations x N_points masked array of arrival times at
each station.
t_min is an N-point array of the index of the first unmasked station
... | 5,319,451 |
def verify_setmem_in_guest(params, env):
"""
"""
pass | 5,319,452 |
def generate_records(jsonDict):
""" Creating Documents for Elasticsearch (XSE)
After loading in the JSON object, this function reformats the JSON to be
acceptable by Elasticsearch.
Limitations: The current script is built specifically for the DAU metadata.
This code will be updated based on requir... | 5,319,453 |
def clmplot(filename: str,
figTitle: str = None,
figWidth: int = 6,
figHeight: int = 7) -> None:
"""
Generates a regression plot on the given dataset and saves it.
Parameters:
filename (str): Name of the dataset to load.
figTitl... | 5,319,454 |
def test_expanse_get_domain(requests_mock):
"""
Given:
- an Expanse client
- arguments (business unit names, limit)
When
- running !expanse-get-domain
Then
- the domains are retrieved and returned to the context as Expanse.Domain
- Domain standard context is prese... | 5,319,455 |
def test_time_delay():
"""Test that time-delaying w/ times and samples works properly."""
# Explicit delays + sfreq
X = rng.randn(2, 1000)
X_sp = np.zeros([2, 10])
X_sp[0, 1] = 1
X_sp = csr_matrix(X_sp)
test_tlims = [((0, 2), 1), ((0, .2), 10), ((-.1, .1), 10)]
for (tmin, tmax), isfreq i... | 5,319,456 |
def get_out_name(subdataset_name_tuple, out_ext=""):
"""
Get output file name for sub dataset
Takes tuple with (subdataset name, description)
"""
subdataset_name = subdataset_name_tuple[0]
outname = os.path.split(subdataset_name)[-1]
outname = outname.replace(".xml","")
outname = outna... | 5,319,457 |
def PinkFilter(c):
"""Returns True if color can be classified as a shade of pink"""
if (c[0] > c[1]) and (c[2] > c[1]) and (c[2] == c[0]): return True
else: return False | 5,319,458 |
def greedy_search(problem, h=None):
"""f(n) = h(n)"""
h = memoize(h or problem.h, 'h')
return best_first_graph_search(problem, h) | 5,319,459 |
def get_callback(request, spider):
"""Get request.callback of a scrapy.Request, as a callable."""
if request.callback is None:
return getattr(spider, 'parse')
return request.callback | 5,319,460 |
def add_plugin(plugins: TDict[Union[str, int], Any], descr: str, instance: Any,
default_id: int = None) -> None:
"""
Add a plugin instance to the plugin dictionary, with the possible alias for
integer plugin IDs; adjust plugin ID and display name; check that there are
no more plugins with... | 5,319,461 |
def veryrandom(msg, min=1, max=6, base=10, num=1):
"""Los datos generados por veryrandom provienen de random.org, lo cual
es una garantía adicional de la aleatoriedad de los resultados. Se
obtendrá un número aleatorio entre los 2 definidos, ambos inclusive.
"""
url = 'http://www.random.org/integers/... | 5,319,462 |
def safe_remove(fn):
"""Remove file skipping
"""
if os.path.exists(fn):
if os.path.isfile(fn):
os.remove(fn)
elif os.path.isdir(fn):
shutil.rmtree(fn) | 5,319,463 |
def read_configuration(start_path, configuration_filename):
"""Return compiler options from configuration.
Return None if there is no configuration.
"""
configuration_path = find_configuration(
os.path.abspath(start_path),
configuration_filename=configuration_filename)
raw_lines =... | 5,319,464 |
def set_beams(n1, n2, symb: list):
"""
There is something that has to be fixed. Note the last_note and j.
:return:
"""
# separate words at notes without flags
start_flag = False
last_note = -1
for i in range(n1, n2):
if symb[i].type == NOTE:
if start_flag:
... | 5,319,465 |
def clean_documents(documents: Union[List[str], Dict[str, str]], **kwargs) -> Union[Sequence[str], Dict[str, str]]:
"""Seaches for `Filth` in `documents` and replaces it with placeholders.
`documents` can be in a dict, in the format of ``{'document_name': 'document'}``, or as a list of strings
(each a sepe... | 5,319,466 |
async def test_default_availability_payload(opp, mqtt_mock):
"""Test availability by default payload with defined topic."""
config = {
scene.DOMAIN: {
"platform": "mqtt",
"name": "test",
"command_topic": "command-topic",
"payload_on": 1,
}
}
... | 5,319,467 |
def calcShannonEnt(dataSet):
"""
计算香农熵,用于判断划分
Parameters
----------
dataSet:数据集(可能是原始数据集,有可能是划分子集)
Returns:数据集的信息熵,根据分类标签信息确定
-------
"""
from math import log
numEntries = len(dataSet) # 数据总量
labelCounts = {} # 创建一个数据字典,用来计数各个类别
for featVec in dataSet.values: # 每次取一行... | 5,319,468 |
def Disc(
pos=(0, 0, 0),
r1=0.5,
r2=1,
c="coral",
alpha=1,
res=12,
resphi=None,
):
"""
Build a 2D disc of internal radius `r1` and outer radius `r2`.
|Disk|
"""
ps = vtk.vtkDiskSource()
ps.SetInnerRadius(r1)
ps.SetOuterRadius(r2)
ps.SetRadialResolution(res)
... | 5,319,469 |
def identity_block(x, n_filters):
""" Construct a Bottleneck Residual Block with Identity Link
x : input into the block
n_filters: number of filters
"""
# Save input vector (feature maps) for the identity link
shortcut = x
## Construct the 1x1, 3x3, 1x1 residual block (fi... | 5,319,470 |
def makeDarker(color: colors.Color) -> colors.Color:
"""
Takes a color and returns a slightly darker version of the
original color.
:param Color color: the color you want to darken
:return: the new, darker color
:rtype: Color
:raises TypeError: if ``color`` is not a :py:class:`~.colors.Colo... | 5,319,471 |
def parse_evaluations(evals, courses):
"""
Adds attributes to each course based on eval data in the given dictionary.
"""
for i, course_attribs in enumerate(courses):
subject_id = course_attribs[CourseAttribute.subjectID]
if subject_id not in evals:
continue
averagi... | 5,319,472 |
def multi_indices(n):
"""Return the list of all multi-indices within the specified bounds.
Return the list of multi-indices ``[b[0], ..., b[dim - 1]]`` such that
``0 <= b[i] < n[i]`` for all i.
"""
iterables = [range(ni) for ni in n]
return [np.asarray(b, dtype=np.intc)
for b in it... | 5,319,473 |
def removeProject(info, project):
"""
Removing an docker stack for the current project
if the checkIfComposerExistsBool == TRUE
else perform `docker rm`
:param info:
:param project:
:return:
"""
print(project)
if checkIfComposerExistsBool(project):
return "dock... | 5,319,474 |
def columnize_as_rows(lis, columns, horizontal=False, fill=None):
"""Like 'zip' but fill any missing elements."""
data = distribute(lis, columns, horizontal, fill)
rowcount = len(data)
length = max(len(x) for x in data)
for c, lis in enumerate(data):
n = length - len(lis)
if n > 0:
... | 5,319,475 |
def single_extra_atom_line_v3000_sdf(tmp_path: Path) -> Path:
"""Write a single molecule to a v3000 sdf with an extra atom line.
Args:
tmp_path: pytest fixture for writing files to a temp directory
Returns:
Path to the sdf
"""
sdf_text = """
0 0 0 0 0 999 V300... | 5,319,476 |
def add_metaclass(metaclass): # pragma: no cover
""" Class decorator for creating a class with a metaclass.
Copied from six
"""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
for slots_var in orig_... | 5,319,477 |
def make_animation():
"""
Good example between 1.272 1.302
because collision
"""
dataio = DataIO(dirname=dirname)
catalogue = dataio.load_catalogue(chan_grp=0)
clusters = catalogue['clusters']
sr = dataio.sample_rate
# also a good one a 11.356 - 11.366
... | 5,319,478 |
def vzerog(v):
"""vzerog(ConstSpiceDouble * v) -> SpiceBoolean"""
return _cspyce0.vzerog(v) | 5,319,479 |
def read_barcodes(barcodes_file: Path) -> dict:
"""
Read in barcodes from file
:param barcodes_file: path to csv file with barcodes and gene name
:return barcode_dict:
barcode_dict = {
barcode_1 : {"gene": Gene_1, "count": 0}
barcode_2 : {"gene": Gene_2, "count": 0}
}
"""
... | 5,319,480 |
def is_localized(node):
"""Check message wrapped by _()"""
if isinstance(node.parent, compiler.ast.CallFunc):
if isinstance(node.parent.node, compiler.ast.Name):
if node.parent.node.name == '_':
return True
return False | 5,319,481 |
def skip(count: int) -> Callable[[Iterable[_TSource]], Iterable[_TSource]]:
"""Returns a sequence that skips N elements of the underlying
sequence and then yields the remaining elements of the sequence.
Args:
count: The number of items to skip.
"""
def _skip(source: Iterable[_TSource]) -> ... | 5,319,482 |
def on_connect(mosq, userdata, flags, rc):
"""
Upon successfully being connected, we subscribe to the check_topic
"""
mosq.subscribe(args.check_subscription, 0) | 5,319,483 |
def train(model, dataset_dir, subset):
"""Train the model."""
# Training dataset.
dataset_train = MitosisDataset()
dataset_train.load_mitosis(dataset_dir, subset)
dataset_train.prepare()
# Image augmentation
# http://imgaug.readthedocs.io/en/latest/source/augmenters.html
augmentatio... | 5,319,484 |
def test_load_fails_no_shell(install_mockery, mock_fetch, mock_archive,
mock_packages):
"""Test that spack load prints an error message without a shell."""
install('mpileaks')
out = load('mpileaks', fail_on_error=False)
assert "To set up shell support" in out | 5,319,485 |
async def send_denial(ctx: Context, reason: str) -> None:
"""Send an embed denying the user with the given reason."""
embed = discord.Embed()
embed.colour = discord.Colour.red()
embed.title = random.choice(NEGATIVE_REPLIES)
embed.description = reason
await ctx.send(embed=embed) | 5,319,486 |
def upload_to_nomad(nomad_configfile, num, mongo_configfile):
"""
upload n launchers to NOMAD using the following procedure
1. Find n launchers and split them into 10 threads
2. upload those n launchers and remove the generated .tar.gz file
:param nomad_configfile: nomad user name and password json... | 5,319,487 |
def model_fn(model_dir):
"""
Load the gluon model. Called once when hosting service starts.
:param: model_dir The directory where model files are stored.
:return: a model (in this case a Gluon network)
assumes that the parameters artifact is {model_name}.params
"""
os.environ["MXNET_CUDNN_A... | 5,319,488 |
def init_db(uri, echo=True):
"""Initialize the database and reflect the tables"""
global meta
uri = make_url(uri)
uri.query.setdefault("charset", "utf8")
engine = create_engine(uri, echo=echo)
meta.bind = engine
Session.configure(bind=engine)
reflect_tables()
return engine | 5,319,489 |
def test_pad_with_identity():
"""Test that pad_with_identity inserts identity channels correctly"""
A = CircuitSymbol('A', cdim=1)
B = CircuitSymbol('B', cdim=1)
res = pad_with_identity(A+B, 1, 2)
expected = A + cid(2) + B
assert res == expected | 5,319,490 |
def get_weighted_average(We, x, w):
"""
Compute the weighted average vectors
:param We: We[i,:] is the vector for word i
:param x: x[i, :] are the indices of the words in sentence i
:param w: w[i, :] are the weights for the words in sentence i
:return: emb[i, :] are the weighted average vector f... | 5,319,491 |
def logout_user_cleanup():
"""Logs out user."""
print("\n\nGot to logout from: {}".format(request.referrer))
logout_user()
session.clear()
flash("You were logged out!")
return redirect(request.referrer) | 5,319,492 |
def read_vtk_sowfa(filename):
"""
Reads SOWFA results .vtk file and returns coordinates of cell centres and velocity field as numpy arrays.
:param filename:
:return:
"""
reader = vtk.vtkPolyDataReader()
reader.SetFileName(filename)
reader.Update()
data = reader.GetOutput()
u = v... | 5,319,493 |
def compute_primary_orientations(primary_segments, angle_epsilon=0.1):
"""
Computes the primary orientations based on the given primary segments.
Parameters
----------
primary_segments : list of BoundarySegment
The primary segments.
angle_epsilon : float, optional
Angles will be... | 5,319,494 |
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
config = Configurator(settings=settings)
config.include('pyramid_chameleon')
config.include('pyramid_debugtoolbar')
# home
config.add_route('index', '/')
# Documentos da Colecao:
config.add... | 5,319,495 |
def trigger_web_jobs(jenkins_url, environment, chef_action, bag_name):
"""
Trigger a mass web job based on environment
:param environment - Which environment would you like to try executing this job on?
:param chef_action - What would you like to perform on this environment?
:param bag_name - Option... | 5,319,496 |
def plot_contribution_map(contribution_map, ax=None, vrange=None, vmin=None, vmax=None, hide_ticks=True, cmap="bwr",
percentile=100):
"""
Visualises a contribution map, i.e., a matrix assigning individual weights to each spatial location.
As default, this shows a contribution map w... | 5,319,497 |
def pac_mvl(z):
""" Calculate PAC using the mean vector length.
Parameters
----------
ang: array_like
Phase of the low frequency signal.
amp: array_like
Amplitude envelop of the high frequency signal.
Returns
-------
out: float
The pac strength using the mean v... | 5,319,498 |
def merge_values(list1, list2):
"""Merge two selection value lists and dedup.
All selection values should be simple value types.
"""
tmp = list1[:]
if not tmp:
return list2
else:
tmp.extend(list2)
return list(set(tmp)) | 5,319,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.