content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def station_suffix(station_type): """ Simple switch, map specific types on to single letter. """ suffix = ' (No Dock)' if 'Planetary' in station_type and station_type != 'Planetary Settlement': suffix = ' (P)' elif 'Starport' in station_type: suffix = ' (L)' elif 'Asteroid' in statio...
c28c4d3f0da8401ffc0721a984ec2b2e2cd50b24
13,200
def temperatures_equal(t1, t2): """Handle 'off' reported as 126.5, but must be set as 0.""" if t1 == settings.TEMPERATURE_OFF: t1 = 0 if t2 == settings.TEMPERATURE_OFF: t2 = 0 return t1 == t2
5c054d23317565e474f6c8d30b7d87c0b832fe9f
13,201
import os def calc_cf(fname, standard='GC',thickness=1.0,plot=False,xmin=None,xmax=None,interpolation_type='linear'): """ Calculates the calibration factor by using different chosen standards like fname : filename containing the experimental data done on standard sample standard ...
68d6366d8b9d0be35509b0d4c0d65dc8c22d5668
13,202
import csv def import_capitals_from_csv(path): """Imports a dictionary that maps country names to capital names. @param string path: The path of the CSV file to import this data from. @return dict: A dictionary of the format {"Germany": "Berlin", "Finland": "Helsinki", ...} """ capitals = {} ...
3c6a9c91df455cb8721371fe40b248fb7af8d866
13,203
import os import configparser def read_config(config_file='config.ini'): """ Read the configuration file. :param str config_file: Path to the configuration file. :return: """ if os.path.isfile(config_file) is False: raise NameError(config_file, 'not found') config = configparser.C...
0cafb2f280e30467e833d404ac86a8cea03f050a
13,204
def deg_to_qcm2(p, deg): """Return the center-of-momentum momentum transfer q squared, in MeV^2. Parameters ---------- p_rel = float relative momentum given in MeV. degrees = number angle measure given in degrees """ return (p * np.sqrt( 2 * (1 ...
4b1840a8c672b443ac1954c0bde0a81a01338862
13,205
from django.conf import settings def i18n(request): """ Set client language preference, lasts for one month """ next = request.META.get('HTTP_REFERER', None) if not next: next = settings.SITE_ROOT lang = request.GET.get('lang', 'en') res = HttpResponseRedirect(next) res....
a56289c03b14b76719fc31bcee7e0e4e590f47ef
13,206
def replace_suffix(input_filepath, input_suffix, output_suffix, suffix_delimiter=None): """ Replaces an input_suffix in a filename with an output_suffix. Can be used to generate or remove suffixes by leaving one or the other option blank. TODO: Make suffixes accept regexes. Can likely replace suff...
6bc899c3ed2bcf86d085972ad6b2cd90f77269aa
13,207
import random def normal222(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2,bb1,bb2,bb3,aa1,aa2): """ for source and destination id generation """ """ for type of banking work,label of fraud and type of fraud """ idvariz=random.choice(bb3)...
5d0a4cfbd5e7ef3223cc67c4759967e86c4081c8
13,208
def _convert_to_coreml(tf_model_path, mlmodel_path, input_name_shape_dict, output_names): """ Convert and return the coreml model from the Tensorflow """ model = tf_converter.convert(tf_model_path=tf_model_path, mlmodel_path=mlmodel_path, out...
b7266a1afe0f03717a8e710f9099a0349cc5b085
13,209
def _tavella_randell_nonuniform_grid(x_min, x_max, x_star, num_grid_points, alpha, dtype): """Creates non-uniform grid clustered around a specified point. Args: x_min: A real `Tensor` of shape `(dim,)` specifying the lower limit of the grid. x_max: A real `Tensor`...
6c209871b3a8aba291b00a513056d5e1ebe111f8
13,210
import functools import logging def node(func): """Decorator for functions which should get currentIndex node if no arg is passed""" @functools.wraps(func) def node_wrapper(self, *a, **k): n = False keyword = True # Get node from named parameter if 'node' in k: ...
d86a6a9e15314905cacc184f5939399f7b481f49
13,211
import uuid def tourme_details(): """ Display Guides loan-details """ return render_template('tourme_details.html', id=str(uuid.uuid4()))
e332546257670bd26d08be8baf4122f93feab170
13,212
import json def gen_dot_ok(notebook_path, endpoint): """ Generates .ok file and return its name Args: notebook_path (``pathlib.Path``): the path to the notebook endpoint (``str``): an endpoint specification for https://okpy.org Returns: ``str``: the name of the .ok fi...
850827a3da476cc64bd50c40c2504d9765b25dfe
13,213
def sarig_methods_wide( df: pd.DataFrame, sample_id: str, element_id: str, ) -> pd.DataFrame: """Create a corresponding methods table to match the pivoted wide form data. .. note:: This requires the input dataframe to already have had methods mapping applied by running ``pygeochemtools.geoc...
95d969213de0702f3a6666e8e13ae2d37e404e3a
13,214
def scan_torsion(resolution, unique_conformers=[]): """ """ # Load the molecule sdf_filename = "sdf/pentane.sdf" suppl = Chem.SDMolSupplier(sdf_filename, removeHs=False, sanitize=True) mol = next(suppl) # Get molecule information # n_atoms = mol.GetNumAtoms() atoms = mol.GetAtoms(...
8dfd6e0443ef83361aa993be4e9613435f78bf14
13,215
def vflip_box(box: TensorOrArray, image_center: TensorOrArray) -> TensorOrArray: """Flip boxes vertically, which are specified by their (cx, cy, w, h) norm coordinates. Reference: https://blog.paperspace.com/data-augmentation-for-bounding-boxes/ Args: box (TensorOrArray[B, 4]): Bo...
99128e7b6d928c1b58457fc6d51b971c109cc77e
13,216
import pathlib def example_data(): """Example data setup""" tdata = ( pathlib.Path(__file__).parent.absolute() / "data" / "ident-example-support.txt" ) return tdata
a8c9a88f8850fecc7cc05fb8c9c18e03778f3365
13,217
def add_ending_slash(directory: str) -> str: """add_ending_slash function Args: directory (str): directory that you want to add ending slash Returns: str: directory name with slash at the end Examples: >>> add_ending_slash("./data") "./data/" """ if directory[-...
2062a55b59707dd48e5ae56d8d094c806d8a2c1d
13,218
import scipy def antenna_positions(): """ Generate antenna positions for a regular rectangular array, then return baseline lengths. - Nx, Ny : No. of antennas in x and y directions - Dmin : Separation between neighbouring antennas """ # Generate antenna positions on a regular grid x...
f47a0c887489987d8fc95205816459db55bbaa19
13,219
from typing import Union from typing import List def folds_to_list(folds: Union[list, str, pd.Series]) -> List[int]: """ This function formats string or either list of numbers into a list of unique int Args: folds (Union[list, str, pd.Series]): Either list of numbers or one str...
f499cce7992b77867fc3a7d95c8dd6efc83c3c79
13,220
import gc def predict_all(x, model, config, spline): """ Predict full scene using average predictions. Args: x (numpy.array): image array model (tf h5): image target size config (Config): spline (numpy.array): Return: prediction scene array average probabilities...
6e5888b1d97c3a0924a67500c4b731fd00654cb2
13,221
def pre_arrange_cols(dataframe): """ DOCSTRING :param dataframe: :return: """ col_name = dataframe.columns.values[0] dataframe.loc[-1] = col_name dataframe.index = dataframe.index + 1 dataframe = dataframe.sort_index() dataframe = dataframe.rename(index=str, columns={col_name: 'a...
522c0f4ca29b10d4a736d27f07d8e9dc80cafba5
13,222
import numpy def wDot(x,y,h): """ Compute the parallel weighted dot product of vectors x and y using weight vector h. The weighted dot product is defined for a weight vector :math:`\mathbf{h}` as .. math:: (\mathbf{x},\mathbf{y})_h = \sum_{i} h_{i} x_{i} y_{i} All weight vector ...
e9bcc295517060f95004aec581055950358c9521
13,223
def dataframify(transform): """ Method which is a decorator transforms output of scikit-learn feature normalizers from array to dataframe. Enables preservation of column names. Args: transform: (function), a scikit-learn feature selector that has a transform method Returns: new_t...
cf21bb7aea90e742c83fb5e1abb41c5d01cddf4e
13,224
def plot_map(self, map, update=False): """ map plotting Parameters ---------- map : ndarray map to plot update : Bool updating the map or plotting from scratch """ if update: empty=np.empty(np.shape(self.diagnostics[self.diagnostic])) empty[:]=np.nan ...
a4effd8c7e958b694f2c01afdaa861455c855a0b
13,225
def definition_activate(connection, args): """Activate Business Service Definition""" activator = sap.cli.wb.ObjectActivationWorker() activated_items = ((name, sap.adt.ServiceDefinition(connection, name)) for name in args.name) return sap.cli.object.activate_object_list(activator, activated_items, coun...
61dd5de0d8e24339c67363e904628390cc79b1da
13,226
import re def extractCompositeFigureStrings(latexString): """ Returns a list of latex figures as strings stripping out captions. """ # extract figures figureStrings = re.findall(r"\\begin{figure}.*?\\end{figure}", latexString, re.S) # filter composite figures only and remove captions (preserv...
83a80c91890d13a6a0247745835e1ffb97d579f7
13,227
import time def osm_net_download( polygon=None, north=None, south=None, east=None, west=None, network_type="all_private", timeout=180, memory=None, date="", max_query_area_size=50 * 1000 * 50 * 1000, infrastructure='way["highway"]', ): """ Download OSM ways and ...
faf949e015c365c3822131634f55c73e2e9fef0c
13,228
import os import logging def _find_results_files(source_path: str, search_depth: int = 2) -> list: """Looks for results.json files in the path specified Arguments: source_path: the path to use when looking for result files search_depth: the maximum folder depth to search Return: Re...
1116ff41301754e79a43a0d25462eddeee3bafa3
13,229
from re import S def rubi_integrate(expr, var, showsteps=False): """ Rule based algorithm for integration. Integrates the expression by applying transformation rules to the expression. Returns `Integrate` if an expression cannot be integrated. Parameters ========== expr : integrand expre...
25eccde81fe0425fbf35c522b24e79195684f537
13,230
def daily_price_read(sheet_name): """ 读取股票名称和股票代码 :param sheet_name: :return: """ sql = "SELECT * FROM public.%s limit 50000" % sheet_name resultdf = pd.read_sql(sql, engine_postgre) resultdf['trade_date'] = resultdf['trade_date'].apply(lambda x: x.strftime('%Y-%m-%d')) resultdf['cod...
d68c326604c21b6375e77fb012a9776d87be617f
13,231
def _isfloat(string): """ Checks if a string can be converted into a float. Parameters ---------- value : str Returns ------- bool: True/False if the string can/can not be converted into a float. """ try: float(string) return True except ValueError...
74ae50761852d8b22ac86f6b6332bd70e42bf623
13,232
def get(url, **kwargs): """ get json data from API :param url: :param kwargs: :return: """ try: result = _get(url, **kwargs) except (rq.ConnectionError, rq.ReadTimeout): result = {} return result
a3c17ce6ab383373e7215dd0e5b3e63130739126
13,233
def sample_indep(p, N, T, D): """Simulate an independent sampling mask.""" obs_ind = np.full((N, T, D), -1) for n in range(N): for t in range(T): pi = np.random.binomial(n=1, p=p, size=D) ind = np.where(pi == 1)[0] count = ind.shape[0] obs_ind[n, t, :c...
69a469d45040ed1598f7d946b6706f70f23dc580
13,234
def _relabel_targets(y, s, ranks, n_relabels): """Compute relabelled targets based on predicted ranks.""" demote_ranks = set(sorted(ranks[(s == 0) & (y == 1)])[:n_relabels]) promote_ranks = set(sorted(ranks[(s == 1) & (y == 0)])[-n_relabels:]) return np.array([ _relabel(_y, _s, _r, promote_ranks...
e8c06364a717210da6c0c60c883fee05d61ed3eb
13,235
def exp(x): """Take exponetial of input x. Parameters ---------- x : Expr Input argument. Returns ------- y : Expr The result. """ return call_pure_intrin(x.dtype, "exp", x)
9ec31c0b9928108680c2818d1fe110d36c81b08d
13,236
def check_table(words_in_block, block_width, num_lines_in_block): """ Check if a block is a block of tables or of text.""" # average_words_per_line=24 # total_num_words = 0 ratio_threshold = 0.50 actual_num_chars = 0 all_char_ws = [] cas = [] # total_num_words += len(line) if num_li...
46c785eefc7694a88d1814b9ca01f41fffa9d1f8
13,237
def defaultSampleFunction(xy1, xy2): """ The sample function compares how similar two curves are. If they are exactly the same it will return a value of zero. The default function returns the average error between each sample point in two arrays of x/y points, xy1 and xy2. Parameters -...
5654145e9a2d3701d289094ababc94d9ed972def
13,238
from re import S def makesubs(formula,intervals,values=None,variables=None,numden=False): """Generates a new formula which satisfies this condition: for all positive variables new formula is nonnegative iff for all variables in corresponding intervals old formula is nonnegative. >>> newproof() >>> makesubs('1-x^...
238923ac5e6e9e577f90091b61b6182323fdee75
13,239
def generateKey(accountSwitchKey=None,keytype=None): """ Generate Key""" genKeyEndpoint = '/config-media-live/v2/msl-origin/generate-key' if accountSwitchKey: params = {'accountSwitchKey': accountSwitchKey} params["type"] = keytype key = prdHttpCaller.getResult(genKeyEndpoint, params...
5da825d809fbb03b5929bcc14f0da0451eaf639a
13,240
def positions_count_for_one_ballot_item_doc_view(request): """ Show documentation about positionsCountForOneBallotItem """ url_root = WE_VOTE_SERVER_ROOT_URL template_values = positions_count_for_one_ballot_item_doc.positions_count_for_one_ballot_item_doc_template_values( url_root) templ...
3c56d186560fa8fae6117b6b656ee0c8d40a8728
13,241
def atcab_sign_base(mode, key_id, signature): """ Executes the Sign command, which generates a signature using the ECDSA algorithm. Args: mode Mode determines what the source of the message to be signed (int) key_id Private key slot used to sign the message. (int) ...
87c9770d6ba456947206ea1abb46b10a3f413811
13,242
from typing import List def load_gs( gs_path: str, src_species: str = None, dst_species: str = None, to_intersect: List[str] = None, ) -> dict: """Load the gene set file (.gs file). Parameters ---------- gs_path : str Path to the gene set file with the following two columns, s...
0e13c355b1a3bd7e88785844262a01c6963ef0ee
13,243
from .points import remove_close def sample_surface_even(mesh, count, radius=None): """ Sample the surface of a mesh, returning samples which are VERY approximately evenly spaced. This is accomplished by sampling and then rejecting pairs that are too close together. Parameters ---------...
9dd9c4aa27f4811511d81ef0c8dabe3097026061
13,244
def allocate_probabilities(results, num_substations, probabilities): """ Allocate cumulative probabilities. Parameters ---------- results : list of dicts All iterations generated in the simulation function. num_substations : list The number of electricity substation nodes we wis...
5692517aa55776c94c7f4027f175eab985000fe1
13,245
def import_one_record_sv01(r, m): """Import one ODK Site Visit 0.1 record into WAStD. Arguments r The record as dict, e.g. { "instanceID": "uuid:cc7224d7-f40f-4368-a937-1eb655e0203a", "observation_start_time": "2017-03-08T07:10:43.378Z", "reporter": "florianm", "photo_s...
ac6cbd8c743241000adbc3395da48b926f71ee78
13,246
def delete_page_groups(request_ctx, group_id, url, **request_kwargs): """ Delete a wiki page :param request_ctx: The request context :type request_ctx: :class:RequestContext :param group_id: (required) ID :type group_id: string :param url: (required) ID :type url...
d9802d66e87eb0ef9e9fe5bee98686caade3e79d
13,247
import os def envset(name): """Return True if the given environment variable is set An environment variable is considered set if it is assigned to a value other than 'no', 'n', 'false', 'off', '0', or '0.0' (case insensitive) """ return os.environ.get(name, 'no').lower() not in ['no', 'n', ...
cb501aa5e106e342d7c8e02bc46f5f0a2621dc00
13,248
def solver(f, p_e, mesh, degree=1): """ Solving the Darcy flow equation on a unit square media with pressure boundary conditions. """ # Creating mesh and defining function space V = FunctionSpace(mesh, 'P', degree) # Defining Dirichlet boundary p_L = Constant(1.0) def boundary_L(x, on...
0630b1199f064044976c24d825332aa2d879dab2
13,249
def set_stretchmatrix(coefX=1.0, coefY=1.0): """Stretching matrix Args: coefX: coefY:coefficients (float) for the matrix [coefX 0 0 coefY] Returns: strectching_matrix: matrix """ return np.array([[coefX, 0],[0, coefY]])
cd11bf0351a205e52b1f99893fe43709636978d3
13,250
def set_bit(v, index, x): """Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value.""" mask = 1 << index # Compute mask, an integer with just bit 'index' set. v &= ~mask # Clear the bit indicated by the mask (if x is False) if x: v |= mask # If x was True, set the...
627744c06709eecec18f0c5956f1af4c57a57b8a
13,251
def test_credentials() -> (str, str): """ Read ~/.synapseConfig and retrieve test username and password :return: endpoint, username and api_key """ config = _get_config() return config.get(DEFAULT_CONFIG_AUTH_SECTION, DEFAULT_CONFIG_USERNAME_OPT),\ config.get(DEFAULT_CONFIG_AUTH_SECT...
2ceb441b338b5ea8b1154c19406af9b1e21ed85e
13,252
import re def BCA_formula_from_str(BCA_str): """ Get chemical formula string from BCA string Args: BCA_str: BCA ratio string (e.g. 'B3C1A1') """ if len(BCA_str)==6 and BCA_str[:3]=='BCA': # format: BCAxyz. suitable for single-digit integer x,y,z funits = BCA_str[-3:] e...
36375e62d70995628e253ba68ba8b777eb88d728
13,253
import numpy def get_strongly_connected_components(graph): """ Get strongly connected components for a directed graph The returned list of components is in reverse topological order, i.e., such that the nodes in the first component have no dependencies on other components. """ nodes = lis...
42783756d8fdada032e2d0ca8a306f10d4977e16
13,254
def dot(a, b): """ Computes a @ b, for a, b of the same rank (both 2 or both 3). If the rank is 2, then the innermost dimension of `a` must match the outermost dimension of `b`. If the rank is 3, the first dimension of `a` and `b` must be equal and the function computes a batch matmul. Sup...
789c9d045d82eb048ff5319d5a7ae99ffb02376d
13,255
def unreshuffle_2d(x, i0, shape): """Undo the reshuffle_2d operation.""" x_flat = unreshuffle_1d(x, i0) x_rev = np.reshape(x_flat, shape) x_rev[1::2, :] = x_rev[1::2, ::-1] # reverse all odd rows return x_rev
72cf59b9e547cf2eb516fca33e9eea7d01c1702b
13,256
def findNodeJustBefore(target, nodes): """ Find the node in C{nodes} which appeared immediately before C{target} in the input document. @type target: L{twisted.web.microdom.Element} @type nodes: C{list} of L{twisted.web.microdom.Element} @return: An element from C{nodes} """ result = No...
85d435a2c10dbaabb544c81d440e2110a6083dd7
13,257
def _format_line(submission, position, rank_change, total_hours): """ Formats info about a single post on the front page for logging/messaging. A single post will look like this: Rank Change Duration Score Flair Id User Slug 13. +1 10h 188 [Episode](gkvlja) <AutoLovepon> <...
70840d0e57194b43fbaf0352ebecdfefa74bd4d7
13,258
from typing import List from typing import Dict from typing import Any from typing import Tuple def run_erasure( # pylint: disable = too-many-arguments privacy_request: PrivacyRequest, policy: Policy, graph: DatasetGraph, connection_configs: List[ConnectionConfig], identity: Dict[str, Any], a...
2b9579ca1c4960da46ee7bb1388ab667dc808f40
13,259
from .build_helper import get_script_module import sys import os def write_module_scripts(folder, platform=sys.platform, blog_list=None, default_engine_paths=None, command=None): """ Writes a couple of scripts which allow a user to be faster on some tasks or to easily get informat...
fe8921b4440b78f6788fe4a41874da1f9fb8228d
13,260
def RichTextBuffer_FindHandlerByName(*args, **kwargs): """RichTextBuffer_FindHandlerByName(String name) -> RichTextFileHandler""" return _richtext.RichTextBuffer_FindHandlerByName(*args, **kwargs)
1122822db4885b6d745f4e893522fb01b988ee3f
13,261
def likelihood(tec, phase, tec_conversion, lik_sigma, K = 2): """ Get the likelihood of the tec given phase data and lik_var variance. tec: tensor B, 1 phase: tensor B, Nf tec_conversion: tensor Nf lik_sigma: tensor B, 1 (Nf) Returns: log_prob: tensor (B,1) """ mu = wrap(tec*tec_...
c5f566484ee8f8cbc48e5302365f0e06c81f49e3
13,262
def angle_between(v1, v2): """Returns the angle in radians between vectors 'v1' and 'v2':: >>> angle_between((1, 0, 0), (0, 1, 0)) 1.5707963267948966 >>> angle_between((1, 0, 0), (1, 0, 0)) 0.0 >>> angle_between((1, 0, 0), (-1, 0, 0)) 3.141592653589793 """ # https://stackoverflow.co...
fc2246c9d3fb55a0c2f692c1533e821a187599b8
13,263
from aiida.engine import ExitCode from ase.lattice.cubic import FaceCenteredCubic from ase.lattice.cubic import BodyCenteredCubic def create_substrate_bulk(wf_dict_node): """ Calcfunction to create a bulk structure of a substrate. :params wf_dict: AiiDA dict node with at least keys lattice, host_symbol a...
cb232093c3f6866bd14d2b19115ef988f279bf2f
13,264
def run_Net_on_multiple(patchCreator, input_to_cnn_depth=1, cnn = None, str_data_selection="all", save_file_prefix="", apply_cc_filtering = False, output_filetype = 'h5', save_prob_map = False): """ run runNetOnSlice() on neighbouring blocks of data. if opt_...
9d4c9c2fa3248258299243e3d7585362f47776a2
13,265
def user_to_janrain_capture_dict(user): """Translate user fields into corresponding Janrain fields""" field_map = getattr(settings, 'JANRAIN', {}).get('field_map', None) if not field_map: field_map = { 'first_name': {'name': 'givenName'}, 'last_name': {'name': 'familyName'},...
767b7003a282e481c1d1753f4c469fec42a5002a
13,266
from typing import Callable from typing import Optional from typing import Generator def weighted(generator: Callable, directed: bool = False, low: float = 0.0, high: float = 1.0, rng: Optional[Generator] = None) -> Callable: """ Takes as input a graph generator and returns a new generator functi...
d4c4d0b93784ca7bee22ecaffc3e8005315aa631
13,267
import argparse import os def arg_parse(dataset, view, num_shots=2, cv_number=5): """ arguments definition method """ parser = argparse.ArgumentParser(description='Graph Classification') parser.add_argument('--mode', type=str, default='train', choices=['train', 'test']) parser.a...
4758fb939584f0433fb669fd03939d54c498f375
13,268
def generate_sampled_graph_and_labels(triplets, sample_size, split_size, num_rels, adj_list, degrees, negative_rate,tables_id, sampler="uniform"): """Get training graph and signals First perform edge neighborhood sampling on graph, then...
7386eada0e0aa70478c063aa4525c62cbc997b2e
13,269
import optparse def ParseArgs(): """Parses command line options. Returns: An options object as from optparse.OptionsParser.parse_args() """ parser = optparse.OptionParser() parser.add_option('--android-sdk', help='path to the Android SDK folder') parser.add_option('--android-sdk-tools', ...
492894d0cb4faf004f386ee0f4285180d0a6c37d
13,270
def get_interface_from_model(obj: Base) -> str: """ Transform the passed model object into an dispatcher interface name. For example, a :class:``Label`` model will result in a string with the value `labels` being returned. :param obj: the model object :return: the interface string """ ...
2ee8d1ac86b0d8d6433ace8d58483dbf91af997b
13,271
import codecs def get_text(string, start, end, bom=True): """This method correctly accesses slices of strings using character start/end offsets referring to UTF-16 encoded bytes. This allows for using character offsets generated by Rosette (and other softwares) that use UTF-16 native string represent...
ffe3c74a248215a82b0e0a5b105f5e4c94c8c2a8
13,272
import math def init_distance(graph: dict, s: str) -> dict: """ 初始化其他节点的距离为正无穷 防止后面字典越界 """ distance = {s: 0} for vertex in graph: if vertex != s: distance[vertex] = math.inf return distance
dd8ceda3ca7435b5f02b7b47a363f017f796bc36
13,273
def read_cry_data(path): """ Read a cry file and extract the molecule's geometry. The format should be as follows:: U_xx U_xy U_xz U_yx U_yy U_yz U_zx U_zy U_zz energy (or comment, this is ignored for now) ele0 x0 y0 z0 ele1 x1 y1 z1 ... elen...
3a7a88e9d70c5f7499ad219602062ad2d852139b
13,274
import torch def get_camera_wireframe(scale: float = 0.3): """ Returns a wireframe of a 3D line-plot of a camera symbol. """ a = 0.5 * torch.tensor([-2, 1.5, 4]) b = 0.5 * torch.tensor([2, 1.5, 4]) c = 0.5 * torch.tensor([-2, -1.5, 4]) d = 0.5 * torch.tensor([2, -1.5, 4]) C = torch.zer...
65bb8fa078f2f6f3edb38ac86da0603073fd413f
13,275
def read_input(file): """ Args: file (idx): binary input file. Returns: numpy: arrays for our dataset. """ with open(file, 'rb') as file: z, d_type, d = st.unpack('>HBB', file.read(4)) shape = tuple(st.unpack('>I', file.read(4))[0] for d in range(d)) retur...
91b10314a326380680898efdb8a7d15aa7a84f24
13,276
from typing import List def maximum_segment_sum(input_list: List): """ Return the maximum sum of the segments of a list Examples:: >>> from pyske.core import PList, SList >>> maximum_segment_sum(SList([-5 , 2 , 6 , -4 , 5 , -6 , -4 , 3])) 9 >>> maximum_segment_sum(PList.f...
a42b41f3a3b020e0bcba80b557c628b2a0805caf
13,277
def list_files(tag=None, sat_id=None, data_path=None, format_str=None): """Return a Pandas Series of every file for chosen satellite data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. (default=None) sat_id : (string or NoneType) Specifies th...
a302202b7a12534186cfabe66a788df5c29b3266
13,278
def has_bookmark(uri): """ Returns true if the asset with given URI has been bookmarked by the currently logged in user. Returns false if there is no currently logged in user. """ if is_logged_in(): mongo.db.bookmarks.ensure_index('username') mongo.db.bookmarks.ensure_in...
8571c8b50c28a0e8829a143b1d33fd549cfad213
13,279
import six import tqdm def evaluate(f, K, dataiter, num_steps): """Evaluates online few-shot episodes. Args: model: Model instance. dataiter: Dataset iterator. num_steps: Number of episodes. """ if num_steps == -1: it = six.moves.xrange(len(dataiter)) else: it = six.moves.xrange(num_ste...
a6feebd96907f01789dd74bfb22e5a5306010bf9
13,280
def find_period_of_function(eq,slopelist,nroots): """This function finds the Period of the function. It then makes a list of x values that are that period apart. Example Input: find_period_of_function(eq1,[0.947969,1.278602]) """ global tan s1 = slopelist[0] s2 = slopelist[1] if tan == 1...
491d853aa99a31348a3acce1c29cc508e7ab3b69
13,281
def merge_date_tags(path, k): """called when encountering only tags in an element ( no text, nor mixed tag and text) Arguments: path {list} -- path of the element containing the tags k {string} -- name of the element containing the tags Returns: whatever type you want -- th...
2ae3bd0dada288b138ee450103c0b4412a841336
13,282
def ocp_play(): """Decorator for adding a method as an common play search handler.""" def real_decorator(func): # Store the flag inside the function # This will be used later to identify the method if not hasattr(func, 'is_ocp_playback_handler'): func.is_ocp_playback_handler ...
9e96fe81b331820bf7485501e458cbb4efba4328
13,283
def _scatter(x_arr, y_arr, attributes, xlabel=None, xlim=None, xlog=False, ylabel=None, ylim=None, ylog=False, show=True, save=None): """Private plotting utility function.""" # initialise figure and axis settings fig = plt.figure() ...
8494f9398ea0e5d197a58ea341c626e03d47b028
13,284
def first_item(iterable, default=None): """ Returns the first item of given iterable. Parameters ---------- iterable : iterable Iterable default : object Default value if the iterable is empty. Returns ------- object First iterable item. """ if not ...
f5ebbaea7cf4152382fb4b2854f68a3320d21fdc
13,285
def stratification(n_subjects_per_strata, n_groups, block_length=4, seed=None): """ Create a randomization list for each strata using Block Randomization. If a study has several strata, each strata is seperately randomized using block randomization. Args: n_subjects_per_strata: A list of the n...
22675c178b389e6d22586fb6640fb1adc1169996
13,286
def ensure_binary(s, encoding='utf-8', errors='strict'): """Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, text_type): return s.encod...
086d2e50b083a869fff2c06b4da7c04975b19fa3
13,287
def FileDialog(prompt='ChooseFile', indir=''): """ opens a wx dialog that allows you to select a single file, and returns the full path/name of that file """ dlg = wx.FileDialog(None, message = prompt, defaultDir = indir) if dl...
cef7816a40297a5920359b2dba3d7e3e6f6d11ec
13,288
def my_account(): """ Allows a user to manage their account """ user = get_user(login_session['email']) if request.method == 'GET': return render_template('myAccount.html', user=user) else: new_password1 = request.form.get('userPassword1') new_password2 = request.form.get...
f3e762931201ed82fa07c7b08c8bc9913c3729dd
13,289
from typing import List def __pad_assertwith_0_array4D(grad: 'np.ndarray', pad_nums) -> 'np.ndarray': """ Padding arrary with 0 septally. :param grad: :param pad_nums: :return: """ gN, gC, gH, gW = grad.shape init1 = np.zeros((gN, gC, gH + (gH - 1) * pad_nums, gW), dtype = grad.dtype)...
3562e42800c25a059f82a0d163e239badefdcfd3
13,290
def islist(data): """Check if input data is a list.""" return isinstance(data, list)
98769191b0215f8f863047ccc0c37e4d0af0a444
13,291
def spatial_mean(xr_da, lon_name="longitude", lat_name="latitude"): """ Perform averaging on an `xarray.DataArray` with latitude weighting. Parameters ---------- xr_da: xarray.DataArray Data to average lon_name: str, optional Name of x-coordinate lat_name: str, optional ...
5afb6cb9e9a6b88cc3368da4f3544ea9b7c217be
13,292
def rank(value_to_be_ranked, value_providing_rank): """ Returns the rank of ``value_to_be_ranked`` in set of values, ``values``. Works even if ``values`` is a non-orderable collection (e.g., a set). A binary search would be an optimized way of doing this if we can constrain ``values`` to be an order...
18c2009eb59b62a2a3c63c69d55f84a6f51e5953
13,293
def Characteristics(aVector): """ Purpose: Compute certain characteristic of data in a vector Inputs: aVector an array of data Initialize: iMean mean iMed median iMin minimum iMax maximum iKurt kurtosis iS...
228ba375a7fca9a4e13920e6eadd0dab83b0847c
13,294
def loglik(alpha,gamma_list,M,k): """ Calculate $L_{[\alpha]}$ defined in A.4.2 """ psi_sum_gamma=np.array(list(map(lambda x: psi(np.sum(x)),gamma_list))).reshape((M,1)) # M*1 psi_gamma=psi(np.array(gamma_list)) # M*k matrix L=M*gammaln(np.sum(alpha)-np.sum(gammaln(alpha)))+np.sum((psi_gamma-ps...
233307f7ef4e350bec162199a5d0cd8c773b4151
13,295
from gum.indexer import indexer, NotRegistered def handle_delete(sender_content_type_pk, instance_pk): """Async task to delete a model from the index. :param instance_pk: :param sender_content_type_pk: """ try: sender_content_type = ContentType.objects.get(pk=sender_content_type_pk) ...
049af2041e3ea33bdfddf81c72aeb95b04e5f60c
13,296
import os def get_file_hashes(directory_path): """Returns hashes of all files in directory tree, excluding files with extensions in FILE_EXTENSIONS_TO_IGNORE or files that should not be built. Args: directory_path: str. Root directory of the tree. Returns: dict(str, str). Dictionary ...
95c9e4c3ff0455b784cca083838e3a4b7a0dd496
13,297
def fixedcase_word(w, truelist=None): """Returns True if w should be fixed-case, None if unsure.""" if truelist is not None and w in truelist: return True if any(c.isupper() for c in w[1:]): # tokenized word with noninitial uppercase return True if len(w) == 1 and w.isupper() and...
9047866f7117e8b1e4090c8e217c3063cfd37c38
13,298
import torch import types def linspace( start, stop, num=50, endpoint=True, retstep=False, dtype=None, split=None, device=None, comm=None, ): """ Returns num evenly spaced samples, calculated over the interval [start, stop]. The endpoint of the interval can optionally b...
0597835fae9658f65553496b1272d786678919c2
13,299