content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def emg10(peak_index, x_pos, amp, init_pars=pars_dict, vary_shape_pars=True, index_first_peak=None): """ Hyper-EMG(1,0) lmfit model (single-peak fit model with one exponential tail on the left) Parameters ---------- peak_index : int Index of peak to fit. x_pos : float ...
b6d58183db77e6ba270005c3d64568eff52acfa4
79,014
def update(A, B, DA=0.2, DB=0.1, f=0.025, k=0.055, dt=1.0): """Apply the Gray-Scott update formula""" # compute the diffusion part of the update diff_A = DA * apply_laplacian(A) diff_B = DB * apply_laplacian(B) # Apply chemical reaction reaction = A*B**2 diff_A -= reaction diff_B +...
4f40af07e7ac4712f0dbf18aa87f1848239ba972
79,015
def type_length(expr_type): """ Counts the number of parameters of a predicate. E.g. type_length(e) = 1 type_length(<e, t>) = 2 type_length(<e, <e,t>>) = 3 """ acc_first, acc_second = 0, 0 if expr_type is None: return 0 if 'first' not in expr_type.__dict__ \ and 'secon...
50c92a5079ff922e806c343d116145bd01c9b57e
79,017
def quit(): """Quit the native GUI event loop. """ return default_app.quit()
7759aa4a3495dacd5d9a865b05bb12c3befb4366
79,018
def get_table(path): """return the score table from the bottom of a PDB as a list of lines""" raw_table = [] infile = fileutil.universal_open(path,'r') table = False for line in infile: line_split = line.split() if len(line_split) <1: break if line_split[0] == "#B...
2b72ec3eef07f2026dbb11d773ca2cbe56ed7fa1
79,019
def get_start_offset(line: str, pos: int, prefix: str): """ Returns start offset (left limit) in `line` where we should stop looking for abbreviation: it’s nearest to `pos` location of `prefix` token """ if not prefix: return 0 scanner = BackwardScanner(line) scanner.pos = pos while no...
2ba255a45e7055b04130a75e07cb7b79ced54138
79,020
def parse_restraints(fid, pdb1, pdb2): """Parse the restraints file.""" if isinstance(fid, str): fid = open(fid) dist_restraints = [] for line in fid: # ignore comments and empty lines line = line.strip() if line.startswith('#') or not line: continue ...
c64aeccd08f61d05ab13ab4647efe8e90c42c20a
79,021
def shift(vis_data: ndarray, ax: Axes, gap: float = 0, inplace: bool = False): """Shift the data so that the max(data[n-1]) - max(data[n]) = line_spacing for n > 1. Parameters ---------- vis_data : ndarray The data to visualize. The first row is independent variables and the later rows are depe...
1364c18f7d46b11aa0e797780995a0a4fb949cec
79,022
def read_energy_units(input_string): """ read in units for energy values *not currently implemented* """ pattern = ('EnergyUnits' + one_or_more(SPACE) + capturing(one_or_more(NONSPACE))) block = _get_training_data_section(input_string) keyword = first_capture(pattern, block) as...
dab32b988a975f1a798c1f083a7a1dcb5bbf386b
79,023
def outer(a: ndarray, b: ndarray) -> ndarray: """Compute the outer product of two vectors.""" return _which_np(a, b).outer(a, b)
619df430ddf3e009ac0dc533558b85a42e2e8016
79,024
def permutationinverse(perm): """ Function generating inverse of the permutation Parameters ---------- perm : 1D array Returns ------- inverse : 1D array permutation inverse of the input """ inverse = [0] * len(perm) for i, p in enumerate(perm): inverse[p] ...
c5a62a7e3acbebaebebbcf0f23dc1989a17f1c75
79,025
def get_idx_from_sent(sent, word_idx_map, max_l): """ Transforms sentence into a list of indices. Pad with zeroes. """ x = [] words = sent.split() for word in words: if word in word_idx_map: x.append(word_idx_map[word]) while len(x) < max_l: # 长度不够的,补充0 x.append(...
2097039e7ac58ee2869effb6a0eb6273f994967e
79,027
def get_counts(dt, num=1): """Get `num` minutes of download counts starting at `dt`.""" if num == 1: rows = hbase.row(row_name(dt), ['product']) else: rows = hbase.scanner(row_name(dt), ['product']).list(num) return [(t.utctimetuple()[:5], row_sum(row)) for t, row in zip(time...
2ee9c1e4cd9114e6a20f79d4335bcb4eb10f26a4
79,028
def _zeros_like_scala(x): """Returns 0 which has the same dtype as x where x is a scalar.""" return 0
405cd960b68b0794bfd813a4e3bd59890f05b315
79,029
def create_pinout_table(top, c_helper, target): """Create the pinout table for a specific target and extract some stats""" header = [ "Pad Name", "Type", "Bank", "Connection", "Special Function", "Pinmux Insel Constant / Muxed Output Index", "Description" ] table_rows = [set_md_table_fon...
00780b955c81fbc2132a04f1e33869f796701954
79,030
def switch(modulefile1, modulefile2): """ Switch loaded modulefile1 with modulefile2. If modulefile1 is not specified, then it is assumed to be the currently loaded module with the same root name as modulefile2. return module('swap {0} {1}'.format(modulefile1, modulefile2)) """ retu...
510d3482f35db192b7e1af9bab05483f71146f34
79,031
from datetime import datetime def config_measures_year(measures_year): """Return mock config values for measures_year related fields.""" return config_side_effect({ 'calculation.measures_year': measures_year, 'calculation.start_date': datetime.date(year=measures_year, month=1, day=1), ...
c0ece70b18f9eaec92c53c7e433f0326ecb12bcc
79,032
import re def generate_slug(session, slug_field, slug): """ Generates a unique slug based on the passed value. Arguments: session: SQLAlchemy session. slug_field: Model attribute containing slug. slug (str): The desired slug value. """ if not session.query(exists().where(s...
983c28a76b9cfa5ffb350299d275002a4f24e88c
79,033
def ricker(freq, length, dt, peak_time): """Return a Ricker wavelet with the specified central frequency.""" t = np.arange(length) * dt - peak_time y = ((1 - 2 * np.pi**2 * freq**2 * t**2) * np.exp(-np.pi**2 * freq**2 * t**2)) return y.astype(np.float32)
6e85fb932634c5f660393abc5ba79cf39e94d999
79,034
def interpolate_points(_points): """ 对线段进行插值,方便后面对多边形进行插值算法的时候更加理想 :param _points: 所有点 :return: 插值完成后的点 """ to_return_points = [] _points = np.array(_points) for m_point_previous, m_point_next in zip(_points, _points[1:]): m_segments = np.max(np.abs(m_point_previous - m_po...
511d288b8e9980fa93389376d76b75c61cd8fbc4
79,035
def prepare_attributes(obj: StructuralElement, prefix: str = "") -> dict: """ ElasticSearch cannot handle attribute names with dots, for example "Subject.Scheme". This is because it tries to interpret Scheme as an attribute for Subject. Fix this by replacing "." with "+" when indexing the Documents. ...
236a5c3da91d2c6a70b2cad39b99cdead8836964
79,036
import collections import ipaddress import itertools def get_target_block(target_host: HostModel) -> str: """ Export target result in markdown block as following: ``` ### Target_1 (x findings) #### proto/port - name (x findings) ``̀` :param target_host: HostModel to print. :return: ...
191c1478cb1a1e663cc8bf769f167bd0e6061bff
79,037
def interpolateVec(rays,I,Nx,Ny,xr=None,yr=None,method='linear',\ polar=False,interpVec=None): """ Interpolate a ray vector onto a 2D grid based on the X and Y positions of the rays. Assume that the rays randomly fill a contiguous region of space. Automatically set up the grid usi...
d424c2529af42e8180b18aa5d64eacd728f251bd
79,038
def add_refinfo_dref(*args): """ add_refinfo_dref(insn, _from, ri, opval, type, opoff) -> ea_t Add xrefs for a reference from the given instruction (\insn_t{ea}). This function creates a cross references to the target and the base. 'insn_t::add_off_drefs()' calls this function to create xrefs for 'offset'...
1b9006c35d89aa854f85207f156d7ffd96f8c1b6
79,039
def random_erasing_per_pixel(image, num_layers=1, scale=(0.02, 0.33333333), ratio=(0.3, 3.3333333), probability=0.5): """ https://github.com/rwightman/pytorch-image-models/blob/master/timm/data/random_erasing.py """ if tf.random.uniform(()) > probability: return image mean = [123.675, 116.28, 103.5...
c1e765ea25054ae18ad5af374e9466f2a5b30db5
79,040
import collections def month_results(exercises): """return results for different months.""" months = [] for e in exercises: monthn = e.date.month yearn = e.date.year monthY = str(monthn) + '/' + str(yearn) months.append((monthY, e.distance, e.time_as_hours)) monthtotals = collections.OrderedDict() mont...
d0a10c0e8721e96aac5db595d77ff0af60ea29fc
79,041
def hflip(img: Tensor) -> Tensor: """Horizontally flip the given image. Args: img (PIL Image or Tensor): Image to be flipped. If img is a Tensor, it is expected to be in [..., H, W] format, where ... means it can have an arbitrary number of leading dimensions. R...
2a51879e57bf83b65b15815ac6f75c87bf69e80e
79,042
def get_background(): """ application: get the background / prior estimate for the minimizer input: None output: PhysicalData (prior estimate) """ global background if background is None: background = d.PhysicalData.from_file( input_defn.prior_file ) return background
766b34b4b71fa9ba96bce4cdcb415b6b019887c2
79,043
def create_buffers( agent_id, max_size, batch_size, n_envs, initial_size=None, as_total=True, ): """ Create deque-based or numpy-based replay buffers. Args: agent_id: str, one of the keys in xagents.agents max_size: Buffer max size. batch_size: Buffer batch si...
7b557852954b9498551cefd94e48990bb6f75bf9
79,044
def extract_arg_default(arg_str): """ Default strategy for extracting raw argument value. """ args_str_split = arg_str.split(" ", 1) if len(args_str_split)==1: args_str_split.append("") return args_str_split
44f139591695ebf015b88cf343c90f7b2d29aff0
79,045
from re import M def xml_get_resolve_names(email): """ https://msdn.microsoft.com/en-us/library/office/aa563518(v=exchg.150).aspx """ return M.ResolveNames( {'ReturnFullContactData': "true"}, M.UnresolvedEntry(UnicodeDammit(email).unicode_markup.encode('utf-8').decode('utf-8')) )
e3bbf113774c0200fa236ad4b269af37719f5c06
79,046
def _create_trip_from_stack(temp_trip_stack, origin_activity, destination_activity): """ Aggregate information of trip elements in a structured dictionary. Parameters ---------- temp_trip_stack : list list of dictionary like elements (either pandas series or python dictionary). Cont...
c40c9a234190d99cb09912e084c73a93eaf9629b
79,047
def get_trade_days(start_time=None, end_time=None, datasource=DataSource.CLICKHOUSE, **kwargs): """ 统一的交易日历获取函数, 默认从clickhouse数据库获取 Parameters ---------- start_time : str, optional 开始时间, by default None end_time : str, optional ...
6e70fe741663b16a605a19db60d83f9692cfa41d
79,048
def format_errors(*errors: str, title: str = None, pydantic: bool = False) -> str: """Format multiple errors into a single error. Args: errors: Error messages. title: Title for error messages. Examples: >>> e = format_errors('worse', title='bad') >>> print(e) bad ...
cae5370563dd57cbca6a580a3ee2a5543c36c5bb
79,049
def namespace_edits_rev_query(users, project, args): """ Obtain revisions by namespace """ return []
8ba25c138e4c807a3c9bb4934eb1ddeb2cf140e5
79,050
def apply_stanfordnlp(nlp, gatenlpdoc, setname=""): """Run the stanford nlp pipeline on the gatenlp document and transfer the annotations. This modifies the gatenlp document in place. Args: nlp: StanfordNLP pipeline gatenlpdoc: gatenlp document setname: set to use (Default value = "") ...
7d442de9428fc361fcea1c5af4695b7e3d726534
79,051
def _test_logged_method(method_name, original_name): """ Decorator for logging message to Eliot logger. - Log before calling given ``method_name``. - Log if ``method_name`` resulted in an ``Exception``. """ def _run_with_logging(self, *args, **kwargs): original = getattr(self, original_n...
2319a7550a41befd3ddd4b501ba565172774b13f
79,052
def test_parallel_coordinates_and_hist(data_frame, columns): """ assigngroup=True, use the same bin size ```python columns = ['USFLUXL', 'Ensemble prob'] test_parallel_coordinates_and_hist(df_test, columns=columns) ``` """ fig = make_subplots(rows=1, cols=len(columns)) for j in range...
1616297435c31a8088b6899f6cd7863a704bb525
79,053
import random import json import logging def _update_traffic_class_v1(class_name, class_type, **kwargs): """ Perform a PUT call to version-up a traffic class. This is required whenever entries of a traffic class are changed in any way. :param class_name: Alphanumeric name of the traffic class :pa...
45896c26640a3a0373d85c6344c09a1413aac3e5
79,054
def perm_matrix(H, permutation): """ Returns a matrix equal to matrix H but with its row and column indices permuted according to the permutation permutation. """ x = H.tocoo() permutation = np.argsort(permutation) permutation_sorted = np.asarray(permutation, dtype=x.row.dtype) x.row = permu...
266ae8a2fa4a9b45be1463cc9a3996d3b778c236
79,055
def get_graph(): """ Retrieves the entire landscape graph. :return: Landscape as a networkx graph. """ landscape = _get("/graph") landscape.raise_for_status() # Raise an exception if we get an error. nx_graph = json_graph.node_link_graph(landscape.json()) return nx_graph
787c50f7995f462f544a789b065b79f6aad01b8b
79,056
def residualplot(obj,labels=True): """ 1)Description: Quantile-Quantile Plot of GPD Residuals 2) Arguments: obj = Fitbygpdpwm function output labels - a logical flag. checks if labels should be printed. 3) Example: obj = Fitbygpdpwm(data, ci, threshold) residual...
778ea2ca618680f49331466994a48de3be6d00d5
79,058
import logging def prediction(body): # noqa: E501 """Call Prediction of specified Endpoint # noqa: E501 :param prediction: :type prediction: dict | bytes :rtype: PredictionResponse """ if connexion.request.is_json: prediction = Prediction.from_dict(connexion.request.get_json(...
70afd50eb3bcbe4442be88cb6e95e47539e830be
79,059
def _estimate_weights( instr, computations): """Estimate the number of weights in a conv or dot instruction.""" weight_shape = _find_rhs_shape(instr, computations) assert weight_shape is not None return onp.prod(weight_shape)
c738cd982b74d4953e16d25c71c50f05b733b87c
79,060
def metrics_with_trailing(trailing): """Expose Prometheus metrics.""" return prom.generate_latest()
51c87db8ce2a815ad85e411a48cc64df4c3b5ff7
79,061
def Planck(x, T): """ Return the Planck function at wavelength x (in cm) and temperature T (in K) """ h = constants.h.cgs.value c = constants.c.cgs.value k = constants.k_B.cgs.value pi = np.pi return 2 * pi * h * c ** 2 / x ** 5 * 1.0 / (np.exp(h * c / (x * k * T)) - 1.0)
aef85cdff41f6c6bb08e875be24a0687a5e0790b
79,062
from pathlib import Path import shutil def pull(asset: Asset, dest: str) -> Path: """Download a single file from a github release.""" dest = Path(dest, asset.name) with request.urlopen(asset.url) as req: with dest.open("wb") as f: shutil.copyfileobj(req, f) return dest
61a5da5f9c0aefd167f4abd24ff562c8b0b8ae85
79,063
def group_words(words, size=2, empty=""): """Generates pairs (tuples) of consequtive words. Returns a generator object for a sequence of tuples. If the length of the input is not divisible by three, the last tuple will have the last len(words) % size spots filled with the value of empty. """ ...
b484915e84796621a8aba8ac9d8060a33ef05805
79,064
def get_object_cache_keys(instance): """ Return the cache keys associated with an object. """ if not instance.pk or instance._state.adding: return [] keys = [] for language in _get_available_languages(instance): keys.append(get_urlfield_cache_key(instance.__class__, instance.pk,...
600cec07db648643b58e6081b5f92bf9adb1f089
79,065
def grant_member(context, request): """Grant member roles in the group.""" mapping = request.json["mapping"] for entry in mapping: user = entry["user"] roles = entry["roles"] username = user.get("username", None) userid = user.get("userid", None) if userid: ...
2d634d32ef11135d200cf0adf63c266096509b8a
79,066
def get_loss(modality_type, value=None): """Gets default loss transformation; if none available, return value.""" if modality_type in (ModalityType.AUDIO, ModalityType.AUDIO_SPECTRAL, ModalityType.CLASS_LABEL, ModalityType.IDENTITY, ...
274fa88436df21a9524689d56147a431e9d2ce9f
79,067
def _PlatformToDimensions(platform): """Maps a platform string to the corresponding swarming dimension.""" return PLATFORM_DIMENSION_MAP[platform][:]
e2a699580686a0f82463f6e390434df0e87a4d59
79,068
def _collect_by_type(values): """Construct a mapping of types to a set of elements drawn from the input values. Parameters ---------- values : An iterable of values. Returns ------- defaultdict(set) A mapping of types to a set of input values of that type. """ valu...
02c56eeabe1cf49e1aa54c3f8537d5e90b5c0bbc
79,069
def home(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/start_date<br/>" f"/api/v1.0/start_date/end_date" )
eb0f2c415ce746a239a0928904f1537e3af50b7c
79,070
def dgdmu(mu, sigma, x): """Partial of g wrt mu""" return (x - mu) / sigma**2 * g(mu, sigma, x)
24dd44796d2c388bb79e694570e937fcc2cf24ae
79,071
def get_template(template_path): """Returns a template object by calling the default value of 'get_template_handler'. Allows getting a template to be the same regardless of template library.""" return config('get_template_handler')(template_path)
954e11bef422ad177e0531974261e356a2aca6d2
79,072
def vecteur_sinus(vec1, vec2): """ Retourne le sinus entre deux vecteurs, utilise le produit vectoriel. """ norm1 = vecteur_norme(vec1) norm2 = vecteur_norme(vec2) if norm1 == 0: return 0 if norm2 == 0: return 0 scal = vec1[0] * vec2[1] - vec1[1] * vec2[0] return ...
22eebdea49892665334b0f2cf9c3f423fa27f021
79,074
def org_view(org_id): """Provide HTML page with all details on an organisation profile """ org_detail = None try: org_detail = Organisation.query.filter_by(id=org_id).first() except IndexError: pass if org_detail is not None: return render_template('organisations/org_view.h...
c8f4f169c0565c8561d0d4ec3df1f109b28eb0cb
79,075
import types import typing import importlib def resolve_command_spec( command_spec_ref: spec.CommandSpecReference, ) -> spec.CommandSpec: """return the command spec referred to by command_spec_ref""" if isinstance(command_spec_ref, types.ModuleType): if hasattr(command_spec_ref, 'get_command_spec'...
a2435bc19bc0708e58fad457f3d42f07e1fba133
79,076
import time def processJobs(jobs, task=None, numThreads=24): """SNIPPET 20.9 EXAMPLE OF ASYNCHRONOUS CALL TO PYTHON’S MULTIPROCESSING LIBRARY Run in parallel. jobs must contain a 'func' callback, for expandCall """ if task is None:task=jobs[0]['func'].__name__ ...
48a9a457c405a113152374de4dbe7fbae172b82e
79,077
def mapStruct(radius, numberVertices): """ Build a lane radius : radius of the circle, integer numberVertices : integer""" theta=np.linspace(0, 360, numberVertices) x=[] y=[] for i in range(len(theta)): x.append(radius*np.sin(theta[i]*2*np.pi/360)+450) y.append(radiu...
1dd2dcff5c0dd61d1b680794904a611708e8802e
79,078
def gate_cost_matrix( kf, cost_matrix, tracks, detections, track_indices, detection_indices, gated_cost=INFTY_COST, only_position=False): """Invalidate infeasible entries in cost matrix based on the state distributions obtained by Kalman filtering. Parameters ---------- kf : The Kal...
5d55667b03ff2d68269f569eabd92e1e9ec6ee99
79,079
import re def get_info(video_file): """Get info about a video. The info is returned by mplayer. The result is a dictionary whose keys start with 'ID_'. """ cmd = video_info.format(video_file) output = process.get_simple_cmd_output(cmd) return dict(re.findall('(ID_.*)=(.*)', output))
3014f74e752a3865c435eb8d832afd469b1e6bc5
79,080
def load_relative_html_file(relative: str, file_name: str): """ Loads an html file in a BeautifulSoup object * **relative**: the path of a module (passed as __file__) * **file_name**: a relative file name to that module * **return** a BeautifulSoup object loaded with the file content """ re...
fd2235c4ddc1510fc0374dd8388ca0051809d85c
79,082
def readFromFile(filePath): """ Read from the specifide file path. Parameters ---------- filePath : str The path to the file to be read from. Returns ------- contents : str The contents of the read file. """ with open(filePath, "r") as timeCh...
4d07a67f1378fe7bc7e061c17c56677cdadce107
79,083
from typing import Dict from typing import Any def duplicate_value_in_header_row_check( context: Dict[str, Any], to_check: str ) -> Dict[str, Any]: """Check that the first row does not have any missing values.""" results = _before_check( s=to_check, context=context, check=CHECK_DUPLICATE_VALUE_IN_...
ebedcd320c165f5f8225c1fe188c51ad87961a45
79,084
import numpy as np def nearest_index(v1, v2): """ find the index where an array is closest to a given value. can pass in the array/value in either order, but one must be a scalar and one must be an array. returns np.argmin(np.abs(v1 - v2)) """ if np.isscalar(v1): assert not np.i...
6308c3ad35e64c76df99a89955835d3082d65118
79,085
def inlatlonbox(latrng, lonrng, latlon): """ INLATLONBOX Returns TRUE for positions within the specified region Usage: tf=inlatlonbox(latrng,lonrng,latlon) Description: TF=INLATLONBOX(LATRNG,LONRNG,LATLON) returns TRUE or FALSE depending on if the posi...
1ebb48cf4287a53225ca94c994ed8a95848a1111
79,086
def attention_lm_moe_base_hybrid(): """Base model with attention expert.""" hparams = attention_lm_moe_base_long_seq() hparams.attention_layers = "hehe" # Alternate local/expert hparams.attention_local = True # hparams.layer_preprocess_sequence = "n" # hparams.layer_postprocess_sequence = "da" return hp...
1f28d2ee35574190d2086642f39a1bfabd867dec
79,087
def _test_script_world_bank(DIRECTORY, script, rebase=False): """World Bank urban population time-series, in wide format. Demonstrate define a schema, create a method, import data, perform actions and generate a schema-compliant output. From https://databank.worldbank.org/reports.aspx?source=2&type=metadata...
f1fba64c1e2f903125caabd09f227f2484402adc
79,088
def centroid(atoms): """ Measure the centroid of a structure. Parameters ---------- atoms: ndarray or AtomArray or AtomArrayStack The structures to determine the centroid from. Alternatively an ndarray containing the coordinates can be provided. Returns ----...
30c51f3924b2bb5b09f134f3250802b2c045b872
79,089
def stemel_player(player,pattern,**args): """ player that wraps foxdot synthdefs and calls them with frequency, duration and sustain parameters, relaying any other keyword parameter while doing so. """ (pitches, durations, sustains, optionals) = foxdotidy_pattern(pattern) opts = {} for optional in optio...
fe8ab774c8887d1659c1e3adfb93606a12b5e46f
79,090
def autoremove(list_only=False, purge=False): """ .. versionadded:: 2015.5.0 Remove packages not required by another package using ``apt-get autoremove``. list_only : False Only retrieve the list of packages to be auto-removed, do not actually perform the auto-removal. purge :...
53d6dd815770dd623559f0ccb7d8dc8903a687b0
79,091
def translate_color(m, use_hex_argb=False, decode=False): """Translate the match object to a color w/ alpha.""" color = None alpha = None alpha_dec = None if m.group('hex_compressed'): if decode: content = m.group('hex_compressed_content').decode('utf-8') else: ...
1871be9f2011da9903b53d14382a7baf681d143e
79,092
import random import time def retry(initial_delay, max_delay, factor=2.0, jitter=0.25, is_retriable=None): """Simple decorator for wrapping retriable functions. Args: initial_delay: the initial delay. factor: each subsequent retry, the delay is multiplied b...
e259dd96dad694fd013c7694128fdce6d2981abb
79,094
def output_params(workflow): """ Generate params """ params = '' count = 0 for job in workflow['jobs']: if 'outputFiles' in job: for filename in job['outputFiles']: params += ' --outfile %s=$(prominenceout%d) ' % (filename, count) count += 1 ...
f539f17e13136dd173dd96e5f38a2ed270e91a4a
79,096
def log_quaternion_loss(predictions, labels, batch_size, name='log_quaternion_loss'): """A helper function to compute the mean error between batches of quaternions. The caller is expected to add the loss to the graph. Args: predictions: A Tensor of size [batch_size, 4]. labels: A Tensor of size [batch...
caccd8313a5f9125f69628751483a5b25f121b9d
79,097
def get_num_bits_different(hash1, hash2): """Calculate number of bits different between two hashes. >>> get_num_bits_different(0x4bd1, 0x4bd1) 0 >>> get_num_bits_different(0x4bd1, 0x5bd2) 3 >>> get_num_bits_different(0x0000, 0xffff) 16 """ return bin(hash1 ^ hash2).count('1')
9023085206e3601c0be9a5cf5531024a4415fe97
79,098
def read_elements(fd, endian, mtps, is_name=False): """Read elements from the file. If list of possible matrix data types mtps is provided, the data type of the elements are verified. """ mtpn, num_bytes, data = read_element_tag(fd, endian) if mtps and mtpn not in [etypes[mtp]['n'] for mtp in m...
58ec040e08c8f33e371610ae2ffa8f1bbf49760a
79,099
def read_stopwords(): """ 读取停用词列表 :return: 停用词列表 [word1, word2, ... ] """ with open(config.stop_words_path, 'r', encoding='UTF-8') as f: stop_words = [line.strip() for line in f if line] return stop_words
29e60ed8ebc3da42f6831ea435c48d8e8d67bcfb
79,100
def maxmin(response, x): """ Compute max & min of a response matrix. Parameters ---------- response : 2d ndarray Matrix where each row is a response signal. x: 1d ndarray X-axis vector (eg, time or frequency); ``len(x) = response.shape[1]`` Returns ------- m...
5159285eb21fd616e762a314d2e410d608664275
79,103
import math def calculate_Resolution_based_MZ(mz): """ based on MZ calculates resolution provided by a LR """ return math.pow(10, 5.847 + math.log10(mz) * (-0.546))
c81f788e5ab3767ee3ae1223054ab186b171eeb7
79,104
def preprocess(x, y): """ x is a simple image, not a batch """ x = tf.cast(x, dtype=tf.float32) / 255. # x = tf.reshape(x, [28*28]) y = tf.cast(y, dtype=tf.int32) # y = tf.one_hot(y, depth=num_classes) return x, y
ac06c1f6d3c7bca6084fb12eabd40ae3fbf7a371
79,105
def contact(): """ A view to return the contact page and add the data inputted into the contact form to the database. Code for returning a success status is from https://stackoverflow.comquestions/26079754/ flask-how-to-return-a-success-status-code-for-ajax-call/26080784#26080784 """ if requ...
22c93470d626168b3393811c9b415fd683bd9c22
79,106
def get_tree(xml_string): """ Parses the xml string input to a lxml tree """ utf8_parser = etree.XMLParser(ns_clean=True, recover=True, encoding='utf-8') tree = etree.XML(xml_string, parser=utf8_parser) return tree
8ca44b2b618ca9793a286965cdd9a35a685722ab
79,107
import textwrap def namedtuple_ast(name, fields, defaults, options): """Make an AST with a namedtuple definition for the given name and fields. Args: name: The namedtuple name. fields: The namedtuple fields. defaults: Sequence of booleans, whether each field has a default. options: A config.Optio...
bbdeddac3aff1176a8e6781d0abded1ea72709de
79,108
def calibrate_gravity(data, calib_cube=0.3, stationary_indicator=None): # noqa: C901 """ Gravity calibration method of van Hees et al. 2014 (https://pubmed.ncbi.nlm.nih.gov/25103964/) :param data: A pandas.DataFrame of acceleration time-series. It must contain at least columns `x,y,z` and the ind...
10e2e4abf55d7e24a85b7a53bdc53f4163b36dde
79,109
def polling_delete(profile, ref, max_attempts=10, wait_interval=1): """Try to delete a security group repeatedly until it's gone. Args: profile A profile to connect to AWS with. ref The name or ID of a security group. max_attempts The number of tim...
fd1ae037345f5229bf78a6008353e3b702c0e2f4
79,110
import csv def read_headers(file_name): """ Generate headers list from file """ with open(file_name) as f: reader = csv.reader(f, delimiter=',', quotechar='"') # Skip the header headers = next(reader) return headers
852c5ced337dd00c38a6fc191f58450b41018e52
79,111
import numpy def rix2losses(n, wl): """Return real(n), imag(n), alpha, alpha_cm1, alpha_dBcm1, given a complex refractive index. Power goes as: P = P0 exp(-alpha*z).""" nr = numpy.real(n) ni = numpy.imag(n) alpha = 4 * numpy.pi * ni / wl alpha_cm1 = alpha / 100. alpha_dBcm1 = 10 * numpy.l...
0b7b82ebb5dddcd89f58a15086b3ac9f23e31048
79,112
def get_final_dx_groups(final_exam): """This function separates the final exam data into diagnosis groups. Each dataframe that is returned follows a group of patients based on their progression during the study. cn_cn means a group that was 'CN' at baseline and 'CN' at final exam, while mci_ad mea...
d8fd5c4d4903b9e4618de75ff734d9037b15b2da
79,113
def data_loader(): """ Function that should be called from other modules for loading data. Depending on --filetype argument function will load data with appropriate function. After data is loaded, it will be processed in __process_data function based on command line arguments. :return: weka arf...
c5392b7bfa3d784ca8ae842c8cd0b2864b7deaa8
79,114
def pairwise_comparisons(G): """ Produces a generator of pairs of nodes. """ return combinations(G.nodes(), 2)
75e46837feb18ea2f857d584047c5799c5c0b4e5
79,116
def Loss_test2(N211,N212,N222,N233,xtrain,ytrain): """Determinar loss y acc para la segunda arquitectura""" Score1=0;Score2=0;Score3=0;loss=0;acierto=0 for i in range(100): Score1=[N2_11.Fordware(xtrain[i][0]),N212.Fordware(xtrain[i][1])] Score2=[N222.Fordware(Score1)] Score1.append(...
4193a3a0b15543d60c3f2c68d41059212ecfa457
79,117
def MD5_f2(b, c, d): """ Second ternary bitwise operation.""" return ((b & d) | (c & (~d))) & 0xFFFFFFFF
4830e3bf4a9ffd5e70ebf15be8eb0352052562b4
79,118
def profile_access_token_response(): """RestrictedProfileNode:5b36406d-da95-4cb0-88d8-2ec6f80e9fc9""" return read_json_file(__file__, "responses", "profile_access_token_response.json")
370e6bec6edce6813d22e6d435db5e321c7c0bf0
79,119
def get_last_two_weeks_uri(eid): """Build usage uri from eid for the last two weeks.""" return get_usage_uri(eid, 0.5)
4f2154f1672b766c4fcd568e918b5f93c678e78b
79,120
def encode(sender, receiver, protocol, payload=None, payload_type='', sequence_num=-1, await_ack=False): """ Encodes the data with the sender, receiver, protocol, payload type and sequence number and forms the packet with data and the header. Args: sender(str): ID of the sender receiver(...
80bdb1f1b4d9ac90c21ddc4785c8d5d9f811ef51
79,121
def computeSystemOptimizedControlMatrix( S2M, gainvector, M2V, TT2HO ): """ Input parameters : <S2M> is the modal control matrix as computed by function computeModalControlMatrix() <gainvector> a 1D vector of modal gains, supposed to be provided by function modalControlOptimization() <M2V> ...
fc213af4ef066382def00d720c9959414b7b9dac
79,122
import random def random_xkcd(): """Select a random xkcd comic""" xkcd = 'https://xkcd.com' current = fetch_json("{}/info.0.json".format(xkcd)) num = random.choice(range(1, current['num'] + 1)) comic = fetch_json("{}/{}/info.0.json".format(xkcd, num)) url = "{}/{}/".format(xkcd, num) retu...
82f5db984cba78ee49409f6655b989ac9b6174e8
79,123