content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Mapping from typing import Any from typing import Tuple def split_config(config: Mapping[str, Any]) -> Tuple[dict, InternalConfig]: """ Break config map object into 2 instances: first is a dict with user defined configuration and second is internal config that contains private keys for ...
74775375cd4f7119b2f31ac31489a1d0509d7729
37,011
from scipy.interpolate import interp1d import numpy as np def klatt_bridge(f0, ff, bw, av, avs, ah, af, fs, dur, inv_samp=50): """ Processes/interpolates input parameters for Klatt synth, runs synth. Arguments: f0 (Track object) -- fundamental frequency contour ff (list, len n_form, T...
9b584479e229ea389eaa927342f3fe0d18975e5a
37,012
def create_dict(data: list): """ Cria um dicionário onde a chave é o tempo de duração da palestra e o valor é uma lista que contém as palestras com essa duração. """ data = lectures_ordered_by_duration(data) new_set = {} for item in data: if item[0] not in new_set: ...
ecd985e57ac7d3244c99e0daee4ba2d0a18b56d3
37,013
def _kernel_cdf_gamma(x, sample, bw): """Gamma kernel for cdf, without boundary corrected part. drops `+ 1` in shape parameter It should be possible to use this if probability in neighborhood of zero boundary is small. """ return stats.gamma.sf(sample, x / bw, scale=bw)
02e50b8fe7e6b594d8d4e9236f3ac611916c98c2
37,016
def infer_type(node): """A method to infer the type of an intermediate node in the relay graph.""" mod = node if isinstance(node, _module.Module) else _module.Module.from_expr(node) mod = _transform.InferType()(mod) entry = mod["main"] return entry if isinstance(node, _expr.Function) else entry.body
d77a9e00562c68337129a020398b0e0359900aff
37,017
from typing import Counter def palindrome_from(letters): """ Forms a palindrome by rearranging :letters: if possible, throwing a :ValueError: otherwise. :param letters: a suitable iterable, usually a string :return: a string containing a palindrome """ counter = Counter(letters) sides ...
cbc4bab8e1ea9ce094007620314803a69f5ad330
37,018
def get_cloud(session, cloud_name, return_type=None, **kwargs): """ Retrieves details for a given cloud name :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type cloud_name: str :param cloud_name: Cloud Name: i.e: zadaraqa9 :typ...
fe524715a931504f3825240d404a0397fd595b54
37,019
def check_scopes(required_scopes, scopes): """Check that required_scope(s) are in scopes Returns the subset of scopes matching required_scopes, which is truthy if any scopes match any required scopes. Correctly resolves scope filters *except* for groups -> user, e.g. require: access:server!user=x,...
34cb956ee1cd3b4657005e3cd06b55b61b2906e4
37,020
def new_filter(filters=None): """ Returns the default lookup filters. :param filters: dict - The defaults are updated with this dict before being returned. :returns: dict """ out = dict(const.DEFAULT_FILTERS) if filters is not None: if not isinstance(filters, dict): ...
c38bd00d08ca10533c39d84753df4c7f1b135687
37,021
import re import math def load(filename): """load a 'TAMO'-formatted motif file""" FID = open(filename,'r') lines = FID.readlines() FID.close() motifs = [] seedD = {} seedfile = '' for i in range(len(lines)): if lines[i][0:10] == 'Log-odds matrix'[0:10]: w = le...
22a6d5796a9fa4b8e813d62fcf52cea05ee5f987
37,023
def create_div_stats(Pi, a, b): """Return div element with text of distribution statistics.""" # Calculate mode and variance probability based on prior. if a == 1 and b == 1: mode_str = "any value" else: # str(round((a - 1.0) / (a + b - 2.0), 7)) mode_str = f"{(a - 1.0) / (a + b...
974c5fbf479a7cc44d7aee16f00e1e08964af259
37,025
def check_credentials(account): """ Function that check if a Credentials exists with that account name and return true or false """ return Credentials.if_credential_exist(account)
cc9724bd6bbc3059ac7610ebcc650d76ba93fcce
37,026
from typing import List from re import T def quicksort(args: List[T]) -> List[T]: """ >>> quicksort([4, 3, 2, 1]) [1, 2, 3, 4] >>> quicksort([4, 2, 3, 1]) [1, 2, 3, 4] >>> quicksort([1, 2, 4, 3]) [1, 2, 3, 4] >>> data = list(range(100)) >>> random.shuffle(data) >>> quicksort(da...
4a48608d10550f60a458337029e0ecbf94167a07
37,027
def vect3_bisector(v1, v2): """ Gives the bisector vector of v1, v2 v1, v2 (3-tuple): 3d vectors return (3-tuple): 3d vector """ return vect3_add(vect3_normalized(v1), vect3_normalized(v2))
9c7209e6850b59ecade9c263e47e9c178010af40
37,028
def check_intra_node_overlap(node_a, node_b): """ check if alignments of the same read hit overlapping parts of the same node (or node_a and _b are different) """ same_node = True if node_a.name != node_b.name: same_node = False same_orientation = False overlap_bp = 0 ...
13f019b552576cf57cf08363ff42f7e3067f659d
37,029
import tensorflow.keras as keras def load_model(filepath, custom_objects=None, compile=True): """ Loads a model saved via `save_model`. Arguments: filepath: One of the following: - String, path to the saved model - `h5py.File` object from which to load the model cu...
7b1dc2616cb81567bb178a33714580275cee0918
37,030
def read_guess_word(row): """ Read the specified row's results. """ guess_result = [read_guess_letter(row, ordinal) for ordinal in range(word_len)] return guess_result
fa86d12a90eefa7e3caa5483aabc379986025076
37,031
def teacher_data(num_train=100, num_test=300, num_feat=5, num_feat_teach=10, width=1.0): """Generate two Gaussians and then split features into normal features and teacher features """ (metadata, examples, labels) = cloudgen(num_train+num_test, num_feat+num_feat_teach, ...
d1adcd8efdcfbe187f5e058500fc3475fc72db16
37,032
def _transformer_mask(x, triu, mask, lengths, left_aligned): """Helper function to determine attention masks for the transformer Args: x (:py:class:`dynet.Expression`): Input (dimensions ``input_dim x L``) triu (bool): Upper triangular masking mask (:py:class:`dynet.Expressi...
d9b639437d95e6b0379016179ceedc328b7ffa2c
37,033
def inverse_alr(Y: np.ndarray, ind=-1, null_col=False): """ Inverse Centred Log Ratio transformation. Parameters --------------- Y : :class:`numpy.ndarray` Array on which to perform the inverse transformation, of shape :code:`(N, D-1)`. ind : :class:`int` Index of column used as...
9cdcf851edad0718cc47b016077cca949670152e
37,034
import re def content_insert_emotes(bot: Bot, string: str): """ Method that will attempt to turn the passed in string and replace emoji sequences with the appropriate emote Parameters ---------- bot: Bot pass in bot reference to find emotes string: str the string that may or m...
54b88baf8c093057a02d41b63bd5f7869606793f
37,036
def square(root): """This function calculates the square of the argument value""" # result = num * num return root * root
54049a92a0383c756911a4604161e092d496ce62
37,037
from typing import MutableSequence from typing import Any def quick_sort(seq: MutableSequence[Any]) -> MutableSequence[Any]: """Quicksort or Hoare's sort. Algorithm in-place, complexity: O(n*log(n)) for a totally unsorted seq. """ def _quick_sort( _seq: MutableSequence[Any], _...
b1003afbe9ddb812ba33a99187e1a7f91c31fcc7
37,038
import string from typing import Counter def letter_frequency(seq): """Returns a dictionary with the frequencies of letters in the sequence""" freq = filter(lambda x: x in string.ascii_letters, seq.lower()) freq = dict(Counter(freq).most_common()) freq.update(dict((x, 0) for x in filter(lambda x: x no...
bcbf61526c395bc8df36bf7b3a7a37b25dbe1aba
37,039
def ns_template(): """api.query.ns_template 获取[模板]命名空间中所有页面 Returns: List Of Response(py.Dict) Response: { 'pageid': 页面id, 'ns': 10, 'title': 标题, } """ return _abstract_ns_allpages(10)
db95dfa9ebe4c632666f02e68df0d478b0748b84
37,040
from typing import Optional from datetime import datetime def test_collect_account_basic_account_metrics(target_datetime: Optional[datetime.datetime] = None) -> dict: """ Run the CostManager.collect_account_basic_account_metrics() function and retrieve the results. """ end, _, previous_month_start = _...
e53242e4fa8109988939de759cf44f3d57af59aa
37,042
def shadow_model(): """The architecture of the shadow model is same as target model, because the attack is white-box, hence the attacker is assumed to know this architecture too. :return: shadow model """ classifier = Sequential() classifier.add( Dense(1, input_dim=featur...
89ae1c17d7cc7d45cff3f28103929d76d4632a63
37,043
def is_kind_of_class(obj, a_class): """ Function that determine if a class is a specific class or an inherited class. Args: obj (object any type): The object to analyze. a_class (object any type): The reference object. Returns: Returns True if the obj is exactly an instanc...
3a31ad121ace5918e7f3f5d7620e5ab94a92501a
37,045
def get_candidate_type(candidate_tokens): """Returns the candidate's type: Table, Paragraph, List or Other.""" first_token = candidate_tokens[0] if first_token == "<Table>": return "Table" elif first_token == "<P>": return "Paragraph" elif first_token in ("<Ul>", "<Dl>", "<Ol>"): ...
298856aef02c44683af6bd32cb9284f62d0aabc9
37,046
def parse_file(input_file): """ Input: A file containing one binary-number string per line Output: A list of binary number strings Blank lines and lines starting with '#' are ignored """ strings = [] with open(input_file) as f: for line in f.readlines(): line = line.strip...
63b51ee15c264c8e0635053d80bf47f70687023e
37,047
import torch def from_numpy(x): """Creates a ComplexTensor from a numpy.ndarray. """ a = x.real.copy() b = x.imag.copy() return ComplexTensor(torch.from_numpy(a), torch.from_numpy(b))
e3cb1577e1d4b27bfacb0c8d93dedc4cfeb4f5f7
37,048
def classification_stats(ytrue, ypred, num_samples=1000): """ construct a dataframe that summarizes classification """ # compute aucs, prec, rec, f1 auc = roc_auc_score(ytrue, ypred) yp = ypred > .5 prec = precision_score(ytrue, yp) rec = recall_score(ytrue, yp) f1 = f1_score(ytrue, y...
7593e835499ad1e1acb5aa12b7556c7a2368d852
37,049
def process_map_input(input_lines): """ Find the dimensions of a map using the lines of input :param input_lines: List of string representing the map :return: (x: width, y: height) Tuple """ height = len(input_lines) - 1 width = len(input_lines[0]) return width, height
30662e1466d6d553ddee797c6252453c6f6f7f47
37,050
def total_loss(c_layer, s_layers, generated): """ Computes the total loss of a given iteration :param c_layer: The layer used to compute the content loss :param s_layers: The layer(s) used to compute the style loss :param generated: The generated image :return: The total loss """ conten...
1914f501873326c92bd28d938872f77df55d67a8
37,051
import random def weighted_choice(lst): """Choose element in integer list according to its value. E.g., in [1,10], the second element will be chosen 10 times as often as the first one. Returns the index of the chosen element. :ivar [int] lst: List of integers. :rtype: int """ total = ...
513ca734a7b96f08993bd03c47df9c60288ebe50
37,052
def git_connect(github_username, github_password, github_repo): """ Logs in to github with our creds, returns gh,repo,branch objects. """ gh = github3.login(username=github_username, password=github_password) # we login and get a session. repo = gh.repository(github_username,github_repo) # we create our...
4bcaf55bbbe3404fffea30c11c9a7f779f213252
37,053
def get_course(doc): """Returns the course name for given document of type Course, Chapter, Lesson or Exercise. """ if doc.doctype == "LMS Course": return doc.name elif doc.doctype == "Course Chapter": return doc.course elif doc.doctype == "Exercise": return doc.course el...
e69510c1d8055e08562c2fe6842ef209b93c5942
37,054
def v_vorticity(u, v, dx, dy, dim_order='xy'): """Wrap vorticity for deprecated v_vorticity function.""" return vorticity(u, v, dx, dy, dim_order=dim_order)
13fa0cdc4be4df6ec98bd9646cbc33ad84a67c19
37,056
from typing import List def split_rgb(stack: Image, with_alpha=False) -> List[Image]: """Variant of stack_to_images that splits an RGB with predefined cmap.""" if not stack.rgb: raise ValueError( trans._('Image must be RGB to use split_rgb', deferred=True) ) images = stack_to_...
dd3b80bf36ba430a26a9ff5605b215b5d6a68524
37,057
def get_country(user): """ Returns the object the view is displaying. """ user_countries = ActivityUser.objects.all().filter( user__id=user.id).values('countries') get_countries = Country.objects.all().filter(id__in=user_countries) return get_countries
1abebfec315834aa00ef8f12b08cf6e64262169b
37,058
def isfirefox(session): """ bool: Whether the session is using Firefox. """ return getattr(session.driver, "_firefox", False)
ca7c5c217de308642e4ec0687c42a0dc71cfeecd
37,059
from typing import Dict from typing import Any from typing import cast def generate_readme(meta: Dict[str, Any]) -> str: """ Generate a Markdown-formatted README text from a model meta.json. Used within the GitHub release notes and as content for README.md file added to model packages. """ md ...
41b91b31d3c2fbeab1440a0ec82d06d857c98168
37,060
def origin_tag(parser, token): """Create a node indicating the path to the current template""" if hasattr(token, "source"): origin, source = token.source return OriginNode(origin) else: return OriginNode()
2ad166eaebcfd6cd6c00f76fdb339342e05ae100
37,061
def get_bucket_name(config, bucket_suffix=None): """ Return a bucket name of the form: ${account_id}-${project}-${suffix} Args: config: dictionary containing all variable settings required to run terraform with. bucket_suffix: string to add to the returned bucket name. ...
0d607f35e2beb6149e21da426dc73a1118ad1967
37,062
def break_track(xy,waypoints,radius_min=400,radius_max=800,min_samples=10): """ xy: coordinate sequence of trackline waypoints: collection of waypoints return pairs of indices giving start/end of transects, split by waypoints. """ breaks=[] for waypt in waypoints: dists = mag( xy[:...
a56795deac8c41a0670a3f4d76d698f2cb54e2e0
37,064
def parse_string(s): """ Parse string containing Snowball code. Returns the corresponding AST. """ reset() return PROGRAM.parseString(s)[0]
b3298ddc2bba330e07cbe15078d2286b5250c95e
37,065
def list_to_multipolygon_df(list_of_inds, discretizer=DefaultSystem, split=True): """ Parameters ---------- split : object """ unique_h3 = list(set(list_of_inds)) polys = [discretizer.ind_to_boundary(cod) for cod in unique_h3] if split: polys = [shp_help.split_polys(poly) for po...
0a2ab86112324480a4e8f3a7a4f3275e7a8fe699
37,066
def Get_Data(filename, start, stop): """Takes output from txt file and converts to a np.array Argument: filename -- filename including end bit, enclosed in single inverted commas start, stop -- integers, lines to read if there's a header etc Returns: array -- np.array of file c...
9844606de755aa71e70df7f5bca67518df5dc595
37,067
from datetime import datetime def get_es_index_name(project, meta): """ Get the name for the output ES index :param project: seqr project identifier :param meta: index metadata :return: index name """ return '{project}__structural_variants__{sample_type}__grch{genome_version}__{datestamp}...
fc1245287aed07ddd8d90f33cadc095c22f944a3
37,069
def triangle_coordinates(i, j, k): """ Computes coordinates of the constituent triangles of a triangulation for the simplex. These triangles are parallel to the lower axis on the lower side. Parameters ---------- i,j,k: enumeration of the desired triangle Returns ------- A numpy ar...
ffdaf2c601cb4f25b15b67a97a9746a80dbcdd6b
37,070
def generate_lines(rects, room): """ Converts a list of rects each containing x, y, width, height, theta into a list of lines (each rect has 4 lines) room is (width, height) of surrounding room returns list of lines, each line is 2 points """ # x, y, w, h, angle rects.append([0, 0, room...
7d57a8dd892727bcda4be9c97cb5aa10509f3519
37,071
def generic_exception_json_response(code): """ Turns an unhandled exception into a JSON payload to respond to a service call """ payload = { "error": "TechnicalException", "message": "An unknown error occured", "code": code } resp = make_response(jsonify(payload), code) ...
ad891505aefa9dc261a00a3a50d0033b9932f113
37,072
def reference_col(tablename, unique=False, nullable=False, pk_name='id', **kwargs): """Column that adds primary key foreign key reference. Usage: :: category_id = reference_col('category') category = relationship('Category', backref='categories') """ return db.Column(...
d7400e6b1a9b65b1aa43e14442fa65ff01ef59c6
37,073
import cairosvg import StringIO def convertSvgToPng(svg_data): """ Converts the given svg data to PNG. This one is preferred over convertSvgTo(), because it simply returns the result instead of a file and does not have excessive white space. """ buffer = StringIO.StringIO() cairosvg.svg2png(by...
93bcc7c6657aee877ca032775903700c00b8617b
37,074
def RegexCheck(re, line_number, line, regex, msg): """Searches for |regex| in |line| to check for a particular style violation, returning a message like the one below if the regex matches. The |regex| must have exactly one capturing group so that the relevant part of |line| can be highlighted. If more ...
31e979570eb4e0b251f445555f24fadef8e6879d
37,075
import time import ast def load_graphml(filename, folder=None): """ Load a GraphML file from disk and convert the node/edge attributes to correct data types. Parameters ---------- filename : string, the name of the graphml file (including file extension) folder : string, the folder contai...
b0c2afff46e8e81d450a1fc32e7e169e04ce285b
37,076
def cosine_distances(test, support): """Computes pairwise cosine distances between provided tensors Parameters ---------- test: tf.Tensor Of shape (n_test, n_feat) support: tf.Tensor Of shape (n_support, n_feat) Returns ------- tf.Tensor: Of shape (n_test, n_support) """ rnorm_test = t...
06214a59cda12b78a2b8a520c3cf7fe02b7c8479
37,077
def substring(column, pos=0, l=1): """ Substring starts at ``pos`` and is of length ``l`` when str is String type or returns the slice of byte array that starts at ``pos`` in byte and is of length ``l`` when ``column`` is Binary type # Arguments column: a ``Column`` object, or a column name ...
6922224fda5a72305f2d7158b28982d30de722fa
37,079
def _f2_div_ ( self , other ) : """Operator for ``2D-function / other''""" return _f2_op_ ( self , other , Ostap.MoreRooFit.Division , "Divide_" )
ecc5ce2cf3e423209f006f04b90953b423270be7
37,080
def usplit( uval ): """ Split Unicode string into a sequence of characters. \U sequences are considered to be a single character. You should assume you will get a sequence, and not assume anything about the type of sequence (i.e. list vs. tuple vs. string). """ # The commented code (below)...
39efcb9e9f87f7809ec5919e23617c860654bcb8
37,081
def aten_mean(mapper, graph, node): """ 构造求均值的PaddleLayer。 TorchScript示例: %x.28 : Tensor = aten::mean(%result.1, %4967, %3, %2) 参数含义: %x.28 (Tensor): 输出,求均值后的结果。 %result.1 (Tensor): 输入,需要求均值的Tensor。 %4967 (int/list): 求平均值运算的维度。 %3 (bool): 是否在输出Tensor中保留减小的维度。 ...
21eba8c745363e21d5e049100f06746fbef2c0e4
37,082
def get_partial_dict(prefix, dictionary, container_type=dict): """Given a dictionary and a prefix, return a Bunch, with just items that start with prefix The returned dictionary will have 'prefix.' stripped so:: get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}) would return...
a4450fe8930932c1568fba1dd42053e29eddc573
37,083
def _AddPropertiesForRepeatedField(field, cls): """Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add val...
2795730972837612d1b87bc6cba2e28a8047c457
37,084
async def add_user(user: NewUserPayload): """ Creates new user in database """ try: user_exists = await storage.driver.user.check_if_exists(user.email, user.id) except ElasticsearchException as e: raise HTTPException(status_code=500, detail=str(e)) if not user_exists: try...
72a2c63eaa335564f4ad385a573847cce5df1f23
37,085
async def _update_instance_async(filter, projection, update) -> dict: """Helper to update an instance async-style""" await moto.update_one(collection="system", filter=filter, update=update) return await _get_instance_async(filter, projection)
7d87e656304e2a28166a059fdda8252c197bed9a
37,087
from pathlib import Path from typing import Optional from typing import List def cryptominisat_solve(input_file: Path, docker_mode: bool = DEFAULT_DOCKER_MODE_ON) -> Optional[List[int]]: """Attempts to solve a CNF formula with CryptoMiniSAT and returns the result as a list of integers. Returns an empty l...
c601574773ca4a1bc2d1e21064e5b8c1e999ecba
37,088
import math def sen(x): """ El seno de un número. El ángulo debe estar expresado en radianes. .. math:: \sin(x) Args: x (float): Argumento. Returns: El seno. """ return math.sin(x)
26f7854e550cd0ac68123d3f2d5b3117aef282a6
37,089
def req_item_packs(): """ Called by S3OptionsFilter to provide the pack options for an Item Access via the .json representation to avoid work rendering menus, etc """ req_item_id = None args = request.args if len(args) == 1 and args[0].isdigit(): req_item_id = args[0] e...
22cf4c4884ef84b924c0e09e134bce8074455349
37,090
def create_board() -> t.List[t.List[int]]: """Initialize game board (road).""" board = [] # Create rows for _ in range(BLOCKS_AMOUNT_Y + 1): board.append( [Blocks.frame] + [Blocks.empty for _ in range(BLOCKS_AMOUNT_X - 2)] + [Blocks.frame] ) return...
d58d82e8b201b8a91a748559f5195cba7355ab3b
37,091
def SymDatToPath(symtext): """Convert a Cygwin style symlink data to a relative path.""" return ''.join([ch for ch in symtext[12:] if ch != '\x00'])
0d5104819678ca12d95b5f987a88726c5aef3f18
37,092
def n_bytes(count: int, name: str = ""): """ Create an instance of a byte string of ``count`` length. Setting ``count`` to ``-1`` will consume the entire remaining buffer. """ class BYTES(BytesDataType): size = count return BYTES(name)
a06668571b2b0c759361ce3bee74fa67af9b682e
37,093
from typing import Container def find_trait_and_value(obj, pathname): """Return a tuple of the form (trait, value) for the given dotted pathname. Raises an exception if the value indicated by the pathname is not found in obj. If the value is found but has no trait, then (None, value) is returned. ...
2a0851e433ceac57494718d38942147c25d2c07a
37,094
def bigbird_block_rand_mask(from_seq_length, to_seq_length, from_block_size, to_block_size, num_rand_blocks, last_idx=-1): """Create adjacency list of random attention. Args: ...
1d51a4eec884b6c38b58897ad245428b73f19f06
37,096
import json def list_(env=None, user=None): """ List the installed packages on an environment Returns ------- Dictionary: {package: {version: 1.0.0, build: 1 } ... } """ cmd = _create_conda_cmd('list', args=['--json'], env=env, user=user) ret = _execcmd(cmd, user=user) if ret[...
25a9f82afe94587b832ccf70a16949d1f400c089
37,097
def read_dir_key(fname='', existing_dict=None, delim=None): """ Read a directory mapping key. """ out_dict = read_nametoname_key(fname=fname, existing_dict=existing_dict, delim=delim) return(out_dict)
5c7a7620bd11e146f37b14129647a057ecd66099
37,098
def get_end_pair_index(s: str, i: int): """ This method takes a string and an integer as inputs. It searches for the opening brace'[' using the given integer as the index of the opening brace in the given string. It outputs the index of the closing pair ']' in the string. :param s: The input string...
bd0413aa2ff48df2bb76736a11fda40757f2d482
37,099
from typing import Union from typing import List def count(obj: Union[int, List]) -> int: """Return the number of integers in obj. >>> count(27) 1 >>> count([4, 1, 8]) 3 >>> count([4]) 1 >>> count([]) 0 >>> count([4, [1, 2, 3], 8]) 5 >>> count([1, [2, 3], [4, 5, [6, 7]...
d982b3096dc9c7776b32bab765e2a17769d128e9
37,100
def kmeans(x, n_clusters=20, random_state=42, **sklearnArg): """Given a set of different 1D functions (represented in matrix form where each row contains the function values on a given grid), this method clusters those functions and tries to find typical function structures. Args: x (numpy matr...
2671a7d40f339cc8e45c28381e65c8f8ceed474e
37,101
def GetClientSecretFlag(): """Anthos auth token client-secret flag, specifies the Client Secret is the shared secret between OIDC client application and OIDC provider.""" return base.Argument( '--client-secret', required=False, help='Client Secret is the shared secret between OIDC client applicati...
7d01e32208f51299e793359458ecef1da5e5bae6
37,102
def login(request): """ Fonction idantifiant les gens et/ou renvoyant le formulaire. """ message = None form = None topThree = [] if request.method == 'POST': if request.session.test_cookie_worked(): request.session.delete_test_cookie() form = LoginForm(reque...
7e3dfe056e690c5830053a6e05f86b74e37e0fec
37,103
def start_instance_pool(instance_pool_id: str, configuration: Configuration = None, secrets: Secrets = None) -> OCIResponse: """Start the given OCI Compute instances.""" client = oci_client(ComputeManagementClient, configuration, secrets, ...
462f76cad9c9c7c7817ccaf6ed4715c7fb5caed1
37,104
def label_rank(label, scores, label_order) -> int: """ Add Labels based on Rank :param label: Label to assign to item :param scores: Score to rank item :param label_order: Order of Labels :return: Return Index """ loc = label_index(label, label_order) if loc is None: return ...
06d5bb4d01f7b8194555f978be66ddb238b03360
37,105
def _single_quote_string(name: str) -> str: # pragma: no cover """Single quote a string to inject it into f-strings, since backslashes cannot be in double f-strings.""" return f"'{name}'"
39868168862f3bd60d8da6168503cbc51fcbda84
37,106
def compute_rel_rois(num_rel, rois, relations): """ union subject boxes and object boxes given a set of rois and relations """ rel_rois = np.zeros([num_rel, 5]) for i, rel in enumerate(relations): sub_im_i = rois[rel[0], 0] obj_im_i = rois[rel[1], 0] assert(sub_im_i == obj_im...
4fcdf1fe57557a73c3da476e327f1632ea217d6d
37,108
from pyparsing import ( srange, oneOf, Forward, Optional, Suppress, Word, ZeroOrMore, dblQuotedString, pythonStyleComment ) def from_gml(text): """ Return the list of graphs read from `text`, a string in GML format. This function assumes that the input follows the GML specification, p...
d223438d6b38d1b1c62c2e9a734a6a08b94e1721
37,109
import typing from unittest.mock import patch def parse(type_string: str, *, func=None): """Parse the given type string. Args: type_string (str): The type string to be parsed. func (function): The function to which the type string belongs (optional). This causes the t...
485d0d5dd2edb63873464e3e02d67c202947d78b
37,110
from threading import Thread def run(data, inFile="", encrypt=False, method=3, aad="", key=config.KEY): """ Run encryption of decryption. data: file name with extension encrypt: False to decrypte method: Block cyphering method """ if len(data) > 100000: thread = Thread(target=wa...
3884592005f72a2e2375da2698f37a61e7bc6aa3
37,111
def convert_str_version_number(version_str): """ Convert the version number as a integer for easy comparisons :param version_str: str of the version number, e.g. '0.33' :returns: tuple of ints representing the version str """ version_numbers = version_str.split('.') if len(version_number...
b550b7d07d9b226800de261f792bf0995ac21738
37,112
import torch def valid_simulation(_state, _params): """ AW - valid_simulation - return a binary variable per simulation indicating whether or not that simulation satifies the desired policy outcome. :param _state: tensor (N x D): tensor of the state trajectory. :return: tensor (N, ), bool: ten...
6eb82ec744cbab353f649e63d54c0d95236f1699
37,113
def computeA(diameter): """Computes area of circle""" radius = diameter / 2.0 return np.pi * (radius**2)
d78b596a3df0e82cf93b5e0318b9ba53c3dc1b6c
37,114
def RemoveFromLinuxKernelCmdline(option): """ Remove 'option' to the kernel boot options of the grub configuration. """ if FindInLinuxKernelCmdline(option): src = r'^(.*?' + MyDistro.grubKernelBootOptionsLine + r'.*?)(' + option + r')(.*?)("?)$' rep = r'\1\3\4' try: R...
798c803d3fb7d2ac9d525e8ea67e858c518e4e2d
37,115
def get_maximum_weight(G, S, T): """ Given a networkx graph G and two subsets of vertices S and T, this method returns the maximum weight of an edge e, having one endpoint in S and the other in T :param G: A networkx graph :param S: A subset of vertices in G :param T: A subset of vertices in G ...
8cb40045a303845b070760aad3c9d66815827a3d
37,116
def create_volume_snapshot(session, cg_id, display_name, return_type=None, **kwargs): """ Creates a new snapshot for the specified volume. Manually initiated snapshots will fall under the "On Demand" snapshot policy. :type session: zadarapy.session.Session :param session...
caf9fdbdb5ddb26c3b271f3c568f3e49b5c5acd2
37,117
def parse_elem(elem): """Determine element type and dispatch to other parse functions.""" if len(elem) == 0: return parse_text(elem) if not elem[0].attrib: return parse_list(elem) if elem[0].get('Name') == 'Key': return parse_key_value_dict(elem) return parse_attrib_dict(elem...
c6195c8f8389b0ea93e8f48a827d0e212eb5aa42
37,118
from typing import Optional def configured_version_for(artifact_name: str) -> Optional[str]: """Given the name of an artifact, retrieves the version of that artifact from the current stack configuration. Returns `None` if no version has been specified for that artifact. In general, we will have versi...
90e6bd5f09aa53ff33fefda5027c3b110d923578
37,119
def filtered_cumulative_sum(df, columns, latest_date, reference_column_name="covid_vacc_date"): """ This calculates cumulative sums for a dataframe, and when given a set of characteristics as columns, produces a dictionary of dataframes. Args: df (Dataframe): pandas dataframe. At the very least...
5bcb2d79fdfb2e8f26868ef3d411163b3d73f8e3
37,120
def handover_results(): """ Endpoint to get a list of all the handover by release This is using docstring for specifications --- tags: - handovers operationId: handovers parameters: - name: release in: query type: string description: get handover list for ...
a15b0b69b5ddf4654311d0940a37fac548c5dcf4
37,121
def safezip(*args): """make sure *args* are equal len before zipping""" Nx = len(args[0]) for i, arg in enumerate(args[1:]): if len(arg) != Nx: raise ValueError(_safezip_msg % (Nx, i + 1, len(arg))) return list(zip(*args))
f8d2a1c3bbe33903b896e1dbf64ffd1c0804d849
37,122
from typing import Union def chaid_to_graphviz( tree: dict, classes: Union[list, np.ndarray] = [], classes_color: list = [], round_pred: int = 2, percent: bool = False, vertical: bool = True, node_style: dict = {}, arrow_style: dict = {}, leaf_style: dict = {}, **kwds, ): "...
e48dc9611b9208b99daa631217320d644d02a769
37,123
import copy def process_dataset(dataset, func): """Calculate things here using the dataset, then return a dictionary containing names and values for each calculated quantity.""" new_dataset = copy.copy(dataset) del new_dataset["val"] new_dataset.update(func(dataset)) return new_dataset
b38b2edd1abe9a990d8f524b78b38e8abadc7c55
37,124