content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_public_roles(): """Roles which make a collection to be considered public.""" return [ Role.load_id(Role.SYSTEM_GUEST), Role.load_id(Role.SYSTEM_USER), ]
5bf1a761c68bf7c6ab904241da854882b3940d5f
50,800
from pathlib import Path import argparse def path_type(arg): """ Checks if supplied paths are exist and contain .csv files. """ try: dir = Path(arg) except TypeError as e: logger.exception(e) raise if not dir.is_dir(): msg = f"'{dir}' is not a valid directory"...
aaafd62da9955394868bb1058f4a9b923817cbdd
50,801
def data_missing(): """Length-2 array with [NA, Valid]""" variant = Variant( chromosome="chr1", position=123456, id="rs12345", ref="A", alt=["T", "G"] ) genotypes = [variant.make_genotype(), variant.make_genotype("T", "T")] return GenotypeArray(values=genotypes)
8123ecda0b73066125b2d716d38fa45dadb68355
50,802
from pyspark.sql import functions as F from pyspark.sql import DataFrame from functools import reduce def append(dfs, like="columns"): """ Concat multiple dataFrames columns or rows wise :param dfs: List of DataFrames :param like: concat as columns or rows :return: """ # FIX: Because mono...
75a28b7ba94838f1f2c8e8bd41f387a5905c8e71
50,803
from typing import Optional def event_to_show( event: Event, session: Depends(get_db), user: Optional[User] = None, ) -> Optional[Event]: """Check the given event's privacy and return event/fixed private event/ nothing (hidden) accordingly""" is_owner = check_event_owner(event, session, user) ...
c502760e1ff1fdc786c30feedb0a6ba99f2b421e
50,804
import os def parse_xml(file_name, check_exists=True): """Returns a parsed xml tree with comments intact.""" error_message = "" if check_exists and not os.path.exists(file_name): return None, f"File does not exist {str(file_name)}" try: tree = galaxy_parse_xml(file_name, remove_comment...
2a9c1f9ab04f3f6805af2614d2e847f401f42588
50,805
import os import time import tqdm def posTag_eval(trainfile, testfile): """评估词性标注模型 Args: trainfile (string): 训练数据集路径 testfile (string): 测试数据集路径 Returns: list: 词性标注结果 """ hmm_pos = HmmPosTag.HmmPosTag() hmm_pos.train(trainfile) posTag_res = [] dataset_size = f...
55ab91c2c09ef8909969b509a69cfaefd48262ec
50,806
def reduce_group_ndims(operation, tensor, group_ndims, name=None): """ Reduce the last `group_ndims` dimensions in `tensor`, using `operation`. In :class:`~tfsnippet.distributions.Distribution`, when computing the (log-)densities of certain `tensor`, the last few dimensions may represent a group of...
d94c5aec353bfde8cc4df56c67eca3be6d7efc41
50,807
def items_id(collection_id, item_id, roles=None): """Retrieve a given feature from a given feature collection. :param collection_id: identifier (name) of a specific collection :param item_id: identifier (name) of a specific item """ item = get_collection_items(collection_id=collection_id, roles=rol...
d5c0d80bced6941c983631d98a49530612f9618c
50,808
def Bi_RNN(vocab_size, embedding_matrix,ckpt_path,max_len,embedding_size): """ bi-RNN + GRU :param vocab_size: :param embedding_matrix: :param ckpt_path: :param max_len: :param embedding_size: :return: """ model = Sequential() model.add(Embedding(len(vocab_size),embedding_size,input_length=max_len)) model.a...
7343db59b3b1accaddbcd718f6880725c4ce7dc4
50,809
import torch def sample_patch_multiscale(im, pos, scales, image_sz, mode: str='replicate', max_scale_change=None): """Extract image patches at multiple scales. args: im: Image. pos: Center position for extraction. scales: Image scales to extract image patches from. image_sz: Si...
1094ca452b78dbcd77bf481a4055a751481c303c
50,810
def make_accumulate_client_votes_fn(round_num, discovered_prefixes_table, possible_prefix_extensions_table): """Returns a reduce function that is used to accumulate client votes. This function creates an accumulate_client_votes reduce function that can be consumed by a tf.data...
b64d53eba57d134d78d9ad5d357b3ce5639e76df
50,811
def octave_to_frequency(octave: float) -> float: """Converts an octave to its corresponding frequency value (in Hz). By convention, the 0th octave is 125Hz. Parameters ---------- octave : float The octave to put on a frequency scale. Returns ------- float The frequency value c...
d50fe69e0dd267b5418834ca2999867213b5f306
50,812
import array def clause_tensor(l, q=2, g=oror, m=0, dtype=int): """ Return tensorization of the truth table of gate g. Generally, g is a l-ary relation in the constraint language of a (weighted) CSP and this function returns a tensor representation of the relation g. """ d = [q] * l ...
ce6804b478bc0a380a957f2a26c912edfb56e65d
50,813
def predictions_wavfile(data, model_type): """ Takes the embeddings of wav file and runs the predictions on it """ # call the model and load the weights model = create_keras_model() if model_type == "Motor": model.load_weights("../predictions/binary_relevance_model/Binary_Relevance_Mode...
0f714454def30ed2883b1da184148391a1c52f83
50,814
import re def _trim_endpoint_api_version(url): """Trim API version and trailing slash from endpoint.""" return re.sub(_API_VERSION_RE, '', url)
207fb5f46c52d92a1cf40c969ad80f2c9891349c
50,815
def get_mmp(option, maps=None, out_put=None, target_id=None, extra=None): """Function to find the MMP comparison Takes a pk of the MMP comparison Returns the SD block of that data""" mmp = MMPComparison.objects.get(pk=option) return mmp.sdf_info
7c0bcb9c2d6b63e508ba411333fb8e7dfb75218e
50,816
def insertion(word1, word2): """ Args: word1: String, a double occurrence word. word2: String, a double occurrence word. Returns: A boolean indicating whether word2 can be constructed by inserting a repeat word or return word into word1. If it can, then the two indi...
3290e722eb55e4a274237fa5dca71ae4767fd003
50,817
import copy def consolidate_trcks(x, include_end=False): """ Consolidates all midi.events in a midi.Pattern into a single track """ if isinstance(x, midi.Pattern): old_ptrn = x else: old_ptrn = midi.Pattern(format=1, resolution=480, tick_relative=True,) for trck in x: ...
ab782d691fe557ca17c1eb70520d7334102f6844
50,818
def calculate_curtailment_time_series(scenario): """Calculate hourly curtailment for each renewable generator. :param powersimdata.scenario.scenario.Scenario scenario: scenario instance. :return: (*pandas.DataFrame*) -- time series of curtailment. """ _check_scenario_is_in_analyze_state(scenario) ...
a8bbaca06e01f67ce4fba717cb8a5556a766aa6b
50,819
def index(): """List archived parties.""" parties = party_service.get_archived_parties_for_brand(g.brand_id) parties = [p for p in parties if not p.canceled] return { 'parties': parties, }
1231f9c7690a7570002f0a2ff27e084ac1f35111
50,820
import os def get_ext_paths(root_dir, exclude_files): """get filepaths for compilation""" paths = [] for root, dirs, files in os.walk(root_dir): for filename in files: if os.path.splitext(filename)[1] != '.pyx': continue file_path = os.path.join(root, file...
a488812617e43d6395b7fe9a19ac55214c3f8648
50,821
def getMessageLength(imageArray): """gets the message length out of the first 8 pixels""" length = "" for i in range(8): for j in range(3): length += str(imageArray[i][j] % 2) if doLogOutput: print(f"Binary length: {str(length)}") print(f"Decimal length: {str(int(len...
97553fb1bbcbda0bcdbc4392da4b2f03594e3a74
50,822
import re def find_orbitals_from_statelines(out_info_dict): """ This function reads in all the state_lines, that is, the lines describing which atomic states, taken from the pseudopotential, are used for the projection. Then it converts these state_lines into a set of orbitals. :param out_info_di...
8d3487013b33f0e9eed14b93d8958ad7e270d9d9
50,823
def EI(model, _, X, xi=0.0): """ Expected improvement policy with an exploration parameter of `xi`. """ model = model.copy() target = model.predict(X)[0].max() + xi def index(X, grad=False): """EI policy instance.""" return model.get_improvement(target, X, grad) return inde...
89e67b14abf6d0c2b76dc45da37281c9c7a01cf9
50,824
def scoring(es_doc): """Return the final scored instance as an elasticsearch-format document.""" doc = {"_source": es_doc[1], "_id": es_doc[0], "_index": get_index_name(), "_type": get_type_name() } result = score_instance(doc) return (es_doc[0], result["...
9e6fb573965d6a7366b2886fc46f8281b8b0737a
50,825
def TFlt_GetMegaStr(*args): """ TFlt_GetMegaStr(double const & Val) -> TStr Parameters: Val: double const & """ return _snap.TFlt_GetMegaStr(*args)
a441ad0288fe891846028c4556d2704039296e36
50,826
def format_metrics_map(metrics_map): """Properly format iterable `metrics_map` to contain instances of :class:`Metric` Parameters ---------- metrics_map: Dict, List Iterable describing the metrics to be recorded, along with a means to compute the value of each metric. Should be of one o...
f366411164879d692d1d1885881c3b5e1b2fe1c2
50,827
import re def add_categories(user_id): """This route handles posting categories""" if request.method == "POST": name = str(request.data.get('name')).strip() name = re.sub(' +',' ', name) resultn = valid_category(name) if resultn: return jsonify(resultn), 400 ...
8df979871c3239b59e3e6c4972f74b15e8bdd8d7
50,828
def WV_WI(bands: dict) -> xr.DataArray: """ WorldView-Water (WV-WI) Useful for detecting standing, flowing water, or shadow in VNIR imagery WV_WI = ((B8-B1)/(B8+B1)) https://resources.maxar.com/optical-imagery/multispectral-reference-guide Args: bands (dict): Bands as {band_name: xr.Da...
5db242ca23ac405d03aa5edc536dae7e6e60db3b
50,829
def api_settings_gui(request): """Test utility.""" auth = get_auth(request) obj = SettingsGui(auth=auth) check_apiobj(authobj=auth, apiobj=obj) return obj
b1f923b60f3eeb5a0a77809c9dc7cd4d41298439
50,830
import numpy def _geometric_mean(array): """Calculate a geometric mean of numpy array of floats. Returns: float, unless array contains a ``nan``, then returns ``nan``. """ return numpy.prod(array)**(1./len(array))
46ca9ec3be68ed3a2687579b2369f082dc030429
50,831
def helicsCreateCore(type: str, name: str, init_string: str) -> HelicsCore: """ Create a `helics.HelicsCore`. **Parameters** - **`type`** - The type of the core to create. - **`name`** - The name of the core. It can be a nullptr or empty string to have a name automatically assigned. - **`init_...
f58cc855650752088b388309d4a3ad6794118a42
50,832
def _complete_choices(msg, choice_range, prompt, all=False, back=True): """Return the complete message and choice list.""" choice_list = [str(i) for i in choice_range] if all: choice_list += ['a'] msg += '\n- a - All of the above.' if back: choice_list += ['b'] msg...
0e5052643cd027d760b08b22bc5f14608845fcb2
50,833
def is_snippet(abbr, doc_type = 'html'): """ Check is passed abbreviation is a snippet @return bool """ return get_snippet(doc_type, abbr) and True or False
8b04700dc7bf7bc5583a6e5971467023afc399c6
50,834
def compute_entropy(x, k=1, norm='max', min_dist=0.): """ Estimates the entropy H of a random variable x (in nats) based on the kth-nearest neighbour distances between point samples. Implementation credits: Paul Brodersen @reference: Kozachenko, L., & Leonenko, N. (1987). Sample estimate of the ...
f9cdbac4fb2cbbcb50d32544f7288202c4d4f372
50,835
import random def building_data_one_per_par(collection,minlen=10,regression=False,time=False,subdir=None,save=False): """Builds the training and out-of-sample sets. Parameters ---------- collection : data in class format Returns ------- list x: list of Numpy data set, ...
10b1554f3597bda86f4abace27f4f5594518d19d
50,836
def create_item(item_create: ItemCreate = Body(..., example=ItemFactory.mock_item)): """ create an item """ return item_service.create_item(item_create)
820e7dc538d5fdbd5812bbbc8b9a85d98759966c
50,837
def satellite_ref(sat): """ To load the band_names for referencing either LANDSAT8 or LANDSAT7 bands """ if sat == 'LANDSAT_8': sat_img = bands_ls8 elif sat == 'LANDSAT_7' or sat == 'LANDSAT_5': sat_img = bands_ls7 else: raise ValueError('Satellite data Not Supported') ...
a4003120c24291e5ea75a5b35e98b911a3f37586
50,838
def is_bitcode_file(path): """ Returns True if path contains a LLVM bitcode file, False if not. """ with open(path, 'rb') as f: return f.read(4) == b'BC\xc0\xde'
acfd17eee949f42994b2bc76499ee58c710eb388
50,839
def licensed(name): """Ensure that Crowdstrike is licensed. .. note:: This state will ONLY license crowdstrike if it isn't licensed. This state should NOT be used to change the license. name: the customer id to license the machine with. """ ret = {'name': name, 'result': Tr...
0021f2d1ac13334db52e5aa16150d0c32f2e19ce
50,840
def PEI_threshold(gp, u, idxU, boundsK): """find the minimum of the prediction for u fixed and compares it with the current evaluated minimum. It serves as the threshold for the PEI criterion :param gp: GaussianProcessRegressor :param u: value that is fixed :param idxU: index of u :param bo...
076563030d29d16af6d6f3a7021141d2f6d71eae
50,841
def gaussian_blur(x: np.ndarray, sigma: float, multichannel: bool = True, xrange: tuple = None) -> np.ndarray: """ Apply Gaussian blur. Parameters ---------- x Instance to be perturbed. sigma Standard deviation determining the strength of the blur. multichannel Wheth...
8a6f3430d7068ca56cb771d673be2b9c322573cd
50,842
def is_vocalized(word): """Checks if the arabic word is vocalized. the word musn't have any spaces and pounctuations. @param word: arabic unicode char @type word: unicode @return: if the word is vocalized @rtype:Boolean """ if word.isalpha(): return False for char in word: ...
afb57cba18ec6c1d3de23d62834439f78c311d46
50,843
from datetime import datetime import pytz from typing import Type def request_extra_time(request): """creates sends an email to the responsible about the user has requested extra time """ # get logged in user as he review requester logged_in_user = get_logged_in_user(request) task_id = reques...
91d170ca6cd45baf07200718dbaa933d05994787
50,844
import os def dataset_to_problem(file, X_cols = None, y_cols = None, T = 1): """ file (string or dataframe): file path or dataframe X (list of strings): y (list of strings): """ if(type(file) is str): tigerforecast_dir = get_tigerforecast_dir() datapath = os.path.jo...
b3915b7ae20be18cf1ddec2bd0f8408e672f529f
50,845
from typing import Callable def _get_and_deflate( function: Callable, base_year: int, target_currency: str = None, col: str = "value", ) -> pd.DataFrame: """Get data using a specific function and apply an exchange rate and deflators if provided""" if target_currency is None: df = ...
e3cab928c824fa9db26958da778a5d30c4a75920
50,846
def main(args=None): """Console script for sentry_onboarding.""" app.run() return 0
cef848459f9f38d5aec1e1fd3c433e511888f446
50,847
import json def responder(): """ Listen to webhooks. Returns ------- response : flask.Response object Response object that is used by default in Flask. """ response = Response(status=200) try: loan_data = request.get_json(force=True, silent=True) trading.b...
59fc385c0207541d02a4e5fb667384bd591a7a80
50,848
def equalization_line(data, key, equilibrium_point): """ Создание линии эквализации. Уравнение прямой с плавающей температурой является прямой с углом наклона, большим, чем 0 градусов. Таким образом, она выражается следующим равенством: y_float = kx = [y(f) - y(0)] / N * x, где а - время в конце, N ...
d3834a738c790b0f0d064f52710db0f93ba3813f
50,849
import torch def pairwise_landmark_ranking_loss_step(model, data, search_space, criterion, args, change_model_spec_fn, module_forward_fn, rank_obj=None, pair_indicies=None): """ Compute the ranking loss: for landmark model...
28b6967a4958304795e5d199cee8ea56a90af968
50,850
def get_org_repo_owner(repo_id): """ Get owner of org repo. """ try: owner = seafserv_threaded_rpc.get_org_repo_owner(repo_id) except SearpcError: owner = None return owner
ddb5699f27a2d326d49dcfb3a24a654db1e71edf
50,851
def remove_from_user_path(path: str): """ Remove **one** path from PATH of current user """ assert ';' not in path old_paths = get_user_path() new_paths = [i for i in old_paths if not is_same_file(i, path)] if new_paths != old_paths: return set_user_path(new_paths)
192f65236bb0b205e9673b2a6970d05074115dd8
50,852
def read_one(activatorId): """ Responds to a request for /api/application_meta/{activatorId} :param application: activatorId :return: count of applications that match the acivatorId """ acount = Application.query.filter(Application.activatorId == activatorId).count() data = ...
a7e47987f0e50ac33fabf17627617e9bc342213f
50,853
import sys import os def host_arch_cc(): """Host architecture check using the CC command.""" if sys.platform.startswith('aix'): # we only support gcc at this point and the default on AIX # would be xlc so hard code gcc k = cc_macros('gcc') else: k = cc_macros(os.environ.get('CC_host')) match...
e564bb7c7282c1fab2e7b6b7e0780fd1539e5e27
50,854
def server_role_def(role): """Defines various role objects""" server_roles = {'simple' : {'groups' : ['default', 'web'], 'ami' : 'precise64', 'role' : SimpleRole} } return server_roles[role]
fa5f21c90db929e2e64d5fc5e580fec494c09698
50,855
import platform def get_session(module): """Return System Object or Fail""" user_agent = '%(base)s %(class)s/%(version)s (%(platform)s)' % { 'base': USER_AGENT_BASE, 'class': __name__, 'version': VERSION, 'platform': platform.platform() } array_name = module.params['fa...
3cd2233286f928c964f94aeac6025fc12504345b
50,856
def read_line_values_as_array(file_path, dtype, line_no): """ Reads in chemical potential multipliers """ success = True error = "" values = None if not check_file: success = False error = "File: %s cannot be found." % (file_path) else: try: f = open(file_path) ...
d40719344212c4077d05232dc97d47640a2a764b
50,857
def comment_delete_answer(request, comment_id): """ HelloWorld 답글댓글삭제 """ comment = get_object_or_404(Comment, pk=comment_id) if request.user != comment.author: messages.error(request, '댓글삭제권한이 없습니다') return redirect('HelloWorld:detail', question_id=comment.answer.question.id) el...
8d6ae80677f43e826db934ecbce3b16e3713f5cd
50,858
def _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1), block_id=1): """Adds an initial convolution layer (with batch normalization and relu6). # Arguments inputs: Input tensor of shape `(rows, cols, 3)` (with `channels_last` data format) or (3, rows, cols) (with ...
b7ff0047313e66e443173c886f0ac1bd079ed143
50,859
from typing import List def get_file_pattern() -> List[str]: """ Returns a list with all possible file patterns """ return ["*.pb", "*.data", "*.index"]
8c4f471dea29dfe5c79cf3ea353cb1a335a5cf45
50,860
from typing import OrderedDict async def async_setup(hass: HomeAssistantType, config: OrderedDict) -> bool: """Set up songpal environment.""" conf = config.get(DOMAIN) if conf is None: return True for config_entry in conf: hass.async_create_task( hass.config_entries.flow.as...
eec8d48b721ff034b1d8cba9719979448065bfd2
50,861
def features_to_nonpadding(features, inputs_or_targets = 'inputs'): """See transformer.features_to_nonpadding.""" key = inputs_or_targets + '_segmentation' if features and key in features: return tf.minimum(tf.to_float(features[key]), 1.0) return None
fcbcac44ef28e0b68188f9295df0c244e90677d9
50,862
import copy import itertools def _make_inner_dense(sparse_nested_table, outer_inner_cards, default_value): """ Convert n sparse nested table dictionary's implicit default values in the innetables to real entries so that all possible assignments are present in the inner sub tables. :param sparse_neste...
372861e9a38016e0426ff29b62eb47fd82ff9631
50,863
def xcafdoc_DatumRefGUID(*args): """ * Return GUIDs for TreeNode representing specified types of datum :rtype: Standard_GUID """ return _XCAFDoc.xcafdoc_DatumRefGUID(*args)
7a84fd9ba0f46266bcb8c7a2e2a205a358ae46ab
50,864
import select import json def get_cohort_dictionary(conn, table_name, year): """Get cohort dictionary.""" s = select([column("cohort_id"), column("features"), column("size")])\ .select_from(table("cohort"))\ .where(column("table") == table_name) if year is not None: s = s.where(col...
1af83b0d877474a163c60e5b9c8accb60e5ee7c0
50,865
def SceneItemListsAddItemLists(builder, itemLists): """This method is deprecated. Please switch to AddItemLists.""" return AddItemLists(builder, itemLists)
8eb80bc94dbac413873963f2b4f0df9b56b0e243
50,866
from typing import Union def native_median(data: Union[list, np.ndarray, pd.Series]) -> float: """ Calculate Median of a list. :param data: Input data. :type data: list, np.ndarray, or pd.Series :return: Returns the Median. :rtype: float :example: *None* :note: If multiple values hav...
fbecfcefb29bd6cf7595936537a6b49a726050d0
50,867
import torch def extract_tensor_batch(t, batch_size): """ batch extraction from tensor """ # extracs batch from first dimension (only works for 2D tensors) idx = torch.randperm(t.nelement()) return t.view(-1)[idx][:batch_size].view(batch_size,1)
291ee82385dad8ad6a60ced0759900a8fb71e0c5
50,868
import pandas def main(): """Main function.""" # Print program info print('AlfheimDataset features program.') # Specify the list of files to read files = ['2013-11-03_tromso_stromsgodset_first_ONLY_ONE_MINUTE.csv']#'2013-11-03_tromso_stromsgodset_first.csv']#, '2013-11-03_tromso_stromsgodset_sec...
d80884b3665f82497fe5025d47ddbc48a5f79e4d
50,869
import os def should_preserve(dir_name): """ Should the directory be preserved? :returns: True if the directory contains a file named '.preserve'; False otherwise """ preserve_path = os.path.join(dir_name, PRESERVE_FILE) if os.path.isdir(dir_name) and os.path.exists(preserve_pat...
fd4b143b37a10b3b67135ba1cce9a9f92b2c3bd9
50,870
def handle_optional_login(func): """ Doesn't show error if no user logged in """ def handle(*args): user_g = users.get_current_user() if user_g: curr_user = user(email=user_g.email()) else: curr_user = None return func(*args, curr_user=curr_user) return handle
21f8dcfe70dbc577a432f0e36bb2f6627677afce
50,871
def charPresent(s, chars): """charpresent(s, chars) - returns 1 if ANY of the characters present in the string chars is found in the string s. If none are found, 0 is returned.""" for c in chars: if str.find(s, c) != -1: return True return False
cac51d18788ae4556609f5f289eb8dbb0741fc79
50,872
def get_dimensions(model_dict): """Extract the dimensions of the model. Args: model_dict (dict): The model specification. See: :ref:`model_specs` Returns: dict: Dimensional information like n_states, n_periods, n_controls, n_mixtures. See :ref:`dimensions`. """ all_n_p...
05898dc93cde86f30b56d09b602a1ba3c8a0a824
50,873
def assign_rank(subs, rank, tree, rankdic, root=None, above=False, major=None, ambig=False): """Assign query to a fixed rank in a classification system. Parameters ---------- subs : set of str Subjects. rank : str Target rank. tree : dict Hierarchical cla...
f65e33d8d8cbc0bd73982b8dd22572e0b12efce3
50,874
def parse_rating(line): """ Parses a recommendation. Format: userId\tgender\tage\toccupation\tavg_rating\trmse\tlabels Parameters ---------- line : str The line that contains user information Returns ------- list : list A list containing gender, age, labels """ ...
9860d05e7a53f9a1710433f9f9f9154e4a4e4435
50,875
import random def enterfn(fname, call=None): """ Start a new call of the given function type :param fname: Function name. All instances of the same function should execute the exact same sequence of instructions :param call: Call name. Should be globally unique (autogenerated if not given) :return...
4ab15ecd2762817ee6b34aa9885c4ed3602d90da
50,876
import urllib def delete_plugin(name): """ Delete all the versions of a plugin by name. Returns: None Raises: 404 - NotFoundError 500 - ChaliceViewError """ try: name = urllib.parse.unquote(name) print(f"Deleting plugin '{name}' and all its versions"...
8ca08d98d6ced2157ed1fe4b08e6e1b464803cef
50,877
def err_ratio(cases): """calculate error ratio Args: cases: ([case,]) all cases in all parts Return: float """ return 1 - len(list(filter(lambda x: x['valid'], cases))) / len(cases)
421905b46c594d99b091e4d6ad094092c4483faa
50,878
def _ProcessPhaseCond(cond, alias, phase_alias, _snapshot_mode): """Convert gate:<phase_name> to SQL.""" op = cond.op if cond.op == ast_pb2.QueryOp.NE: op = ast_pb2.QueryOp.EQ elif cond.op == ast_pb2.QueryOp.NOT_TEXT_HAS: op = ast_pb2.QueryOp.TEXT_HAS cond_str, cond_args = _Compare( phase_alia...
1395e084071fcf0621e92d5c2829fe2bab3188b1
50,879
from typing import Union from typing import NoReturn import sys def get_feed_times_until_mount(pet_name: str, food_name: str) -> Union[int, NoReturn]: """ Return how often a pet needs to be fed until it turns into a mount. :param pet_name: the pet to be fed :param food_name: the food to give the pet ...
f7d870cac53a32493094f52f447e572c6964f7ed
50,880
def config_valid(loaded_config): """ Test if the given dictionary contains valid values for the r0_to_dl3 processing. Not all combinations are sensible! Parameters: ----------- loaded_config: dict Dictionary with the values in the config file Returns: -------- True if ...
9f15cff7fee4e22c6635797ddd52261b8f9c930c
50,881
def create_keymaps(raw_keymaps): """Create `Keymap` object from `raw_keymaps`.""" keymap_objs = [] for raw_keymap in raw_keymaps: try: keymap_obj = KeymapCreater.create(raw_keymap) keymap_objs.append(keymap_obj) except exception.InvalidKeymapException as e: ...
5d26613f39b423fc0db2607b03e7d6fa69718da9
50,882
def get_param_cols(columns): """ Get the columns that were provided in the file and return that list so we don't try to query non-existent cols Args: columns: The columns in the header of the provided file Returns: A dict containing all the FPDS query columns that the provi...
8a0030c745d2de5bd2baf93af79efce4dcb4c696
50,883
import re def depluralize(word): """Return the depluralized version of the word, along with a status flag. Parameters ---------- word : str The word which is to be depluralized. Returns ------- str The original word, if it is detected to be non-plural, or the dep...
9d879a320da566bceb6e5db6cbfe2e7f23f9bb73
50,884
from typing import List def generate_text(n: int, **kwargs) -> List[str]: """ :param n: number of words :return: """ words = [generate_word(**kwargs) for _ in range(n)] return words
fdf08af9ea537255c38d5004e814e3d137448b67
50,885
def do_process_user_file_chunks(count, error_handler, skip_count, participant): """ Run through the files to process, pull their data, put it into s3 bins. Run the file through the appropriate logic path based on file type. If a file is empty put its ftp object to the empty_files_list, we can't delete ...
bbd916d327f7db61e730c9d337546fa3b86f89fe
50,886
def TInt_GetInRng(*args): """ TInt_GetInRng(int const & Val, int const & Mn, int const & Mx) -> int Parameters: Val: int const & Mn: int const & Mx: int const & """ return _snap.TInt_GetInRng(*args)
30be5d5f6dbad6b119192f71c039e88c3af69b05
50,887
async def room_data(room_id: int, redis: Redis = Depends(get_redis)): """Get the current state of the room. The clients maintain their own state, which _should_ each be accurate, but as not all clients may join before one of the clients start making changes to the room's state. """ return get_r...
e5d7200eab587e38f85d7941c294a7e74bf7b6fb
50,888
def get_reference_model(model, endog, exog): """ Build an `UnobservedComponents` model using as reference the input `model`. We need an exactly similar object as `model` but instantiated with different `endog` and `exog`. Args ---- model: `UnobservedComponents`. Template model t...
2139ca7fe371ef9547d38fa4ca604600fb38735b
50,889
def remove_suffix_ness(word): """ :param word: str of word to remove suffix from. :return: str of word with suffix removed & spelling adjusted. This function takes in a word and returns the base word with `ness` removed. """ # print(word[:-4]) word = word[:-4] if word[-1] == "i": ...
c8fa4e55a8eaa1259e66a90adc60329d3a9bc3c9
50,890
import ipaddress def _get_network_address(ip, mask=24): """ Return address of the IPv4 network for single IPv4 address with given mask. """ ip = ipaddress.ip_address(ip) return ipaddress.ip_network( '{}/{}'.format( ipaddress.ip_address(int(ip) & (2**32 - 1) << (32 - mask)), ...
bb706209cc7295ab1d0b4bf88e11d3efba10d526
50,891
def happy_birthday(name, age:hug.types.number): """Says happy birthday to a user""" return "Happy {age} Birthday {name}!".format(**locals())
2483f1f1e47720e93772a4fddf3486c3cb39e2be
50,892
def get_admin_ids(bot, chat_id): """ Returns a list of admin IDs for a given chat. Results are cached for 1 hour. Private chats and groups with all_members_are_administrator flag are handled as empty admin list """ chat = bot.getChat(chat_id) if chat.type == "private" or chat.all_members_are_adm...
6bd89e1d6b7333d97cbc60fd2617a86d1b69fb2f
50,893
import torch def multiply_conj(x, y): """Return x * conj(y) in complex form.""" x_real, x_imag = unpack(x) y_real, y_imag = unpack(y) yconj_real = y_real yconj_imag = -y_imag return torch.stack( [ x_real * yconj_real - x_imag * yconj_imag, x_imag * yconj_real + ...
89bbd49d5052aa4f3c6ef611c461b4fb44c82070
50,894
def read_results_file(filename): """ For n=3 with automatic interval selection, reads in the results file to get C Args: filename: location of results file Returns: C: list form of the second column of the result copy number profile """ with open(filename) as f: lines = ...
0c9854476ed28142930b21bf55df54c63a598fd5
50,895
from typing import List from typing import Union def find_data_paths(parent_group: h5py.Group, data_name: str, first_only: bool = False) -> List[str]: """ Returns list of data_paths to data with 'data_name'. If first_only is True, then will return the first found matching data_path as a string Args: ...
204b704d92598b3414ac0dcc13f1b0a8ecb8a7f1
50,896
from typing import List def initial_models(petab_problem_yaml) -> List[Model]: """Models that can be used to initialize a search.""" initial_model_1 = Model( model_id='myModel1', petab_yaml=petab_problem_yaml, parameters={ 'k1': 0, 'k2': 0, 'k3': 0, ...
05b85e54629b831d1fa16001239d8a4da2e50c29
50,897
def log10(column): """ Computes the logarithm of the given value in base 10 """ return _with_expr(exprs.Log10, column)
b18296eb0c03d866f483b804deca7bb95d6eb68e
50,898
from typing import List from typing import Union def get_data_query( id: str = Query(..., title="Observatory code"), starttime: UTCDateTime = Query( None, title="Start Time", description="Time of first requested data. Default is start of current UTC day.", ), endtime: UTCDateTi...
51b10c4f529447267dc26465194716d4f9543cfa
50,899