content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def example_bytes(values): """Input must be float32 np.array""" return tf.train.Example( features=tf.train.Features( feature={'dosages': _bytes_feature(values.tobytes())} ) )
1db2de7db6b93e414e7636107a40c510dda1cadd
34,800
from typing import Union from pathlib import Path def _write_svg_file( filename: str, svg_root: _SvgNamedElement, write_dir: Union[Path, str] = None, ) -> Path: """Format the svg then write the svg to a file in write_dir.""" # Add a credit comment at top of SVG. comment = ( f"Created b...
196e9c1601106fc6e5f7bbe293ab5d80677d1cfc
34,801
def _build_extension_download_url( extension_name: str, publisher_name: str, version: str ) -> str: """ Build the download url for the given parameters. Just a shortcut for the string formatting. :param extension_name: Desired extension name. :type extension_name: str :param publisher_name:...
884ad99bb7e2d1c7d4fe7cc53f277962eb47414d
34,802
import scipy def sortedEig(X,M=None,k=None, lambda0=0): """ Return the k largest eigenvalues and the corresponding eigenvectors of the solution to X*u = b*M*u Inputs: X: matrix M: matrix k: (int) if k is None, return all but one. lambda0: (float) regularization parameter to ensur...
957c36b625d2e7676123547e49b9a8d3e2ba48d2
34,803
from typing import List def _fourier_transform_multi_fermionic_mode( n: int, amplitude: complex, modes: List[int]) -> np.ndarray: """Fermionic Fourier transform of a multi Fermionic mode base state. Args: n: State length, number of qubits used. amplitude: State amplitude. Absolute val...
a4983387f622f450d31e25ba1a30027eda9d99c5
34,804
def get_metric_parser(op): """Return a function which can parse a line with this operator.""" return { OP_START_TIMER: parse_timer, OP_STOP_TIMER: parse_timer, OP_NAMED_EVENT: parse_named_event, OP_GAUGE: parse_gauge, }[op]
b78272c9f70318bc76d43ccaf03df294cc2de4ea
34,805
def parse_division(l, c, line, root_node, last_section_node): """ Extracts a division node from a line :param l: The line number (starting from 0) :param c: The column number :param line: The line string (without indentation) :param root_node: The document root node. :return: tuple(last...
376322fa8678f5440a96caaa7f3b4f968e4f24de
34,806
def diff_eqs(INP, t): """The main set of equations""" Y = np.zeros((2)) V = INP Y[0] = gamma * (N0 - V[0]) - tau * V[1] Y[1] = ( tau * (n - 1) * (n * V[0] - V[1]) * V[1] / (n * V[0]) + gamma * (n * N0 - n * V[0] - V[1]) - tau * V[1] - tau * (n - 1) * V[1] * V[1] / (n ...
6736fab5d0f1c54a0d44cb64af85fca31f4b18dd
34,807
from datetime import datetime def register(): """ Функция регистрации пользователя :return: Страницы Login или Register """ if request.method == "POST": # Достаем из формы данные пользователя username = request.form["FirstName"] lastname = request.form["LastName"] ...
6663508e40746484c96bb789ae091ba2c7a6662b
34,808
from pathlib import Path import re def get_detectron2_current_version(): """Version is not available for import through Python since it is above the top level of the package. Instead, we parse it from the file with a regex.""" # Get version info from detectron2 __init__.py version_source = (Path(_...
52b7717fdee1fc64b7e8c3d4d3aa074373fcffb6
34,809
def accuracy_score(y_true, y_pred, *, normalize=True, sample_weight=None): """Accuracy classification score. In multilabel classification, this function computes subset accuracy: the set of labels predicted for a sample must *exactly* match the corresponding set of labels in y_true. Read more in the...
306b7095ec02e4192cf7de76aa31fb8503ce0a9f
34,810
def aspect_ratio(bbox, ratios): """ Enumerate box for each aspect ratio. Args: bbox (:py:class:`BBox2D`): 2D bounding box. ratios (:py:class:`list`): list of int/float values. """ cx, cy = bbox.center() w, h = bbox.w, bbox.h size = w * h ratios = np.asarray(ratios, dtyp...
73ce16b3ed755bb07e680ab5626fb2b160b4aa53
34,811
def str2bool(value): """ Convert CLI args to boolean :param str value: :return bool: """ if value.lower() in ("yes", "true", "t", "y", "1"): return True elif value.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError("Boolean value...
5b204bb20913f0214048a8332229b80017c7a701
34,812
import sys import os def delete_bundles(uuids, force, recursive, data_only, dry_run): """ Delete the bundles specified by |uuids|. If |force|, allow deletion of bundles that have descendants or that appear across multiple worksheets. If |recursive|, add all bundles downstream too. If |data_only|, ...
87e2554de74ee43fad3e25560b53d34419708163
34,813
def layernorm_cx(cx, w_in): """Accumulates complexity of layernorm into cx = (h, w, flops, params, acts).""" h, w, flops, params, acts = cx["h"], cx["w"], cx["flops"], cx["params"], cx["acts"] params += 2 * w_in return {"h": h, "w": w, "flops": flops, "params": params, "acts": acts}
97ffd7678c3d4d3fbbf63b6717fe3cc11823c230
34,814
async def _get_privileges(user_id: int, chat_id: int) -> Privileges: """ Check user access :param user_id: user id :param chat_id: access chat id :return: privileges """ bot = Bot.get_current() chat_member = await bot.get_chat_member(chat_id, user_id) if chat_member.is_chat_admin(): ...
421cfeb48c2a1a4bfd8d0240d4f7c3acc25bb856
34,815
def _get_project_permissions(user, gl_project): """Return the user's access level for the given project.""" permissions = gl_project.attributes["permissions"] access_level = max( [x[1].get("access_level", 0) for x in permissions.items() if x[1]] ) current_app.logger.debug( "access le...
0fdae254d91cda4e209201c2931b794ff918c89b
34,816
def sso_login_url(service): """Get SSO login url for service""" app_config = current_app.config login_host = app_config.get('SSO').get('HOST') sso_redirect_url = app_config.get(f'SERVER_{service}_DOMAIN_NAME') query = urlencode({ 'service': service, 'redirect_url': f'https://{sso_red...
28828ab734d95304e60b13812de4550587f577d9
34,817
import os def check_for_commit(repo_path, commit): """Checks a directory for a specific commit. Args: repo_path: The name of the directory to test for the commit. commit: The commit SHA to check for. Returns: True if directory contains that commit. """ # Check if valid git repo. if not os.p...
2a78190561ab18744e368e0b2f04478186917058
34,818
def get_config(): """Default configuration for the Harvest level.""" config = config_dict.ConfigDict() # Basic configuration. config.individual_observation_names = ["RGB"] config.global_observation_names = ["WORLD.RGB"] # Lua script configuration. config.lab2d_settings = { "levelName": # ...
8cfbac7ebe371278332e7d71f7f89b02f701b59b
34,819
def evaluate_regression_error(predicted_output, true_output, norm=norms.euclidean_2): """Calculate the error with respect to a norm of regression output. Parameters ---------- predicted_output : numpy.ndarray The predictions made by the classifier. true_output...
243bc61234f20995a8db765653bd37cf7d3f8e40
34,820
def classify(character: str) -> int: """String classifier.""" if character.isupper(): return StringType.UPPER if character.islower(): return StringType.LOWER if character.isnumeric(): return StringType.NUMERIC return StringType.OTHER
a17af3771bc2d1dd51ea735bcc78f856a01df5cd
34,821
import json def getGold(session, city): """ Parameters ---------- session : ikabot.web.session.Session city : dict Returns ------- gold : int """ url = 'view=finances&backgroundView=city&currentCityId={}&templateView=finances&actionRequest={}&ajax=1'.format(city['id'], actionRe...
e312f7bda229340ec3709f025ae33194909e82ee
34,822
from typing import Iterable from typing import Mapping def _iter_but_not_str_or_map(maybe_iter): """Helper function to differ between iterables and iterables that are strings or mappings. This is used for pynads.concrete.List to determine if an iterable should be consumed or placed into a single value tup...
3dab46cfd2d2d19bd0fa744370b9059d6a0683bc
34,823
def interrogate_decision_tree(wxtree): """ Obtain a list of necessary inputs from the decision tree as it is currently defined. Return a formatted string that contains the diagnostic names, the thresholds needed, and whether they are thresholded above or below these values. This output is used to cr...
14ac92c25bccd8c549de6d7a5bbf696e18c1e47e
34,824
def script_resolve_name(script_name, name): """ Name resolver for scripts. Supports ROS_NAMESPACE. Does not support remapping arguments. @param name: name to resolve @type name: str @param script_name: name of script. script_name must not contain a namespace. @type script_name: str ...
38e0be53417719bc9521b80a4621b3127aab1749
34,825
def offbyKExtra(s1,s2,k): """Input: two strings s1,s2 and integer k Process: to check if number of extra characters in s2 as compared to s1 (or vice versa) is equal to k Output: return True when above condition is met otherwise return False""" flag=0 extra1='' if len(s1)>len(s2): for...
10cb2480c95a729aceb219e14999dcbcf0cad1eb
34,826
import os import sys def collect(basepath, exclude=None, processPlugins=True): """ Collects all the packages associated with the inputted filepath. :param module | <module> :return ([<str> pkg, ..], [(<str> path, <str> relpath), ..] data) """ if exclude is None: excl...
c6432cf820a61abb0103eb89c8b4572830b34c2f
34,827
def Optimizer(Efunc,x0,method='L-BFGS-B',jac=None,optns={}): """ Efunc(x,count) See the scipy.optimize.minimize manual for options """ const.CONSOLEMESSAGE('Entered in lib.Optimizer') methlst=['Nelder-Mead','Powell','CG','BFGS','Newton-CG','Anneal','L-BFGS-B', 'TNC', 'COBYLA', ...
2fe2ff9263a0cb0662c30a47b90e089b92988ad2
34,828
def plot_feature_calibrator(model_graph, feature_name, plot_submodel_calibration=True, font_size=12, axis_label_font_size=14, figsize=None): """Plots feature calibrator(s) extrac...
16576f1497937fb04be2d7fea17b578177564f65
34,829
def calc_reg_cdd( temperatures, t_base_cooling, model_yeardays, crit_temp_min_max=False ): """Calculate CDD for every day and daily yd shape of cooling demand Arguments ---------- temperatures : array Temperatures t_base_cooling : array Base tempe...
62699977be16efbdd511e987e736822fca6a82c3
34,830
def get_number_of_polymorphic_sites(pileup): """ # ======================================================================== GET NUMBER OF POLYMORPHIC SITES PURPOSE ------- Returns the number of polymorphic sites. INPUT ----- [PILEUP] [pileup] A Pileup object, which rep...
e388b20f500b141da0eedc54616703c6e444de8a
34,831
def test(sess, evaluate, ph, dataset, testmodel): """Apply the models.""" ## word model acc = Accuracies() out_sentences = [] results_w = [] for f_word in dataset.batches: batch_values, out_logits_w_out_w = sess.run( [testmodel.predictions_w, testmodel.out_logits_w], feed_dict={ph.inputs...
03f2035e90f1facce191548b061c7407d9715ab7
34,832
def _compile_rules(rules_file, externals, cur_logger): """ Saves Yara rule content to file, validates the content with Yara Validator, and uses Yara python to compile the rule set. Args: rules_file: Yara rule file content. Returns: Compiled rules, compiled rules md5. """ tr...
dcad814fc91ae577952a926021dbfb71ae638080
34,833
async def hello(request): """Test webserver request.""" return web.Response(text="Hello, world")
d8a68eb12fd094a5beed0610d8601ea63334aaab
34,834
from typing import Set def delete_unwanted(wanted: Set[PathLike], folder: PathLike, need_permission: bool=True) -> int: """ Deletes all Unwanted files in a folder. Returns amount of deleted files """ todelete = [] for path in listdir(folder): path = realpath(join(folder,path)) ...
44674cf2fc153d054e8ea767b2fc477bda2ee25c
34,835
def user_save(form, is_patient=False, is_office=False): """Function saving the user to the database.""" user = form.save(commit=False) # The account is not active until the user activates it. user.is_active = False user.is_patient = is_patient user.is_office = is_office user.save() retur...
8ce0a7af24bc72da98c015d0e9f7545069bbce19
34,836
def int_divmod(context, builder, ty, x, y): """ Integer divmod(x, y). The caller must ensure that y != 0. """ if ty.signed: return int_divmod_signed(context, builder, ty, x, y) else: return builder.udiv(x, y), builder.urem(x, y)
93fa13c703a9419ea9a5926f32a69a7269d57fd9
34,837
def initial_state(layer, dimensions=None): """ Initalizes the recurrence relation with an initial hidden state if needed, else replaces with a "None" to tell Theano that the network **will** return something, but it does not need to send it to the next step of the recurrence """ if dimension...
3788adbe14604d50b5aa9701616f3bdaa5af94a7
34,838
def lin_smooth(x, window_len=15, window='hanning'): """ Smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that tr...
a1a5a5c0ab76a4b38007947cc161fbcf0bc90dd9
34,839
def product_details(request, id): """ The view rendering the page for one selected product and all of its details """ selected_product = get_object_or_404(Product, id=id) # get existing number of views, increment and update model number = selected_product.num_of_views + 1 Product.objects.fi...
d567b378286a19bdc70442f18e65922912aa7c67
34,840
def compute_colors_for_labels(labels): """Simple function that adds fixed colors depending on the class """ palette = np.array([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1, 1]) colors = labels[:, None] * palette colors = (colors % 255).astype("float") colors /= 255 colors[:, -1] = 1 return colors
5ce1dc5a43d94a7bd316137b217c32cec9fab355
34,841
import os def set_log_level(logger, debug): """Set log level based on debug state.""" if debug: os.environ["HYPERGLASS_LOG_LEVEL"] = "DEBUG" base_logger("DEBUG") if debug: logger.debug("Debugging enabled") return True
8030a943724d4ac650da27372f1c71b234a82a80
34,842
def vms_ajax_revoke_ip(request, vm_id, template_name='generic/form.html', form_class=RevokeIPForm): """ Ajax view for detaching elastip IP from a virtual machine. """ rest_data = prep_data({'vm': ('user/vm/get_by_id/', {'vm_id': vm_id})}, request.session) if request.method == 'POST': form =...
8ae82abbde4a883673b376af05820dd882813f96
34,843
import hashlib def make_message_hash(msg, include=(), exclude=()): """ Returns hashcode for ROS message, as a hex digest. @param include message fields to include if not all, as [((nested, path), re.Pattern())] @param exclude message fields to exclude, as [((nested, path), re.Pattern())] ...
325d5d0bd5d8d5f05ecfcc6983425ac121fbbea3
34,844
def non_overlap_df(input_df: pd.DataFrame) -> pd.DataFrame: """ Args: input_df: DataFrame with possibly overlapping calls Returns: a DataFrame object with non-overlapping calls (after merge). """ non_overlap = [] for file_name, file_df in input_df.groupby(by='filename'): file_df...
8753f0c3f28d3b9e31b415c7a4d05aab22001df1
34,845
import prometheus_client def benchmark_last_result(project,benchmark): """ Get latest benchmark result from Victoria Metrics Returns "-1" if result not found """ query = f"last_over_time(parity_benchmark_common_result_ns{{project=\"{project}\",benchmark=\"{benchmark}\"}}[1y])" query_result = p...
9e7db0dda645f977fab85a98e9efdfbc7c6683be
34,846
def get_lambda_config(module, aws): """ Returns the lambda function configuration if it exists. :param module: Ansible module reference :param aws: AWS client connection :return: """ client = aws.client('lambda') # set API parameters api_params = dict(FunctionName=module.params['f...
509db0f745a3aeaea07722f1135a339d720cabdc
34,847
def standard_deviation(lst, population=True): """Calculates the standard deviation for a list of numbers.""" num_items = len(lst) mean = sum(lst) / num_items differences = [x - mean for x in lst] sq_differences = [d ** 2 for d in differences] ssd = sum(sq_differences) if population is True...
7f15f6d80adf722912cba49c3dfad9b40e2f3b2a
34,848
def solve(global_step): """add solver to losses""" # learning reate lr = _configure_learning_rate(82783, global_step) optimizer = _configure_optimizer(lr) tf.summary.scalar('learning_rate', lr) # compute and apply gradient losses = tf.get_collection(tf.GraphKeys.LOSSES) loss = tf.add_n(...
e26ccdcfef8eadc7f0335ff4d36e29158c85134b
34,849
def group_points_into_lines(edges, x_coords, y_coords, x_size=10, y_size=3): """ Группирует отдельные точки в линии при помощи функции connect_line :param edges: :param x_coords: :param y_coords: :param x_size: :param y_size: :return: """ point_dict = {(x_, y_): i for i, (x_, y_)...
dd505f739b83aef2bf91f0eb816e86c1bb7df997
34,850
def start(image): """Function to find start point of the Non - White pixel""" for i in range(image.shape[0]): if 0 in image[i]: return i
504b3cfc90610f34ce1ee6791dcf4c8139f06fe8
34,851
import itertools from typing import List def bench_merge_pandas(**kwargs) -> Dataset: """Merge benchmark for pandas.""" # Fixed parameters which apply to all of the trials in this benchmark. warmup_iters = 1 iters = 5 # Setup parameters. rng_seeds = [12345] left_key_unique_counts = [100]...
1f7d3f0c38cd8a667edd4b6c43b0ad68fbc3f5e0
34,852
import io import pickle def download_plot_analyses_to_txt(request, analyses): """Download plot data for given analyses as CSV file. Parameters ---------- request HTTPRequest analyses Sequence of Analysis instances Returns ------- HT...
b1d8331872255d49e97a2a5794c4dff09fa40645
34,853
import os def create_package(source=None, manifest=None, project_id=None, auth_token=None): """ Upload a package manifest """ if manifest is None: if source is None: raise SaltInvocationError( "create_or_update_package requires either source or man...
eadd39599aa2c7f63e815bea6b17507277063602
34,854
import os def get_default_autodist(): """Get the AutoDist object the scope of which you are in.""" global _DEFAULT_AUTODIST return _DEFAULT_AUTODIST.get(os.getpid(), None)
6c87c515da5b131a22e939c66742fcb59603e4e1
34,855
def ip4_bytes_to_str(ip_bytes): """Convert ip address from byte representation to 127.0.0.1.""" return "%d.%d.%d.%d" % unpack_ipv4(ip_bytes)
feb662972ff8d808dfeb0794cc9bfb443234fbe6
34,856
def BuildTelemax(x: int, c: int) -> str: """ utility fct to build Telemax Pointage """ msg = '123456MAC:4c24e9870203PROT005170817100*Q:' msg += str(x + c + 1).zfill(6) msg += '9103' msg += '0071' msg += '0093' msg += '2 ' msg += '0' # msg += 'xx' msg += '10020100^1*' ...
ba5d51cc6e7463d693f74eb618471fb23a62b6a9
34,857
import os def renameFileName(fileName, toAdd): """ rename a fileName. Modify the basename of a path string with a given string. Example modify 'data.pk' to 'data_sample.pk'. Parameter : fileName : string relative path to fileName toAdd : ...
38ffad918035917982a143a0fad2f6b031809b51
34,858
from typing import Tuple from typing import cast def create_ephemeral_key_pair(curve_type: str) -> Tuple[PublicKey, SharedKeyGenerator]: """Facilitates ECDH key exchange.""" if curve_type != "P-256": raise NotImplementedError() key_pair = create_new_key_pair(curve_type) def _key_exchange(ser...
ada825897fec2c818835f4d70298cf571ab79183
34,859
from typing import Dict from typing import Any def get_unlisted_livestreams_by_username(username: str) -> Dict[str, Any]: """Get a user's unlisted livestreams from their username. Args: username (str): The user's username. Returns: Dict[str, Any]: The unlisted livestream. """ ite...
53a9ac945457eaa4b4418605670b13db90e201b7
34,860
async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Add a weather entity from mapped location.""" fcst_coordinator = hass.data[DOMAIN][entry.entry_id]["fcst_coordinator"] if not fcst_coordinator.data: return cur_coordinator = hass.data...
526bea80afeaa4f6c91db6d2de91f625bc5e4bcd
34,861
def parse_sync_agent_forwarder_id(json): """ Extract the sync agent forwarder id from the get response of LearningLocker. :param json: JSON statement from the get response. :type json: dict(str, list(dict(str, str)) :return: The statement forwarder id from the sync agent. :rtype: str """ ...
4b07dc13ca978cfc3fad46e432c8c21d46ee53fa
34,862
import numpy def generate_lineal_parameter(parameter_values): """Generate parameters list for lineal parameter type.""" initial_value = parameter_values['initial_value'] final_value = parameter_values["final_value"] interval = parameter_values["interval"] param_options = numpy.arange( ...
6359a0c93c07aa3dfeba096501b73f69fb3b02f9
34,863
def get_plugin_arguments(plugin_name): """Gets plugin arguments, as a dict of version to argument list.""" plugin = plugins_base.PLUGINS.get_plugin(plugin_name) versions = plugin.get_versions() return {version: plugin.get_image_arguments(version) for version in versions}
ad056ecccc5ac40120493245709235b6587955b5
34,864
import re def to_snake_case(s): """Convert a string to snake-case format Parameters ---------- s: String String to convert to snake-case Returns ------- String Snake-case formatted string Notes ----- Adapted from https://gist.github.com/jaytaylor/3660565 ...
cf3ca065c471ed526ab15de5d6c07e9be74ddb59
34,865
def get_var(name, program=None): """ Get a variable by name from the global block of a program Args: name(str): name of the variable program(Program|None): program object. If None, default_global_program() will be used. Returns: Variable """ if program is No...
7f6bca1482834b1688175b6508fa269cfcee882a
34,866
def _update_cluster_config(cluster, session=None, user=None, **kwargs): """Update a cluster config.""" check_cluster_editable(cluster, user=user) return utils.update_db_object( session, cluster, **kwargs )
fe7e2f099f2719385ccde62aa94c71f2c91fbf85
34,867
def read_file(file_path="data/short.list"): """ Reads file, short.list by default. """ data = "" with open(file_path, "r", encoding="utf8", errors="ignore") as file: data = file.read().split("\n")[14:-1] return tuple(set(data))
f2ced72bfa6328c6794b629d043b837144304716
34,868
def inv_tabs(r): """ Add an expandable set of Tabs for a Site's Inventory Tasks @ToDo: Make these Expand/Contract without a server-side call """ settings = current.deployment_settings if settings.get_org_site_inv_req_tabs() and \ current.auth.s3_has_permission("read", "inv_inv_i...
ba97dd8219b3140889a2ea285a1aefbd60a9c54f
34,869
import torch def sample(lnprobs, temperature=1.0): """ Sample an element from a categorical distribution :param lnprobs: Outcome log-probabilities :param temperature: Sampling temperature. 1.0 follows the given distribution, 0.0 returns the maximum probability element. :return: The index o...
62ef43b30ffd9c6fac4254074d7b740cbfc01987
34,870
import pprint import logging def get_submit_input_metadata(body): """ Extract relevant metadata from the body message included with a submit input action. :param body: (dict) the body of the json payload, including details about the message and the button clicked :returns: user_i...
7d26392d54c9996a48965fa696a9243f5ea85716
34,871
def connection_is_established(): """ Function to check if a connection to the remote server has been established """ return (not _remote_client is None)
8ea9583b6585e8af57f775d8ce974dbdaf85197f
34,872
def getLanguage(langcode): """Returns the full name of the language referred to by its two-letters language code. """ if languages.has_key(langcode): return languages[langcode] else: raise RuntimeError("cannot find language with code " + str(langcode))
777c069f24f92ff9b2f65413535bc38c4be57865
34,873
import json def get_images(username): """ Retrieves image history for given username :return: resp: (json) All the pathways to the images the user has previously uploaded """ resp = [] for image in ImPath.query.filter_by(username=username): if (is_valid_image_path(image.impath)): ...
cdf5ed91d0c88065d07e0c992dc460f6555ee8ef
34,874
def otf2psf(otf, shape): """ Convert optical transfer function (OTF) to point-spread function (PSF). Compute the Inverse Fast Fourier Transform (ifft) of the OTF array and creates the PSF array that is not influenced by the OTF off-centering. By default, the PSF array is the same size as the OTF arr...
b3a142d26b15951c32e5c2e10aaba69ac9552fc8
34,875
def inventreeInstanceName(): """ Returns the InstanceName settings for the current database """ return InvenTreeSetting.get_setting("InstanceName", "")
7c57f2156b69b8a0155ce168921132863483824f
34,876
def predict(sentence: str) -> [str]: """ Lemmatize a given sentence :param sentence: sentence to lemmatize :return: lemmatized sentence """ lemmatizer = WordNetLemmatizer() word_list = nltk.word_tokenize(sentence) return [lemmatizer.lemmatize(w) for w in word_list]
b9b11cbb7d540fc517d9888f9e2449e3773617f4
34,877
def is_nominal_tolerance_met(data : pd.DataFrame, criteria_nominal : list = [], nominal_tolerance : list = []): """ Checks that the tolerances for categorical columns are met. The tolerance is defined as the sum of the maximum frequency deviation between groups for each categorical column passed in criteri...
03a432010f1ca46b6d80d491f76fa9acf3e2aa91
34,878
def field(type_hint=None, # type: Union[Type[T], Iterable[Type[T]]] nonable=GUESS, # type: Union[bool, Type[GUESS]] check_type=False, # type: bool default=EMPTY, # type: T default_factory=None, # type: Callable[[], T] validators=None, ...
b1f5b43b73f92d8b23699ea3116505d88cb1ce4a
34,879
def test_limit_by_resource_and_method(): """ Test using a custom key_func - one which creates different buckets by resource and method """ def get_key(req, resp, resource, params) -> str: user_key = get_remote_addr(req, resp, resource, params) return f"{user_key}:{resource.__class__.__name_...
b20492c686411a5d7db13959a7745bade605d1d1
34,880
def pdoo_wrap(doo_obj, total_budget, nu_max=1.0, rho_max=0.9, K=2, C_init=0.8, tol=1e-3, POO_mult=0.5, Randomize=False, return_history=False): """ Wrapper for running PDOO optimisation. """ # pylint: disable=too-many-locals total_budget = total_budget * doo_obj.eval_cost_single_point_normalise...
0d06a400a62021cf4c6f1f91ed3bc547ce822ca9
34,881
def chi2(sp, pars): """ Given a spectrum and some parameters, calculate the chi^2 value """ pars = list(pars) + [0] return ((sp.specfit.get_model_frompars(sp.xarr, pars) - sp.specfit.spectofit)**2 / (sp.specfit.errspec**2) ).sum()
ce8c6362eb88dfce17dc56414e3bed4f67ec6ffa
34,882
import os import json def handle_workflow_recover() -> tuple: """Attempts to recover workflows """ if 'workflows' in session: known_workflows = session['workflows'] else: known_workflows = [] found_workflow_ids = [] if known_workflows: for one_workflow_id in known_workf...
a96fe683a5e169b96b6062a3442e83d45e646737
34,883
def cartesian2spherical(xyz): """ Transform cartesian coordinates (x, y, z) in spherical coordinates. The function only returns the (theta, phi) pair since the magnetisation is fixed at zero Temperature (the r-component is constant) and is fully characterised by two degrees of freedom. (...
8f1ed7021da943082ae336f6d52bed8df09ee52b
34,884
from typing import Mapping def dict_list_select(dict_list, keys, default_value='', include_conditions={}, exclude_conditions={}): """ Transforms a list of dictionaries into a new list of dictionaries that only includes the specified keys. List entries that are missing key(s) will get the default valu...
472f1c14eea0b40fa438aa5e0d13f42a95dd33c7
34,885
import inspect def route_hardware_function(api_version: str, function: str): """Can be used to execute standard UOS IO functions.""" if api_version not in API_VERSIONS: return jsonify( ComResult( False, exception=f"'{function}' not supported in api version {...
0be2fbe888b516dde6337ef532b05ace82217152
34,886
def calculate_ci(patICDList, version=ELIXHAUSER): """ Calculate comorbidity index """ if version not in CI_MAP: raise ValueError("Unsupported comorbidity index") patCCMap = _calculate_comorbidity_score(patICDList, CI_MAP[version]) return sum(patCCMap.values())
69d37081466f2564e3334bb60742cece19bcdc89
34,887
def _map_spectrum_weight(map, spectrum=None): """Weight a map with a spectrum. This requires map to have an "energy" axis. The weights are normalised so that they sum to 1. The mean and unit of the output image is the same as of the input cube. At the moment this is used to get a weighted exposure...
0b7571bbc50aa7fed154951d2fc433e2952c0ab2
34,888
import torch def predict(processed_input): """Function to predict dog breed using the available model Args: processed_input (torch 4D tensor): transformed and preprocessed image Returns: breed_pred (str): name of the predicted breed class_prob (float):...
4af217d05b6734de67b99c9171f1e06d9d11dfd3
34,889
from torch import optim from torch.nn import functional as F from torch.optim import lr_scheduler from torch.utils import data from torchvision import datasets from torchvision import transforms from pytorch_generative import trainer from pytorch_generative import models def reproduce( n_epochs=457, batch_size=12...
9ca30ecfe3ab043cd3688f2ec68a7277b11c1668
34,890
def getChannels(server: utils.HikVisionServer): """ It is used to get the properties of streaming channels for the device """ return utils.getXML(server, "Streaming/channels")
032718216dfba1c7011a29c4d298a16599a0c873
34,891
import os import zipfile def has_valid_zip(zip_path): """ Return True if valid zip exists. Parameters ---------- zip_path : str absolute path to zip Returns ------- bool : True if valid zip exists at path """ if os.path.isfile(zip_path): if zipfile.is...
0968c552b33b0164250c624ce8b51c7a2ac1982e
34,892
def is_help_command(command): """ Checks that the user inputted command is a help command, which will not go over the wire. This is a command with -h or --help. The help functionality is triggered no matter where the -h appears in the command (arg ordering) :param command: a list of strings repres...
e68142c38d734e492f9f65dfdf04ac87f79bd666
34,893
def _holoviews_chart(): """## Dashboard Orders Chart generated by HoloViews""" data = _get_chart_data() line_plot = data.hvplot.line( x="Day", y="Orders", width=None, height=500, line_color="#007BFF", line_width=6, ) scatter_plot = data.hvplot.scatter(x="Day", y="Orders", height=300).opts( ...
4ceb6e712b72a247ead5a6e5f0b442f704e40ab8
34,894
def api_user_required(f): """A decorator for APIs that require a logged-in user.""" @wraps(f) def decorated(*args, **kwargs): if not are_logged_in(): return Response("API requires logged-in user", 401) return f(*args, **kwargs) return decorated
b4439868dc1401203a50052c430f3213352b1cbe
34,895
import warnings def fitGMM_patch_post_process( centre_patch_intensity, n_samples=1000, max_dist_thresh=10, min_area_pair=0, max_area_pair=10000): """ Fits an n-component mixture to a 2d image to resolve closely overlapping centroids This function simplifies the calling and wraps `fit_2dGMM` so we directly gi...
5bacc80660a144572b3fbd599e2ca07e2c1f8aaa
34,896
def generate(pTable, proxyService): """ for rows without candidates in subject cells, try to deduce candidates from the object properties in the same row -> add CEA candidates for subject columns and the respective cell_pair candidates """ # get subject columns subj_col_ids = pTable.getSubj...
4e094250d784918b591401207fd8800470f9d685
34,897
def StartOfInterval(intervalVar:NexVar) -> NexVar: """Creates the new event. Copies the start of each interval of the specified interval variable to the result.""" return NexRun("StartOfInterval", locals())
a272a09944ccc5433182ca58fdc7c085212e8706
34,898
import ipaddress def is_global(host: str) -> bool: """ >>> assert not is_global("127.0.0.1") >>> assert not is_global("192.168.20.168") >>> assert is_global("211.13.20.168") >>> assert is_global("google.com") """ if host == "localhost": return False try: address = ipadd...
1e68b762a279eb7b54f32339c783a631bedfa2c9
34,899