content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def make_strided_slice_tests(options):
"""Make a set of tests to do strided_slice."""
# TODO(soroosh): add test/support for uint8.
test_parameters = [
# 4-D (basic cases with const/non-const indices).
{
"dtype": [tf.float32, tf.int32, tf.int64, tf.bool],
"index_type": [tf.int32],
... | 58,800 |
def _run_pipelines(pipelines):
"""Run the pipelines to load data.
Args:
pipelines (list): List of pipelines to be run.
Returns:
list: a list of booleans whether each pipeline completed
successfully or not.
"""
# TODO: Define these status codes programmatically.
run_... | 58,801 |
def test_rcv_all():
"""
test the ability to receive a batch of queued messages.
"""
pay_fmt = "send to ring msg: %d" # dynamic message format with counter
send_burst(MRC_SEND, pay_fmt) # send a bunch of 13 messages that should queue
time.sleep(1) # ensure underlying transport gets cycles to ... | 58,802 |
def dump(data: InDataExT, out: PathOrIOInfoT,
ac_parser: MaybeParserT = None, **options) -> None:
"""
Save 'data' to 'out'.
:param data: A mapping object may have configurations data to dump
:param out:
An output file path, a file, a file-like object, :class:`pathlib.Path`
obje... | 58,803 |
def reorg_train_valid(data_dir, labels, valid_ratio):
"""将验证集从原始的训练集中拆分出来"""
# 训练数据集中样本最少的类别中的样本数
n = collections.Counter(labels.values()).most_common()[-1][1]
# 验证集中每个类别的样本数
n_valid_per_label = max(1, math.floor(n * valid_ratio))
label_count = {}
for train_file in os.listdir(os.path.join(da... | 58,804 |
def pack(*v):
"""Packs value to fit into a word"""
w = 0
for i, x in enumerate(v):
w += INST_SZ**(len(v) - i - 1) * x
return w | 58,805 |
def get_logging_connection():
"""
Get main connection for logging
:return:
"""
# todo if your db have authorize or other settings
# todo please attach your code here
return pymongo.MongoClient(host=DOCKER_HOST_IP, port=27017, maxPoolSize=1000) | 58,806 |
def print_card(card):
"""
Makes a card string from a card object
:param card: The card object
:return: The card string
"""
if card.layout() == 'normal':
return make_card_string(card)
elif card.layout() == 'split':
return make_split_card_string(card)
elif card.layout() == ... | 58,807 |
def component_declaration1(): # type: ignore
"""
component_declaration1 =
declaration comment
"""
return syntax.declaration, syntax.comment | 58,808 |
def BackupConfiguration(sql_messages,
instance=None,
backup_enabled=None,
backup_location=None,
backup_start_time=None,
enable_bin_log=None,
enable_point_in_time_recovery=None,... | 58,809 |
def artifact_patch_request(user_id, req_op, req_path, req_value=None,
req_from=None):
"""Modifies an attribute of the artifact
Parameters
----------
user_id : str
The id of the user performing the patch operation
req_op : str
The operation to perform on th... | 58,810 |
def topo_2_property(topology, property):
"""
Returns properties of a topology for a given topology name.
Properties:
'stk_func' - gives the stk topology function for building cages
'stoich' - gives the stoichiometries of both building blocks
assuming that the first building bloc... | 58,811 |
def create_single_sign_on_session(remote_ip, auth_user, secure=True):
"""
WSGI/RevProxy no-login session creations.
Successful authentication and access verification,
create a session and return.
:return: not used
"""
# must define groups but not populating at the moment !!!
groups = []
... | 58,812 |
def get_full_names(pdb_dict):
"""Creates a mapping of het names to full English names.
:param pdb_dict: the .pdb dict to read.
:rtype: ``dict``"""
full_names = {}
for line in pdb_dict.get("HETNAM", []):
try:
full_names[line[11:14].strip()] += line[15:].strip()
except: f... | 58,813 |
def create_package(base_url, data=None, api_key=None):
"""Post a data dict to one of the actions of the CKAN action API.
See the documentation of the action API, including each of the available
actions and the data dicts they accept, here:
http://docs.ckan.org/en/ckan-1.8/apiv3.html
:param base_url:... | 58,814 |
def version(ctx):
"""Show the ScopePlot version"""
click.echo("ScopePlot {}".format(__version__)) | 58,815 |
def getDiffError(a, b):
"""
(Deprecated)Calculate the distance square between a and b.
Parameters
----------
a, b : ndarray of float, in the same shape
The two matrices to be compared
Returns
-------
float
The sum of element-wise distance square between a and b.
... | 58,816 |
def _fit_corrs(x_xt, x_y, n_ch_x, reg_type, alpha, n_ch_in):
"""Fit the model using correlation matrices."""
from scipy import linalg
known_types = ('ridge', 'laplacian')
if isinstance(reg_type, string_types):
reg_type = (reg_type,) * 2
if len(reg_type) != 2:
raise ValueError('reg_ty... | 58,817 |
def symbol(a=None):
"""
Return a variable from the symbolic ring with the given name.
If an expression is given, it is returned unchanged.
"""
if isinstance(a, Expression):
return a
return SR.symbol(a) | 58,818 |
def read_write_check(outfile, dname, data, dtype=None):
"""Tests scalar input/output on HDF5 files"""
if dtype is not None: data = [dtype(k) for k in data]
# First, we test that we can read and write 1 single element
outfile.append(dname + '_single', data[0])
# Set attributes on the dataset and current pat... | 58,819 |
def get_files(base_dir, ref_dir):
"""
get_files: get all the asdf files in base_dir.
"""
allfiles = sorted(glob(join(base_dir, "*h5")))
# we should use the head of ref_dir and the base of the globbed files
result = []
for each_file in allfiles:
result.append(join(ref_dir, basename(ea... | 58,820 |
def load_image(filename):
"""Loads a PNG image file."""
string = tf.read_file(filename)
image = tf.image.decode_image(string, channels=3)
image = tf.cast(image, tf.float32)
image /= 255
return image | 58,821 |
def save_search(search, filename):
"""
Save a search to disk in a pickle file using joblib
"""
joblib.dump(search, filename, compress=True) | 58,822 |
def _actor_in_relationship(actor, relationship):
"""Test whether the given actor is present in the given attribute"""
if actor == relationship:
return True
if isinstance(relationship, (AppenderMixin, Query, abc.Container)):
return actor in relationship
return False | 58,823 |
def gamma_correct(cs, c):
"""
Transform linear RGB values to nonlinear RGB values. Rec.
709 is ITU-R Recommendation BT. 709 (1990) ``Basic
Parameter Values for the HDTV Standard for the Studio and
for International Programme Exchange'', formerly CCIR Rec.
709. For details see
http://www.... | 58,824 |
def getbyid(ctx,
# Mandatory main parameter
accountid):
"""GetAccountByID enables you to return details about a specific account, given its accountID."""
cli_utils.establish_connection(ctx)
ctx.logger.info(""": """"""accountid = """ + str(accountid)+""";"""+"")
tr... | 58,825 |
def test_interactions():
"""Test we've instantiated the local interactions successfully"""
assert len(pyglobi.interactions) != 0
for i in pyglobi.interactions.keys():
assert isinstance(pyglobi.interactions[i], Interaction) | 58,826 |
def test_choose_none():
"""Tests choose when none of the alternatives match."""
t = BoostBuild.Tester(use_test_config=0)
t.write("Jamroot", """
import configure ;
obj fail : fail.cpp ;
explicit pass fail ;
obj foo : foo.cpp :
[ configure.choose "which one?" : fail <define>FAIL ] ;
""")
t.write("fail.c... | 58,827 |
def get_flat_pos_array(img_arr):
"""Converts grayscale image numpy array into flat array
with cube positions for blender.
"""
WIDTH = 160
HEIGHT = 120
THRESH = 127
res_arr = np.zeros(WIDTH*HEIGHT*3)
white_indexes = np.argwhere(img_arr > THRESH)
for row in white_indexes:
y, x... | 58,828 |
def recordAttr(attribute: str = "",delete: bool = False) -> None:
"""
記録するアトリビュートをセットアップします。記録コマンドを実行すると、このアトリビュートのすべての変更内容が記録されます。記録が停止すると、この変更内容はキーフレームに変わります。
-----------------------------------------
Flags:
-----------------------------------------
attribute (string): 記録するアトリビュートを指定... | 58,829 |
def extract_last_reg_status_change(strValue):
"""处理show onu last-reg-status-change命令得到的数据。其中,时间若为0000-00-00 00:00:00,将会转换为None。
Args:
strValue (str): show onu last-reg-status-change命令得到的数据
Returns:
list: 字典列表。
"""
# SLOT PON ONU LAST_OFF_TIME LAST_ON_TIME
# 4 8 1 Las... | 58,830 |
def slurp(filename):
"""Return the contents of a file as a single string."""
fh = open(filename, 'r')
try:
contents = fh.read()
finally:
fh.close()
return contents | 58,831 |
def refsoot_imag(wavelengths, enhancement_param=1):
"""imaginary part ot the refractive index for soot
:param wavelengths: wavelength(s) in meter.
:param enhancement_param: This parameter enhances the mass absoprtion efficiency of BC.
It makes it possible to scale BC absorption. Values of this param... | 58,832 |
def calculate_all_metrics(obs: DataArray, sim: DataArray) -> dict:
"""Calculate all metrics with default values."""
results = {
"NSE": nse(obs, sim),
"MSE": mse(obs, sim),
"RMSE": rmse(obs, sim),
"KGE": kge(obs, sim),
"Alpha-NSE": alpha_nse(obs, sim),
"Beta-NSE": ... | 58,833 |
def _file_path_check(filepath=None, format="png", interactive=False, is_plotly=False):
"""Helper function to check the filepath being passed.
Args:
filepath (str or Path, optional): Location to save file.
format (str): Extension for figure to be saved as. Defaults to 'png'.
interactive ... | 58,834 |
def transform(pattern: Pattern) -> "Either":
"""Expand pattern into an (almost) equivalent one, but with single Either.
Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d)
Quirks: [-a] => (-a), (-a...) => (-a -a)
"""
result = []
groups = [[pattern]]
while groups:
chil... | 58,835 |
def create_placeholders(n_x, n_y):
"""
Creates the placeholders for the tensorflow session.
Arguments:
n_x -- scalar, size of an image vector (num_px * num_px = 64 * 64 * 3 = 12288)
n_y -- scalar, number of classes (from 0 to 5, so -> 6)
Returns:
X -- placeholder for the data input, of sha... | 58,836 |
def checkIfUpdateAvailable(updateDateFileAddress):
"""Checks the Jyväskylä open data website for wheter
there is an update for the linkkidata-package
Returns true if there is, false if there is not"""
try:
lastUpdatedDate = getCurrentPackageDate(updateDateFileAddress)
page = requests.g... | 58,837 |
def nmse(outputs, targets):
"""
Normalized mean square error
:param outputs: Module's output
:param targets: Target signal to be learned
:return: Normalized mean square deviation
"""
# Flatten tensors
outputs = outputs.view(outputs.nelement())
targets = targets.view(targets.nelement(... | 58,838 |
async def get_schema_template(
db: AsyncSession,
tenant_id: UUID,
wallet_id: UUID,
schema_template_id: UUID,
deleted: bool | None = False,
) -> SchemaTemplateItem:
"""Get Schema Template.
Find and return a Traction Schema Template by ID.
Args:
db: database session
tenant_i... | 58,839 |
def get_random_box(shape: AxesLike, box_shape: AxesLike, axes: AxesLike = None, distribution: Callable = uniform):
"""Get a random box of shape ``box_shape`` that fits in the ``shape`` along the given ``axes``."""
start = distribution(shape_after_full_convolution(shape, box_shape, axes))
return start, start... | 58,840 |
def _optimize_font_size(font, text, max_font_size, min_font_size,
max_text_len):
"""Calculate the optimal font size to fit text in a given size."""
# Check size when using smallest single line font size
fontobj = ImageFont.truetype(font, min_font_size)
text_size = fontobj.getsiz... | 58,841 |
def redis_exists():
"""
Test that redis-py is installed and redis-server is running locally.
"""
try:
from redis import StrictRedis as Redis, RedisError
except ImportError:
return False
try:
Redis(db=15).ping()
return True
except RedisError:
return Fa... | 58,842 |
def _update_mt3dms_files(srcdir, fc, cc, arch, double):
"""Update MT3DMS source files.
Parameters
----------
srcdir : str
path to directory with source files
fc : str
fortran compiler
cc : str
c/c++ compiler
arch : str
architecture
double : bool
b... | 58,843 |
def apply_manifest(
workspace: tsrc.Workspace, manifest_path: Path, **kwargs: Any
) -> None:
""" apply a local manifest file """
ui.info_1("Applying manifest from", manifest_path)
manifest = tsrc.manifest.load(manifest_path)
workspace.repos = repos_from_config(manifest, workspace.config)
worksp... | 58,844 |
def configure(options, updated):
"""
Called once on script startup before any other events, and whenever options changes.
"""
mitmproxy.ctx.log("configure") | 58,845 |
def get_table_type(filename):
""" Accepted filenames:
device-<device_id>.csv,
user.csv,
session-<time_iso>.csv,
trials-<time_iso>-Block_<n>.csv
:param filename: name of uploaded file.
:type filename: str
:return: Name of table type.
:rtype: str|None
"""
basename, ext = f... | 58,846 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up the IPX800v5."""
hass.data.setdefault(DOMAIN, {})
config = entry.data | entry.options
session = async_get_clientsession(hass, False)
ipx = IPX800(
host=config[CONF_HOST],
port=config[CONF_PORT]... | 58,847 |
def get_paradigm(dataset_name):
""" Return the paradigm of a dataset ('domain_generalization' or 'subpopulation_shift')
Args:
dataset_name (str): Name of the dataset to get the paradigm of. (Must be part of the DATASETS list)
Return:
str: The paradigm of the dataset
"""
... | 58,848 |
def fix_cropBox_rot(img, bbox, input_size, rot):
"""Crop bbox from image by Affinetransform.
Parameters
----------
img: torch.Tensor
A tensor with shape: `(3, H, W)`.
bbox: list or tuple
[xmin, ymin, xmax, ymax].
input_size: tuple
Resulting image size, as (height, width).... | 58,849 |
def find_locations(text):
"""
Find normalized location mentions in text, with natasha library
"""
locations = []
try:
doc = Doc(text)
doc.segment(segmenter)
doc.tag_morph(morph_tagger)
doc.parse_syntax(syntax_parser)
doc.tag_ner(ner_tagger)
for token i... | 58,850 |
def zipr_longest(*iterables, fillvalue=None):
"""Like zipr, but terminate on the longest input."""
yield from rev(zip_longest(*iterables, fillvalue=fillvalue)) | 58,851 |
def length_of_longest_substring(s: str) -> int:
"""
The most obvious way to do this would be to go through all possible substrings of the string which would result in
an algorithm with an overall O(n^2) complexity.
But we can solve this problem using a more subtle method that does it with one linear tr... | 58,852 |
def loads(s):
"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a
NeXTSTEP property list document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified.... | 58,853 |
def test_p_adjust_vector_2_values_bonf():
"""
Testing p_adjust with a vector of 2 values and using bonferroni method.
"""
d = {"p_value": [0.07, 0.2], "adjusted": [0.14, 0.4]}
df = pd.DataFrame(data=d)
df = df[["p_value", "adjusted"]]
assert df.equals(p_adjust(data=[0.07, 0.2], method="bonf... | 58,854 |
def make_download_filename(genome, args, response_format):
"""
Make filename that will explain to the user what the predictions are for
:param genome: str: which version of the genome we are pulling data from
:param args: SearchArgs: argument used for search
:param response_format: str file extensio... | 58,855 |
def make_oracle(input_qubits,
output_qubit,
secret_factor_bits,
secret_bias_bit):
"""Gates implementing the function f(a) = a·factors + bias (mod 2)."""
if secret_bias_bit:
yield cirq.X(output_qubit)
for qubit, bit in zip(input_qubits, secret_factor_... | 58,856 |
def ranges_means(data):
"""
Return ranges, means of cycles counted using Downing's method 1.
"""
turns = data_rearranged_for_rainflow_counting(data)
values = [] # of the current turns being processed
ranges = []
means = []
for turn in turns:
values.append(turn)
while ... | 58,857 |
def graphics_from_directories(directories):
"""
Calls the tools.load_all_graphics() function for all directories passed.
"""
base_path = os.path.join("static", "images")
GFX = {}
for directory in directories:
path = os.path.join(base_path, directory)
GFX[directory] = tools.load_a... | 58,858 |
def window_to_bounds(window, affine):
"""Convert pixels to coordinates in a window"""
minx = ((window[1][0], window[1][1]) * affine)[0]
maxx = ((window[1][1], window[0][0]) * affine)[0]
miny = ((window[1][1], window[0][1]) * affine)[1]
maxy = ((window[1][1], window[0][0]) * affine)[1]
return min... | 58,859 |
def matches_version_constraint(constraint, target, version):
""" See http://wiki.opscode.com/display/chef/Version+Constraints
Do not pad the target to 3 (it would change the meaning of ~>)
"""
version = pad_to_3(version) # just in case
if constraint == '~>':
high = pad_to_3(target[:-2] + [(... | 58,860 |
def game_loop():
""" game_loop loops through the main menu of the game """
talk = ['talk', 't', '1']
use = ['use', 'u', '2']
inspect = ['inspect', 'i', '3']
inventory = ['inventory', 'inv', '4']
openDoor = ['door', 'doors', 'd', '5']
roomDescription = ['room', 'room description', 'r', '6']
... | 58,861 |
def rename_job(session, name, new_name):
"""
Rename job *name* to *new_name* on server.
"""
url = urlparse.urljoin(session.jenkins_url, '/job/%s/doRename?newName=%s' %
(name, new_name))
resp = session.post(url)
resp.raise_for_status() | 58,862 |
def get_management_unit_from_pt(request):
"""This function accepts post requests that contains a geojson
representation of a point. The view returns a dictionary contianing
the id, label, mu_type, centroid and bounds (extent) of the management_unit
containing the point, or an empty dictionary if the da... | 58,863 |
def say_hello(name: str,
greeting: Arg('-g', str, 'Greeting to use') = 'sup',
num_times: int = 1):
"""Reach out and greet somebody."""
for _ in range(num_times):
print(f'{greeting}, {name}') | 58,864 |
def forge_buy(oc_user,params):
"""购买打造的装备
"""
data = {}
user_forge_obj = UserForge.get_instance(oc_user.uid)
user_property_obj = UserProperty.get(oc_user.uid)
cost_smelting = user_forge_obj.cost_smelting
user_smelting = user_property_obj.property_info.get("smelting",0)
if cost_sm... | 58,865 |
def tm_path(name: str) -> str:
"""Returns the path of the settings file for name ('9o', 'doc', 'go',
'gohtml')
Note: This is used to locate syntax files, and appears to break when
GoSublime is not located in the ST Package directory.
"""
pkg = "Packages/GoSubl/"
if name == "9o":
ret... | 58,866 |
def delete_dict_key(dictobj, key):
"""Dictionary Key削除
Args:
dictobj (dict): Dictionary
key (any): key
"""
if key in dictobj:
del dictobj[key] | 58,867 |
def write_file(string, path, file_name):
""" Write a given string in a file with specified prefix path
and name.
:param string: string to write to file
:type string: str
:param path: path of directory where file will be written
:type path: str
:param file_name: name ... | 58,868 |
def get_javascript_value(value):
"""
Get javascript value for python value.
>>> get_javascript_value(True)
true
>>> get_javascript_value(10)
10
"""
if isinstance(value, bool):
if value:
return 'true'
else:
return 'false'
else:
return j... | 58,869 |
def test_with_ranker_gt_no_importances_substitution(cfg: PipelineConfig):
"""When no `feature_ranking` available, `feature_importances` should substitute
for the ranking."""
cfg.dataset.feature_importances = {"X[:, :]": 1.0} # uniform
cfg.ranker.estimates_feature_ranking = False
run_pipeline___te... | 58,870 |
def visualize_modules(
data: ProteomicsData,
annotations: Optional[DataFrame] = None,
col_cluster=True,
row_cluster=True,
cluster_kws: dict = {},
annot_kws: dict = {},
heatmap_kws: dict = {},
file_prefix: str = 'heatmap'
):
"""Makes heatmap figures of ... | 58,871 |
def make_targz_one_by_one(output_filename, source_dir):
"""
压缩文件目录,
:param output_filename: 输出路径,
:param source_dir: 输入路径,
:return:
"""
tar = tarfile.open(output_filename,"w:gz")
for root,dir,files in os.walk(source_dir):
os.chdir(source_dir)
os.chdir('..')
path =... | 58,872 |
def test_new_use_without_email(django_user_model):
"""
test creating new account without email return correct error message
"""
with pytest.raises(TypeError, match='Users must have an email'):
django_user_model.objects.create_user(
username='someone', password='pass123', email=None
... | 58,873 |
def sort_by_seq_lens(args, batch, sequences_lengths, descending=True):
"""
Sort a batch of padded variable length sequences by their length.
Args:
batch: A batch of padded variable length sequences. The batch should
have the dimensions (batch_size x max_sequence_length x *).
seq... | 58,874 |
def docker_compose_package_project_name():
"""Generate a project name using the current process PID and a random uid.
Override this fixture in your tests if you need a particular project name.
This is a package scoped fixture. The project name will contain the scope"""
return "pytest{}-package{}".forma... | 58,875 |
def run_example():
""" Gets the annual modulation signal for 2016 and 2017.
Runs AnnualModulation()
Creates a number of matplotlib plots and displays them.
"""
tmin = dt.datetime(2016,1,1,0,0,0,tzinfo = dt.timezone.utc)
tmax = dt.datetime(2018,1,1,0,0,0,tzinfo = dt.timezone.utc)
times,r... | 58,876 |
def test_branch_delete_current():
"""Assert that we can delete the current branch."""
atom = ATOMClassifier(X_bin, y_bin, random_state=1)
atom.branch = "b2"
atom.branch.delete()
assert "b2" not in atom._branches | 58,877 |
def neighbors(vertices, triangles, depth=1, direct_neighbor=False):
""" Build mesh vertices neighbors.
This is the base function to build Direct Neighbors (DiNe) kernels.
See Also
--------
neighbors_rec
Examples
--------
>>> from surfify.utils import icosahedron, neighbors
>>> imp... | 58,878 |
def Bootstrap(data1, data2, M = 1e4, paired = False, direction = None, verbose = False):
""" Bootstrap difference in means between two groups.
M = float64 # Number of iterations
paired = {True, False}
direction = {"greater", "lesser", None}
if verbose = True, returns distribution and p_value, shows... | 58,879 |
def read_station_coordinates(file, group=None, var_x='Xs', var_y='Ys'):
"""
Read the x and y coordinates from an NetCDF file.
:param file: Input NetCDF file
:param group: The group of the NetCDF file to read. See xarray.open_mfdataset for details.
:param var_x: Variable name for x coordinates
... | 58,880 |
def is_ctrl_z(e: InputEvent, keyboard: InputDevice) -> bool:
"""
Check whether event invokes ^z or not.
"""
return e.code == ecodes.KEY_Z and ecodes.KEY_LEFTCTRL in keyboard.active_keys() | 58,881 |
def test_Sequence_alignment_fixed_width(all_terms):
"""Test alignment methods with width provided"""
@as_subprocess
def child(kind):
term = TestTerminal(kind=kind)
pony_msg = 'pony express, all aboard, choo, choo!'
pony_len = len(pony_msg)
pony_colored = u''.join('%s%s' % (te... | 58,882 |
def import_module_from_path(filepath):
"""
Import a module from given path.
https://stackoverflow.com/a/67692/5159551
"""
spec = importlib.util.spec_from_file_location('person', filepath)
person_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(person_module)
return ... | 58,883 |
def removefromaccessgroup(ctx,
# Mandatory main parameter
volumeaccessgroupid,
# Mandatory main parameter
volumes):
"""The RemoveVolumeFromVolumeAccessGroup method enables you to remove volumes from a volume access group."""
cli_utils.establish_connection(ctx)
... | 58,884 |
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the Adax thermostat with config flow."""
adax_data_handler = Adax(
entry.data[ACCOUNT_ID],
entry.data[CONF_PASSWORD],
websession=async_get_clien... | 58,885 |
def time_mask(spec, T=40, n_mask=2, replace_with_zero=True, inplace=False):
"""freq mask for spec agument
:param numpy.ndarray spec: (time, freq)
:param int n_mask: the number of masks
:param bool inplace: overwrite
:param bool replace_with_zero: pad zero on mask if true else use mean
"""
i... | 58,886 |
def change(csq):
"""
>>> change("missense|TMEM240|ENST00000378733|protein_coding|-|170P>170L|1470752G>A")
('170P', '170L', True)
>>> change('synonymous|AGRN|ENST00000379370|protein_coding|+|268A|976629C>T')
('268A', '268A', False)
"""
parts = csq.split("|")
if len(parts) < 7:
ret... | 58,887 |
def process(
in_dir: Path = typer.Argument(
..., help="The directory containing the input form files"
),
out_dir: Optional[Path] = typer.Option(
None,
"--out_dir",
help="The directory where the output flat files will be created. Defaults to the current working directory",
... | 58,888 |
def p_optional_specifier_optional(p):
"""optional_specifier : OPTIONAL"""
p[0] = True | 58,889 |
def build_html(f_target):
"""
Build the html from the markdown.
"""
f_html_output = f_target.replace(".md", ".html")
logger.info(f"Building {f_target} to {f_html_output}")
with open(f_target) as FIN:
markdown = FIN.read()
html = miniprez_markdown(markdown)
soup = build_body(ht... | 58,890 |
def update_params(
workload: spec.Workload,
current_param_container: spec.ParameterContainer,
current_params_types: spec.ParameterTypeTree,
model_state: spec.ModelAuxiliaryState,
hyperparameters: spec.Hyperparameters,
batch: Dict[str, spec.Tensor],
# This will define the output activation vi... | 58,891 |
def info(config, stdout=True):
"""
Info cmdline wrapper
"""
state = _get_state(config.base_dir,
config.baseline,
config.target,
config.cursor,
schema=config.schema)
if stdout:
out_state = OrderedDict(... | 58,892 |
def with_coordinates(pw_in_path, positions_type, atom_symbols, atom_positions):
"""Return a string giving a new input file, which is the same as the one at
`pw_in_path` except that the ATOMIC_POSITIONS block is replaced by the one
specified by the other parameters of this function.
`positions_type`, `a... | 58,893 |
def test_fails(file: Path, tmp_path: Path):
"""
Tests for failing builds.
The tests are structured as .txt files, parsed and executed here.
The structure of the file is::
lines to add to the default conf.py
# split
index.html content
"""
conf, index = file.read_text('ut... | 58,894 |
def list_serial_ports():
""" Lists serial port names
https://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
... | 58,895 |
def setup():
"""
Sets the admin user credentials, adds a db connection and sets a few other configurations.
Patch or copy this method if you want to something differently.
"""
print('\033[36m.. creating admin user \033[0m')
add_user(email=config.metabase_admin_email(),
first_name=c... | 58,896 |
def find_nearest(array, value):
"""
Returns the index of "array" whose data best matches "value".
https://tinyurl.com/yc7twjx8
"""
array = np.asarray(array)
idxs = np.argsort(np.abs(array - value))[0]
return idxs | 58,897 |
def TDVGGNetV1(output_units, input_shape,
num_conv_blocks=5, num_block_layers=2*[2]+3*[3], num_fc_layers=3,
conv_filters=64, conv_filters_factor=2, max_conv_filters=512,
dilation_rate=1, dilation_rate_factor=0,
hidden_fc_units=4096,
kernel_size=... | 58,898 |
def test_truncation_parents_selection():
""" Test (mu + lambda), i.e., parents competing with offspring
Create parent and offspring populations such that each has an "best" individual that will be selected by
truncation selection.
"""
parents = [Individual([0, 0, 0], decoder=IdentityDecoder(), prob... | 58,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.