content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def message(**properties): """Convenience to create a proton.Message with properties set""" m = Message() for name, value in dict_iteritems(properties): getattr(m, name) # Raise exception if not a valid message attribute. setattr(m, name, value) return m
b34a01f6c20dba44f7d05c8bdfc7ba733726f689
79,937
def replace_url_el(url: str, props: PropertySet, allow_no_schema=False) -> str: """ Replaces all EL variables in the url, validates schema and returns the url. """ url_with_var = replace_el_with_var(url, props=props, quote=False) if not is_allowed_schema(allow_no_schema, url_with_var): raise...
59a012da7cfb902c26addb807b5f97e9827819b8
79,938
def dist(p,q): """ Calculates the distance between the points p and q. Parameters --------- p : Point the first point q : Point the second point Returns ---------- Float The distance between the points p and q. """ return (sum((p.array()-q.array())*...
97c0beb7f8c22e59da9551e35e66a7d8e39bf667
79,939
import six import random import numpy def predictive_columns(M_c, X_L, X_D, columns_list, optional_settings=False, seed=0): """ Generates rows of data from the inferred distributions Inputs: - M_c: crosscat metadata (See documentation) - X_L: crosscat metadata (See documentation) - X_D: crosscat metadata (See...
a4731b0f3c7ce8882b83b7cb06c7eaf92c389ed4
79,940
from datetime import datetime def datetimeformat(date_str: str) -> str: """日付フォーマット変更 Args: date_str (str): 時刻文字列(YYYY-MM-DD HH:mm:ss+hh:mmZ) Returns: str: 変換後時刻文字列 """ if not isinstance(date_str, datetime.datetime): return "-" dt = arrow.get(date_str) local = dt...
5f3e94fbd9b306cbb68cad8dfba229753f90bd5d
79,941
import array def analytical_value_k_ejr2(distr1, distr2, u, par1, par2): """ Analytical value of the Jensen-Renyi kernel-2. Parameters ---------- distr1, distr2 : str-s Names of distributions. u : float, >0 Parameter of the Jensen-Renyi kernel-2 (alpha = 2: fixe...
864a232568fece4a9c598a39d7998eae2f7ed0ee
79,942
def _to_system(sab): """Converts an SAB to a system. Args: sab: a UMLS source name abbreviation Returns: the identity of the terminology system """ return _SAB_TO_SYSTEM.get(sab, 'http://www.nlm.nih.gov/research/umls/%s' % sab.lower())
8cd05f19aef06ddbf9f5b0f7735d08334634a3b2
79,943
def _shorten_ops(a, b): """Shorten two ops by the part that cancels each other out.""" len_a = _op_len(a) len_b = _op_len(b) if len_a == len_b: return (None, None) if len_a > len_b: return (_shorten(a, len_b), None) return (None, _shorten(b, len_a))
1000f89c0b9464aacaa2516bc4547da7e452f3fd
79,944
from datetime import datetime def makedatetimestamp(t): """Like util.makedate() but for time t instead of current time""" delta = (datetime.datetime.utcfromtimestamp(t) - datetime.datetime.fromtimestamp(t)) tz = delta.days * 86400 + delta.seconds return t, tz
5126eac899a323475262dbdf07d82edc0d4f7469
79,945
def reward_binary_goal_based(navenv): """ Reward of 1 is given when close enough to the goal. """ curpos = navenv.current_pos if (dist(curpos, navenv.goalPos) <= navenv.goalRadius): return 1. else: return 0.
036cfc6b173d8581fb0e17bef3b6356f50de8fed
79,946
def sync_synchronize(repository_id, user_id=None, manual=False): """ Run all tasks for a repository, to be called from scheduler """ auth.s3_impersonate(user_id) rtable = s3db.sync_repository query = (rtable.deleted != True) & \ (rtable.id == repository_id) repository = db(...
b9ee37505ab2b42f4520fe9c9d32f33f642b3d7e
79,947
import uuid def _generate_id() -> str: """Generate the image identifier. Returns: The image identifier as a string. """ hw = hw_info.HWInfo() return ('%s-%s' % (str(hw.BiosSerial()), str(uuid.uuid4())[:7])).upper()
968eed7b8eff293141b96cec40a76418fb3f2d72
79,948
def build_feature_summary(data, information_level, feature_description, missing_values, generate_excel=False): """ Build new dataset describing each column more precisely to support decision making and analytics All columns from the main dataset is merged datasets `information levels` and `feature desc...
48ea2c0aedaebcb59ff0500a12af201056b35543
79,949
from datalad.consts import DATASETS_TOPURL def get_datasets_topdir(): """Delayed parsing so it could be monkey patched etc""" return RI(DATASETS_TOPURL).hostname
a2cf782729855ba087d125b4d51844d553a2c5e0
79,950
def create_min_ndvi_mosaic(dataset_in, clean_mask=None, no_data=-9999, dtype=None, intermediate_product=None, **kwargs): """ Method for calculating the pixel value for the min ndvi value. Parameters ---------- dataset_in: xarray.Dataset A dataset retrieved from the Data Cube; should contain...
61cd2934f3faac6b781af0dd0b46b9d0d3e506dd
79,951
def compute_binary_classification_loss(scores, labels, weight): """ Compute classification loss :param scores Shape=[batch_size] :param labels Shape=[batch_size] :param weight Shape=[batch_size] """ # Binary classification loss return tf.compat.v1.losses.sigmoid_cross_entropy(logits=tf.expa...
3a2112ec6cb66fb5a9eccdd5ba04dcd9a191a892
79,953
def bulk_lag_estimate(y, shift, x=None, poly=None, log=False): """Create estimates for a specific time horizon for an entire data frame. No missing values permitted. Args: y (pandas.DataFrame): a dataframe where each row is a time period and each column is a metric to be predicted. shift (...
cd90704bc89971d5fb9a1dd1452373ad80c7fa6f
79,954
def check_is_executable(program): """Check whether a program is executable. Parameters ---------- program : str Program name. Returns ------- str Human-readable message. """ check_message = '%s is executable...' % program return result_message(_is_executable(pr...
233828b81f8dd634178b2d98ed008ff0f2f70121
79,955
import traceback def request(path): """Send a request to a given URL accepting JSON format and return a \ deserialized Python object. If no "http://" protocol is specified, \ BASE_URL is used in the request. Args: path (str): The URI to be requested. Returns: response: Deserial...
e913060238abcf6508ffd03fd95f393e40932b41
79,956
def parse_transformers(transformers): """ Parse the list of transformers, given by configuration, into a list of tuple of the transformers name and a dictionary containing additional args. The transformer is assumed to be of the form 'name/arg1=value/arg2=value' :raw_transformers: list of strings ...
7812f9929d75c1e6b496821eb0566ead2f57f812
79,957
def try_int(text, default=0): """Try to parse an integer but return a default if it fails.""" try: return int(text) except ValueError: return default
b699bbd7209a88e1df3d2b941d581904bf30e737
79,958
from typing import IO from typing import Any from typing import Sequence import struct def read_bytes_as_tuple(f: IO[Any], fmt: str) -> Sequence[Any]: """Read bytes using a `struct` format string and return the unpacked data values. Parameters ---------- f : IO[Any] The IO stream to read byte...
b2622d5aad02c528163cb3318b5c70ea0510ea01
79,959
def mask_to_signal(lst): """将持仓蒙板转化为交易信号. 转换的规则为比较前后两个交易时间点的持仓比率,如果持仓比率提高, 则产生相应的补仓买入信号;如果持仓比率降低,则产生相应的卖出信号将仓位降低到目标水平。 生成的信号范围在(-1, 1)之间,负数代表卖出,正数代表买入,且具体的买卖信号signal意义如下: signal > 0时,表示用总资产的 signal * 100% 买入该资产, 如0.35表示用当期总资产的35%买入该投资产品,如果 现金总额不足,则按比例调降买入比率,直到用尽现金。 ...
cd541c9afbc65c584dace4e2fd64c7056869d235
79,960
import json def extract_request_from_record(record): """extract refresh credential request from record""" payload = json.loads(record['body']) request = RefreshCredentialRequest(**payload) if not request.email: request.email = common.find_user_tag(iam_client, request.user_name,'IamRotateCreden...
50e985f221685f7a8707e56df22f12c56b94b3aa
79,961
import re def getLevelFromServerProps(): """Search the server props file for the configured security level""" pattern = r"RoutesSecurityLevel=(\d+)" file = open(CONF_FILE, "r") for line in file: result = re.match(pattern, line) if result: return int(result.group(1))
c0f043df6afa274b83c4c369c836afaed17f5f82
79,963
def find_silver_token(angle,length): """ Function to find the closest silver token Returns: dist (float): distance of the closest silver token (-1 if no silver token is detected) rot_y (float): angle between the robot and the silver token (-1 if no silver token is detected) """ #angle signifies the a...
4ff3a52769c8a02381a206cd581a8277de4c9694
79,965
def clean_record(rec: list, field_names: list) -> dict: """ Parses the record supplied by the calling function and returns a dictionary that can be transformed into a database record. :param rec: record extracted from file :ptype rec: list :param field_names: field names for the record :pty...
a76974cb8f7e12aec80404df85b90001df2a69f4
79,966
import warnings def train_segmentor(model, dataset, cfg, distributed=False, validate=False, timestamp=None, meta=None, compression_ctrl=None, val_dataloader=N...
5e6f14bf214e54c00db49a701946c86d18e8748d
79,968
def virtual(func: "callable"): """ mark a function as "virtual", which means that this function can be override. any base class should use this or @abstractmethod to decorate all functions that can be (re)implemented by subclasses. """ return func
46b31f828c19c3288028eb485bfe78795c632148
79,969
def get_template(template: str) -> Template: """Read template from file :param template: path to template :return: Template """ template_file_content: str = read_file(template) return Template(template_file_content)
38b1046cb9097d1dbe419385e520d53bf2ff09c8
79,970
import asyncio async def main(argv: list[str]): """Restart a KNX device.""" if len(argv) != 2: print(f"{argv[0]}: missing target address.") return 1 address = IndividualAddress(argv[1]) xknx = XKNX() await xknx.start() await xknx.telegrams.put(Telegram(address, payload=Resta...
47614d167e8901bd1092efac6c75a2315f8a84bf
79,971
import re def _get_changelist(perforce_str): """Extract change list from p4 str""" rx = re.compile(r'Change: (\d+)') match = rx.search(perforce_str) if match is None: v = 'UnknownChangelist' else: try: v = int(match.group(1)) except (TypeError, IndexError): ...
26b08d8ccf6251e0d3a9698147093e2bb6e89919
79,972
from pycsw.plugins.profiles.apiso.apiso import APISO def caps2iso(record, caps, context): """Creates ISO metadata from Capabilities XML""" apiso_obj = APISO(context.model, context.namespaces, context) apiso_obj.ogc_schemas_base = 'http://schemas.opengis.net' apiso_obj.url = context.url queryable...
83e1f460a956b5de2231a8e8eab39bfc9c4db6f1
79,973
def get_top_k_trigrams(poi_gdf, names, k): """ Creates a features array. Firstly, the top *k* % trigrams among *names* \ are considered (e.g. a set of trigrams *T*). Then, for each poi *p* (each \ row) the array will contain 1 (True) in column *c*, if trigram *T[c]* \ appears in *p*'s name. Arg...
bea2046ae61e7fd2e4907ec81f903b5336e659b0
79,974
def read_recs(con, tbl, q="", qwhere="", qorder=""): """ Read recs matching where clause. con: sqlite connection tbl: table name qwhere: sql where clause """ if qwhere == "": qwhere = "1" if qorder == "": qorder = "_id" if not tbl in all_tables(con): return [] ...
60d7a4a82bd54c3d2b7dfc81d46c888cb17442ce
79,975
def LoadEcgPipeline(batch_size=20, annot_ext="pu1"): """Preprocessing pipeline for Hidden Markov Model. This pipeline prepares data for ``hmm_train_pipeline``. It works with dataset that generates batches of class ``EcgBatch``. Parameters ---------- batch_size : int Number of samples i...
65c746f95dd74140b5d8034d776089a94f74ea42
79,976
async def me(request: web.Request, auth: SpotifyAuth) -> web.Response: """View to show the authorized user's Spotify user information""" response = await request.app["spotify_app"]["spotify_client"].request( request.app["client_session"], auth, "/me" ) # Don't forget to update the authorization...
1f223c9c95a53b059ae29444e02581a886b41cdd
79,978
def parse_step_id_from_sacct(output, step_name): """Parse and return the step id from a sacct command :param output: output of sacct --noheader -p --format=jobname,jobid --job <alloc> :type output: str :param step_name: the name of the step to query :type step_name: str :retu...
2ed06aba82665ad2a42c12a39c589d10258883f4
79,979
def parse_namespace_uri(uri): """Get the prefix and namespace of a given URI (without identifier, only with a namspace at last position). :param str uri: URI :returns: prefix (ex: http://purl.org/dc/terms/...) :returns: namespace (ex: .../isPartOf) :rtype: tuple[str,str] """ # Split the uri...
9d883db067720cfa37eeec2d986a84506e6aaff8
79,981
def validate_course_policy(module_store, course_id): """ Validate that the course explicitly sets values for any fields whose defaults may have changed between the export and the import. Does not add to error count as these are just warnings. """ # is there a reliable way to get the module loca...
5725d03bd3b3823f0c6dc6f5d6d4a1cb94692420
79,982
def best_fit_decreasing_no_overload(last_n_vm_cpu, hosts_cpu, total_threshold_cpu, hosts_ram, total_threshold_ram, inactive_hosts_cpu, inactive_hosts_ram, vms_cpu, vms_ram, cpu_weight, ram_weight, overload_threshold): "...
d34ffae2eb0904a46f2e396cb64f2fa07c887081
79,983
def cors_header(func): """ @cors_header decorator adds CORS headers """ @wraps(func) def wrapper(self, request, *args, **kwargs): res = func(self, request, *args, **kwargs) request.setHeader('Access-Control-Allow-Origin', '*') request.setHeader('Access-Control-Allow-Headers', 'Conte...
b7900d771f0c6c9ef088873f9fc28a3b235a319c
79,984
import array def qpoases_solve_qp(P, q, G=None, h=None, A=None, b=None, initvals=None, verbose=False, max_wsr=1000): """ Solve a Quadratic Program defined as: .. math:: \\begin{split}\\begin{array}{ll} \\mbox{minimize} & \\frac{1}{2} x^T P x + q^T x \\\\ ...
3e8143d68337735ae76ab605c0c0ec9fbd46d4bc
79,985
def verify_input_data(function): """ Check that all input data is present in JSON file for each step :param function: function to populate ui :return: None """ def check(*args): try: function(*args) except ValueError: msg = "Please verify that integer numb...
8374d14e3db687c9013aeabfd41f22fbbd4a8851
79,987
def detectLanguage(pathToFile): """ Detects the language of a code file (based on the extension) Parameters: pathToFile - The path to the file Returns: language - The language used in the file """ try: assert isinstance(pathToFile, str) except AssertionError: ...
2f690fa942c5f90d1c56fe6c6ce117a3fd1115b1
79,988
def t_test_p_value(sample1, sample2): """ Performs pairwise t-test for computing the p-value given two samples""" if(len(sample1) > 1 and len(sample2 > 1)): res = stats.ttest_rel(sample1, sample2) return res.pvalue else: return 1.0
93044f0f196b2cff03fd6311349a1b4aa8d67bd6
79,989
def drop_observations( dataset: timeseries.MultiRegionDataset, filter_: Filter ) -> timeseries.MultiRegionDataset: """Drops observations according to `filter_` from every region in `dataset`.""" assert filter_.drop_observations # wide-dates DataFrames that will be concat-ed to produce the result MultiR...
1bda28828eed99df3700470b2feb8c3ecda73b5e
79,990
def read_stock(ticker: str, folder_path: str) -> pd.DataFrame: """ Function that read the history of a stock from the stocks folder. @param ticker: ticker to read the data from. @folder_path: folder of the stocks. @return: df with the data. """ try: df_stock = pd.read_csv(folder_pat...
e566710808ea88ad9de36b1972fa4f072145fad3
79,992
def snapshot(self, label, snap_type='statevector'): """Take a snapshot of the internal simulator representation (statevector) Works on all qubits, and prevents reordering (like barrier). Args: label (str): a snapshot label to report the result snap_type (str): a snapshot type (only supports...
cb7f1b7d8013c08092e8acf3ff98bd405e52801d
79,994
def to_hpr(dcm): """Convert a direction cosine matrix to heading, pitch and roll angles. The returned heading is within [0, 360], the pitch is within [-90, 90] and the roll is within [-90, 90]. If ``90 - abs(pitch) < np.rad2deg(1e-3)`` then the roll is set to 0 and the heading is computed accordin...
13415b2f5f06a94d3f4274788e6d9302d8c05046
79,995
def InverseStudentT(degree_of_freedom, probability): """Inverse of Student's T distribution CDF. Returns the value x such that CDF(x) = probability. Ported from Java: http://jsci.sourceforge.net/ This is not the best algorithm in the world. SciPy has a Fortran version (see special.stdtrit): http:/...
de8ef2075f814ea2fe39159a025d308454d1357c
79,996
def init_seq(VCFFileName, maxskip=100, name=None): """Open a (gzipped) VCF4.1 file. Try to open the given VCF file, checks if it is in VCF format. Initialize a :class:`VCFStream` object that contains the first base. Please close the associated file object with :func:`VCFStream.close` when you ...
db35f9c404c6cc7a0ae1e3c58f3df817e2bd2ad0
79,998
def prism_layer( coordinates, surface, reference, properties=None, ): """ Create a layer of prisms of equal size Build a regular grid of prisms of equal size on the horizontal directions with variable top and bottom boundaries and properties like density, magnetization, etc. The fun...
f0a003544e722ad33c72b29431c928d8b05d88f4
79,999
import pickle def loadPop(filename="popSaved045_long.dat"): """ Loads a saved population """ fin=open(filename,'r') b=pickle.load(fin) fin.close() return b
712408bdc6f8bc354db399287e298ccf4010df30
80,000
def extract_items(topitems_or_libraryitems): """ Extracts a sequence of items from a sequence of TopItem or LibraryItem objects. """ seq = [] for i in topitems_or_libraryitems: seq.append(i.item) return seq
6a6918b4fc8153f4c98f5df906ce584422b3df78
80,001
def lda(): """LDA vectorizer.""" return [LDAVectorizer()]
2bf6e1f0a688eeb40e285617b4afc5eff1eab8a7
80,002
def morphAnnList(AIs,winCounterList): """ Takes the top half of the ANNs and gives them 2 children each. """ surviving = findTheMostFit(AIs,winCounterList) new_generation_ann = [] for ann_nr in surviving: for child_nr in range(2): child = AIs[ann_nr].spawnChild() ...
bf72efb08143687beb0af5115b278f5fb44e0cb7
80,003
def construct_federated_getitem_call(arg, idx): """Constructs computation building block passing getitem to federated value. Args: arg: Instance of `computation_building_blocks.ComputationBuildingBlock` of `computation_types.FederatedType` with member of type `computation_types.NamedTupleType` from...
afaca4648975b207eed88ca8ee85e63ab84c2130
80,004
import pdb import torch def cal_si_snr(source, estimate_source, source_lengths=None): """Calculate SI-SNR with PIT training. Args: source: [B, C, T], B is batch size estimate_source: [B, C, T] source_lengths: [B], each item is between [0, T] """ pdb.set_trace() assert sourc...
f1e4ed6474868a3da2fd6ad16564cf962c0f37f0
80,005
def match_candidates_by_time(images, exifs, max_neighbors, use_capture_time=True): """Find candidate matching pairs by time difference.""" if max_neighbors <= 0: return set() k = min(len(images), max_neighbors + 1) times = np.zeros((len(images), 1)) for i, image in enumerate(images): ...
ce85e8a87ac43f43bca71a81de98692be8c56d9e
80,006
def city_data(): """The data for the one and only `City` object as a `dict`.""" return { 'id': 1, 'name': 'Paris', 'kml': "<?xml version='1.0' encoding='UTF-8'?> ...", 'center_latitude': 48.856614, 'center_longitude': 2.3522219, 'northeast_latitude': 48.9021449, ...
346e067ecb48e8f3c56eb0834af92a78867ce9f5
80,007
def start_data_service(): """ Get application of data :return: APPLICATION FLASK """ logger.info("Start data service") return DATA_SERVICE.run(host=env.DATA_SERVICE_ADD, port=env.DATA_SERVICE_PORT)
8cba9185d154e80ec9dafd1cca0435c48f07fbb9
80,008
def combine_translations(accept_language, domain="nbjs"): """Combine translations for multiple accepted languages. Returns data re-packaged in jed1.x format. """ lang_codes = parse_accept_lang_header(accept_language) combined: dict = {} for language in lang_codes: if language == "en": ...
e182418a68728f0071b0ffed2f2cfa6a107543d8
80,009
def print_model(text: str = '', model: ModelType = []): """ It prints sqlmodel responses for complex relationship models. """ return print(text, jsonable_encoder(model))
048bf63e19d6d421e15237b7b852c8770047b8eb
80,010
def gaussin(nsigma=1): """FRACTION WITHIN nsigma""" return erf(nsigma / sqrt(2))
3372b4fdccfc2ee4a895f55bc06487a496f937ac
80,011
def get_custom_module_description(name): """Return string with description for custom modules.""" return "Custom module from corpus directory ({}.py).".format(name.split(".")[1])
647e2df266a25b888558c34b4d425e09b0f58ca1
80,012
def _showcompatlist( context, mapping, name, values, plural=None, separator=b' ' ): """Return a generator that renders old-style list template name is name of key in template map. values is list of strings or dicts. plural is plural of name, if not simply name + 's'. separator is used to join v...
a0e717c645aa00a8dd239a435cdec42593d58411
80,013
def _current_groups(request, authority): """ Return a list of the groups the current user is a member of. This list is meant to be returned to the client in the "session" model. """ user = request.user svc = request.find_service(name="group_list") groups = svc.session_groups(user=user, aut...
ca21c322eadc01c21478c96a61ca608e620b61b2
80,015
def evaluate_hist_multi_x_multi_y_product(x, row, bins, vals, derivs=None): #pragma: no cover """ Evaluate a set of values from histograms Parameters ---------- x : array_like (npts) X values to interpolate at row : array_like (npdf, 1) Which rows to interpolate at bins : a...
14ee6bbd94d21ee8dfdc5e0554d816c5e0cfc83f
80,016
def get_pixdist_ratio(m_size, ant_rad): """Get the ratio between pixel number and physical distance Returns the pixel-to-distance ratio (physical distance, in meters) Parameters ---------- m_size : int The number of pixels used along one-dimension for the model (the model is assume...
b307ee5da49b9cd92958aa6d94c4e3ffa860bf1d
80,017
def sstrip(s, suffix): """Suffix strip >>> sstrip('foo.oof', '.oof') 'foo' >>> sstrip('baroof', '.oof') 'baroof' """ i = - len(suffix) if s[i:] == suffix: return s[:i] return s
7f4d0f118caa48d68ae826813b65e3d452c2c1e8
80,018
def affine_map( T, P, t=None , get_inverse=True): """ Returns the affine map of a polytope. """ if type(t)==type(None): t=np.zeros((T.shape[0],1)) if P.type=='AH_polytope': return pp.AH_polytope(t=t+np.dot(T,P.t),T=np.dot(T,P.T),P=P.P) elif P.type=='zonotope': ...
47af53524b50d8e468151074c393b0c3ff99a51b
80,019
def make_view(robot): """ 为一个 BaseRoBot 生成 Django view。 :param robot: 一个 BaseRoBot 实例。 :return: 一个标准的 Django view """ assert isinstance(robot, BaseRoBot),\ "RoBot should be an BaseRoBot instance." def werobot_view(request): timestamp = request.GET.get("timestamp", "") ...
2c3f51a10bff6f31640bc28ea30ef79c215e3ce0
80,020
def play_action_logic(): """ Executes an action for the current player in the game and accordingly updates the state of the game. The action is passed as an argument to the application call. :return: """ position_index = Btoi(Txn.application_args[1]) state_x = App.globalGet(AppVariables.Pla...
c2111c72c09c2136d768cdf10fdd0dea42f54d6e
80,022
def usersitedata_update(user_id, site_id, data=None): # noqa: E501 """usersitedata_update # noqa: E501 :param user_id: A UUID value identifying the user. :type user_id: dict | bytes :param site_id: A unique integer value identifying the site. :type site_id: int :param data: :type dat...
9946334f73974d7adc6f50e3fab40590dc03c405
80,023
def median_absolute_error(y_true, y_pred): """ Returns the median absolute error. Parameters ---------- y_true : array_like The correct targets. y_pred : array_like The estimated targets. Returns ------- float The median absolute error. """ y_true, y...
06510ce4276828af2000c8a8e83a9014051f4cfe
80,024
def bottleneck_block(filters, init_strides=1, is_first_block_of_first_layer=False): """bottleneck blocks for use on resnets with layers > 34. Follows improved proposed scheme in http://arxiv.org/pdf/1603.05027v2.pdf """ def f(input): if is_first_block_of_first_layer: # don't repeat ...
f28b7ad6d095feba37a8f141d37067fd7238b620
80,026
def add_test(args=list(), solutions=list()): """ Adds a new `TestCase` object to `tests` for function `fn` with paramaters `args` and expected return values `solutions`. """ def wrap(fn): global tests new_test = TestCase(fn, args, solutions) tests = tests >> new_test if te...
9c076294b808019946adff9ae3b03627828fb2f2
80,027
def get_processed_mnist_data(group_size, class0=0, class1=1): """Creates a set of bags, each containing a number of samples and the proportion of a certain label in that bag. The propotion is the number of class1 items in the bag, divided by the total number of items in the bag. Keyword arguments: group_si...
cf7c8af70f0cbec62b4cb1a693dcb30fca12bd76
80,028
import pyarrow as pa def to_arrow_type(dt): """ Convert Spark data type to pyarrow type """ if type(dt) == BooleanType: arrow_type = pa.bool_() elif type(dt) == ByteType: arrow_type = pa.int8() elif type(dt) == ShortType: arrow_type = pa.int16() elif type(dt) == Integer...
18146e22dde47ef014b26fb32424e94af3127145
80,029
def to_int(domain: Domain) -> int: """ Convert Domain to big endian int since sigp/milagro_bls use big endian int on hash to g2. """ return int.from_bytes(domain, "big")
66bc5131205e22bef8e4d5b5c2e3566cf37990a1
80,030
from datetime import datetime def rpt_tickets_partner(): """Lista os items do Relatorio agrupando por tipo e com count decrescente""" report_set = db.session.query(ServiceTicket.id_partner, func.count(ServiceTicket.id).label("Total")).filter(ServiceTicket.id_partner != 0).\ group_by(Se...
9ba75f65d0b2b87492f0a8f62db1e54f5aecf9c0
80,031
def __dive(state_machine, state_index, character_n, passed_state_list, CharacterToCount): """Once the distance to the acceptance state is determined, we store it in a cache database. Note, that the distance is only stored after all possible pathes starting from the state have been investigated. Note a...
cb7123f48279661f7f4721a5c2c9a106eb03ec70
80,032
import colorsys def colorPalette(path, view, max_number_of_colors, hue_separation, sq, vq, space): """ Generates a color palette for an image. Args: path (str): Path to the image. view (bool): Choice to view the color palette. max_number_of_colors (int): The maximum number of colors ...
655609f7a6e6622eb2ae88165959022a47c5b40b
80,033
import textwrap def wrap_string(data, width=40, indent=32, indentAll=False, followingHeader=None): """ Print a option description message in a nicely wrapped and formatted paragraph. followingHeader -> text that also goes on the first line """ data = str(data) if len(data) > width: ...
4e983e4116058da1fa263e65aa3516a275d89001
80,034
def initial(x, idx): """ Get first value of series. """ if idx is None: return x.iloc[0] return x.iloc[idx.start or 0]
28d364329af3f579868807773efb8a074e2c3cb5
80,035
def _potential_sadpt(evals, ethresh=0.3): """ Determine points on a 1D-grid that could correspond to a saddle point """ # Determine the idxs for all of the local extrema loc_max, loc_min = _local_extrema(evals) # Find min1-max-min2 triplets for each local maxima final_idx = len(evals) -...
5b8e63ec7377f4f3d1a139c79614a9193c0b9dfd
80,036
def zeros_like(t: Tensor): """ Return zero-tensor with the same shape as the input tensor. ## Parameters t: `Tensor` - input parameter ## Example usage ```python from beacon.tensor import Tensor from beacon.tensor import functinos as fn t = Tensor([1, 2, 3]) x = fn.zeros_like(t...
a26832f09dac69497efe2a89bc1544e9318738ee
80,037
import logging import pickle def load_cached_mode(s, l, m, n): """Read a KerrSpinSeq from disk. Path is determined by :meth:`mode_pickle_path(s, l, m, n)`. Parameters ---------- s: int Spin-weight of field of interest. l: int Multipole number of mode. l >= angular.l_min(s, m) ...
57d20a6d878df556c58f64a913cfb50af56f4286
80,038
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.layers import LSTM from tensorflow.keras.constraints import NonNeg def create_lstm(train_shape: tuple, depth: int=1, n_nodes: int=10, loss='mse', compilation_kwargs={}): """ Helper fu...
708f5d907cf28e31c283d3f2fe6d4b4f722c59e3
80,039
def _quote(filename, protect = "="): """Quote the filename, by escaping = by \\= and \\ by \\""" return filename.replace("\\", "\\\\").replace(protect, "\\" + protect)
649d27f261ce37601ab432699885fb346df23931
80,040
import six def create_hkl_group(py_obj, h_group, call_id=0): """ Create a new group within the hickle file Args: h_group (h5.File.group): group to dump data into. call_id (int): index to identify object's relative location in the iterable. """ h_subgroup = h_group.create_group('data_...
eb0b79503dbfb224b65e5080df14978dd6051329
80,041
def precompute_size_scattering(J, Q, max_order=2, detail=False): """Get size of the scattering transform The number of scattering coefficients depends on the filter configuration and so can be calculated using a few of the scattering transform parameters. Parameters ---------- J : int ...
9549e35605943416323e63369535e88643df1e5c
80,042
def _get_pole(ds): """returns the first pole we find in the dataset""" pol_names = ["rotated_latitude_longitude", "rotated_pole"] for pol in pol_names: if pol in ds: return ds[pol] return None
c9969287a87c1e0c43aee02c407f5ee06fac9169
80,043
import torch def _conjugate_gradient(f_Ax, b, cg_iters, residual_tol=1e-10): """Use Conjugate Gradient iteration to solve Ax = b. Demmel p 312. Args: f_Ax (callable): A function to compute Hessian vector product. b (torch.Tensor): Right hand side of the equation to solve. cg_iters (in...
ab8aa89ae15bef9214dbecfcff2b587993d550f9
80,044
def _applyColormap(colormap, values, minVal=None, maxVal=None, clip=True): """ Converts an array (values) to a rgba array. :param colormap: An Xsocs2DColormap instance :param values: Values to convert to color values. :param...
16580a22eaa410b63622c7d38d2da47bb7bb2e9e
80,045
def supplierMetafieldsUpdate(supplierId): """ Update supplier metafield mapping. :param supplierId: The supplier id. """ supplierId = escape(supplierId) supplier = None if supplierId in thk.suppliers: supplier = thk.suppliers[supplierId] unsuccessful_count = 0 successful_co...
ab4f5b3200e7d2881af38e3ef39fb2501105c7bb
80,046
def expectation(q, weights=None): """ the expectation (or expected value or first moment) refers, to the value of a random variable one would "expect" to find if one could repeat the random variable process an infinite number of times and take the average of the values obtained. Formally, the ex...
cdc12eb10f3aa8ddcd7008b702bc8dd8782b02e9
80,047
def get_repo_auth_string(user, password): # type: (Text, Text) -> Text """ Return user:password only if user and password are valid :param user: username :param password: :return: URL authentication string """ if not (user and password): return "" return ":".join(map(quote, (...
f61df0793c517325761299ab241960af3b076919
80,050
import time import json def sendemail(request): """ 发邮件 :param request: :return: """ data='' if request.method=='GET': #获取当前周 year_week= int(time.strftime("%W"))+1 #获取当前session id try: pid=request.session.get('id') except: dat...
db20b38acccc75d3138f96871abc286606d798cc
80,051