content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def linearly_spaced_combinations(bounds, num_samples):
"""
Return 2-D array with all linearly spaced combinations with the bounds.
Parameters
----------
bounds : sequence of tuples
The bounds for the variables, [(x1_min, x1_max), (x2_min, x2_max), ...]
num_samples : integer or array_lik... | 4d493290ae5c8af91f2f0dce5041c12c22bb6aaa | 569 |
from typing import Optional
from typing import Tuple
def flatten_expressions_tree(
expression: Optional[Expression]) -> Tuple[Expression, ...]:
"""
Flatten expressions tree into a list.
"""
if not expression:
return tuple()
expressions = [expression]
for arg in expression.argu... | dea87f37663e995a74b7709b3dbb62d5cc370f50 | 570 |
def policy_head(x, mode, params):
"""
The policy head attached after the residual blocks as described by DeepMind:
1. A convolution of 8 filters of kernel size 3 × 3 with stride 1
2. Batch normalisation
3. A rectifier non-linearity
4. A fully connected linear layer that outputs a vector of size... | 8e8418ffd46857cf03921ea516729d15a0ef5ca9 | 571 |
def _get_word_ngrams(n, sentences):
"""Calculates word n-grams for multiple sentences.
"""
assert len(sentences) > 0
assert n > 0
words = sum(sentences, [])
return _get_ngrams(n, words) | 73640beb269895d7c54d21825135908eba3f3bd4 | 573 |
from typing import List
def override_list(base_list: List, dynamic_key: str, val):
"""
Customize the base list by updating with the
dynamic_key and val.
Parameters
----------
base: dict
Dictionary or List to be customized with dynamic args
dynamic_key: str
Key to identify ... | eb7e4a0462d2db82cb1900784b5d99e2865dcc00 | 574 |
def c_components(DAG):
"""Return a list of the maximal c-component node sets in DAG."""
G = nx.Graph();
G.add_nodes_from(observable_nodes(DAG))
G.add_edges_from([(u,v) for u,v in observable_pairs(DAG) if
has_confounded_path(DAG, u, v)])
return list(nx.connected_components(G)) | 85c4ae4ee7b9572e31727f672864e4b079e3bde7 | 575 |
def wss_over_number_of_clusters(data, algorithm='kmeans',
max_iter=100, num_repeats = 5, max_num_clusters = 12,
plot_file = None):
"""
Calculates the within-sum-of-squares (WSS) for different numbers of clusters,
averaged over several iteratio... | fa00e00a5b0ba53b4b578fae04c43c69500d2d97 | 576 |
from typing import List
from typing import Tuple
def separate_classes(x: np.ndarray, y: np.ndarray) -> List[Tuple[int, np.ndarray]]:
"""Separate samples by classes into a list.
Args:
x (np.ndarray): Samples.
y (np.ndarray): Target labels (classes).
Returns:
List[Tuple[int, np.nda... | ee0a93b44785f6f017769da6fd6f1cc65f9cf121 | 577 |
import time
from datetime import datetime
def monitor_threads(threads, arguments):
"""
Monitor the threads.
Parameters
----------
threads: dict
The threads to monitor.
arguments: namespace
The parsed command line.
# --GT-- not used, kept to avoid to break the function ... | fa0e1f329cb70eb1fd81c74c9ec555921cab9041 | 578 |
def fetch_cfr_parts(notice_xml):
""" Sometimes we need to read the CFR part numbers from the notice
XML itself. This would need to happen when we've broken up a
multiple-effective-date notice that has multiple CFR parts that
may not be included in each date. """
parts = []
for cfr_el... | d4fc1be9004f5a670c58dc3badaef80d53f73fc4 | 579 |
def get_dayofweek(date):
"""
Returns day of week in string format from date parameter (in datetime format).
"""
return date.strftime("%A") | 4a0f728733870998331ea6f796b167b9dd3276ab | 580 |
def add_model_output(modelIn, mode=None, num_add=None, activation=None):
""" This function modifies the last dense layer in the passed keras model. The modification includes adding units and optionally changing the activation function.
Parameters
----------
modelIn : keras model
Keras model... | 2b869477bb67f7349569d15e0ada229cc1400e39 | 581 |
def parse(f):
"""Parse ASDL from the given file and return a Module node describing it."""
parser = ASDLParser()
return parser.parse(f) | ca6b97c2181444dd7325877d67d74bb894c1bfef | 582 |
def distance(xyz, lattice, PBC=[1,2,3]):
"""
Returns the Euclidean distance from the origin for a fractional
displacement vector. Takes into account the lattice metric and periodic
boundary conditions, including up to one non-periodic axis.
Args:
xyz: a fractional 3d displacement vector... | e6a6a925773b35996cc5f71982b72aeaef25cc4f | 583 |
def dobro(n=0, formato=False):
"""
Dobrar número
:param n: número a ser dobrado
:param formato: (opicional) mostrar o moeda
:return: resultado
"""
n = float(n)
n += n
return moeda(n) if formato else n | f01267cf432d48ab263d90756fd920c7d6d987a1 | 584 |
def f_q2d(n, m):
"""Lowercase f term for 2D-Q polynomials. oe-20-3-2483 Eq. (A.18b).
Parameters
----------
n : int
radial order
m : int
azimuthal order
Returns
-------
float
f
"""
if n == 0:
return np.sqrt(F_q2d(n=0, m=m))
else:
ret... | 52919fab40e51dfa8ba89eb1d6f97ec733ce9de5 | 585 |
def binary_search(data, target, low, high):
"""Return position if target is found in indicated portion of a python list and -1 if target is not found.
"""
if low > high:
return -1
mid = (low + high) // 2
if target == data[mid]:
return mid
elif target < data[mid]:
# recur... | 8f85596e4ff8971f4002b2f108c9c276304924be | 586 |
def delete_position(id):
"""Delete a post.
Ensures that the post exists and that the logged in user is the
author of the post.
"""
db = get_db()
db.execute('DELETE FROM gatekeeping WHERE id = ?', (id,))
db.commit()
return jsonify(status='ok') | cf5d6580eea191a0d17d1a98e2f86a8610a5f58a | 587 |
import struct
def read_string(stream, length):
"""read data from the file and return as a text string
"""
text = struct.unpack('{}s'.format(length), stream.read(length))
try:
result = str(text[0], encoding='utf-8')
except UnicodeDecodeError:
result = str(text[0], encoding='latin-1'... | da8ddf04ea6c0232e59c4612105a243a5c1807d4 | 588 |
import math
def generate_gate_y_hamiltonian_vec() -> np.ndarray:
"""Return the vector representation for the Hamiltonian of a Y gate with respect to the orthonormal Hermitian matrix basis with the normalized identity matrix as the 0th element.
The result is a real vector with size 4.
Parameters
----... | 0a290c8f4a2c0acd81439caa4e5c4a7032a91d83 | 589 |
def _semi_implicit_midpoint(ode_fun, jac_fun, y_olds, t_old, f_old, dt, args,
solver_parameters, J00, I):
"""
Calculate solution at t_old+dt using the semi-implicit midpoint
formula. Based on equations IV.9.16a-b of Ref II.
"""
y_older, y_old = y_olds
je_tot=0
i... | 7807427e64d4348eb4deb4624d1db5e4df0226ca | 590 |
from tensorflow.python.framework.graph_util import (
convert_variables_to_constants,
remove_training_nodes,
)
def freeze_session(session,
keep_var_names=None,
output_names=None,
clear_devices=True):
"""
Freezes the state of a session int... | 3617fc93a1727fcabf128622fcaf0e8dd5008b24 | 591 |
def get_system_cpu_times():
"""Return system CPU times as a namedtuple."""
user, nice, system, idle = _psutil_osx.get_system_cpu_times()
return _cputimes_ntuple(user, nice, system, idle) | c2edb6c0b87449c31aba1fe023736e30cdf41154 | 592 |
def Mce1(m, q, ξ, *, p=0):
"""
v = Mce1(m, q, ξ, *, p=0)
Compute the value of the even Radial Mathieu function of the first kind
Mce⁽¹⁾ₘ(q, ξ).
Parameters
----------
m : array_like
interger order of the Mathieu function
q : array_like
positive parameter in the Mathieu d... | 7a5c7fc6b9a9380c5d763f1773a26516345e5a3b | 593 |
def profileown():
"""Display user's profile"""
return render_template("profile.html", user=session, person=session, books=None) | 83ac3e78fb2f3b43596874c8208099d041536ebb | 594 |
def GetChildConfigListMetadata(child_configs, config_status_map):
"""Creates a list for the child configs metadata.
This creates a list of child config dictionaries from the given child
configs, optionally adding the final status if the success map is
specified.
Args:
child_configs: The list of child co... | 621fa06eb0055a2dec1941bb4fd84ecb8fd6847c | 595 |
def get_samples(df, selected_rows, no_of_samples, records_in_db):
""" get samples without shuffling columns """
df_fixed = None
df_random = None
generic_data_dict = []
#drop rows with 'ignore' set to 'yes'
if 'ignore' in df.columns:
df = df[df["ignore"] != "yes"]
df = df.drop(['i... | 16b13d59e50ebcb16e65feea41bc801b1e8b87b8 | 596 |
def update_member_names(oldasndict, pydr_input):
"""
Update names in a member dictionary.
Given an association dictionary with rootnames and a list of full
file names, it will update the names in the member dictionary to
contain '_*' extension. For example a rootname of 'u9600201m' will
be repl... | 364a4bdd742fe03545e9bb4fb72ef996beea1550 | 597 |
def part1(entries: str) -> int:
"""part1 solver take a str and return an int"""
houses = {(0, 0): 1}
pos_x, pos_y = 0, 0
for direction in entries:
delta_x, delta_y = moves[direction]
pos_x += delta_x
pos_y += delta_y
houses[(pos_x, pos_y)] = houses.get((pos_x, pos_y), 0) ... | 104cf7b32ec9f395603a32f57b146129d30a417b | 598 |
def quantile_compute(x, n_bins):
"""Quantile computation.
Parameters
----------
x: pd.DataFrame
the data variable we want to obtain its distribution.
n_bins: int
the number of bins we want to use to plot the distribution.
Returns
-------
quantiles: np.ndarray
th... | 4c23b417bb8c9e99709fca2371e476e4edadfeec | 600 |
def remove_separators(version):
"""Remove separator characters ('.', '_', and '-') from a version.
A version like 1.2.3 may be displayed as 1_2_3 in the URL.
Make sure 1.2.3, 1-2-3, 1_2_3, and 123 are considered equal.
Unfortunately, this also means that 1.23 and 12.3 are equal.
Args:
vers... | c29b9e7ca84705a9f36123ff0d84e3beb24468bf | 601 |
def parse_coverage_status(status):
"""Parse a coverage status"""
return Status.HIT if status.upper() == 'SATISFIED' else Status.MISSED | 8a295b3df2d10b7813ce0efc96331607da5ba1b9 | 602 |
def max_index(list):
"""Returns the index of the max value of list."""
split_list = zip(list, range(len(list)))
(retval, retI) = reduce(lambda (currV, currI), (nV, nI):
(currV, currI) if currV > nV
else (nV, nI), split_list)
return retI | 43e15edbc227b13db3d468b4ee8d030770d5f1a2 | 603 |
def mask_coverage(coverage: mx.sym.Symbol, source_length: mx.sym.Symbol) -> mx.sym.Symbol:
"""
Masks all coverage scores that are outside the actual sequence.
:param coverage: Input coverage vector. Shape: (batch_size, seq_len, coverage_num_hidden).
:param source_length: Source length. Shape: (batch_si... | d2594a12a78d604c26588218f8b084bf5c18d2ac | 604 |
def DFS_complete(g):
"""Perform DFS for entire graph and return forest as a dictionary.
Result maps each vertex v to the edge that was used to discover it.
(Vertices that are roots of a DFS tree are mapped to None.)
"""
forest = {}
for u in g.vertices():
if u not in forest:
forest[u] = None ... | ec141354d41cf87381db841e6adf8e888a573494 | 605 |
def _transform_p_dict(p_value_dict):
"""
Utility function that transforms a dictionary of dicts into a dataframe representing the dicts as rows
(like tuples). Is needed to keep track of the feature names and corresponding values.
The underlying datastructures are confusing.
:param p_value_dict: dic... | 154ce78ae03267ce69254ff583ca0b736d62d435 | 606 |
import torch
from typing import Optional
def iou(
predict: torch.Tensor,
target: torch.Tensor,
mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
"""
This is a great loss because it emphasizes on the active
regions of the predict and targets
"""
dims = tuple(range(predict.dim())[1... | 7608189bde3b640a8f148e3628e5668a3b310655 | 607 |
import re
def get_sequence(seq_id):
"""
TO DO:
1. redirection 303. (not tested in compliance_suite)
2. Note: compliance_suite ignores the range if it is out of bounds or if > SUBSEQUENCE_LIMIT
3. Ambiguous error code resolution in refget documentation:
range:
The server MUST r... | d0d10c1c491d32ffc70c5579330163bee11d5a15 | 608 |
def getCondVisibility(condition):
"""
Returns ``True`` (``1``) or ``False`` (``0``) as a ``bool``.
:param condition: string - condition to check.
List of Conditions: http://wiki.xbmc.org/?title=List_of_Boolean_Conditions
.. note:: You can combine two (or more) of the above settings by using "+" a... | 761914696ac2050c6bf130e5b49221be043903bd | 609 |
def history_cumulative(request):
"""
This endpoints returns the number of cumulative infections for each area given a date in history.
"""
days = int(request.query_params.get("days"))
observed = Covid19DataPoint.objects.all()
historyDate = max([d.date for d in observed]) - timedelta(days=-days)
... | 7ecdf3e41304d99b11e7695e2962dbe3b7f6c96a | 611 |
def check_partial(func, *args, **kwargs):
"""Create a partial to be used by goodtables."""
new_func = partial(func, *args, **kwargs)
new_func.check = func.check
return new_func | 55a723bc81e5666db9fdd97a4ea88d36635e3dc3 | 612 |
def mcas(mc, entries):
"""Multi-entry compare-and-set.
Synopsis:
>>> from memcache_collections import mcas
>>> mc = memcache.Client(['127.0.0.1:11211'], cache_cas=True)
>>> # initialize a doubly-linked list with two elements
>>> mc.set_multi({
... 'foo': {'next': 'bar'},
... 'bar': ... | 741cbc4d9962292fc544b945785a72cc25060d5b | 613 |
def figure_8s(N_cycles=2, duration=30, mag=0.75):
"""
Scenario: multiple figure-8s.
Parameters
----------
N_cycles : int
How many cycles of left+right braking.
duration : int [sec]
Seconds per half-cycle.
mag : float
Magnitude of braking applied.
"""
on = [(2... | 3bb485b23ea337b038a52fa946b5080cb8ae79eb | 614 |
import inspect
def grad_ast(func, wrt, motion, mode, preserve_result, verbose):
"""Perform AD on a single function and return the AST.
Args:
See `grad`.
Returns:
node: The AST of a module containing the adjoint and primal function
definitions.
required: A list of non-built in functions tha... | 1b358f36fb73169fa31bfd3266ccfae172980178 | 615 |
import re
def sortRules(ruleList):
"""Return sorted list of rules.
Rules should be in a tab-delimited format: 'rule\t\t[four letter negation tag]'
Sorts list of rules descending based on length of the rule,
splits each rule into components, converts pattern to regular expression,
and appends... | 5b98903fd48f562d22e0ce269aa55e52963fa4a9 | 616 |
def v3_settings_response():
"""Define a fixture that returns a V3 subscriptions response."""
return load_fixture("v3_settings_response.json") | 909d538388dde838bc57d6084c98db40b24db4f8 | 617 |
def Geom2dLProp_Curve2dTool_FirstParameter(*args):
"""
* returns the first parameter bound of the curve.
:param C:
:type C: Handle_Geom2d_Curve &
:rtype: float
"""
return _Geom2dLProp.Geom2dLProp_Curve2dTool_FirstParameter(*args) | f9dea146d3e9002c17cddd3f60ff6fe5362a1268 | 618 |
def decode_regression_batch_image(x_batch, y_batch, x_post_fn = None, y_post_fn = None, **kwargs):
"""
x_batch: L or gray (batch_size, height, width, 1)
y_batch: ab channel (batch_size, height, width, 2)
x_post_fn: decode function of x_batch
y_post_fn: decode function of y_batch
"""
a... | 270c0b60646c0d16f8f8a4f3f2d5933bef369e3e | 619 |
def get_mag_from_obs(h, e, d0=0):
"""gets the magnetic north components given the observatory components.
Parameters
__________
h: array_like
the h component from the observatory
e: array_like
the e component from the observatory
d0: float
the declination baseline angle ... | 27f4d538c3a9e13522f195bd9abb2683037ba72a | 620 |
def set_cell(client, instance, colid, value, file_=None):
"""Set the value of one cell of a family table.
Args:
client (obj):
creopyson Client.
instance (str):
Family Table instance name.
colid (str):
Column ID.
value (depends on data type):
... | b1617484a3a710046cda5daaf6bbe9b376f83418 | 622 |
def find_bounds(particles):
"""
Find the maximum and minimum bounds describing a set of particles.
"""
min_bound = np.array(
[np.min(particles[:, 0]), np.min(particles[:, 1]), np.min(particles[:, 2])]
)
max_bound = np.array(
[np.max(particles[:, 0]), np.max(particles[:, 1]), np.... | 2640ce6aa79cbe4392d2e044bddf46a94f6b76af | 623 |
def get_tags_date(link, default_date=None):
"""Extract tags and date from the link."""
tags = ["links"]
date = ""
fltr = [
"Bookmarks Menu",
"Bookmark Bar",
"Personal Toolbar Folder",
"Importierte Lesezeichen",
"Bookmarks Toolbar",
"Kein Label vorhanden",
... | b9f28a1f2f819cdfcc794ce3dc507ff4df288906 | 624 |
from datetime import datetime
def _is_future(time, time_ref=None):
"""
check if `time` is in future (w.r.t. `time_ref`, by default it is now)
Parameters
----------
time : int or datetime
the time to check (if int it's considered a
timestamp, see :py:meth:`datetime.timestamp`)
... | ece5121ee0e49c77a260b117cb0f251a35aa289b | 625 |
from datetime import datetime
def create_and_train_model(x_learn, y_learn, model, n_cores):
"""General method to create and train model"""
print(model.fit(x_learn, y_learn))
start_time = datetime.now()
c_val = cross_val_score(model, x_learn, y_learn, cv=10, n_jobs=n_cores)
end_time = datetime.now(... | babef20c893c39a09fe4a0e0f777b2ec326b694c | 626 |
def cardidolizedimageurl(context, card, idolized, english_version=False):
"""
Returns an image URL for a card in the context of School Idol Contest
"""
prefix = 'english_' if english_version else ''
if card.is_special or card.is_promo:
idolized = True
if idolized:
if getattr(card... | c69e1a4d998d632091fcf1d69a240d68386e0b21 | 627 |
def extract_simple_tip(e):
"""
"""
emin = e.min()
emax = e.max()
indices = [nearest_index(emin), nearest_index(emax)]
indices.sort()
imin,imax = indices
imax +=1 # for python style indexing
return imin, imax | c3d215ee34caa733a83b8be54cc92f9071839bef | 628 |
def parse_pipeline_config(pipeline_config_file):
"""Returns pipeline config and meta architecture name."""
with tf.gfile.GFile(pipeline_config_file, 'r') as config_file:
config_str = config_file.read()
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
text_format.Merge(config_str, pipeline_config)
... | 4e7047c2e7b195bce8cadf83fa19e1b7c1cb16ca | 629 |
import math
def get_pwl(time_series, pwl_epsilon):
""" This is a wrapper function for getting a bounded piecewise linear approximation of the data """
if not isinstance(pwl_epsilon, (int, float)):
raise TypeError("pwl_epsilon must be a numeric type!")
if not (isinstance(time_series, pd.DataFrame... | 431d83e59e4f3faa3cbe7f21106690f030330529 | 630 |
def to_array(string):
"""Converts a string to an array relative to its spaces.
Args:
string (str): The string to convert into array
Returns:
str: New array
"""
try:
new_array = string.split(" ") # Convert the string into array
while "" in new_array: # Check if th... | 7ee87a2b245a71666939e9ce2e23dc07fcaa0153 | 631 |
def convert_atoms_to_pdb_molecules(atoms: t.List[Atom]) -> t.List[str]:
"""
This function converts the atom list into pdb blocks.
Parameters
----------
atoms : t.List[Atom]
List of atoms
Returns
-------
t.List[str]
pdb strings of that molecule
"""
# 1) GROUP... | 3f073818b92ce1db7b2e8c4aaf0724afb546beba | 632 |
def unvoiced_features(sig,fs,vcont,sil_cont):
"""
Unvoiced segment features.
Requires voiced and silence/pauses segment detection.
"""
#Unvoiced features
uv_seg,_,_ = unvoiced_seg(sig,fs,vcont,sil_cont)
lunvoiced = []
for uv in uv_seg:
lunvoiced.append(len(uv)/fs)#Length of ... | bb6f5fc0c939a7d838140b7a7eadda2ff32e5592 | 633 |
def civic_methods(method001, method002, method003):
"""Create test fixture for methods."""
return [method001, method002, method003] | 63913e2cfe866c65d9a1e7d5d3ba2e081b8e12f6 | 634 |
def _generate_tags(encoding_type, number_labels=4):
"""
:param encoding_type: 例如BIOES, BMES, BIO等
:param number_labels: 多少个label,大于1
:return:
"""
vocab = {}
for i in range(number_labels):
label = str(i)
for tag in encoding_type:
if tag == 'O':
if ... | 36125c684be9dc1d0abc522d536276be7e3d7328 | 635 |
def delete_link_tag(api_client, link_id, tag_key, **kwargs): # noqa: E501
"""delete_link_tag # noqa: E501
Delete link tag by key
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> response = await api.delete_link_tag(clie... | 5e643eaa02b50a733030ac35da5821a494ee2517 | 636 |
def infect_graph(g, title):
"""
Function to infect the graph using SI model.
Parameters:
g: Graph
Returns:
G : Infected graph
t : Time of diffusion of each node
"""
G=g
# Model selection - diffusion time
model = ep.SIModel(G)
nos = 1/len(G)
# Model Configuration
config = mc.Configurat... | b0c3f5d2518083cabf4de4214acf65027fc623f5 | 637 |
def main_func_SHORT():
""" Func. called by the main T """
sleep(SHORT)
return True | de5cffd80a74a048f0016e5912dd15b93f0a4dd6 | 638 |
from typing import Tuple
import math
def split_train_test(X: pd.DataFrame, y: pd.Series, train_proportion: float = .75) \
-> Tuple[pd.DataFrame, pd.Series, pd.DataFrame, pd.Series]:
"""
Randomly split given sample to a training- and testing sample
Parameters
----------
X : DataFrame of sh... | 2261e72821ab55ac12f4f0b88511ce1f6d9d8d5f | 639 |
def s2sdd(s):
""" Converts a 4-port single-ended S-parameter matrix
to a 2-port differential mode representation.
Reference: https://www.aesa-cortaillod.com/fileadmin/documents/knowledge/AN_150421_E_Single_ended_S_Parameters.pdf
"""
sdd = np.zeros((2, 2), dtype=np.complex128)
sdd[0, 0] = 0.5*(s... | 0d29d2d248a49dd27bab202abd84014aab799907 | 640 |
def plot_gdf(gdf, map_f=None, maxitems=-1, style_func_args={}, popup_features=[],
tiles='cartodbpositron', zoom=6, geom_col='geometry', control_scale=True):
"""
:param gdf: GeoDataFrame
GeoDataFrame to visualize.
:param map_f: folium.Map
`folium.Map` object where the GeoDataFram... | 80c4002ca82e849a1701c00ead54671729009670 | 641 |
def set_catflap_cat_inside(request, catflap_uuid):
"""GET so it can be used as an email link."""
catflap = CatFlap.objects.get(uuid=catflap_uuid)
if not catflap.cat_inside:
catflap.cat_inside = True
catflap.save()
track_manual_intervention(catflap, cat_inside=True)
return redire... | cb7feabe83ef69598aff9fe6ba9867996312c892 | 642 |
import ctypes
def feature_list():
"""Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc
Returns
-------
list
List of :class:`.Feature` objects
"""
lib_features_c_array = ctypes.POINTER(Feature)()
lib_features_size = ctypes.... | ec20748fb4aae07898949822b3a7ba9835f4ed57 | 643 |
def _symm_herm(C):
"""To get rid of NaNs produced by _scalar2array, symmetrize operators
where C_ijkl = C_jilk*"""
nans = np.isnan(C)
C[nans] = np.einsum('jilk', C)[nans].conj()
return C | bd2e46b3ed751eb380aedd8d280294177fb6b3fd | 644 |
def cat(self, dim=0):
"""Map of 'cat' pytorch method."""
x = self
dim = _dim_explicit(x[0].shape, dim)
return P.concat(x, dim) | 9eba4de4941ac437e82f98647e0c6dc014b1578f | 645 |
import re
def _name_xform(o):
"""transform names to lowercase, without symbols (except underscore)
Any chars other than alphanumeric are converted to an underscore
"""
return re.sub("\W", "_", o.lower()) | 8ea563f805493d8885c143d9c2e2e54447ef19e8 | 646 |
def runner(app):
"""创建一个运行器,用于调用应用注册的 Click 命令"""
return app.test_cli_runner() | f9ffb3040045e0789a5686eb9a80f3fdef126a9d | 647 |
def create_activation_cache(model):
"""Creates an activation cache for the tensors of a model."""
input_quantizer = quantized_relu(8, 0)
output_cache = {}
# If using a Sequential model, the input layer is hidden. Therefore, add the
# input quantization to the cache if the first layer is not an input layer
... | a35c11e95831e3aa51fadce75577e97bd150cc1e | 648 |
def feature_scatterplot(fset_path, features_to_plot):
"""Create scatter plot of feature set.
Parameters
----------
fset_path : str
Path to feature set to be plotted.
features_to_plot : list of str
List of feature names to be plotted.
Returns
-------
(str, str)
R... | e8e0a545b992042eb334554042c9efa68a4f6a1f | 649 |
def model1(v, va, vb, ka, Wa, Wb, pa):
"""
A translation of the equation from Sandström's Dynamic NMR Spectroscopy,
p. 14, for the uncoupled 2-site exchange simulation.
v: frequency whose amplitude is to be calculated
va, vb: frequencies of a and b singlets (slow exchange limit) (va > vb)
ka: ra... | c1110cbd16bfcd942a086e8d878bfe3117bf4f99 | 650 |
def calculate_laminar_flame_speed(
initial_temperature,
initial_pressure,
species_dict,
mechanism,
phase_specification="",
unit_registry=_U
):
"""
This function uses cantera to calculate the laminar flame speed of a given
gas mixture.
Parameters
-----... | cdceb35dd5313d32e5b7cdfd4af2b842d2019587 | 651 |
def extrapolate_coverage(lines_w_status):
"""
Given the following input:
>>> lines_w_status = [
(1, True),
(4, True),
(7, False),
(9, False),
]
Return expanded lines with their extrapolated line status.
>>> extrapolate_coverage(lines_w_status) == [
(1, ... | e7685359f570ae979f2421c3a64513409b9df352 | 652 |
def get_image_features(filename):
"""
Param:
Path to image
Returns:
Desired features of image in the form of a dictionary (key = feature_name, value = feature_value)
"""
array, metadata = nrrd.read(filename)
return {k: f(array, metadata, filename) for k, f in image_feature_functi... | 0f991ebed175f0f41e30654cb4665dea09a1053d | 653 |
def get_DCT_transform_matrix(N):
"""
Return the normalised N-by-N discrete cosine transform (DCT) matrix.
Applying the returned transform matrix to a vector x: D.dot(x) yields the
DCT of x. Applying the returned transform matrix to a matrix A: D.dot(A)
applies the DCT to the columns of A. Taking D.... | 87314407c0836892a79747ea01aa9c369224198b | 654 |
def get_reduce_nodes(name, nodes):
"""
Get nodes that combine the reduction variable with a sentinel variable.
Recognizes the first node that combines the reduction variable with another
variable.
"""
reduce_nodes = None
for i, stmt in enumerate(nodes):
lhs = stmt.target.name
... | 8438829236f9c45986d1e1394cd0c6864caec73f | 655 |
def extract_mesh_descriptor_id(descriptor_id_str: str) -> int:
""" Converts descriptor ID strings (e.g. 'D000016') into a number ID (e.g. 16). """
if len(descriptor_id_str) == 0:
raise Exception("Empty descriptor ID")
if descriptor_id_str[0] != "D":
raise Exception("Expected descriptor ID to... | 9f013eadee9a149b9617e4a1c058bbe67c6dd8ba | 656 |
def process_sources(sources_list):
"""
This function processes the sources result
:param sources_list: A list of dictionaries
:return: A list of source objects
"""
sources_results = []
for sources_item in sources_list:
id = sources_item.get('id')
name = sources_item.get('name... | 7742a721802c66daf525520969f5831f9a497137 | 657 |
import math
def encrypt(message_text, key):
"""Method Defined for ENCRYPTION of a Simple \
String message into a Cipher Text Using \
2x2 Hill Cipher Technique
\nPARAMETERS\n
message_text: string to be encrypted
key: string key for encryption with length <= 4
\nRETURNS\n
cipher_text: ... | 2b36ba888980021cc69bffb1316b4e352bd026e8 | 658 |
import torch
def resnet101(pretrained=False, num_groups=None, weight_std=False, **kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 23, 3], num_groups=num_groups, weight_std=weight_std, **... | da4213b280eeef56cf1bdce7bfd05cfc0b8cde7d | 659 |
def cron(cronline, venusian_category='irc3.plugins.cron'):
"""main decorator"""
def wrapper(func):
def callback(context, name, ob):
obj = context.context
crons = obj.get_plugin(Crons)
if info.scope == 'class':
callback = getattr(
ob... | 9ffe20fd3e803b1260577ff38122b4912ab4d69a | 660 |
def oauth_type():
"""Check if Slack or another OAuth has been configured"""
if "OAUTH_TYPE" in current_app.config:
return current_app.config["OAUTH_TYPE"].lower()
else:
return None | d9fe8f77fd502890becd44cbaf802b2e94598a6f | 661 |
import random
import string
def create_categories():
"""Create a group of random strings for each column in the table."""
return [
[
''.join(random.choices(string.ascii_lowercase, k=random.randint(STR_MIN, STR_MAX)))
for _i in range(CAT_COUNT)
]
for _j in range(... | 8552be3fb45091f404d396f452dd37824a0cae23 | 663 |
from typing import Union
from typing import Tuple
from typing import List
from typing import Any
def _compute_comm_classes(
A: Union[np.ndarray, spmatrix]
) -> Tuple[List[List[Any]], bool]:
"""Compute communication classes for a graph given by A."""
di_graph = (
nx.from_scipy_sparse_matrix(A, cre... | 15a7025d10855a4644be60d52dba273c526c2b43 | 665 |
import typing
def parse_lines(lines: typing.List[str],
units: Units,
use_na: bool = True) -> typing.List[typing.Dict[str, typing.Any]]:
"""
Returns a list of parsed line dictionaries
"""
parsed_lines = []
prob = ''
while lines:
raw_line = lines[0].strip(... | 356b3c4d80a462643ab6c7747d4f1174202129be | 666 |
import random
def rand_cutout(np_img, pcts=(0.05, 0.4), depth=(1., 0.), max_k=1):
"""Cut out from image, and edges of rectangles are smooth.
Returns:
applied image, cut mask
"""
cut = np.ones(np_img.shape[:2])
k = random.randint(1, max_k)
for _ in range(k):
d = random.random()... | fd5b40138314827c3ff69bb571f30453049c073b | 667 |
from typing import List
def create_content_list(contents: List[str]) -> str:
"""Format list of string into markdown list
Args:
contents: (List[string]), list of string to be formatted
Returns:
String
"""
return '\n'.join(
[template.LIST_TEMPLATE.format(
level='',
content=... | 4080d7540def0bd0199f380a787b49eafc512b6f | 668 |
from typing import Optional
import requests
import logging
def convert(key: str, content: str, output_format: OWLFormat=OWLFormat.func) -> Optional[str]:
"""
Convert content into output_format
:param key: Key of content for error reporting
:param content: OWL representation
:param output_format: t... | c350a00198489d6224693cf528fb952283c6fc27 | 669 |
def _post_single_image(client: Imgur, image_path, title, description=None):
"""
Limit to 1250 POST requests per hour and 12500 per day
"""
image = client.image_upload(image_path, title, description)
# album_id = client.album_get('Family Photos')['response']['data']['id']
# client.album_add(album... | 22b1c5996986616515e8edcfcd22d9c82df1d27b | 670 |
def load_data(path, start=0, end=99999, step=1, returnNames = False):
"""Load images into a list
#Arguments
paths: List of strings representing paths to folders containing
images that must be named as numbers
start,end,step: Refers to the number of name of images. Only loads
... | 7edaff4bc977a63c22f140b74a86bc9c6fdae604 | 671 |
def animated_1d_plot(probe_data_dnf: np.ndarray,
probe_data_input1: np.ndarray,
probe_data_input2: np.ndarray,
interval: ty.Optional[int] = 30) -> None:
"""Generates an animated plot for examples in the DNF regimes tutorial.
Parameters
--------... | 8ec34c6772b728daeb429a2ecf4af52ab673bc96 | 672 |
def create_tendencies(params, return_inner_products=False, return_qgtensor=False):
"""Function to handle the inner products and tendencies tensors construction.
Returns the tendencies function :math:`\\boldsymbol{f}` determining the model's ordinary differential
equations:
.. math:: \dot{\\boldsymbol{x... | 2ca9f8f6c52b72070c8d339a6ec23d7dd52ea66c | 673 |
import re
def git_get_keywords(versionfile_abs):
"""Extract version information from the given file."""
# the code embedded in _version.py can just fetch the value of these
# keywords. When used from setup.py, we don't want to import _version.py,
# so we do it with a regexp instead. This function is n... | ff70ee2690bc36aaf892653040996597750c52da | 674 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.