content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def gumbel_softmax(log_pi, tau=0.1, axis=1): """Gumbel-Softmax sampling function. This function draws samples :math:`y_i` from Gumbel-Softmax distribution, .. math:: y_i = {\\exp((g_i + \\log\\pi_i)/\\tau) \\over \\sum_{j}\\exp((g_j + \\log\\pi_j)/\\tau)}, where :math:`\\tau` is a tem...
91751a5bd8069c71de5dbe9f2cbbc7757daff140
31,400
def has_active_lease(storage_server, storage_index, now): """ :param allmydata.storage.server.StorageServer storage_server: A storage server to use to look up lease information. :param bytes storage_index: A storage index to use to look up lease information. :param float now: The curre...
544b17489bc766a15bf2eca5cddab55c1bf473dd
31,401
from typing import List import os def _enumerate_files(path: str, parts: List[str], repl_list1: List[str], repl_list2: List[str] = None) -> str: """ Enumerate all possible file names """ if len(parts) <= 2: for token in repl_list1: parts[-1] = token candidate = os.path.join(pat...
a227d9727efe27038f40b814cce6647cb0c75862
31,402
def MXfunc(A, At, d1, p1): """ Compute P^{-1}X (PCG) y = P^{-1}*x """ def matvec(x): return p1 * x N = p1.shape[0] return LinearOperator((N, N), matvec=matvec)
c2c1d6361756779f9318a9356251c8ba1a610057
31,403
from ._filter import filter_ from typing import Callable def filter(predicate: Predicate[_T]) -> Callable[[Observable[_T]], Observable[_T]]: """Filters the elements of an observable sequence based on a predicate. .. marble:: :alt: filter ----1---2---3---4---| [ filter(i: i>2) ...
b56f4ed6e770d9b623362cca92a791d7f1ef5fa7
31,404
def scb_to_unit(scb): """Convert codes used by Statistics Sweden to units used by the NAD GIS files.""" scbform = 'SE/' + '{:0<9}'.format(scb) if scbform in g_units.index: return g_units.loc[scbform, 'G_unit'] else: return 0
1c878492bb0bb4e8c7b7874097c86fa8bbc93329
31,405
import os def revision_pattern_from_build_bucket_path(bucket_path): """Get the revision pattern from a build bucket path.""" return '.*?' + os.path.basename(bucket_path)
b7db362eb47531413397f0dc2079f4f7fd931d94
31,406
def img_to_square(im_pic): """ 把图片处理成正方形 :param im_pic: :return: """ w, h = im_pic.size if w >= h: w_start = (w - h) * 0.618 box = (w_start, 0, w_start + h, h) region = im_pic.crop(box) else: h_start = (h - w) * 0.618 box = (0, h_start, w, h_start + w)...
ae672ea715cb982272eddaff0417d4f64926894c
31,407
from typing import List def load_sentence( filename: str, with_symbol: bool=True ) -> List[str]: """コーパスをロードする。""" if with_symbol: tokens = [ list(sent.split()) + [config.END_SYMBOL] for sent in (_.strip() for _ in open(filename)) ] else: tokens = [ ...
3f494b740a4ed157f163329de8cc0568e5541cdc
31,408
def to_str(bytes_or_str): """ The first function takes a bytes or str instance and always returns a str. """ if isinstance(bytes_or_str, bytes): value = bytes_or_str.decode('utf-8') else: value = bytes_or_str return value
4a73559039501764a00e697c092d20426949058d
31,409
def configure_ampliseq(request): """View for ampliseq.com importing stuff""" ctx = get_ctx_ampliseq(request) return render_to_response( "rundb/configure/ampliseq.html", ctx, context_instance=RequestContext(request) )
90cdd14de158efc79b5cad11feaa115878469866
31,410
import struct def _copy(s): """Creates a new set from another set. Args: s: A set, as returned by `sets.make()`. Returns: A new set containing the same elements as `s`. """ return struct(_values = dict(s._values))
b505af5037d0aa889aa8ed707eaf69d572e54f84
31,411
import random def particle_movement_x(time): """ Generates a random movement in the X label Parameter: time (int): Time step Return: x (int): X position """ x = 0 directions = [1, -1] for i in range(time): x = x + random.choice(directions) return x
0dff68080dbfd56997cffb1e469390a1964a326f
31,412
def find_match_characters(string, pattern): """Find match match pattern string. Args: params: string pattern Returns: Raises: """ matched = [] last_index = 0 if not string or not pattern: return matched if string[0] != pattern[0]: return matc...
6d3bc3844c20584038e41c22eeead7325031b647
31,413
import itertools def cross_product_configs(**configs): """ Given configs from users, we want to generate different combinations of those configs For example, given M = ((1, 2), N = (4, 5)), we will generate (({'M': 1}, {'N' : 4}), ({'M': 1}, {'N' : 5}), ...
7fcf61abcbb850630a5be9468822f567199460bc
31,414
from typing import Union def columnwise_normalize(X: np.ndarray) -> Union[None, np.ndarray]: """normalize per column""" if X is None: return None return (X - np.mean(X, 0)) / np.std(X, 0)
24b5995a5b36738e1c9eecf427fdb4ed83d43145
31,415
import os def fq_classification(fqclass, verbose=False): """ Read the fastq classification file :param fqclass: the classification file that has the file name and then arbitrary classifications separated by tabs :param verbose: more output :return: a dict of the classification. Guaranteed that all...
84f71e91ad9b20c5781377b05f3a72c05a6d28b5
31,416
def line_intersect(a1, da, b1, db): """ compute intersection of infinetly long lines """ dba = np.array(a1) - np.array(b1) da_perpendicular = perp(da) num = np.dot(da_perpendicular, dba) denom = np.dot(da_perpendicular, db) dist_b = (num / denom) return dist_b*db + b1
5be8211d3f31d7984820349dfbbb1e05592287a4
31,417
def sequence_(t : r(e(a))) -> e(Unit): """ sequence_ :: (Foldable r, Monad e) => r (e a) -> e () Evaluate each monadic action in the structure from left to right, and ignore the results. For a version that doesn't ignore the results see sequence. As of base 4.8.0.0, sequence_ is just sequenceA...
85c36cc767f60eaccd8d91cdc4d14ca2370069f7
31,418
import re def param_validated(param, val): """Return True if matches validation pattern, False otherwise""" if param in validation_dict: pattern = validation_dict[param] if re.match(rf'{pattern}', val) is None: log.error("Validation failed for param='%s', " "v...
4359b20437e8cfd21b82b5952cc1c9026e6dca13
31,419
def remove_keys_from_array(array, keys): """ This function... :param array: :param keys: :return: """ for key in keys: array.remove(key) return array
3143b8e42eb1e1b2f5818a254bcec3631c30f5ea
31,420
def create_tree_data(codepage, options, target_node, pos): """Create structure needed for Dijit Tree widget """ tree_nodes = [] for opt in options: code = opt['code'] cp = codepage + code add_tree_node(tree_nodes, cp, code+"-"+opt['label'], cp) tree_data = { ...
fededfc4bc3e39860221783459d324a15f16d081
31,421
def detect_octavia(): """ Determine whether the underlying OpenStack is using Octavia or not. Returns True if Octavia is found in the region, and False otherwise. """ try: creds = _load_creds() region = creds['region'] for catalog in _openstack('catalog', 'list'): ...
265e01730cfc2b7e1870c0364ddb4cd5d7c4b336
31,422
def add_cache_control_header(response): """Disable caching for non-static endpoints """ if "Cache-Control" not in response.headers: response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" return response
06f3f4a7259076be535b4ea0ca719a13e9e665a0
31,423
from typing import List def clean_new_import_aliases( import_aliases: List[ImportAlias], ) -> List[ImportAlias]: """Clean up a list of import aliases.""" # Sort them cleaned_import_aliases = sorted(import_aliases, key=lambda n: n.evaluated_name) # Remove any trailing commas last_name = cleaned...
5f0b25798f353c999d325125e80c9ccb67b5afec
31,424
def _format_td(timedelt): """Format a timedelta object as hh:mm:ss""" if timedelt is None: return '' s = int(round(timedelt.total_seconds())) hours = s // 3600 minutes = (s % 3600) // 60 seconds = (s % 60) return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
071f25c3c8cfc75cacf2fedc7002527897362654
31,425
def add_quad_reaction_node(graph, rxn): """ Adds a "Quad Reaction Node" (QRN) group of nodes to a graph, and connects them to the correct compound nodes. The QRN consists of two nodes constituting the intended forward direction of the reaction and two nodes constituting the reverse direction. Each ...
360e7c4e74ed58da9b85548c4d217e3d1f40150b
31,426
import os def api_dataset(dataset): """ Return a list of available years """ path = os.path.join(geodata_dir, dataset) if os.path.exists(path): return jsonify(find_maps(path)) else: return 'error: cannot find dataset: %s' % dataset
92dd50dfcb4b8d4ec2bb87f1e098ebc06ac3bec9
31,427
def matrixFilter(np_image_2D, np_mask): """ Processing filtering with given matrix Keyword argument: np_image_2D -- two dimensional image(grayscale or single color channel) np_mask -- mask matrix as numpy array Return: np_image_fil -- image as numpy 2D array, after specified filtering ...
422de6c4c539ceb154827d511127f1b120519a2a
31,428
def batch_split_axis(batch, n_split): """Reshapes batch to have first axes size equal n_split.""" x, y = batch n = x.shape[0] n_new = n / n_split assert n_new == int(n_new), ( "First axis cannot be split: batch dimension was {} when " "n_split was {}.".format(x.shape[0], n_split)) n_new = int(n_...
0f413e40961b15b64bf118b2daa012e853dbc294
31,429
def right_align(value, length): """ :param value: string to right align :param length: the number of characters to output (spaces added to left) :return: """ if length <= 0: return u"" value = text(value) if len(value) < length: return (" " * (length - len(value))) + va...
de8c42734b094514ebd45c2cb5517da806ec74b8
31,430
import yaml from pathlib import Path def test_disable_functions_as_notebooks(backup_spec_with_functions): """ Tests a typical workflow with a pieline where some tasks are functions """ with open('pipeline.yaml') as f: spec = yaml.safe_load(f) spec['meta']['jupyter_functions_as_notebooks']...
f5e5c8cc687a64d4c7593ef571e181d6cf4d27ce
31,431
import builtins def proxy_gettext(*args, **kwargs): """Proxy calls this function to the real built-in gettext() function. This is not required for normal operation of the application, could be not imported at all, but will help development. """ ### this would load gettext in case it wasn't done b...
870e5c3d7c6bceec438f042c875e313e4877d9b4
31,432
def generate_users_data(users): """ Generate users' rows (assuming the user's password is the defualt one) :param users: :return: """ headers = ['שם משתמש', 'סיסמה'] rows = [[user.username, DEFAULT_TEAM_USER_PASSWORD] for user in users] rows.insert(0, headers) return rows
c6d9ef03b3b28c31f59627be574c4d20328b5d82
31,433
def ListToMatrix(lv): """ Convert a list of 3 or 4 ``c4d.Vector`` to ``c4d.Matrix``. """ if not isinstance(lv, list): raise TypeError("E: expected list of vectors, got %r" % type(lv)) m = len(lv) if not isinstance(lv[0], c4d.Vector): raise TypeError("E: expected list elements of type c4...
b60e1f62d250ce1f7c8ef2772755c3a3ce878395
31,434
def loadEpithelium(name): """Returns an epithelium from a CSV file with the given name. Precondition: name exists and it's in CSV format""" assert type(name) == str, "name isn't a string" recs = [] text = open(name) i = 0 for line in text: if i > 0: recs.append(loadRecept...
01e0c613faa71dbc77be650c3eba1f5006966f9e
31,435
def focal_attention(query, context, use_sigmoid=False, scope=None): """Focal attention layer. Args: query : [N, dim1] context: [N, num_channel, T, dim2] use_sigmoid: use sigmoid instead of softmax scope: variable scope Returns: Tensor """ with tf.variable_scope(scope or "attention", reus...
27f480b8911b3ff1a4367af6b7d5b9a549d24653
31,436
def format_float(x): """ Pretty formatting for floats """ if pd.isnull(x): return " ." else: return "{0:10.2f}".format(x)
9f3cdc0ab41bc69807d178e1c4a56abec0ac6fab
31,437
def random_points_and_attrs(count, srs_id): """ Generate Random Points and attrs (Use some UTM Zone) """ points = generate_utm_points(count, srs_id) rows = [] for p in points: rand_str = ''.join(choice(ascii_uppercase + digits) for _ in range(10)) rand_bool = bool(randint(0, 1)) ...
1dcdbb376f91d75c33baf40275a047393bf13fd5
31,438
from typing import Union from typing import List def trimap(adata, **kwargs) -> Union[Axes, List[Axes], None]: """\ Scatter plot in TriMap basis. Parameters ---------- {adata_color_etc} {edges_arrows} {scatter_bulk} {show_save_ax} Returns ------- If `show==False` a :class...
e3294c689e9081813c6e1defecdf20918dc02b8b
31,439
import collections def quantile(arg, quantile, interpolation='linear'): """ Return value at the given quantile, a la numpy.percentile. Parameters ---------- quantile : float/int or array-like 0 <= quantile <= 1, the quantile(s) to compute interpolation : {'linear', 'lower', 'higher', ...
42e53b43d7ea580616d82fea4bdc08260de3b661
31,440
def random_new(algo=RNG_CMWC): """Return a new Random instance. Using ``algo``. Args: algo (int): The random number algorithm to use. Returns: Random: A new Random instance using the given algorithm. """ return tcod.random.Random(algo)
f6eef62d3eb483dbcb85d420262cf411d6934790
31,441
def get_kth_value(unsorted, k, axis=-1): """ Args: unsorted: numpy.ndarray of any dimensionality. k: int Returns: kth values along the designated axis. """ indices = np.argpartition(unsorted, k, axis=axis)[..., :k] k_smallests = np.take_along_axis(unsorted, indices, axis=...
ab787a89c04d390424749916a6ec7958efcc931e
31,442
def rdc_transformer( local_data, meta_types, domains, k=None, s=1.0 / 6.0, non_linearity=np.sin, return_matrix=False, ohe=True, rand_gen=None, ): # logger.info('rdc transformer', k, s, non_linearity) """ Given a data_slice, return a transformation of the features data...
420e0ca3dfedf23434cb1f2ee500a2d0f8969f52
31,443
import sys def trim(docstring): """Trims the leading spaces from docstring comments. From http://www.python.org/dev/peps/pep-0257/ """ if not docstring: return '' # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expa...
f1b96cebf76df60491324a9f8a20477b3bd6cc11
31,444
async def get_layer_version(compatible_runtime=None,layer_name=None,version=None,opts=None): """ Provides information about a Lambda Layer Version. """ __args__ = dict() __args__['compatibleRuntime'] = compatible_runtime __args__['layerName'] = layer_name __args__['version'] = version _...
57319a257b4e15e2d7ab2d14bfc43718967ea7e2
31,445
from typing import Optional from typing import List def get_header_names(header_annotation_names: Optional[List[str]], doc: Optional[str] = None, docs: Optional[List[str]] = None): """Get a list of header annotations and a dictionary for renamed annotations.""" # Get ...
e011af009e350e0ddbd5b18d19eb45816a7e8d6c
31,446
def data_index(data, key): """Indexing data for key or a list of keys.""" def idx(data, i): if isinstance(i, int): return data[i] assert isinstance(data, dict) if i in data: return data[i] for k, v in data.items(): if str(k) == str(i): ...
f2b6d18bcd83eb0ffd9b355643e79b40459d8d6a
31,447
def calculate_misfit(da): """ For each force orientation, extracts minimum misfit """ misfit = da.min(dim=('origin_idx', 'F0')) return misfit.assign_attrs({ 'best_force': _min_force(da) })
3dcba853b2e30d9fb5d3cbf96cfa6a00760335a6
31,448
def f_score_one_hot(labels,predictions,beta=1.0,average=None): """compute f score, =(1+beta*beta)precision*recall/(beta*beta*precision+recall) the labels must be one_hot. the predictions is prediction results. Args: labels: A np.array whose shape matches `predictions` and must be one_hot. ...
091143244858dee1e001042931f625db30c58195
31,449
def articles(): """Show a list of article titles""" the_titles = [[a[0], a[1]] for a in articles] return render_template('articles.html', titles = the_titles)
bb8f9af9cedb30f89fa950f60c7710ac840f026c
31,450
import json from pathlib import Path import uuid def create_montage_for_background(montage_folder_path: str, im_b_path: str, f_path: str, only_face: bool) -> str: """ Creates and saves the montage from a designed background. If a folder is provided for faces, it will create a file 'faces.json' inside the ...
b0c229d16e0ffdf2a8ea63cbc5785be918c09d46
31,451
def deserialize_question( question: QuestionDict ) -> Question: """Convert a dict into Question object.""" return Question( title=question['title'], content=question.get('content'), choices=[ Choice( title=title, goto=goto ) ...
c6f5dd962cdc7a0ef273d4397472de572f92c1f8
31,452
from datetime import datetime def ensure_utc_datetime(value): """ Given a datetime, date, or Wayback-style timestamp string, return an equivalent datetime in UTC. Parameters ---------- value : str or datetime.datetime or datetime.date Returns ------- datetime.datetime """ ...
0d5c631d2736094f5a60c2eb4ca7c83fcb1e3e6a
31,453
def get_pod_status(pod_name: str) -> GetPodEntry: """Returns the current pod status for a given pod name""" oc_get_pods_args = ["get", "pods"] oc_get_pods_result = execute_oc_command(oc_get_pods_args, capture_output=True).stdout line = "" for line in oc_get_pods_result.splitlines(): if po...
1353fb4f457a4818ffcfda188ca4d3db55ce5cc9
31,454
def helix_evaluate(t, a, b): """Evalutes an helix at a parameter. Parameters ---------- t: float Parameter a: float Constant b: float Constant c: float Constant Returns ------- list The (x, y, z) coordinates. Notes ----- An i...
2d62cae57dac72cd244d66df8de2d0a5d3b70c38
31,455
import scipy def get_pfb_window(num_taps, num_branches, window_fn='hamming'): """ Get windowing function to multiply to time series data according to a finite impulse response (FIR) filter. Parameters ---------- num_taps : int Number of PFB taps num_branches : int Number o...
1193a29ab754e2c8f30e1a58f34c9efcf58513af
31,456
from typing import Dict from typing import OrderedDict def retrieve_bluffs_by_id(panelist_id: int, database_connection: mysql.connector.connect, pre_validated_id: bool = False) -> Dict: """Returns an OrderedDict containing Bluff the Listener information for ...
f3f5d3e86423db20aa4ffe22410cc491ec5e80ed
31,457
def extract_protein_from_record(record): """ Grab the protein sequence as a string from a SwissProt record :param record: A Bio.SwissProt.SeqRecord instance :return: """ return str(record.sequence)
a556bd4316f145bf23697d8582f66f7dcb589087
31,458
import cftime def _diff_coord(coord): """Returns the difference as a `xarray.DataArray`.""" v0 = coord.values[0] calendar = getattr(v0, "calendar", None) if calendar: ref_units = "seconds since 1800-01-01 00:00:00" decoded_time = cftime.date2num(coord, ref_units, calendar) co...
e430d7f22f0c4b9ac125768b5c69a045e44046a5
31,459
import _tkinter def checkDependencies(): """ Sees which outside dependencies are missing. """ missing = [] try: del _tkinter except: missing.append("WARNING: _tkinter is necessary for NetworKit.\n" "Please install _tkinter \n" "Root privileges are necessary for this. \n" "If you have these, t...
05aad218f3df84ddb5656d0206d50ec32aa02dcb
31,460
from typing import Dict from typing import Any def get_user_groups_sta_command(client: Client, args: Dict[str, Any]) -> CommandResults: """ Function for sta-get-user-groups command. Get all the groups associated with a specific user. """ response, output_data = client.user_groups_data(userName=args.get('user...
b21b087e4e931e33111720bbc987b1bb6749fee8
31,461
def get_capital_flow(order_book_ids, start_date=None, end_date=None, frequency="1d", market="cn"): """获取资金流入流出数据 :param order_book_ids: 股票代码or股票代码列表, 如'000001.XSHE' :param start_date: 开始日期 :param end_date: 结束日期 :param frequency: 默认为日线。日线使用 '1d', 分钟线 '1m' 快照 'tick' (Default value = "1d"), :param...
f7c3f94fd012672b75d960ef1c4d749959a7e6cc
31,462
def split_quoted(s): """Split a string with quotes, some possibly escaped, into a list of alternating quoted and unquoted segments. Raises a ValueError if there are unmatched quotes. Both the first and last entry are unquoted, but might be empty, and therefore the length of the resulting list must...
0790e7b2fecfd6c2aa1ca04c8cb5f1faebb3722b
31,463
import torch def calc_IOU(seg_omg1: torch.BoolTensor, seg_omg2: torch.BoolTensor, eps: float = 1.e-6) -> float: """ calculate intersection over union between 2 boolean segmentation masks :param seg_omg1: first segmentation mask :param seg_omg2: second segmentation mask :param eps: eps for numerica...
6586b1f9995858be9ab7e40edd1c3433cd1cd6f4
31,464
import time def _call_list(urls, method, payload=None, headers=None, auth=None, proxies=None, timeout=None, stream=None, verify=True, payload_to_json=True, allow_redirects=True): """Call list of supplied URLs, return on first success.""" _LOGGER.debug('Call %s on %r', method, url...
f172e726991235fc9b6bfc63c9071994ab33e7c0
31,465
def td_path_join(*argv): """Construct TD path from args.""" assert len(argv) >= 2, "Requires at least 2 tdpath arguments" return "/".join([str(arg_) for arg_ in argv])
491f1d50767a50bfbd7d3a2e79745e0446f5204c
31,466
import torch def calculate_segmentation_statistics(outputs: torch.Tensor, targets: torch.Tensor, class_dim: int = 1, threshold=None): """Compute calculate segmentation statistics. Args: outputs: torch.Tensor. targets: torch.Tensor. threshold: threshold for binarization of predictions....
ccc017dd5c7197565e54c62cd83eb5cdc02d7d17
31,467
def sample_from_cov(mean_list, cov_list, Nsamples): """ Sample from the multivariate Gaussian of Gaia astrometric data. Args: mean_list (list): A list of arrays of astrometric data. [ra, dec, plx, pmra, pmdec] cov_list (array): A list of all the uncertainties and covariances: ...
353c08bfd8951610fdcf1511107888c1153d3eed
31,468
def get_finger_distal_angle(x,m): """Gets the finger angle th3 from a hybrid state""" return x[2]
f93b1931f3e4a9284ccac3731dfeea21526ea07c
31,469
def get_karma(**kwargs): """Get your current karma score""" user_id = kwargs.get("user_id").strip("<>@") session = db_session.create_session() kama_user = session.query(KarmaUser).get(user_id) try: if not kama_user: return "User not found" if kama_user.karma_points == ...
29f2622e65c45e642285014bbfa6dc33abb0e326
31,470
from pathlib import Path import os import logging def medical_charges_nominal(dataset_dir: Path) -> bool: """ medical_charges_nominal x train dataset (130452, 11) medical_charges_nominal y train dataset (130452, 1) medical_charges_nominal x test dataset (32613, 11) medical_charges_nominal y trai...
719ae4cef8fdae440fb601d18dc5ae8d88bbacca
31,471
def plotly_shap_violin_plot(X, shap_values, col_name, color_col=None, points=False, interaction=False): """ Returns a violin plot for categorical values. if points=True or color_col is not None, a scatterplot of points is plotted next to the violin plots. If color_col is given, scatter is colored by c...
03754df82272826965e73266075f3a0334620e93
31,472
def animation(): """ This function gives access to the animation tools factory - allowing you to access all the tools available. Note: This will not re-instance the factory on each call, the factory is instanced only on the first called and cached thereafter. :return: factories.Factor...
682cfe96f5682296ae721519be03aeb98b918e20
31,473
def merge(pinyin_d_list): """ :rtype: dict """ final_d = {} for overwrite_d in pinyin_d_list: final_d.update(overwrite_d) return final_d
512f551620ccedae8fb53f0c60f7caf931aae249
31,474
import subprocess def HttpPostRequest(url, post_dict): """Proceed an HTTP POST request, and returns an HTTP response body. Args: url: a URL string of an HTTP server. post_dict: a dictionary of a body to be posted. Returns: a response from the server. """ body = urlencode(post_dict) cmd = [GO...
59322ac0c7beff4ba71c2ec6ee3661c18ac0fb28
31,475
from typing import Dict from typing import Callable def nn_avg_pool2d(expr: Expr, params: Dict[str, np.ndarray], schedule: Schedule, net: Dict[Expr, Expr], op_idx: Dict[str, int], RELAY_2_XLAYER: Dict[str, Callable], ...
6da43b7927049af26be40f3c153dab2f319312e1
31,476
def dprnn_tasnet(name_url_or_file=None, *args, **kwargs): """ Load (pretrained) DPRNNTasNet model Args: name_url_or_file (str): Model name (we'll find the URL), model URL to download model, path to model file. If None (default), DPRNNTasNet is instantiated but no pretrained ...
cf3190656d9c24730d9bab1554987d684ec33712
31,477
def utcnow(): """Better version of utcnow() that returns utcnow with a correct TZ.""" return timeutils.utcnow(True)
a23cc98eca8e291f6e9aff5c0e78494930476f78
31,478
def build_profile(base_image, se_size=4, se_size_increment=2, num_openings_closings=4): """ Build the extended morphological profiles for a given set of images. Parameters: base_image: 3d matrix, each 'channel' is considered for applying the morphological profile. It is the spectral inf...
7f7cd0e1259cdd52cd4ce73c3d6eee9c9f87b474
31,479
def mujoco_env(env_id, nenvs=None, seed=None, summarize=True, normalize_obs=True, normalize_ret=True): """ Creates and wraps MuJoCo env. """ assert is_mujoco_id(env_id) seed = get_seed(nenvs, seed) if nenvs is not None: env = ParallelEnvBatch([ lambda s=s: mujoco_env(env_id, seed=s, s...
5bad4500be5261f33a19e49612ce62e1db8c66dd
31,480
import torch def polar2cart(r, theta): """ Transform polar coordinates to Cartesian. Parameters ---------- r, theta : floats or arrays Polar coordinates Returns ------- [x, y] : floats or arrays Cartesian coordinates """ return torch.stack((r * theta.cos(), ...
c13225a49d6435736bf326f70af5f6d4039091d8
31,481
def belongs_to(user, group_name): """ Check if the user belongs to the given group. :param user: :param group_name: :return: """ return user.groups.filter(name__iexact=group_name).exists()
e1b70b4771dfec45218078ca16335ddc3c6214e2
31,482
import torch def sum_log_loss(logits, mask, reduction='sum'): """ :param logits: reranking logits(B x C) or span loss(B x C x L) :param mask: reranking mask(B x C) or span mask(B x C x L) :return: sum log p_positive i over all candidates """ num_pos = mask.sum(-1) # B...
88a312f74e7d4dce95d8dcadaeeaa1a136fceca6
31,483
from acor import acor from .autocorrelation import ipce from .autocorrelation import icce def _get_iat_method(iatmethod): """Control routine for selecting the method used to calculate integrated autocorrelation times (iat) Parameters ---------- iat_method : string, optional Routine to use...
a5bbe3a4f4bad486f9bab6ca4b367040ce516478
31,484
def run(): """Main entry point.""" return cli(obj={}, auto_envvar_prefix='IMPLANT') # noqa
ae9e96478dbf081469052ff29d31873263060bff
31,485
def qtl_test_interaction_GxG(pheno, snps1, snps2=None, K=None, covs=None, test="lrt"): """ Epistasis test between two sets of SNPs Args: pheno: [N x 1] np.array of 1 phenotype for N individuals snps1: [N x S1] np.array of S1 SNPs for N individuals snps2: [N x S2] np.array of S2 S...
77eebc7c1c673562b1b793e9e5513b9a50aa6f1b
31,486
import copy import io def log_parser(log): """ This takes the EA task log file generated by e-prime and converts it into a set of numpy-friendly arrays (with mixed numeric and text fields.) pic -- 'Picture' lines, which contain the participant's ratings. res -- 'Response' lines, which contain the...
7793cb1b53100961aca5011655211b0da47af856
31,487
from typing import List def line_assign_z_to_vertexes(line_2d: ogr.Geometry, dem: DEM, allowed_input_types: List[int] = None) -> ogr.Geometry: """ Assign Z dimension to vertices of line based on raster value of `dem`. The values from `dem` are interp...
ae3e6c496cd10848e35830c1122a77589f322aad
31,488
def backoff_linear(n): """ backoff_linear(n) -> float Linear backoff implementation. This returns n. See ReconnectingWebSocket for details. """ return n
a3a3b3fc0c4a56943b1d603bf7634ec50404bfb3
31,489
import pkg_resources def _doc(): """ :rtype: str """ return pkg_resources.resource_string( 'dcoscli', 'data/help/config.txt').decode('utf-8')
e83f8a70b9d6c9cff38f91b980cd3f9031d84fd7
31,490
def sk_algo(U, gates, n): """Solovay-Kitaev Algorithm.""" if n == 0: return find_closest_u(gates, U) else: U_next = sk_algo(U, gates, n-1) V, W = gc_decomp(U @ U_next.adjoint()) V_next = sk_algo(V, gates, n-1) W_next = sk_algo(W, gates, n-1) return V_next @ W_next @ V_next.adjoint() @ W...
e8251d7a41899584f92c808af1d4fdee10757349
31,491
def get_movie_list(): """ Returns: A list of populated media.Movie objects """ print("Generating movie list...") movie_list = [] movie_list.append(media.Movie( title='Four Brothers', summary='Mark Wahlberg takes on a crime syndicate with his brothers.', trailer_yo...
e00f67b55a47bf13075a4b2065b94feec4138bcd
31,492
def check_dna_sequence(sequence): """Check if a given sequence contains only the allowed letters A, C, T, G.""" return len(sequence) != 0 and all(base.upper() in ['A', 'C', 'T', 'G'] for base in sequence)
2f561c83773ddaaad2fff71a6b2e5d48c5a35f87
31,493
def test_inner_scalar_mod_args_length(): """ Feature: Check the length of input of inner scalar mod. Description: The length of input of inner scalar mod should not less than 2. Expectation: The length of input of inner scalar mod should not less than 2. """ class Net(Cell): def __init__...
06bc7530106c5bf2f586e08ee2b941bd964228f1
31,494
import requests def zip_list_files(url): """ cd = central directory eocd = end of central directory refer to zip rfcs for further information :sob: -Erica """ # get blog representing the maximum size of a EOBD # that is 22 bytes of fixed-sized EOCD fields # plus t...
694f6340145d509e7a18aa7b427b75f521c389df
31,495
import torch import numpy import math def project_ball(tensor, epsilon=1, ord=2): """ Compute the orthogonal projection of the input tensor (as vector) onto the L_ord epsilon-ball. **Assumes the first dimension to be batch dimension, which is preserved.** :param tensor: variable or tensor :type ...
188eda46ede2b6ac08bc6fc4cfa72efb56e2918e
31,496
import os import base64 def decode_json(filepath="stocks.json"): """ Description: Generates a pathname to the service account json file needed to access the google calendar """ # Check for stocks file if os.path.exists(filepath): return filepath creds = os.environ.get("GOOGLE_SER...
095dabf2a397576289bf1754f4eae4406e6648c1
31,497
def load_model(filename): """ Loads the specified Keras model from a file. Parameters ---------- filename : string The name of the file to read from Returns ------- Keras model The Keras model loaded from a file """ return load_keras_model(__construct_path(file...
89656f682f1e754a08c756f0db49fc3138171384
31,498
import os def get_ffmpeg_executable_path(ffmpeg_folder_path): """ Get's ffmpeg's executable path for current system, given the folder. :param ffmpeg_folder_path: Folder path for the ffmpeg and ffprobe executable. :return: ffmpeg executable path as absolute path. """ return os.path.join(ffmpeg...
a309030dce3adc5e6252b915f6a48d540d64dee3
31,499