content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def trimylim(simdat, ylim): """ Remove realization experimental variogram points beyond a variogram value so they won't be plotted. Parameters: simdat (pd.DataFrame): ylim (float): Value to trim points after """ # Get the column containing the index if 'Variogram Index' in s...
7f60073810a4167bc491772ce9e4c1aa23ec8183
63,600
def encode_operation(operation, flags): """Encodes a flagged operation as a single-byte opcode.""" encoding = OPCODE_ENCODING[operation] for flag in flags: encoding |= FLAG_ENCODING[flag] return encoding
633a7587ab08b996cad22036ae9133b061fe0249
63,601
import time def sparseFitFluxes(oi, firstGuess, N={}, initFlux={}, refFlux=None, significance=4, fitOnly=None, doNotFit=None, maxfev=5000, ftol=1e-3, epsfcn=1e-8, prior=[]): """ use discrete wavelets (WVL) to model spectra of different components. firstGuess: initial multi...
83f51b4778ec115e49e7e1e7370bb32fab1660ba
63,602
def transform_action_symbol(sym): """Transform the action symbol to a form to be more easily tokenized by BART vocabulary. We adopt the following rules: - lower-case everything, so that SHIFT -> shift, REDUCE -> reduce, MERGE -> merge - verbalize some actions, so that the meanings are better rep...
e901689c217bf47c5127b7ebadb679c3618365c6
63,603
from typing import Dict import PIL def plot_detections( detection: Dict, data: "DetectionDataset" = None, idx: int = None, keypoint_meta: Dict = None, ax: plt.axes = None, ) -> PIL.Image.Image: """ Put mask onto image. Args: detection: output running model prediction. data...
40ac809842fc0095fa84d1c66527909eec956c37
63,604
def sfc_area_latlon_box(ds, lat_str=LAT_STR, lon_str=LON_STR, lat_bounds_str=LAT_BOUNDS_STR, lon_bounds_str=LON_BOUNDS_STR, sfc_area_str=SFC_AREA_STR, radius=RAD_EARTH): """Calculate surface area of each grid cell in a lon-lat grid.""" lon ...
2aef4dd42dad32c0e58ed064280cbe10088ecb23
63,605
import os import tempfile def assert_image_equal(disable_diff_save, pytestconfig): """ Save the current figure to a temporary file and check that it's the same as the reference image of the given name. """ def inner(name, tol=1e-6): path = os.path.join( os.path.dirname(os.path.abs...
e233f0a3e9c7f50117ae89bc76641a14919aca7f
63,606
def list_rules(repository): """ Returns all RepoMirrorRules associated with a Repository. """ rules = RepoMirrorRule.select().where(RepoMirrorRule.repository == repository).all() return rules
cf9137f3b105c361af3d53d94da737a0b89bccf3
63,607
def my_imfilter(image, filter): """ Apply a filter to an image. Return the filtered image. Args - image: numpy nd-array of dim (m, n, c) - filter: numpy nd-array of dim (k, k) Returns - filtered_image: numpy nd-array of dim (m, n, c) HINTS: - You may not use any libraries that do the work for...
26bff06dcbe8de21622519af37b92eda3049816d
63,608
import torch def repeat_column(column: torch.Tensor, times: int) -> torch.Tensor: """ Repeats the given column the given number of times. :param column: the column to repeat. Size [H]. :param times: the number of repetitions = W. :return: the given column repeated the given number of times. Size [...
dfa955fbff0c4b87a7f5cef729a454eb99c93760
63,609
from keras.utils import multi_gpu_model def create_models(backbone_retinanet, num_classes, weights, multi_gpu=0, freeze_backbone=False, lr=1e-5, config=None): """ Creates three models (model, training_model, prediction_model). Args backbone_retinanet : A function to call to create a...
ca2e91bc0703726093929fd1f749918f1011201c
63,610
def get_input_decay(name): """ Generates the appropriate decay function for a given variable. The decays that can be generated are static (no decay over time), linear and exponential. :param name: name of the variable that will be generated :return: decay function for the variable with appropria...
cd78a75f475be01e0927cf0725b9ff0c2bb308e4
63,611
def tide_pred(modfile,lon,lat,time,z=None,conlist=None): """ Performs a tidal prediction at all points in [lon,lat] at times in vector [time] z: provide depths for the transport to velocity conversion. If None, the OTPS model depths will be used. If 1.0, it will effectively return transport values ...
48a4544db875ac061233d5ecdffd60c844e461db
63,612
def _batchnorm_fold_grad_compute(d_batch_mean, d_batch_std, data_x, batch_mean, batch_std): """_batchnorm_fold_grad_compute """ shape_x = te.lang.cce.util.shape_to_list(data_x.shape) normal_size = shape_x[0] * shape_x[2] * shape_x[3] d_batch_mean_broad = te.lang.cce.broadcast(d_batch_mean, shape_x) ...
3ee1d8830b73c215ae1b2d14ddb586455c486262
63,613
import os def send_css(path): """ Serve static CSS files """ return flask.send_from_directory(os.path.join(static_folder, 'css'), path)
47e2aee5fa9df1bac1c55a7462b42c5cf041dec8
63,614
def plot_model(fig,ax,M,my_cmap = 'cividis',lim=None): """ Plot 2D model, setting zeros to nans so they are not shown """ sel = (~np.isnan(M)) if lim is None: lim = [M[sel].min(),M[sel].max()] im = ax.matshow(M,cmap=plt.get_cmap(my_cmap),vmin=lim[0],vmax=lim[1]) cbar = fig.colorb...
be5e7feb0dfe4ed5c075682376a67887cc906be5
63,615
import logging import requests def youtube_video_details(key, vid_ids): """Return details of videos for which the ids are given. Assumes ``ids`` is a comma-separated list of video ids with no spaces.""" base_url = ('https://www.googleapis.com/youtube/v3/videos?part=' 'contentDetails,id...
b6bbe82278357536b6f0f551ea50e45497154cc5
63,616
def build_put_model_as_string_required_one_value_no_default_request( **kwargs # type: Any ): # type: (...) -> HttpRequest """Puts constants to the testserver. Puts constants to the testserver. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into...
d787dd034a8202e9d03c6a9f9d35263c2d91e6ac
63,617
import itertools def return_output(sim, outputs, reduced_precision=True): """Save simulated time series in npz format under keywords corresponding to monitor names. Parameters ---------- sim : tvb.simulator Instance of the simulator which produced the outputs. outputs : list R...
5ab349fcfdc23c601d37dd17f513bfa292109465
63,618
from typing import Optional from typing import Tuple import torch def _input_format_classification( preds: Tensor, target: Tensor, threshold: float = 0.5, top_k: Optional[int] = None, num_classes: Optional[int] = None, multiclass: Optional[bool] = None, ) -> Tuple[Tensor, Tensor, DataType]: ...
c265a1360fe92631baf5a9aa634ab55879486969
63,619
def get_nickname(email, never_me=False, request=None): """Return a nickname for an email address. If 'never_me' is True, 'me' is not returned if 'email' belongs to the current logged in user. If 'request' is a HttpRequest, it is used to cache the nickname returned by models.Account.get_nickname_for_email(). ...
7c59f40aa816313c05b65322bf89ed7d7f388a11
63,620
def recipe_detail_url(recipe_id: int) -> str: """Return recipe detail URL""" return reverse("recipe:recipe-detail", args=[recipe_id])
93180992c2d7a9a00b06383d2296a44909d1ec2a
63,621
def add_page_to_extra_context(view_func): """ Adds the best-match page to the extra_context keyword argument. Mainly used to provide generic views which integrate into the page module. """ def inner(request, *args, **kwargs): kwargs.setdefault('extra_context', {}) kwargs['extra_cont...
764e1fc9046f4cdb893ace566ceccf6a9a175ec1
63,622
def _create_outer_to_inner(angle: f32['']) -> geom.Transform: """Constructs an "outside" box to "inside" box transform. Consider an "outside" box of shape [-1, 1]^3. We define an "inside" box to be a box that sits inside of the "outside" box with a rotation about the z-axis. The inside box is defined such that...
b097a1e248cae1e40414d7b76754e8f67d460177
63,623
def where_not_all_match(labels_1: Labels, labels_2: Labels): """Compare clustering labels of the same input data generated by different DBSCAN approaches. """ more_than_one_unique_label = [] for unique_label_1 in labels_1.unique.labels: idx_1 = np.where(labels_1.labels == unique_label_1)[0] ...
b586754a138f94544014317da557b5507e7c98f6
63,624
def zpad(x, pd, ax): """Zero-pad array `x` with `pd = (leading, trailing)` zeros on axis `ax`. Parameters ---------- x : array_like Array to be padded pd : tuple Sequence of two ints (leading,trailing) specifying number of zeros for padding ax : int Axis to be padded ...
671d8ada6ffbc5b6700c7500d633c6c0449adc28
63,625
import operator def get(ind, seq, default=no_default): """ Get element in a sequence or dict Provides standard indexing >>> get(1, 'ABC') # Same as 'ABC'[1] 'B' Pass a list to get multiple values >>> get([1, 2], 'ABC') # ('ABC'[1], 'ABC'[2]) ('B', 'C') Works on any value th...
61dc1a0cc02e29f9f51cc57f34aa60bf6bf8d83a
63,626
import sys def _is_generator_func(func_impl): """ Return True if the func_impl is a generator :param func_impl: :return: """ if (3, 5) <= sys.version_info < (3, 6): # with Python 3.5 isgeneratorfunction returns True for all coroutines # however we know that it is NOT possible t...
f542e7ee82f319ccbcde9703a4ecfcd228e80463
63,627
from typing import Union from typing import Optional def get_flops(model: Union[Model, Sequential], batch_size: Optional[int] = None) -> int: """ Calculate FLOPS for tf.keras.Model or tf.keras.Sequential . Ignore operations used in only training mode such as Initialization. Use tf.profiler of tensorfl...
73c7a935815731863c0d62eea0ef00db65b678cf
63,628
def compare(hand1, hand2): """ Compares hand1 to hand2 Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. In the foregoing description, the notation sgn(expression) designates the mathe...
5c7a652e27effe9cd01762839f78af53b889a93c
63,629
def identity(): # type: () -> Projection """Creates a projection that does no transformation. Returns: Projection[hazelcast.core.MapEntry]: A projection that does no transformation. """ return _IdentityProjection()
2dd69bb631ddf8fb0bef53b0b509a3a74d104cd1
63,630
import unicodedata def remove_punctuation(text): """Replaces all Unicode punctuation except dashes (Pd) with whitespaces. Potentially induces duplicate whitespaces. """ text = ''.join( ' ' if unicodedata.category(c)[0] == 'P' and unicodedata.category(c)[1] != 'd' else c...
0bf4c1f9100051a09252bcd3f24a8a593dc02ce2
63,631
def remove_distant_agents(x, k, indices=None): """ Remove the distant agents. Args: x (N, N, C): The state difference of N agents. k (int): The K nearest agents to keep. Returns: x (N, K, C): The K nearest agents. indices (N, K): The indices of K nearest agents of each agent....
292072c14f4ed42999f30ec3b4b17bc90280257f
63,632
import time def _strTogMonth(v): """Test gYearMonth value @param v: the literal string @return v @raise ValueError: invalid value """ try: time.strptime("2001-" + v + "-01", "%Y-%m-%d") return v except: raise ValueError("Invalid gMonth %s" % v)
64962552ab9ae5df06f76f07c91c549927caa0dd
63,633
import torch def calc_cam(x, label, model): """ function to generate a class activation map corresponding to a torch image tensor Args: x: the 1x3x224x224 pytorch tensor file that represents the NIH CXR label:user-supplied label you wish to get class activation map for; must be in FINDING...
57712b9a043808f867e447dcdcb94b077e968e05
63,634
import json def load_data(): """記録データを返します""" try: database = json.load(open(DATA_FILE, mode="r", encoding="utf-8")) except FileNotFoundError: database = [] return database
3ec779d6618ed497f25ad78b140efbd551daaab7
63,635
def parse_markers(f): """ Parse markers from mrk file f. Each marker determines a time point and an according class-label of the movement that was imagined. Args: f (String) - an mrk file Returns: tuple of lists of ints - one list for the markers, one for ...
670ce43529a7aae4f4ed4341938a90eb6e714fb3
63,636
def insert_file(service, title, description, parent_id, mime_type, filename): """Insert new file. Args: service: Drive API service instance. title: Title of the file to insert, including the extension. description: Description of the file to insert. parent_id: Parent folder's ID. mime_type: MIM...
b33afc947c33bfc96ddfa0ccbb92afb19ad9e454
63,637
from openeye import oechem, oedocking from openeye import oeomega def dock_molecules_to_receptor(receptor_filename, molecules): """ Dock the specified molecules, writing out to specified file Parameters ---------- receptor_filename : str Receptor .oeb.gz filename molecules : list of o...
5e1f66f8ea768e2b6423c5151d58d0f4a06619fe
63,638
def polygon_shapes_from_voronoi_lines(poly_lines, geo_shape=None, shapes_from_diff_with_min_area=None): """ Form shapely Polygons objects from a list of shapely LineString objects in `poly_lines` by using [`polygonize`](http://toblerity.org/shapely/manual.html#shapely.ops.polygonize). If `geo_shape` is not ...
75b842948f739ab0ef222bda2996712c9dbeaa6a
63,639
import time import numpy def simulate_conway_generations_from_image(initial_image, life_generations, empty_space_detection_depth=6): """ :param initial_image: The image that is the initial state, generation 0, of the simula...
dd5a7d3686fc6fea4a537438e3d9903496960cf8
63,640
import random def randomFlip(input_image, flip_prob = 0.5): """ flip the single image horizontally with probability flip_prob""" tmp = random.random() if tmp <= flip_prob: fliped_image = input_image[:, ::-1,:]; output_image = fliped_image FLAG = 1 else: output_image = i...
93587e838439aea12ea84ba44556c8575b7e3759
63,641
def countPlayers(): """Returns the number of players currently registered.""" conn = connect() c = conn.cursor() c.execute("SELECT * FROM players;") playerList = c.rowcount conn.close() return playerList
f487b5a61d687e218767b8865a7d9bca3426b8e2
63,642
import requests def fetch_mb_release(mbid, user_agent='mb2md/1.0', https=True): """Fetches and returns the JSON recordings info for a specific MusicBrainz ID from the MusicBrainz API. :param mbid: MusicBrainz release ID :param user_agent: what user-agent header to send :param https: whether to us...
315a475aa4dc2fc312aff5107d03127002230b99
63,643
from typing import Any def build_post_flattened_simple_product_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest: """Put Flattened Simple Product with client flattening true on the parameter. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request...
1ee8bdc207cfd3d379466a9ceaf39f22d3c218dd
63,644
def capture_reward_expected_c(cap_skill=CAP_SKILL_NONE): """ Expected value for number of capture rewards given the specified capture skill (none by default). """ if cap_skill == CAP_SKILL_NONE: min_c = 2 max_c = 3 extend_p = 22 * 100.0 / 32 elif cap_skill == CAP_SKILL_EX...
563f3a4ad07a6121880f0fba989331a63fd3990b
63,645
from concurrent.futures import ThreadPoolExecutor def thread_map(fn, *iterables, **tqdm_kwargs): """ Equivalent of `list(map(fn, *iterables))` driven by `concurrent.futures.ThreadPoolExecutor`. Parameters ---------- tqdm_class : optional `tqdm` class to use for bars [default: tqdm.au...
84e325ae66a33fd3fe3ac2f912449951c136b035
63,646
def print_file(remote_filename): """ Gets and returns the content of a remote file. Do this instead of call type in order to avoid console width issues. """ temp_file = cStringIO.StringIO() with hide('everything'): get(remote_path=remote_filename, local_path=temp_file) te...
0385f2201bb5d02f527825953212b661ed515b6d
63,647
def get_max_cpus(): """ Returns the maximum number of CPU cores available for us to use """ try: return cpu_count() except NotImplementedError: # If we can't figure out how many CPU cores we have... well there's got # to be at least 1 right? return 1
467a1686bf18b1fccef9408562a088ca739d30c0
63,648
def fuzzy_vector_equal(x_vec, y_vec, tolerance=global_tolerance): """ Same as above, but for vectors. x_vec, y_vec are 1d numpy arrays """ return all(abs(el) < tolerance for el in x_vec - y_vec)
7ffe5864396234713dc583e76418120621ead1b3
63,649
def dp_key(relations): """ generates a unique key for the dptable dictionary :param relations: set of relations :return: str """ return '-'.join(sorted([r.name for r in relations]))
e415778193d5a5c90ba7574bccc7e82d0d95c2e8
63,650
def interp_empty_months(ds, method='full', inplace=True): """ Takes a xarray dataset/array and performs linear interpolation across each month seperatly. A concatenated xr dataset is returned. This is a wrapper for perform_interp function. The method can be set to full or half. Full will use the b...
b935948d3345cab8fd6f6cf6cf5b6259474cec77
63,651
import argparse def parse_args(): """Get the command line arguments, and make sure they are correct.""" parser = argparse.ArgumentParser( description='Build and test compilers and other things.') parser.add_argument("build_type", help="The kind of build to trigger.", ...
7c14baccb52d8cb1c1cde820efed45641d779f49
63,652
import json import requests def submitNotebookJob(notebookPath, dockerComputeDomain=None, dockerImageName=None, userVolumes=None, dataVolumes=None, resultsFolderPath="", parameters="", jobAlias= ""): """ Submits a Jupyter Notebook for execution (as an asynchronous job) inside a Docker compute domain. :p...
98217c2ed3b29638a6b25fe98cbfe37d06f25e80
63,653
def _MergeSwarmingTestShards(shard_results): """Merges the shards into one. Args: shard_results (list): A list of dicts with individual shard results. Returns: A dict with the following form: { 'all_tests':[ 'AllForms/FormStructureBrowserTest.DataDrivenHeuristics/0', 'AllForms/...
2c9161bf0b5f4e748e54c51b45742505ef685d78
63,654
def find_nonterminals(mat): """Find nonterminal states in a transition matrix.""" return [ix for ix, row in enumerate(mat) if row[ix] != 1]
04a7e58d4dc94aa5d7370aadc65f06edd47459b7
63,655
def transfer_asset(txn_key, batch_key, identifier, label, sender, amount): """Create an AcceptOffer txn and wrap it in a Batch and list. Args: txn_key (sawtooth_signing.Signer): The Txn signer key pair. batch_k...
ac1ff5956f164dc07cb05cb12c4a08397375e3d0
63,656
import pandas def prepare_and_plot_box_risk_groups(df: pandas.DataFrame, trait_code: str, data_column_name: str, output_path: str, sex: str = 'both', ancestry: str = 'All'): """Prepares data for plotting box plots for risk groups, creates t...
d276c6523d297260988a2c62607e77b13907158c
63,657
def _set_up_parser(): """Defines a parser object used in the API that also defines possible choices presented to the user.""" problems = ("max_cut", "stable_set", "graph_partition", "vertex_cover") p_values = (1, 2, 3, 4) graph_types = ("random", "caveman", "barbell", "ladder") parser = reqparse.Re...
ee03d818cc4e28dff5507e4efe74608b2828d4ab
63,658
def prepare_design_masked(D: np.ndarray, mask_bw: np.ndarray) -> np.ndarray: """Design matrix using only the pixels in the mask Args ---- D: np.ndarray The design matrix as it comes from build_Design_Matrix mask_bw: np.ndarray (binary or boolean) The image used as mask. Entryes ...
47072e25178722b106ef8d7221f249408a33ae74
63,659
import html def subview_results_container_html(): """ The placeholder html block for results. This is updated via callback. WANRING: for the loading animation to work correctly, it must be the direct parent of an html block which is being updated via callback. Args: None Returns: ...
acd30316cc46cfdb49f09acf97b3e235fec6db56
63,660
import numpy def vdisp_trailing(sdf): """Return the velocity dispersion in km/s for the trailing tail""" # Go out to RA=245 deg trackRADec_trailing=\ bovy_coords.lb_to_radec(sdf._interpolatedObsTrackLB[:,0], sdf._interpolatedObsTrackLB[:,1], ...
3eed9f0bdbaa84c67a09bbd52a1623dc1d66bdb3
63,661
import time import http def test_endpoint(conn, headers, method, endpoint): """ Test passed endpoint using passed method and determine whether endpoint requires auth """ debug("Trying: {} {}".format(method, endpoint)) try: conn.request(method, endpoint, headers=headers) except OSError:...
1267bbb5a1362c297d6fbfe3e9d4ca280f34a186
63,662
from pathlib import Path import os import subprocess def find_workspace() -> Path: """Find the root of the current Bazel workspace.""" # Try to get the workspace from Bazel itself if this script was run with `bazel run` if WORKSPACE_ENV_VARIABLE in os.environ: return Path(os.environ[WORKSPACE_ENV_...
855a7b05dca2b3eefe66777d235da926f2a426d1
63,663
import sys def _called_with_wrong_args(f): """Check whether calling a function raised a ``TypeError`` because the call failed or because something in the factory raised the error. :param f: The function that was called. :return: ``True`` if the call failed. """ tb = sys.exc_info()[2] ...
cf8b53eebf9a79399b7f6bdb7bb8cf6bce92e5a8
63,664
def is_equal(M, N): """ Determines if both matrices are equal. :param M: A matrix. :param N: A matrix. :return: True if both M and N are equal to each other. False otherwise. """ return np.array_equal(M, N)
ec90ca098d94217ff3b8fab5a7be0aa624986bf0
63,665
def view_election_statistics_table(self, request): """" View for the standalone statistics table. """ layout = ElectionLayout(self, request, 'statistics') return { 'election': self, 'layout': layout, 'type': 'election-table', 'scope': 'statistics' }
f6ed76fcb8172a75b13a011357870fc2f9400cbe
63,666
def combineNeighborPeaks(peaks, energyScale): """ Combine three neighboring peaks together using intensity for weighted average calculations. The peaks must be responsed. The baseline is not calculated for the new peaks and is set to 0. Args: peaks: List of Peak energyScale: Energy sca...
254c09988aa8c4ee0f25e83f2f0e3b35469582bb
63,667
def extrinsic_euler_yxy_from_active_matrix(R, strict_check=True): """Compute extrinsic yxy Euler angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation m...
6dfb58398a872f1259eea77e03e5e402b927d618
63,668
import os def get_rpm_upstream_source_tarball(specfile, destdir): """ Get or download the upstream source tarball file. :param specfile: the RPM spec file :param destdir: the destination directory to store the downloaded file returns the file path of the downloaded tarball """ name, versio...
1462dce3e8e511ff53cf63c89e9c66861970ee3d
63,669
def calc_uncertainity_polygon(lon,lat,wspd): """ Function creates the uncertainity polygon of storm track Arguments: Lon, Lat, Wind speed Returns: polygon """ error = get_ibtracs_uncertainity(wspd) hours = np.arange(1,len(error)+1,1) # interpolate points_num = 10...
6a91259f65764dc6c842d447c21765cf855223f9
63,670
import os def prepare_monitor(tenant=tenant, user=user, password=password, organization=organization, zone_name=zone_name): """ :param tenant: tenant url :param user: user's email :param password: user's password :param zone_name: (optional) zone_name :return: """ router = PrivatePath(...
0f74bd74cb34593def80da30c9bc82604f84410d
63,671
def validate_installs(list_of_packages): """ Wrapper function to validate multiple installs :param list_of_packages: packages to validate :return: Dictionary of {"package_name": install_validity(true/False) """ package_validity = {} for package in list_of_packages: package = package....
4df6654bcbadd7059b0b3c684505003aa558ee7d
63,672
def as_list(obj, tuple_to_list=False, if_none=NotImplemented): """ This is useful to allow arguments that are theoretically lists, but tend to be single items in practice. As syntactic sugar, we allow passing in these single items in some cases. For example, multiple allowed statuses or zones migh...
d1331365111cf16919285575600f437e09cb0405
63,673
import tempfile import os import subprocess def edit_rec(editor, url, title_in, tags_in, desc): """Edit a bookmark record. Parameters ---------- editor : str Editor to open. URL : str URL to open. title_in : str Title to add manually. tags_in : str Comma-se...
406957085d654a7a88ed1e4ef8baf0c9eebc030d
63,674
def create_whimsy_computation_tensorflow_constant(): """Returns a tensorflow computation and type `( -> float32)`.""" value = 10.0 tensor_type = computation_types.TensorType(tf.float32) value, type_signature = tensorflow_computation_factory.create_constant( value, tensor_type) return value, type_signatu...
953b73077eda5b151a523459b26f8f7b921bde3f
63,675
def estimateValueFromAgent (stateSamples, agent, rewardFn) : """ Use the learnt value function network through A2C to estimate value for states. """ def estimateForState (s) : cpus = list(range(C.N_PARALLEL)) affinity = dict(cuda_idx=C.CUDA_IDX, workers_cpus=cpus) agent_ = ...
52c3c4f377804f3b154d098768dc1c56eaa3ac61
63,676
def _format_command_stdout(stdout): """ Formats the output from stdout returned from subprocess """ lines, list_of_strs = stdout.splitlines(), list() for line in lines: list_of_strs.append(line.decode()) return list_of_strs
69603c16f35f92cc4da7d2b3710ffa44f295d24d
63,677
from pathlib import Path def reclassify_from_map(in_raster, map_values, dst_raster=None, overwrite=False): """ Remap raster values from map_values dictionary. If the are missing values in the dictionary 0 value will be returned Args: in_raster (path to raster): Input raster to reclassify ...
93c48dee8ce42b8c31d67b5b73ff317c56ff87f3
63,678
def somme(*nombres): """Retourne la somme des nombre de la liste donnée """ total = 0 for nombre in nombres: total += nombre return total
683a8b48a59d538d9883f25cf5ab8f8f2bbf9232
63,679
import re import os def fix_media_src(filestr, dirname, dest): """Fix the (relative) path to any figure and movie in the DocOnce file. The generated .md and .ipynb files will be created in the path passed to `--dest`. This method fixes the paths of the image and movie files so that they can be found ...
ef651d499c2dc3bbe999efff0fa108c8b33200da
63,680
from datetime import datetime def dayStart (origin): """Reset datetime's time part to start of the day (i.e. 00:00:00).""" return datetime.datetime(origin.year, origin.month, origin.day)
39909b9b6ffe7d5363e9eae2856608820a0c8a08
63,681
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/start (enter YYYY-MM-DD)<br/>" f"/api/v1.0/start/end (enter YYYY-MM-DD/YYYY-MM-DD)"...
1ff99658d4586de603c75ff2738a98b5c4ea48f4
63,682
def trimVersionString(version_string): """Trims all lone trailing zeros in the version string after major/minor. Examples: 10.0.0.0 -> 10.0 10.0.0.1 -> 10.0.0.1 10.0.0-abc1 -> 10.0.0-abc1 10.0.0-abc1.0 -> 10.0.0-abc1 """ if version_string == None or version_string == '': ...
ddaba8c5ed3d16cf9f1c6ce8f4c82784968b306e
63,683
def filter_section_with_drugs(input_data: pd.DataFrame, drug_lex_path: str): """ Filter to sections where section text contains drug terms. :param input_data: pandas dataframe with publication text :param drug_lex_path: file path for list of drug terms to search for :return: Dataframe with sections...
9680ebe5252a482ab6792603b1e84f12ab77fec8
63,684
def find_builds_with_status(service, branch, target, starting_build_id): """Find Android builds (and their status) in the target branch whose build IDs are >= to the provided build ID.""" build_list = None for i in range(2): build_list = query_for_build_status(service, branch, target, starting_build_id) ...
7af8505bfb4de2dffbca66e7db7373160ca30158
63,685
def ReadRosterFromFile(file_name, hub_map, rosterC): """ roster_tools.ReadRosterFromFile PURPOSE: Reads a roster file with the following fields: <**Last Name>,<**First Name>,<**Grade>,<**Parent/Guardian Name(s)>,<***Teacher Name> ** - indicates always required field *** - indicates field that i...
44691daff187724e869d5044861a50b5fdce20e2
63,686
def extract_sectors(pred_df, thres): """Extracts labels for sectors above a threshold Args: pred_df (df): predicted sector thres (float): probability threshold """ long_df = ( pred_df.reset_index(drop=False) .melt(id_vars="index", var_name="division", value_name="probabi...
a772e965685ca8ac8cd6a52861c36e9cf7faf887
63,687
def run_CIS_checks5(region_list): """ Checks CIS lvl 5 (Networking). Returns: list """ control = [] control.append(control_5_1(region_list))# Testing with port 3389 and 22. Add more admin ports increment_progress() control.append(control_5_2(region_list))# Testing with port 3389 and 22. ...
d2f2f74063425fd132a1c216550a29e3c297f993
63,688
def _formats_count_query( storage_service_id, start_date, end_date, storage_location_id=None ): """Fetch information from database on file formats. :param storage_service_id: Storage Service ID (int) :param start_date: Inclusive AIP creation start date (datetime.datetime object) :param end_...
3e89fe4c223c078271ef65b2c78b0689daf4a21c
63,689
import bisect def find_closest(numeric_list, query_number): """ Given a list of numbers, and a single query number, find the number in the sorted list that is numerically closest to the query number. Uses list bisection to do so, and so should be O(log n) """ sorted_numeric_list = sorted(numeric_l...
ae2dad58162f38f7c1e4d7149943488a96c3c8dc
63,690
def parameters_ok(): """check for reasonableness of parameters""" # FIXME we do not check table string at all # make sure we can get an integer value here, as expected try: parameters['num_pkts'] = int(parameters['num_pkts']) except Exception as e: print('did not get num_pk...
6c81244e4dd2eb747e6044eabb0ab287fe6654ab
63,691
def survey_year_plot(continent_code='All', country_code='All'): """Takes a continent code and country code and returns choropleth object""" filtered_data = q.geo_filter(continent_code=continent_code, country_code=country_code) figure = px.choropleth( filtered_data, locations="country_code"...
c0a3ca40f864c3037b4141a197305d97f95b1136
63,692
def set_starting_position(poly, ggr=None): """Check and set starting position.""" if not ggr: starting_position = "upperleftcorner" # EnergyPlus default else: starting_position = ggr.Starting_Vertex_Position.lower() poly = poly.order_points(starting_position) return poly
0c04182e3bb23e817e551a5a361fba28f812aad4
63,693
def get_zone_list(verbose=False): """ This function retrieves a list of all the zones within the IDS. Returns a list sorted by zone name, or None if some error occurred. """ output = run_iquest('select order(ZONE_NAME)', format='%s', verbose=verbose) if not outp...
53ccefa61836eef04d692a522f8c3248951b58b2
63,694
from io import StringIO def get_evaluate_resource(model_name, model): """get resource associated with evaluate""" parser = reqparse.RequestParser() parser.add_argument('variable', type=str, required=True) for var_symbol in model: if type(var_symbol) != UndefinedFunction: func = mo...
c4b2f4ac3b7437130e50b616387a2549d8678800
63,695
import os def read(*paths): """ read files """ with open(os.path.join(*paths), 'r') as filename: return filename.read()
0a30fa6e88eb5cca0c2a052a165426114a892d4e
63,696
import json from typing import Collection import re def view(entity_id): """ View tokens and precomputed or user-generated annotations --- get: summary: Get annotations for a specific entity description: > Get annotations for a specific entity with id `entity_id` parameters: ...
455d1ae368fc93ae251f2623d00a0402200fafae
63,697
def _parse_image_format(image_link): """Parse an image format from a download link. Args: image_link: link to download an image. >>> link = "http://blogs.elpais.com/.a/6a00d8341bfb1653ef01a73dbb4a78970d-pi" >>> Google._parse_image_format(link) >>> link = "http://minionslovebananas.com/ima...
cee5ec7a102cd457b1899d1229386cc5b17103e3
63,698
from typing import List import os import glob def detect_vcss(directory, *args, **argv) -> List[VCS]: """ Interrogate the given directory for vcs information, returning an object that can be used to obtain information about the current conditions of the source tree. """ directory = directory o...
176af08f761d4ee8a311385600928058a79f7992
63,699