content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def policy_compare(sen_a, sen_b, voting_dict): """ Input: last names of sen_a and sen_b, and a voting dictionary mapping senator names to lists representing their voting records. Output: the dot-product (as a number) representing the degree of similarity between two senators' voting p...
d90c3c584f27979ca41bd8bff939da47a8656601
3,626,000
def _py2java(sc, obj): """ Convert Python object into Java """ if isinstance(obj, RDD): obj = _to_java_object_rdd(obj) elif isinstance(obj, DataFrame): obj = obj._jdf elif isinstance(obj, SparkContext): obj = obj._jsc elif isinstance(obj, (list, tuple)): obj = ListCon...
4889a4ce782ee00172ee29c7ff2ac98f3fa15d8d
3,626,001
def docopt_attr(doc, argv=None, help=True, version=None, options_first=False): """docopt with options in attributes rather than dictionary elements args['--verbose'] => args.verbose args['<file>'] => arg.file All else remains the same. Attributes are single values or lists ...
9e7d28032f5634e4a5eaa8226ca33dba2827ecbd
3,626,002
import os from pathlib import Path def get_notebooks_run_in__jobs_update(): """ """ #| - get_notebooks_run_in__jobs_update #| - Read file lines # Jobs update method in bash_methods path_i = os.path.join( os.environ["PROJ_irox_oer"], "scripts/bash_methods.sh") with open(pat...
e66f16fc00c44b1c80651ad75e20e2765ac577cc
3,626,003
def must_be_known(in_limit, out_limit): """ Logical combinatino of limits enforcing a known state The logic determines that we know that the device is fully inserted or removed, alerting the MPS if the device is stuck in an unknown state or broken Parameters ---------- in_limit : ``boo...
241b66b359643d069aa4066965879bb6ac76f2ae
3,626,004
def delete_item(category_id, item_id): """ Deletes Item :param category_id: :param item_id: :return: render_template """ if 'username' not in login_session: return redirect('/login') category = session.query(Category).filter_by(id=category_id).one() item = session.query(Item).f...
13df75535eb7dde90764baa6540caa0b18ba0c64
3,626,005
import urllib from bs4 import BeautifulSoup import regex def download_floras(): """Get the floras from the main page.""" url = SITE path = FAMILY_DIR / 'home_page.html' urllib.request.urlretrieve(url, path) with open(path) as in_file: page = in_file.read() floras = {} soup = Bea...
665d5afdbd5caf2ba2a61de915a4c97228433027
3,626,006
def scale(x): """Scales values to [-1, 1]. **Parameters** :x: array-like, shape = arbitrary; unscaled data **Returns** :x_scaled: array-like, shape = x.shape; scaled data """ minimum = x.min() return 2.0 * (x - minimum) / (x.max() - minimum) - 1.0
e5c40a4a840a1fa178a2902378a51bfefc83b368
3,626,007
def group_data_by_columns(datasets, columns): """ :param datasets: [CxNxSxF] :param columns: F :return: CxNxFxS """ new_dataset = [] for i in range(len(datasets)): datalist = [] for row in range(len(datasets[i][0][0])): row_data = [] for column_idx in ...
8a73c959501f422c26fe358c05ddc6a574123009
3,626,008
def create_er_html(relations): """This function create entity-relationship html. Args: relations (list): List of (:class:`FieldPath` :class:`FieldPath`) Returns: Html str. A way might be used is >>> print create_structure_ers_from_relations([(FieldPath('db', 'ac', 'id'), FieldPath...
bb2392b811226c849dc9a08a596a337ea855a28d
3,626,009
def plotlimit(ul, alpha=0.05, CLs=True, ax=None): """ plot pvalue scan for different values of a parameter of interest (observed, expected and +/- sigma bands) Args: ul: UpperLimit instance alpha (float, default=0.05): significance level CLs (bool, optional): if `True` uses pvalues ...
f1ac8459ee417dd93c219073fbc2815e7e9a5362
3,626,010
from typing import BinaryIO import asyncio import os async def spawn_carla( cuda_device: int, carla_world_port: int, log_file: BinaryIO ) -> asyncio.subprocess.Process: """Spawns CARLA simulator in the background. Returns the process handle.""" environ = os.environ.copy() environ["DISPLAY"] = "" ...
002e10f0c45de149084b7033423d23753a0f1570
3,626,011
def rand_dm(N, density=0.75, pure=False, dims=None): """Creates a random NxN density matrix. Parameters ---------- N : int, ndarray, list If int, then shape of output operator. If list/ndarray then eigenvalues of generated density matrix. density : float Density between [0,1...
ef91b913e4eb62f2bd7b80c27f2deabd62756c7d
3,626,012
def GetStaticPipelineOptions(options_list): """ Takes the dictionary loaded from the yaml configuration file and returns it in a form consistent with the others in GenerateAllPipelineOptions: a list of (pipeline_option_name, pipeline_option_value) tuples. The options in the options_list are a dict: Key i...
d49effbdeb687ec62a2e2296330f66521023944c
3,626,013
import os import hashlib def gen_signed_cert(domain, ca_crt="ca.crt", ca_key="ca.key", key_path="cert.key"): """ This function takes a domain name as a parameter and then creates a certificate and key with the domain name(replacing dots by underscores), finally signing the certificate using specified CA a...
27fdb06c08309274df8e7464b27883030e0b1bea
3,626,014
import os def _nb_dir_file_profiler(path, _f, report=False): """Get the profile for a single file on a specified path.""" f = os.path.join(path, _f) if f.endswith('.ipynb'): if report: print(f'Profiling {f}') return process_notebook_file(f) return pd.DataFrame()
090fd5532fb2ae31705f572e33d65fbeeae6c012
3,626,015
def ExtractNLargestBlobsn(binaryImage, numberToExtract=1): """Extract N largest blobs from binary image. Arguments: binaryImage: boolean numpy array one or several contours. numberToExtract: number of blobs to extract (integer). Returns: binaryImage: boolean numpy are containing on...
84c9643d2ed9007b346b20be3fef8bfd6103d687
3,626,016
import json import collections def awx_manage_check_license_data_datasource(broker): """ This datasource provides the not-sensitive information collected from ``/usr/bin/awx-manage check_license --data``. Typical content of ``/usr/bin/awx-manage check_license --data`` file is:: {"contact_ema...
329a8de2848772b35e3a52e069912fd17a3e73ca
3,626,017
def create_addresses(account_id): """ Create an Address on an Account This endpoint will add an address to an account """ app.logger.info("Request to add an address to an account") check_content_type("application/json") account = Account.find_or_404(account_id) address = Address() a...
07fa9df9708bf9d5fddd050cb65c3effcf2ca1b3
3,626,018
import torch def anderson( f, x0, m=5, max_iter=50, tol=1e-4, stop_mode='rel', lam=1e-4, beta=1.0, **kwargs ): """ Anderson acceleration for fixed point iteration. Args: f (`Callable` or `nn.Module`): Function to be minimized. x0 (`torch.Tensor`): A batch of ve...
e731635b9e557f8a53f423842a956d0e33874290
3,626,019
def flip_axis(x, axis): """flip tensor中的对应轴 # Args x: nd array axis: int, axis of x """ x = np.asarray(x) x = np.flip(x, axis=axis) return x
d0085a6b1d1d3db7bd60fd953b640a380b8f70d4
3,626,020
from datetime import datetime def beginning_of_day_utc(day_offset: int) -> datetime: """Return Local Midnight time of today +/- day_offset days in UTC time.""" return _apply_day_offset( datetime.now().replace(hour=0, minute=0, second=0, microsecond=0), day_offset ).astimezone(timezone.utc)
e46a88edaff5619b6cf0d85cf3bfe8882f3ee1ca
3,626,021
def fit_austourists_with_R_params(model, results_R, set_state=False): """ Fit the model with params as found by R's forecast package """ params = get_params_from_R(results_R) with model.fix_params(dict(zip(model.param_names, params))): fit = model.fit(disp=False) if set_state: s...
4135e702ef27ec0c975d611852a0924db2493e6c
3,626,022
from typing import Callable from typing import Optional from typing import Any from typing import Dict async def execute( schema: "GraphQLSchema", document: "DocumentNode", response_builder: Callable, root_value: Optional[Any], context: Optional[Any], variables: Optional[Dict[str, Any]], o...
13d63f943901d5895d4b0dd7e2f0590c7595d1c4
3,626,023
def validate_ip_addr(addr, version): """ Validates that an IP address is valid. Returns true if valid, false if not. Version can be "4", "6", None for "IPv4", "IPv6", or "either" respectively. """ try: ip = netaddr.IPAddress(addr, version=version) return True except (netaddr....
938de99ed978887619463c55ce6128c1eabee0ba
3,626,024
from datetime import datetime def create_localized_datetime(*args, timezone='UTC', **kwargs): """ Creates an aware time in the given timezone. The intuitive way of doing this will give you the wrong answer: https://stackoverflow.com/questions/24856643/unexpected-results-converting-timezones-in-python...
0750455d8203ebf01699876c31bdd6993989f394
3,626,025
def resnet18(resnet_cls, **kwargs): """Construct a ResNet-18 model.""" return resnet_cls(block=BasicBlock, layers=[2, 2, 2, 2], **kwargs)
b66cece9f691b252d67b7547dd3c077ea3eefaf0
3,626,026
import logging import re def beautify_declaration_markup(markup : str) -> str: """Format our function and class declarations in NOMNOML to be a consistent size""" # We do not want to break before separators or before the end of a word # A 'word' in this case may include a trailing colon # Also catch ...
ae1124acce7b2a1df775c97423067c95dc1a93ae
3,626,027
import os from datetime import datetime def calibration_run(param_set_dirpath: str) -> str: """ Allows a user to select what model run they want, given an app Returns the directory name selected. """ # Read model runs from filesystem model_run_dirs = os.listdir(param_set_dirpath) # Parse...
d8ab9c4c43f7e5c786ea6a8e002496908c27cacb
3,626,028
def post(host, path, data): """Sends POST request using HttpClient and the data from GUI form. :param host: host ip addr :param path: resource endpoint path :param data: data to be sent as body of the POST request :return: HTTP response body """ cover = open(data, 'rb').read() print('Sen...
82a11497e8d2052eea32efa946616042fb1cb997
3,626,029
import pytest from typing import Optional def round_trip_pathlib(writer, reader, path: Optional[str] = None): """ Write an object to file specified by a pathlib.Path and read it back Parameters ---------- writer : callable bound to pandas object IO writing function (e.g. DataFrame.to_csv ...
742201b375f5e85a7adc485e60ca95d36e4c37e1
3,626,030
def conv_junc_to_exon(): """ Converting sorted junctions to exons here """ def overlap(start, end, start2, end2): return not (start > end2 or end < start2) cons_exons = [] overlaps = 0 prev_astart, prev_aend = juncs[0][-2], juncs[0][-1] prev_jstart, prev_jend = juncs[0][2], juncs[0][3] ...
1e98de11fa14cd0271abd6e1937e4f8bd7eb203e
3,626,031
import json from datetime import datetime def check_temperature (device, root_dir): """Check the temperature status and generates files with the tests result. Required EOS command: show system environment temperature | json Test failure conditions: A sensor test fails if a sensor HW status is not OK or i...
14951c63080e5d8d97eb5544b1d306d4cca39728
3,626,032
def create_folder_hierarchy(item, user, folder): """ Create a folder hierarchy that matches the original if the original is under a project folder. :param item: the item that will be moved or copied. :param user: the user that will own the created folders. :param folder: the destination project...
b5a7f0069fbdcd28ace8787c52963a6ae199f5e8
3,626,033
def compute_eval_metrics(gt_mask, pred_mask): """ Evaluate a mask w.r.t a GT mask :param gt_mask: m x n grid of 0s and 1s :param pred_mask: m x n grid of 0s and 1s :return: """ assert (gt_mask.size == pred_mask.size) tp = float(np.sum(np.logical_and(pred_mask == 1, gt_mask == 1))) fp...
bce074a18835fde4532b24b8568d6b7c382bdfac
3,626,034
import pickle def load_current_test_data(collection_name="current_test_data"): """loads the current test data and converts it back to normal Args: collection_name (str, optional): name of the collection. Defaults to "current_test_data". Returns: List of DataFrames: List of the current te...
f929d399b75ea6ab5d2723add3eefb4b8d50c743
3,626,035
def convolutional_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2)): """A block that has a conv layer at shortcut. Arguments: input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters...
7fafe41621aa155b8c9cb6dbccb92a09b780bc4b
3,626,036
def check_type_data(data, data_type=np.ndarray, dim=2): """ Some basic type checking on data """ # Code assumes that we have a matrix, so force it for single samples if len(data.shape)==1: data = data.reshape((data.size,1)) if type(data) != data_type: raise TypeError('data is n...
0eb9b2d958ce7b142133ecc68022b77783a418c3
3,626,037
from malaya_speech.utils import describe_availability def available_model(): """ List available speaker change deep models. """ return describe_availability( _availability, text='last accuracy during training session before early stopping.', )
bbcea119f0a888720928c6c583f6652e65946d73
3,626,038
def is_date_field(field, field_schema): """ Helper method that determines if field_schema is """ return determine_if_is_date_field(field, field_schema)
d8ffcfedcfeb1a2ca8d636be2e462522cca40acd
3,626,039
def generate_script_pick_and_place_block(tcp, frames, ur_ip, ur_port, velocity = 0.05, radius = 0, vacuum_on=2, vacuum_off=5): """Generate multiple linear movements and Airpick on/off commands. Parameters ---------- tcp : sequence of float Tool center point in a form of list. tcp = [x, ...
bfe81dd48691c44b7e42a6feaa71a766bcadc088
3,626,040
import pyranges as pr import warnings import os import subprocess import shutil from packaging.version import parse as parse_version from Bio import SeqIO from Bio.SeqIO.FastaIO import SimpleFastaParser from Bio.Seq import Seq from Bio.SeqFeature import SeqFeature, FeatureLocation from Bio.SeqRecord import SeqRecord ...
8e1ec157b6b5616d5b30ae0d2c489d09f255a068
3,626,041
def get_ds003_downsampled(data_dir=None, url=None, resume=True, verbose=1): """Download and load the BIDS-fied ds003_downsampled :param str data_dir: path of the data directory. Used to force data storage in a non-standard location. :param str url: download URL of the dataset. Overwrite the defaul...
d55870e661abc040bad993303c8ee60614e58371
3,626,042
def open_clean_bands(band_path, valid_range=None,): """Open/mask single landsat band using a valid reflectance value range. Parameters ----------- band_path : string A path to the array to be opened valid_range : tuple (optional) A tuple of min and max values of...
e91a8b358558d5e2f7781525a7a637e4a2b74c75
3,626,043
from datetime import datetime from typing import Tuple def calculate_new_case_data_by_region( region_timeseries: OneRegionTimeseriesDataset, t0: datetime, include_testing_correction: bool = False, testing_correction_smoothing_tau: float = 5, ) -> Tuple[np.array, np.array]: """ Calculate new ca...
3ed0829dacbc3809834b7550ea1dc12cb18a6806
3,626,044
def _field_object_metadata(field_object): """Return mapping of field metadata key to value. Args: field_object (arcpy.Field): ArcPy field object. Returns: dict. """ meta = {"object": field_object} key_attribute_name = { "alias_name": "aliasName", "base_name": "b...
1e653737f1dee41c7ce786735368e55f4908b116
3,626,045
import os def _cohn_kanade(datadir, im_shape, na_val=-1): """Creates dataset (pair of X and y) from Cohn-Kanade image data (CK+)""" images = [] labels = [] for name in os.listdir(os.path.join(datadir, 'faces')): impath = os.path.join(datadir, 'faces', name) labelpath = os.path.join...
7b84aeb41dafd7b852f17b506e08fb9b121d0ecf
3,626,046
def svn_utf_initialize2(*args): """svn_utf_initialize2(svn_boolean_t assume_native_utf8, apr_pool_t pool)""" return _core.svn_utf_initialize2(*args)
da0c3296fa6477e3a9d20669fdfd61ed5207a76d
3,626,047
def init_console(parser): """Initialises the console""" font = pygame.font.SysFont("Courier", 12) text = Text(font, size=(200, 40), position=(0, 0)) error_text = init_error_message(parser) return Console(parser, text, error_text)
8f387f83fca2fbe25283dc62c3c6ed50ec24ebd3
3,626,048
import sys def _xinf_ND(xdot,x0,args=(),xddot=None,xtol=1.49012e-8): """Private function for wrapping the fsolving for x_infinity for a variable x in N dimensions""" try: result = fsolve(xdot,x0,args,fprime=xddot,xtol=xtol,full_output=1) except (ValueError, TypeError, OverflowError): x...
ae23fdb8baa832fb181ba523fdf43aa596dbe6a2
3,626,049
def read_targets(targets): """Reads generic key-value pairs from input files""" results = {} for target, regexer in regexer_for_targets(targets): with open(target) as fh: results.update(extract_keypairs(fh.readlines(), regexer)) _LOG.debug("found the following key-value pairs in sour...
7b0689252f81328f5430acc59ad3f9c32878aafa
3,626,050
import logging async def refresh_pool_ledger(handle: int) -> None: """ Refreshes a local copy of a pool ledger and updates pool nodes connections. :param handle: pool handle returned by indy_open_pool_ledger :return: Error code """ logger = logging.getLogger(__name__) logger.debug("refre...
d6c3d53d406f9ca37b063dfd3d65a19d798a4f60
3,626,051
import _datetime def seconds_function(context, string=None): """ The date:seconds function returns the number of seconds specified by the argument string. If no argument is given, then the current local date/time, as returned by date:date-time is used as a default argument. Implements version 1. ...
8d9d1d5d6cd9d5261746ca14257bf8c2e0dc9886
3,626,052
def mean_of_cluster(list_of_points): """Calculates the center of the list of points """ number_of_points = float(len(list_of_points)) vector_total = [float(0), float(0)] for point in list_of_points: for index, component in enumerate(point): vector_total[index] += component re...
b94b5ea40fb08253bcade35282692bbb58b85e98
3,626,053
def symlog(values, threshold): """ Convert values to log with linear threshold near zero """ return np.sign(values) * np.log10(1 + np.abs(values) / threshold)
f0bcd06326eedc7a2dd65b239b2ad81499ae2d68
3,626,054
def cluster_by_best_antecedent(document, predictions, threshold=0.5): """ Clusters the document's mentions by matching each with its best antecedent with a score above the 0.5 threshold. @arg predictions Mention-pair predictions. @arg threshold The classification threshold, above this value mention...
a4c3db4ae799047340c2cfcfa4f21d7414797a86
3,626,055
def max_pooling(x, pool_h, pool_w, stride): """Max pooling.""" validator.check_integer("stride", stride, 0, Rel.GT, None) num, channel, height, width = x.shape out_h = (height - pool_h)//stride + 1 out_w = (width - pool_w)//stride + 1 col = im2col(x, pool_h, pool_w, stride) col = col.reshap...
c427c2ecd555ce48d73aa989ccfd4595d84ef36d
3,626,056
import os from functools import reduce def multiple_process(distribute_list, partition_func, task_func, n_jobs, reduce_func, parameters): """ Args: distribute_list(list): The "data" list to be partitioned, such as a list of files which will be distributed among different tasks and each t...
a070e510b071b5be6ccdf906e5e17ed693251d42
3,626,057
def get_unique_pairs(pairs, return_indices=False) -> np.array: """Extract unique pairs.""" # idx: Indices in triples of unique pairs _, idx = np.unique(pairs, return_index=True, axis=0) sorted_indices = np.sort(idx) # uniquoe pairs where original order of triples is preserved unique_pairs = pai...
3f8c6408d9a6f871e7f89278448dcaa1b5028c12
3,626,058
def preprocess_data(tokenizer, task, batch_size, dev_batch_size, max_len, vocab, world_size=None): """Train/eval Data preparation function.""" label_dtype = 'int32' if task.class_labels else 'float32' truncate_length = max_len - 3 if task.is_pair else max_len - 2 trans = partial(convert_examples_to_feat...
8ee375a58d8a827f3ab09658bf3d3927696c303b
3,626,059
def revSequence(channels, n_block): """Make a sequence of multiple reversible block Arguments: channels {[int]} -- [number of channels fixed] n_block {[int]} -- [Number of blocks] Returns: [nn.Module] -- [The reversible sequence] """ sequence = [] for i in range(n_block): sequence.append(revBlock(chan...
cd145bb5901b2e389a5fa772e3e08abba44b227d
3,626,060
def calculate_angle(v1, v2): """ Calculate the angle ([0, Pi]) between two vectors according to: p = u * v = |u||v|cos(a) Parameters ---------- v1 : arr v2 : arr Returns ------- angle : float The angle ([0, Pi]) between these two given vectors """ product = np...
9c50fe95f15ff2a6dc41d9c30f792e8aee27d831
3,626,061
def range_overlap(a_min, a_max, b_min, b_max): """ Neither range is completely greater than the other """ return (a_min <= b_max) and (b_min <= a_max)
c05d8b0799f62300760ad69704a5091c3830ad26
3,626,062
def flip_errors(data): """Flip sign for lower boundary responses. :Arguments: data : numpy.recarray Input array with at least one column named 'RT' and one named 'response' :Returns: data : numpy.recarray Input array with RTs sign flipped wher...
2ae325534658c055ff4d0cb841de696875a46aa6
3,626,063
def predict(patches, DEBUG): """ predict zebra crossing for every patches 1 is zc 0 is background """ #print(len(patches)) labels = np.zeros(len(patches)) index = 0 for Amplitude, theta in patches: mask = (Amplitude>25).astype(np.float32) h, b = np.histogram(theta[mask.astype(np....
3bc52da0c4e6e44549ab7fb8ee7598d362f1f5e1
3,626,064
from datetime import datetime import ipaddress import socket from operator import or_ def is_clone(nickname, hostmask, withdate=False): """ Checks whether a nickname is considered a clone by the bot. :param withdate: Whether to return a tuple containing both matches and the last timestamp of connection ...
8d7ee5d6a39e8fdb356f61d7e3890a9f34e3b4ca
3,626,065
import logging import copy def test_online_reads_checkpoint(): """Test that online analysis reads the checkpoint correctly in all cases""" current_log_level = logger.level logger.setLevel(logging.ERROR) # Temporarily suppress some of the logging output raw_template_script = get_template_script() ...
0a89f8bccbb7f278c7d236834518fc45b28236bb
3,626,066
def preview(df,preview_rows,preview_max_cols): """ Returns a preview of a dataframe, which contains both header rows and tail rows. """ assert type(df) is pd.DataFrame if preview_rows <= 0: preview_rows = 1 initial_max_cols = pd.get_option('display.max_columns') pd.set_option('displa...
10a6ee5c59de16cf9ff11bcb739afa8cdc8bf462
3,626,067
import json def read_json(json_file_path: str) -> dict: """Takes a JSON file and returns a dictionary""" with open(json_file_path, "r") as fp: data = json.load(fp) return data
07cb6c606de83b2b51ddcbf64f7eb45d6907f973
3,626,068
def _log10_cumulative_shmf(logmp, y0, m, xc, x0, kc, dy): """Differentiable kernel of the cumulative subhalo mass function.""" y = y0 + m * (logmp - x0) return _jax_sigmoid(logmp, xc, kc, y, y - dy)
cb82fb8d6d0cffbfe6553c9e11b4ff006ab24583
3,626,069
def internal_token_encoder() -> TokenEncoder[InternalToken]: """Return InternalToken encoder with correct secret embedded.""" return TokenEncoder( schema=InternalToken, secret=INTERNAL_TOKEN_SECRET, )
e9239e81dfa0f385f02387886a52399d2093fd94
3,626,070
import os def _get_user_guide_directory(): """Returns absolute path to docs/ directory""" docsdir = os.path.join("docs", "user_guide") return os.path.abspath(docsdir)
147294fe005f7d6756aeb4c3579bddf795668087
3,626,071
import os import math import pickle def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False): """ Trains a k-nearest neighbors classifier for face recognition. :param train_dir: directory that contains a sub-directory for each known person, with its name. (V...
17ffe96bd12b1b80b9a977b8b103b0758a6e7687
3,626,072
def index(request): """ Serve view for home page """ return render(request, "index.html")
ddcafaf5312f7c811f4aacbb3fcb6285e9b6ab22
3,626,073
import glob import os def get_env(pathname=None, *, profile_dir=None, prefix=None): """Read the BASH file and extract the variables. Currently this is done with pattern matching. Another way would be to run the BASH script as a subshell and then do a printenv and actually capture the variables :param pathname...
4b772415276796926d0466966e6867f7063c7cee
3,626,074
from typing import Tuple def _get_property_types(layer: Layer) -> Tuple[str, ...]: """Given a GDAL Layer, return the non-geometry field types.""" layer_definition = layer.GetLayerDefn() type_codes = tuple( layer_definition.GetFieldDefn(index).GetType() for index in range(layer_definition.G...
54377e5fb50b7c6953a3cf863bbaa8bf3831b0e5
3,626,075
def TInt_GetKiloStr(*args): """ TInt_GetKiloStr(int const & Val) -> TStr Parameters: Val: int const & """ return _snap.TInt_GetKiloStr(*args)
b2a0582548d86dcf3eb9e3b489776116ae9d68bc
3,626,076
def linear(x, n_units, scope=None, stddev=0.02, activation=lambda x: x): """Fully-connected network. Parameters ---------- x : Tensor Input tensor to the network. n_units : int Number of units to connect to. scope : str, optional Variable scope to use. stdd...
e0b2a70f6480dae16e384ceab6aabfc21daaa5ca
3,626,077
def RadialSymmetryFunction(R, rc, rs, e): """Calculates radial symmetry function. B = batch_size, N = max_num_atoms, M = max_num_neighbors, d = num_filters Parameters ---------- R: tf.Tensor of shape (B, N, M) Distance matrix. rc: float Interaction cutoff [Angstrom]. rs: float Gaussian dista...
7f6dc67d6f7c1d490d116528c14ca90f2b732d8d
3,626,078
def plot_curve(axis, params, train_column, valid_column, linewidth = 2, train_linestyle = "b-", valid_linestyle = "g-"): """ Plots a pair of validation and training curves on a single plot. """ model_history = np.load(Paths(params).train_history_path + ".npz") train_values = model_history[train_colu...
2efcf1a780091ae2ce2025555aeb270d20dc07e9
3,626,079
from typing import Optional from typing import Dict def set_magmoms( atoms: Atoms, elemental_mags_dict: Optional[Dict] = None, copy_magmoms: bool = True, mag_default: Optional[float] = 1.0, mag_cutoff: float = 0.05, ) -> Atoms: """ Sets the initial magnetic moments in the Atoms object. ...
80aee80bb737963247dfdd8ff2e223dbe3c9b971
3,626,080
def round_list(x, digits=6): """helper for approximate tests, round a list""" if isinstance(x, csr_matrix): x = sparse_to_dense(x) return [round(_, digits) for _ in list(x)]
ff61b1266bf6bfc5618aed13af125a64333d1457
3,626,081
def iter_to_table(value): """Convert raw API responses to response tables.""" if isinstance(value, list): return _format_list(value) if isinstance(value, dict): return _format_dict(value) return value
a4d12f677e425330368218f050d2a83d9d459a4f
3,626,082
def get_last_line(fn): """Returns the last line of a file Args: fn (str): File name of the file to read from """ with open(fn, 'r') as fin: for line in fin: pass return line
40867816657af6350aa400ab17d60b816566d5c5
3,626,083
def _gen_tinynet(variant_cfg, channel_multiplier=1.0, depth_multiplier=1.0, depth_trunc='round', pretrained=False, **kwargs): """Creates a TinyNet model. """ arch_def = [ ['ds_r1_k3_s1_e1_c16_se0.25'], ['ir_r2_k3_s2_e6_c24_se0.25'], ['ir_r2_k5_s2_e6_c40_se0.25'], ['ir_r3_k3_s2_e6_c80_se0.25'...
4836e4fbacb36af927b8ad6b81084cbd769111d3
3,626,084
from typing import OrderedDict def full_sdssmatch(img1,img2,inst,gmaglim=19): """ This function requires two stacked images, one each filter that will be used in solving the color equations. The purpose of this function is to first collect all of the SDSS sources in a given field using the ``odi.s...
b8640db90998eda702709dff33130a84301891d6
3,626,085
def calcula_menor_caminho(nome, origem, destino): """Retorna o menor caminho entre os dois pontos.""" mapa = Mapa() rotas = Rota.objects.filter(nome=nome) for rota in rotas: mapa.add_ponto(rota.origem) mapa.add_rota(rota.origem, rota.destino, ...
44000464ec156c5a0abc5e93c91564921aa827ba
3,626,086
import argparse def init(): """ The root entrypoint for the ``wa_cli`` is ``wa``. This the first command you need to access the CLI. All subsequent subcommands succeed ``wa``. """ # Main entrypoint and initialize the cmd method # set_defaults specifies a method that is called if that parser is use...
e423482375874f082718b8b672e754e9cd3c1f78
3,626,087
import logging import warnings import os def configure_logging(): """ Initialization of the logging system for the framework :return: """ global LOG debug = ConfigHelper.get(CFS_GENERAL, "debug") if debug.lower() == "true": file_level = logging.DEBUG else: file_level = ...
fa832c4716df2afb00cd2dae39e282c69ea9e63e
3,626,088
import re def HasServices(proto_path): """Does a .proto file have any service definitions? Args: proto_path: path to .proto. Returns: True iff there are service definitions in the .proto at proto_path. """ with open(proto_path, 'r', encoding='utf8') as f: for line in f: if re.match(SERVI...
e8393a0ec23dece420d7074df122adf52fe142f6
3,626,089
import posixpath import requests def _remote_file_size(url=None, file_name=None, pn_dir=None): """ Get the remote file size in bytes. Parameters ---------- url : str, optional The full url of the file. Use this option to explicitly state the full url. file_name : str, optional...
62d478f3620dd5532e9ee5657946afbce1d233b2
3,626,090
import random import tqdm import torch def estimate_compression(model, data, nsamples, context, batch_size, verbose=False): """ Estimates the compression by sampling random subsequences instead of predicting all characters. NB: This doesn't work for GPT-2 style models with super-character tokenization, s...
700e13925d7781f383c3470cd273be1d83acdab5
3,626,091
def OptionalLibraryDefines(): """ Work out what optional libraries have been asked for, and return the appropriate #define names, as a list. """ # Todo #2367 take out adaptivity, and replace with warning/error? possible_flags = {'cvode': 'CHASTE_CVODE', 'vtk': 'CHASTE_VTK', 'adaptivity': 'CHASTE...
5448a616e449a9eab0929d99a29113645e56a3dc
3,626,092
def filter_by_distance(points, mindist=4): """Evaluate the distance between each pair os points in @points and return just the ones with distance gt @mindist Args: points(set of tuples): set of positions mindist(int): minimum distance Returns: set: set of points with a minimum distance be...
1fe33da983fee9bab2fcde533191d93180cdb01e
3,626,093
def read_point_cloud_log(path: str, row_size: int, double_precision: bool = True) -> np.ndarray: """Reads a .pcl file and containing x, y, z values specifying a point cloud.""" with open(path, 'rb') as f: data_type = np.double if double_precision else np.single data = np.fromfile(f, data_type) ...
a63eb568a73f803bbb194fbd67f8759fe0b21c73
3,626,094
def HLRBRep_CurveTool_Parabola(*args): """ :param C: :type C: Standard_Address :rtype: gp_Parab2d """ return _HLRBRep.HLRBRep_CurveTool_Parabola(*args)
557fd2b10fd86db72d443fcd1f534a2496d232bc
3,626,095
import uuid def unique_variable_name(): """Creates a unique variable name. Useful when attempting to introduce a new token to see if it can fix specific cases of SyntaxError.""" name = uuid.uuid4() return "_%s" % name.hex
d4b54a8ab76fa8bddd6fe62a735f1dd886e9e62a
3,626,096
def impersonated_session_status(request): """ Adds variable to all contexts :param request: :return bool: """ return {"is_impersonated_session": is_impersonated_session(request)}
2499946653a2cb411fbe7e2b389f72c08fcec92d
3,626,097
def random_dates(start, end, size): """ Generate random dates within range between start and end. Adapted from: https://stackoverflow.com/a/50668285 """ # Unix timestamp is in nanoseconds by default, so divide it by # 24*60*60*10**9 to convert to days. divide_by = 24 * 60 * 60 * 10**9 st...
589b974b262d41f5903362fd62bfc506ed8ff40d
3,626,098
def cleaner_unicode(string): """ Objective : This method is used to clean the special characters from the report string and place ascii characters in place of them """ if string is not None: return string.encode('ascii', errors='backslashreplace') else: return string
f4e2c4b9fa7f4a644e409a5d429531a34bc1c6c2
3,626,099