content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_current_user(): """Gets the current logged in user""" user = User.get_one_by_field('id', value=get_jwt_identity()) response = { 'name': user['name'], 'username': user['username'], } return jsonify(response)
ad5df5b9360b92f9cca9b5591ddb76eb67c814b8
5,700
import time def create_kv_store(vm_name, vmdk_path, opts): """ Create the metadata kv store for a volume """ vol_meta = {kv.STATUS: kv.DETACHED, kv.VOL_OPTS: opts, kv.CREATED: time.asctime(time.gmtime()), kv.CREATED_BY: vm_name} return kv.create(vmdk_path, v...
d2f14ca7f0ead2baca68db3fb62b0fcce83425cb
5,701
def mapdict(itemfunc, dictionary): """ Much like the builtin function 'map', but works on dictionaries. *itemfunc* should be a function which takes one parameter, a (key, value) pair, and returns a new (or same) (key, value) pair to go in the dictionary. """ return dict(map(itemfunc, diction...
1f0573410f82acb1f3c06029cf4bfaccd295e1ac
5,702
import logging def get_backup_temp(): """ This is the function for if the BMP280 malfunctions """ try: temp = BNO055.temperature logging.warning("Got backup temperature") return temp except RuntimeError: logging.error("BNO055 not connected") return get_backu...
5a573f72ea05889bc0fe48c6b896311423f3c6f1
5,703
from typing import Counter def density_matrix(M, row_part, col_part): """ Given a sparse matrix M, row labels, and column labels, constructs a block matrix where each entry contains the proportion of 1-entries in the corresponding rows and columns. """ m, n = M.shape if m <= 0 or n <= 0: r...
542c6dab2c987902825056f45dd51517446bc6de
5,704
def isAddressInMyAddressBookSubscriptionsListOrWhitelist(address): """ Am I subscribed to this address, is it in my addressbook or whitelist? """ if isAddressInMyAddressBook(address): return True queryreturn = sqlQuery( '''SELECT address FROM whitelist where address=?''' '''...
05c7ed302e5edd070b26d3a04e3d29072c6542c8
5,705
from datetime import datetime def GetDateTimeFromTimeStamp(timestamp, tzinfo=None): """Returns the datetime object for a UNIX timestamp. Args: timestamp: A UNIX timestamp in int or float seconds since the epoch (1970-01-01T00:00:00.000000Z). tzinfo: A tzinfo object for the timestamp timezone or Non...
c3f224c300c3c1b497d16b92facd8118534e446f
5,706
def success(parsed_args): """ :param :py:class:`argparse.Namespace` parsed_args: :return: Nowcast system message type :rtype: str """ logger.info( f"FVCOM {parsed_args.model_config} {parsed_args.run_type} run boundary condition " f'file for {parsed_args.run_date.format("YYYY-MM-...
448dda23f35d450049673a41c8bc9042e9387e8c
5,707
def _kv_to_dict(kv_string): """ Simple splitting of a key value string to dictionary in "Name: <Key>, Values: [<value>]" form :param kv_string: String in the form of "key:value" :return Dictionary of values """ dict = {} if ":" not in kv_string: log.error(f'Keyvalue parameter not i...
5afe7272ec97a69ee8fb18e29e0fda062cfc0152
5,708
from typing import List def get_column_names(df: pd.DataFrame) -> List[str]: """Get number of particles from the DataFrame, and return a list of column names Args: df: DataFrame Returns: List of columns (e.g. PID_xx) """ c = df.shape[1] if c <= 0: raise IndexError("...
f935d2db8cca04141305b30bb4470f7a6c96012e
5,709
def get_default(schema, key): """Get default value for key in voluptuous schema.""" for k in schema.keys(): if k == key: if k.default == vol.UNDEFINED: return None return k.default()
7a3963984ddbfaf38c75771115a31cfbbaa737e3
5,710
import sys def get_font_loader_class(): """Get the font loader associated to the current platform Returns: FontLoader: specialized version of the font loader class. """ if "linux" in sys.platform: return FontLoaderLinux if "win" in sys.platform: return FontLoaderWindows ...
5b5d9b19ae852b5e3fffac89c609067932836c65
5,711
def _map_tensor_names(original_tensor_name): """ Tensor name mapping """ global_tensor_map = { "model/wte": "word_embedder/w", "model/wpe": "position_embedder/w", "model/ln_f/b": "transformer_decoder/beta", "model/ln_f/g": "transformer_decoder/gamma", } if origina...
3331d13e667ee3ef363cdeca5122e8a256202c39
5,712
from clawpack.visclaw import geoplot from numpy import linspace from clawpack.visclaw.data import ClawPlotData from numpy import mod from pylab import title from pylab import ticklabel_format, xticks, gca from pylab import plot import os from clawpack.visclaw import plot_timing_stats def setplot(plotdata=None): #----...
caad86086eb60a83bf9634a326d18f154487785b
5,713
def test_skeleton(opts): """ Template of unittest for skeleton.py :param opts: mapping parameters as dictionary :return: file content as string """ template = get_template("test_skeleton") return template.substitute(opts)
99afb92b3cb2054bf85d62760f14108cabc2b579
5,714
def get_classpath(obj): """ Return the full module and class path of the obj. For instance, kgof.density.IsotropicNormal Return a string. """ return obj.__class__.__module__ + "." + obj.__class__.__name__
bf986e2b27dd8a216a2cc2cdb2fb2b8a83b361cc
5,715
import json def bill_content(bill_version: str) -> str: """ Returns the bill text, broken down by the way the XML was structured Args: bill_version (str): bill_version_id used as a fk on the BillContent table Returns: str: String json array of bills """ results = get_bill_con...
3bb5ce368a9d789e216926f41dad8c858fd2858c
5,716
def has_default(column: Column) -> bool: """Column has server or Sqlalchemy default value.""" if has_server_default(column) or column.default: return True else: return False
d2b0a3d3bdd201f9623c2d9d5587c5526322db54
5,717
import statistics def iterations_median(benchmark_result): """A function to calculate the median of the amount of iterations. Parameters ---------- benchmark_result : list of list of list of namedtuple The result from a benchmark. Returns ------- numpy.ndarray A 2D array ...
9f758ec3777303e0a9bddaa2c4f6bd3b48a47bcc
5,718
def _make_list(input_list, proj_ident): """Used by other functions, takes input_list and returns a list with items converted""" if not input_list: return [] output_list = [] for item in input_list: if item is None: output_list.append(None) elif item == '': output_...
188bd9cb5d8afdce2ce58326376bc1c71627142c
5,719
import os def monthly_ndvi(): """Get monthly NDVI from MOD13C2 products.""" mod13c2_dir = os.path.join(DATA_DIR, 'raw', 'MOD13C2') months = [m for m in range(1, 13)] cities = [city.id for city in CASE_STUDIES] ndvi = pd.DataFrame(index=cities, columns=months) for city, month in product(CASE_ST...
9be57a809576db720ba562640f7040d822e4212a
5,720
def dvds_s(P, s): """ Derivative of specific volume [m^3 kg K/ kg kJ] w.r.t specific entropy at constant pressure""" T = T_s(P, s) return dvdT(P, T) / dsdT(P, T)
4eeb3b50c9347ea34bb6cc781001da61cef2d638
5,721
from typing import Tuple def serialize(_cls=None, *, ctor_args: Tuple[str, ...] = ()): """Class decorator to register a Proxy class for serialization. Args: - ctor_args: names of the attributes to pass to the constructor when deserializing """ global _registry def wrapped(cls): ...
e79e93569c17f09f156f19a0eb92b326ffbb0f83
5,722
import subprocess def runcmd(args): """ Run a given program/shell command and return its output. Error Handling ============== If the spawned proccess returns a nonzero exit status, it will print the program's ``STDERR`` to the running Python iterpreter's ``STDERR``, cause Python to exit ...
bd7ea3e7c86992d5051bc3738769e37c5443f46e
5,723
def get_as_by_asn(asn_): """Return an AS by id. Args: asn: ASN """ try: as_ = Asn.get_by_asn(asn_) except AsnNotFoundError as e: raise exceptions.AsnDoesNotExistException(str(e)) return as_
7e102894db3ca65795ec3097c3ca4a80e565666b
5,724
def spoken_form(text: str) -> str: """Convert ``text`` into a format compatible with speech lists.""" # TODO: Replace numeric digits with spoken digits return _RE_NONALPHABETIC_CHAR.sub(" ", text.replace("'", " ")).strip()
a816cf64e198b41c75ee4bfe1327c22ed309f340
5,725
def get_default_group_type(): """Get the default group type.""" name = CONF.default_group_type grp_type = {} if name is not None: ctxt = context.get_admin_context() try: grp_type = get_group_type_by_name(ctxt, name) except exception.GroupTypeNotFoundByName: ...
c7077d9dbf90d2d23ac68531c703a793f714f90a
5,726
from typing import Any from typing import Optional def toHVal(op: Any, suggestedType: Optional[HdlType]=None): """Convert python or hdl value/signal object to hdl value/signal object""" if isinstance(op, Value) or isinstance(op, SignalItem): return op elif isinstance(op, InterfaceBase): re...
291ee67b2f3865a4e8bda87c9fd5e2efc098362f
5,727
from typing import Dict from typing import Any def _make_readiness_probe(port: int) -> Dict[str, Any]: """Generate readiness probe. Args: port (int): service port. Returns: Dict[str, Any]: readiness probe. """ return { "httpGet": { "path": "/openmano/tenants",...
d12f9b91a35a428b9a3949bcfe507f2f84e81a95
5,728
def compute_embeddings_and_distances_from_region_adjacency(g,info, metric='euclidean', norm_type = 2, n_jobs=1): """ This method runs local graph clustering for each node in the region adjacency graph. Returns the embeddings for each node in a matrix X. Each row corresponds to an embedding of a node in ...
324b3b282f87c10a0438130a2d30ad25af18a7ec
5,729
import shlex def _parse_assoc(lexer: shlex.shlex) -> AssociativeArray: """Parse an associative Bash array.""" assert lexer.get_token() == "(" result = {} while True: token = lexer.get_token() assert token != lexer.eof if token == ")": break assert token =...
f62c23880972e860c5b0f0d954c5526420ef0926
5,730
def get_addon_by_name(addon_short_name): """get Addon object from Short Name.""" for addon in osf_settings.ADDONS_AVAILABLE: if addon.short_name == addon_short_name: return addon
f59b2781343ea34abeaeb5f39b32c3cb00c56bb4
5,731
def _normpdf(x): """Probability density function of a univariate standard Gaussian distribution with zero mean and unit variance. """ return 1.0 / np.sqrt(2.0 * np.pi) * np.exp(-(x * x) / 2.0)
62088f218630155bbd81f43d5ee78345488d3e57
5,732
def scalar_mult(x, y): """A function that computes the product between complex matrices and scalars, complex vectors and scalars or two complex scalars. """ y = y.to(x) re = real(x) * real(y) - imag(x) * imag(y) im = real(x) * imag(y) + imag(x) * real(y) return to_complex(re, im)
3ab2eaa8a969684e52b3b38922027e39741197d7
5,733
import random def train_trajectory_encoder(trajectories): """ Train a fixed neural-network encoder that maps variable-length trajectories (of states) into fixed length vectors, trained to reconstruct said trajectories. Returns TrajectoryEncoder. Parameters: trajectories (List of np.nd...
83e3557841269cde9db969d3944ccccae5c4cb45
5,734
def flatten_list(x): """Flatten a nested list. Parameters ---------- x : list nested list of lists to flatten Returns ------- x : list flattened input """ if isinstance(x, list): return [a for i in x for a in flatten_list(i)] else: return [x]
409fc5ee2244426befab9d4af75ba277d5237208
5,735
def check_vpg_statuses(url, session, verify): """ Return a list of VPGs which meet the SLA and a list of those which don't """ good, bad = [], [] for vpg in get_api(url, session, "vpgs", verify): name = vpg['VpgName'] status = vpg_statuses(vpg['Status']) if status == vpg_s...
0c3623c89a6879e398f5691f8f8aa0933c055c76
5,736
def get_hits(adj_matrix, EPSILON = 0.001): """[summary] hubs & authorities calculation Arguments: adj_matrix {float[][]} -- [input Adjacent matrix lists like [[1, 0], [0, 1]] Keyword Arguments EPSILON {float} -- [factor of change comparision] (default: {0.001}) Returns: ...
ad9037247e95360e96b8ff4c8ed975d5e0a1f905
5,737
def quicksort(seq): """ seq is a list of unsorted numbers return a sorted list of numbers """ ##stop condition: if len(seq) <= 1: return seq ##get the next nodes and process the current node --> call the partition else: low, pivot, high = partition(seq) ## s...
943b13185ebfe6e44d0f927f9bf6a3a71130619a
5,738
import time import sys import traceback def scan_resource( location_rid, scanners, timeout=DEFAULT_TIMEOUT, with_timing=False, with_threading=True, ): """ Return a tuple of: (location, rid, scan_errors, scan_time, scan_results, timings) by running the `scanners` Scanner objects...
6309b2d91d39137949fce6f9fe34c9b0a5e90402
5,739
import numpy as np def label_generator(df_well, df_tops, column_depth, label_name): """ Generate Formation (or other) Labels to Well Dataframe (useful for machine learning and EDA purpose) Input: df_well is your well dataframe (that originally doesn't have the intended label) df_tops is your label dataf...
16336d8faf675940f3eafa4e7ec853751fd0f5d0
5,740
def tclexec(tcl_code): """Run tcl code""" g[TCL][REQUEST] = tcl_code g[TCL][RESULT] = tkeval(tcl_code) return g[TCL][RESULT]
c90504b567390aa662927e8549e065d1c98fcc40
5,741
import os def cleanFiles(direct, CWD=os.getcwd()): """ removes the year and trailing white space, if there is a year direct holds the file name for the file of the contents of the directory @return list of the cleaned data """ SUBDIR = CWD + "output/" # change directory to ouput folder co...
2a16037ef15d547af8c1b947d96747b2b2d62fd1
5,742
def test_labels(test_project_data): """A list of labels that correspond to SEED_LABELS.""" labels = [] for label in SEED_LABELS: labels.append(Label.objects.create(name=label, project=test_project_data)) return labels
9f7477fa313430ad0ca791037823f478327be305
5,743
def unravel_index_2d(indices, dims): """Unravel index, for 2D inputs only. See Numpy's unravel. Args: indices: <int32> [num_elements], coordinates into 2D row-major tensor. dims: (N, M), dimensions of the 2D tensor. Returns: coordinates: <int32> [2, num_elements], row (1st) and column (2nd) indic...
e7de01de80ba39a81600d8054a28def4dd94f564
5,744
def np_xcycwh_to_xy_min_xy_max(bbox: np.array) -> np.array: """ Convert bbox from shape [xc, yc, w, h] to [xmin, ymin, xmax, ymax] Args: bbox A (tf.Tensor) list a bbox (n, 4) with n the number of bbox to convert Returns: The converted bbox """ # convert the bbox from [xc, yc, w, ...
382230768efc625babc8d221a1984950fd3a08eb
5,745
def wmedian(spec, wt, cfwidth=100): """ Performs a weighted median filtering of a 1d spectrum Operates using a cumulative sum curve Parameters ---------- spec : numpy.ndarray Input 1d spectrum to be filtered wt : numpy.ndarray A spectrum of equal length as the input array to p...
2642238419c6c503a8369a8c16464c74180db9c9
5,746
import subprocess def execute_command(cmd, logfile): """ Function to execute a non-interactive command and return the output of the command if there is some """ try: rows, columns = subprocess.check_output(["stty", "size"]).decode().split() child = pexpect.spawn( "/bin/...
8553b5b8010353fe28b00d1fbca79b6ee229ec6b
5,747
def _read(filename, format=None, **kwargs): """ Reads a single event file into a ObsPy Catalog object. """ catalog, format = _read_from_plugin('event', filename, format=format, **kwargs) for event in catalog: event._format = format return catalog
1489d72bacb445d8101d7e4b599c672359680ce5
5,748
def compute_encrypted_key_powers(s, k): """ Compute the powers of the custody key s, encrypted using Paillier. The validator (outsourcer) gives these to the provider so they can compute the proof of custody for them. """ spower = 1 enc_spowers = [] for i in range(k + 2): enc_spow...
d7654018501096eebcc7b4dfa50f342a5522c528
5,749
def idiosyncratic_var_vector(returns, idiosyncratic_var_matrix): """ Get the idiosyncratic variance vector Parameters ---------- returns : DataFrame Returns for each ticker and date idiosyncratic_var_matrix : DataFrame Idiosyncratic variance matrix Returns ------- i...
fd7d1344f4e5941c4f9d239a0eaf2a6cac088973
5,750
def get_ticker_quote_type(ticker: str) -> str: """Returns the quote type of ticker symbol Parameters ---------- ticker : str ticker symbol of organization Returns ------- str quote type of ticker """ yf_ticker = yf.Ticker(ticker) info = yf_ticker.info return...
7f105789d88591f240e753df104bb7428eef5f74
5,751
def sensitivity_score(y_true, y_pred): """ Compute classification sensitivity score Classification sensitivity (also named true positive rate or recall) measures the proportion of actual positives (class 1) that are correctly identified as positives. It is defined as follows: ...
bb09213eca5a6696e92ebafa204975bc3e6e2f7b
5,752
def wrap_compute_softmax(topi_compute): """Wrap softmax topi compute""" def _compute_softmax(attrs, inputs, out_type): axis = attrs.get_int("axis") return [topi_compute(inputs[0], axis)] return _compute_softmax
3a5e3843f77d8bdfefc0f77b878f135aac4896f6
5,753
from typing import Any import requests def post(url: str, **kwargs: Any) -> dict: """Helper function for performing a POST request.""" return __make_request(requests.post, url, **kwargs)
37a4b7c7128349248f0ecd64ce53d118265ed40e
5,754
import pandas as pd import os def vote92(path): """Reports of voting in the 1992 U.S. Presidential election. Survey data containing self-reports of vote choice in the 1992 U.S. Presidential election, with numerous covariates, from the 1992 American National Election Studies. A data frame with 909 observat...
1d08d8087b7ced665399011986b27c92d3f96140
5,755
def csr_full_col_slices(arr_data,arr_indices,arr_indptr,indptr,row): """ This algorithm is used for when all column dimensions are full slices with a step of one. It might be worth it to make two passes over the array and use static arrays instead of lists. """ indices = [] data = [] for i,...
bf5684a4b54988a86066a78d7887ec2e0473f3a9
5,756
def slide_period(scraping_period, vacancies): """Move upper period boundary to the value equal to the timestamp of the last found vacancy.""" if not vacancies: # for cases when key 'total' = 0 return None period_start, period_end = scraping_period log(f'Change upper date {strtime_from_unixt...
fc7654835270cf78e7fb3007d0158c565717cf47
5,757
def merge_to_many(gt_data, oba_data, tolerance): """ Merge gt_data dataframe and oba_data dataframe using the nearest value between columns 'gt_data.GT_DateTimeOrigUTC' and 'oba_data.Activity Start Date and Time* (UTC)'. Before merging, the data is grouped by 'GT_Collector' on gt_data and each row on gt...
0c9bc4269127f063fca3e0c52b677e4c44636b7d
5,758
def returnDevPage(): """ Return page for the development input. :return: rendered dev.html web page """ return render_template("dev.html")
d50134ebc84c40177bf6316a8997f38d9c9589fb
5,759
def toeplitz(c, r=None): """Construct a Toeplitz matrix. The Toeplitz matrix has constant diagonals, with ``c`` as its first column and ``r`` as its first row. If ``r`` is not given, ``r == conjugate(c)`` is assumed. Args: c (cupy.ndarray): First column of the matrix. Whatever the actual s...
d8d9246a766b9bd081da5e082a9eb345cd40491b
5,760
import os def download_private_id_set_from_gcp(public_storage_bucket, storage_base_path): """Downloads private ID set file from cloud storage. Args: public_storage_bucket (google.cloud.storage.bucket.Bucket): google storage bucket where private_id_set.json is stored. storage_base_path...
05c29687c1c2350510e95d6d21de3ac3130c25f9
5,761
def matmul_op_select(x1_shape, x2_shape, transpose_x1, transpose_x2): """select matmul op""" x1_dim, x2_dim = len(x1_shape), len(x2_shape) if x1_dim == 1 and x2_dim == 1: matmul_op = P.Mul() elif x1_dim <= 2 and x2_dim <= 2: transpose_x1 = False if x1_dim == 1 else transpose_x1 t...
ee485178b9eab8f9a348dff7085b87740fac8955
5,762
def Align4(i): """Round up to the nearest multiple of 4. See unit tests.""" return ((i-1) | 3) + 1
16ff27823c30fcc7d03fb50fe0d7dbfab9557194
5,763
def poggendorff_parameters(illusion_strength=0, difference=0): """Compute Parameters for Poggendorff Illusion. Parameters ---------- illusion_strength : float The strength of the line tilt in biasing the perception of an uncontinuous single line. Specifically, the orientation of the lin...
22647299bd7ed3c126f6ac22866dab94809723db
5,764
from typing import List from typing import Tuple def download_blobs(blobs: List[storage.Blob]) -> List[Tuple[str, str]]: """Download blobs from bucket.""" files_list = [] for blob in blobs: tmp_file_name = "-".join(blob.name.split("/")[1:]) file_name = blob.name.split("/")[-1] tmp...
e2ea0f373f6097a34e1937944603456d52771220
5,765
def testMarkov2(X, ns, alpha, verbose=True): """Test second-order Markovianity of symbolic sequence X with ns symbols. Null hypothesis: first-order MC <=> p(X[t+1] | X[t], X[t-1]) = p(X[t+1] | X[t], X[t-1], X[t-2]) cf. Kullback, Technometrics (1962), Table 10.2. Args: x: symbolic sequen...
15200c720eecb36c9d9e6f2abeaa6ee2f075fd3f
5,766
import aiohttp import json async def send_e_wechat_request(method, request_url, data): """ 发送企业微信请求 :param method: string 请求方法 :param request_url: string 请求地址 :param data: json 数据 :return: result, err """ if method == 'GET': try: async with aiohttp.ClientSession() ...
e7bd7c4bcfd7a890733f9172aced3cd25b0185d4
5,767
def no_missing_terms(formula_name, term_set): """ Returns true if the set is not missing terms corresponding to the entries in Appendix D, False otherwise. The set of terms should be exactly equal, and not contain more or less terms than expected. """ reqd_terms = dimless_vertical_coordinates[f...
4edafafc728b58a297f994f525b8ea2dc3d4b9aa
5,768
import torch def initialize(X, num_clusters): """ initialize cluster centers :param X: (torch.tensor) matrix :param num_clusters: (int) number of clusters :return: (np.array) initial state """ num_samples = X.shape[1] bs = X.shape[0] indices = torch.empty(X.shape[:-1], device=X.de...
a704daf3997202f4358bb9f3fbd51524fee4afe5
5,769
def unflatten_satisfies(old_satisfies): """ Convert satisfies from v2 to v1 """ new_satisfies = {} for element in old_satisfies: new_element = {} # Handle exsiting data add_if_exists( new_data=new_element, old_data=element, field='narrative' ...
aba5e1f8d327b4e5d24b995068f8746bcebc9082
5,770
def require_backend(required_backend): """ Raise ``SkipTest`` unless the functional test configuration has ``required_backend``. :param unicode required_backend: The name of the required backend. :returns: A function decorator. """ def decorator(undecorated_object): @wraps(undecorat...
859ca429466962ebba30559637691daf04940381
5,771
import os def clip(src, shp): """ :param src: shapefile class with karst polygons. sinks.shp in db. :param shp: shapefile class with basin boundary. :return: shapefile output and class with karst. """ driver = ogr.GetDriverByName("ESRI Shapefile") src_ds = driver.Open(src.path, 0) sr...
427512487b73dd77ac420418bcace2b7693ca9bc
5,772
def fixed_data(input_df, level, db_name): """修复日期、股票代码、数量单位及规范列名称""" # 避免原地修改 df = input_df.copy() df = _special_fix(df, level, db_name) df = _fix_code(df) df = _fix_date(df) df = _fix_num_unit(df) df = _fix_col_name(df) return df
9a56115c210403a01d5ce39ec6596d217a8d4cd9
5,773
def get_nsg_e(ocp: AcadosOcp): """ number of slack variables for linear constraints on terminal state and controls """ return int(ocp.constraints.idxsg_e.shape[0])
0e69fc188dd7812748cf5b173b7cc187a187b125
5,774
def generate_test_samples(y, input_seq_len, output_seq_len): """ Generate all the test samples at one time :param x: df :param y: :param input_seq_len: :param output_seq_len: :return: """ total_samples = y.shape[0] input_batch_idxs = [list(range(i, i + input_seq_len+output_seq_l...
cc849695598ac77b85e0209439ca8034844968fa
5,775
import re from bs4 import BeautifulSoup def get_tv_torrent_torrentz( name, maxnum = 10, verify = True ): """ Returns a :py:class:`tuple` of candidate episode Magnet links found using the Torrentz_ torrent service and the string ``"SUCCESS"``, if successful. :param str name: the episode string on which to...
48d67a36b3736c26d188269cc3308b7ecdd1ecb4
5,776
def errfunc(p, x, y, numpoly, numharm): """ function to calc the difference between input values and function """ return y - fitFunc(p, x, numpoly, numharm)
1b075b08668656dcf2a395545d4af2f5ff36508f
5,777
def create_token_column(col): """ Creates a cleaned and tokenised column based on a sentence column in a dataframe """ # Convert it to lowercase col = col.str.lower() # Remove all non-alphanumeric characters col = col.replace(r"\W", " ", regex=True) # Collapse repeated spaces ...
71f798e176ae3a0c407e5c9cae50d699cb99db4b
5,778
def get_browser(request, ): """ 获取浏览器名 :param request: :param args: :param kwargs: :return: """ ua_string = request.META['HTTP_USER_AGENT'] user_agent = parse(ua_string) return user_agent.get_browser()
3cc6322baf3969e8d1936ccf8bd4f3d6bb423a5f
5,779
def predict(X, centroids, ccov, mc): """Predict the entries in X, which contains NaNs. Parameters ---------- X : np array 2d np array containing the inputs. Target are specified with numpy NaNs. The NaNs will be replaced with the most probable result according to the GMM model p...
043046623022346dcda9383fa416cffb59875b30
5,780
def rotate_image(img, angle): """ Rotate an image around its center # Arguments img: image to be rotated (np array) angle: angle of rotation returns: rotated image """ image_center = tuple(np.array(img.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle...
649cdf9870ac31bd6bb36708417f0d9e6f0e7214
5,781
def standardize_1d(self, func, *args, autoformat=None, **kwargs): """ Interpret positional arguments for the "1D" plotting methods so usage is consistent. Positional arguments are standardized as follows: * If a 2D array is passed, the corresponding plot command is called for each column of data ...
332bb996cdd6d9991b64c42067110ec11ecb358b
5,782
def build_transformer_crf_model(config): """ """ src_vocab_size = config["src_vocab_size"] src_max_len = config["src_max_len"] n_heads = config["n_heads"] d_model = config["d_model"] d_ff = config["d_ff"] d_qk = config.get("d_qk", d_model//n_heads) d_v = config.get("d_v", d_model//n...
e95e0ff30b450c3e55c4a38762cb417c8cbea5a5
5,783
def frac_mole_to_weight(nfrac, MM): """ Args: nfrac(np.array): mole fraction of each compound MM(np.array): molar mass of each compound """ return nfrac * MM / (nfrac * MM).sum()
8e9fce630e3bf4efbd05956bea3708c5b7958d11
5,784
from datetime import datetime def get_close_hour_local(): """ gets closing hour in local machine time (4 pm Eastern) """ eastern_tz = timezone('US/Eastern') eastern_close = datetime.datetime(year=2018, month=6, day=29, hour=16) eastern_close = eastern_tz.localize(eastern_close) return str...
9a0b1256864e028a6cccda7465da0f0e4cc3a009
5,785
def parse_structure(node): """Turn a collapsed node in an OverlayGraph into a heirchaical grpah structure.""" if node is None: return None structure = node.sub_structure if structure is None: return node.name elif structure.structure_type == "Sequence": return {"Sequence" : [parse_structure(n) f...
f9374ff9548789d5bf9b49db11083ed7a15debab
5,786
import torch def softmax_kl_loss(input_logits, target_logits, sigmoid=False): """Takes softmax on both sides and returns KL divergence Note: - Returns the sum over all examples. Divide by the batch size afterwards if you want the mean. - Sends gradients to inputs but not the targets. """ ...
8faaee09947dca5977744b3f9c659ad24d3377e8
5,787
def cut_rod_top_down_cache(p, n): """ Only difference from book is creating the array to n+1 since range doesn't include the end bound. """ r = [-100000 for i in range(n + 1)] return cut_rod_top_down_cache_helper(p, n, r)
36b35ec560fea005ae49950cf63f0dc4f787d8d0
5,788
def column_ids_to_names(convert_table, sharepoint_row): """ Replace the column ID used by SharePoint by their column names for use in DSS""" return {convert_table[key]: value for key, value in sharepoint_row.items() if key in convert_table}
6ae1474823b0459f4cf3b10917286f709ddea520
5,789
def recursive_olsresiduals(res, skip=None, lamda=0.0, alpha=0.95, order_by=None): """ Calculate recursive ols with residuals and Cusum test statistic Parameters ---------- res : RegressionResults Results from estimation of a regression model. skip : int, defau...
36e74d41920d3c176365c753bcf6cfae6e6cd20d
5,790
def is_RationalField(x): """ Check to see if ``x`` is the rational field. EXAMPLES:: sage: from sage.rings.rational_field import is_RationalField as is_RF sage: is_RF(QQ) True sage: is_RF(ZZ) False """ return isinstance(x, RationalField)
7ab6b67eb666ae85456d48f1b79e180634252066
5,791
def add_nearest_neighbor_value_field(ptype, coord_name, sampled_field, registry): """ This adds a nearest-neighbor field, where values on the mesh are assigned based on the nearest particle value found. This is useful, for instance, with voronoi-tesselations. """ field_name = ("deposit", f"{pty...
a0078a3baf1ff9525c4445225ca334609ded7e24
5,792
def create_directory_if_not_exists(dir_path): """ Create directory path if it doesn't exist """ if not path_exists(dir_path): mkdir_p(dir_path) print('Creating {}'.format(dir_path)) return True return False
2eb62dbfb180e82296f8aba66e528bf749f357db
5,793
def rdkit_smiles(): """Assign the SMILES by RDKit on the new structure.""" new_smiles = "" mol = Chem.MolFromMolFile("output.sdf") new_smiles = Chem.MolToSmiles(mol, isomericsmiles=False) return new_smiles
10de3f05bb4b6edefabe28134deae4371cc2cd2a
5,794
def load_ref_case(fname, name): """Loads PV power or Load from the reference cases :param fname: Path to mat file :type fname: string :param name: Identifier for PV Power or Load :type name: string :return: Returns PV power or load from the reference case :rtype: numpy array """ ...
fc03fa8f9ef2070d2a6da741579f740fa85fa917
5,795
import uuid def make_unique_id(): """Make a new UniqueId.""" return uuid.uuid4() # return UniqueId(uuid.uuid4())
c7ab0e5242a954db75638b3193609d49f0097287
5,796
import gzip def read_uni(filename): """ Read a '*.uni' file. Returns the header as a dictionary and the content as a numpy-array. """ with gzip.open(filename, 'rb') as bytestream: header = _read_uni_header(bytestream) array = _read_uni_array(bytestream, header) return header, a...
c930d4dd8de9c5da10a4e31be6b987cc4f0f25ac
5,797
def _F(startmat,endmat): """Calculate the deformation tensor to go from start to end :startmat: ndarray :endmat: ndarray :returns: ndarray """ F=np.dot(endmat,np.linalg.inv(startmat)) return F
2a357d55e0f73c6f827c35ab72673f6b42875129
5,798
from typing import OrderedDict import logging def get_docstrings(target, functions): """ Proceses functions in target module and prompts user for documentation if none exists. :param target: Loaded target python module :param functions: List of defined functions in target module :returns: Dict contai...
98bc2e4267415e74b70a5342115d4dcabfbefcba
5,799