content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def table_interpolation_trilinear( V_xyz: ArrayLike, table: ArrayLike ) -> NDArray: """ Perform the trilinear interpolation of given :math:`V_{xyz}` values using given interpolation table. Parameters ---------- V_xyz :math:`V_{xyz}` values to interpolate. table 4-Dimensi...
55c386bf7ca42b2e3b955c8ec46e3684b2841a8a
63,500
import torch def __fan(mask, iter): """Fans out bitmask from input to output at `iter` stage of the tree See arrows in Fig. 1 (right) of Catrina, O. "Improved Primitives for Secure Multiparty Integer Computation" """ multiplier = (1 << (2 ** iter + 1)) - 2 if isinstance(mask, (int, float)) or...
e98679e04ff4b4cab2f281bfed0085dfab7a6484
63,501
import tokenize from typing import Counter def count_text(ngram, hash_size, doc_id, text=None): """Compute hashed ngram counts of text.""" row, col, data = [], [], [] # Tokenize tokens = tokenize(utils.normalize(text)) # Get ngrams from tokens, with stopword/punctuation filtering. ngrams = to...
ec7f004976a4726480ebf15246880ae97ae006d6
63,502
def gmtnow(): """ 現在時刻を aware GMT で取得します """ return utcnow().astimezone(gmt)
49131c0caf55105cac3b2a7e194e7b6af69a5cd8
63,503
def is_out_of_boundaries(state): """ Function that detects if the puck is out of the board limits. Returns: None: if is not out of the boundaries str: 'horizontal' or 'vertical' if is out of boundaries. """ # if next_pos_from_state(state)['x'] + state['puck_radius'] >= state['board_shap...
27f34c31086381dfceb8b48b23be68750bd66d1d
63,504
def pointcloud_normalization(ptc1): """Normalize pointcloud as out=(input-input.mean())/input.std()""" if ptc1[:, 0].std() == 0: ptc1[:, 0] = ptc1[:, 0] - ptc1[:, 0].mean() else: ptc1[:, 0] = (ptc1[:, 0] - ptc1[:, 0].mean()) / ptc1[:, 0].std() if ptc1[:, 1].std() == 0: ptc1[:, 1]...
cca4f23d810a56a0f06115de67d2f2ec6feee918
63,505
from typing import Optional def parse( header_text ): """Uses pyparsing to extract information from the header of a mcstas component file. Takes a string of the general form: * Component: componentname * * %I * copyright information * * simple description * * %D * ...
93b542e04358646492039bac99501ddbfa60a0aa
63,506
def all_punctuations_space(text: str) -> str: """ Add spaces after punctuations used in ``urdu`` writing Args: text (str): ``Urdu`` text Returns: str: Returns a ``str`` object containing normalized text. """ text = _SPACE_BEFORE_ALL_PUNCTUATIONS_RE.sub(' ', text) text = _SPA...
4c6b384def762a6ac0b591a8fa86a188bac94c9f
63,507
def selftest_function(opts): """ Placeholder for selftest function. An example use would be to test package api connectivity. Suggested return values are be unimplemented, success, or failure. """ try: options = opts.get("fn_hibp", {}) hibp = Hibp(options) test_url = "{0}/{1...
9f08521ed34f0ff402ef90c65d4a5dbc04ccbfb2
63,508
def duration_to_basic_name(duration, ppq): """ Gets a note duration name for a given duration. :param duration: duration :type duration: int :param ppq: ppq (midi pulses per quarter note) :type ppq: int :return: C128 BASIC name for the duration :rtype: str """ f = constants.Frac...
3c0cb19118da15267d562a38d1a0df24a54f85cc
63,509
import scipy def calc_fn_rate_override(M, N, m, s, rho, alpha, test_type, override_diff): """ :param M: :param N: :param m: :param s: :param rho: :param alpha: :param test_type: :param offset: :param sign: :param override_diff :return: """ if not is_iterable(s)...
5b880daa066cfec21832e3bc24ed3023a5f3b621
63,510
def create_single_choice_dom_from_option(option): """ Creates dom look for a specific option of a question """ doc = minidom.Document() li = doc.createElement("li") li.attributes["class"] = "choice" # Each list element has a 'selector', i.e the option that can be selected # and a 'resp...
5632c7253177aae52447b3686288cb5d01a4de12
63,511
import os from datetime import datetime def command_cgi(): """ Implementation of the FlashAir API endpoint that are relevant for debugging the client application. FlashAir API documentation: https://www.flashair-developers.com/en/documents/api/commandcgi/ Implemented operations: - Get ...
2fd8d4160c553d1a2db4b2ef07cab7cbbc700a9e
63,512
def pow_sq(x, y): """ Compute x^y, without calling its pow, using exponentiation by squaring. """ r = 1 while y: if y & 1: r = r * x x = x * x y >>= 1 return r
f6d82257ff909d9c890360dcd9408db0d742b13d
63,513
def backend_table_spec(backend: Backend, db_name: str, table_name: str) -> TableSpec: """ >>> from jasmine.etl.backends import example_create_sqlite_schema_statements, tmp_mock_sqla_backend >>> from pprint import pprint >>> with tmp_mock_sqla_backend(example_create_sqlite_schema_statements) as backend:...
3ca68d3d6bf8c7ce52be0bcee11867b14b84005c
63,514
from typing import Any def _sort_key_source(item: CollectorItem) -> Any: """Return a sort key for 'source' sorting of CollectorItems.""" # if 'line_start' isn't found on the object, the item will go to # the start of the list. return item.get("source", {}).get("line_start", -1)
9f3a6ccbd43f171eeec466cc88f47234615791e3
63,515
import logging import os import fnmatch def find_tpf_files(rootdir, starid=None, sector=None, camera=None, ccd=None, findmax=None): """ Search directory recursively for TESS Target Pixel Files. Parameters: rootdir (string): Directory to search recursively for TESS TPF files. starid (integer or None, optional)...
2f71a26ca4eff62fe166fd2e736d6c2d11a99643
63,516
def parse_ascii_input(filename): """Parse station info from an input file. This function will try to read Stations of from the input file, named filename. For this to work, the lines in the input file, should conform to the following format: "name lon lat Ve Vn Se Sn RHO T" ...
0e2c40b72d2ee02c8358aac515686568d7eb01d9
63,517
def current_minor_solar_term(date): """Return last Chinese minor solar term (jieqi) before date, date.""" s = solar_longitude(universal_from_standard(date, chinese_location(date))) return amod(3 + quotient(s - deg(15), deg(30)), 12)
9aa27324b8f42ef2aa6067416f46b760b595f75c
63,518
def discussions_to_df(discussions: list) -> pd.DataFrame: """Generates a discussion-centered DataFrame from the `discussions` list. Args: discussions (list): Designed to be the output of the `tree_mapping.map_as_tree` method. Returns: (pd.DataFrame): a DataFrame based on `discussions`. ...
02e4c4c0487d9ee5be3214f2ac519555ba7ed791
63,519
import logging import os def wordtype_form(request): """ Show the form for adding types of words """ logging.info(f'{os.getenv("ID_LOG", "")} Show the form for adding types of word') template_name = 'english_dic/wordtypes_form.html' queryset = WordTypeItem.objects.all().order_by('word_type') # ...
f49ff41c6c0e7852aeee66ad7e22891bc01dcbcf
63,520
def pauli_group(number_of_qubits, case=0): """Return the Pauli group with 4^n elements. The phases have been removed. case 0 is ordered by Pauli weights and case 1 is ordered by I,X,Y,Z counting last qubit fastest. Args: number_of_qubits (int): number of qubits case (int): determin...
a927cea4741b7e872800e890a2d51929fb3526fd
63,521
from datetime import datetime def update_comment( comment_id: MatchCommentID, editor_id: UserID, body: str ) -> MatchComment: """Update a comment on a match.""" comment = _get_db_comment(comment_id) comment.body = body comment.last_edited_at = datetime.utcnow() comment.last_edited_by_id = edi...
f8327be177589714c06d44060959583733d1b7e0
63,522
import copy def walk_wproj(client: _w.WaapiClient, start_guids_or_paths: _StrOrSeqOfStr, properties: _StrOrSeqOfStr = None, types: _StrOrSeqOfStr = 'any') -> _t.Iterator[_t.Tuple[_WaapiValue]]: """ Walk through descendants of an object and yield their properties. ...
efa667e8f1e80b2fa8323dd1fbce6b5a4399debe
63,523
def endpoints_api( name, version, auth_level=None, allowed_client_ids=None, **kwargs): """Same as @endpoints.api but tweaks default auth related properties. By default API marked with this decorator will use same authentication scheme as non-endpoints request handlers (i.e. fetch a whitelist of O...
baf0f454a16de769dda4875774b71d35f3e005a4
63,524
def list_attributes(any_class): """List all public methods and attributes of a class sorted by definition order """ return [x for x in any_class.__dict__.keys() if not x.startswith("_")]
fb3d8624b318a13b40f7b6f70482671943c37fc0
63,525
def get_counts_string(match): """ Looks for keys matching top_events_X in matches, generated by get_top_counts, and returns a readable string about the various counts. """ message = '' for key, counts in match.items(): if key.startswith('top_events_'): message += '%s:\n' % (key[11:])...
28674902c488add7e5e50af7bcf1a555255a07f7
63,526
def set_tv_importation_as_birth_rates(model, importation_times, importation_n_cases): """ When imported cases are explicitly simulated as part of the modelled population. They enter the late_infectious compartment through a birth process """ # inflate importation numbers to account for undetected ca...
ac6e82ee72d482d453665885564d6546580436d4
63,527
def one_car_position_axis(position_1): """Create a one car position in time axis.""" data = dict( data=[position_1], y_label='position') return dacite.from_dict(Axis, data)
96f9656d755953070e9031550c55f1664d74c9bf
63,528
import argparse import sys import logging def init(): """ Initialize application arguments and logs and return parsed input args :return: parsed arguments """ parser = argparse.ArgumentParser() parser.add_argument('--verbose', '-v', action='count', default=0, help='Increase the log verbosity')...
f0c7396c68ce437ad779ca8a6f80743e4f480a0d
63,529
import re def parse_ldd_output(output): """Parses the output from a run of 'ldd' on a binary. Returns a dictionary of {path: address} for each library required by the specified binary. Arguments: output(str): The output to parse Example: >>> sorted(parse_ldd_output(''' ... ...
d056cb2f782e01db829b3f9d8433e18f49b69ab3
63,530
def get_target_pts(pts_path): """ 获取真实的牙龈线点 """ target_pts = np.loadtxt(pts_path) return target_pts
204aae53a8eb53f0020c22e3a418a1b4e29bf57b
63,531
def cancel_and_stop_intent_handler(handler_input): """Single handler for Cancel and Stop Intent.""" # type: (HandlerInput) -> Response speech_text = INTENT_ANSWERS['stop'] return handler_input.response_builder.speak(speech_text).response
208a0abe5df177f95c02c0f98532a3ca5df687db
63,532
def colorizer(x, y): """ Map x-y coordinates to a rgb color """ r = min(1, 1-y/3) g = min(1, 1+y/3) b = 1/4 + x/16 return (r, g, b)
6b135728e02148af5368bc21bfb7d1bed90200d5
63,533
from typing import Optional from typing import Tuple import re def parse_commit_heading(heading: str) -> Optional[Tuple[str, Version, Version]]: """Parse nixpkgs-style commit header.""" msg_pattern = re.compile(r"^(?P<attrname>[^:]+):\s*(?P<old_version>.+)\s*(?:→|->)\s*(?P<new_version>.+)$") match = msg_p...
46ef4db36caf34165cb28ce7d8997acba2d5dc77
63,534
def _append_attr_suffix(name): """ Append auto parallel suffix for distributed attribute name. """ return name + core.kAutoParallelSuffix()
75445809505a21b4d612aa454a6e58806fecb414
63,535
import math from functools import reduce def CalculateTruncatedMean(data_set, truncate_percent): """Calculates the truncated mean of a set of values. Note that this isn't just the mean of the set of values with the highest and lowest values discarded; the non-discarded values are also weighted differently de...
56792561096127992c978985a444e124fbe4c5be
63,536
import logging def imreproj(image_in, epsg_out, mode='nearest'): """ Reproject a raster in memory (without write on disk) :param image_in: path of input raster :param epsg_out: output epsg (int) :param mode: interpolation mode ['nearest' (default), 'bicubic', 'average', 'bilinear', 'l...
51d4813fe816542c66bfcd40041e7651e0b43bca
63,537
def min_max_scale(values, raise_error=True, default_value=scalar_pass_through): """Normalize values in a list using min-max feature scaling. Values that are not numeric are either replaced with a given default value or an error is raised if the raise error flag is True. Parameters ---------- va...
28551f46a0ae10057149cefac864a69f46f2887a
63,538
def get_multiformat_body(request, key, default=None): # type: (Request, Str, Optional[Any]) -> Any """ Obtains the value of :paramref:`key` element from the request body according to specified `Content-Type` header. .. seealso:: - :func:`get_multiformat_body_checked` - :func:`get_permis...
51ccae9457f0a390a9a6030e0448d1f604a996b7
63,539
def SimTK_version_SimTKcommon(major, minor, build): """ SimTK_version_SimTKcommon(int * major, int * minor, int * build) Parameters ---------- major: int * minor: int * build: int * """ return _simbody.SimTK_version_SimTKcommon(major, minor, build)
ed5b1a4fbcb2df30b9fe070fc5e71840c0085360
63,540
def base(n: float, alphabet: str, digits: int) -> str: """ Converts a real-valued number into its baseN-notation. Parameters ---------- n : float Number to be converted (decimal precision will be droped) alphabet : str Alphabet of the positional notation system digits : int ...
64b1a2e7315e24e584520b1975a843acce152b21
63,541
import os import uuid def processing_config(get_topic_name): """ Returns a minimal configuration for setting up a relay capable of processing :param options: initial options to be merged :return: the altered options """ def inner(options=None): # The Travis script sets the kafka boots...
387a9a3b070930f57c43ca3c36033ce10499f678
63,542
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): """ Convert a list of `InputExample` to be labelled into a list of bert `InputFeatures` """ features = [] input_tokens = [] for (ex_index, example) in enumerate(examples): feature, tokens = convert_single_...
54f4fa4afe6edf4ca3bdc8c84d03ddd94f7bd3c3
63,543
def get_point(values, pct): """ Pass in array values and return the point at the specified top percent :param values: array: float :param pct: float, top percent :return: float """ assert 0 < pct < 1, "percentage should be lower than 1" values = sorted(values) return values[-int(len(...
11474d804e0845284a864a5cb8de23299999a5e7
63,544
import os import yaml def _get_smartstack_proxy_ports_from_file(root, file): """Given a root and file (as from os.walk), attempt to return the highest smartstack proxy port number (int) from that file. Returns 0 if there is no smartstack proxy_port. """ ports = set() with open(os.path.join(roo...
7456db23657a158f083247a4300fd891a0034b97
63,545
def get_data(data_args, data_cache, read_from_cache=True, write_to_cache=True, write_args_to_cache=True): """ Prepares the raw data, if it is not yet cached. """ random_state = tools.check_arg( 'random_state', data_args['random_state'], int, (0...
5bb6143d22394888fad38a5e58f6342580ce3656
63,546
import os def file_select(origin_path): """Getting the user to select the file they want""" rolling_number = 1 for root, dirs, files in os.walk(origin_path, topdown=True): dirs.clear() for file in files: print(str(rolling_number) + ") " + file) rolling_number += 1 ...
a44bd662d2e59e16fc9a83786796c56dc0096245
63,547
def get_xpub_fingerprint(xpub): """ Retuns fingerprint of the XPUB itself. IMPORTANT! NOT parent fingerprint, but hash160(pubkey) itself! """ b = decode_base58(xpub) return hash160(b[-33:])[:4]
e73c4da74eeeb47a5cfb3d519647fafc213041d5
63,548
import gettext def order(): """Order articles.""" storefront = _get_storefront_or_404() shop = shop_service.get_shop(storefront.shop_id) if storefront.closed: flash_notice(gettext('The shop is closed.')) return order_form() article_compilation = ( article_service.get_arti...
2e5e15a62f62d085ecd9bd1a930d987be3483b50
63,549
def get_necessary_conf_property(conf, name): """ Return configuration property value and expect it to be set. :param conf: Dictionary. :param name: Configuration property string. :return: Configuration property value. """ check_necessary_conf_property(conf, name, None) return conf[name]
aff866d6e1bb72b9ca5a4262d87d24e65af3eb66
63,550
def get_pixel_path(p0, p1): """ Return pixel path from p0 to p1 Args: p0: tuple(float, float) Start pixel p1: tuple(float, float) End pixel Returns: list(tuple(float, float)) Ordered list of pixels """ p0 = np.array(p0) p1 = np.a...
f91ee59bc35ed3b5e694a902b438628c24b81df2
63,551
def PMR_Choquet(x, y, prefs): """ Si positif: x possiblement préféré à y Si nul: x est possiblement autant préféré que y Si négatif: x est tout le temps préféré à y """ #Number of variables n = x.shape[0] xcopy=x.copy() xcopy[::-1].sort() listX=[np.where(x==xcopy[0])[0]] ycopy=y.copy() ycopy[::-1]....
728b5057215022e2876a6d121f54a5719bfc0463
63,552
def get_handlers(requested=None): """ get multiple chksum handlers :param requested: None (all handlers), or a sequence of the specific handlers desired. :raise MissingChksumHandler: if requested chksum type has no registered handler :return: dict of chksum_type:chksum handler """ ...
d6a7781761cb21dc95e5349c7243910760dce078
63,553
import json import time def start_topology_old(request): """ DEPRECATED verify the topology exists and is started! required parameters: topology_name, id of which to clone, cloud_init data returns json { "status": "running|unknown|powered off", "topology_id": "0" } """ con...
ff611c0ea930d269e8022a0c5ca540376e6078ff
63,554
def code(*content, sep=" "): """ Make mono-width text (Markdown) :param content: :param sep: :return: """ return markdown_decoration.code(value=html_decoration.quote(_join(*content, sep=sep)))
b9cac8bb6b73ce6f372feeb8f14694c88a0317b0
63,555
import abc import json def stringify(obj): """Convert object to string. If the object is a dictionary-like object or list, the objects in the dictionary or list will be converted to strings, recursively. Returns: If the input is dictionary or list, the return value will also be a list or dictionary. ...
c7e6dca941edf1adbc49b745dfc81e0eeb15d02a
63,556
import torch def decode_predictions(predictions): """ CTC RNN Layer decoder. 1. 2 (or more) repeating digits are collapsed into a single instance of that digit unless separated by blank - this compensates for the fact that the RNN performs a classification for each stripe that re...
b49ade62b5a301c9b703608635931c4dc1029ed4
63,557
import torch def merge_aug_bboxes_3d(aug_results, img_metas, test_cfg): """Merge augmented detection 3D bboxes and scores. Args: aug_results (list[dict]): The dict of detection results. The dict contains the following keys - boxes_3d (:obj:`BaseInstance3DBoxes`): Detection bb...
b9f478dd754348c9e058eca0b9732e52d45e4480
63,558
from typing import Tuple def weird_argument(request, prior_and_prior_type_and_value: Tuple[str, str, str]): """ Fixture that provides a weird name, along with a prior and value. """ weird_param_name = request.param prior_str, prior_type, value = prior_and_prior_type_and_value return WeirdArgument( ...
a4938733a7ef7b09fdcb94f1217834a750516ed9
63,559
def is_valid(number): """Check if the number provided is a valid NIE. This checks the length, formatting and check digit.""" try: return bool(validate(number)) except ValidationError: return False
8245d43e59f831f7e03ad4e8415acc2ce2f54fef
63,560
async def getObjectJson(app, obj_id, bucket=None, refresh=False, include_links=False, include_attrs=False): """ Return top-level json (i.e. excluding attributes or links by default) for a given obj_id. If refresh is False, any data present in the meta_cache will be returned. If not the DN will be queries, ...
8fef9d74ed0d362cc80070d2f010f121215d8d10
63,561
def prepare_for_table(data, machine_id): """We don't want to store certain fields in the DB, e.g. the _BOOT_ID or the __CURSOR because they don't add any value in the central log index. """ defint = lambda x: 0 if x == '' else int(x) keep_and_convert = { 'MESSAGE': str, 'PRIORI...
54c75fac6206c0c5e6b8d44553853c0c624080fa
63,562
def run_2020_02_1() -> str: """ Run the main function and return a single result to be printed. Returns ------- `str` The result to be printed. """ with open("advent_2020/data/02.txt") as f_in: # Read the text and store each line in a collection. rules_and_data = r...
cc5b1bb08150f8a30a3237355dc2069c4dfe8063
63,563
def reverse_table(tab): """Function that reverse an array Args: tab: an array return the array reversed """ if not(isinstance(tab,list)): raise ValueError('max_value, expected a list as input') if len(tab)==0: raise ValueError('max_value, expected a non empty a list as in...
8ab03236e40cb270f51dde91a0e2f2760ab90316
63,564
def check_columns(df): """ Checks wether dataframe contains the required columns. :param df: the data frame with track data. :return: whether or not df contains all the required columns. required columns: refName, start, end, name, score (is optional) :rtype: boolean """ require...
3ddc53fc0e2caad74b3218f7f47134aed258cba9
63,565
import logging def DPS_account_query(DB_Engine, fromtime, endtime, uri_stem, query, result_dict=None): """ Input: result_dict dict Output: { uid:{ first_time: last_time: is_test: is_white: strategys: {strategy1:count} origin: { ip:{ ...
e4488bb7963df6aaaca9d07e42f013863aeeeb21
63,566
import sys import urllib import tarfile import shutil import os def create_asn_db(): """Open ASN DB if available, download if needed""" try: # Try to open an existing ASN DB asn_db_reader = geoip2.database.Reader("GeoLite2-ASN.mmdb") return asn_db_reader except IOError: t...
c0494ab29bcef188705eeaeeeaf8d55a40948590
63,567
def accuracy_inf_sol(inferred,cliques_solution): """ 'inferred' should be a set of vertices 'cliques_solution' an iterable of all the solution cliques (as sets) """ assert len(cliques_solution)!=0, "No solution provided!" max_overlap = 0 best_clique_sol = cliques_solution[0] clique_size ...
d2d38d7f3470520058f90699dab6b7eb59cbd5cf
63,568
def GetGlobalParamsFromFlags(): """Return a StandardQueryParameters based on flags.""" result = messages.StandardQueryParameters() if FLAGS['alt'].present: result.alt = messages.StandardQueryParameters.AltValueValuesEnum(FLAGS.alt) if FLAGS['fields'].present: result.fields = FLAGS.fields.decode('utf8') ...
85758c3bf6acf7bd4c1d2b7045ffb0b4704c27c9
63,569
def load_japanese_vowels(split='TRAIN', return_X_y=False): """ Loads the JapaneseVowels time series classification problem and returns X and y. Parameters ---------- split: str{"ALL", "TRAIN", "TEST"}, optional (default="TRAIN") Whether to load the train or test partitio...
2a378ee9e6625dbcc00463dd785e2b979bcc54bc
63,570
def _ziprange(alist, ix): """ returns zip of the list, and the one with ix added at the end and first element dropped Example ------- :: alist = [2,4,7] _ziprange (alist, 10) --> zip([2,4,7], [4,7,10]) -> (2,4), (4,7), (7,10) """ blist = alist.copy() ...
e816ad20e8c193487d8483cdfd3ee27d77fef814
63,571
def sgnlog( x, base=np.e): """ Signed logarithm of x: log(abs(x) * sign(x) Args: x (float|ndarray): The input value(s) Returns: The signed logarithm Examples: >>> sgnlog(-100, 10) -2.0 >>> sgnlog(-64, 2) -6.0 >>> sgnlog(100, ...
f1ea3520e85d6dfdad28deb3653356f6e3e515cd
63,572
import os def iterFilePaths(root_path): """Walks through all files in all subdirectories of the given root_path and yields their full path.""" return (os.path.join(root_path, file) for _, _, f in os.walk(root_path) for file in f)
cee890e16210967a75b0e0b7fc915b62b9202a2c
63,573
import re def title_output_replace(input_title_output, metadata_dict, data_dict, rel_channels_dict, is_title = False, custom_vars = None): """Substitute %VAR% variables with provided values and constants. Given a title (or output path) string template, replace %VAR% variables with the appropriate va...
83102c1557643b67ce1c52f0c69154bcfac4ac72
63,574
def get_sf(labels): """Returns the shape factor for each object in a labeled image Parameters ---------- labels : 2D numpy array an image (usually 16bit) with the cell/object labels Returns ------- sf_list : 1D numpy array shape factor for each label (order corresponds to...
34da736eaf90e927df45563ae8002f4d5203559e
63,575
def getManagementBodies(project, category): """Returns a sorted list of a specific category of management bodies for a given project.""" # transform QuerySet into list bodies = list(ManagementBody.objects.filter(project=project).filter(category=category)) # sort by title return sorted(bodi...
12be33558e1e6094b645f9f5f86465d83affbc22
63,576
def is_reference(message_or_descriptor: MessageOrDescriptorBase) -> bool: """Returns true if message_or_descriptor is of a reference type. Args: message_or_descriptor: A protobuf Message or DescriptorBase to examine. Returns: A Boolean indicating whether or not message_or_descriptor is a reference. R...
1db6e9f1c36774a662a032b9b7e1c943ca28eed1
63,577
def format_data(data, es_index): """ Format data for bulk indexing into elasticsearch """ unit = data["unit"] rate_unit = data["rateUnit"] egvs = data["egvs"] docs = [] for record in egvs: record["unit"] = unit record["rate_unit"] = rate_unit record["@timestamp"]...
094af427daaf4922371e17fca70a2b8c8539d54c
63,578
from pathlib import Path def specifier_proc(dataset, subject, ix_run, es): """ Like specifier, but returns the equivalent folder structure for processing. Unlike for specifier, these folders do not need to exist a-priori. For convenience, they generally take a similar structure to what is written for ...
7f06fd9a0bb61b9b97e67f261609e00ebdbb9e45
63,579
from pathlib import Path import subprocess import os def add_video_padding(video_path: Path) -> Path: """Adds audio padding to previously rendered videos. This ensures that there won’t be a shift between the audio and video when rendering the final project. This function does not edit the original v...
e505286c11f4b791ed1202abb8d46c0d11b516d1
63,580
def get_first_derivative_matrix(n): """ :param x: numpy array of x-values :return: A matrix D such that if x.size == (n,1), D * x is the first derivative of x :symmetric first derivative (excludes endpoints like as before) """ m = n - 2 F = spmatrix(list(chain(*[[-0.5, 0.0, 0.5]] * m)), ...
0ce67edd5e0acb411a394d410c27cbb373f86d42
63,581
def house(house, featured=None): """ Read/update list of house candidates. """ house_slug = u'H' if house == 'senate': house_slug = u'S' is_featured = False if featured == u'featured': is_featured = True if request.method == 'GET': # Get all of the candidates ...
ac8630b43e98995a38b8258e6a38cb9d30480b8b
63,582
def song_comments(commentThreadId, limit=10, offset=0): """ 根据commentThreadId获取歌曲评论 """ # upl = user_playlist(uid, limit=1) base_url = 'http://music.163.com/weapi/v1/resource/comments/%s/' % commentThreadId # data = {'offset': offset, 'limit': limit, 'uid': uid} for i in range(retry_times):...
1ec01ff6458396756d4c58e2a94ee1a54ae7949c
63,583
from typing import Optional def get_description(prefix: str, use_markdown=True) -> Optional[str]: """Get the description for the given prefix, if available.""" entry = get_resource(prefix) if entry is None: return None return entry.get_description(use_markdown=use_markdown)
257da257e65ef8b51ca431d7b6e061f7816cb06d
63,584
import requests def chain_entry_first(chain_id=None): """ """ res = requests.request("GET", URL + '/chains/%s/entries/first' % chain_id, headers=HEADERS) return _decode_response(res.content)
a97fb998272e6266730a23de8a78782d94da491c
63,585
def paste_filename(search): """ Function that will create a name for the files to be saved to using the search """ # Removes any spaces cleaned_keyword = search.replace(' ', '_') # Adds 'videos.csv' at the end filename = cleaned_keyword + "_videos.csv" return filename
3279ef21e039b7a63a728a6d02714086a61f3e0e
63,586
def format_date(df, columns, current_format, output_format): """ Parameter --------- df : dataframe whose date column has to be modified columns : Name date columns to be transformed. current_format : current date string format eg: dd-MM-yyy output_format ...
eedaab4469312f9404da5600c6739004ccda53e4
63,587
def Hindex(citationlist): """根据citationlist获得h因子。 citationlist是按顺序的每篇文章引用次数列表 """ indexSet = sorted(list(set(citationlist)), reverse=True) for index in indexSet: clist = [i for i in citationlist if i >= index] if index <= len(clist): break return index
5ef90ebf60c04df466d92bcc0d4dbb136bd4d8ca
63,588
from typing import Dict from typing import Any from typing import Optional from typing import Union async def parse( bot: Bot, _dict: Dict[str, Any], guild: Optional[Guild] = None ) -> Union[Channel, ChannelGroup]: """ 解析子频道信息字典为 `Channel` 或 `ChannelGroup` 类型。 参数: - _dict: 将用于解析的字典 ...
381e2fb1134d55589e3f309dfc08f68fafb59276
63,589
from typing import OrderedDict def get_global_vars_dict(scope=None): """Returns all variables in the session in a dictionary form""" all_vars = get_global_vars_list(scope) vars_dict = OrderedDict() for var in all_vars: vars_dict[var.name] = var return vars_dict
45e70fc62cbacdf1658ad283bea72f898f8ff5ca
63,590
def get_parser(): """ Get parser object for `eco_mocks_create.py` script. Returns ------- args: input arguments to the script """ ## Define parser object description_msg = 'Downloads the necessary catalogues from the web' parser = ArgumentParser(description=description_msg,...
7f16ac54794625a2e74df29cbefc09744c8f2c64
63,591
import numpy def CalculateTotalNCharge(mol): """ ################################################################# The total negative charge -->Tnc Usage: result=CalculateTotalNCharge(mol) Input: mol is a molecule object. Output: result is a numeric...
55cd6bbc164cf1fbf6c244f491104ada2658e488
63,592
def create_pr_par(chrom, par_dict): """ create_pr_par ============= Method to create a pyranges object of the PAR regions on the X chromosome. Parameters: ----------- 1) chrom: (str) The Chromosome to use. (NOTE: Should be the "X" chromosome" 2) par_dict: (dict) The genome build spe...
3dc523cb889ac7ad18972de618a05b3797e32822
63,593
async def async_setup(hass: HomeAssistant, config: dict): """Set up the foscam component.""" hass.data.setdefault(DOMAIN, {}) return True
2af8bd4a8f7f1c7bf201e3297cc59242fc6bb2c5
63,594
import codecs import logging def load_embedding(filename, embedding_size): """ load embedding """ embeddings = [] word2idx = defaultdict(list) idx2word = defaultdict(list) idx = 0 with codecs.open(filename, mode="r", encoding="utf-8") as rf: try: for line in rf.read...
374a067c91e722c8a2f3052e38f447ce7b83bfaf
63,595
def grib_keys_iterator_new(msgid, namespace=None): """ @brief Create a new iterator on the keys. The keys iterator can be navigated to give all the key names which can then be used to get or set the key values with \ref grib_get or \ref grib_set. The set of keys returned can be controlled with ...
9ee9bb3304f49bd192ba0998942f514fce2d85d6
63,596
def get_eval_list(assessment, current_user): """Returns the list of teammates who are evaluated""" for team in Team.objects.all(): if current_user in team.student.all() and team.course == assessment.course: # get the team evaluated_list = [student for student in team.student.all() if student...
25fb566f37d90f577e92005eb75fcb552c0096d0
63,597
def _run_in_background(func): """Run func in a new thread. The thread is expected to exit on its own.""" @wraps(func) def wrapped(*args, **kwargs): Thread(target=func, args=args, kwargs=kwargs).start() return wrapped
b9af5bc8cb8e653720c5cfac812289312539df79
63,598
def input_default(default_word='', tip_words='Please input words.'): """return default_word while input() return blank""" input_data = input(tip_words + '(default: ' + default_word + ')\n') if input_data.strip() == '': print('Blank input. Using the default value: {0}'.format(default_word)) r...
5873fd6b29f932c8f59262fb44749827eb9bcc29
63,599