content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def as_singleton_instance(cls): """ This is where the magic happens. This defines a class decorator that returns an *instance* of a class with the name "_<original_name>__class" that has the same member functions, etc as the cls argument. The type of the returned value is not accessible to the ...
3fc00dbfb24cd87401214806ddd93ff2ba15be50
3,623,200
def set_size(width, fraction=1, subplots=(1, 1)): """ Set figure dimensions to avoid scaling in LaTeX. Parameters ---------- width: float or string Document width in points, or string of predined document type fraction: float, optional Fraction of the width which you wish th...
2cbc82e17baceffcb81249d5dde99b6e10c4afa9
3,623,201
import argparse def parse_options(): """Parses command line options and returns an option dictionary.""" options = {} parser = argparse.ArgumentParser( description='Recursively apply Review Board reviews' ' and GitHub pull requests.') parser.add_argument('-d', '--dry-run'...
6d35277fe508ef43e4631904f5b07d2cc5b947fd
3,623,202
def create_keras_model(): """ create model """ model = Sequential() model.add(Conv1D(500, input_shape=(1280, 1), kernel_size=128, strides=128, activation='relu', padding='same')) model.add(De...
043b3db24bb4b24932d1fad50acc72f9354a154d
3,623,203
def ndgrid(*args,**kwargs): """ Same as calling meshgrid with indexing='ij' (see meshgrid for documentation). """ kwargs['indexing'] = 'ij' return meshgrid(*args,**kwargs)
342530125f045d36a7c49baff72904ed90877452
3,623,204
def _wass_gen_loss_fn(gen_images, discriminator: tf.keras.Model, generator: tf.keras.Model): """Calculate the Wasserstein (generator) loss.""" disc_gen_output = discriminator( gen_images, training=TRAINING_KWARG_FOR_SECOND_MODEL) gen_loss = tf.reduce_mean(-disc_gen_output) # Now add...
caaacb970476a38364ffc9e1b82566c6cda1481a
3,623,205
from typing import List def _get_create_repo(request) -> List[str]: """ Retrieves the list of all GIT repositories to be created. Args: request: The pytest requests object from which to retrieve the marks. Returns: The list of GIT repositories to be created. """ names = request.confi...
4ac8cefefb75af3bb86fcc16f5c8b79953b136bf
3,623,206
def read_in_posterior(date): """ read in samples from posterior from inference """ df = pd.read_hdf("results/soc_mob_posterior"+date+".h5", key='samples') return df
f5754628f17de8629e3d197a73645e6fa541722b
3,623,207
def wrap_dtype(func): """ Check the dtype of the `X` array. Convert dtype of X to np.float64 before to pass to cython function and convert to specified dtype at the end. """ @wraps(func) def check_dtype(X, *args, dtype=None, **kwargs): X, dtype = _check_dtype(X, dtype) if dtyp...
2ace06e7f6447e71d3b7f586fde1cf853400d4d1
3,623,208
def dirdiff(HEADING,Nmin,loffset): """ Function to calculate the maximum difference of a [0, 360) direction during specified time averging intervals :param HEADING: time series of a direction in degrees [0, 360) :param Nmin: integer specifying the number of minutes to average ...
e552018dbdfc0dd83f9ac5e25116a9144133d9fc
3,623,209
def update_outputs(region, resource_type, name, outputs): """ update outputs with appropriate results """ element = { "op": "remove", "path": "/%s/%s" % (resource_type, name) } outputs[region].append(element) return outputs
97858e5d183af9974bd31be180dfe05c26048ab3
3,623,210
def generate_inputs_1d_spherical(): """Return inputs that parser will expect for the 1D case with spherical averaging.""" inputs = { 'parent_folder': orm.FolderData().store(), 'parameters': orm.Dict( dict={ 'INPUTPP': { 'plot_num':...
633fb78031eaeaf0067479d5aa600ed8fd462f90
3,623,211
def _check_electrification_scenarios_for_download(es): """Checks the electrification scenarios input to :py:func:`download_demand_data` and :py:func:`download_flexibility_data`. :param set/list es: The input electrification scenarios that will be checked. Can be any of: *'Reference'*, *'Medium'*, *...
ccd1ec8f0b1349267ba1334f7744056bc43e32ec
3,623,212
from typing import Sequence from typing import List def bubble_sort(nums: Sequence) -> List: """Sort a list in non-descending order using bubble sort. Return a new list, leaving the original `nums` intact. """ # Bubble sort compares each element with the next element, and if the previous one ...
0cc60f00fd7fb55098e34745e3bad76be7fcdf5f
3,623,213
def image_to_byte_array(image: Image): """ Converts an image into a byte array """ imgByteArr = BytesIO() image.save(imgByteArr, format=image.format if image.format else 'JPEG') imgByteArr = imgByteArr.getvalue() return imgByteArr
82e6413978ee07d1d2cd434e144c1f1732133dab
3,623,214
import logging def crawling_tweet(): """ Twitter APIを利用して対象ユーザーのツイートを収集する 収集したツイートはGoogle Cloud Text to Speech APIへ連携し、 音声読み上げデータとしてmp3に変換し、保存する :return: """ auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tw...
008bf8a4c08cdce18c1fbea0dc053b8e5a974025
3,623,215
from typing import Optional def is_subject_condition_dataframe( data: SubjectConditionDataFrame, raise_exception: Optional[bool] = True ) -> Optional[bool]: """Check whether dataframe is a :obj:`~biopsykit.utils.datatype_helper.SubjectConditionDataFrame`. Parameters ---------- data : :class:`~pan...
993065496e7fff951986fd2141af7a222060433b
3,623,216
def _update_earned_request(player_id, achievement_id, current_value, max_value): """ Create the DynamoDB update_item parameter request to update earned attribute """ now = ddb.timestamp() return { 'Key': { 'player_id': player_id, 'achievement_id': achievement_id ...
f9c1cd62f537bcd6841ee33d59645fba976c82f9
3,623,217
def mosaic(*rasters): """ Mosaic rasters covering different areas together into one file. Parts of the rasters may overlap each other, in which case we use the value from the last listed raster (the "last" overlap rule). """ # align all rasters, ie resampling to the same dimensions as the first...
fd43edbafc4173129614dcc8ced6aa01390f0d3a
3,623,218
def typing_loop(options, add, atom_type_dict): """ types atoms in ambiguous cases, options should be ordered correctly """ ty = None for option in options: try: ty = atom_type_dict[add + option] break except KeyError: continue if ty !=...
5198375c775cdbf1819998dca4d7c05287ba273d
3,623,219
def enable_func_trace(*args): """ enable_func_trace(enable=True) -> bool """ return _ida_dbg.enable_func_trace(*args)
f2e9944f9651c56ab19fa1b444395d5ccf0df036
3,623,220
def get_exp_or_package_from_repo_name(repo_name): """Helper function to retrieve experiment or InternalPackage DB object based on repository name Useful for tasks that do not have a session or other information""" git_repo = GitRepository.objects.filter(name=repo_name) if git_repo: git_repo = gi...
32403e7b223e55583959e0cd0be556e476be591a
3,623,221
import re def text_to_pronounceable_text(text, symbols_for_base_idx=vowels_and_consonants, captured_alphabet=alpha_numerics, case_sensitive=False, max_word_length=30, ...
d7f60bfc784975b166793edc1e8baee09036c5db
3,623,222
def is_shuffle(s1, s2, s3): """ Runtime: O(n) """ if len(s3) != len(s1) + len(s2): return False i1 = i2 = i3 = 0 while i1 < len(s1) and i2 < len(s2): c = s3[i3] if s1[i1] == c: i1 += 1 elif s2[i2] == c: i2 += 1 else: return False i3 += 1 return True
3b88d117efde1d6b8ea8e0266a9c3ac7ae039458
3,623,223
def header_is_sorted_by_coordinate(header): """Return True if bam header indicates that this file is sorted by coordinate. """ return 'HD' in header and 'SO' in header['HD'] and header['HD']['SO'].lower() == 'coordinate'
b656770806818abe742be32bc14c31a8a8e3e535
3,623,224
def delete( name, endpoint="incidents", id=None, api_url=None, page_id=None, api_key=None, api_version=None, ): """ Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. ...
900126d08761793a4f97c1b4acbda224218103da
3,623,225
import re def name_conversion(caffe_layer_name): """ Convert a caffe parameter name to a tensorflow parameter name as defined in the above model """ # beginning & end mapping NAME_MAP = {'bn_conv1/beta': 'conv0/bn/beta', 'bn_conv1/gamma': 'conv0/bn/gamma', 'bn_conv1...
c9025c01eeb8d319a4e76db167f65bac99adf396
3,623,226
def square(x, name=None): """Computes square of x element-wise. I.e., \\(y = x * x = x^2\\). Args: x: An `Output` or `SparseTensor`. Must be one of the following types: `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns:...
666e4b272b454561d2474229ed12ff94b8a629ef
3,623,227
def manually_adjust_data(pnid, sc_entry): """Returns a modified version of sc_entry to fix some issues manually. Args: pnid: string, ProteinNet ID sc_entry: dictionary containing "seq", "ang", "crd" data Returns: If sc_entry must be modified, then it is corrected and returned. ...
90d801a5549b87e15e0c8e45f11de92ab2ad6cea
3,623,228
def get_network_container_hostnames(name): """Returns a list of every container hostname in the specified network.""" for network in get_networks(): if network["Name"] == name: return [get_container_hostname(container) for container in network["Containers"]]
f7b1f176f2c0e5a879930c2189f36f933075664e
3,623,229
def spearmanr_no_pval_vec(X, Y): """Returns spearmans correlation, vectorized version Parameters ---------- X : ndarray (n_samples, n_observations) Y : ndarray (n_samples, 1) Returns ------- R : array (n_observations,) spearmans correlation between each column of X and Y ""...
9a4aeae514d80963ba1d12a574c3aebb8bdc30d4
3,623,230
import json async def surprise_communities(request): """ --- description: This end-point allows to compute surprise_communities Community Discovery algorithm to a network dataset. tags: - surprise_communities produces: - application/json responses: ...
785c2b6e14516b0f5ddd140310fe75fb4759900f
3,623,231
def set_case(words, method="lower", testing=False): """ Perform capitalization on some or all of the strings in `words`. Default method is "lower". Args: words (list): word list generated by `choose_words()` or `find_acrostic()`. method (str): one of {"alter...
92465688c8a7e2e85d2631b8acd8496fab5d0c33
3,623,232
def button(channel, red, blue): """Returns the button for a Combo PWM Mode command.""" return (pf_rc.CHANNEL[channel], PWM_STEP[red], PWM_STEP[blue])
821ce8c5684bb7634281b95960607537de15b4a4
3,623,233
def mini_xception(input_shape, num_classes, regularization = l2(0.01)): """ This function architects the mini_xception model network. This is the best performing model in the facial emotion analysis input_shape: input shape of the image num_classes: number of classes in the output return: Ret...
a7003277cc25e4029cfcf0dea580833f68916af5
3,623,234
def calc_node_size(self): """ calculate minimum node size. """ title_width = self._text_item.boundingRect().width() port_names_width = 0.0 port_height = 0.0 if self._input_items: input_widths = [] for port, text in self._input_items.items(): input_width = port.bo...
9d6b8a37ef13a9698d6523baeacc2da0686c9c4d
3,623,235
def page_osr_vieworder(): """Return everything.""" query = f'SELECT DISTINCT orderdate FROM orderlog' g.cur.execute(query) rows = g.cur.fetchall() return render_template('vieworder.html', dates=rows)
a28ce95ae9930d1da19cd1af817b6376d3dc4f83
3,623,236
def eval_metric_fns(): """Returns a dict from name to metric functions. This can be customized as follows. Care must be taken when handling padded lists. (only takes labels >= 0. def _auc(labels, predictions, features): is_label_valid = tf_reshape(tf.greater_equal(labels, 0.), [-1, 1]) clean_l...
cfa13913bd7132fc558b0e3b4ab71fd8dc9328c7
3,623,237
from typing import List from typing import Dict from typing import Optional from typing import Union def combine_score_weights( weights: List[Dict[str, float]], overrides: Dict[str, Optional[Union[float, int]]] = SimpleFrozenDict(), ) -> Dict[str, float]: """Combine and normalize score weights defined by ...
f75b444a013087350412b1bb65780b42496632af
3,623,238
def calc_ideal_vel(traj_ref, dt): """ Parameters ------------ traj_ref : numpy.ndarray, shape (2, N) these points should follow subseqently dt : float sampling time of system """ # end point and start point diff = traj_ref[:, -1] - traj_ref[:, 0] distance = np.sqrt(n...
45c4ae252c9689d57733ffc4fb0b976999e2b583
3,623,239
import requests def getImport(accessToken: str, groupId: str, importId: str) -> dict: """ :param accessToken :param groupId :param importId """ url = 'https://api.powerbi.com/v1.0/myorg/groups/{groupId}/imports/{importId}'.format( groupId=groupId, importId=importId, ) ...
c3609f555511d2d9c04733d002a2c2f3ed26cbd2
3,623,240
def make_rgba(grid2D, levels, colorlist, mask=None, mercator=False): """ Make an rgba (red, green, blue, alpha) grid out of raw data values and provide extent and limits needed to save as an image file Args: grid2D: Mapio Grid2D object of result to mape levels (list): list...
f337ac86909d0941d513648f309602e76dd56374
3,623,241
import binascii def AES_encryption(enc,server=False): """ Performs AES encryption using the globablly declared AES key. """ enc = str(enc) enc = enc + ((16 - len(enc) % 16) * ' ') iv = enc[:16] aes_cipher = None if server: aes_cipher = AES.new(login_server_key, AES.MODE_CBC, iv...
00f89db237a746a6a72cc7f168d14d616aded659
3,623,242
def named_cache_page(cache_timeout): """ Decorator for views that tries getting the page from the cache and populates the cache if the page isn't in the cache yet. The cache is keyed by view name and arguments. """ def wrapper(func): def foo(*args, **kwargs): key = func.__na...
1c946370640bd76c3a4a3d3a6a3c0fe5a76d0215
3,623,243
def get_product(location, product_id, quantity): """ Used by the movement route to get a product from a location. """ product_array = [] db = get_db() b_id = session.get("user_id") if location == "product_factory": # Get product from product table, deduct the quantity ogquantity = d...
cda91efeb3bbc280a609bc560e4a9b9867d6d1ed
3,623,244
def calc_psi_r(qr, r1, r2, r3, r4): """ radial geodesic angle Parameters: qr (float) r1 (float): radial root r2 (float): radial root r3 (float): radial root r4 (float): radial root Returns: psi_r (float) """ kr = ((r1 - r2) * (r3 - r4)) / ((r1 - ...
2d9744361739db19e1c347b902a5844f1a23c655
3,623,245
def mse(tensor_true, tensor_pred): """ Mean squared error Parameters ---------- tensor_true : Tensor tensor_pred : {Tensor, TensorCPD, TensorTKD, TensorTT} Returns ------- float """ tensor_res = residual_tensor(tensor_true, tensor_pred) return np.mean(tensor_res.data ** 2)
afc7bce6515bfc656da3fdb15f5605184bcc10a7
3,623,246
def covered_cv_skills_from_course(user_id, course_id): """This function is used find the relation of a course to a user cv""" fetch_cv_command = """SELECT DISTINCT id FROM "CVs" WHERE user_id={user_id}""""".format(**{'user_id': user_id}) cv_df = get_table(sql_command=fetch_cv_command) if len(cv_df) > 0:...
6befec8d8e15e759ac24718176fcf516d851d3ae
3,623,247
def processRHS(rhs): """ Depending on the type of the argument, calls the corresponding function to deal with that type. :param rhs: portion of JSGF rule :type rhs: either a JSGF Expression, list, or string :returns: list of strings """ if type(rhs) is list: return processSequen...
412def2461fcfa3cc3ae48f8bcb2e4a4c18bb9e9
3,623,248
def svn_prop_name_is_valid(prop_name): """svn_prop_name_is_valid(char const * prop_name) -> svn_boolean_t""" return _core.svn_prop_name_is_valid(prop_name)
50c9c833f5d1935d6f411530700bb28ce60f0ca7
3,623,249
def factory(): """ A factory that creates clustering algorithms. """ return ClusteringFactory
4b4e81e4e32b9bf1e0b69b499e4f748f4a4836d3
3,623,250
import pycountry def subdivision_type(country_code): """Returns the name of the most common country subdivision type for the given country code.""" ensure_definition(country_code) counts = dict() for subdivision in pycountry.subdivisions.get(country_code=country_code): if subdivision.paren...
e8268095cea3eb8e0e48772dd2b257f78fc4d314
3,623,251
def get_fans(tp): """ Get fan_in and fan_out with corresponding slices """ slices_fan_in = {} # fan_in per slice slices_fan_out = {} for weight, instr in zip(tp.weight_views(), tp.instructions): slice_idx = instr[2] mul_1, mul_2, mul_out = weight.shape fan_in = mul_1 * mul_2 ...
7fdff84c5129bd22a738653b6676d48c2a5f073d
3,623,252
import numpy as np import xarray as xr from pandas import Timestamp def download_noaa_mbl( noaa_mbl_url, download_dest="../data/raw/co2_GHGreference_surface.txt", target_lat=None, target_lon=None, interp_method="linear", ): """ Downloads the NOAA marine boundary layer xCO2 and grids it ...
ba13bce93174bf3fbf3b47de2855f7fd3ff7dee3
3,623,253
import math def get_pier_nodes(bridge: Bridge, ctx: BuildContext) -> PierNodes: """All the nodes for a bridge's piers. NOTE: This function assumes that 'get_deck_nodes' has already been called with the same 'BuildContext'. """ pier_nodes = [] for pier_i, pier in enumerate(bridge.supports): ...
4f2ca233c4c58538c5074f168c52d086614e71b7
3,623,254
def secret_token(): """ Fixture that yields a usable secret token. """ return 'super-secret-token-string'.encode()
90e6c54a18387c64e27fea93912278c126df1585
3,623,255
def gf_from_int_poly(f, p): """ Create ``GF(p)[x]`` polynomial from ``Z[x]``. **Examples** >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_from_int_poly >>> gf_from_int_poly([7, -2, 3], 5) [2, 3, 3] """ return gf_trunc(f, p)
8716d08286b49310953a5d00d2d0c7f8a98a540d
3,623,256
import requests def macro_uk_halifax_yearly(): """ 东方财富-经济数据-英国-Halifax 房价指数年率 http://data.eastmoney.com/cjsj/foreign_4_1.html :return: Halifax房价指数年率 :rtype: pandas.DataFrame """ url = "http://datainterface.eastmoney.com/EM_DataCenter/JS.aspx" params = { "type": "GJZB", ...
09214bda60da565865c24e82f831466844fac92e
3,623,257
def fock_state(state, device_wires, params): """Computes the expectation value of the ``qml.FockStateProjector`` observable in Strawberry Fields. Args: state (strawberryfields.backends.states.BaseState): the quantum state device_wires (Wires): the measured mode params (Sequence): se...
955d59f3edcb8c6d0fbdfebb0fe1beca534df957
3,623,258
from datetime import datetime def datetime_from_filetime(filetime): """return a :class:`datetime.datetime` from a ``windows`` FILETIME int""" # Manual non-approx rounding as filetime will not have a perfect representation as Python float # We do some sort of "manual rounding cause of py2 vs py3 # PY2:...
fc63e7a1072adff64bc8da3548285fed2e0add44
3,623,259
def forward_one_to_one_with_sr(request): """ Return all the publishers with associated owner, using select_related. 53ms overall 1ms on queries 1 queries SELECT "bookstore_publisher"."id", "bookstore_publisher"."name", "bookstore_publisher"."owner_id", "auth_us...
70b991a56b30e8ba0847ca6a69b64c8d44647bd1
3,623,260
import types def is_variable(tup): """ Takes (name, object) tuple, returns True if it is a variable. """ name, item = tup # callable() # 函数用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败; # 但如果返回False,调用对象ojbect绝对不会成功。 # 对于函数, 方法, lambda 函式, 类, 以及实现了 __call__ # 方法的类实例, 它都返回 True。 if callab...
81055d1ed252160c417b386c875e818b87780f14
3,623,261
import os import errno def _IsOnDevice(path, st_dev): """Checks if a given path belongs to a FS on a given device. Args: path: a filesystem path, possibly to a non-existent file or directory. st_dev: the ID of a device with a filesystem, as in os.stat(...).st_dev. Returns: True if the path or (if ...
391843553ea49ae7c0998dac5601d5d525890265
3,623,262
def _Solve_Amplitude(data, ufit, error=None) : """ Compute the amplitude needed to normalise the 1d profile which minimises the Chi2, given a x array, data and an error array The calculation follows a simple linear optimisation using Ioptimal = (dn x dn / dn x fn) where dn i...
ccf513130dd8631acc61e88a328645243bdf7f94
3,623,263
def generate_ethmac(peripheral, shadow_base, **kwargs): """ Generates definition of 'ethmac' peripheral. Args: peripheral (dict): peripheral description shadow_base (int or None): shadow base address kwargs (dict): additional parameters, including 'buffer' Returns: string: ...
e0c34117c972fb007ec9b322a48f54fcdad6c8ab
3,623,264
def pix_centers(geoTransform, rows, cols, make_grid=True): """ provide the pixel coordinate from the axis, or the whole grid Parameters ---------- geoTransform : tuple, size=(6,1) georeference transform of an image. rows : integer amount of rows in an image. cols : integer ...
05ad408b99c70c554eb42300e0d7cdd19630817f
3,623,265
from typing import List def rhymes(input_val: str_or_list_of_str, sample_size=None) -> List[str]: """Return a list of rhymes in randomized order for a given word if at least one can be found using the pronouncing module (which uses the CMU rhyming dictionary). :param input_val: the word or words in relat...
71366876027efaf5ab43f7fe1e765aaad068825d
3,623,266
async def logout(): """Clear the current session, including the stored user id.""" logout_user() return redirect(url_for("index"))
cc944f1069cf87d7b6cc94a44dde94e91efba369
3,623,267
from typing import Any def delete_user_class(user_class_id: int) -> flask.Response: """ Create a new user class. Requires the ``userclasses_modify`` permission. .. :quickref: UserClass; Delete user class. **Example request**: .. parsed-literal:: PUT /user_classes HTTP/1.1 { ...
acb7327231ff15473ada1906da75452c04c1a555
3,623,268
def ajax_form_errors(errors): """ returns form errors as python list """ errs = [{'key': k, 'msg': unicode(errors[k])} for k in errors.keys()] #equivalent to #for k in form.errors.keys(): # errors.append({'key': k, 'msg': unicode(form.errors[k])}) return errs
678c47de36d3f72c37acb394aff02b6c3f1253b6
3,623,269
import os def load_data_file(name, skip_header=None) -> np.recarray: """Load a data file. Returns ------- data : :class:`numpy.recarray` data values """ fname = os.path.join(os.path.dirname(__file__), 'data', name) return np.recfromcsv( fname, skip_header=skip_header, case...
a1fd6b1a02a5bbffdddb6c7fcf3e11b431e10e23
3,623,270
def sanitize_html(html, bad_tags=['body']): """Removes identified malicious HTML content from the given string.""" if html is None or html == '': return html cleaner = Cleaner(style=False, page_structure=True, remove_tags=bad_tags, safe_attrs_only=False) return cleaner.clea...
260f01804b720de97406c3f277a91c17c360ccab
3,623,271
from typing import Optional def create_base_map( move_data: DataFrame, lat_origin: Optional[float] = None, lon_origin: Optional[float] = None, tile: Optional[Text] = TILES[0], default_zoom_start: Optional[float] = 12, ) -> Map: """ Generates a folium map. Parameters ---------- ...
f5be52152234747469bb20357cba65f9c2b2f7cd
3,623,272
from typing import Callable import operator def when(condition: Callable, f_true: Callable) -> Callable: """Returns `f_true(args)` if `condition(args)` returns true, else returns args. >>> f = when(gamla.greater_than(5), lambda i: -i) >>> f(6) '-6' >>> f(3) '3' """ return ternary(cond...
0fa5b4ae94910624a42f2da86d7c45be516f9cc4
3,623,273
from typing import Dict def check_use_speech_in_inference(tts: AbsTTS, decode_config: Dict) -> bool: """Check whether to require speech in inference. Args: tts (AbsTTS): TTS model instance. decode_config (Dict): Decoding config dictionary. Returns: bool: True if speech is require...
147a144dc326a3eea3017f288dde24111dc44569
3,623,274
def f56a(): """Return a unit-distance embedding of the F56A graph. Note that MathWorld's LCF notation for this is incorrect; it should be [11, 13, -13, -11]^14.""" t = tan(pi/14) u = sqrt(polyval([-21, 98, 71], t*t)) z1 = 2*sqrt(14*polyval([31*u, -20, -154*u, 104, 87*u, -68], t)) z2 = 7*t*(t...
c5c0b0ac623858fc23005b82e81a9d3ca21834c4
3,623,275
def _nova_to_osvif_route(route): """Convert Nova route object into os_vif object :param route: nova.network.model.Route instance :returns: os_vif.objects.route.Route instance """ obj = objects.route.Route( cidr=route['cidr']) if route['interface'] is not None: obj.interface =...
2c6c3ae48f7c58e5b88404844e8a7ad4bc24fde7
3,623,276
import torch def recall(pred, target): """Calculate macro-averaged recall according to the prediction and target Args: pred (torch.Tensor | np.array): The model prediction. target (torch.Tensor | np.array): The target of each prediction. Returns: float: The function will return a...
a4b0852f4a66fdabee0ef2fee8f29fdb8ceda7db
3,623,277
def send_ui_notification(error_message, success_message, error_event_type=EVENT_TYPE_ERROR, migrate_op=False, log_exception=False): """ Send a notification to the GUI. If the decorated method throws an exception, an error notification will be sent, else a su...
5095cb2b2dd847a861b872a535bf806b498f0ddc
3,623,278
from typing import Union def fetch_dataset_as_namedtuple(dataset_id: int, target: str, read_csv_kwargs: dict, load_dataframe: bool, ) -> Union[DatasetAll, DatasetInfoOnly]: """ Takes a dataset identifier, a target ...
489106701c5f016cd6c25ff1a60b44491990ef8d
3,623,279
def mps_to_kmph(mps): """ Transform a value from meters-per-second to kilometers-per-hour """ return mps * 3.6
fee133def1727801e5e473d3ffb2df6c7e733a04
3,623,280
from typing import List def get_comparison_data(data_type: str, similar: List[str]): """Screener Overview Parameters ---------- data_type : str Data type between: overview, valuation, financial, ownership, performance, technical Returns ---------- pd.DataFrame Dataframe w...
7d736b666a98edacdfaa69e8894ba5782158901f
3,623,281
def common_params(task_instance, task_cls): """ Grab all the values in task_instance that are found in task_cls. """ if not isinstance(task_cls, task.Register): raise TypeError("task_cls must be an uninstantiated Task") task_instance_param_names = dict(task_instance.get_params()).keys() ...
3d9fd8e4d6aad9a04841fe1338d51bcf9b968a96
3,623,282
def two_ammonia_fake_print(ammonia_fake) -> (oechem.OEMol, oechem.OEMol): """ Returns two fingerprints for ammonia molecules with fake Wiberg bond orders """ fingerprint1 = danceprops.DanceFingerprint(ammonia_fake[1], 0.05) fingerprint2 = danceprops.DanceFingerprint(ammonia_fake[1], 0.05) re...
e7e7ccc44b7beea1f78a33ea7779438e02473574
3,623,283
def imread(path, grayscale=False, size=None, interpolate="bilinear", channel_first=False, as_uint16=False, num_channels=-1, **kwargs): """ Read image from ``path``. If you specify the ``size``, the output array is resized. Default output shape is (height, width, channel) for RGB image and (he...
d647b8248a40de6a254303db9ac06046fbbd5e23
3,623,284
import logging import ssl def get_client(project_id, cloud_region, registry_id, device_id, private_key_file, algorithm, ca_certs, mqtt_bridge_hostname, mqtt_bridge_port): """Create our MQTT client. The client_id is a unique string that identifies this device. For Google Cloud IoT Core, it must be i...
7e135739b7eaf87f8a761a1b7eebea61febef727
3,623,285
def mutAddConn(self, connG, nodeG, innov, gen): """Add new connection to genome. To avoid creating recurrent connections all nodes are first sorted into layers, connections are then only created from nodes to nodes of the same or later layers. Todo: check for preexisting innovations to avoid duplicates in s...
583cc8764aef0eca857be18adc0d924a66d9473b
3,623,286
def heat_diffusion(heat, laplacian, start=0, end=0.1): """Heat diffusion Iterative matrix multiplication between the graph laplacian and heat """ out_vector=expm_multiply( -laplacian, heat, start=start, stop=end, endpoint=True )[-1] return out_vect...
a308f8719ec340435751ac32fd7ca1fb176b8374
3,623,287
import inspect def behavior(instance_mode="session", instance_creator=None): """ Decorator to specify the server behavior of your Pyro class. """ def _behavior(clazz): if not inspect.isclass(clazz): raise TypeError("behavior decorator can only be used on a class") if instan...
748817411f58cdbce66b2cacdaf0a642183c7963
3,623,288
import torch def gt2out(gt_bboxes_list, gt_labels_list, inp_shapes_list, stride, categories): """transform ground truth into output format""" batch_size = len(gt_bboxes_list) inp_shapes = gt_bboxes_list[0].new_tensor(inp_shapes_list, dtype=torch.int) output_size = inp_shapes[0] / stride height_rat...
da3636776f75abc53cc790e0ffd6871fc6a1d7ca
3,623,289
def lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b): """ Forward pass for a single timestep of an LSTM. The input data has dimension D, the hidden state has dimension H, and we use a minibatch size of N. Inputs: - x: Input data, of shape (N, D) - prev_h: Previous hidden state, of shape (N,...
7d898c35b2f50248f98a511a50c6dab5bef8d756
3,623,290
import time import hashlib def get_wx_js_sdk_config(): """ 获取微信JS-SDK权限验证配置 :return: """ url = request.args.get('url') claim_args(1201, url) appid = current_app.config['INTERVAL_APPID'] wx_authorizer = WXAuthorizer.query_by_appid(appid) jsapi_ticket = wx_authorizer.get_jsapi_ticket...
46daffecd53d08945dc601368a3a0291c85bd7fc
3,623,291
def get_reviewer_by_id(reviewerID): # noqa: E501 """Get a Reviewer by ID # noqa: E501 :param reviewerID: ID of Reviewer :type reviewerID: int :rtype: List[Reviewer] """ results = _globals.pgapi.get( 'Reviewers', clause=f'WHERE reviewerID={reviewerID}' ) if type...
72564cd627c1ccc3c384e5df2539c893b67e931d
3,623,292
def get_quats(tpf=None, camera=None, sector=None, time=None, dt=None): """Get an array of the quaternions, at the time resolution of the input TPF""" if (tpf is None) and (camera is None) and (sector is None): raise ValueError('set either TPF or camera/sector') if camera is None: camera = tp...
99f6b9093e24528a353618ac1f2fbe4606bc02c0
3,623,293
def create_list_id_title(sheets: list) -> list: """ Args: this function gets a list of all the sheets of a spreadsheet a sheet is represented as a dict format with the following fields "sheets" : [ { "properties": { ...
a32d2cbfce6f06d326f49e69983e05e67bfc1697
3,623,294
import types import scipy def qng(qc: qiskit.QuantumCircuit, thetas: np.ndarray, create_circuit_func: types.FunctionType, **kwargs): """Calculate G matrix in qng Args: - qc (qiskit.QuantumCircuit) - thetas (np.ndarray): parameters - create_circuit_func (FunctionType) - num_lay...
4c7433f96c7a4ce36ea6e20d0c82e189e725e611
3,623,295
def horizontal_projection(img_matrix): """ Function that calculate the angle rotation according to the Hough Transform technique :param img_matrix: A list of ints with the matrix of pixels of the image :return: rotateAngle: angle of rotation """ try: img_grey = cv2.cvtColor(img_matrix...
3eb7596a4f082300216fa4d7b3a87983aeee2b11
3,623,296
from matplotlib.ticker import AutoMinorLocator def set_minor_tick(ax: Axes, n: int = 2): """Set one minor tick between major ticks.""" ax.xaxis.set_minor_locator(AutoMinorLocator(n)) ax.yaxis.set_minor_locator(AutoMinorLocator(n)) return ax
c41f72c4417a49d89b5c94c9d4b2185f69281403
3,623,297
def fit_lfm_pcfp(x, p, sig2, k_): """For details, see here. Parameters ---------- x : array, shape (t_, n_) p : array, shape (t_,) sig2 : array, shape (t_, t_) k_ : scalar Returns ------- alpha_PC : array, shape (n_,) beta_PC : array, shape (n_, k_) ...
9154045af81561b20a83394f0f03bcb9b27719c3
3,623,298
def _generate_is_in_range(message): """Generate range checks for all signals in given message. """ signals = [] for signal in message.signals: scale = signal.decimal.scale offset = (signal.decimal.offset / scale) minimum = signal.decimal.minimum maximum = signal.decima...
2fc3e9939cb6225d4e6fb405efb4dd323e698179
3,623,299