content
stringlengths
22
815k
id
int64
0
4.91M
def Ignore(el, scopes, sc): """Literal RegExpLiteral Directive EmptyStatement DebuggerStatement ThrowStatement UpdateExpression ImportExpression TemplateLiteral ContinueStatement BreakStatement ThisExpression ObjectPattern ArrayPattern""" # I assume that template strings will be used only for strings, not for DOM el...
16,700
def history_save_to_txt(path, data): """ Cette fonction permet de sauvegarder l'historique dans un fichier txt. Args: path (str): Fichiers TXT correspondants data (dict): Donnees à déposer dans le fichier """ count_round = len(data["history"]) success = False out = False giv...
16,701
def prod(a, axis=None, dtype=None, out=None): """ Product of array elements over a given axis. Parameters ---------- a : array_like Elements to multiply. axis : None or int or tuple of ints, optional Axis or axes along which a multiply is performed. The default (`axis` =...
16,702
def demo(printer, **kwargs): """ Prints demos. Called when CLI is passed `demo`. This function uses the DEMO_FUNCTIONS dictionary. :param printer: A printer from escpos.printer :param kwargs: A dict with a key for each function you want to test. It's in this format since it usually comes fr...
16,703
def sample_pagerank(corpus, damping_factor, n): """ Return PageRank values for each page by sampling `n` pages according to transition model, starting with a page at random. Return a dictionary where keys are page names, and values are their estimated PageRank value (a value between 0 and 1). All ...
16,704
def guess_layout_cols_lr(mr, buf, alg_prefix, layout_alg_force=None, verbose=False): """ Assume bits are contiguous in columns wrapping around at the next line Least significant bit at left Can eithe...
16,705
def decrease(rse_id, account, files, bytes, session=None): """ Decreases the specified counter by the specified amount. :param rse_id: The id of the RSE. :param account: The account name. :param files: The amount of files. :param bytes: The amount of bytes. :param session: The database...
16,706
def write_vec_flt(file_or_fd, v, key=''): """ write_vec_flt(f, v, key='') Write a binary kaldi vector to filename or stream. Supports 32bit and 64bit floats. Arguments: file_or_fd : filename or opened file descriptor for writing, v : the vector to be stored, key (optional) : used for writin...
16,707
def get_import_error(import_error_id, session): """ Get an import error """ error = session.query(ImportError).filter(ImportError.id == import_error_id).one_or_none() if error is None: raise NotFound("Import error not found") return import_error_schema.dump(error)
16,708
def payment_reversal(**kw): """ 冲正交易 """ req_packet = py8583.Iso8583(IsoSpec=py8583spec.IsoSpec1987BCD()) req_packet.MTI('0400') req_packet.TPDU('6005810000') req_packet.HEADER('603100000000') req_packet.FieldData(3, '190000') # 交易处理码 req_packet.FieldData(4, kw.get('amount', '1').rjus...
16,709
def get_violations(nsi_uuid=None): """Returns info on all SLA violations. :param nsi_uuid: (Default value = None) uuid of a service instance. :returns: A list. [0] is a bool with the result. [1] is a list of SLA violations associated to a service instance. """ url = env.sl_violations_ap...
16,710
def roll_dice(): """ simulate roll dice """ results = [] for num in range(times): result = randint(1, sides) results.append(result) return results
16,711
def _read_calib_SemKITTI(calib_path): """ :param calib_path: Path to a calibration text file. :return: dict with calibration matrices. """ calib_all = {} with open(calib_path, 'r') as f: for line in f.readlines(): if line == '\n': break key, value = line.split(':', 1) calib_all...
16,712
def _bias_act_cuda(dim=1, act='linear', alpha=None, gain=None, clamp=None): """Fast CUDA implementation of `bias_act()` using custom ops. """ # Parse arguments. assert clamp is None or clamp >= 0 spec = activation_funcs[act] alpha = float(alpha if alpha is not None else spec.def_alpha) gain ...
16,713
def root_nodes(g: Mapping): """ >>> g = dict(a='c', b='ce', c='abde', d='c', e=['c', 'z'], f={}) >>> sorted(root_nodes(g)) ['f'] Note that `f` is present: Isolated nodes are considered both as root and leaf nodes both. """ nodes_having_parents = set(chain.from_iterable(g.values())) ...
16,714
def _GetRemoteFileID(local_file_path): """Returns the checked-in hash which identifies the name of file in GCS.""" hash_path = local_file_path + '.sha1' with open(hash_path, 'rb') as f: return f.read(1024).rstrip()
16,715
def stress_stress( bond_array_1, c1, etypes1, bond_array_2, c2, etypes2, sig, ls, r_cut, cutoff_func ): """2-body multi-element kernel between two partial stress components accelerated with Numba. Args: bond_array_1 (np.ndarray): 2-body bond array of the first local environment....
16,716
def update_plugins_secondary_variables_on_tracer_solver(ctx: "void*") -> "int": """ **c++ signature** : ``HOOK_UPDATE_PLUGINS_SECONDARY_VARIABLES_ON_TRACER_SOLVER(void* ctx)`` Internal simulator hook to update plugin's secondary variables in the Tracer Solver scope. Tracer Solver is used to solve the t...
16,717
def is_color_rgb(color): """Is a color in a valid RGB format. Parameters ---------- color : obj The color object. Returns ------- bool True, if the color object is in RGB format. False, otherwise. Examples -------- >>> color = (255, 0, 0) >>> is_col...
16,718
def get_databases( catalog_id: Optional[str] = None, boto3_session: Optional[boto3.Session] = None ) -> Iterator[Dict[str, Any]]: """Get an iterator of databases. Parameters ---------- catalog_id : str, optional The ID of the Data Catalog from which to retrieve Databases. If none is...
16,719
def generate_html(collections): """This function is used to generate the HTML file to browse the photo gallary. """ print('generating HTML:') collection_info = list() # Sorting collections for sorted display collections.sort() for collection in collections: in_path = os.path....
16,720
def edit_post_svc(current_user, id, content): """ Updates post content. :param current_user: :param id: :param content: :return: """ post = single_post_svc(id) if post is None or post.user_id != current_user: return None post.content = content db.session.commit() return True
16,721
def free_free_absorp_coefPQ(n_e,n_i,T,f): """Returns a physical quantity for the free-free absorption coefficient given the electron density, ion density, kinetic temperature and frequency as physical quantities. From Shklovsky (1960) as quoted by Kraus (1966).""" value = 9.8e-13 * n_e.inBaseUnits().value * n_i...
16,722
def module_version(module_lint_object, module): """ Verifies that the module has a version specified in the ``modules.json`` file It checks whether the module has an entry in the ``modules.json`` file containing a commit SHA. If that is true, it verifies that there are no newer version of the modul...
16,723
def test_profile_init(): """ Test that the Profile module initializes correctly. Expected result: profile is initialized """ profile = Profile(os.path.join(os.path.dirname(__file__), "profile.yaml")) assert profile.profile
16,724
def plot_intensities(spikes, lambda0, W, theta, path): """Plot the intensity given event data and fitted parameters.""" seconds = pd.date_range(start='01-02-2013 10:30:00', end='01-02-2013 14:59:59', freq='S') hours = pd.date_range(start='01-02-2013 10:30:00', end='01-02-2013 14:59:59', freq='H') def ...
16,725
def train_net_alter(network, imdb_train_s, roidb_train_s, imdb_train_ws, roidb_train_ws, imdb_test, roidb_test, \ output_dir, pretrained_model=None, \ max_iters=80000, s_start_iter=0, s_end_iter=80000, ws_start_iter=0, ws_end_iter=80000, \ opt='adam', lr=5e...
16,726
def setupBinaries(options): """Ensure that Cactus's C/C++ components are ready to run, and set up the environment.""" if options.latest: os.environ["CACTUS_USE_LATEST"] = "1" if options.binariesMode is not None: # Mode is specified on command line mode = options.binariesMode else...
16,727
def pixel_gain_mode_statistics(gmaps): """returns statistics of pixels in defferent gain modes in gain maps gr0, gr1, gr2, gr3, gr4, gr5, gr6 = gmaps """ arr1 = np.ones_like(gmaps[0], dtype=np.int32) return [np.sum(np.select((gr,), (arr1,), default=0)) for gr in gmaps]
16,728
def run_parallel(ds1, ds2): """ Run the calculation using multiprocessing. :param ds1: list with points :param ds2: list with points :return: list of distances """ pool = mp.Pool(processes=mp.cpu_count()) result = pool.starmap(euclidian_distance, [(p1, p2) for p1 in ds1 for p2 in ds2]) ...
16,729
def to_latin(name): """Convert all symbols to latin""" symbols = (u"іїєабвгдеёжзийклмнопрстуфхцчшщъыьэюяІЇЄАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", u"iieabvgdeejzijklmnoprstufhzcss_y_euaIIEABVGDEEJZIJKLMNOPRSTUFHZCSS_Y_EUA") tr = {ord(a): ord(b) for a, b in zip(*symbols)} translated_name = na...
16,730
def network_instance_create(network, host, attrs=None): """ Creates a network_instance of given kind and host, configuring it with the given attributes. Parameter *kind*: The parameter *kind* must be a string identifying one of the supported network_instance kinds. Parameter *host*: The parameter *host* ...
16,731
def update_get(): """Fetches the state of the latest update job. Returns: On success, a JSON data structure with the following properties: status: str describing the status of the job. Can be one of ["NOT_RUNNING", "DONE", "IN_PROGRESS"]. Example: { ...
16,732
def create_github_url(metadata, is_file=False): """Constrói a URL da API Constrói a URL base da API do github a partir dos dados presentes no metadata. Args: metadata: JSON com informações acerca do dataset. is_file: FLAG usada pra sinalizar se o dataset é apenas um elemento. """ url_params = metadata['url'...
16,733
def kge_2012(obs, sim, missing="drop", weighted=False, max_gap=30): """Compute the (weighted) Kling-Gupta Efficiency (KGE). Parameters ---------- sim: pandas.Series Series with the simulated values. obs: pandas.Series Series with the observed values. missing: str, optional ...
16,734
async def test_entity_device_info_update(opp, mqtt_mock): """Test device registry update.""" await help_test_entity_device_info_update( opp, mqtt_mock, binary_sensor.DOMAIN, DEFAULT_CONFIG )
16,735
def flatten(items): """Yield items from any nested iterable; see REF.""" for x in items: if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): yield from flatten(x) else: yield x
16,736
def hms_to_dms(h, m, s): """ Convert degrees, arcminutes, arcseconds to an ``(hour, minute, second)`` tuple. """ return degrees_to_dms(hms_to_degrees(h, m, s))
16,737
def main( date: datetime = YESTERDAY, telescope: str = "LST1", config: Path = DEFAULT_CFG, simulate: bool = False, ): """Plot theta2 histograms for each source from a given date.""" log.setLevel(logging.INFO) log.debug(f"Config: {config.resolve()}") # Initial setup of g...
16,738
def color_calibration( src_imgs, src_color_space, src_is_linear, ref_imgs, ref_color_space, ref_is_linear, verbose=False, distance="de00", ): """Function that does color calibration for a given target image according to a given reference image STEP1: load the colorcheckers from ...
16,739
def getChiv6ch(mol): """ Chiv6h related to ring 6 """ return getChivnch(mol, 6)
16,740
def test_trend_prec(tmpdir): """A Test Function the plot of the precipitation trend Author: Raphael Tasch """ df_cities = pd.read_csv(cfg.world_cities) dfi = df_cities.loc[df_cities.Name.str.contains('innsbruck', case=False, na=False)].iloc[0] df ...
16,741
def is_outside_of_range(type_key: CLTypeKey, value: int) -> bool: """Returns flag indicating whether a value is outside of numeric range associated with the CL type. """ constraints = NUMERIC_CONSTRAINTS[type_key] return value < constraints.MIN or value > constraints.MAX
16,742
def test_generate_circuit_raises(): """Test raising errors in circuit generator.""" with pytest.raises(TypeError): cirq.Circuit(generate_circuit_from_pauli_string(0, 'theta_0')) with pytest.raises(TypeError): cirq.Circuit(generate_circuit_from_pauli_string( openfermion.FermionOpe...
16,743
def read_skel(dset, path): """ :param dset: name of dataset, either 'ntu-rgbd' or 'pku-mmd' :param path: path to the skeleton file :return: """ if dset == 'ntu-rgbd': file = open(path, 'r') lines = file.readlines() num_lines = len(lines) num_frames = int(lines[0]) # print(num_lines, num_...
16,744
def cmd_start(message): """Старт диалога с ботом""" mainmenu(message)
16,745
def test_safe_failure(): """Ensures that safe decorator works correctly for Failure case.""" failed = _function(0) assert isinstance(failed.failure(), ZeroDivisionError)
16,746
def test_rambo(sqrts=7e3, max_n=8): """Check that rambo produces the right type of phase space""" for n in range(2, max_n): auto_test_rambo_massless(n, sqrts) # Check that it also accepts a variable input energy events = 13 variable_sqrts = tf.random.uniform((13,), dtype=DTYPE) * sqrts ...
16,747
def humanize_date(date_string): """ returns dates as in this form: 'August 24 2019' """ return convert_date(date_string).strftime("%B %d %Y")
16,748
def delete_quota(module, blade): """Delete Filesystem User Quota""" changed = True if not module.check_mode: try: if module.params["uid"]: blade.quotas_users.delete_user_quotas( file_system_names=[module.params["name"]], uids=[modul...
16,749
def get_checkpoint(checkpoint_path, requested_step=None, basename='checkpoint'): """ 根据checkpoint重载模型 """ if requested_step is not None: model_checkpoint_path = '%s/%s-%s' % (checkpoint_path, basename, requested_step) if os.path.exists(model_checkpoint_path) is None: print(...
16,750
def handle_error(exception: Exception, request: Request=None): """ If an exception is thrown, deal with it and present an error page. """ if request is None: request = {'_environ': {'PATH_INFO': ''}} if not getattr(exception, 'hide_traceback', False): (e_type, e_value, e_tb) = sys.e...
16,751
def train_argument_from_bp(params, extractor): """ :type params: dict :type extractor: nlplingo.nn.extractor.Extractor """ print('################ train_argument_from_bp ###############') bp_filepath = params['bp_file'] labels = create_sequence_labels(extractor.domain.event_roles.keys()) ...
16,752
def tree_sanity_check(tree: Node) -> bool: """ Sanity check for syntax trees: One and the same node must never appear twice in the syntax tree. Frozen Nodes (EMTPY_NODE, PLACEHOLDER) should only exist temporarily and must have been dropped or eliminated before any kind of tree generation (i.e. parsi...
16,753
def update_database(path=None, encoding="cp1252", **kwargs): """ Update the reference composition database. Notes ------ This will take all csv files from the geochem/refcomp pyrolite data folder and construct a document-based JSON database. """ if path is None: path = __dbfile_...
16,754
def fileCompare( filename1, filename2, folder1=None, folder2=None, printFlag=True, exitCount:int=10 ): """ Compare the two utf-8 files. """ filepath1 = Path( folder1, filename1 ) if folder1 else filename1 filepath2 = Path( folder2, filename2 ) if folder2 else filename2 if verbosityLevel > 1: ...
16,755
def compute_std_error(g,theta,W,Omega,Nobs,Nsim=1.0e+10,step=1.0e-5,args=()): """ calculate standard errors from minimum-distance type estimation g should return a vector with: data moments - simulated moments as a function of theta Args: g (callable): moment function (ret...
16,756
def p_error(parse): """ Error rule for Syntax Errors handling and reporting. """ if parse is None: print("Error! Unexpected end of input!") else: print("Syntax error! Line: {}, position: {}, character: {}, " "type: {}".format(parse.lineno, parse.lexpos, parse.va...
16,757
def target_thread(sess): """a thread for target nets in DQN""" global obstacles while True: ## get current state for camera_sensor, lane_invasion, obj_collision in zip(cameras, lane_invasions, obj_collisions): img = camera_sensor.get() img = img[int(FLAGS.img_height*...
16,758
def lhs(paramList, trials, corrMat=None, columns=None, skip=None): """ Produce an ndarray or DataFrame of 'trials' rows of values for the given parameter list, respecting the correlation matrix 'corrMat' if one is specified, using Latin Hypercube (stratified) sampling. The values in the i'th column...
16,759
def add_account(account): """ add account for LDAP entry """ type = 'USER' try: client.get_account(account) print 'Account \'' + account + '\' is already registered as Rucio account' except exception.AccountNotFound: client.add_account(account, type, None) pass ...
16,760
def percentError(mean, sd, y_output, logits): """ Calculates the percent error between the prediction and real value. The percent error is calculated with the formula: 100*(|real - predicted|)/(real) The real and predicted values are un normalized to see how accurate the true predic...
16,761
def get_file_names(directory, prefix='', suffix='', nesting=True): """ Returns list of all files in directory Args: directory (str): the directory of interest prefix (str): if provided, files returned must start with this suffix (str): if provided, files returned must end with this ...
16,762
def parse_multiple_files(*actions_files): """Parses multiple files. Broadly speaking, it parses sequentially all files, and concatenates all answers. """ return parsing_utils.parse_multiple_files(parse_actions, *actions_files)
16,763
def frequent_combinations(spark_df: DataFrame, n=10, export=True): """ takes a dataframe containing visitor logs and computes n most frequent visitor-visite pairs :param spark_df: Spark Dataframe :param n: number of top visitors :return: pandas dataframe with visitor-visite pairs """ # com...
16,764
def main(blogname, timesleep=0): """ 多线程处理下载图片部分""" url_sub = find_latest_page(blogname) image = ImagesDownloader() text = TextWriter(blogname) with futures.ThreadPoolExecutor(max_workers=PROCESSES*2) as ex: while url_sub: # 如需设置proxies, 在下行代码设置设置 item, url_sub = page...
16,765
def reservoir_sampling(items, k): """ Reservoir sampling algorithm for large sample space or unknow end list See <http://en.wikipedia.org/wiki/Reservoir_sampling> for detail> Type: ([a] * Int) -> [a] Prev constrain: k is positive and items at least of k items Post constrain: the length of retur...
16,766
def create_db_engine(app: Flask) -> Engine: """Create and return an engine instance based on the app's database configuration.""" url = URL( drivername=app.config['DATABASE_DRIVER'], username=app.config['DATABASE_USER'], password=app.config['DATABASE_PASSWORD'], host=app.config['...
16,767
def wgs84_to_gcj02(lat, lng): """ WGS84转GCJ02(火星坐标系) :param lng:WGS84坐标系的经度 :param lat:WGS84坐标系的纬度 :return: """ dlat = _transformlat(lng - 105.0, lat - 35.0) dlng = _transformlng(lng - 105.0, lat - 35.0) radlat = lat / 180.0 * pi magic = math.sin(radlat) magic = 1 - ee * magi...
16,768
def check_dict(data: dict, dict_name: str, check_str_values=True): """ Check that a given top-level element in 'data' dict is a simple str-to-str dict. """ assert dict_name in data, \ f"Top-level dict must contain key '{dict_name}'." d = data[dict_name] assert isinstance(d, dict), \ ...
16,769
def save_raw_csv(raw_frames: Iterable[Frame], target_path: str) -> None: """ Saves raw_frames as a csv file. """ fields = Frame.get_fields() with open(target_path, "w") as file: wr = csv.writer(file, quoting=csv.QUOTE_NONE) wr.writerow(fields) for frame in raw_frames: wr...
16,770
async def test_reload(hass): """Verify we can reload.""" respx.get("http://localhost") % 200 assert await async_setup_component( hass, DOMAIN, { DOMAIN: [ { "resource": "http://localhost", "method": "GET", ...
16,771
def test_unsigned_byte_enumeration002_1804_unsigned_byte_enumeration002_1804_v(mode, save_output, output_format): """ TEST :Facet Schemas for string : facet=enumeration and value=0 and document value=0 """ assert_bindings( schema="msData/datatypes/Facets/unsignedByte/unsignedByte_enumeration...
16,772
def _normalize_kwargs(kwargs, kind='patch'): """Convert matplotlib keywords from short to long form.""" # Source: # github.com/tritemio/FRETBursts/blob/fit_experim/fretbursts/burst_plot.py if kind == 'line2d': long_names = dict(c='color', ls='linestyle', lw='linewidth', ...
16,773
def fprime_to_jsonable(obj): """ Takes an F prime object and converts it to a jsonable type. :param obj: object to convert :return: object in jsonable format (can call json.dump(obj)) """ # Otherwise try and scrape all "get_" getters in a smart way anonymous = {} getters = [attr for att...
16,774
def subsequent_mask(size: int) -> Tensor: """ Mask out subsequent positions (to prevent attending to future positions) Transformer helper function. :param size: size of mask (2nd and 3rd dim) :return: Tensor with 0s and 1s of shape (1, size, size) """ mask = np.triu(np.ones((1, size, size))...
16,775
def replace(tree: bpy.types.NodeTree, node: 'ArmLogicTreeNode'): """Replaces the given node with its replacement.""" # the node can either return a NodeReplacement object (for simple replacements) # or a brand new node, for more complex stuff. response = node.get_replacement_node(tree) if isinstan...
16,776
def process_entries(components): """Process top-level entries.""" data = {} for index, value in enumerate(STRUCTURE): label = value[0] mandatory = value[1] # Raise error if mandatory elements are missing if index >= len(components): if mandatory is True: ...
16,777
def test_render_changelog_unsupported_type(config): """Test that unsupported types are excluded from the changelog content.""" cz = discover_this(config) parser = cz.commit_parser changelog_pattern = cz.bump_pattern gitcommits = [ git.GitCommit(rev='003', title='feat: started commitizen', bo...
16,778
def normalize_input_vector(trainX: np.ndarray, testX: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Normalize the input vector Args: trainX (np.ndarray): train embedding array. testX (np.ndarray): test embedding array. Returns: np.ndarray, np.ndarray: normalized train and test a...
16,779
def update_cache(cache_data, new_data, key): """ Add newly collected data to the pre-existing cache data Args: cache_data (dict): Pre-existing chip data new_data (dict): Newly acquired chip data key (str): The chip UL coordinates Returns: """ if key in cach...
16,780
def test_empty_data(empty_data): """Test that we gracefully get an empty list of data if we feed an empty string to the function """ yaml_parser.read_yaml(empty_data)
16,781
def status(command, **keys): """Run a subprogram capturing it's output and return the exit status.""" return _captured_output(command, **keys).status
16,782
def normalize(flow: Tensor) -> Tensor: """Re-scales the optical flow vectors such that they correspond to motion on the normalized pixel coordinates in the range [-1, 1] x [-1, 1]. Args: flow: the optical flow tensor of shape (B, 2, H, W) Returns: The optical flow tensor with flow vect...
16,783
def to_graph6_bytes(G, nodes=None, header=True): """Convert a simple undirected graph to bytes in graph6 format. Parameters ---------- G : Graph (undirected) nodes: list or iterable Nodes are labeled 0...n-1 in the order provided. If None the ordering given by ``G.nodes()`` is used....
16,784
def test_inbound_bad_provider(): """Test the inbound user filter with bad provider throws error""" with pytest.raises(TypeError): inbound_user_filter({"id": "123-456-abs3"}, "potato")
16,785
def get_arrays_from_img_label(img, label, img_mode=None): """Transform a SimpleITK image and label map into numpy arrays, and optionally select a channel. Parameters: img (SimpleITK.SimpleITK.Image): image label (SimpleITK.SimpleITK.Image): label map img_mode (int or None): optional mode c...
16,786
def _get_error_code(exception): """Get the most specific error code for the exception via superclass""" for exception in exception.mro(): try: return error_codes[exception] except KeyError: continue
16,787
def render_pep440_branch(pieces): """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . The ".dev0" means not master branch. Note that .dev0 sorts backwards (a feature branch will appear "older" than the master branch). Exceptions: 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["close...
16,788
def read_json_file(file_name: str, encoding: str = "utf-8") -> dict: """Reads a json file :param file_name: path :param encoding: encoding to use :return: dict content """ with open(file_name, "r", encoding=encoding) as json_file: return json.load(json_file)
16,789
def pretty_print_row(col_full_widths, row, max_field_size): """ pretty print a row such that each column is padded to have the widths in the col_full_widths vector """ start = "| " if len(row) == len(col_full_widths): end = " |" else: end = "|" return start + "|".join(pretty_...
16,790
def check_embedding(X, Y, score=0.76): """Compares TSNE embedding trustworthiness, NAN and verbosity""" nans = np.sum(np.isnan(Y)) trust = trustworthiness(X, Y) print("Trust = ", trust) assert trust > score assert nans == 0
16,791
def register(username, password, email): """Register a new user""" auth.register(username, email, password)
16,792
def _get_data_for_agg(new_svarcube, new_tacube): """Reshape data for use in iris aggregator based on two cubes.""" dims_to_collapse = set() dims_to_collapse.update(new_svarcube.coord_dims('air_pressure')) untouched_dims = set(range(new_svarcube.ndim)) -\ set(dims_to_collapse) dims = list(unt...
16,793
def refs_changed_by_other_cc(current_user): """ Return dictionary with id of reference and log object changed by other cooperative centers """ current_user_cc = current_user.profile.get_attribute('cc') result_list = defaultdict(list) # get last references of current user cooperative center ...
16,794
def chain_head(head: int, child: int, heads: Dict[int, int]): """ >>> chain_head(0, 2, {1: 2, 2: 3, 3: 0}) True >>> chain_head(2, 0, {1: 2, 2: 3, 3: 0}) False """ curr_child = child while curr_child != -1: if curr_child == head: return True curr_child = heads....
16,795
def read_conll(fp): """ Generator that returns a list of Row tuples for each document :param fp: handle to CoNLL tsv file with columns: token tag token doc_id start stop sentence :return: list of Row tuples """ reader = csv.reader(fp, delimiter='\t', quoting=csv.QUOTE_NONE) first_row = next(...
16,796
def UpgradeFile(file_proto): """In-place upgrade a FileDescriptorProto from v2[alpha\d] to v3alpha. Args: file_proto: v2[alpha\d] FileDescriptorProto message. """ # Upgrade package. file_proto.package = UpgradedType(file_proto.package) # Upgrade imports. for n, d in enumerate(file_proto.dependency): ...
16,797
def _get_ip_block(ip_block_str): """ Convert string into ipaddress.ip_network. Support both IPv4 or IPv6 addresses. Args: ip_block_str(string): network address, e.g. "192.168.0.0/24". Returns: ip_block(ipaddress.ip_network) """ try: ip_block = ipaddress....
16,798
def mul_ntt(f_ntt, g_ntt, q): """Multiplication of two polynomials (coefficient representation).""" assert len(f_ntt) == len(g_ntt) deg = len(f_ntt) return [(f_ntt[i] * g_ntt[i]) % q for i in range(deg)]
16,799