content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def bz2_uncompress_stack(archive_name):
"""" Takes .bz2 archive and unpacks it into file with the same name, minus '.bz2' extension
Arguments
---------
archive_name: str
Full path name of the source archive.
Returns
-------
none
"""
with bz2.BZ2File(archive_name, 'rb') as fin... | 54,800 |
def trace_func(resource):
"""Trace calls to function using provided resource name"""
@wrapt.function_wrapper
def _trace_func(wrapped, instance, args, kwargs):
pin = Pin.get_from(molten)
if not pin or not pin.enabled():
return wrapped(*args, **kwargs)
with pin.tracer.tr... | 54,801 |
def search_for_item(project):
"""Generate a string search key for a project"""
elements = []
elements.append(project['attributes']['title'])
return u' '.join(elements) | 54,802 |
def test_stratified_data_splitting():
"""test stratified data splitting, basic"""
data = pd.DataFrame(data = {"x": np.arange(120),
"group": [1]*40+[2]*40+[3]*40})
for seed in [1,3]:
np.random.seed(seed)
out1 = lc.stratified_data_splitting(data, group_col = "gro... | 54,803 |
def bench_chaoda(dataset_names: List[str], fast: bool, individuals_csv_path: Optional[Path] = None):
""" Calculates anomaly scores for all datasets using the CHAODA class.
"""
scores_df, times_df = helpers.get_dataframes()
model_name = 'CHAODA_FAST' if fast else 'CHAODA'
for i, dataset in enumerate... | 54,804 |
def sort_by_status(ori_list):
"""
sort feature progress
:param ori_list:
:return:
"""
for i in range(len(ori_list) - 1):
for j in range(len(ori_list) - 1 - i):
if compare_two_features(ori_list[j], ori_list[j + 1]):
ori_list[j], ori_list[j + 1] = ori_list[j + 1... | 54,805 |
def stop(
session_name: str,
) -> None:
"""
Stop LTTng session, and check for errors.
:param session_name: the name of the session
"""
result = lttng.stop(session_name)
if result < 0:
raise RuntimeError(f'failed to stop tracing: {lttng.strerror(result)}') | 54,806 |
def test_uart_irq_tbe(dut):
"""
Check if the Transmit Buffer Empty interrupt is sent
"""
yield _init_dut(dut)
yield _activate_module(dut)
wb_master = WishboneMaster(dut, dut.clk)
# ensure that IRQ is lowered before we start sending
if dut.irq.value != 0:
raise TestFailure("irq... | 54,807 |
def log_command(ctx: Context, command: str):
"""
Logs a command to a file.
`ctx`: Command Invocation Context
`command`: The Command Name
"""
log = get_logger(__name__)
debug_or_info = constants.DEBUG_MODE
if not debug_or_info:
log.info(f"{ctx.author} used {command} in {ctx.guil... | 54,808 |
def perturb_word(word: str, skip_stopwords=True, skip_punctuation=True):
"""
:param skip_stopwords:
:param word:
:return: pertubed word, None if no perturbation is available
"""
if skip_stopwords and word.lower() in stopwords.words('english') \
or skip_punctuation and not word.lowe... | 54,809 |
def boxzoom(viewer, event):
"""Enable box zoom."""
def _get_shape():
if "Control" in event.modifiers:
return Shape.VERTICAL
elif "Shift" in event.modifiers:
return Shape.HORIZONTAL
return Shape.BOX
# make sure box is visible
if not viewer.drag_tool.tool.... | 54,810 |
def gen_coeffs(num_dim):
"""
Helper function for generating a linear simulation.
:param num_dim: number of dimensions for the simulation
:return: a vector of coefficients
"""
coeff_vec = np.array([1 / (x+1) for x in range(num_dim)])
return coeff_vec.reshape(-1, 1) | 54,811 |
def read_passwords(addr):
""" read passwords as list from a file """
with open(addr) as f:
lines = f.readlines()
pwlist = [clean_word(line) for line in lines]
pwlist = [x for x in pwlist if x != ""]
return pwlist | 54,812 |
def get_model(name, version, project_name=None):
"""
Get a specific model version given a model name and a version.
For example if you run this:
>>> from hops import model
>>> model.get_model('mnist', 1)
You will get version 1 of the model 'mnist'
Args:
:name: name of the model
... | 54,813 |
def index():
"""Return the home page."""
return render_template('index.html') | 54,814 |
def generate_scope_name(data_loader):
"""
Generate scope name according to computation graph.
Args:
data_loader (OnnxDataLoader): Data loader instance.
Returns:
list[str], generated scope name.
"""
init_dag = _build_connection(data_loader)
try:
if USER_DEFINED_PATTE... | 54,815 |
def write_jobfile(cmd, jobname, sbatchpath='./sbatch/',
nodes=1, ppn=1, gpus=0, mem=16, nhours=3):
"""
Create a job file.
Args:
cmd : str, Command to execute.
jobname : str, Name of the job.
sbatchpath : str, Directory to store SBATCH file in.
scratchpath :... | 54,816 |
def execute_command(command, args):
"""
Runs the provided command with the given args. Exceptions are propogated
to the caller.
"""
if args is None:
args = sys.argv[1:]
try:
command.execute(args)
except IOError as failure:
if failure.errno == errno.EPIPE:
... | 54,817 |
def get_active_questions(netid, course_id):
"""Gets all questions that are not yet being helped
Returns a list of questions with their question text, id, enqueue_time, and the asking student's name
or None if the requester is not a TA
"""
if not verify_is_ta(netid, course_id):
return None
... | 54,818 |
def hamiltonian(edges, directed=False, time_limit=5, concorde=False, precision=0):
"""
Calculates shortest path that traverses each node exactly once. Convert
Hamiltonian path problem to TSP by adding one dummy point that has a distance
of zero to all your other points. Solve the TSP and get rid of the ... | 54,819 |
def analytic_kernel(k):
"""Calculate the X4 kernel from the X2 kernel (for proof see appendix in paper)"""
k_size = k.shape[0]
# Calculate the big kernels size
big_k = np.zeros((3 * k_size - 2, 3 * k_size - 2))
# Loop over the small kernel to fill the big one
for r in range(k_size):
for ... | 54,820 |
def sortNDHelperA(fitnesses, obj, front):
"""Create a non-dominated sorting of S on the first M objectives"""
if len(fitnesses) < 2:
return
elif len(fitnesses) == 2:
#Only two individulas, compare them and adjust front number
s1, s2 = fitnesses[0], fitnesses[1]
if isdominated... | 54,821 |
def simple_3dof_arm(seg1_len, seg2_len, seg3_len, q0, base=None):
"""Creates a simple human-like robotic arm with 7 links and 2 segments
with the desired lengths and starting joint configuration
:param seg1_len: The length of the first segment of the arm
:type seg1_len: int
:param seg2_len: The le... | 54,822 |
def collect_nodes(points, highlighted_nodes=[], color='#79FF06', highlighted_color='blue', width=200, highlighted_width=400):
"""
Собирает необходимые нам вершины в нужный формат
Parameters
----------
points : [str, str, ...]
Вершины графа.
highlighted_nodes : [str, str, ...], optional
... | 54,823 |
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
conv3x3 = nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False),
nn.BatchNorm2d(out_planes),
nn.ReLU(inplace=True),
)
return conv3x3 | 54,824 |
def test_init_select_module(
cd_tmp_path: Path, cp_config: CpConfigTypeDef, mocker: MockerFixture
) -> None:
"""Test init select from two modules."""
mock_runway = mocker.patch(f"{MODULE}.Runway", Mock(spec=Runway, spec_set=True))
cp_config("min_required_multi", cd_tmp_path)
runner = CliRunner()
... | 54,825 |
def check_url_content(
url: str, content_match: typing.Optional[re.Pattern] = None
) -> typing.Tuple[str, int, float, bool, datetime.datetime]:
"""
Get URL and return basic information.
Args:
url (str): The URL to check.
content_match (str): A regular expression to match on the content.... | 54,826 |
def post_reasoner_query(request_body):
"""Get associations for a given ReasonerAPI query.
:param request_body: The ReasonerStdAPI query in JSON
:return: Results as a ReasonerStdAPI Message
"""
query_graph = request_body["message"]["query_graph"]
print(query_graph)
if len(query_graph["ed... | 54,827 |
def get_ransac_pipeline():
""" Function return pipeline with lagged transformation in it """
node_ransac = PrimaryNode('ransac_lin_reg')
node_final = SecondaryNode('linear', nodes_from=[node_ransac])
pipeline = Pipeline(node_final)
return pipeline | 54,828 |
def phon2cv_generator(ipalist):
"""generator function called by word2struc"""
for i in ipalist:
yield phon2cv(i) | 54,829 |
def feature_names_from_extractor_list(feature_extractors):
"""
get a list of feature names from a list of feature extractors
:param feature_extractors: a list of feature extractors
:return: a list of the feature names for each extractor (think first row of .csv file)
"""
feature_names = [feature... | 54,830 |
def upload_files(local_path, warm_up=False):
"""
upload files to hdfs
"""
remote = os.getenv("OUTPUT_PATH")
job_id = os.getenv("SYS_JOB_ID")
local = local_path.split('/')[-1]
remote_path = "{}/{}/{}/{}".format(remote, job_id, "model", local)
client.makedirs(remote_path)
hadoop_path =... | 54,831 |
def blank_publish_view(request):
"""Save posts into db w/o publishing."""
return poster(lambda: tasks.fetch_and_publish(force=True, blank=True)) | 54,832 |
def read_txt(filename, encoding='utf-8'):
"""Text file reader."""
with io.open(filename, 'r', encoding=encoding) as f:
return f.read() | 54,833 |
def main():
"""Entry point function
"""
try_ftp_anonymous_login("127.0.0.1") | 54,834 |
def level_detect(x, fs, attack_ms=0.1, release_ms=100, mode='peak'):
"""Performs level detection on an input signal
Parameters
----------
x : ndarray
Input vector
fs : float
Sample rate [Hz]
attack_ms : float, optional
Time constant for attack [ms]
release_ms : float... | 54,835 |
def get_doc_permissions(doc, verbose=False, user=None, ptype=None):
"""Returns a dict of evaluated permissions for given `doc` like `{"read":1, "write":1}`"""
if not user: user = frappe.session.user
if frappe.is_table(doc.doctype): return {"read": 1, "write": 1}
meta = frappe.get_meta(doc.doctype)
if has_contro... | 54,836 |
def write_mapping_table(path, data_table, header=False):
"""
Writes to the table where the translations are found
:param path: where the table to write into is located
:param data_table: contents of the data table
:param header: contents of the header
:return: None
"""
with open(path, '... | 54,837 |
def delete_downloaded_content(
id_or_url: str,
novel_service: BaseNovelService = Provide[Application.services.novel_service],
):
"""deletes all the downloaded content from chapters of novel"""
try:
novel = cli_helpers.get_novel(id_or_url)
except ValueError:
sys.exit(1)
n... | 54,838 |
def get_job_type(name):
"""Returns job type based on its name."""
if 'phase1' in name:
return 'phase1'
elif 'phase2' in name:
return 'phase2'
elif 'dfg' in name:
return 'dfg'
else:
return 'other' | 54,839 |
def ames_score(emb):
"""
Measure the ames positive probability of molecule,
more close to 1, more "toxic"
Parameters
----------
emb : numpy.ndarray, size (x,512)
the cddd descriptor of molecule
Returns
-------
ames : float
ames score
"""
ames = ames_model.p... | 54,840 |
def do_task(msg):
"""
新进程的处理回调函数,用于根据任务类型选择对于的数据抓取实现函数.
:param msg: 待抓取数据的相关参数
:return:
"""
# 处理weibo.cn的抓取任务
if msg["type"] == "weibo_cn":
weibo_cn.fetch(msg["task"], msg["keyword"], int(msg["start"]), int(msg["end"]))
elif msg["type"] == "medium_com":
medium_com.fetch(m... | 54,841 |
def quadrature(func,a,b,args=(),tol=1.49e-8,maxiter=50, reference=False):
"""Compute a definite integral using fixed-tolerance Gaussian quadrature.
Description:
Integrate func from a to b using Gaussian quadrature
with absolute tolerance tol.
Inputs:
func -- a Python function or method to integr... | 54,842 |
def getargs():
""" Parse program arguments.
"""
parser = argparse.ArgumentParser(
description=DESCRIPTION,
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('ori_lst', type=str,
help='original image list')
parser.add_argument('bat_lst', type=... | 54,843 |
def read_sensor():
"""Returns the orientation in quaternion form"""
quat = sensor.quaternion
return quat | 54,844 |
def is_resnet(name):
"""
Simply checks if name represents a resnet, by convention, all resnet names start with 'resnet'
:param name:
:return:
"""
name = name.lower()
return name.startswith('resnet') | 54,845 |
def _get_object_system_id(obj) -> Optional[str]:
"""Finds the System id (as a string) for the supplied object"""
system_id = None
if isinstance(obj, System):
system_id = obj.id
elif isinstance(obj, BrewtilsSystem):
system_id = ObjectId(obj.id)
elif type(obj) in _types_that_derive_sy... | 54,846 |
def assert_produces_warning(expected_warning=Warning, filter_level="always",
clear=None, check_stacklevel=True):
"""
Context manager for running code expected to either raise a specific
warning, or not raise any warnings. Verifies that the code raises the
expected warning, an... | 54,847 |
def find_closest_config_file():
"""
Returns the location of the closest Verta config file.
Returns
-------
config_filepath: str or None
Path to config file.
"""
for dirpath in get_possible_config_file_dirs():
# TODO: raise error if YAML and JSON in same dir
filepath... | 54,848 |
def _regress_1d(design_matrix, boot_mean, boot_var, Nc_list, treatment_idx, **kwargs):
"""
Performs hypothesis testing for a single gene for many bootstrap iterations.
Here, :X_center:, :X_center_Sq:, :boot_var:, :boot_mean: should have the same number of rows
"""
num_boot = boot_mean.shape[1]
nonneg = Fal... | 54,849 |
def clear_flask_context():
"""
Clear flask current_app and request globals.
When using :meth:`flask.Flask.test_client`, even as context manager,
the flask's globals :attr:`flask.current_app` and :attr:`flask.request`
are left dirty, so testing code relying on them will probably fail.
This func... | 54,850 |
def convert_output_record(data):
"""Covert data record into a list for output csv
"""
output_record = []
# Participant ID
output_record.append(os.path.basename(data['filename']).replace('.eaf', ''))
# Speaker
output_record.append(data['speaker'])
# Timestamp
output_record.append(d... | 54,851 |
def handle_pmid_25502872(filename):
"""Bergseng, ..., Sollid. Immunogenetics 2015 [PMID 25502872]"""
return None | 54,852 |
def expand_schema_for_inheritance(schema):
"""
Allows the schema to support inheritance.
The schema supports configs that (optionally) point to zero or more parent YAML configs
(using a path) that will be taken as base configurations to be overwritten.
"""
return merge({'inherit': stlistorstring... | 54,853 |
def option_two(choice_two):
"""Functions to for different methods to search the database"""
if choice_two == 1:
query_sub = search_record.search_date()
elif choice_two == 2:
query_sub = search_record.search_time()
elif choice_two == 3:
query_sub = search_record.search_string()
... | 54,854 |
def parse_fmt(fmt: str) -> (int, int):
"""Parse Q<m>.<n> string
Parameters
----------
fmt
Format string in the form 'Qm.n', where
m is the number of integer bits
n is the number of fractional bits
Returns
-------
n, m
Number of int and fr... | 54,855 |
def invert_dictionary(mapping: Dict) -> Dict:
"""Invert the keys and values of a dictionary."""
remap = {v: k for k, v in mapping.items()}
if len(remap) != len(mapping):
raise ValueError("Dictionary cannot be inverted; some values were not unique")
return remap | 54,856 |
def create_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs):
"""Create permissions on django 1.10+."""
if not app_config.models_module:
return
try:
ContentType = apps.get_model('contenttypes', 'ContentType')
Permission = apps.get_model('auth',... | 54,857 |
def PrettyPrintBackupRunsList(backups_list):
"""Pretty prints a list of backups.
Args:
backups_list: A dict object representing the the list of backups
resources.
"""
printer = util.PrettyPrinter(0)
if 'nextPageToken' in backups_list:
page_token = backups_list['nextPageToken']
printer.Pri... | 54,858 |
def store_file(file):
"""Stores the file to specified destination"""
destination = "/".join(["api/test_docs", file.name])
file.save(destination)
return destination | 54,859 |
def test_fail_get_transformation_class():
""" tests if get_transformation_class throws an error if it cannot find a transforamtion"""
assert_raises(
NotImplementedError, get_transformation_class, None, LagrangePolynomial
) | 54,860 |
def model_fn(model_dir):
"""Load the PyTorch model from the `model_dir` directory."""
print("Loading model.")
# Determine the device and construct the model.
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
name = 'cnn.pth'
checkpoint = torch.load(os.path.join(model_di... | 54,861 |
def getNumberedTypedString(items, maxLen=5000, numPrefix=''):
"""get a string that has each item of the list on its own line,
and each item is numbered on the left from zero"""
digits = 0
n = len(items)
while n > 0:
digits += 1
n //= 10
digits = digits
format = numPrefix + '%... | 54,862 |
def send(subject, body, from_name=None, _test_config=None):
"""
Sends a notification email with the specified subject, body, and (optional)
sender name.
Arguments:
* subject : unicode|bytes<utf-8> Subject of the email to send.
* body : unicode|bytes<utf-8> Body of the email to send... | 54,863 |
def mpl_dict(params):
""""Convert _ to . for easier mpl rcparams grid definition"""
return {k.replace('_', '.'): v for k, v in params.items()} | 54,864 |
def _format_accelerations(pivot_x, pivot_y, is_acceleration, h):
""" Returns the pivot movement as acceleration
The user is allowed to enter the pivot's movement as two functions of time.
If is_acceleration is set to True, these functions are interpreted as
pivot's acceleration. Otherwise, they are int... | 54,865 |
def data_source_get(context, data_source):
"""Return the Data Source or None if it does not exist."""
return IMPL.data_source_get(context, data_source) | 54,866 |
def add_pseudo_counts(ccm,ad=None,num=None):
"""Add a small number of fake mutations or 'pseudo counts' to the co-clustering and ancestor-descendant matrices for
subchallenges 2 and 3, each in their own, new cluster. This ensures that there are not cases where
either of these matrices has a variance of zero... | 54,867 |
def compute_coefficients(xyz):
"""Fit a plane to the first three dimensions of a matrix
Parameters
----------
xyz : array-like
The matrix of data to fit the plane to.
Returns
-------
np.array
1-dimensional array with four values, the coefficients `a`, `b`, `c`
and `... | 54,868 |
def _build_step(
docker_api, variables, build_config, step_config, from_image, should_ignore_cache,
should_remove_container):
"""
Builds the image for the given step
:param docker_api: The api interface that is to be used to connect to the docker daemon
:param variables: The list of var... | 54,869 |
def Sum(onnx_node, ng_inputs): # type: (NodeWrapper, List[TensorOp]) -> Op
"""Calculate element-wise sum of the input tensors."""
return reduce(ng.add, ng_inputs) | 54,870 |
def test_df_keys():
"""List of keys to be used for populating a bucket with DataFrames"""
return {
'avro': ['df.avro'],
'csv': ['df.csv'],
'csv.gz': ['df.csv.gz'],
'csv.zip': ['df.csv.zip'],
'csv.bz2': ['df.csv.bz2'],
'csv.xz': ['df.csv.xz'],
'psv': ['df.p... | 54,871 |
def first_existing(d, keys):
"""Returns the value of the first key in keys which exists in d."""
for key in keys:
if key in d:
return d[key]
return None | 54,872 |
def test_mesh_shape(lower_bound: float, size: float, num_segments: int):
"""Check consistency of a ``Mesh`` arrays shapes."""
upper_bound = lower_bound + size
partition_x = Partition(lower_bound, upper_bound, num_segments)
partition_y = Partition(lower_bound, upper_bound, num_segments)
partition_z =... | 54,873 |
def _verify_kubeapi_service(host):
"""Verify that the kubeapi service answer"""
with host.sudo():
cmd = "kubectl --kubeconfig=/etc/kubernetes/admin.conf cluster-info"
res = host.run(cmd)
if res.rc != 0:
pytest.fail(res.stderr) | 54,874 |
def aseg_stats_subcortical(fspath, subjid):
"""
Returns all the subcortical volumes found in stats/aseg.stats.
Equivalent of load_fs_segstats.m
"""
ignore_seg_names = cfg.freesurfer_subcortical_seg_names_to_ignore
segstatsfile = os.path.join(fspath, subjid, 'stats', 'aseg.stats')
# ColH... | 54,875 |
def test_get_404():
"""a TAXIICollectionSource.get() call that receives an HTTP 404 response
code from the taxii2client should be be returned as None.
TAXII spec states that a TAXII server can return a 404 for nonexistent
resources or lack of access. Decided that None is acceptable reponse
to imply... | 54,876 |
def _expand_right(a, n):
"""Insert multiple axes of size 1 at right end of tensor's shape.
Equivalent to performing `expand_dims(..., -1)` `n` times.
Args:
a: tensor into which extra axes will be inserted.
n: number of inserted axes.
"""
return tf.reshape(a, tf.concat([
tf.shape(a), tf.ones([... | 54,877 |
def unregister_mod(mod: Mod) -> bool:
"""
unregisters a mod from the global cache `mods`
:param mod: mod to unregister
:return: if it successfully unregistered it
"""
if mod.name_or_class_name() not in mods:
return False
get_event_loop().create_task(mod.unloaded())
del mods[mod.... | 54,878 |
def resolve_usr_filename(filename):
"""Resolve the filename to an absolute path.
:param filename: The input file name.
"""
full_filename = filename
if os.path.isabs(full_filename) == False:
full_filename = os.path.join(os.path.expanduser("~"),
full_filename)
return os.path.n... | 54,879 |
def curveAddPtCtx(q=1,e=1,ex=1,i1="string",i2="string",i3="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/curveAddPtCtx.html
-----------------------------------------
curveAddPtCtx is undoable, queryable, and editable.
The curveAddPtCtx command creates a new curve add p... | 54,880 |
def ignore_error(error=Exception):
"""
个别情况下会忽略遇到的错误
Args:
Returns:
"""
# noinspection PyBroadException
try:
yield
except error:
pass | 54,881 |
def ASCIItoRaster(ASCIIFile,savePath,pixel_type=1,RasterFile = None,epsg = None):
"""
=========================================================================
ASCIItoRaster(ASCIIFile,savePath,pixel_type=1,RasterFile = None,epsg = None)
===============================================================... | 54,882 |
def errors(module):
""" dict: {name:Exception or None} for tests in module. """
modname = module.__name__
errors = ((k, do(v)) for k, v in all_tests(module))
errors = ((k, v) for k, v in errors if v is not None)
return {f"{modname}.{name}": err for name, err in errors} | 54,883 |
def polygon_pairs(i):
"""Generate all two digits pairs for given polygon sequence."""
for k, v in value_map[i].items():
for l in v:
yield k, l | 54,884 |
def add_column(graph, results, selector):
"""Add a column to `graph`, produce a new graph.
Args:
graph (:class:`Graph`): Source ArrowProperty graph.
results (:class:`Context`): Results that generated by previous app querying.
selector (str): Used to select a subrange of data of results,... | 54,885 |
def list_templates(sitename):
"""return a list of template names for this site"""
path = WEBROOT / sitename / '.templates'
if not path.exists():
return []
return sorted([f.name for f in path.iterdir() if f.suffix == '.tpl']) | 54,886 |
def test_duration_enumeration004_1107_duration_enumeration004_1107_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : facet=enumeration and value=P1347Y
P1347M P1Y2MT2H and document value=P1347Y
"""
assert_bindings(
schema="msData/datatypes/Facets/duration/duration_enu... | 54,887 |
def resample(myarray, shift, include_edge=False):
"""
Resample an array, e.g. duration or start times, with a certain delta step (shift).
Parameters:
myarray -- input array to resample
shift -- unit to shift
Outputs:
myarray -- resampled
"""
ishift = int(shift / (myarray[1]-myarr... | 54,888 |
def from_pyqtgraph_struct(dct):
"""
Get simple structured dict from pyqtgraph params saveState() export.
:param dct: dct = parameters.saveState()
:return:
"""
output = {}
key = dct["name"]
if "children" in dct.keys():
reconstruction_type = "dict"
if "reconstruction_type... | 54,889 |
def add_secondaryip(obj, context, **kwargs):
"""
:param obj:
:param context:
:param kwargs:
'name': vl_ext_xx,
'vdom': const.EXT_VDOM,
'ip': 'x.x.x.x x.x.x.x'
:return:
"""
records = fortinet_db.query_records(context,
fortine... | 54,890 |
def receive_msg(topic):
"""
Decorator
"""
def inner(func):
@sio.on(topic)
async def handle_request(data):
# call 'func' to return the data
func(data)
# returning inner function
return inner | 54,891 |
def test_run_backup_database(mock_exists_retval, mock_isdir_retval):
"""test run with mock obj as input."""
mock_db_path = mock.Mock()
mock_base_path = mock.Mock()
mock_name = mock.Mock()
with mock.patch('version.utils.os') as mock_os, \
mock.patch('version.utils.shutil') as mock_shutil,... | 54,892 |
def get_requirements():
"""Return a list of package requirements from the requirements.txt file."""
with open('requirements.txt') as f:
return f.read().split() | 54,893 |
def MissalignmentTest(windows):
"""Run the test on the windows passed in"""
refAlignments = {}
#find the controls alligned along each axis
for win in windows:
if not win.ref:
continue
for side in ("top", "left", "right", "bottom"):
sideValue = getatt... | 54,894 |
def integer_to_real_mapper(integers):
"""Define Integer Mapping Function Here(If Needed.)"""
real_numbers = []
range_of_integers = 32767 # each value goes from 0-32767(2 ^ length_of_chromosome)
integer_to_real_number_mapper = 1 / range_of_integers # will produce number between 0-1 when multiplie... | 54,895 |
def get_feature_normalizer_filename(fold, path, extension='cpickle'):
"""Get normalizer filename
Parameters
----------
fold : int >= 0
evaluation fold number
path : str
normalizer path
extension : str
file extension
(Default value='cpickle')
Returns
-... | 54,896 |
def weather_from_metar_string(weather_object: WeatherABC):
"""
Creates a Weather object from a METAR string
:param weather_object: weather object to fill
:type weather_object: WeatherABC
"""
LOGGER.debug('building Weather from METAR string')
weather_object.source_type = 'METAR'
LOGGER.d... | 54,897 |
def fake_post_data(target, data_dict):
"""
In order for form to don't fail submission, all permission fields need
to receive values. This function populates data dict with default values
for permissions, making form validation pass
"""
for form in get_permissions_forms(target):
for field... | 54,898 |
def get_3d_kgrid(fk,alat,nk,exclude_gamma=False):
""" put a k-space function fk onto an FFT grid for inverse Fourier transform
fr = np.fft.ifft(fk)*(alat/nk)**ndim ! Don't forget the normalization! """
kgrid = np.zeros([nk,nk,nk],dtype=complex)
kint_unit = lambda x:kint_to_kvec(x,nk,alat)
for kx in... | 54,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.