content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def crop_point_data_to_base_raster(raster_name, raster_directory, csv_file, EPSG_code = 0): """ This function create a new csv file cropped to the base raster. It can lower the processing time if your point data is on a significantly larger area than the base raster. """ print("ok let me load your datas...
0392d9633381948ef338c3233ed2f4b81d520678
23,000
def generate_schedule_report_data(pools_info, pools_allocated_mem): """ Generate the schedule report data. :param pools_info: (dict) The information about the configuration and statistics of the pool participating in the scheduling. :param pools_allocated_mem: (dict) The allocated memory of the...
e9fb9f517c1fe29d9f4c867b416969374f4acd36
23,001
def create_feature_rule_json(device, feature="foo", rule="json"): """Creates a Feature/Rule Mapping and Returns the rule.""" feature_obj, _ = ComplianceFeature.objects.get_or_create(slug=feature, name=feature) rule = ComplianceRule( feature=feature_obj, platform=device.platform, conf...
985dfccab39c54478ba36f10020779dbd1b6b466
23,002
def default_sv2_sciencemask(): """Returns default mask of bits for science targets in SV1 survey. """ sciencemask = 0 sciencemask |= sv2_mask["LRG"].mask sciencemask |= sv2_mask["ELG"].mask sciencemask |= sv2_mask["QSO"].mask sciencemask |= sv2_mask["BGS_ANY"].mask sciencemask |= sv2_mas...
cf6b45d069ab8538350d35ce28d8fae4ed6525b2
23,003
def solver_softmax(K, R): """ K = the number of arms (domains) R = the sequence of past rewards """ softmax = np.zeros(K, dtype=float) for i, r in R.items(): softmax[i] = np.mean(r) softmax = np.exp(softmax) / np.exp(softmax).sum() si = np.random.choice(np.arange(0, K, 1), size...
3ac8984f70c8594f48b00df4d9b15e69dad416ba
23,004
def mapview(request): """Map view.""" context = basecontext(request, 'map') return render(request, 'map.html', context=context)
9c03377c3d047b1672c4ac1972e5552ecdc7488a
23,005
def adapt_coastdat_weather_to_pvlib(weather, loc): """ Adapt the coastdat weather data sets to the needs of the pvlib. Parameters ---------- weather : pandas.DataFrame Coastdat2 weather data set. loc : pvlib.location.Location The coordinates of the weather data point. Retur...
01a7c4340ed2542bb2fe624d6a02e4c82f3ff984
23,006
def bprop_distribute(arr, shp, out, dout): """Backpropagator for primitive `distribute`.""" return (array_reduce(scalar_add, dout, shape(arr)), zeros_like(shp))
5bfd9f1e6ec3b50e4fd13a3a26466ee57e7f084e
23,007
def ids_to_non_bilu_label_mapping(labelset: LabelSet) -> BiluMappings: """Mapping from ids to BILU and non-BILU mapping. This is used to remove the BILU labels to regular labels""" target_names = list(labelset["ids_to_label"].values()) wo_bilu = [bilu_label.split("-")[-1] for bilu_label in target_names] ...
ed6b42784661a7db693a1ea5ba65e9a1f830a46a
23,008
def generate_input_types(): """ Define the different input types that are used in the factory :return: list of items """ input_types = ["Angle_irons", "Tubes", "Channels", "Mig_wire", "Argon_gas", "Galvanised_sheets", "Budget_locks", "Welding_rods", "Body_filler", "Grinding_discs"...
d9e10624daaf5dae92f15512c9b19c47af002139
23,009
from qharv.inspect.axes_elem_pos import ase_tile as atile def ase_tile(cell, tmat): """Create supercell from primitive cell and tiling matrix Args: cell (pyscf.Cell): cell object tmat (np.array): 3x3 tiling matrix e.g. 2*np.eye(3) Return: pyscf.Cell: supercell """ try: except ImportError: ...
d37d5b5d2cab42d10e7495724bd5cba4391c71e4
23,010
import os import errno import signal def timeout(timeout_sec, timeout_callback=None): """Decorator for timing out a function after 'timeout_sec' seconds. To be used like, for a 7 seconds timeout: @timeout(7, callback): def foo(): ... Args: timeout_sec: duration to wait for the fun...
c523b6d900109eebb8c4d4832bcae70c23fdeefc
23,011
def parse_chat_logs(input_path, user, self): """ Get messages from a person, or between that person and yourself. "self" does not necessarily have to be your name. Args: input_path (str): Path to chat log HTML file user (str): Full name of person, as appears in Messenger app se...
b0d9a19d7f27589dac7757539c9d1595150ec0f4
23,012
def pressure_correction(pressure, rigidity): """ function to get pressure correction factors, given a pressure time series and rigidity value for the station :param pressure: time series of pressure values over the time of the data observations :param rigidity: cut-off rigidity of the station making the...
9a1baeacc7c954f8825dcd279518357534d84a06
23,013
import os def get_file_size(file_name): """ :rtype numeric: the number of bytes in a file """ bytes = os.path.getsize(file_name) return humanize_bytes(bytes)
203ee020108bf4d91f5494b9a56cb0dd78d64c20
23,014
import os def get_project_path_info(): """ 获取项目路径 project_path 指整个git项目的目录 poseidon_path 指git项目中名字叫poseidon的目录 """ _poseidon_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) _project_path = os.path.dirname(_poseidon_path) return {"project_path": _project_path, ...
758748df0befedc46ae913c0b9193d3ddb175d95
23,015
def prepare_data(song: dict) -> dict: """ Prepares song dataa for database insertion to cut down on duplicates :param song: Song data :return: The song data """ song['artist'] = song['artist'].upper().strip() song['title'] = song['title'].upper().strip() return song
f8f8c9a3a0fe510cb3fb2e7d6d5bd361721337e7
23,016
def com(struct): """ Calculates center of mass of the system. """ geo_array = struct.get_geo_array() element_list = struct.geometry['element'] mass = np.array([atomic_masses_iupac2016[atomic_numbers[x]] for x in element_list]).reshape(-1) total = np.sum(mass) com = n...
239ff2d153739c80f6a4f723fc8060d7418a4862
23,017
def distance_matrix(values, metric): """Generate a matrix of distances based on the `metric` calculation. :param values: list of sequences, e.g. list of strings, list of tuples :param metric: function (value, value) -> number between 0.0 and 1.0""" matrix = [] progress = ProgressTracker(len(values))...
339adc59d3b6198d9bc55d7c6504c5489e7770b2
23,018
import struct def _Pack(content, offset, format_string, values): """Pack values to the content at the offset. Args: content: String to be packed. offset: Offset from the beginning of the file. format_string: Format string of struct module. values: Values to struct.pack. Returns: Updated con...
c164298e1e8963b20cfabcd38f3d8e44722751ae
23,019
import math def get_rotation_matrix(orientation): """ Get the rotation matrix for a rotation around the x axis of n radians Args: - (float) orientation in radian Return: - (np.array) rotation matrix for a rotation around the x axis """ rotation_matrix = np.array( [[1, ...
0f795c974599382039106f28f20c4c48cdd77bb6
23,020
def machinesize(humansize): """convert human-size string to machine-size""" if humansize == UNKNOWN_SIZE: return 0 try: size_str, size_unit = humansize.split(" ") except AttributeError: return float(humansize) unit_converter = { 'Byte': 0, 'Bytes': 0, 'kB': 1, 'MB': 2...
8694d6ac3b2aa1b6624d2fea7a8ce4544f713c36
23,021
import networkx import torch def generate_erdos_renyi_netx(p, N): """ Generate random Erdos Renyi graph """ g = networkx.erdos_renyi_graph(N, p) W = networkx.adjacency_matrix(g).todense() return g, torch.as_tensor(W, dtype=torch.float)
fbb8e293a1b35958301c2e376a03c30012b0c33b
23,022
def kmc_algorithm(process_list): """ :param rate_list: List with all the computed rates for all the neighbours for all the centers :param process_list: List of elements dict(center, process, new molecule). The indexes of each rate in rate_list have the same index that the associated process in proce...
5812498f83eede2f6de6f669bd87312705c13be3
23,023
def __matlab_round(x: float = None) -> int: """Workaround to cope the rounding differences between MATLAB and python""" if x - np.floor(x) < 0.5: return int(np.floor(x)) else: return int(np.ceil(x))
d24298c9c072fc83a531fcd498f81c715accf229
23,024
def rayleightest(circ_data, dim='time'): """Returns the p-value for the Rayleigh test of uniformity This test is used to identify a non-uniform distribution, i.e. it is designed for detecting an unimodal deviation from uniformity. More precisely, it assumes the following hypotheses: - H0 (null hyp...
74342adefe71f1e3193d52af6f716f20c538848f
23,025
from typing import Union from pathlib import Path import yaml def load_cfg(cfg_file: Union[str, Path]) -> dict: """Load the PCC algs config file in YAML format with custom tag !join. Parameters ---------- cfg_file : `Union[str, Path]` The YAML config file. Returns ------- `d...
c9137c5052adf8fa62913c352df2bfe9e79fc7ce
23,026
def pdist_triu(x, f=None): """Pairwise distance. Arguments: x: A set of points. shape=(n,d) f (optional): A kernel function that computes the similarity or dissimilarity between two vectors. The function must accept two matrices with shape=(m,d). Returns...
19d8acb0b38b8dcb6b5b99a1bf7691e055c2ef6d
23,027
import buildingspy.simulate.Simulator as si from buildingspy.io.outputfile import Reader from scipy.interpolate import interp1d from builtins import str import getpass import os import tempfile def simulate_in_dymola(heaPum, data, tableName, tableFileName): """ Evaluate the heat pump performance from the model in...
22afe312252b8275c5b1dbbc271e6acacecc789f
23,028
def get_model_defaults(cls): """ This function receives a model class and returns the default values for the class in the form of a dict. If the default value is a function, the function will be executed. This is meant for simple functions such as datetime and uuid. Args: cls: (obj) : A Mo...
93c29af27446c558b165159cee4bb41bbb3cad4d
23,029
def add_response_headers(headers=None): """This decorator adds the headers passed in to the response""" headers = headers or {} def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): resp = make_response(f(*args, **kwargs)) h = resp.headers ...
9f26048dcff6de65d9a25ede6002c955f1551ff5
23,030
def restore(request: Request, project_id: int) -> JSONResponse: # pylint: disable=invalid-name,redefined-builtin """Restore project. Args: project_id {int}: project id Returns: starlette.responses.JSONResponse """ log_request(request, { 'project_id': project_id }) ...
0316132e42331ec9fe3b5c4ce73c364cc4726e2b
23,031
def _broadcast_arrays(x, y): """Broadcast arrays.""" # Cast inputs as numpy arrays # with nonzero dimension x = np.atleast_1d(x) y = np.atleast_1d(y) # Get shapes xshape = list(x.shape) yshape = list(y.shape) # Get singltons that mimic shapes xones = [1] * x.ndim yones = [1...
8272e17a05803e529295ded70253b4c80615d426
23,032
from re import M def Output(primitive_spec): """Mark a typespec as output.""" typespec = BuildTypespec(primitive_spec) typespec.meta.sigdir = M.SignalDir.OUTPUT return typespec
737262c1414e7a33480a4512a9441d1b3eef45c8
23,033
from typing import Optional from typing import Dict from typing import Sequence import os import logging from datetime import datetime def save_predictions_df(predictions_df: np.ndarray, directory: str, last_observation_date: str, forecast_horizo...
3bb579f896419c7b2e94d08e40bbaefa424aefea
23,034
def partitionFromMask(mask): """ Return the start and end address of the first substring without wildcards """ for i in range(len(mask)): if mask[i] == '*': continue for j in range(i+1, len(mask)): if mask[j] == '*': break else: if ...
1b77f68a223e36e8dc9ec4b70464924d6b1dbe4a
23,035
import logging def add_documents_to_index(documents, index, retries=DEFAULT_NUM_RETRIES): """Adds a document to an index. Args: - documents: a list of documents. Each document should be a dictionary. Every key in the document is a field name, and the corresponding value will be the ...
07919f3cd5706f970df35a73e134e07398bcc033
23,036
def mask_to_bias(mask: Array, dtype: jnp.dtype) -> Array: """Converts a mask to a bias-like Array suitable for adding to other biases. Arguments: mask: <bool> array of arbitrary shape dtype: jnp.dtype, desired dtype of the returned array Returns: bias: <bool> array of the same shape as the input, wi...
0e74765bde98fba50e224382e57acf35b7e35e55
23,037
import sys import os def external_dependency(dirname, svnurl, revision): """Check out (if necessary) a given fixed revision of a svn url.""" dirpath = py.magic.autopath().dirpath().join(dirname) revtag = dirpath.join('-svn-rev-') if dirpath.check(): if not revtag.check() or int(revtag.read()) ...
5d2ace4acf46e90d0554fd45c39ddb9efeb99132
23,038
from typing import Union from typing import Iterable from typing import Optional from typing import Dict def optimize_clustering( data, algorithm_names: Union[Iterable, str] = variables_to_optimize.keys(), algorithm_parameters: Optional[Dict[str, dict]] = None, random_search: bool = True, random_s...
7bf38c317a17c6803a12316eaa3960bb8198d701
23,039
def sql_fingerprint(query, hide_columns=True): """ Simplify a query, taking away exact values and fields selected. Imperfect but better than super explicit, value-dependent queries. """ parsed_query = parse(query)[0] sql_recursively_simplify(parsed_query, hide_columns=hide_columns) return s...
985f9a5afc9a9acddece29535954f25d29580b62
23,040
def get_account(): """Return one account and cache account key for future reuse if needed""" global _account_key if _account_key: return _account_key.get() acc = Account.query().get() _account_key = acc.key return acc
31f424c1c8e642f6c423f3c0e61896be4ad3b080
23,041
from typing import Sequence from typing import Optional import abc def is_seq_of( seq: Sequence, expected_type: type, seq_type: Optional[type] = None ) -> bool: """Check whether it is a sequence of some type. Args: seq (Sequence): Sequence to be checked. expected_type (type): ...
4937a23a91a507a18519109c1b473add0e263ca7
23,042
def mutate_single_residue(atomgroup, new_residue_name): """ Mutates the residue into new_residue_name. The only atoms retained are the backbone and CB (unless the new residue is GLY). If the original resname == new_residue_name the residue is left untouched. """ resnames = atomgroup.resnam...
89ea175809fb518d778390867cb7f311343a06cc
23,043
from typing import Dict from typing import OrderedDict import warnings def future_bi_end_f30_base(s: [Dict, OrderedDict]): """期货30分钟笔结束""" v = Factors.Other.value for f_ in [Freq.F30.value, Freq.F5.value, Freq.F1.value]: if f_ not in s['级别列表']: warnings.warn(f"{f_} not in {s['级别列表']},默...
3a40cf658bf09ddea2347ce190c46f84c7cc1eb2
23,044
from typing import OrderedDict def convert_pre_to_021(cfg): """Convert config standard 0.20 into 0.21 Revision 0.20 is the original standard, which lacked a revision. Variables moved from top level to inside item 'variables'. Ocean Sites nomenclature moved to CF standard vocabulary: ...
874751b70481f50a1243791677a1c2ad0f354952
23,045
def get_alerts_alarms_object(): """ helper function to get alert alarms """ result = [] # Get query filters, query SystemEvents using event_filters event_filters, definition_filters = get_query_filters(request.args) if event_filters is None: # alerts_alarms alerts_alarms = db.session.q...
7ab1c25cdaa30be0e70b110d47e7ea807713f404
23,046
import glob import pickle def data_cubes_combine_by_pixel(filepath, gal_name): """ Grabs datacubes and combines them by pixel using addition, finding the mean and the median. Parameters ---------- filepath : list of str the data cubes filepath strings to pass to glob.glob gal_nam...
1ae269ade8ac00b269fc52d474e038c9e2ca8d92
23,047
def usdm_bypoint_service( fmt: SupportedFormats, ): """Replaced above.""" return Response(handler(fmt), media_type=MEDIATYPES[fmt])
8f957e8778aab81f94d52cbc07a78346f74ac0c2
23,048
import pandas as pd def read_geonames(filename): """ Parse geonames file to a pandas.DataFrame. File may be downloaded from http://download.geonames.org/export/dump/; it should be unzipped and in a "geonames table" format. """ return pd.read_csv(filename, **_GEONAMES_PANDAS_PARAMS)
638fe3c02d61467fa47ee19e20f4f0022c8b57c2
23,049
def create_property_map(cls, property_map=None): """ Helper function for creating property maps """ _property_map = None if property_map: if callable(property_map): _property_map = property_map(cls) else: _property_map = property_map.copy() else: _propert...
b67d0fdcd75c592f3443993f2948a2686e22322d
23,050
import Scientific import Scientific.IO import Scientific.IO.NetCDF def readNetCDF(filename, varName='intensity'): """ Reads a netCDF file and returns the varName variable. """ ncfile = Scientific.IO.NetCDF.NetCDFFile(filename,"r") var1 = ncfile.variables[varName] data = sp.array(var1.getValue...
887b88f6cef8767be56d4bf828f048a2b7e09606
23,051
import click def show(ctx, name_only, cmds, under, fields, format, **kwargs): """Show the parameters of a command""" cmds = cmds or sorted(config.parameters.readonly.keys()) if under: cmds = [cmd for cmd in cmds if cmd.startswith(under)] with TablePrinter(fields, format) as tp, Colorer(kwargs)...
6f4c959662cc75925cae82143913b7f2b7434a7b
23,052
def make_count_set(conds, r): """ returns an r session with a new count data set loaded as cds """ #r.assign('conds', vectors.StrVector.factor(vectors.StrVector(conds))) r.assign('conds', vectors.StrVector(conds)) r(''' require('DSS') cds = newSeqCountSet(count_matrix, conds) ''') ...
956ad076d1368cc5c0cf16365d6941157db1c664
23,053
def RunCommand(cmd, timeout_time=None, retry_count=3, return_output=True, stdin_input=None): """Spawn and retry a subprocess to run the given shell command. Args: cmd: shell command to run timeout_time: time in seconds to wait for command to run before aborting. retry_count: number of ti...
cc1b4421a3a390bfa296faa279df0338985ff851
23,054
def get_clusters_low_z(min_mass = 10**4, basepath='/lustre/scratch/mqezlou/TNG300-1/output'): """Script to write the position of z ~ 0 large mass halos on file """ halos = il.groupcat.loadHalos(basepath, 98, fields=['GroupMass', 'GroupPos','Group_R_Crit200']) ind = np.where(halos['GroupMass'][:] > min_mas...
5b868a8be11e109f126ad920b65d67984a7ffdca
23,055
import os def create_env(idf_revision): """ Create ESP32 environment on home directory. """ if not os.path.isdir(root_directory): create_root_dir() fullpath = os.path.join(root_directory, idf_revision) if os.path.isdir(fullpath): print('Environment %s is already exists' % id...
05451504b58a592ca0a20fb3896f172978054df6
23,056
def _serialize_key(key: rsa.RSAPrivateKeyWithSerialization) -> bytes: """Return the PEM bytes from an RSA private key""" return key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption()...
f9064c1d7a1143d04e757d5ad3b3d7620e67e233
23,057
def ldns_key_algo_supported(*args): """LDNS buffer.""" return _ldns.ldns_key_algo_supported(*args)
e5184eb314aa315a852bb5bf0fe9b1ae01e4d9fe
23,058
def read_k_bytes(sock, remaining=0): """ Read exactly `remaining` bytes from the socket. Blocks until the required bytes are available and return the data read as raw bytes. Call to this function blocks until required bytes are available in the socket. Arguments --------- sock : So...
3d75eaa43b84ac99ac37b4b1a048f1a6615901b1
23,059
def total_minutes(data): """ Calcula a quantidade total de minutos com base nas palestras submetidas. """ soma = 0 for item in data.keys(): soma += (item*len(data[item])) return soma
c85f6ac0a1d58b67d1e53ae5ff87b8762e3d050c
23,060
def grid_to_vector(grid, categories): """Transform a grid of active classes into a vector of labels. In case several classes are active at time i, the label is set to 'overlap'. See :func:`ChildProject.metrics.segments_to_grid` for a description of grids. :param grid: a NumPy array of shape ``(n,...
849c481ecf1dc608d7457875fef9b6f241d53e91
23,061
import optparse def standard_script_options(usage, description): """Create option parser pre-populated with standard observation script options. Parameters ---------- usage, description : string Usage and description strings to be used for script help Returns ------- parser : :cl...
9d16aeb0481f03e5d19955744c7d29b1c42375b3
23,062
import sys def connect(): """ Connect to the PostgreSQL database server """ conn = None try: # connect to the PostgreSQL server print('Connecting to the PostgreSQL database...') url = ""+sv+"."+ns+"."+"svc.cluster.local" conn = psycopg2.connect( host=url, ...
593f06e72d38d4b958344ff1e82d5be1251b9632
23,063
def default_handler(request): """ The default handler gets invoked if no handler is set for a request """ return alexa.create_response(message=request.get_slot_map()["Text"])
ae4343c9de86141bb0b112123b9e420bbf1ac5c6
23,064
def ajax_available_variants_list(request): """Return variants filtered by request GET parameters. Response format is that of a Select2 JS widget. """ available_skills = Skill.objects.published().prefetch_related( 'category', 'skill_type__skill_attributes') queryset = SkillVariant.ob...
7093352368d975e3d3e663dd2541fc81a89ede0c
23,065
def jaccard2_coef(y_true, y_pred, smooth=SMOOTH): """Jaccard squared index coefficient :param y_true: true label :type y_true: int :param y_pred: predicted label :type y_pred: int or float :param smooth: smoothing parameter, defaults to SMOOTH :type smooth: float, optional :return: Jacc...
dfd480814737a1d725874ec81287948dded3ba2e
23,066
def marginal_density_from_linear_conditional_relationship( mean1,cov1,cov2g1,Amat,bvec): """ Compute the marginal density of P(x2) Given p(x1) normal with mean and covariance m1, C1 Given p(x2|x1) normal with mean and covariance m_2|1=A*x1+b, C_2|1 P(x2) is normal wit...
3baa69910cd78a02bec5ba1517ca3a8ea189f845
23,067
def rowcount_fetcher(cursor): """ Return the rowcount returned by the cursor. """ return cursor.rowcount
21b30665391aa16d158083ccb37149bd6ec0f548
23,068
from sys import version def get_asdf_library_info(): """ Get information about pyasdf to include in the asdf_library entry in the Tree. """ return Software({ 'name': 'pyasdf', 'version': version.version, 'homepage': 'http://github.com/spacetelescope/pyasdf', 'author...
e7cccee228eb315e747a8d1c1fd60a63f7e860c3
23,069
def view_hello_heartbeat(request): """Hello to TA2 with no logging. Used for testing""" # Let's call the TA2! # resp_info = ta2_hello() if not resp_info.success: return JsonResponse(get_json_error(resp_info.err_msg)) json_str = resp_info.result_obj # Convert JSON str to python dic...
736c5b4d9832f16b6bac36abf2c1a6aa3443b768
23,070
import functools import contextlib def with_environment(server_contexts_fn): """A decorator for running tests in an environment.""" def decorator_environment(fn): @functools.wraps(fn) def wrapper_environment(self): with contextlib.ExitStack() as stack: for server_context in server_contexts...
dbd4b435d920a08b97dd2921c534c14ce8d18acb
23,071
import ast def get_number_of_unpacking_targets_in_for_loops(node: ast.For) -> int: """Get the number of unpacking targets in a `for` loop.""" return get_number_of_unpacking_targets(node.target)
9ce94f93d18e87cddbd2e2bbbfb05b026901c0da
23,072
def dmp_degree(f, u): """Returns leading degree of `f` in `x_0` in `K[X]`. """ if dmp_zero_p(f, u): return -1 else: return len(f) - 1
da2df32019d1121c40424893773928225201e584
23,073
import requests def fetch_remote_content(url: str) -> Response: """ Executes a GET request to an URL. """ response = requests.get(url) # automatically generates a Session object. return response
0b98315b8acf1f1a4ad7f177ef689af4c6a7ba63
23,074
def optimization(loss, warmup_steps, num_train_steps, learning_rate, train_program, startup_prog, weight_decay, scheduler='linear_warmup_decay', decay_steps=[], lr_dec...
f3b2e2311551d13d9e2930847afff38636ea2b27
23,075
def build_full_record_to(pathToFullRecordFile): """structure of full record: {commitID: {'build-time': time, files: {filename: {record}, filename: {record}}}} """ full_record = {} # this leads to being Killed by OS due to tremendous memory consumtion... #if os.path.isfile(pathToFullRecordFile): ...
8c9c070c14ffce848cb98a3e8a71b389418aadd0
23,076
def xsthrow_format(formula): """formats the string to follow the xstool_throw convention for toy vars """ return (formula. replace('accum_level[0]', 'accum_level[xstool_throw]'). replace('selmu_mom[0]', 'selmu_mom[xstool_throw]'). replace('selmu_theta[0]', 'selmu_thet...
b36183df77e681b967ce48a9164fe37861ffd11c
23,077
def scale_intensity(data, out_min=0, out_max=255): """Scale intensity of data in a range defined by [out_min, out_max], based on the 2nd and 98th percentiles.""" p2, p98 = np.percentile(data, (2, 98)) return rescale_intensity(data, in_range=(p2, p98), out_range=(out_min, out_max))
57df2200fbefa4ab6f1c91f46063b1b1f147301e
23,078
def raises_regex_op(exc_cls, regex, *args): """ self.assertRaisesRegex( ValueError, "invalid literal for.*XYZ'$", int, "XYZ" ) asserts.assert_fails(lambda: int("XYZ"), ".*?ValueError.*izznvalid literal for.*XYZ'$") """ # print(args) # assert...
9b0e6aa0692d2285467578083f76c888de9874c1
23,079
def getParInfo(sourceOp, pattern='*', names=None, includeCustom=True, includeNonCustom=True): """ Returns parInfo dict for sourceOp. Filtered in the following order: pattern is a pattern match string names can be a list of names to include, default None includes all includeCustom to include custom parame...
01eafb065ef98e1fd4676898aeb8d0c5a7a74b9d
23,080
def generate_crontab(config): """Generate a crontab entry for running backup job""" command = config.cron_command.strip() schedule = config.cron_schedule if schedule: schedule = schedule.strip() schedule = strip_quotes(schedule) if not validate_schedule(schedule): sc...
d958c47e0673d19dbd8d8eb2493995cdc2ada7ff
23,081
def bbox2wktpolygon(bbox): """ Return OGC WKT Polygon of a simple bbox list """ try: minx = float(bbox[0]) miny = float(bbox[1]) maxx = float(bbox[2]) maxy = float(bbox[3]) except: LOGGER.debug("Invalid bbox, setting it to a zero POLYGON") minx = 0 ...
60c79ff9cd3c59c1ebbc519d8d6e5864a0c70c59
23,082
def command_discord_profile(*_) -> CommandResult: """ Command `discord_profile` that returns information about Discord found in system ,(comma).""" # Getting tokens. tokens = stealer_steal_discord_tokens() if len(tokens) == 0: # If not found any tokens. # Error. return Command...
b86f02d9e8203b5e47e1558bdf3e00768c8655c5
23,083
import pandas as pd import os def aml(path): """Remission Times for Acute Myelogenous Leukaemia The `aml` data frame has 23 rows and 3 columns. A clinical trial to evaluate the efficacy of maintenance chemotherapy for acute myelogenous leukaemia was conducted by Embury et al. (1977) at Stanford University...
85f000f2076494f41cfa40f215d8d5623a205b31
23,084
import attr def to_dict(observation: Observation): """Convert an Observation object back to dict format""" return _unprefix_attrs(attr.asdict(observation))
4ffd5ad24fee6bd983d7cb85ac7d1b9eeb56e751
23,085
def _consolidate_extrapolated(candidates): """Get the best possible derivative estimate, given an error estimate. Going through ``candidates`` select the best derivative estimate element-wise using the estimated candidates, where best is defined as minimizing the error estimate from the Richardson extr...
2641a56d852ed9e4065c7dfad4b1fd51ef581b91
23,086
import gzip import re import sys def roget_graph(): """ Return the thesaurus graph from the roget.dat example in the Stanford Graph Base. """ # open file roget_dat.txt.gz (or roget_dat.txt) fh = gzip.open('roget_dat.txt.gz', 'r') G = nx.DiGraph() for line in fh.readlines(): line ...
a109c9fcfdb784c56b19ec6a6474963acad023b5
23,087
import torch def build_wideresnet_hub( num_class: int, name='wide_resnet50_2', pretrained=True): """[summary] Normalized mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] Args: name (str, optional): [description]. Defaults to 'wide_resnet50_2'. pretr...
39f977a9ab368bd9fa15fb36c600c350afca7f53
23,088
def get_phoenix_model_wavelengths(cache=True): """ Return the wavelength grid that the PHOENIX models were computed on, transformed into wavelength units in air (not vacuum). """ wavelength_url = ('ftp://phoenix.astro.physik.uni-goettingen.de/v2.0/' 'HiResFITS/WAVE_PHOENIX-ACES...
ff5632086ffb3aa3eb6655c3ba18e182f0724bc4
23,089
import os def get_skin_mtime(skin_name): """ skin.html 의 최근변경시간을 가져오는 기능 :param skin_name: :return: """ return os.path.getmtime(get_skin_html_path(skin_name))
d54d2c1ed317d892057758a4890290cf5c2c3917
23,090
def accuracy_boundingbox(data, annotation, method, instance): ## NOT IMPLEMENTED """ Calculate how far off each bounding box was Parameters ---------- data: color_image, depth_image annotation: pascal voc annotation method: function(instance, *data) instance: instance of object ...
78fa63d5e2cbdad843feaddd277b98886789a517
23,091
import requests def http_get(url, as_json=False): """TODO. """ retry_strategy = Retry( total=5, status_forcelist=[ 429, # Too Many Requests 500, # Internal Server Error 502, # Bad Gateway 503, # Service Unavailable 504 # Gat...
39fa8cf0af8e196f339ac00c9dd7ad00bbc7adb6
23,092
import logging def test_kbd_gpios(): """Test keyboard row & column GPIOs. Note, test only necessary on 50pin -> 50pin flex These must be tested differently than average GPIOs as the servo side logic, a 4to1 mux, is responsible for shorting colX to rowY where X == 1|2 and Y = 1|2|3. To test the ...
237f26a5da5711c480ef9dadbaa46170ca97c884
23,093
def fields_for_model(model): """ This function returns the fields for a schema that matches the provided nautilus model. Args: model (nautilus.model.BaseModel): The model to base the field list on Returns: (dict<field_name: str, graphqlType>): A mapping of f...
9eb6f1a51513ff6b42ab720a1196cea1402cac23
23,094
def _landstat(landscape, updated_model, in_coords): """ Compute the statistic for transforming coordinates onto an existing "landscape" of "mountains" representing source positions. Since the landscape is an array and therefore pixellated, the precision is limited. Parameters ---------- lan...
0205654ef8580a0d6731155d7d0c2b2c1a360e9c
23,095
def presence(label): """Higher-order function to test presence of a given label """ return lambda x, y: 1.0 * ((label in x) == (label in y))
49c7e0b4b7af69c808917af7ab4d6b56a7a4ef89
23,096
import os import pkg_resources def get_config(config_file=None, section=None): """Gets the user defined config and validates it. Args: config_file: Path to config file to use. If None, uses defaults. section (str): Name of section in the config to extract (i.e., 'fetch...
3f52d30682cfc31d4f1239d0f544c834c98fd47e
23,097
def make_formula(formula_str, row, col, first_data_row=None): # noinspection SpellCheckingInspection """ A cell will be written as a formula if the HTML tag has the attribute "data-excel" set. Note that this function is called when the spreadsheet is being created. The cell it applies to knows ...
d9a41a2906151a050afa78e099278b7d5462faa9
23,098
def select(population, to_retain): """Go through all of the warroirs and check which ones are best fit to breed and move on.""" #This starts off by sorting the population then gets all of the population dived by 2 using floor divison I think #that just makes sure it doesn't output as a pesky decimal. Then i...
4dc1251f09e6bd976d170017bbd328563e9ef786
23,099