content
stringlengths
22
815k
id
int64
0
4.91M
def process_docstrings(docstrings): """Process the docstrings into a proper structure""" docs = {} # First we'll find all of the modules and prepare the docs structure for chunk in docstrings: if chunk[2].startswith("==="): # This is a module definition modulename = chun...
5,333,100
def create_deck(request: HttpRequest): """ Форма для кода колоды + ее отображение """ deck, deckstring_form, deck_save_form = None, None, None title = _('Hearthstone | Decoding the deck code') if request.method == 'POST': if 'deckstring' in request.POST: # код колоды отправлен с формы D...
5,333,101
def read_completed_flag(uarm, flag_type): """ Read Complete Flag from EEPROM :param uarm: uArm instance :param flag_type: protocol.CALIBRATION_FLAG, protocol.CALIBRATION_LINEAR_FLAG, procotol.CALIBRATION_SERVO_FLAG :return: """ if flag_type == CALIBRATION_FLAG: if uarm.get_rom_data(C...
5,333,102
def update_collections(parameters, session=None): """ update collections. :param parameters: list of dictionary of parameters. :param session: The database session in use. :raises NoObject: If no content is founded. :raises DatabaseException: If there is a database error. """ try: ...
5,333,103
def zpves(output_string): """ Reads the zero-point energies for each of the hindered rotors from MESS output file string. :param output_string: string of lines of MESS output file :type output_string: str :return zpves: zero-point energy for each of the rotors :rtype: list(f...
5,333,104
def _get_cast_type(field_type: type, value: Any) -> Optional[Callable]: """Get a casting callable for a field type/value.""" if type(value) is dict: return _get_cast_type_for_dict(field_type) if type(value) is str: return _get_cast_type_for_str(field_type) return None
5,333,105
def read_data(filepath , strict_lang='en'): """Read data in csv format in order to preprocess. Args: filepath (str): a filepath to a csv file with twitter data. strict_lang (str, optional): whether to select only tweets with explicit language metadata.Defaults to 'en'. Returns: ...
5,333,106
async def absent(hub, ctx, name, resource_group, connection_auth=None, **kwargs): """ .. versionadded:: 4.0.0 Ensure the specified disk does not exist in a resource group. :param name: The name of the disk. :param resource_group: The name of the resource group containing the disk. :param con...
5,333,107
def MakeCommandName(name): """adds '.exe' if on Windows""" if os.name == 'nt': return name + '.exe' return name
5,333,108
def read_meta(path=path): """Correctly reads a .tsv file into a numpy array""" with open(path) as fd: rd = csv.reader(fd, delimiter="\t", quotechar='"') data = [] for idx, row in enumerate(rd): if idx == 0: continue data.append(row) return np...
5,333,109
def _update_dicts(name_scope, model_layer, input_to_in_layer, model_name_to_output, prev_node_name): """Updates input_to_in_layer, model_name_to_output, and prev_node_name based on the model_layer. Args: name_scope: a string representing...
5,333,110
def test_disabling_topology_loadbalancing(): """ Title: Balances traffic correctly when loadbalancer topology elements are disabled. New connections to the VIP should fail when any of the elements are disabled. In the case of pool members, connections should fail when *all* pool...
5,333,111
def geomance_results(session_key): """ Looks in the Redis queue to see if the worker has finished yet. """ rv = DelayedResult(session_key) if rv.return_value is None: return jsonify(ready=False) redis.delete(session_key) result = rv.return_value return jsonify(ready=True, result...
5,333,112
def _return_dataframe_type(dataframe, dataframe_type): """ Helper method for returning te dataframe in spark/pandas/numpy/python, depending on user preferences Args: :dataframe: the spark dataframe to convert :dataframe_type: the type to convert to (spark,pandas,numpy,python) Returns: ...
5,333,113
def split_dataset( raw: pd.DataFrame, train_ratio: float, val_ratio: float, lags: int, verbose: bool = False ) -> Tuple[np.ndarray]: """ Generate and split the prepared dataset for RNN training into training, testing and validation sets. Args: raw: A dataframe contain...
5,333,114
def main(): """Main""" parser = _argparse.ArgumentParser( formatter_class=_argparse.RawTextHelpFormatter, epilog=_COMMANDS_HELP_STR) parser.add_argument( "-V", "--version", action='version', version=_VERSION_STR) parser.add_argument('-p', '--port', required=True, help="serial por...
5,333,115
def test_n_ary_crossover_bad_crossover_points(): """ Test assertions for having more crossover points than genome length """ pop = [Individual([0, 0]), Individual([1, 1])] i = ops.naive_cyclic_selection(pop) with pytest.raises(RuntimeError): new_pop = list(itertools.islice(ops.n_ary...
5,333,116
def test_contributor_affiliations_invalid( running_app, minimal_record_with_contributor ): """Should fail on invalid id's and invalid structure.""" minimal_record = minimal_record_with_contributor # The id "invalid" does not exists. minimal_record["metadata"]["contributors"][0]["affiliations"] = ( ...
5,333,117
def test_platform(): """Run windows only tests""" build() test_setup() sh("%s psutil\\tests\\test_windows.py" % PYTHON)
5,333,118
def CompileRes(target, src, opts): """Compiles a Windows .rc file into a .res file.""" ipath = GetListOption(opts, "DIR:") if (COMPILER == "MSVC"): cmd = "rc" cmd += " /Fo" + BracketNameWithQuotes(target) for x in ipath: cmd += " /I" + x for (opt,dir) in INCDIRECTORIES: ...
5,333,119
def create_ranking_model() -> tf.keras.Model: """Create ranking model using Functional API.""" context_keras_inputs, example_keras_inputs, mask = create_keras_inputs() context_features, example_features = preprocess_keras_inputs( context_keras_inputs, example_keras_inputs, mask) (flattened_context_featur...
5,333,120
def to_count_matrix(pair_counts, vocab_size): """ transforms the counts into a sparse matrix """ cols = [] rows = [] data = [] for k, v in pair_counts.items(): rows.append(k[0]) cols.append(k[1]) data.append(v) # setting to float is important, +1 for UNK # COO...
5,333,121
def create_dataset(genres_types: List[str], sp: spotipy.Spotify, genius: Genius, limit: Optional[int] = 50, how_many_in_genre: Optional[int] = 2_000, sleep_time: Optional[int] = 30, path_to_save: Opti...
5,333,122
def extract(config): """Extract zip files.""" try: cfg = config.config except AttributeError: click.echo(MSGNOCFG) return pth = os.path.abspath(cfg['path']) click.echo(f'Extracting files at {pth}') extract_files(**cfg)
5,333,123
def get_enum_type_definition(ua_graph: UAGraph, data_type_id: int): """Given a UAGraph object and a internal id of an enum type, the definition of the enumeration will be produced. The form of the definition may vary based on the enumeration. Args: ua_graph (UAGraph): UAGraph where the enum defi...
5,333,124
def create_classification_of_diseases(): """ :param qtty: number of objects to create """ fake = Factory.create() return ClassificationOfDiseases.objects.create( code=randint(1, 1000), description=fake.text(), abbreviated_description=fake.text(max_nb_chars=100), parent=None...
5,333,125
def is_path_parent(possible_parent, *paths): """ Return True if a path is the parent of another, False otherwise. Multiple paths to test can be specified in which case all specified test paths must be under the parent in order to return True. """ def abs_path_trailing(pth): pth_abs =...
5,333,126
def create_measurement(coordinate, timestamp, velocity, altitude, user_id): #TODO: Rename to create_location_measurement """ Creates location entry. """ new_loc = ecwl.Location( ts = timestamp, latitude = coordinate[0], longitude = coordinate[1], sensed_speed = veloc...
5,333,127
def cmpversion(a, b): """Compare versions the way chrome does.""" def split_version(v): """Get major/minor of version.""" if '.' in v: return v.split('.', 1) if '_' in v: return v.split('_', 1) return (v, '0') a_maj, a_min = split_version(a) b_maj, b_min = split_version(b) if a_maj...
5,333,128
def migrate_work_dir_structure_v2(server_id: str) -> None: """Function to reorganize working directory data to be sorted by server_id. This assumes no migration has previously run Args: server_id: server id to move user dirs into """ __migrate_repository_data(server_id) __migrate_sens...
5,333,129
def get_dict_json(attr_name: str, possible_dict: dict) -> dict: """ returns a {key : item}. If the item is a np.ndarray then it is converted to a list Parameters ---------- attr_name possible_dict Returns ------- """ if type(possible_dict[0]) == np.ndarray: output_tail...
5,333,130
def eulers_totient_phi(num): """ Euler's totient (a.k.a. phi) function, φ(n). Count the number of positive integers less than or equal to "n" that are relatively prime (coprimes) to "n". Coprimes: if the only positive integer that evenly divides two numbers is 1. This is the same thi...
5,333,131
def create_nav_btn(soup,date,text): """ Helper functions for month_calendar, generates a navigation button for calendar :param soup: BeautifulSoup parser of document :param date: Date to create nav button :param text: Text for button """ nav_th = soup.new_tag('th',attrs=[('colspan','2')...
5,333,132
def parse_history_event(directive_result): """Based on the type of event, parse the JSON.serializable portion of the event.""" event_type = directive_result.event_type if event_type is None: raise ValueError("EventType is not found in task object") # We provide the ability to deserialize custom...
5,333,133
def _remove_irrelevant_subelement(base, tag): """If element with a given tag has no children, remove it. Args: base: The base node element. (lxml node) tag: Child elements own tag, to be created. (string) Returns: The node element with the tag. """ # Check if the tag alrea...
5,333,134
def runQuery(cred, structuredQuery): """ Run the structured query defined according to the Firestore rest API docs, see NetFlowPingApp getItems() function as an example @param structuredQuery: query the firestore database according to the structure defined by... https://firebase.goo...
5,333,135
def pad_with_dots(msg, length=PAD_TEXT): """Pad text with dots up to given length. >>> pad_with_dots("Hello world", 20) 'Hello world ........' >>> pad_with_dots("Exceeding length", 10) 'Exceeding length' """ msg_length = len(msg) if msg_length >= length: return msg msg = m...
5,333,136
def get_top_10_features(target_params, results, importance_type="weight"): """Gets the top 10 features of each XGBoost regressor. Parameters ---------- target_params: dictionary Should contain a dict with with params for each target label. results : dictionary Should contain a d...
5,333,137
def nlj2csv(infile, outfile, header, skip_failures, quoting, json_lib): """ Convert newline JSON dictionaries to a CSV. Defaults to reading from `stdin` and writing to `stdout`. CSV fields are derived from the first record and `null` values are converted to empty CSV fields. """ with nlj...
5,333,138
def index(): """ Class check list view """ new_class_check_form = NewClassCheckForm() upload_csv_form = UploadCSVForm() classes = ClassCheck.query.all() return render_template('index.html', new_class_check_form=new_class_check_form, upload_csv_form=upload_csv_form, cl...
5,333,139
def test_use_proactoreventloop(monkeypatch): """Test that ProActorEventLoop is created""" class StopTest(Exception): pass monkeypatch.setattr(loadlimit.importhook, 'lstaskfiles', fake_lstaskfiles) monkeypatch.setattr(loadlimit.importhook, 'SourceFileLoader', FakeSourceF...
5,333,140
def autoupdate(request): """ Execute auto-update if the request contains the correct `X-Hub-Signature`, depending on the shared secret key. See https://developer.github.com/webhooks/creating/. """ github_api_token, github_webhook_secret = _read_secrets() _check_signature(github_webhook_sec...
5,333,141
def sync_directories( sourcedir: str, targetdir: str, action: str = 'sync', *, twoway: Optional[bool] = False, purge: Optional[bool] = False, verbose: Optional[bool] = True ) -> None: """ Parameters ---------- sourcedir : str The source directory for syncing. targ...
5,333,142
async def test_hmip_water_detector(hass, default_mock_hap): """Test HomematicipWaterDetector.""" entity_id = "binary_sensor.wassersensor" entity_name = "Wassersensor" device_model = "HmIP-SWD" ha_state, hmip_device = get_and_check_entity_basics( hass, default_mock_hap, entity_id, entity_nam...
5,333,143
def fuse_gelu_tanh_approximation(prog): """ Identify the pattern that corresponds to the tanh approximate version of gelu, and replace it with a single gelu layer with mode=TANH_APPROXIMATION y = ( tanh((.0447)x^3 + x ) * (sqrt(2/pi)) + 1 ) * 0.5 * x [...] -----> pow (3) ----> mul (.044715) ---> a...
5,333,144
def main(args): """Main function called when run from command line or as part of pipeline.""" usage = """ Usage: split_by_taxa.py --genomes-a=FILE file with genome GenBank Project ID and Organism name on each line for taxon A --genomes-b=FILE file with genome GenBank Project ID and Organism name o...
5,333,145
def countSkipped(line, specs, skipCount): """ Keep track of the number of skipped ligands, and the criteria that got them rejected """ # If the word 'Skipping' is found, if "Skipping" in line: skipCount += 1 endLine = line.split(",")[1].strip() endll = endLine.split() ...
5,333,146
def nrmse(y_true, y_pred, MEAN_OF_DATA): """ Calculates the normalized root mean square error of y_true and y_pred where MEAN_OF_DATA is the mean of y_pred. """ y_true = y_true.squeeze() y_pred = y_pred.squeeze() std = np.sum(np.square(y_true - MEAN_OF_DATA)) errors = np.sum(np.square(y...
5,333,147
def field_references( model_tuple, field, reference_model_tuple, reference_field_name=None, reference_field=None, ): """ Return either False or a FieldReference if `field` references provided context. False positives can be returned if `reference_field_name` is provided without ...
5,333,148
def spsa(u, J, c, a, conv_u, conv_J, max_steps=np.inf, alpha=0.602, A=1., gamma=0.101, m=0., verbose=False): """ Uses simulataneous perturbation stochastic approximation [1]_ [2]_ to minimize a function `J` with respect to the vector `u`. Notation follows the Wikipedia_ page on the topic at the time of writ...
5,333,149
def friendlist_embed(friendlist, guild): """ :param friendlist: The friendlist of the source guild :param guild: Soruce guild :return: Embedded friendlist """ embed = Embed() embed.set_author( name=guild.name, icon_url=guild.icon_url ) friends_field = '\n'.join( ...
5,333,150
def helicsFederateSetFlagOption(fed: HelicsFederate, flag: int, value: bool): """ Set a flag for the federate. **Parameters** - **`fed`** - The federate to alter a flag for. - **`flag`** - The flag to change. - **`value`** - The new value of the flag. 0 for false, !=0 for true. """ f =...
5,333,151
def find_contours(img): """ Find all contours in the image """ _, thresh = cv2.threshold(img,127,255,0) _, contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) return contours
5,333,152
def _split_binline(binline): """Internal function to read the line of bin specs Returns bin width and array of bin lower edges """ bin_strings = tabmatch.split(binline.strip()) # Grab the first float from each binspec, we'll return lower edges # Note that commas must be stripped from numbers.....
5,333,153
def parse_name(content): """ Finds the name of the man page. """ # Create regular expression name_regex = re.compile(r"^([\w\.-]*)") # Get name of manual page just_name = name_regex.search(content) name_str = "" if just_name is not None: name_str = just_name.group(1) ...
5,333,154
def albanian_input_normal(field, text): """ Prepare a string from one of the query fields for subsequent processing: replace common shortcuts with valid Albanian characters. """ if field not in ('wf', 'lex', 'lex2', 'trans_ru', 'trans_ru2'): return text text = text.replace('ё', 'ë') ...
5,333,155
def test_download_message_positive(mocker, request, requests_mock, client): """ Given: - GUID of existing message to download When: - Running download message commandd Then: - Ensure file name - Ensure file content """ mocker.patch.object(demisto, 'uniqueFile', re...
5,333,156
def extract_share_id_from_url(public_base_url: str) -> str: """ Extracts the Airtable share id from the provided URL. :param public_base_url: The URL where the share id must be extracted from. :raises ValueError: If the provided URL doesn't match the publicly shared Airtable URL. :return: T...
5,333,157
def load_data(file_path): """ 读取地名文件,解析出外文和中文的字符总数(去重后),做成字符和索引映射表。 加工地名数据,首尾增加开始和结束标记。 :param file_path: 文件路径 :return: 字符和索引映射表, 地名列表 """ df = pd.read_table(file_path) df.columns = ['source', 'chinese'] # 获取外文和中文字符数组 characters_source = sorted(list(set(df.source.unique().sum()))...
5,333,158
def train_step(opt_g, opt_h, g, h, X, Y, u, train_loss_tracker, rec_loss_tracker, lin_loss_tracker, pred_loss_tracker): """Takes one training step with the Koopman loss. Args: opt_g (tf.keras.optimizers.Optimizer): Optimizer for encoder network. opt_h (tf.keras.optimizers.Optimizer): Optimizer ...
5,333,159
def verify_portchannel_member(dut, portchannel, members, flag='add', cli_type=""): """ This API is used to verify the members of portchannel Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com) :param dut: :param dut: :param portchannel: :param members: :param flag: :return: ...
5,333,160
def test_progress_ready(request, app): """Test progress API when spawner is already started e.g. a race between requesting progress and progress already being complete """ db = app.db name = 'saga' app_user = add_user(db, app=app, name=name) r = yield api_request(app, 'users', name, 'server...
5,333,161
def test_compute_volumes(): """Check _compute_volumes for several masses.""" estimators = [AverageKLPE(k=3, novelty=True), MaxKLPE(k=3, novelty=True), OCSVM(sigma=1.), IsolationForest(n_estimators=5, random_state=2), KernelSmoothing()] alphas = rng.randi...
5,333,162
def adjust_learning_rate(optimizer, epoch, args): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" if args.lr_policy == 'decay': lr = args.lr * (args.lr_decay ** epoch) elif args.lr_policy == 'poly': interval = len([x for x in args.lr_custom_step if epoch >= x]) ...
5,333,163
def refresh_well_known_oidc(realm): """ Refresh Open ID Connect .well-known :param django_keycloak.models.Realm realm: :rtype django_keycloak.models.Realm """ server_url = realm.server.internal_url or realm.server.url # While fetching the well_known we should not use the prepared URL o...
5,333,164
def get_access_token(jwt_token: str) -> str: """ Gets an access token, used for fully-authenticated app actions """ installations = requests.get( "https://api.github.com/app/installations", headers=GH_JWT_HEADER(jwt_token) ) response = requests.post( installations.json()[0]["acc...
5,333,165
def m_create_identities(): """Create identities in the Trust Framework hierarchy.""" # Retrieve the Alastria account for node "ala", using the password from deployment (not for production) print(f"\n==> Retrieve Alastria account") Alastria_account = wallet.account( "Alastria", "ThePassword") ...
5,333,166
def donation_process_subscription_deleted(event): """ :param event: :return: """ donation_manager = DonationManager() data = event['data'] subscription = data['object'] subscription_ended_at = subscription['ended_at'] subscription_canceled_at = subscription['canceled_at'] custom...
5,333,167
def get_most_probable_strand(filenames, tolerance, sample_name): """Return most propable strand given 3 feature count files (strand of 0,1, and 2) Return the total counts by strand from featureCount matrix folder, strandness and probable strand for a single sample (using a tolerance threshold for stran...
5,333,168
def main(input_file: str, output_file: str, max_words: int = 10000000, max_len: int = 20) -> None: """ Calculate ngram probabilities at different positions :param input_file: List of words, one per line :param output_file: JSON file where ngram probabilities are stored :param max_words: Max. no. of ...
5,333,169
def listBlogs(username, password, serverURL=None): """Get a list of your blogs Returns: list of dictionaries [{"blogid": ID_of_this_blog, "blogName": "name_of_this_blog", "url": "URL_of_this_blog"}, ...] Arguments: - username: your weblog username - password: yo...
5,333,170
def find_lineup_no_optimization(set1, set2): """ Find the approximate offset between two GPS data sets without range start optimization. This algorithm first identifies a primary data set and a secondary one based on which starts later. The offset is then applied to the secondary data set. After ma...
5,333,171
def strongly_connected_components(G): """Generate nodes in strongly connected components of graph. Parameters ---------- G : NetworkX Graph An directed graph. Returns ------- comp : generator of lists A list of nodes for each strongly connected component of G. Raises ...
5,333,172
def matching_plots_nn(plots_0, plots_1, K): """ :param plots_0: :param plots_1: :param K: :return: """ M, N = plots_0.shape[0], plots_1.shape[0] mapping = {} cost_mat = np.zeros((M, N), dtype=np.float32) for i, plot_0 in enumerate(plots_0): for j, plot_1 in enumerate(plo...
5,333,173
def find_file_start(chunks, pos): """Find a chunk before the one specified which is not a file block.""" pos = pos - 1 while pos > 0: if chunks[pos][0] != 0x100 and chunks[pos][0] != 0x102: # This is not a block return pos else: pos = pos - 1 return pos
5,333,174
def navigation_children(parser, token): """Navigation""" args = token.contents.split() kwargs = extract_kwargs(args) if len(args) < 2: raise template.TemplateSyntaxError( _("navigation_children requires object as argument and optionally tree={{tree_name}}") ) return Navig...
5,333,175
def _update_manifest(manifest_file, name, version): """Update the toolplus manifest file with updated name and version """ if os.path.exists(manifest_file): with open(manifest_file) as in_handle: manifest = yaml.safe_load(in_handle) else: manifest = {} manifest[name] = {"...
5,333,176
def get_all_ann_index(self): """ Retrieves all annotation ids """ return list(self.ann_infos.keys())
5,333,177
def file_to_list(file_path): """ 读取文件到lists :param param1: this is a first param :param param2: this is a second param :returns: this is a description of what is returned :raises keyError: raises an exception @author: jhuang @time:1/22/2018 """ lists...
5,333,178
def reverse_words(str): """Reverses the letters in each word of a string.""" words = str.split() new_words = reverse(words[0]) for word in words[1:]: new_words += ' ' + reverse(word) return new_words
5,333,179
def download_file( bucket_name, source_file_name, destination_file_name, bucket_client=None ): """Downloads a blob from the bucket.""" # The ID of your GCS bucket # bucket_name = "your-bucket-name" # The ID of your GCS object # source_blob_name = "storage-object-name" # The path to which t...
5,333,180
def review_request_closed_cb(sender, user, review_request, type, **kwargs): """Send e-mail when a review request is closed. Listens to the :py:data:`~reviewboard.reviews.signals.review_request_closed` signal and sends an e-mail if this type of notification is enabled (through the ``mail_send_review...
5,333,181
def parse_www_authenticate_header(value, on_update=None): """Parse an HTTP WWW-Authenticate header into a :class:`WWWAuthenticate` object. :param value: a WWW-Authenticate header to parse. :param on_update: an optional callable that is called every time a value on the :class:`WWWA...
5,333,182
def get_image_feature_column(X: pd.DataFrame) -> str: """ Get only the image feature column name from X """ X = X.select_dtypes(object) img_features_col_mask = [X[col].str.startswith("/9j/", na=False).any() for col in X] # should have just one image feature assert sum(img_features_col_mask) == 1, "...
5,333,183
def pbr_specular_glossiness(mh): """Creates node tree for pbrSpecularGlossiness materials.""" # This does option #1 from # https://github.com/KhronosGroup/glTF-Blender-IO/issues/303 # Sum a Glossy and Diffuse Shader glossy_node = mh.node_tree.nodes.new('ShaderNodeBsdfGlossy') diffuse_node = mh....
5,333,184
def stop(): """ Stops session, clean all tables associated with this session. Examples -------- >>> from common.python import session >>> session.stop() """ RuntimeInstance.SESSION.stop()
5,333,185
def _PlusMinusString(added_items, removed_items): """Return a concatenation of the items, with a minus on removed items. Args: added_items: list of string items added. removed_items: list of string items removed. Returns: A unicode string with all the removed items first (preceeded by minus sign...
5,333,186
def write_to_log(msg, room_name): """ Writes chat events to log. :param msg: the message to write to the log. :type msg: str :param room_name: the room name. :type room_name: str """ d = time.strftime('%Y-%m-%d') file_name = d + '.log' path = config.CONFIG_PATH + room_name + '/logs/...
5,333,187
def merge_sort(sez): """urejamo z zlivanjem, torej nazačetku razdelimo seznam na 2 dela, potem pa jih zlijemo tako da imenično jemljemo manjše elemente z enega ali drugega seznama. Nakoncu naredimo nov seznam, ki je urejen""" n=len(sez) if n<=1: return sez levo = merge_sort(sez[:n//2]) desn...
5,333,188
def forall_funct(pred, l): """TODO : une version résursive de forall, plus fonctionnelle, utilisant UNIQUEMENT empty, head et tail sans boucle for ni affectation. La fonction sera récursive""" if empty(l): return True return pred(head(l)) and forall_funct(pred, tail(l))
5,333,189
def get_pairs(l, k): """ Given a list L of N unique positive integers, returns the count of the total pairs of numbers whose difference is K. First, each integer is stored into a dictionary along with its frequency. Then, for each integer I in the input list, the presence of the integer I+K is checked w...
5,333,190
def numba_to_jax(name: str, numba_fn, abstract_eval_fn, batching_fn=None): """Create a jittable JAX function for the given Numba function. Args: name: The name under which the primitive will be registered. numba_fn: The function that can be compiled with Numba. abstract_eval_fn: The abstract ...
5,333,191
def zip_metadata(iterable: Iterable[T], keys: Iterable[str], values: Iterable[Any]) -> Iterator[T]: """ Adds meta-data to each object in an iterator. :param iterable: The object iterable. :param keys: The meta-data key iterable. :param values: The meta-data iterable. :return: ...
5,333,192
def get_projects_query_flags(project_ids): """\ 1. Fetch `needs_final` for each Project 2. Fetch groups to exclude for each Project 3. Trim groups to exclude ZSET for each Project Returns (needs_final, group_ids_to_exclude) """ project_ids = set(project_ids) now = time.time() p = r...
5,333,193
def openTypeNameVersionFallback(info): """ Fallback to *versionMajor.versionMinor* in the form 0.000. """ versionMajor = getAttrWithFallback(info, "versionMajor") versionMinor = getAttrWithFallback(info, "versionMinor") return "%d.%s" % (versionMajor, str(versionMinor).zfill(3))
5,333,194
def do_class_schema(mc, args): """Display class schema""" schema = mc.schemas.get(args.class_name, args.method_names, class_version=args.class_version, package_name=args.package_name) print(utils.json_formatter(schema.data))
5,333,195
def get_quoted_text(text): """Method used to get quoted text. If body/title text contains a quote, the first quote is considered as the text. :param text: The replyable text :return: The first quote in the text. If no quotes are found, then the entire text is returned """ lines = text.split('\n...
5,333,196
def pad_sequences(sequences, pad_tok): """ Args: sequences: a generator of list or tuple pad_tok: the char to pad with Returns: a list of list where each sublist has same length """ max_length = max(map(lambda x: len(x), sequences)) sequence_padded...
5,333,197
def get_username_for_os(os): """Return username for a given os.""" usernames = {"alinux2": "ec2-user", "centos7": "centos", "ubuntu1804": "ubuntu", "ubuntu2004": "ubuntu"} return usernames.get(os)
5,333,198
def stats_getter(context, core_plugin, ignore_list=None): """Update Octavia statistics for each listener (virtual server)""" stat_list = [] lb_service_client = core_plugin.nsxlib.load_balancer.service # Go over all the loadbalancers & services lb_bindings = nsx_db.get_nsx_lbaas_loadbalancer_bindings...
5,333,199