content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def command_talk(current_buffer, args): """ Open a chat with the specified user /slack talk [user] """ server = servers.find(current_domain_name()) if server: channel = server.channels.find(args) if not channel: channel.open() else: user = server....
75ffd363c126fc43bb650aaa3b5bdf1e7192eb8a
37,591
def project_name(settings_dict): """Transform the base module name into a nicer project name >>> project_name({'DF_MODULE_NAME': 'my_project'}) 'My Project' :param settings_dict: :return: """ return " ".join( [ x.capitalize() for x in settings_dict["DF_MODU...
07411942978ad769d25234f8c7286aaddc365470
37,593
def is_acceptable_smiles(smile: str, allowed_chars=smiles_encoding['indices_token'].values(), min_len=smiles_encoding['min_smiles_len'], max_len=smiles_encoding['max_smiles_len']): """ Checks which smiles Args: smile: (str) smiles string allowed_chars: (lst) list of all...
5eba7e323e17e4ced5e169d4bf107fd98bb39130
37,594
def parse_config_vars(config_vars): """Convert string descriptions of config variable assignment into something that CrossEnvBuilder understands. :param config_vars: An iterable of strings in the form 'FOO=BAR' :returns: A dictionary of name:value pairs. """ result = {} for val...
1bc1b96b6a2b0bf8e42fca0bb4ee9601c883b124
37,595
def create_detections(detection_mat, frame_idx): """Create detections for given frame index from the raw detection matrix. Parameters ---------- detection_mat : ndarray Matrix of detections. The first 10 columns of the detection matrix are in the standard MOTChallenge detection format. ...
ac17116651f90ae1e2e844f6e5e51473b13ea742
37,596
def q_values(state, actions, weights, xf_vec): """ Calculate q values for current state and actions Parameters ---------- state : tuple current state- actions : ndarray possible actions- weights : ndarray weights of linear function approximation- xf_vec : list ...
1922b60dcc8bb64a78909288eeae21e38596c4c0
37,598
import textwrap def _get_parsed_args(): """Parses command line arguments and the config file. Order of precedence for config values is: command line > config file values > defaults Returns: A "Namespace" object. See argparse.ArgumentParser.parse_args() for more details. """ parser = con...
726a022e1e7278d07ee36c74df26793fd055c803
37,599
def sniff(start, data): """ Given the first byte (start) and an unspecified (maybe not all) amount of a FASTA or FASTQ, return summary statistics. """ # scan through the file and get ids/seq_counts (and quality info) if start == '>': seq_count, ids, status = read_fasta(data) elif sta...
861604f2b797e64030b968a427ddc2c61309d0ed
37,600
def is_power_of_two(x): # type: (int) -> bool """Check if `x` is a power of two: >>> is_power_of_two(0) False >>> is_power_of_two(1) True >>> is_power_of_two(2) True >>> is_power_of_two(3) False """ return x > 0 and x & (x-1) == 0
c657fc5c74dacd2acd7855d99bd277933423b1eb
37,601
def link_account(external_id, community, platform_type, platform_identifier, community_platform_id=None, custom_data=None, link_type=None, link_quality=None): """Links a new platform account to an existing user, as specified by their external metagov id.""" metagovID = MetagovID.objects.get(external_id=ext...
eb947132328b9e35048a5d3fc34bd12f95ab99d9
37,602
def validate_jwt(scope, request, on_error=None): """ Validate the incoming JWT token, don't allow access to the endpoint unless we pass this test :param scope: A list of scope identifiers used to protect the endpoint :param request: The incoming request object :param on_error: The error structure ...
ed79c3c725e7d479e57bf6385e6d37ac22920c30
37,603
def cartesian(tensor1, tensor2): """ Computes the pair-wise combinations of first dimensions of tensor1 and tensor2, leaving the last dimension. """ # exclude last dimension *shape1, last1 = shape(tensor1) *shape2, last2 = shape(tensor2) if last1 != last2: raise ShapeError( ...
1ed3588dbd6edc9f45827257dd4054fd7ffd288a
37,604
def add_malicious_key(entity, verdict): """Return the entity with the additional 'Malicious' key if determined as such by ANYRUN Parameters ---------- entity : dict File or URL object. verdict : dict Task analysis verdict for a detonated file or url. Returns ------- dic...
a20ba12ae04d09047f228a26ef6f39e334225cb3
37,605
def _decrypt(cipher, key, data, iv, padding): """ Decrypts AES/RC4/RC2/3DES/DES ciphertext :param cipher: A kSecAttrKeyType* value that specifies the cipher to use :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string ...
19154d4b20e41273d2fcd95fed2fae29288a84fb
37,607
def pieColor(renderer, x, y, rad, start, end, color): """Draws an unfilled pie slice (i.e. circle segment) to the renderer. The start and end of the pie are defined in units of degrees, with 0 being the bottom of the circle and increasing counter-clockwise (e.g. 90 being the rightmost point of the circ...
acfa8d7da01bed1bf45749db2a75f6e2b235e3ef
37,608
def assimilate(left: pd.DataFrame, right: pd.DataFrame): """Assimilate ``right`` to look like ``left`` by casting column data types in ``right`` to the data types in ``left`` where the column name is the same. :param left: left DataFrame :param right: right DataFrame """ # give me all the eleme...
9b6e848a467582da95b692744b47042c886d7a04
37,609
def fix_armature_scale(armature_object, scale_factor, context, properties): """ This function scales the provided armature object and it's animations. :param object armature_object: A object of type armature. :param float scale_factor: The amount to scale the control rig by. :param dict context: A ...
2a19e06f0112a24599f985e4d1e725a5209aff8f
37,610
def remove(property_name): """ Removes the given property. :param property: The property (or property identifier) to remove :type property: Host Specific :return: True if the property was removed """ return None
6f0fd282164d91cf2772ac4155a842a4cb3ccfd2
37,611
from datetime import datetime def get_locality(row_dict): """ Fetch the corresponding locality object for an occurrence and create a new one if necessary. :param row: :return locality_object: """ # Validate and build locality text basis_of_record = row_dict['basis_of_record'] collecti...
fafb414ea410cc8458f0205d5aaa74645f8f3c3e
37,612
import re import string def process_sentence(sentence) : """ Parameters ---------- sentence : a string of words Returns ------- clean_sentence : a string of words without having the unessasry words """ stemmer = PorterStemmer() stopwords_english = stopwords.words('engl...
e490a65ee2ab5925c53038d9276e5ef53915667f
37,614
from typing import Counter def count_terms(terms: list) -> dict: """ Count the number of terms :param terms: term list :return dict_term: The dictionary containing terms and their numbers """ entity_dict = dict(Counter(terms)) print('There are %s entities in total.\n' % entity_dict.__len__...
77e362894fbbae3d0cec99daea845734d30e8a2d
37,616
def augmented_system_projections(A, m, n, orth_tol, max_refin, tol): """Return linear operators for matrix A - ``AugmentedSystem``.""" # Form augmented system if A.size != 0: K = np.block([[np.eye(n), A.T], [A, np.zeros((m,m))]]) else: K = np.eye(n) # LU factorization # z = x - ...
ebd8b0f279a48e49e5eeef88835e68ff62b30b5b
37,617
import json async def export_from_json_file(framework: Frameworks, architecture_file: bytes = File(..., alias='architecture-file'), line_break: LineBreaks = LineBreaks.lf, indent: Indents = Indents.spaces_4, ...
62ccbe303fce141d48545831ea27903594fd87f4
37,618
import asyncio async def toggle_inline(m: Message): """Turn on | off inline mode of your bot""" try: await send_edit(m, "Processing command . . .", mono=True) await app.send_message("BotFather", "/mybots") # BotFather (93372553) await asyncio.sleep(1) # floodwaits data = await get_last_msg(m) usernames ...
2db29162ff064608549d82b11820f154bb11c8a0
37,619
def to_cartesian(r, coord_sys): """ Transforms an array of vectors from a coord_sys to the cartesian coordinate system. :param r: n x 3 matrix of position or any other vectors in spherical coordinates :param coord_sys: 'spherical' or 'cylindrical' :return: n x 3 matrix of position vectors in...
e463bc3e1b284878b15de414a47786b9c2ef83e3
37,620
def pretty_duration(seconds): """Return a pretty duration string Parameters ---------- seconds : float Duration in seconds Examples -------- >>> pretty_duration(2.1e-6) '0.00ms' >>> pretty_duration(2.1e-5) '0.02ms' >>> pretty_duration(2.1e-4) '0.21ms' >>> pr...
ceec602cb07ab5c27831c4ed9e1cd552c5b9dde8
37,621
from datetime import datetime import pytz def get_red_spot(utdt, jupiter): """ GRS: System II: longitude = 9° (jan 2022), drifts 1.75°/month best placed within 50m of transit time """ u0 = datetime.datetime(2022, 1, 1, 0, 0).replace(tzinfo=pytz.utc) dd = utdt - u0 delta_longitud...
9715f8393524a973921ea2c0d4c5a21cdb1eba87
37,622
def set(key, value, expire=0, path='', filename='linuxfabrik-plugin-cache.db'): """Set key to hold the string value. Keys have to be unique. If the key already holds a value, it is overwritten, including the expire timestamp in seconds. Parameters ---------- key : str The key. valu...
9620660953aef0cc38b86a7e4e4609e05b4f53f0
37,623
def users_similarity_score(consumer, producer): """ Compute a similarity score between a consumer's and a producer's signatures. The score is a float between 0 (complete similarity) and 1 (nothing in common). """ count_consumer = float(consumer.rated_statuses) count_producer = float(producer...
4216b7b6610bce210d18642748b3f04088f3103a
37,625
def flip_randomly(inputs, horizontally, vertically, name=None): """Flip images randomly. Make separate flipping decision for each image. Args: inputs (4-D tensor): Input images (batch size, height, width, channels). horizontally (bool): If True, flip horizontally with 50% probability. Otherwise, don't....
7b56322d31e3db7168f7285a3551b96ef9da1e55
37,626
def get_active_games(request): """Get info of selected game type.""" games = GameType.objects.filter(is_active=True).only( 'name', 'description', 'polls_count', 'image') data = [ { 'id': game.id, 'name': game.name, 'description': game.description, ...
4316f2fb66510c3dfaeee08caf3458be4d423ecd
37,628
import requests def total_mastery(key, sID): """ Total Mastery :param key: API key :param sID: Summoner ID :return: The total mastery score of a summoner as an int """ url = nabase + '/lol/champion-mastery/v3/scores/by-summoner/' + str(sID) + \ '?api_key=' + key r = requests.get...
ccc0bac491bd7c8ededc96a9178010d590336214
37,629
from pathlib import Path def find_entry_point_type(entry_point): """ Step 1: If not ENTRY_POINT is defined nor a value is passed, a default value is used (pipeline.yaml for CLI, recursive lookup for Jupyter client). If ENTRY_POINT is defined, this simply overrides the default value, but passing a ...
0625a24504473b3e078bf229390ac43b83c3e7c9
37,630
from typing import Optional import torch def sqrt(x: DNDarray, out: Optional[DNDarray] = None) -> DNDarray: """ Return the non-negative square-root of a tensor element-wise. Result is a :py:class:`~heat.core.dndarray.DNDarray` of the same shape as ``x``. Negative input elements are returned as :abbr:`...
80764b12aa6ac82f117cf8884bbe9036b20abb4f
37,631
import numpy def get_buffered_points(points, centroid=None, factor=2.0): """ Add buffer to points in a plane. For example, to expand a convex hull param points: Points we want to buffer param centroid: Centroid of the points param factor: Defines scalar product for point vectors return numpy a...
08fdc70a867fddda82bc9b1207587db66852d7fb
37,632
def roman(num): """ Examples -------- >>> roman(4) 'IV' >>> roman(17) 'XVII' """ tokens = 'M CM D CD C XC L XL X IX V IV I'.split() values = 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 result = '' for t, v in zip(tokens, values): cnt = num//v res...
e0f51cefd16a098336cd28fb3e35249063c9761c
37,633
def get_available_actions(node,dset): """ get next available actions according to dfg flow """ graph = get_dfg_graph(dset) available_nodes = list(graph[node].keys()) return available_nodes
8bb1f7e118dfc7e931dcaf6063b98dcd08e10c31
37,634
def get_horizontal_angles(): """Get horizontal visual angles (in °).""" x = np.arange(0, _WIDTH) x = x.astype(np.float) x -= np.mean(x) a_x = _ANGULAR_RESOLUTION * x return a_x
0cd362cd3f503221cb2e9756ae5db1dd980ec4a4
37,635
def clone(repo, branch=None, replace=None, skip_existing=None, target_dir=None): """ Clone files from a Git repository. Only the files are copied, not the Git metadata. Can be run multiple times to clone files from multiple repositories. Won't overwrite any existing files unless `replace=True`. ...
05b8f5cbdbbe9dd59e06bba74a7389f65d784992
37,636
def create_url(url, data): """ Method which creates new url from base url :param url: base url :param data: data to append to base url :return: new url """ return url + "/" + str(data)
b08fdc2c9e7ecef589ac5208905de8934f667f2b
37,638
def test_item_path(fconfig: Config, db: SQLAlchemy): """ Tests that the URL converter works for the item endpoints of the resources. The following test has set an URL converter of type int, and will allow only integers using the flask rules. """ DeviceDef, *_ = fconfig.RESOURCE_DEFINITIONS ...
606d996b12eea0efac8da4901a37d504711268a5
37,639
import ast def is_side_effecting(node): """ This determines whether node is a statement with possibly arbitrary side-effects """ node = node.value return isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
137eabb0cbb1b92b48ef05e2800c10e8e598ed1b
37,640
def read_wordlist_file(file_name): """ Reads a one-word-per-line list of words to accumulate (w,c) counts for. Duplicates are collapsed via a dictionary. """ word_list = {} f = open(file_name,'r') lines = f.readlines() for l in lines: word = l.strip() if len(word) > 0: ...
aa304c23431c6c4a462fac21fbf96377dcdcafcf
37,641
def get_onto_class_by_node_type(ont: owlready2.namespace.Ontology, node_label: str): """Get an object corresponding to an ontology class given the node label. `owlready2` doesn't make it easy to dynamically retrieve ontology classes. This uses some (relatively unsafe) string manipulation to hack together a...
96274e02f2d75c5296b36d395374c7ceb087a87d
37,642
def get_transceiver_sub_id(ifindex): """ Returns sub OID for transceiver. Sub OID is calculated as folows: sub OID = MODULE_TYPE_PORT + ifindex * PORT_IFINDEX_MULTIPLE :param ifindex: interface index :return: sub OID of a port """ return (MODULE_TYPE_PORT + ifindex * PORT_IFINDEX_MULTIPLE, )
d4ed3fa64740e3bb744f1a912712000fc1593511
37,643
def create_conj_flows(port, conj_id, direction, ethertype): """Generate "accept" flows for a given conjunction ID.""" flow_template = { 'priority': 70, 'conj_id': conj_id, 'dl_type': ovsfw_consts.ethertype_to_dl_type_map[ethertype], # This reg_port matching is for delete_all_port...
5668b41b97991c09f576a90e6c0ad7eda6f48f90
37,644
def read_g_cas(in_name): """ Read a Gaussian .log file for CAS calculations Returns the total energy, and gradients for two states Parameters ---------- in_name : str Name of the file to read Returns ------- energy_e : float Gaussian total calculated energy in Hartr...
fb58cfb2973e63950f5ccd6688eb843f96cd393f
37,645
def query(primary_name, tables, where_clauses=None): """ Generates a MySQL SELECT statement to retrieve data. This function recursively walks the tree of foreign key relationships to build a query that joins all tables necessary to retrieve full data rows. :param primary_name: The name of the prima...
611a8a4d54fee8bfc5d5ca1143110a3cde6c8926
37,646
def cost2_lloyd_only_rref(p, et, resp): """ Cost function for rref with sum of squared deviations """ return np.sum((resp-lloyd_only_rref_p(et,p))**2)
e73a8f07d8924c662c18d934a2d9a37105ccf436
37,647
import re def add_locations(string, args): """ Adds location links to a snippet string """ string = string.replace(' ', ' ') locs = args[0] text = args[1] for loc in locs: pattern = re.compile(r'(?<!=)\b{0}[a-zA-Z-]*\b'.format(loc['location']), flags=re.I) for (match) in re.findal...
0dca0118e1bc3fae7c6ad5a7c7317f11b2bedb68
37,649
def should_transition(issue): """ Return a boolean indicating if the given issue should be transitioned automatically from "Needs Triage" to an open status. """ issue_key = issue["key"] issue_status = issue["fields"]["status"]["name"] project_key = issue["fields"]["project"]["key"] if is...
eeb9730a735e8c32349396e74adb84d6876d1a67
37,650
def _gaussian1d_no_bg_deriv(p, x): """ Required Arguments: p -- (m) [A,x0,FWHM] x -- (n) ndarray of coordinate positions Outputs: d_mat -- (3 x n) ndarray of derivative values at positions x """ x0 = p[1] FWHM = p[2] sigma = FWHM/gauss_width_fact dydx0 = _gaussian1d_no_bg...
62bbec50b82753288e41b0e871019d44371bfbf5
37,651
def extract_results(results, mode, limit=50): """extract result from json style list returned by download_results: parameters: results: json style - list with results mode: str- "ppa" for questions, "organic" for link of answers limit: int - max number of items per keyword Returns list of list...
64a9a159f5499295c3cb52239b0cdc49c0cd6ecd
37,652
def getSquareDistance(p1, p2): """ Square distance between two points """ dx = p1['x'] - p2['x'] dy = p1['y'] - p2['y'] return dx * dx + dy * dy
44e41632cd73b5c85b5206fc3af395e535062a14
37,653
import typing def is_owner(func: typing.Awaitable): """ Checks if the user is the owner. """ func.is_owner = True return func
6b5611100aee56401bad2f60cc48de4066c664eb
37,654
import tokenize def convert_examples_to_features(examples, max_seq_length, tokenizer): """Loads a data file into a list of `InputBatch`s.""" print("#examples", len(examples)) features = [[]] for (ex_index, example) in enumerate(examples): tokens_a, tokens_a_speaker_ids, tokens_a_mention_ids ...
c5492f5b21096065fad3c5aea95ba27b20a566d4
37,655
def generate_anatomical_volume_views(*actors, size=(600, 600)): """Generate anatomical (coronal anterior, sagittal right and axial superior) views of the actor(s). Arguments --------- actors : vtkActor Actor(s) to be displayed. size : Tuple (int, int) Size of each view. Ret...
153a71a109e158e9104db239b6186fa4f3d21a63
37,657
def getsize(datadescriptor): """Get the size of a data descriptor tuple.""" if datadescriptor[0] == 'reg': size = datadescriptor[1][2] elif datadescriptor[0] == 'mem': size = datadescriptor[1][1] elif datadescriptor[0] == 'heap': size = datadescriptor[1][2] elif datadescriptor[0] == 'perp': size = datade...
feaaa9d0698b58649a55c53ba399a46ba81520b6
37,658
def find_int_in_str(string=None): """ trouver les nombres entiers dans une chaine de caractere en ignorant les signes :param string: str :reutrn: ['float', 'float', ...] """ response = [] if string: # si la chaine n'est pas vide response = reg.findall("([0.0-9.9]+)", s...
6484ab52b0ed1431761649a57c331f8cbabdff46
37,659
import math def jzczhz_to_jzazbz(jzczhz): """JzCzhz to Jzazbz.""" jz, cz, hz = jzczhz hz = util.no_nan(hz) # If, for whatever reason (mainly direct user input), # if chroma is less than zero, clamp to zero. if cz < 0.0: cz = 0.0 return ( jz, cz * math.cos(math.ra...
2ff23a210fee9943128ea06ea8734ad6c3980e5c
37,660
def _encode_state_dict(state_dict): """Since dicts of (type, state_key) -> event_id cannot be serialized in JSON we need to convert them to a form that can. """ if state_dict is None: return None return [(etype, state_key, v) for (etype, state_key), v in iteritems(state_dict)]
c6ee240d5f0e48e376649f0bb127eef38355a4ed
37,661
import socket def cleanup_for_test(test_case): """ Return a ``Datera Client`and register a ``test_case`` cleanup callback to remove any volumes that are created during each test. :param test_case object """ config = datera_config_from_environment() datera = DateraBlockDeviceAPI( cl...
1c3b2bcc02343f96fde436dd523b9333dfe71d27
37,662
def IC_SSG(mode, **kwargs): """function to compute the information content of a simple graph pattern as proposed in SSG Args: mode (int): 1 if pw, kw, nw is provided 2 if supergraph G is provided along with a linst of nodes in subgraph WL 3 if a subgraph pattern ...
0762ac8a0674cbaca9e5eb7e89999ebd4348fcac
37,663
import random def crossover(parent1, parent2, d): """One point crossover Args: parent1 (int, (int, int)[])[]): chromosome of parent1 parent2 (int, (int, int)[])[]): chromosome of parent2 d (int): Total duration, in durks, of song Returns: ((int, int)[],(int, int)[...
bea05705b758e8e37dc637bec09566fda8978c6b
37,664
def _StringTraits_read_value_dataset(d, iss, sp): """_StringTraits_read_value_dataset(hid_t d, hid_t iss, hid_t sp) -> RMF::HDF5::StringTraits::Type""" return _RMF_HDF5._StringTraits_read_value_dataset(d, iss, sp)
2c37074ac3d661f147b41e25485b674e7897fffd
37,665
def argmaxIndexWithTies(l, f = lambda x: x): """ @param l: C{List} of items @param f: C{Procedure} that maps an item into a numeric score @returns: the index of C{l} that has the highest score """ best = []; bestScore = f(l[0]) for i in range(len(l)): xScore = f(l[i]) if xSco...
9d14ae30478c7e1e0fb429dc9fc75b92c2882b04
37,666
def get_j2k_parameters(codestream): """Return some of the JPEG 2000 component sample's parameters in `stream`. .. deprecated:: 1.2 Use :func:`~pydicom.pixel_data_handlers.utils.get_j2k_parameters` instead Parameters ---------- codestream : bytes The JPEG 2000 (ISO/IEC 1544...
722a84eadb6f381a531d09d3b6279b7775bca1d3
37,667
def derivative(tensor, shape, dist_metric=DistanceMetric.euclidean, with_normalize=True, alpha=1.0, time=0.0, speed=1.0): """ Extract a derivative from the given noise. .. image:: images/derived.jpg :width: 1024 :height: 256 :alt: Noisemaker example output (CC0) :param Tensor tens...
d3197c843db76ef81b1527eb85c603363cd1c362
37,669
import collections def backbone_lite(inputs, is_training): """mobilenetv2( deleted the global average pooling ) Args: inputs: a tensor with the shape (bs, h, w, c) is_training: indicate whether to train or test Return: all the end point. """ endPoints = collections.OrderedD...
7fb3632849d0b70bd075670f9a7d9d65c1e83352
37,670
def get_partition_from_arn(arn): """Given an ARN string, return the partition string. This is usually `aws` unless you are in C2S or AWS GovCloud.""" result = parse_arn(arn) return result["partition"]
3c723b19780b26be075c2b05e1f9b01cae115924
37,671
from typing import List from typing import Any def default_collate(batch: List[Any]) -> Any: """The :func:`flash.data.utilities.collate.default_collate` extends `torch.utils.data._utils.default_collate` to first extract any metadata from the samples in the batch (in the ``"metadata"`` key). The list of metada...
c9f979284e2d332f23bb0c6f70582324780a0831
37,673
def to_lowercase(word_list): """Convert all characters to lowercase from list of tokenized word_list Keyword arguments: word_list: list of words """ lowercase_word_list = [word.lower() for word in word_list] return lowercase_word_list
025e3edaa79723f8656d10a8d52fe16a402644ae
37,674
def T_from_R_t(R, t): """Combine rotation matrix and translation vec into a transform.""" t = t[..., None] o = np.zeros_like(R[..., -1:, :]) i = np.ones_like(t[..., -1:, :]) return np.concatenate( [np.concatenate([R, t], axis=-1), np.concatenate([o, i], axis=-1)], axis=-2 )
d56167fdbd90e2056c29d5a92289adb6261dbf9b
37,675
def x448(k, u): """ Perform point multiplication on X448 curve. :type k: bytearray :param k: random secret value (multiplier), should be 56 bytes long :type u: bytearray :param u: curve generator or the other party key share :rtype: bytearray """ bits = 448 k = decodeScalar448...
f579990de0e87c9dcb7e352608daaf399d72c218
37,676
def lesser_gf_ongrid(energy_grid, ret_gf, sigma_les): """ Lesser gf on grid """ lesser_gf = np.array([np.dot(np.dot(\ ret_gf[:, :, en], sigma_les[:, :, en]), ret_gf[:, :, en].T.conj())\ for en in range(len(energy_grid))]) lesser_gf = np.swapaxes(lesser_gf, 0, ...
5cde26dba44374dc48839dc398518b9ca18a7c6c
37,677
def getSpecies(head): """ Returns the species when the head is given. """ for species in toonSpeciesTypes: if (species == head[0]): return species
29f40899049274bbf7c70ce1b1455ec109c67482
37,678
from typing import Tuple def sinkhorn_knopp_iteration(cost: np.ndarray, p_s: np.ndarray = None, p_t: np.ndarray = None, a: np.ndarray = None, trans0: np.ndarray = None, beta: float = 1e-1, error_bound: float = 1e-3, max_iter: int =...
895e4a6f86e3e89391be0b139d782a1ff04bcbde
37,679
def get_data(): """It returns the x and y data points of the plot.""" return h.x, h.y
a81353dd83fa17810c9dce43454140f51a2936aa
37,681
def convert_to_score(label_name, label_dict): """Converts the classification into a [0-1] score. A value of 0 meaning non-toxic and 1 meaning toxic. """ if label_name=='non-toxic': return 1-label_dict[label_name] else: return label_dict[label_name]
608caf76f62a70d09e1592367daeb2ad3ebae248
37,682
import re def just_one_dot(text): """Some metrics can end up with multiple . characters. Replace with a single one""" rx = re.compile(r"\.+") return rx.sub(".", text)
331d77801d5c07d5165eb965b8e637f112344cbd
37,684
def get_config_file(*args): """Return specified args from `~/.plotly/.config`. as tuple. Returns all if no arguments are specified. Example: get_config_file('plotly_domain') """ if check_file_permissions(): ensure_local_plotly_files() # make sure what's there is OK return...
e4aa7cc431e122ebf4849e13121b847106bdf150
37,685
from typing import Iterable from re import T from typing import List def deterministic_sort(sequence: Iterable[T]) -> List[T]: """Private API that order a sequence of objects lexicographically (by :obj:`deterministic_name`), removing duplicates, which is needed for determinism. The main purpose of this f...
48498b222cfa6a44828d855df87535af45db9b9b
37,686
def iterations(solver: GromovWasserstein, prob: problems.QuadraticProblem) -> GWOutput: """A jittable Gromov-Wasserstein outer loop.""" def cond_fn(iteration, constants, state): solver = constants return solver.not_converged(state, iteration) def body_fn(iteration, constants, state, compu...
953a2899d9f226bc78e2c4b3fd69e0e071375d16
37,687
import re def _CheckFieldName(name): """Checks field name is not too long and matches field name pattern. Field name pattern: "[A-Za-z][A-Za-z0-9_]*". """ _ValidateString(name, 'name', _MAXIMUM_FIELD_NAME_LENGTH) if not re.match(_FIELD_NAME_PATTERN, name): raise ValueError('field name "%s" should match...
c304088a6f05560b839b47b4b6dcea2e64954536
37,688
def spawner_server(loop, aiohttp_server): """ Spawns backend services (emulates director) """ # uses mountpoint as a unique identifier registry = {} # registry[mountpoint] -> {info:{}, server:} async def list_infos(reg: web.Request): return web.json_response([v["info"] for v in re...
7c4060eb8a4a952764802acb2ab656922792118c
37,690
import pandas as pd import six def csv2df(csv_string): """http://stackoverflow.com/a/22605281""" return pd.read_csv(six.StringIO(csv_string),index_col=False)
2aeda7db7f36dac8fcec20e1f09a9299d362dfa6
37,691
def fidelity_KS_univariate(fcst, obsv, max_period, by_lead): """ Perform a Kolmogorov-Smirnov test on univariate data """ def _get_KS_statistic(fcst_ds, obsv_ds, by_lead=False): if by_lead: # Applied per lead_time within groupby stack_dim = [d for d in fcst_ds.dims if 'stacked_' ...
6c33d419cd9cbb09740c8ae0ed978c3e4f8123fd
37,692
def _generate_csv_header_line(*, header_names, header_prefix='', header=True, sep=',', newline='\n'): """ Helper function to generate a CSV header line depending on the combination of arguments provided. """ if isinstance(header, str): # user-provided header line header_line = header + newl...
b9a7f32404a432d2662c43f4fe6444241698bf37
37,693
def filter_labeled_genes(genes): """Filter genes which already have a label and return number of labels. Args: genes(dict): dictionary of genes {g_name: gene object} Returns: dict: dictionary of genes without label {g_name: gene object} int: number of distinct labels in the set of labele...
4d50580a07ad6825b4c28e7c91780f1964568056
37,694
def get_floss_params(str_floss_options, filename): """Helper routine to build the list of commandline parameters to pass to Floss.""" # First parameter is the name of the Floss "main" routine. list_floss_params = ['main'] # Add the options from app.config list_options = str_floss_options.split(",")...
e637c25d299c8217fef31b85a2610ec46e53d1f3
37,695
def noboot_roc_curve(X=None, y=None, y_score=None, model=None, fitMethod='', predictMethod='', alpha=0.05, method='score'): """Compute ROC curve with confidence intervals using score test and other methods, for the classification model. Code in powercalc.py has been checked against R binom package. "Score" was...
0f66f21960c1e7539a2d1789d32fa16befe8fd0e
37,696
def fma(x, y, z): """ fma(x, y, z) -> number Return the correctly rounded result of (x * y) + z. """ try: # XXX Optimise res, mpfr_x = _init_check_mpfr(x) res, mpfr_y = _init_check_mpfr(y) res, mpfr_z = _init_check_mpfr(z) gmp.mpfr_fma(res, mpfr_x, mpfr_y, mp...
3983245cea7169506bbf3adfcb3e6c14fb82bc03
37,697
def is_leap_year(year: int) -> bool: """Whether or not a given year is a leap year. If year is divisible by: +------+-----------------+------+ | 4 | 100 but not 400 | 400 | +======+=================+======+ | True | False | True | +------+-----------------+------+ Args: ...
e4cca9a2b9f0475aadc763fed679eee8b5dddc4a
37,699
def is_allowed_file(filename): """Check if a file extension is allowed. Args: filename (str): Name of the file to check. Returns: True if the file upload is allowed. """ return '.' in filename and \ filename.rsplit('.', 1)[1] in current_app.config['ALLOWED_EXTENSIONS']
db9368d48655bba85ea91e847cc5e1fd7a60c06e
37,700
def _build_distance_estimator(X, y, w2v, PoS, NER, regressor, verbose=1): """Build a vector reprensation of a pair of signatures.""" if w2v == 'glove': PairVecTransformer = PairGloveTransformer elif w2v == 'spacy': PairVecTransformer = PairSpacyVecTransformer elif w2v == 'polyglot': ...
475309904ced42479b197974b2e48dca6c200160
37,701
from typing import Optional from typing import Union from typing import List import logging import csv def n15hsqc(bmrb_ids: Optional[Union[str, List[str], int, List[int]]] = None, input_file_names: Optional[Union[str, List[str]]] = None, entry_objects: Optional[Union[pynmrstar.Entry, List[pyn...
1d66d698cade1c77195dcdd599cdcdbe00d2148b
37,703
def binary_prediction_results(y_true, y_pred): """ Returns a dictionary with counts of TP, TN, FP, and FN Args: y_true, y_pred (numpy-compatible, 1D array-like): binary valued objects holding the ground truth and predictions (respectively), on which validation has already been run. ...
583b161155dd0465918f9be6caadfc28cec4385b
37,704
from typing import Optional from typing import Sequence def SplitFMNIST(n_experiences: int, first_batch_with_half_classes: bool = False, return_task_id=False, seed: Optional[int] = None, fixed_class_order: Optional[Sequence[int]] = None, ...
ad0bc32448d80435fa31ab356689a18f48adb4da
37,705
from typing import Union from typing import Dict from typing import List def group_by(value, key: Union[str, int] = "", count=False, *, context) -> Dict[any, Union[List[any], int]]: """ Group the incoming values :param value: Incoming list :param key: The key to use in grouping the items. If no key, t...
b28ae115aec54e03202287dcc8f3119b562a7830
37,706
import html def create_index_page(): """ Dynamically create links for all app pages """ links = [] for page in pages: links.append(dcc.Link("Go to Page " + page, href="/pages/" + page)) links.append(html.Br()) return links
4a949ac7a0803d8c22ea1dc72a110617d50bc213
37,707