content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def build_table_schema(data, index=True, primary_key=None, version=True): """ Create a Table schema from ``data``. Parameters ---------- data : Series, DataFrame index : bool, default True Whether to include ``data.index`` in the schema. primary_key : bool or None, default True ...
bb84be571d2e151285099a9a1f2c44b93427cced
3,601,387
def remove_non_ascii(s): """ Remove non-ascii characters in a file. Needed when support for non-ASCII is not available. Args: s (str): Input string Returns: String with all non-ascii characters removed. """ return "".join(i for i in s if ord(i) < 128)
0a215ffa1841667d7dd7d9c1d9a12bbe84e2cbcd
3,601,389
def gaussian_z(covar): """Single-dimensional Gaussian PDF normalizing coefficient. Args: covar (scalar): Covariance of the Gaussian PDF Returns: float: Normalizing coefficient Z """ return np.sqrt(2.0 * np.pi * covar)
3691a37f5925cf2c12c54e8a31649ad09ece0297
3,601,390
def _hoeffding_interval(sample: np.ndarray, ref_size, c, delta, mode) -> float: """ A helper function calculates the concentration interval using Hoeffding inequality. No assumptions over the sampled distribution. Parameters ---------- sample : np.ndarray Sample data ref_size : (int...
a51e72a3ac6fd14ce6469a670e5982727add3d3e
3,601,391
def animation_make(year_range, save_name = None, approx=10): """ Makes an animation for the given diagram. Optionally, it saves Parameters ---------- year_range : TYPE DESCRIPTION. save_name : TYPE, optional DESCRIPTION. The default is None. approx : TYPE, optional S...
67076212eed0c989b0f2b8bd824f2548dbadbbc7
3,601,392
def get_acis_fp_limits(states, acis_s=-111.0, acis_i=-112.0): """ Get ACIS Focal Plane limits based on SIM position. This function uses SIM position to assign temperature limits. Args: states (ndarray): States array, in the form returned by the cmd_states.get_cmd_states.fetch_states function ...
ae7aca016d8af77dae3c8c079c12ca3577cc81e9
3,601,393
from functools import reduce def compose(fns, x=nil): """Takes a set of functions and returns a fn that is the composition of those fns. The returned fn takes a variable number of args, applies the rightmost of fns to the args, the next fn (left-to-right) to the result, etc. If no value is supplied, returns a s...
56952b8e7d653355e138844ce91ea8db9d9c3b30
3,601,394
def fuzzy_match(s, choices, score_cutoff=80): """Fuzzy match string to list of possible values. Based on http://pbpython.com/excel-pandas-comp.html """ m = process.extractOne(s, choices=choices, score_cutoff=score_cutoff) if m: return m[0] else: return nan
2165bdce5cba5612d4aebcc47444cd68043149d9
3,601,395
def handle_formula_data(Y, X, formula, depth=0): """ Returns endog, exog, and the model specification from arrays and formula Parameters ---------- Y : array-like Either endog (the LHS) of a model specification or all of the data. Y must define __getitem__ for now. X : array-lik...
38081650b99d1b917c6d986e6fc3ab2b9a8cd0b7
3,601,396
def draw_animation_layers(app, current_frame, img): """ Draw animation layers :param app: generator app context :param current_frame: array with number of current frames :param img: target image :return: new image and states array """ config = app.config state = [False, False, False,...
f6bc4f8a59f3c108ab1182f76b959a05a7dbcef9
3,601,397
def generate_streak_matrix(weeks_data): """ Create the streak matrix 1 if the user committed 0 if the user hasn't committed -1 to store null values :param weeks_data: week-wise contribution data of the user :return: matrix containing the values of the contribution streak """...
e6cc9e3c96aebb20ca8af11ae19e7f86aab96d62
3,601,398
def any_in_seq(search_vals, seq): """Check if any value in search_vals in the sequence seq""" for v in search_vals: if v in seq: return True return False
d314355aef2cba89833394ff6aeacf675daec7e6
3,601,399
from typing import List from typing import Tuple import itertools def get_direction_permutations(number_of_particles: int) -> List[Tuple[Direction, Direction]]: """ Returns all the possible direction permutations that can be obtained from a certain number of particles >>> perms = get_direction_permutations(2...
d441b742281490d01b3925475c29d9a47f9932df
3,601,400
def weeks_splitting_general(time1,data_list): """ Input: time1: 1d numpy array, machine time since 1970 data_list: list of several 1d numpy arrays Output: unique_weeks_per_year: [[unique weeks for year1],..[unique weeks for year n],...] times_per_week_per_year: [[times per week for...
f4638ca0571bc419ad3e0484f74d20a28ad6fc39
3,601,401
def fnrgf( smap, radial_bin_edges, order, attenuation_coefficients, ratio_mix=[15, 1], scale=None, intensity_summary=np.nanmean, intensity_summary_kwargs={}, width_function=np.std, width_function_kwargs={}, application_radius=1 * u.R_sun, number_angular_segments=130, ): ...
36b160caa3fe18d06f795c84a3d5276148ff5fe6
3,601,403
def response(status, response_def): """ Define a single response for the given handler. You can define multiple responses for the given handler by using this decorator multiple times. """ def decorator(fn): # pylint: disable=missing-docstring meta = RouteMeta.load(fn) meta.set_resp...
f8f5142ec7b4dde85a881b0f9262b5245d0832e4
3,601,404
import torch def pseudo_beta_fn(aatype, all_atom_positions, all_atom_mask): """Create pseudo beta features.""" is_gly = torch.eq(aatype, rc.restype_order["G"]) ca_idx = rc.atom_order["CA"] cb_idx = rc.atom_order["CB"] pseudo_beta = torch.where( torch.tile(is_gly[..., None], [1] * len(is_gl...
2dcdf505a5e8a2d13d9fa0c0a4729ac057252ab7
3,601,405
def split_code_at_show(text): """ Split code at plt.show() """ parts = [] is_doctest = contains_doctest(text) part = [] for line in text.split("\n"): if (not is_doctest and line.strip() == 'plt.show()') or \ (is_doctest and line.strip() == '>>> plt.show()'): ...
a2676e233ac73bbb59061d264022fcace8406e87
3,601,406
def repr_value(value): """ Represent a value in human readable form. For long list's this truncates the printed representation. :param value: The value to represent. :return: A string representation. :rtype: basestring """ if isinstance(value, list) and len(value) > REPR_LIST_TRUNCATION...
7541117982db6552202c70ca998fdd6618278521
3,601,407
def parse_test_list(test_list): """Parse user provided test list into internal format for test_runner. Args: test_list: A list of test classes/cases. """ result = [] for elem in test_list: result.append(_parse_one_test_specifier(elem)) return result
ad239514d30e9587684a804ccf672239b708d50f
3,601,408
def date2season(dt): """converts datetime to season like 2008/2009""" y = dt.year if dt.month <= 6: return "%s/%s" % (y - 1, y) else: return "%s/%s" % (y, y + 1)
e8653264fb682c0c2e5ceeb0548f513e0af0eb33
3,601,409
def asHash(mobj): """Return a given hashCode for `mobj`, without caching it This can be helpful in case you wish to synchronise `cmdx` with a third-party library or tool and wish to guarantee that an identical algorithm is used. """ handle = om.MObjectHandle(mobj) return handle.hashCode()
fe8dd0c0934ae942d3a2b118add75cc5ab657224
3,601,410
import numpy import scipy def _c2g(timeaxis,coft): """ Converts correlation function to lineshape function Explicit numerical double integration of the correlation function to form a lineshape function. Parameters ---------- timeaxis : cu.oqs.time.TimeAxis TimeAxis of the correlatio...
6ce3d260a0de1228e523fa69943b07922e7e1b17
3,601,412
def Run(benchmark_spec): """Measure the sql performance in one VM. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects with the benchmark results. """ vm = benchmark_spec.vms[0] return hammerd...
84a4d5a487759d4aff617c4bfb65dcade1d10f42
3,601,413
def limit(self, *args, **kwargs): """ Calls :meth:`.Table.limit` on each table in the TableSet. """ return self._proxy('limit', *args, **kwargs)
40b22ac87d582d6e245bb3ed2ba6d60766ec0870
3,601,414
from datetime import datetime def time_activation_domain(url): """Return time (in days) of domain activation.""" if url['host'].startswith("www."): url['host'] = url['host'][4:] pythonwhois.net.socket.setdefaulttimeout(3.0) try: result_whois = pythonwhois.get_whois(url['host'].lower()...
d048ae3ea00f419d84ceeb930540a0dc3efa6b3f
3,601,415
def basic_cleaners(text): """Basic pipeline that lowercases and collapses whitespace without transliteration.""" text = lowercase(text) text = collapse_whitespace(text) return text
f9d9f102396128d8e8a6ca53b3356bf06395f172
3,601,416
import json def get_json_file(path): """ Load a JSON file from disk. """ with open(path) as f: data = json.load(f) return data
acb099868c4baeb59ead76bb20018af477720609
3,601,417
def demask(data_masked, masks): """ Fills the masked data with zeros. Args: data_masked: `float` of shape `[N_filtered, C]`, masks: `bool`of shape `[N]`. Returns: `float` of shape `[N, C]`. """ C = tf.shape(data_masked)[-1] masks = tf.reshape(masks, [-1]) shape = [tf.shape(masks)[0], C] ids ...
6507aea30dcddab22fbfeb075f24cdb647a3284f
3,601,418
import dateutil def _parse_common_date(date_str): """ :type date_str: str :rtype: struct_time or None """ if date_str: return dateutil.parser.parse(date_str) return None
d4e1f26d66ed711dc7df9c199fdfc32f9b32709e
3,601,419
def can_use_slay(user_id): """Return true if the user can use the command "slay" Characters that can slay: - All characters (to allow for fake claiming) """ return True
f8be6bd59c1c8bb8acb12d164c7b452c6ede1308
3,601,420
def make_parts(text, encoding=consts.SMPP_ENCODING_DEFAULT): """Returns tuple(parts, encoding, esm_class)""" try: # Try to encode with the user-defined encoding first. encode, split_size, part_size = ENCODINGS[encoding] encoded_text = encode(text) except KeyError: raise NotIm...
f1231a75c96cf0600216f0bc4f4379ac0fe94fa2
3,601,421
def cloud_eval(fen, **kwargs): """Wrapper for the `GET api/cloud-eval <https://lichess.org/api#operation/apiCloudEval>`_ endpoint.""" kwargs["fen"] = fen return _api_get("/api/cloud-eval", kwargs)
af8feccaaf528a3a3e51b1f283da17b63000260a
3,601,422
def get_emojis(): """Retrieves hundreds of emoji glyphs derived from the UTF-8 character table. Examples: >>> moji = get_emojis()\n >>> moji[1540:1547]\n '🤠 🤡 🤢 🤣' """ emoji_list_1 = [chr(i) for i in range(127744, 127994)] emoji_list_2 = [chr(e) for e in range(128000, 12...
2ba1401ac5a2b326f56fc29fa91cd638e27c5426
3,601,424
def subjects_dewey(self, key, value): """Translates subject classification.""" _subjects = self.get("subjects", []) _subjects.append({"scheme": "Dewey", "value": clean_val("a", value, str)}) return _subjects
c1db1f20418bfb517110b8857d490613beb8ff22
3,601,425
import itertools def cmr_filter_urls(search_results): """Select only the desired data files from CMR response.""" if 'feed' not in search_results or 'entry' not in search_results['feed']: return [] entries = [e['links'] for e in search_results['feed']['entry'] if 'li...
403cfe92f6520af59a851b7b1913404be429a507
3,601,426
def measure_sidechain_torsion_angles(residue, verbose=True): """Calculates sidechain dihedral angles for a residue Parameters ---------- residue : [ampal.Residue] `Residue` object. verbose : bool, optional If `true`, tells you when a residue does not have any known dihedral ...
6809e692c1630dbfd58569074995dba1becb3acf
3,601,427
from typing import List from typing import Tuple def residues(pdbfile: str, residues: List[int], buffer: float = 0.) -> Tuple[Tuple, Tuple]: """Generate a ligand autobox from a list of protein residues The ligand autobox is the minimum bounding box of the alpha carbons of the listed residues Paramet...
3ac4f9bd55fc58d342a37054405512f0722c3509
3,601,428
def roll_to_center(raw_transform, xc, yc): """ Shifts ("rolls") a two-dimensional numpy array so that the given coordinate will be in the center. Pixels shifted over the edge re-appear on the other side :param raw_transform: A numpy array to be shifted :param xc: current x position in pixels :p...
a2790ec03d6a4a912828e312361b8e69b78b50d6
3,601,429
import time def generate_jsapi_pay_params(wx, prepay_id): """ 生成微信公众号支付参数(WeixinJSBridge对象getBrandWCPayRequest参数) :param wx: [dict] :param prepay_id: :return: """ params = { 'appId': wx['app_id'], 'timeStamp': str(int(time.time())), 'nonceStr': generate_random_key(1...
bfe9bea6820a30fdb9acf854c280cbad6abe4764
3,601,430
import math def plot_binary_proportion_comparison( series_names, values_by_category, title, xlabel, ylabel, secondary_series_names=None, secondary_data=None, tertiary_series_names=None, tertiary_data=None, baseline_series_names=None, baseline_data=None, raw_data_to_label_fn=str, show_ebars=True, z...
778345ab57dabfb2c3d2d794e2e953dce2417538
3,601,431
def is_valid_instance_version(version): """True if string looks like an instance ID or a ref, or a tag.""" return ( is_valid_instance_id(version) or is_valid_package_ref(version) or is_valid_instance_tag(version))
e51eb3fd129b401bcc1fdaaa44771f428a1e35b6
3,601,432
def _parse_config_file(filename): """Return plugin name and meta-data dict from plugin config file.""" parser = ConfigParser() parser.read(filename) name = parser.sections()[0] meta_data = {} for opt in parser.options(name): meta_data[opt] = parser.get(name, opt) return name, meta_...
3802aa55b07749e2f452fd23c2acffc53e4118a7
3,601,433
def Floyd(G): """Returns the length of paths from all nodes to remaining nodes Parameters ---------- G : graph weighted graph Returns ------- result_dict : dict the length of paths from all nodes to remaining nodes Examples -------- Returns the length of p...
9fc9102225bf5273ff5a507b14ef2d8d679b2223
3,601,434
def merge(source, destination): """ run me with nosetests --with-doctest file.py a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } } b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } } merge(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'n...
aed6471ecce859c496b811ed81ea5f16b83b5c7d
3,601,435
def transformer_decoder_attention_unit(x, hparams, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, ...
2e07cc2aecc62a727f479c408fba52144d5a38f7
3,601,436
def isFileHandler(inSource, inTarget=None): """Source and target types can be either RegistrationPipeFH (or its base class) or strings. Regardless of which is chosen, they must both be the same type. If this function returns True - both types are fileHandlers. If it returns false, both types are string...
1c47e3af7d98fb9b802a90b372dce71c5ad76bff
3,601,437
def _skip_node_of_type(node: Node, node_ops_to_skip: list): """ Skips nodes of specified ops starting from node 'node'. :param node: node to start skipping Identity nodes. :return: node of the op """ # skip the Identity node while len(node.out_edges()) == 1 and node.op in node_ops_to_skip: ...
904f4973f5d314786aea7408d83534ccef90318b
3,601,439
def multiple_auth_methods(self): """ClickHouse SHALL reject Kerberos authentication if other auth method is specified for user alongside with Kerberos. """ ch_nodes = self.context.ch_nodes config_path = f"kerberos/configs/{ch_nodes[0].name}/users.d/kerberos-users.xml" def modify_file(root): ...
bd35a3e9c620af8ca8ff05c4823f2df83a4ca7f3
3,601,440
def make_encoder_network(x, code_size): """ Define the network mapping text vectors to embeddings """ x = keras.layers.Conv1D( filters=64, kernel_size=3, strides=2, activation="linear" )(x) x = keras.layers.BatchNormalization()(x) x = keras.layers.LeakyReLU()(x) x = keras.layers.Conv1D(...
67c6b46bad29861b913c42ca34862224b75af9fd
3,601,441
def format_datetime(session): """Convert date or datetime object into formatted string representation. """ if session.data is not None: date_format = session.field.opts.date_format if date_format == 'iso8601': session.data = session.data.isoformat() else: sess...
53a99843e47dde6b82cb48e77fd553bbf65dd646
3,601,442
def kde_max(kde, tol=1e-3): """Determine the maximum value of a KDE INPUT: scipy.stats.kde object""" # 2010-07-23 11:14 IJC: Created cenguess = np.median(kde.dataset, 1) init_steps = np.std(kde.dataset, 1) max_vals = np.zeros(kde.d) for dim in range(kde.d): this_step = init_steps[dim...
3dae757fa64f7e6a90b761cc966e2cb0fdb74770
3,601,443
from bs4 import BeautifulSoup def UsaScraping(): """ Take all USA page urls """ usa_url = "https://univ.cc/states.php" usa_req = Request(usa_url, headers={'User-Agent': 'Mozilla/5.0'}) usa_webpage = urlopen(usa_req).read() usa_soup = BeautifulSoup(usa_webpage,...
add4ce326b9f5e7599ff686605e09e7d9c428fb2
3,601,444
def get_pipeline_output_for_equity(df, symbol, drop_level=False): """ pipeline output contains many equities, if you want to view the pipeline for jsut one equity you could use this method which slices a multiindex df (dates and equities) :param df: :param symbol: :param drop_level: if True it w...
86cb4a94d99ea32b42cdb868dea3cf4246ffe381
3,601,445
def _get_package_fields_from_configuration(): """Get package fields from package field config dir.""" env_locals = {} env_locals.update(metadata_validator.VALIDATOR_LOCALS) env_locals.update(metadata_callback.CALLBACK_LOCALS) configs = util.load_configs( setting.PACKAGE_FIELD_DIR, en...
006b1b296a4b3121b42992f33b6769311ebb2272
3,601,446
def train_step(model, optimizer, loss_fn, conditions, true, out): """One training step Args: model: the feed-forward network optimizer: the optimizer for the network loss_fn: the loss function conditions: the observing conditions used as inputs true: the true galaxy ...
8d9ba730582e1d7992bf2bd2f8359f4531392645
3,601,447
def train_step(train_loss, x, t, depth_t): """ 学習処理 """ with tf.GradientTape() as tape: #勾配計算の明示的指示 preds = model(x, t) # t = t[:, 1:] # mask_t = tf.cast(tf.not_equal(t, 0), tf.float32) # t = tf.one_hot(t, depth=depth_t, dtype=tf.float32) # t = t * mask_t[:, :...
ac2c8141c5c7fa0ff9e398dae670d547d7b7ef33
3,601,448
import torch def get_concentrated_mask(class_weights, topk): """ Returns a logical mask indicating the categories with the top k largest probabilities, as well as the catogories corresponding to those with the top k largest probabilities. Parameters ---------- class_weights : torch.Tensor...
8663c6e4d868eb2100684132ef95c59eee9b3560
3,601,449
import json import random from geolocate_world import * from geolocate_US import GeoLocation import sqlite3 def geolocate_reverse(latlon): """ given (lat, lon) returns reverse geo location information import json from geolocate_reverse import geolocate_reverse result = geolocate_reverse((40.733104,-73.99...
07fde2bea4ce74c0e6f1fbfbe9ccee0bdef5b8d9
3,601,450
def read_pickle_template(file_path: str, col_date: list, array_col: str, date_col: str, id_col: str, some_feature: str, one_layer: bool = True ):...
adaeaac303fa171df87b0f4b73f5fa743677fc63
3,601,453
def mni152_to_fsaverage(img, fsavg_density='41k', method='linear'): """ Projects `img` in MNI152 space to fsaverage surface Parameters ---------- img : str or os.PathLike or niimg_like Image in MNI152 space to be projected fsavg_density : {'3k', '10k', '41k', '164k'}, optional D...
1abb5f80eb7b06e79b953dad47002d93fa369f19
3,601,454
from typing import Dict from typing import Any def robot_and_modules( modules_only: Dict[str, Any], ot2_default: Dict[str, Any] ) -> Dict[str, Any]: """Structure of SystemConfigurationModel with robot and modules.""" modules_only["robot"] = ot2_default return modules_only
126965499a60ff2355eaae4241e8caf0d6066555
3,601,455
def get_drush_user_password_command(name, password): """ Construct the drush user-password command Prior to Drush 9.x, the upwd command expects --password, newer versions of Drush do not. """ if determine_drush_major_version() >= 9: return "upwd %s '%s'" % (name, password) return "upwd %s --password=...
61fad60a0c1b9763158e8170c8f9e8b1d89d492d
3,601,456
import re def get_params(rule): """ Returns params from the url Args: rule (str): the endpoint path (e.g. '/v1/data/<int:id>') Returns: (list): parameters from the endpoint path Examples: >>> rule = '/v1/random_resource/<string:path>/<status_type>' >>> get_params(rul...
05414d950a6a603ff79fa2efff3ff3fef1e375f2
3,601,457
def add_brach(user): """ This function creates a new branch and adds the branch to the database, The branch will belong to class Branch. """ chatt_object = Chatt.query.filter_by(user_id=user).first() if chatt_object is not None: new_branch = Branch(user) db.session.add(new_branc...
f4dfe310bb226f22247f448c55096db50efd4e69
3,601,459
def reset_var(): """reset vars""" return [], [], True
3d78de5df772f60e0331a95d9ca14f46d1d36071
3,601,460
def get_verts_from_master_arr(master_array): """ Extracts vertex objects based on state transitions in master_array. Args: master_array (numpy array) """ cur_state = master_array[0, 6] vertices = [] for index, row in enumerate(master_array[:]): if row[6] != cur_state: cur_state = row[6] vertices...
3b526dbf59a26fd14853eb22fe1da2840209e6e9
3,601,461
def upstream_or_distgit_path( request, upstream_and_remote, distgit_and_remote, ogr_distgit_and_remote ): """ Parametrize the test to upstream, downstream [currently skipped] and ogr distgit """ return { "upstream": upstream_and_remote[0], "distgit": distgit_and_remote[0], "o...
6f94a44e95301398c495dff56f9e470b46b5c737
3,601,462
def find_subclass(base: type, name: str) -> type: """Find a named subclass of a base class. Uses only the class name without namespace. """ class_candidates = [ klass for klass in all_subclasses(base) if klass.__name__ == name ] if len(class_candidates) == 0: raise RuntimeError(...
c99c1d7949d56c94cb3531af381c644b5f4e397d
3,601,463
def metrics(y_pred, y_true): """ Calucate evaluation metrics for precision, recall, and f1. Arguments --------- y_pred: ndarry, the predicted result list y_true: ndarray, the ground truth label list Returns ------- precision: float, precision value recall: float, re...
bb0dfb24c3d9ddd0ce1a94887e60fe4ef2a89763
3,601,464
def get_related_field(name, short_description=None, admin_order_field=None, admin_prefix='admin'): """ Create a function that can be attached to a ModelAdmin to use as a list_display field, e.g: client__name = get_related_field('client__name', short_description='Client') """ as_link = name.startswit...
58197aabc818c1a40dda233945dc65594c50774a
3,601,466
def soft_quantile_normalization(x, f, axis=-1, **kwargs): """Applies a (soft) quantile normalization of x with f. The usual quantile normalization operator uses the empirical values contained in x to construct an empirical density function (EDF), assign to each value in x its corresponding EDF (i.e. its rank d...
0c43527413f1f9fa39c1c8ccc5a5023ca0cccd9b
3,601,467
import random def get_random_path(graph): """Get a random path from the graph as a list of nodes. :param pybel.BELGraph graph: A BEL graph :rtype: list[BaseEntity] """ wg = graph.to_undirected() nodes = wg.nodes() def pick_random_pair(): """Get a pair of random nodes. :...
4e42d8bcc1ddf52e169041eef26b298dd707319a
3,601,468
def is_pre_release(version): # type: (str) -> bool """Figure out if a given version is a pre-release.""" try: return SemanticVersion(version).is_prerelease except ValueError: return False
6bc4772bbfe54a2cc0dfa75ad5b3f87052d8b935
3,601,469
import re def process_line(line): """ Pre processes the given line. :param line: line as str :return: preprocessed sentence """ if line == u"": return u"" # detect sentences sentences = sentence_detector.tokenize(line) # process each sentence for sentence in sentences:...
ab51d9331561f7e0ab85bbc2059538d586848861
3,601,470
def DTRTAV( file_contents, data_type, regression_var ): """ 'Do The Right Thing' using adapative-validated glmnet as the regression method. Pick the right version of glmnet to use based on data type. Args: file_contents: Raw form-data from HTTP POST request. data_type: Parameter of the sam...
15a9838f1b3dd404d70bd7f76325cf35f65d0057
3,601,471
def schedule_adaptive_max_pool2d(_, outs, target): """Schedule definition of adaptive_max_pool2d""" with target: return topi.generic.schedule_adaptive_pool(outs)
df74a56fdc222c03b7720447fc0cf4d3f72b0151
3,601,472
def dotProduct(d1, d2): """ @param dict d1: a feature vector represented by a mapping from a feature (string) to a weight (float). @param dict d2: same as d1 @return float: the dot product between d1 and d2 """ if len(d1) < len(d2): return dotProduct(d2, d1) else: return sum(...
65892f62f3c9d1ec13a62427aaafa7831a8ee1e5
3,601,473
import math def rotatePoint(centrePoint,point,angle): """Rotates a point around another centerPoint. Angle is in degrees. Rotation is counter-clockwise""" pointX, centrePointX = point.getX(), centrePoint.getX() pointY, centrePointY = point.getY(), centrePoint.getY() angle = math.radians(angle...
59bb9cea7f803113796e7249f1aeb6cffc75929a
3,601,476
def input_data(): """Input data (as coming from the view layer).""" return { "metadata": {"title": "Test", "type": {"type": "test"}}, }
7a8bb2b82ee4754b2ee8b535c76a23ca5695c237
3,601,477
def create_synt_cube(cube, psf, ang, plsc, dist=None, theta=None, flux=None, verbose=False): """ """ centy_fr, centx_fr = frame_center(cube[0]) np.random.seed() if theta is None: theta = np.random.randint(0,360) posy = dist * np.sin(np.deg2rad(theta)) + centy_fr ...
3f833764968cc2449f49cdf8d0df87026adc1d58
3,601,478
def _chk_format_is_for_single_channel(chk_format: str = DFLT_CHK_FORMAT): """ Returns if a struct format string is designated for a single channel of data >>> assert _chk_format_is_for_single_channel('h') == True >>> assert _chk_format_is_for_single_channel('@hq') == False """ return _chk_format...
b2d1f91b1847a7002c7f053230ddc6cea573945e
3,601,479
def match_card(qCard, train_ranks, train_suits): """Finds best rank and suit matches for the query card. Differences the query card rank and suit images with the train rank and suit images. The best match is the rank or suit image that has the least difference.""" best_rank_match_diff = 10000 bes...
d1797ce279e1ec8a45d27bc0a5a29960bf87b032
3,601,480
import re def remove_extra_space(text): """ Remove extra space between two words Parameters ---------- text : str Returns ------- text: str """ return re.sub(' +', ' ', text)
d1b68128fe0655fe2f84263b0b9d6b83759552b1
3,601,481
def linter(): """Fixture providing a testing linter.""" pylinter = UnittestLinter() pylint_sqlalchemy.register(pylinter) return pylinter
3620d34a48b6ec675f47d83146fd9b6576563b2b
3,601,482
def string_from_file(file_name): """Read contents of a resource file into a string If the class has public attributes, they may be documented here in an ``Attributes`` section and follow the same formatting as a function's ``Args`` section. Good for planning using just docstrings. :param str file_...
8419740fd12a2cf37fab3b55610b6ccf9009e54a
3,601,483
def bitvec_number(x): """Return number represented by given bitve""" return sum(x << (32 * i) for i, x in enumerate(x.data[0:x.size]))
ad393d4f30d9fef35f089491a7c59faca3ec6610
3,601,484
def convolve(img, kernel): """Performs a naive convolution.""" if kernel.shape[0] % 2 != 1 or kernel.shape[1] % 2 != 1: raise ValueError("Only odd dimensions on filter supported") img_height = img.shape[0] img_width = img.shape[1] pad_height = kernel.shape[0] // 2 pad_width = kernel.sha...
51bd2bd681fb404d9dbce745f46406f136f22090
3,601,485
def ddt_named(parent, child): """ Helper to get more readable dynamically-generated test names from ddt. """ args = RenamedTuple([parent, child]) args.__name__ = f'parent_{parent}_child_{child}' # pylint: disable=attribute-defined-outside-init return args
9772c35d56afbc1f4fb07d65e2d28662878cbb68
3,601,486
def garfield_empty_mock(url, request) -> str: """ Mock HTTP empty response using HTTMock :param url: str :param request: Request :return: str """ return """ <html> <body></body> </html> """
c2c349e40f315bfc625680fc5b0e92a7a54f5f7c
3,601,487
from urlparse import parse_qs def callback(): """ Step 3: Retrieving an access token. The user has been redirected back from the provider to your registered callback URL. With this redirection comes an authorization code included in the redirect URL. We will use that to obtain an access token. ""...
d49dc7f53763dedd64050fea746a489d67d90e34
3,601,489
def model_atmosphere(altitudes): """Model atmospheric pressure, temperature and speed of sound. Args: altitudes (np.array): 1-d array of geopotential altitudes in metres Returns: A triple giving corresponding 1-d arrays of estimated pressure, temperature and speed of sound. Units a...
1693a0501e6c6e804b67289dd7d3136d71d2a3fd
3,601,490
def has_permissions(**perms): """ Same as the default discord.ext.commands.has_permissions except this one supports overriding perms """ def predicate(ctx): if ctx.override_perms: return True ch = ctx.channel permissions = ch.permissions_for(ctx.author) ...
4beafbae218d3fc6ac88215b8d94b27b46a26099
3,601,491
def check_order(order): """ Checks the specified drawing order is valid and returns the corresponding tree traversal order. """ if order is None: order = "minlex" traversal_orders = { "minlex": "minlex_postorder", "tree": "postorder", } if order not in traversal_o...
c8478bbbb59ce25beec4a4196dc183a49ecb62ba
3,601,492
def get_total_num_women(dataframe, fil): """Counts total women in category Returns: [list] -- total number of women, total number in category """ total = 0 matched = 0 for index, row in dataframe.iterrows(): if fil(row): total += 1 if row["gender"] == "F"...
478046f1f7bb62280f36df50b50c537dba2eb063
3,601,493
def get_cat2id(item_metas, n_entities): """Extracts all categories from item metada and maps them to an id""" categories = set([cat for it_meta in item_metas for cat in it_meta.categories]) return {cate: n_entities + i for i, cate in enumerate(categories)}
38c7895949d3eccf9d8d4fc6c609b036700f93d8
3,601,494
def flatten_weights_and_state(weights, state): """Flatten weights and state into lists, excluding empty and cached ones.""" def _is_empty_weight(x): return (x is EMPTY_WEIGHTS or (isinstance(x, dict) and x == GET_WEIGHTS_FROM_CACHE)) flat_weights = [w for w in fastmath.tree_flatten(weights) ...
4e25fe154e27315ecab6f800d3f0ad800c33cd7d
3,601,495
def add_acids(EP, amino_acids): """ The function check that all alpha amino acids in sequence, else add this monomers. Parameters ---------- EP : dict Variants of peptide sequences. amino_acids : list List of alpha amino acids. Returns ------- EP : dict C...
45027c8b38c97da4af677e79af0c302539d8b747
3,601,496
def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients...
b7fecfb9ad602c3c388e78fc08b8945351583909
3,601,497
def winnforum_testcase(testcase): """Decorator for common features (e.g. logging) for WinnForum test cases.""" def decorated_testcase(*args, **kwargs): if not testcase: raise ValueError('Avoid using @winnforum_testcase with ' '@configurable_testcase') _log_testcase_header(testca...
9bc212ac433eec09cfc283edf5f272b7860d81c8
3,601,498