content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def eperm_crim(por, eperm1, eperm2, eperm3=None, sw=None): """Effective electric permittivity after CRIM. Markov et al., 2012, Journal of Applied Geophysics, Eq. 7. Parameters ---------- por: float or array Concentration of constituent 1 (host, wetting phase). eperm1, eperm2, eperm3 :...
4daa8528b8e91ff315ee1ecf49f0f88d219cbb87
3,605,900
def shortest_paths(graph, vertex_key): """Uses Dijkstra's algorithm to find the shortest path from `vertex_key` to all other vertices. If we have no lengths, then each edge has length 1. :return: `(lengths, prevs)` where `lengths` is a dictionary from key to length. A length of -1 means t...
f2ac9abf9292364099748475988d4ee1dbeb4b23
3,605,901
def process_overall_mode_choice(mode_choice_data): """Processing and reorganizing the data in a dataframe ready for plotting Parameters ---------- mode_choice_data: pandas DataFrame From the `modeChoice.csv` input file (located in the output directory of the simulation) Returns ------...
870685017d223f8a277265f80eea56e50eedec90
3,605,902
import os import pathlib def local_to_cloud(local_path): """ takes a path to a local file or directory and converts it to a Dropbox location. This is done by replacing definitions.HOME_DIR with definitions.CLOUD_HOME_DIR. :param local_path: path to a local file. Note: file must be somewhere in the cur...
401f27bdc605ed3d93e7aa8372b8a095abe84ceb
3,605,903
def loadtemplater(ui, spec, defaults=None, resources=None, cache=None): """Create a templater from either a literal template or loading from a map file""" assert not (spec.tmpl and spec.mapfile) if spec.mapfile: frommapfile = templater.templater.frommapfile return frommapfile(spec.mapfil...
fffc64d1a41486c20c4e61aa4281787730c93cb4
3,605,904
def vgg16(inputs, batch_size=100, num_classes=12, is_training=True, dropout=0.5, weight_decay=0.005, spatial_squeeze=True, scope='vgg_16'): """Oxford Net VGG 16-Layers version D Example. Note: All the fully_connected layers have been transfo...
e70abe98dc581c42526a95deb9f03126b7c3a37f
3,605,905
def print_movie_rating_results(genre_to_rating_map): """Given a dictionary, prints the average IMBD ratings for each year for each genre formatted as: *genre* *space* *release years* : *average IMBD rating* Parameters: genre_to_rating_map: a dictionary that maps genres to r...
d045cce8a6fe2f73ce27327a6f6aabb97473a5d9
3,605,906
def flatten_datasets(rel_datasets): """Take a dictionary of relations, and returns them in tuple format.""" flattened_datasets = [[], [], []] for kind in rel_datasets.keys(): for i in range(0, 3): for rel in rel_datasets[kind][i]: flattened_datasets[i].append([*rel, kind]...
70affa370a98c8328effed0bdb015999c5874913
3,605,907
from typing import Callable def requires_token(func: Callable): """ This annotation protects API calls that require authentication. It will cause them to raise NoAcccessTokenException if the token is not set in the client. :return: Function decorated with the protection """ def wrapper(self...
368b223bc824c394072f1f99a7bb33d19015a545
3,605,908
import torch def log_sum_exp(x, dim=None): """Log-sum-exp trick implementation""" x_max, _ = torch.max(x, dim=dim, keepdim=True) x_log = torch.log(torch.sum(torch.exp(x - x_max), dim=dim, keepdim=True)) return x_log+x_max
45b1f6d198569567d3284bab4116a4703b0589a3
3,605,909
import hashlib def feature(self, node="clickhouse1"): """Check alter user query syntax. ```sql ALTER USER [IF EXISTS] name [ON CLUSTER cluster_name] [RENAME TO new_name] [IDENTIFIED [WITH {PLAINTEXT_PASSWORD|SHA256_PASSWORD|DOUBLE_SHA1_PASSWORD}] BY {'password'|'hash'}] [[ADD|DROP] HOST {LOCA...
d9cde1936c78d9d61ca9a446d5018e51c74c221f
3,605,910
def nb_year(p0, percent, aug, p): """ Finds the amount of years required for the population to reach a desired amount. :param p0: integer of starting population. :param percent: float of percent increase per year. :param aug: integer of new inhabitants. :param p: integer of desired population. ...
054496347fc8bedca3424143d48d122712dd1363
3,605,911
def find_largest_digit(n): """ :param n: the number to be processed and compared with :return: the largest digit in the number """ num = abs(n) initial_largest_digit = num % 10 # set largest digit to the last digit of the number return helper(num, initial_largest_digit)
3f9324ab3676bb29b1d81b2eea13c43fc0d338c0
3,605,912
def compute_overlaps(boxes1, boxes2): """Computes IoU overlaps between two sets of boxes. boxes1, boxes2: [N, (y1, x1, y2, x2)]. For better performance, pass the largest set first and the smaller second. """ # Areas of anchors and GT boxes area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - ...
f224ee968a824984e8463ab43e346e6396cf4325
3,605,913
def search_master(request): """Method to query existing customers.""" try: results = [] query_id = int(request.GET.get('id')) query = request.GET.get('q') school_level = request.GET.get('level') # Filters for external ids if query_id == 1: agents = OVCFacility.objects.filter(facility_name__icontains=qu...
30ce02b79a05ec5d37c08f36ea25836fc3ba2b5d
3,605,914
def generate_importance_map(map_size): """ This function generates a weighted map of "where we want the brain to be". It is thus 1 at the center and 0 at the edges. """ importance_map = np.zeros(map_size) for i in range(map_size[0]): for j in range(map_size[1]): for k in rang...
4931dd522cbf8e6cec53edd13a6814d47a5ba8f3
3,605,915
import os def full_path_to(file): """Returns an absolute path to the given file.""" # We need to use full paths to files because `git status --porcelain` shows # paths relative to the repository's root. return os.path.join(repository_path(), file)
49eb10e1513e66dc2a9f85427a024a594f0a7441
3,605,916
from typing import Optional def change_email_address( user_id: UserID, new_email_address: Optional[str], verified: bool, initiator_id: UserID, *, reason: Optional[str] = None, ) -> UserEmailAddressChanged: """Change the user's e-mail address.""" user = _get_user(user_id) initiator ...
baae07a39055b302bdabaae0df65f0136da6303f
3,605,917
def write_walks_to_disk(args): """ Write random walk into file :param args: arguments for random walk write Returns ------- the name of file containing random walks """ num_walks, walk_length, window_size, num_pairs_required, subsample, file_name, iter_function, seed, __current_graph, __vertex2str =...
dcec7907a8c7986fff6f71469ffdd3b629980138
3,605,918
def tshark_read( device, capture_file, packet_details=False, filter_str=None, timeout=60, rm_file=True, ): """Read the packets via tshark :param device: lan or wan... :type device: Object :param capture_file: Filename in which the packets were captured :type capture_file: St...
8fc31098e750691a1aa7c27a868abf0d6254adec
3,605,919
def light_similarity(conn, entry_ids_1, entry_ids_2, metric, cpu_cores): """ main function :param conn: db_connection :param entry_ids_1: list of entries 1 :param entry_ids_2: list of entries 2 :param cpu_cores: number of cores to be used :param metric: 'lin', 'resnick', 'jc' or 'all' :r...
f5684a3cc96a456cffd18393f760d740c2d394b6
3,605,920
def prepare_window(ds_length, window_name, window_kwargs): """Window needs special preparation as the parameters can be dependent on dataset length. Args: ds_length (int): Length of the dataset. window_name (str): Name of the window module. window_kwargs (dit): Key word arguments from t...
9607cc89227e54b8b477d5fab05ec85d1e3925d1
3,605,921
def resize_image(img): """resize images prior to utilizing in trianing model""" width, height = img.size ratio = width/height new_height = 100 new_width = int(new_height*ratio) img = img.resize((new_width, new_height)) return img
1aa0164e1e25ef0f22e55a15a654fda2dfef5b12
3,605,922
def _filter_calibration(time_field, items, start, stop): """filter calibration data based on time stamp range [ns]""" if len(items) == 0: return [] def timestamp(x): return x[time_field] items = sorted(items, key=timestamp) calibration_items = [x for x in items if start < timestam...
c7575ec85c7da9f1872150a1da3d7b02718df8a0
3,605,923
import torch def phi_inv(D): """ Inverse of the reallification phi""" AB,_ = torch.chunk(D,2,dim=0) A,B = torch.chunk(AB,2,dim=1) return torch.stack([A,B],dim=len(D.shape))
b8198764b89f3f1261e96014697cf1346e1c7d43
3,605,924
import spacy import subprocess def load_spacy_nlp(language, disable_components): """Load the spaCy nlp object. If the language's models cannot be found, they are downloaded. """ try: spacy_nlp = spacy.load(language, disable=disable_components) except OSError: subprocess.run(["pyt...
7df4f1714a0a46b7f709509a000df85109af4404
3,605,925
import os def is_created(): """ Checks to see if ginger new command has already been run on dir """ return os.path.isfile(os.getcwd()+'/_config.yaml')
3a91185bd5c17d659e8cd30bf57c781c6a657092
3,605,926
def activate_wps(wps, endpoint, name): """ Activate a WebProcessingService object by calling getcapabilities() on it and handle errors appropriately. Args: wps (owslib.wps.WebProcessingService): A owslib.wps.WebProcessingService object. Returns: (owslib.wps.WebProcessingService): Returns a...
d146f22db9d13db17e688bfb404366b9e236dc8c
3,605,927
import argparse def read_param() -> dict: """ read parameters from terminal """ parser = argparse.ArgumentParser() parser.add_argument( "--ScreenType", help="type of screen ['enrichment'/'depletion']", type=str, choices=["enrichment", "depletion"] ) parser.add_argument("--LibFilen...
5efb8419266b34807b286a411cfd36365c66c628
3,605,928
def make_low_freq(xx, halfperiod=10, halfamplitude=1.): """ make low frequncy signals """ omega = np.pi / halfperiod return halfamplitude * np.sin(omega * xx + np.random.uniform(0, 2*np.pi))
f3ca7ab174f8e9d3b7f06251009820c753622f15
3,605,929
from re import T def tree_weight(pytree: T, weight: float) -> T: """Weights tree leaves by weight.""" return jax.tree_map(lambda l: l * weight, pytree)
b6da802e783632fc3986fa5547fad8ca5994e3a7
3,605,930
def get_sigma_clip(img,sigma=3,iters=100): """ Do sigma clipping on the raw images to improve constrast of target regions. Reference ========= [1] sigma clip http://docs.astropy.org/en/stable/api/astropy.stats.sigma_clip.html """ img_clip = sigma_clip(img, sigma=sigma, iters=ite...
a426fea3caafcb382fb0547145eadbeef0f9d7c8
3,605,931
def Get_foregroundapp(device): """Return the foreground app""" return device.shell("dumpsys activity recents | grep 'Recent #0' | cut -d= -f2 | sed 's| .*||' | cut -d '/' -f1").strip()
236986e3d08f6a4c7dd4cd8c8441806d25e76654
3,605,932
import glob import os def find_current_eofs(cur_path): """Returns a list of SentinelOrbit objects located in `cur_path`""" return sorted( [ SentinelOrbit(filename) for filename in glob.glob(os.path.join(cur_path, "*EOF")) ] )
a71d75dd5a420cc234a7fe232e686b7c34d92163
3,605,933
def chunk_size(request): """ Set the chunk size for the source (or None to use the default). """ return request.param
c57269f434790953d475a2791c862d70d204ed86
3,605,934
import csv import os def search_in_database(ip): """ search_in_database(ip_number) => (code, country) returns ('--', 'unknown') if nothing found """ global ip_database if not ip or not ip_database: return unknown try: # do a binary search. n = sum_ip(ip) fd ...
d663ff6d2cf011081fd651743abad2059386a92c
3,605,935
def finite_diff_hessian_diag(x, grad, epsilon=FINITE_DIFF_EPSILON): """ Approximate the diagonal of the Hessian of a function using finite difference in the partial gradient. :param np.ndarray x: point at which to evaluate derivative :param function grad: function that returns the gradient """ f...
c1670919376ab554d02f4e954c0e6775328bf469
3,605,936
import json def get_new_username(): """Prompt for a new username.""" username = input("What is your name? ") filename = 'Excercise_10_13.json' with open(filename, 'w') as f_obj: json.dump(username, f_obj) return username
e25546247a849aca6dae94728c4318ff10a43434
3,605,937
def densify(*args): """ Make the matrix dense and assign nonzeros to a value. densify(IM x) -> IM densify(DM x) -> DM densify(SX x) -> SX densify(MX x) -> MX """ return _casadi.densify(*args)
122c0f4710ca8b4e6b3274a665caab1ffc568acf
3,605,938
def t0(S, t_r, n): """ t0 = t_r - M_r / n :param S: S angle :type S: float :param t_r: reference time :type t_r: float :param n: mean movement :type n: float :return: t0 :rtype: float """ return t_r - 2 / 3 * np.sqrt(2) / n / np.tan(S)
7534034e64476fcdec3a2585f7716bd8daa26f08
3,605,939
import re def parse_ndx(lines): """ Parses a GROMACS ndx file. :param lines: Iterable of strings. :return: Dictionary with group names as key, list of 0-based atom indices as value. """ groups = dict() lastgroup = None thisvalues = [] for line in lines: line = line.strip() # skip comments and empty line...
aeca75ff4ec626e814336b327b11f942a46815b7
3,605,940
def duration_format(delta: float): """ Duration format :param delta: seconds :return: string representation: 1 days 1 hour 1 min """ if delta < 0: delta = f'{int(delta * 1000)} ms' elif delta < 60: delta = f'{int(delta)} sec' elif delta < 3600: delta = f'{int(delt...
4ea92191076281d2108066a85b2c8662024bdaaf
3,605,941
from datetime import datetime def isoformat(dt: datetime) -> str: """ISO format datetime object with max precision limited to seconds. Args: dt: datatime object to be formatted Returns: ISO 8601 formatted string """ # IMPORTANT should the format be ever changed, be sure to updat...
679ce7aa71ab30e4c78a0953272c17f487714177
3,605,942
def BuilderName(build_config, active_waterfall, current_builder): """Gets the corresponding builder name of the build. Args: build_config: build config (string) of the build. active_waterfall: active waterfall to run the build. current_builder: buildbot builder name of the current builder, or None. ...
eaebc50d653b759eff0005e0347f3cd09a4d07e0
3,605,943
def message_box(message, informativeText, type, question=False): """ADD Parameters ---------- Returns ------- """ # TODO: ADD DETAILED TEXT WITH TRACEBACKS AND EXCEPTION CATCHING msg = QMessageBox() msg.setText(message) msg.setInformativeText(informativeText) if ty...
a15ccbf33e674640e871dbefa7c795c45d7d5b06
3,605,944
def ndcg_at_k( rating_true, rating_pred, col_user=DEFAULT_USER_COL, col_item=DEFAULT_ITEM_COL, col_rating=DEFAULT_RATING_COL, col_prediction=DEFAULT_PREDICTION_COL, relevancy_method="top_k", k=DEFAULT_K, threshold=DEFAULT_THRESHOLD, ): """Normalized Discounted Cumulative Gain (nD...
edcb1da897b218c720c868f597463569d6e06952
3,605,945
from re import T def partners(): """ RESTful CRUD controller for Organisations filtered by Type """ # @ToDo: This could need to be a deployment setting get_vars["organisation_type.name"] = \ "Academic,Bilateral,Government,Intergovernmental,NGO,UN agency" # Load model table = ...
5cb3b9283fd04c854d4e8f4e4b6fd26480ac691f
3,605,946
def _opt_to_mymessage(msg): """Transforms dictionary representation of the VkOpt message to the MeMessage obj. Notes: Document id of a VkOpt message isn't parsed and may only be -1. Photos aren't documents (for some reason). Message is forwarded if only it has attached forwarded message...
e0cd6ce735b175e08375d940820e862aa075ab62
3,605,947
def _xls_dslx_verilog_impl(ctx): """The implementation of the 'xls_dslx_verilog' rule. Converts a DSLX file to an IR, optimizes the IR, and generates a verilog file from the optimized IR. Args: ctx: The current rule's context object. Returns: DslxInfo provider. ConvIRInfo provide...
4a45b1392e8755218efc593cf3aa3bd9a10c52c9
3,605,948
import os def getParentPath(): """ Convenience function. Returns the parent folder of the \\*.sikuli bundle. """ return os.path.dirname(Settings.BundlePath)
dc10d674fe7acbcd46153de462a3e00845be14ac
3,605,949
def generate_X_df_from_descriptor_list(descriptor_list, default_csv_paths, col2remove = DEFAULT_INDEX_COLS, **args, ): """ This function generates the combi...
5c73bbb8d8a3c9621554cbf1efc6dd3746e0b540
3,605,950
def compile_template(line): """ Compile a template expression into a python function (like jsps, but way shorter) """ extr = [] def repl(match): g = match.group if g('dollar'): return "$" elif g('backslash'): return "\\" elif g('subst'): extr.a...
68a275902d20f50c00597194c970237f6c86ae2e
3,605,951
from typing import Optional def _residual_star( regular_expression: RegularExpression, letter: Letter) -> Optional[RegularExpression]: """Residual computation, ``STAR`` case """ residual_inner = residual(regular_expression.inner, letter) if residual_inner is not None: return Re...
aa67c212f2ff063552ef1fd0f1629cf4ee2725b9
3,605,952
import sqlite3 import os def get_db_cache(cache_dir: str) -> sqlite3.Connection: """ Open cache and return sqlite3 connection Table is created if it does not exists """ cache_file = os.path.join(cache_dir, "cache.sqlite3") conn = sqlite3.connect(cache_file) cursor = conn.cursor() curso...
7dd6a909ba210a261196ddd1273795d76a27464a
3,605,953
def evaluate_policy(env, policy, args, eval_episodes=1): """ Runs policy for X episodes and returns average reward """ avg_reward = 0. avg_episode_steps = 0 save_state = True if save_state == True: evaluate_episode_states = [] for _ in range(eval_episodes): print('eval_episodes', eval_episodes) obs = env.re...
47ff74bf41949c78b5e141a34c617909c4347279
3,605,954
def get_dict(file_name): """ This function returns the english to french dictionary given a file where the each column corresponds to a word. Check out the files this function takes in your workspace. """ my_file = pd.read_csv(file_name, delimiter=' ') etof = {} # the english to french dictiona...
b86d21914c2b978909e7d88b0ca5e9d770a1dd05
3,605,955
from sklearn.utils import resample def calc_bootstrap(fcs, obs, func, L, B=1000, bootstrap_range=[2.5, 97.5]): """ Calculates moving block bootstrap estimates for an evaluation metric defined and calculated inside 'func' argument. INPUT fcs: forecasted time series obs: ...
90b4bcc57e6c337b5638008334e299bdfc70f13d
3,605,956
def histeq(im,nbr_bins = 256): """对一幅灰度图像进行直方图均衡化""" #计算图像的直方图 #在numpy中,也提供了一个计算直方图的函数histogram(),第一个返回的是直方图的统计量,第二个为每个bins的中间值 imhist,bins = histogram(im.flatten(),nbr_bins,normed= True) cdf = imhist.cumsum() # cdf = 255.0 * cdf / cdf[-1] #使用累积分布函数的线性插值,计算新的像素值 im2 = interp(im.flatten...
11f54f5440eadefa5bd03912d2e5f786eb2a7f29
3,605,957
def validate(obj, validator, name="object"): """Generic function""" if not isinstance(validator, Validator): raise TypeError("Not a validator.") if hasattr(validator, 'validate'): # Check to ensure that this hasn't looped back to this already return validator.validate(obj, n...
527f28f91694593571485ac1d8a828ac7d425906
3,605,958
def _recursive_namedtuple_convert(data): """ Recursively converts the named tuples in the given object to dictionaries :param data: An object in a named tuple or its children :return: The converted object """ if isinstance(data, list): # List return [_recursive_namedtuple_conver...
292bc249b056c14eb1c700561d366ff4e6e64a10
3,605,959
def compute_crowd_performance(df_crowd_results, crowd_score_column, experts_score_column): """ Function to evaluate the answers of the crowd at each posible crowd score threshold""" rows = [] rows.append(["Thresh", "TP", "TN", "FP", "FN", "Precision", "Recall", "Accuracy", "F1-score"]) precision = 0.0 ...
8316f8af86f9cad7eccf3f2175d0c14e2fbb8e84
3,605,960
def series_key_from_name(name): """Get an ESeries from its name. Args: name: The series name as a string, for example 'E24' Returns: An ESeries object which can be uses as a series_key. Raises: ValueError: If not such series exists. """ try: return ESeries[name...
c571a8975fadf4de14471a0b83157a06d2999080
3,605,961
import json import os import sys import re def initialize_exp(params): """ Initialize the experiment: - dump parameters - create a logger """ # dump parameters exp_folder = get_dump_path(params) json.dump(vars(params), open(os.path.join(exp_folder, 'params.pkl'), 'w'), indent=4) #...
dcfd58f020741051a96ee28528a5ad2b8fe018d2
3,605,962
def make_transform_sql2(sqlname, typefun, pyfun=None): """ Makes a sql transformer that accepts two arguments. sqlname: the name of the sql function. typefun: a function that accepts a list of datatypes and returns a datatype. numargs: the number of arguments accepted by this transformer. pyfun: a python fun...
d2a2b02253670ea4cc7ea6d4ab67ea992c5869cd
3,605,963
def _find_start(score_matrix, align_globally): """Return a list of starting points (score, (row, col)). Indicating every possible place to start the tracebacks. """ nrows, ncols = len(score_matrix), len(score_matrix[0]) # In this implementation of the global algorithm, the start will always be ...
361a1ea87ecf9bbef0950521ed0fdcfd70b7b608
3,605,964
def get_arguments_by_statement(statement: Statement, issue: Issue) -> dict: """ Collects every argument which uses the given statement. :param statement: Statement which is used for query :param issue: Extract information for url manager from issue :rtype: dict :return: prepared collection with...
faa7d60fa3d4ac073b6ff1cf9104d0f3ccd92299
3,605,965
def plot_fig(model_name, crypto_list: list, epoch: int, loss: list, acc: list): """ draw a figure for loss and acc """ cl = concat2str(crypto_list) pic_name = model_name + '_' + cl x = np.linspace(1, epoch, epoch) plt.figure(figsize=(4.5, 5)) plt.subplot(211) plt.plot(x, loss) ...
3ebdf445862955c6a1f4f5ac7b3e710578e486bc
3,605,966
def KLT(a): """ Returns Karhunen Loeve Transform of the input and the transformation matrix and eigenvalues. *** IN DEVELOPMENT *** Ex: import numpy as np a = np.array([[1,2,4],[2,3,10]]) kk,m = KLT(a) print(kk) print(m) # to check, the following should return...
29ad1baebdb34f474a6a8fdfa89f188b7cc02edc
3,605,967
def get_f1_score(precision, recall): """ Calculate and return F1 score :param precision: precision score :param recall: recall score :return: F1 score """ return (2 * (precision * recall)) / (precision + recall)
e94dd20acac443be9856b9dbb43adf2ead2e0ba5
3,605,968
def bh2u(x: bytes) -> str: """ str with hex representation of a bytes-like object >>> x = bytes((1, 2, 10)) >>> bh2u(x) '01020A' """ return x.hex()
8ab7bf9b536d13a1944e014ea83a4302917c2306
3,605,969
def chromAndPosSort(x, y): """ Comparison function for use in sort routines. Compares strings of the form chr10:0-100. Sorting is done first by chromosome, in alphabetical order, and then by start position in numerical order. """ xChrom = x.split("_")[-1].split(":")[0] yChrom = y.split("_")[...
27db2d05e918f1652ebf154c1004cfad112b5891
3,605,970
def vis_FasterRCNN_loss(self, scale_weight): """ Calculate the roi losses for faster rcnn. Args: -- self: FastRCNNOutputs. -- scale_weight: the weight for loss from different scale. Returns: -- losses. """ return{ "loss_cls": self.vis_softmax_cross_entropy_loss_(scale_weigh...
5832d7f28179085db939a7bd624e9ffb08461fe4
3,605,971
def simple_mask(model, init_fn, masked_param): """Creates a mask given a model and numpy initialization function. Args: model: The model to create a mask for. init_fn: The numpy initialization function, e.g. numpy.ones. masked_param: The list of parameters to mask. Returns: A mas...
053ed147fe780296de133e9d438127569609d3ed
3,605,972
def word_dropout(tokens, dropout): """ Randomly dropout tokens (IDs) and replace them with <UNK> tokens. """ return [constant.UNK_ID if x != constant.UNK_ID and np.random.random() < dropout \ else x for x in tokens]
d4a50bccef6e562bd4edb0320c6c5ecdb83fb4bc
3,605,973
def createSimpleResourceMap(ore_pid, sci_meta_pid, data_pids): """Create a simple resource map with one metadata document and n data objects.""" ore = d1_common.resource_map.ResourceMap() ore.initialize(ore_pid) ore.addMetadataDocument(sci_meta_pid) ore.addDataDocuments(data_pids, sci_meta_pid) ...
8837d120804dc75330f8d50a1086a83dabd25059
3,605,974
import binascii def crc32(data): """计算输入流的crc32检验码: Args: data: 待计算校验码的字符流 Returns: 输入流的crc32校验码。 """ return binascii.crc32(b(data)) & 0xffffffff
ed8966e87070e4fb26e9468fb5ec1bc7b30ebcd1
3,605,975
def scale(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None): """ Scale operator. Putting scale and bias to the input Tensor as following: ``bias_after_scale`` is True: .. math:: Out=scale*X+bias ``bias_after_scale`` is False: .. math:: ...
b68c737ebc0fb10dc43dc9d15b919705d2171555
3,605,976
def get_version_data(session, url, authenticated=None): """Retrieve raw version data from a url.""" headers = {'Accept': 'application/json'} resp = session.get(url, headers=headers, authenticated=authenticated) try: body_resp = resp.json() except ValueError: pass else: ...
b48550583286a7f3941a1ffd71c8129803ec077e
3,605,977
def _select_relevant_files(api_type): """ Select the folder related to the api_type Exclude certain files and directories based on api_type :param api_type: framework or plugin api :return: The base file path for the api files to document The list of files to exclude from api """ if api_...
fedd27d728aa7e164e709ca0cf5daa473de58927
3,605,978
from typing import Union def datetime_to_string( date: dt.datetime, date_format: str = "%Y-%m-%d %H:%M:%S" ) -> Union[float, str]: """Returns a string representation of a datetime object Args: date: dt.datetime the date date_format: what is the format of the date? see datetime documentati...
9dd7f8f6f53662cdaf6158b100658465893d286b
3,605,979
import json def request_game( request: game_server_pb2.GameRequest ) -> game_structs_pb2.GameRequestResponse: """Request a game.""" handler = get_default_tictactoe_cache_handler() # Set a random number seed based on the fractional second part # of the timestamp. This makes it more reliable on hig...
3263b33c557ccaf9448f63e4dc22bddbc878e41f
3,605,980
from typing import List from functools import reduce def decode(obs: int, spaces: List[int]) -> List[int]: """ Decode an observation from a list of gym.Discrete spaces in a list of integers. It assumes that obs has been encoded by using the 'utils.encode' function. :param obs: the encoded observation ...
6c3c1348776b7b164cf70a5bfa9da3e8b53a280f
3,605,981
def anagram_solution_1(words): """ Complexity O(n2) If it is possible to “checkoff” each character, then the two strings must be anagrams :param words: Tuple :return: bool """ s1, s2 = words still_ok = True if len(s1) != len(s2): still_ok = False a_list = list(s2) po...
942ef7bb631bd803d89e71643e994505cb9b827a
3,605,982
def allocation_shimen_wpp(): """ Real Name: Allocation ShiMen WPP Original Eqn: IF THEN ELSE( ShiMen Reservoir Depth>=ShiMenReservoir Operation Rule Lower Limit , Water Right ShiMenLongTan WPP\ *0.387, IF THEN ELSE( ShiMen Reservoir Depth >=ShiMenReservoir Operation Rule Lower Severe Limit , Water Right Shi...
3f489eec46527d59b305bcaced216c83e90ef6bc
3,605,983
def bleached(source): """Render a string through the bleach library, caching the result.""" render_function = partial(bleach.clean, tags=settings.BLEACH.allowed_tags, attributes=settings.BLEACH.allowed_attrs) return cached_render(render_function, s...
d734ae5d7997be878bf002c0e1fcba7516b9591b
3,605,984
import os def read(path, do_tail = 0): """ Read file content. :param str path: path to file :param int tail: number of lines to read (from end), entire file if 0 :return: file content splitted by newline :rtype: :py:obj:`list` [ :py:obj:`str` ... ] """ try: if do_tail: ...
d942c4ba037dc20ede8615abfa950cb9ed639389
3,605,985
def cna(mac): """Builds a mock Client Network Adapter for unit tests.""" return mock.Mock(spec=pvm_net.CNA, mac=mac, vswitch_uri='fake_href')
28ae759612d9b608b8288f627ac5d013914bbbd4
3,605,986
def product_from_hand(cards): """ Expects a list of cards in integer form. """ product = 1 card_symbols = [] i = 0 for n in cards: product *= (n & 0xFF) card_symbols.append(RANKS[i]) i += 1 return card_symbols, product
74eb8df29ed20c886745619d712595c975132f2e
3,605,987
def most_popular(request, username=None, search_key=None): """ Shows the most popular search results. The ``username`` kwarg should be the ``username`` field of ``django.contrib.auth.models.User``. The ``search_key`` can be any string. Template:: ``saved_searches/most_popular.html`` Co...
79e505270a783e188a913113f67bcecc5ae5814f
3,605,988
from typing import List from typing import Dict from typing import Any def replace_foreign_columns_with_local_columns(foreign_columns: List[ForeignColumnPath], fks_by_name: Dict[str, Any], src_table: str ) -> List[ForeignCol...
58346be57c746f1db136c50f786a4c2d4e95667d
3,605,989
from typing import Dict from typing import List def split_data(data: pd.DataFrame, parameters: Dict) -> List: """Splits data into training and test sets. Args: data: Source data. parameters: Parameters defined in parameters.yml. Returns: A list containing split...
a91b8bde176280635f4474e9965a54d6b7fb8cd0
3,605,990
def enum_pair(): """ 枚举所有的对子 """ return [(cards2str(pair), w) for w, pair in enumerate(CARD_PAIR)]
1f993b9014250d71185da3d34d89394b398e75ab
3,605,991
def _normalize_type(i_type: str) -> str: """Normalize AXI4-Stream names""" if i_type in _m_type: i_type = 'INITIATOR' elif i_type in _s_type: i_type = 'TARGET' else: raise ValueError("Unknown BUSINTERFACE type {}".format(i_type)) return i_type
35e9ecc7d3f8bab6d0d996e8ec47382dc7113999
3,605,992
def gt(input, other, out=None): """Compute *input* > *other* element-wise. Parameters ---------- input : dragon.vm.torch.Tensor The input tensor. other : dragon.vm.torch.Tensor, number The other tensor. out : dragon.vm.torch.Tensor, optional The optional output tensor. ...
978937f5917a9a7917f5d033815d6f17476dea43
3,605,993
def do_train(config, plugin_factory=None): # type: (MyNLUConfig, Optional[PluginFactory]) -> Tuple[Trainer, Interpreter, Text] """Loads the trainer and the data and runs the training of the specified model.""" # Ensure we are training a model that we can save in the end # WARN: there is still a race co...
053262e4678fd40f1adfc84682911cf073fc521e
3,605,994
def remove_invalid_rows(data): """ Removes invalid rows from data. A row is invalid if * the text is NaN * session_id is 0 """ progress = progressbar.ProgressBar(max_value=data.shape[0]).start() invalid_utterances = [] for i, row in data.iterrows(): if type(r...
7b409669261289784d0df49702d653318cea4a17
3,605,995
def load_feature_extractors(rt=None, wp=None, ap=None, slm=None, lm=None) -> 'tuple': """ Load feature extractors depending on command line options. For now we have the following extractors: * RuleTable * WordPenalty * ArityPenalty * StatelessLM * KenLM :return...
675728cddce5687df44db7d022594dc27aad3675
3,605,996
def oneYear(token="", version="stable", filter="", format="json", **timeseries_kwargs): """Rates data https://iexcloud.io/docs/api/#treasuries Args: token (str): Access token version (str): API version filter (str): filters: https://iexcloud.io/docs/api/#filter-results form...
a11973e8af3b02f5c89bd9a8c527a990f61d7d7d
3,605,997
from typing import Union from typing import Optional from typing import List from typing import Dict from typing import Any from typing import Tuple def sharpen( image: Union[str, Image.Image], output_path: Optional[str] = None, factor: float = 1.0, metadata: Optional[List[Dict[str, Any]]] = None, ...
9c9c59638c23761ac3ff9612cb9c256cbde8b24a
3,605,998
def get_unlisted_addons(): """Load the unlisted addons file as a set.""" return set_from_file('validations/unlisted-addons.txt')
1519dddfb84ee6f3e600fe044b4431e524fd1c38
3,605,999