content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _l1m_objective(a,X,*args): """ Optimization objective for l1median """ return(np.sum(np.apply_along_axis(_euclidnorm,1,_diffmat_objective(a,X))))
6275dce7ac6a3810149ee2ef13346155fe50aa87
3,611,141
def _new_x_concatenated_sequence( duration=1.0, concatenation_order=None, pre_post_rotation=False, **kwargs ): """ Creates X-Concatenated Dynamic Decoupling Sequence. Concatenation of base sequence C(\tau/2)XC(\tau/2)X Parameters ---------- duration : float, optional defaults to Non...
77a4d639acd74e2e93ad956cb2afe4a03745821a
3,611,142
def addData2matrix(X_train: modALinput, X_new, X_idx, symmetrical) -> modALinput: """ Adds the new data to a sparse matrix Args: X_train: Training data in sparse format matrix X_new: Value of new data to be added to training set X_idx: Set of form (sparse_coordinate, row_idx, col_id...
6782a3d678ea6c752a128428a16def4300ff80a8
3,611,143
def load_people(path): """Loads a list of people from the path and assigns each default score.""" people = [] with open(path, 'r') as people_file: for line in people_file.readlines(): people.append(Person(line.strip())) return people
e48050594432ad1567633a81627469f092b02b38
3,611,144
import aiohttp async def test_set_audio(aresponses: ResponsesMockServer) -> None: """Test setting display properties.""" async def response_handler(request: aiohttp.ClientResponse) -> Response: """Response handler for this test.""" data = await request.json() assert data == { ...
ca7d0b5dee9fa366c4d51fc01f212984eff94e9f
3,611,145
import io def pathway_genes(pathway: str) -> set: """Returns genes for a given pathway in KEGG""" kgml = _get(pathway, form='kgml').text # Wrap text in a file handle for KGML parser f = io.StringIO(kgml) k = KGML_parser.read(f) genes = set() for gene in k.genes: for x in gene.nam...
2357ff501998711984362214183a4777e0afb806
3,611,146
def get_availability_domains(identity_client, compartment_id): """ Gets the list of AvailabilityDomain for the specified compartment. :param network_client: OCI VirtualNetworkClient client :type network_client: oci.core.VirtualNetworkClient :param compartment_id: The OCID of the compartment to che...
ac13aa820309fbc5a627d87c778b6e004d7def73
3,611,147
def method_authorizations(*scopes: str) -> dict: """ Return method security. Contains only one OAuth2 security. :param scopes: All scope names that should be available (as string). """ return {"security": [{"oauth2": scopes}]}
4bf2f93715b9798ef20119288178d69b3907e85e
3,611,149
def glGetProgramiv( baseOperation, program, pname, params=None ): """Will automatically allocate params if not provided""" if params is None: params = arrays.GLintArray.zeros( (1,)) baseOperation( program, pname, params ) return params[0] else: baseOperation( program,pname, p...
71c7a992e8eb84485c394c77caf29af780dc6d20
3,611,150
def get_aoi_dir(aoi_name): """get the result dir associated with the aoi name""" aoi_dir = result_dir.joinpath(aoi_name) aoi_dir.mkdir(exist_ok=True) return aoi_dir
21da45b9bf6dcabbae487a94127675dc8f43e311
3,611,151
def dhcpcap_maker(request): """ return a function which creates initialized dhcpcap instances. """ def maker(): dhcpcap = DHCPCAP(client_mac="00:01:02:03:04:05", iface='eth0', xid=900000000) return dhcpcap return maker
ca1e353cde2e684bf3151125ff188118fc0c1491
3,611,152
def validate(config_dir): """ Reads config.json in the config_dir and prepopulates with default values. Ensures that all configured values are of the appropriate types. Returns (config, message to report if error). Returns None if something is wrong with the config it read. """ config = rea...
496e7ad8b2b7c64ecf3d7b68b521ce048c3cb2f1
3,611,153
def _split(X: TData) -> XData: """Split dict into elements.""" Xcon = _make_mask(X["con"], X["con_mask"]) if "con" in X else None Xcat = _make_mask(X["cat"], X["cat_mask"]) if "cat" in X else None return XData(Xcon, Xcat, X["indices"], X["coords"])
459f0477776e343f59c0b45f5c7030f3facc5e31
3,611,154
def get_address(address): """ Request information about a bitcoin address :param str address: an address hash/id :return: an instance of Address class """ resource = f'address/{address}' response = util.call_api(resource) return Address(response)
dd6a1961954bccebcbb9b74d07d18973345ee4df
3,611,155
def loadRectilinearGrid(filename): """Load a ``vtkRectilinearGrid`` object from file.""" reader = vtk.vtkRectilinearGridReader() reader.SetFileName(filename) reader.Update() return reader.GetOutput()
48aaed3d50d24ee83450831cf9047bb89ca592be
3,611,156
def update_rule(request): """ Tags: rules --- Update a rule given its UUID The expected request body is the same as for the `add_rule` endpoint. The difference is that none of the parameters are required. Only the specified parameters will be updated, leaving the rest unchanged. READ p...
02aa4beb8234231a46242a07e0ffe6357c2ec966
3,611,157
def process_properties(adapter, params): """ Process the properties specified in the 'properties' module parameter, and return a dictionary (update_props) that contains the properties that can be updated. The input property values are compared with the existing resource property values and the retur...
5d802fa8f53a094ffad2d1226761c65a33b5404f
3,611,158
def horizontal_dominoes_removed(r, s): """ Returns all partitions obtained from a rectangle of width s and height r by removing horizontal dominoes. EXAMPLES:: sage: sage.combinat.crystals.kirillov_reshetikhin.horizontal_dominoes_removed(2,2) [[], [2], [2, 2]] sage: sage.combin...
e410c4c77399db5264fe464e98419eaf47a6dc89
3,611,159
def load_entities(geobase_file): """Returns list of GeoEntity tuples for geobase entities.""" # Identifier string to GeoEntity tuple. identifiers_to_entities = {} with gfile.GFile(geobase_file, "r") as inputfile: for line in inputfile: # line = line.decode("latin1") if line.startswith("state"):...
edf78d592893050a070e3662935c2ab7efe8cccc
3,611,160
from datetime import datetime def kurtosis(pos: TimeSeriesInterface, lookback: str, date: datetime = None, **kwargs) -> float: """ Compute the kurtosis of the returns distribution from a TimeSeries object :param pos: TimeSeries Object (Portfolio, Position, Pandas DataFrame/Series :param lookback: Str...
775d730a457fcfbda9f31f9648b3906cee7edc56
3,611,161
def session(dsn='postgres:///b2', echo=False): """SQLAlchemy session""" engine = create_engine(dsn, echo=echo) Session = sessionmaker(bind=engine) return Session()
09bbfb11e880345f435781ff261370f7d533df39
3,611,162
def _variable_on_cpu(name, shape, initializer, use_fp16=False): """Helper to create a Variable stored on CPU memory. Args: name: name of the variable shape: list of ints initializer: initializer for Variable Returns: Variable Tensor """ with tf.device('/cpu:0'): dtype = tf.float16 if use_f...
554e00c66d0854f04e82f302df9c3bfb9fa688dc
3,611,163
def get_db_uri(): """ Get the current DB URI. :return: The DB URI. """ global _db_uri if _db_uri is not None: return _db_uri elif env.get_env(_DB_URI_ENV_VAR) is not None: return env.get_env(_DB_URI_ENV_VAR) else: return DEFAULT_SUBMARINE_JDBC_URL
45bceb06d8d6fe7208b8476ddadbfec5e6da1282
3,611,164
import io import PIL def _open_file(full_path: str) -> tuple: """Read an image path, load the image and encoded in bytes""" with tf.io.gfile.GFile(full_path, 'rb') as fid: encoded_file = fid.read() encoded_file_io = io.BytesIO(encoded_file) image = PIL.Image.open(encoded_file_io) return im...
7f1e60a9973a4f7184189e5cf0453efc884fd865
3,611,166
def full2sparse_clipped(vec, topn, eps=1e-9): """Like :func:`~gensim.matutils.full2sparse`, but only return the `topn` elements of the greatest magnitude (abs). Parameters ---------- vec : numpy.ndarray Input dense vector topn : int Number of greatest (abs) elements that will be pre...
a5b2c526839e6cde73ad2380cf9bef438664e2eb
3,611,167
import copy def _open(input_op_node: cc_dag.OpNode, output_name: str, target_party: int): """ Define Open operation. :param input_op_node: Parent node for the node returned by this method. :param output_name: Name of returned Open node. :param target_party: ID of party that will receive outputs o...
199cb47822e6891b1421baa20d93d779cdf55d9e
3,611,169
def loss(z, y, loss_function, isbinary=None): """ Calculates the loss given the loss function used. Parameters ---------- z : ndarray Array containing logits. y : ndArray Array containing labels. loss_function : str Name of loss function. isbinary : bool ...
ee92e1a9e426155aba8f36d37f1149c08730902d
3,611,170
def file_to_save(_x): """Definition of argument type for learner save data file, a string with a pathname of a file.""" return _x
e67821fa7a273d41f5a69c0577b3e9ace0955e20
3,611,171
def mmd_x_xsqred(x, y): """ Maximum mean discrepancy with squared kernel This will distinguish mean and variance see https://stats.stackexchange.com/questions/276497/maximum-mean-discrepancy-distance-distribution Parameters ---------- x : list of ints y : list of ints Returns ---...
be182455ee471b085acdf3a57de87f383d5f38a1
3,611,172
def deltas_to_dfs(deltas): """Transform deltas to displacement fields. Parameters ---------- deltas : np.ndarray The array with deltas. Has to have shape (n_dfs, 2, height, width). Returns ------- dfs : list The resulting displacement fields. """ dfs = [Displacement...
3b6600539994744da7ac818240fb1afd05ace09b
3,611,173
def vector_tile(vec, reps: int): """Turn a 1d vector into a 2d matrix by tiling on the leading dimension. Casadi represents vectors as D x 1 array, so needs to be treated differently. For casadi: [D x 1 ] vector -> [N x D] array For numpy/jax: [D, ] vector -> [N x D] array """ if lnp.get_back...
495afeacfff013f9bce361015053f03e5f19089d
3,611,176
import requests import json def list_tags(image, cli=False): """ Return a list of tags of a given Docker Hub image. Example: In : list_tags('google/debian') Out: ['jessie', 'wheezy'] In : list_tags('python') Out: ['31', 'rawhide', '30', '29', 'latest' ...] """ if cli: prin...
aefa058e32b72911a0b97619edeee119914440b7
3,611,177
import warnings from datetime import datetime from pathlib import Path def mt_metrics( stack, out_prefix, metrics, rescale_to_datatype, to_power, outlier_removal, datelist ): """ :param stack: :param out_prefix: :param metrics: :param rescale_to_datatype: :param to_power: ...
26063461aaa0c824330ae5aba6378b55e4c5de37
3,611,179
def create_blank(width, height, rgb_color=(0, 0, 0)): """Create new image(numpy array) filled with certain color in RGB ref: https://stackoverflow.com/questions/4337902/how-to-fill-opencv-image-with-one-solid-color author: Kimmo usage: import cv2 import numpy as np ...
50655136d34ccaea35cda35a2b28324dcad9a9d6
3,611,181
def mutate(proposed_graphs, graphs, part_importance_estimator=None, feasibility_estimator=None): """mutate.""" mutated_proposed_graphs = [] mutated_proposed_graphs += perturb( proposed_graphs, NeighborhoodNodeLabelMutation(n_nodes=None).fit(graphs), part_importance_estimator, ...
1e929b35f862cc489f97f14685360f89d2806194
3,611,182
def get_slurm_script_gpu(output_dir, command): """Returns contents of SLURM script for a gpu job.""" return """#!/bin/bash #SBATCH -N 1 #SBATCH --ntasks-per-node=1 #SBATCH --ntasks-per-socket=1 #SBATCH --gres=gpu:tesla_p100:1 #SBATCH --cpus-per-task=4 #SBATCH --mem=64000 #SBATCH --output={}/slurm_%j.out #SBATCH...
3f9d587c2943cd821d000fab419d3591440c4d3d
3,611,183
def tensor_extend(x, y): """Extending tensor with new_slice. new_slice.shape should be same as tensor.shape[1:] Args: x (Tensor): tensor to be extended y (Tensor): the tensor which will be appended to `x` Returns: the extended tensor. Its shape is (x.shape[0]+1, x.shape[1:]) ...
df0a3c3ab9aa636621783907e3ef1bdccf3fd79a
3,611,184
def boxSnap(n, shape, usegrid=False, randomness=0.): """ Initialize snap shot with n randomly placed gas particles inside a box. if usegrid=True, a grid is used to seed the particle positions (see grid()) n can then be [nx, ny, nz, ...] to specify the resolution along each dimension. Otherwise...
cc430d7d110b7efbb1a9bc735a77b749205811a3
3,611,186
def strobe_color(brightness=100): """ Rapid flashing colors. :param int brightness: The brightness of the transition. :returns: An infinite Flow consisting of 6 transitions. :rtype: Flow """ return Flow( count=0, action=Action.recover, transitions=transitions.strobe_color(brightnes...
e666e53713a3a6e32503e00eb9f0ffa9500399d8
3,611,188
import uuid import six def create_uuid3(namespace, name): """ Return new UUID based on a hash of a UUID namespace and a string. :param namespace: The namespace :param name: The string :type namespace: uuid.UUID :type name: six.text :return: :rtype: uuid.UUID """ return uuid.uui...
1a6898f80849a11f643a58798adc8a165e3b0e8d
3,611,189
def build_roi_extractor(cfg): """Build RoI feature extractor.""" if cfg['type'] in NECKS._module_dict.keys(): return ROI_EXTRACTORS.build(cfg) else: return MMDET_ROI_EXTRACTORS.build(cfg)
9ad5d7edc1395cc702beb00091ae8aec782ed716
3,611,191
import time def deterministic(pred, obs, forecast_type="continuous", aggregating_dim=None, skip_na=True, thr=0.000001): """Compute deterministic skill metrics.""" # Check if not isinstance(forecast_type, str): raise TypeErr...
b95c85624429f60990e784d8656a0214f8c0c501
3,611,192
def asy_add_ucb_for_boca(mfgp, fidel_to_opt, anc_data): """ Asynchronous Add UCB. """ return _add_ucb_for_boca(mfgp, fidel_to_opt, None, anc_data)
def0e7dcf50ac660573e2645afb17490711b43e3
3,611,193
def patch_twitter_add_list_users(value): """Return a function decorator which patches the TwitterClient.add_users_to_list method.""" return patch_twitter_client_method("add_users_to_list", value)
fab0da1bc2e682d3e7bb3a3c6b031b255983de21
3,611,194
def sbol_ribozyme (ax, type, num, start, end, prev_end, scale, linewidth, opts): """ Built-in SBOL ribozyme renderer. """ return stick_figure(ax,type,num,start,end,prev_end,scale,linewidth,opts)
b391524534ee7ced11cf536090a8f88cadc5eefa
3,611,195
def buildTypeTree(cls:type) -> dict: """ Return a tree of subclasses of a class Arguments: cls (type): Class from which to return descendants Returns: dict: Dict of all subclasses Example: buildTypeTree(MainClass) returns: { MainClass.SubClass1: { MainClass.SubClass1.SubClass11: {}, MainC...
7937df4d9643f20c3e5379f84ef36a28226707ba
3,611,197
def add_at(a, indices, b): """Add the elements of `b` to the locations in `a` specified by `indices`. Allows adding to an element of `a` repeatedly. """ value = a.array.copy() np_add_at(value, indices, b.array) local_gradients = [ (a, lambda path_value: path_value), (b, lambda pa...
46246ddca7e9ed2b6c7d7d5d1c5d4d1550c8c13d
3,611,198
def judge(sample, w, c_1, c_2): """ true 属于1 false 属于2 :param sample: :param w: :param center_1: :param center_2: :return: """ u1 = np.mean(c_1, axis=0) u2 = np.mean(c_2, axis=0) center_1 = np.dot(w.T, u1) center_2 = np.dot(w.T, u2) pos = np.dot(w.T, sample) r...
49d5d65055874a2600fcc449d696de6021265a1b
3,611,201
def get(myobject, query, default=None): """This function allows you to query a dict object to get the value recursively through dicts and array's, returning the value found at the end of the query chain. Arguments: myobject {object} -- dictionary or array of objects query {str} -- query...
bb27d6420a392d939cbc8dd46d23f050094603b6
3,611,202
def QueueMark(*args): """QueueMark(qtype_t type, ea_t ea)""" return _idaapi.QueueMark(*args)
3dd12653a6a0a65d7c0b791e37c8c60e40b3ea29
3,611,203
def maya_main_window(): """ Get Maya main window :return: int (maya main ptr) """ maya_main_ptr = omUi.MQtUtil.mainWindow() return wrapInstance(int(maya_main_ptr), QtWidgets.QWidget)
96ccc1f82b5ee48f048cba66c95fcc42abe7fd14
3,611,205
import click def _cb_key_val(ctx, param, value): """ Click callback to validate and convert `--opt key=val --opt key2=val2` to `{'key': 'val', 'key2': 'val2'}`. Returns ------- dict """ output = {} for pair in value: if '=' not in pair: raise click.BadParamet...
b74dea54c8e57e8c6ebbd743401f45ba57bff03b
3,611,206
def short_map(file, size=96, valid=True): """Returns a dataframe from a 'short' plate map csv file that defines each and every well from a well plate of defined size Contains the columns 'Well ID', 'Compound', 'Protein', 'Concentration', 'Concentration Units', 'Contents', 'Type' and 'Valid'. Each defined w...
72f614f616dbfc7759624908db37addbcd70fb69
3,611,207
import numpy def epsfunc(x_, y_): """Return a matrix describing a 2d material. :param x_: x values :param y_: y values :return: 2d-matrix """ # xx, yy = numpy.meshgrid(x_, y_) working = geom[0][5] * numpy.ones((x_.size, y_.size)) for i in range(1, len(geom)): ixmin = numpy.sea...
549a27b8b1186b3bb42aaf7d9d893ffc9696c75c
3,611,208
def create_referral(request): """Create a referral.""" email = request.POST.get("email", "missing email") data = {"email": email, "referring_user": request.user} form = ReferralForm(data=data) if form.is_valid(): form.save() messages.success(request, "We will message your friend shor...
df66efca2f2603e9987535efbcc34ae5041cca7b
3,611,209
def fetch_reg(reg_dict, reg, index, data, use_init): """ Fetches register from state global store. Initialises it if needed. """ if reg in reg_dict: d = reg_dict[reg] if is_reg_indexed(data): if index in d.keys(): return d[index] #else: ...
35ca7f40686fc8f101fee4c9ba655b23733f1fff
3,611,210
def first_day_of_last_month(any_date): """Returns the first day of last month for any date >>> first_day_of_last_month(datetime.date(2016, 1, 21)) datetime.date(2015, 12, 1) """ return first_day_of_the_month(last_day_of_last_month(any_date))
af438cac1e67889d885952f3e07f8b8022849134
3,611,211
import hashlib def digest_file(file_path: PathLike, hash_algo: str) -> str: """ Reads and digests a file according to specified hashing-algorith. :param file_path: path to a file on disk :param hash_algo: any algo contained in :mod:`hashlib` :return: <hash_algo>=<hex_digest> From http://stac...
121fcbe81c8c690a011adff9a0502879b5a4855e
3,611,212
from typing import List def _parse_nodes(text: str) -> List[Node]: """ Quick and dirty implementation of a .rst parser to extract directives """ nodes = [] c_indent = "" in_section = [] directive = "" last_directive = "" args = "" last_args = "" text_split = text.split("\n...
2f0167ccf6aff4009e65d63a3a53314d354052a6
3,611,213
from typing import List from typing import Union from typing import Tuple def executeColorToken(token: lexerTokens.toColorToken, inputDirection: direction, dataStack: List[int]) -> Union[Tuple[direction, List[int]], BaseException]: """ Executes the to color operations :param token: input token :param ...
fa6687b81ab18862f7dce34f1aa5fddca81d77e0
3,611,214
import re def rfc822_parse(message): """Parse a message in RFC822 format. @param message: The message in RFC822 format. Either CRLF or LF is an accepted line separator. @return Returns a tuple of (headers, body) where headers is a list of (name, value) pairs. The body is a CRLF-separated string. ...
a9fba803ca428c96fd98af20c3015479dae77645
3,611,215
def get_all_users(**options): """Returns all users. Args: **options: Options passed to query. Returns: A list of user dictionaries. """ cursor = _db.users.find( {}, sort=[('create_time', pymongo.ASCENDING)], **options) return list(cursor)
385dfb58c231b84adbe00d2fb0db7a50a3e987b1
3,611,216
def handle_exception(e): """ To keep all responses consistently JSON. Return JSON instead of HTML for HTTP errors. """ return ( jsonify( { "code": e.code, "name": e.name, "description": e.description, } ), ...
5bd5cd8877878ec5c591ce8a553d1a9f652ee1d2
3,611,218
import requests def _create_download_failed_message(exception, url): """ Creates message describing why download has failed :param exception: Exception raised during download :type exception: Exception :param url: An URL from where download was attempted :type url: str :return: Error message ...
2ff2493cc1167246083ef703bdff8c76cb36a733
3,611,219
import json def read_mongo(db, collection, query={}, projection='', limit=1000, host='localhost', port=27017, username=None, password=None, no_id=False): """ Read from Mongo and Store into DataFrame """ # Connect to MongoDB db = _connect_mongo(host=host, port=port, username=username, password=password, d...
9b49f40de1eb49eece981d01d2fb5d41788ff029
3,611,220
def buffer_with_count(this, count): """ """ if count < 0: raise FatalError q = [ [] ] num_seen = [0] def on_next(self, x): num_seen[0] += 1 q[0].append(x) if num_seen[0] == count: self._dispatch_next(q[0]) num_seen[0] = 0 q[0]...
2d2760b9a9223db04fe33da6442c380f6d6a23b3
3,611,221
def _apply_hadamard_to_all_qubits(s, optype, qubit_labels): """ Applies Hadamard gates to all qubits Parameters ---------- s : np.array A (2n,2n) matrix over [0,1]. optype : 'row' or 'column' If 'row', we use row-operation Hadamard gates. If 'column', we use column-oper...
5a62d48dc115d903fd6580c1052d44771649ddae
3,611,222
def create_empty_dataset(shape, h5_group, name='nDIM_Data'): """ returns a h5py.Dataset filled with zeros according to required shape list. Parameters ---------- shape: list List of integers denoting the shape of the main dataset h5_group: h5py.Group HDF5 group into which the da...
ccd773b91b0144be8be1f0040d4a4e206b489b50
3,611,223
def smooth_l1(weight=1.0, sigma=3.0): """ Create a smooth L1 loss functor. Args sigma: This argument defines the point where the loss changes from L2 to L1. Returns A functor for computing the smooth L1 loss given target data and predicted data. """ sigma_squared = sigma ** 2 ...
af5c09eba3f7139cead43b1e1f23e2ee253dd82c
3,611,224
import re def encode_laTex(text): """ :param text: :return: """ if (len(text) > 1): # if any greek letter macro map it here # convert something like \\Sigma\\ to \textbackslash{}Sigma\textbackslash{} # however needs to go through utf8tolatex so add placeholder to be replac...
093be21fe9cbdd62cfc7396a78632492f9212d0f
3,611,225
def LF_DG_BICLUSTER_PROGRESSION(c): """ This label function uses the bicluster data located in the A global network of biomedical relationships """ sen_pos = c.get_parent().position pubmed_id = c.get_parent().document.name query = bicluster_dep_df.query("pubmed_id==@pubmed_id&sentence_num==...
1b0847001d888b5954385759ab513e5cedb6341f
3,611,226
def gap2d(): """Helper for building a global average pooling layer.""" return nn.AdaptiveAvgPool2d((1, 1))
f8bde4a603e36361ffb4541caeaadf7b95428bc7
3,611,227
def find_(a,n=None,d=None,nargout=1): """ function which returns a column vector or a tuple of column vectors (depending on the value of nargout) containing indices where a[indices] are true in the vector/matrix 'a' Argument 'n' tells us how many of those indices we want """ if d: r...
7c9a844d454a1a1392b8e170b6b7ec9032c3cabf
3,611,228
def __covid_brief() -> str: """ Generates a brief message about the latest covid19 data. """ try: ( is_latest_covid_data_available, _, new_cases, cumulative_cases, new_deaths, cumulative_deaths, ) = fetch_covid_data...
4500dced365697617d13ec24afbd835845a5f9b2
3,611,229
def correct_for_absorption(flux, ebv, band): """Corrects for MW dust absorption. Keyword arguments: flux -- Python list containing fluxes. ebv -- float, MW E(B-V). band -- photometric band in which correction has to be applied. Returns: Python list containing values of flux corrected by ab...
b6833eaa4211a319dfffe3fde26122437ce48ed0
3,611,230
def flag_bad_words(transcriptions): """ :params transcriptions:transcriptions is the dictionary containing the text file that has been converted into an array :return: updated transcriptions dictionary This function checks to see if any words have been added to the flagged_list. """ if any(flag...
bd167612055ec872dcc67810ae3823c25b6f686b
3,611,231
from typing import Dict def update(id_: int, type_: str, object_: Dict[str,str], session: scoped_session, api_name:str) -> int: """Update an object properties based on the given object [PUT].""" # Keep the object as fail safe instance = get(id_=id_, type_=type_, session=session, api_name=api_name) ins...
7ace29574136b20932b0ed9196a7e68ef9c6323a
3,611,232
def method_resolve_vessel(cookie, in_stimuli): """ Auto-generated UCS XML API Method. """ method = ExternalMethod("MethodResolveVessel") method.cookie = cookie method.in_stimuli = in_stimuli xml_request = method.to_xml(option=WriteXmlOption.DIRTY) return xml_request
a5b64728fdac06e7b4653cb4d8f466d32f73be51
3,611,233
def get_month(): """Fetch the value of month entered by user""" # Creating a single item list for appending to global list of months all_filter = ['all'] while True: # Get user input for month (all, january, february, ... , june) month = str(input('\nSelect the month - january, febr...
e08913007642803c5fd2b6b4f4ca3332bffdedd2
3,611,234
def ZA( particle ) : """ Uses ZAInfo to compute the particle ZA. See ZAInfo for more detail """ return( ZAInfo( particle )[2] )
a96be9a671fee5b9d50b1d8477c66fbbbc230f0e
3,611,235
def get_category(category_id: TicketCategoryID) -> TicketCategory: """Return the category with that ID, or raise an exception not found.""" category = find_category(category_id) if category is None: raise ValueError(f'Unknown ticket category ID "{category_id}"') return category
f5c1462cd353c8c5112e59509096f2f7617642cc
3,611,236
from typing import Optional from typing import Dict def abbreviated_interface_name( interface: str, addl_name_map: Optional[Dict[str, str]] = None, addl_reverse_map: Optional[Dict[str, str]] = None, ) -> str: """Function to return an abbreviated representation of the interface name. :param interf...
f711d4dfef1e4e435e172dd535366c61ede99735
3,611,238
def edits1(word): """ Produces a list of all possible edits of a given word that can be produced by applying a single character modification. From Peter Norvig, see http://norvig.com/spell-correct.html. """ letters = 'abcdefghijklmnopqrstuvwxyz' splits = [(word[:i], word[i:]) for ...
9ccab14554fe1d945d5da848376bd18bcbf25ed2
3,611,239
def highway(input_, size, num_layers=1,scope='Highway'): """Highway Network (cf. http://arxiv.org/abs/1505.00387). t = sigmoid(Wy + b) z = t * g(Wy + b) + (1 - t) * y where g is nonlinearity, t is transform gate, and (1 - t) is carry gate. """ # return linear(input_, size) with tf.variabl...
597c3d3f569882992f027fa69ebf76c4ad19eb07
3,611,240
def lst_mp_equality(lst1, lst2): """Wrapper function to check if two lists are identical when the lists contain MeasurementProcess objects.""" assert len(lst1) == len(lst2) lsts_same = True for index in range(len(lst1)): if not isinstance(lst1[index], type(lst2[index])): # if they are diff...
747262632f6981f47a32bc2f0ad6fcd99d763cc7
3,611,241
def asv_uncertain(unc, apf, fm): """Load Maribot Vane performance data.""" perf = np.genfromtxt(pyroute_path+"analysis/asv_transat/maribot_vane.csv", delimiter=",") tws = np.array([0, 4, 8, 12, 16, 20]) twa = np.array([0, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160]) return ...
a197ee2808e55767145ea6f396165e305d2bb71f
3,611,242
def flow_resize(flow, out_size, is_scale=True, method=0): """ method: 0 mean bilinear, 1 means nearest, 2 bicubic and 3 area See: https://www.tensorflow.org/api_docs/python/tf/image/ResizeMethod """ flow_size = tf.to_float(tf.shape(flow)[-3:-1]) flow = tf.image.resize_images(flow, out_si...
c720aacfe926a8897e0a87c14fae71581017791c
3,611,243
def center_crop(img, dim): """Returns center cropped image Args:Image Scaling img: image to be center cropped dim: dimensions (width, height) to be cropped from center """ width, height = img.shape[1], img.shape[0] # process crop width and height for max available dimension crop_width =...
b5e54550d9774f999a3b94dabde95fd12b2aaa8f
3,611,244
import math def ae_latent_softmax(latents_pred, latents_discrete, hparams): """Latent prediction and loss.""" vocab_size = hparams.v_size if hparams.bottleneck_kind == "semhash": vocab_size = 2**hparams.z_size if hparams.num_decode_blocks < 2: latents_logits = tf.layers.dense(latents_pred, vocab_size,...
b43512063ed58d214e3c4637288d079a64e26235
3,611,245
async def convSingleLottieTransparentFrames( lottieFile: LottieFile, frameSkip: int = 0, scale: float = 1, ) -> dict[str, LottieFrames]: """Convert a single lottie file to a dictionary of LottieFile.path to LottieFrames (LottieFile.data and a list of PIL.Image.Image frames) with transparency. Args: lottieFile...
6b9cbd68d529f609d6681240b071367baf6b8db9
3,611,248
def _unit_variance_scale(f: np.ndarray) -> np.ndarray: """Rescales a feature to have a unit variance.""" f_nan_max = np.nanmax(f) f_nan_min = np.nanmin(f) if np.isnan(f_nan_max) or np.isnan(f_nan_min): raise ValueError('Continuous feature all missing.') if f_nan_max == f_nan_min: ret = np.full_like(f,...
02a3ea26936e385910eff0d39926cc6370e17966
3,611,249
def get_champions_name(_id): """ this functions takes an _id and returns the associate champions name :param _id: any integer from 1 to 555. if there is a champion, it will return the name. :return: champions name """ all_champion_id = { 1: "Annie", 2: "Olaf", 3: "Galio",...
4e062bca3636a261df1d17d77417fc19f5d89305
3,611,250
def get_resources_grouped_by_domain(tech): """ Given a tech slug, this function will return all the resources for that tech grouped by domains i/p: 'python' """ return_data = {} all_resources = Resources.objects.filter(technology__slug=tech) for resource in all_resources: domains...
eb57410ccf99d414811863577cdc7427893aa702
3,611,251
def babel_fish_dispenser(matrix1, matrix2=None, step_size=None, axis=2): """Adds an input corresponding to the running average over a set number of time steps. This helps the neural network to ignore high frequency noise by passing in a uniform 1-D filter and stacking the arrays. Parameters ---------- ...
8afe5425a9a0bde13dd874359e20ffd2faeaa21b
3,611,252
def isAVersionableResource(obj): """ True if an object is versionable. To qualify, the object must be persistent (have its own db record), and must not have an true attribute named '__non_versionable__'.""" if getattr(obj, '__non_versionable__', 0): return 0 return hasattr(obj, '_p_oid')
42dcd02b1f4e1c9f9ff555ec597d8011cfe64893
3,611,253
def fix_variable(problem, pivot, value): """ Return a new problem that is a copy of the one provided with the pivot variable set to value This function is used for branching, and prints the selection made. """ new_problem = problem.copy() new_problem['variables'] = problem['variables']....
40e7d358eff405c481aedd9d2b1505664fcd4d6e
3,611,254
def test_progress(arg1, arg2, kwd1, kwd2, progress): """Simple test target for submit_progress.""" return arg1, arg2, kwd1, kwd2
1d761c572b15c41e1a04aafbb53ca825792df8fe
3,611,255
import asyncio async def stick_maker_static_phlogo( text: str, image_file: Image.Image, font_path: str, image_wight: int, image_height: int) -> Image.Image: """ ph表情包模板 """ def __handle() -> Image.Image: # 处理文本主体 test_sentences = text.strip().split(maxsplit=1) white_tex...
eff35b2eccf15f6a381c99fcaf1437bf550d017f
3,611,256
def transform_dict_to_kv_list(options): """ {"key": None, "key2": None} becomes 'key, key2' {"key": "\"\"", "key2": "3.5in", tocbibind: None} becomes 'key="", key2=3.5in, tocbibind' """ assert isinstance(options, dict) return ", ".join(["{}={}".format(k,v) if v is not None else k for k,v in opti...
571b3d5724b7aa0ff53698349a3255b14517bd78
3,611,257
import numpy def Mat(m,n): """ Build an m x n matrix (using numpy) For example: >>> Mat(2,3) array([[ 0., 0., 0.], [ 0., 0., 0.]]) """ return numpy.zeros((m,n),'d')
e36164cd29ed0070a01b87ca32e6f130271dbb95
3,611,258