content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import requests def build_response(status=OK, etag='etag', modified='modified', max_age=None): """Make a requests.Response object suitable for testing. Args: status: HTTP status exp-time: cache expire time (set to future for fresh cache, past for stale cache (defaults to stale)) ...
f9a97da74b7802511180f30dc45e9df5d5e87f51
3,651,849
from typing import List from re import T def split_list(big_list: List[T], delimiter: T) -> List[List[T]]: """Like string.split(foo), except for lists.""" cur_list: List[T] = [] parts: List[List[T]] = [] for item in big_list: if item == delimiter: if cur_list: parts...
c56dd88a7376f002ae6b91c3b227c8a16991ca31
3,651,850
def generate_partitions(data): """ Generates a random nested partition for an array of integers :param data: :return: """ if len(data) == 1: return data else: mask1 = np.random.choice(len(data), np.floor(len(data)/2), replace=False) par1 = [data[i] for i in range(le...
164749c135de1cf690bb209a18270a5550cdefc8
3,651,851
def randomRectangularCluster(nRow, nCol, minL, maxL, mask=None): """ Create a random rectangular cluster neutral landscape model with values ranging 0-1. Parameters ---------- nRow : int The number of rows in the array. nCol : int The number of columns in the array. ...
b53db06114ac3a465c1e0444bed59aa7403bba83
3,651,853
def add_arc(): """ :return: arc object """ l_hand = GArc(200, 200, 60, 150, x=480, y=270) l_hand.filled = True l_hand.fill_color = "#8eded9" r_hand = GArc(200, 200, -30, 120, x=650, y=300) r_hand.filled = True r_hand.fill_color = "#8eded9" return l_hand, r_hand
667004d534d58ab11e9b41ca42572dc445ffcf7d
3,651,855
def get_data_item_or_add(results_dic, name, n_hid, epochs, horizon, timesteps): """ Return or create a new DataItem in `results_dic` with the corresponding metadata. """ if name not in results_dic: results_dic[name] = [] found = False for item in results_dic[name]: if item.is_me...
e6c713cd89b7a9816f52be11a4730f1cef60355c
3,651,856
def midcurve_atm_fwd_rate(asset: Asset, expiration_tenor: str, forward_tenor: str, termination_tenor: str, benchmark_type: str = None, floating_rate_tenor: str = None, clearing_house: str = None, location: PricingLocation = None, *, source: s...
e77ba9ef705c2eefe0f46431862697b6a840d6fd
3,651,857
def extrode_multiple_urls(urls): """ Return the last (right) url value """ if urls: return urls.split(',')[-1] return urls
34ec560183e73100a62bf40b34108bb39f2b04b4
3,651,858
def build_header(cp: Config) -> str: """Build the email header for a SMTP email message""" header = '\n'.join([ 'From: {}'.format(cp.sender), 'To: {}'.format(''.join(cp.receiver)), 'Subject: {}\n\n'.format(cp.subject) ]) return header
a0c9fdc820d4a454c0384c46775d3e1359710fad
3,651,859
def apex_distance(r0, rc, Rc, uvec): """ Implements equation (E4) of TYH18 """ R0 = rc + Rc * uvec - r0 return np.hypot(*R0)
f88d59727fce25306ae6ef0856941efdbb80a712
3,651,860
def pixel2phase(data): """ converts each channel of images in the data to phase component of its 2-dimensional discrete Fourier transform. :param data: numpy array with shape (nb_images, img_rows, img_cols, nb_channels) :return: numpy array with same shape as data """ channels = data.shape[-1] ...
1b6b2c513cc20fe9642dd375dd17ee2205692912
3,651,861
def take_last_while(predicate, list): """Returns a new list containing the last n elements of a given list, passing each value to the supplied predicate function, and terminating when the predicate function returns false. Excludes the element that caused the predicate function to fail. The predicate fun...
19468c9130e9ab563eebd97c30c0e2c74211e44b
3,651,862
import re from bs4 import BeautifulSoup def get_notes() -> str: """Scrape notes and disclaimers from dashboard.""" # As of 6/5/20, the only disclaimer is "Data update weekdays at 4:30pm" with get_firefox() as driver: notes = [] match = re.compile('disclaimers?', re.IGNORECASE) driv...
7ec0efab1c5ed17c1878ece751bffe82d77f0105
3,651,863
def signup_logout(request): """ Just wrapping the built in """ return logout_view(request, template_name='logged_out.html')
14c403720c396aa8bbb37752ce304bb2804dd46b
3,651,864
def stress_rotation(stress, angle): """ Rotates a stress vector against a given angle. This rotates the stress from local to the global axis sytem. Use a negative angle to rotate from global to local system. The stress vector must be in Voigt notation and engineering stress is used. Parameters...
96ae75ae61fdbee0cf120e6d705cadc265452e7d
3,651,865
def blue_noise(x=None, hue=None, data=None, dodge=False, orient='v', plot_width=None, color='black', palette='tab10', size=3, centralized=False, filename='', scaling=10): """ Renders a *Blue Noise Plot* from the given data. Args: x (str in data): Variables that specify pos...
8743dacba9ddac1b1e73e676962d850876c5b2f3
3,651,866
def get_repository(auth_user: check_auth, repository_id: hug.types.text): """ GET: /repository/{repository_id} Returns the CLA repository requested by UUID. """ return cla.controllers.repository.get_repository(repository_id)
ad9bb45a4d4526b790abb7f89d72a3deafb2d10f
3,651,867
def _and(mat,other,obj,m): """ Can only be used with '&' operator not with 'and' Multi-column boolean matrices' values are compared with 'and' operator, meaning that 1 false value causes whole row to be reduced to a false value """ if mat.BOOL_MAT: if isinstance(other,obj): ...
ac4e4d5f205c6aeb068d9fb427839e4e8f85f0ea
3,651,869
def _parcel_profile_helper(pressure, temperature, dewpt): """Help calculate parcel profiles. Returns the temperature and pressure, above, below, and including the LCL. The other calculation functions decide what to do with the pieces. """ # Find the LCL press_lcl, temp_lcl = lcl(pressure[0], t...
2e9abd03dbf4617e53ea19ac7a415025567195e8
3,651,871
def best_param_search(low=1, margin=1, func=None): """ Perform a binary search to determine the best parameter value. In this specific context, the best parameter is (the highest) value of the parameter (e.g. batch size) that can be used to run a func(tion) (e.g., training) successfully. Beyond ...
6392d8c019ebb50a49c46e724e62fd63671a00df
3,651,873
def get_supervised_timeseries_data_set(data, input_steps): """This function transforms a univariate timeseries into a supervised learning problem where the input consists of sequences of length input_steps and the output is the prediction of the next step """ series = pd.Series(data) data_set = pd.D...
0fce866ea266c15e83e57795f86fcfe4fee4a54e
3,651,875
def load_template_spectra_from_folder(parent_folder, spectrum_identifier, normalization=None): """ Load template spectrum data into a dictionary. This allows templates from different folders to be loaded into different dictionaries....
466d0eb74de197ddb18e289f072d9451bc7ea2d8
3,651,877
import json def remove_screenshot_from_object(request): """ Removes the screenshot from being associated with a top-level object. :param request: The Django request. :type request: :class:`django.http.HttpRequest` :returns: :class:`django.http.HttpResponse` """ analyst = request.user.use...
36836120c79dc8d825c91370074da09fd2255c6d
3,651,878
import csv import json def read_csv_as_dicts( filename, newline="", delimiter=",", quotechar='"', encoding="utf-8", remove_prefix=True, prefix="dv.", json_cols=CSV_JSON_COLS, false_values=["FALSE"], true_values=["TRUE"], ): """Read in CSV file into a list of :class:`dict`. ...
bf15b684120445adf7e6ba8ae18befd64ad6a99f
3,651,879
def get_interface_breakout_param(dut,**kwargs): """ Author: Naveen Nag email : naveen.nagaraju@broadcom.com :param dut: :param interface: :param fields: :return: interface breakout speed Usage: port.get_interface_breakout_param(dut1, 'Ethernet4') :return - ['4x10G', 'Completed...
43286c8dbc29fef096d34c567f3f7c4ff2a06691
3,651,882
def home(): """Home view""" if flask.session.get('userid'): leaderboard_players = rankedlist( member=db.web.session.query( models.Member).get( flask.session['userid'])) member = db.web.session.query( models.Member).get( flask.se...
89211f6b79eae71b757201a2d8b234000a3e42bf
3,651,884
def is_number(string): """ Tests if a string is valid float. """ try: float(string) return True except ValueError: return False
1c46820de59b932ec565af55c565d175eef58c3c
3,651,885
def inputs(filename, batch_size, n_read_threads = 3, num_epochs = None, image_width = 200, image_height=290): """ reads the paired images for comparison input: name of the file to load from, parameters of the loading process output: the two images and the label (a logit classifier for 2 class - yes or no) """...
1b22a3f5b28513a2f65312981205b2df40acd2b3
3,651,887
def abs_p_diff(predict_table, categA='sandwich', categB='sushi'): """Calculates the absolute distance between two category predictions :param predict_table: as returned by `predict_table` :param categA: the first of two categories to compare :param categB: the second of two categoreis to compare :r...
235bfc7df29ac4a2b67baff9dfa3ee62204a9aed
3,651,889
def _is_target_feature(column_names, column_mapping): """Assert that a feature only contains target columns if it contains any.""" column_names_set = set(column_names) column_types = set(column['type'] for column_name, column in column_mapping.iteritems() if column_name i...
098af45938c616dd0ff2483a27131f15ba50797b
3,651,890
def _default_mono_text_dataset_hparams(): """Returns hyperparameters of a mono text dataset with default values. See :meth:`texar.MonoTextData.default_hparams` for details. """ return { "files": [], "compression_type": None, "vocab_file": "", "embedding_init": Embedding....
bfd015cc93bd974b6486cf07cf72f1dfb7443b61
3,651,892
def validate_engine_mode(engine_mode): """ Validate database EngineMode for DBCluster Property: DBCluster.EngineMode """ VALID_DB_ENGINE_MODES = ( "provisioned", "serverless", "parallelquery", "global", "multimaster", ) if engine_mode not in VALID_DB...
69f7952a998b6ca593106c92710909104e21f55f
3,651,893
from datetime import datetime def run_command(cmd, log_method=log.info): """Subprocess wrapper for capturing output of processes to logs """ if isinstance(cmd, str): cmd = cmd.split(" ") start = datetime.utcnow() log_method("Starting run_command for: {}".format(" ".join([str(x) for x in cm...
8366c9306810d927daf82b473db86dc67b0d84c6
3,651,895
def jar(state: State, fail: Fail): """ Store a function by a name """ (identifier, (code, rest)) = state.infinite_stack() if identifier.tag != "atom": fail(f"{identifier} is not an atom") if code.tag not in ["code", "native"]: fail(f"{code} is not code") if code.tag == "cod...
5f60a30ff7bed1a453bfe6ff354dc34a6fabee4f
3,651,896
import requests import json def get_daily_activity(p_sap_date: str) -> dict: """ Returns activities on the given date """ fiori_url = config.CONSTANTS["ECZ_DAHA_DAILY_URL"] + "?date=" + p_sap_date resp = requests.get( fiori_url, auth=HTTPBasicAuth( config.CONSTANTS["ECZ_DAHA_US...
68da0af50b0fc828d6eae3d1685911f039bd9732
3,651,898
import random from typing import Optional def load_example_abc(title: Optional[str] = None) -> str: """Load a random example ABC if `title` not provided. Case ignored in the title. """ if title is None: k = random.choice(list(examples)) else: k = title.lower() abc = examples....
d1deba6a03814da68c5d47a7018a6768059fef62
3,651,899
from typing import Dict def get_last_confirmed() -> Dict: """ This function get the last day saved on mongodb and show us the confirmed cases and the accumulated. - The country is the only needed path parameter. """ date = db.find({}, {"date": 1, "_id": 0}).sort("date", -1).limit(1) date =...
af2cf9ea3da1d361bf1347c389c2c9a6f095629e
3,651,901
def _newNode( cls, named ): """Construct new instance of cls, set proper color, and add to objects""" if not scene.visible: scene.visible = 1 if not [k for k in ('color','red','green','blue') if k in named]: named['color'] = scene.foreground if 'display' in named: target = named[...
7b81b4ec5c1a540f7159dd532c87cc2ebd3c7150
3,651,902
def MplJs(): """ Serves the generated matplotlib javascript file. The content is dynamically generated based on which toolbar functions the user has defined. Call `FigureManagerWebAgg` to get its content. """ js_content = FigureManagerWebAgg.get_javascript() resp = make_response(js_con...
d7b34b86d75f1375f6788a40245e7d04cb3ce6d9
3,651,903
def VVSS2021_fig4_plot(data, model, sizes=fig_sizes, cmaps=colormaps): """ Create and save a plot of the results from the linear regression reaction time model :param data: the data frame :param model: the fitted reaction time model :param cmaps: a dictionary of colormaps :param sizes: a diction...
47e63763073c454f1c44cf6e4c590b8b7a985f43
3,651,904
def stat(noten): """ Berechne Mittelwert, Median, min, max, oberes und unteres Quantil """ minimum = round(min(noten), 2) maximum = round(max(noten), 2) _median = median(noten) _mittelwert = mittelwert(noten) [unteres_quartil, oberes_quartil] = quartile(noten) return [minimum, unteres_quarti...
89d00c9b91b142366a4ca927298931a2f22bc715
3,651,905
def translation_activate_block(function=None, language=None): """ Activate language only for one method or function """ def _translation_activate_block(function): def _decorator(*args, **kwargs): tmp_language = translation.get_language() try: translation....
8615b02e4e3aa0560be0734f8e6564755f5e5e9b
3,651,906
def _loaded_schema_collections(schema_file_relative_dir) -> SchemaCollectionManager: """A loaded ``SchemaCollectionManager`` object, but this should never be modified. This object manages ``Schema`` objects corresponding to ``tests/{datasets,formats,licenses}.yaml``. Note that these are not necessarily the same...
ba5d03c8ad1c622391247ef505ccad21476c17d2
3,651,907
import uuid def dag(name=None, child_tasks=None, edges=None, target=None): """ Create a DAG task Args: name (str): Name for the task child_tasks (list [Task]): Child tasks within this dag edges (list [tuple (Ref, Ref)]): List of tuples of ref(Task). ...
ce12e46141ab030297303b4d55585475eb74f2cf
3,651,908
async def async_validate_pdf_signature( embedded_sig: EmbeddedPdfSignature, signer_validation_context: ValidationContext = None, ts_validation_context: ValidationContext = None, ac_validation_context: ValidationC...
fb4a8ae244d80c672ddc35c94d75953ab2d7d119
3,651,909
import inspect def get_one_to_many_foreign_key_column_name(model, name): """ Returns the constituent column names for the foreign key on the remote table of the one-to-many relationship specified by name. Args: model (class or object): The given model class or model instance. name (st...
f829de2cbb29034f033f3c124837ac888f7526eb
3,651,910
from typing import List def formula(formula: str, formula_param: str, cols: List[str]) -> Aggregation: """ Create a user defined formula aggregation. Args: formula (str): the user defined formula to apply to each group formula_param (str): the parameter name within the formula cols (L...
86247179aa3252bf24500c53b2cf7c20eb9afe62
3,651,913
def num_false_positives(df): """Total number of false positives (false-alarms).""" return df.noraw.Type.isin(['FP']).sum()
6aa339b86d15072c6a6910a43e70281575da5d36
3,651,914
import ctypes def repmot(instr, marker, value, repcase, lenout=None): """ Replace a marker with the text representation of an ordinal number. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmot_c.html :param instr: Input string. :type instr: str :param marker: Marker to be replace...
1be758f8c594805ae08c4b2e62014809e62039ad
3,651,915
def emulatte_RESOLVE( thicks, resistivity, freqs, nfreq, spans, height, vca_index=None, add_noise=False, noise_ave=None, noise_std=None ): """ return : ndarray [ Re(HCP1), Re(HCP2), Re(HCP3), (Re(VCX)), Re(HCP4), Re(HCP5), Im(HCP1), I...
0cdd44d9d3d53c1813ed25f230e29adec36fca5e
3,651,917
import csv from pathlib import Path def metadata_dict_chex_mimic(metadata_location): """Reads whole csv to find image_name, creates dict with nonempty bboxes Output: Bboxes dictionary with key the img_name and values the bboxes themselves.""" bboxes = {} with open(metadata_location) as f_obj...
716358d1eb5a77c177a41076bb630108d7ffc934
3,651,918
def create_feature_df(cnv_dict, feature_type, labels, csv=False): """Creates a pandas Dataframe containing cnvs as rows and features as columns""" # get features for each CNV cnv_features = [] if csv: for chrom in cnv_dict: for cnv in cnv_dict[chrom]: if cnv.tads: ...
76af71f73ee09a7cbfbafed3ad447b20a98e0da5
3,651,919
import xml def simulationcell_from_axes(axes, bconds='p p p', rckc=15.): """ construct the <simulationcell> xml element from axes Args: axes (np.array): lattice vectors bconds (str, optional): boundary conditions in x,y,z directions. p for periodic, n for non-periodic, default to 'p p p' rc...
c3cdc77f9cce7ef09418459832c60b6570d7e11c
3,651,920
def diff_seq(seq1, seq0): """Returns the difference of two sequences: seq1 - seq0. Args: seq1: The left operand. seq0: The right operand. Returns: The difference of the two sequences. """ return (seq1 - seq0) % MAX_SEQ
cd1632357d6ff61fcd2a32ba71a6a6be2454521d
3,651,921
def method_menu(): """Method menu items 1. Add a new method 2. Duplicate selected method 3. Remove selected method ------------------------------ 4. Clear methods """ message_method = "You are about to delete all methods. Do you want to continue?" method_items = [ menu_item(i...
d22a820a249728650b49f75ccfcdc254f3a84e76
3,651,922
def shapeanalysis_OuterWire(*args): """ * Returns the outer wire on the face <Face>. This is replacement of the method BRepTools::OuterWire until it works badly. Returns the first wire oriented as outer according to FClass2d_Classifier. If none, last wire is returned. :param face: :type face: TopoDS_Face...
7fa38d16cdfe40f802dea7d93666870e82d5cf26
3,651,923
def is_numeric(val: str) -> bool: """Check whether an unparsed string is a numeric value""" if val in MISSING_VALUES: return True try: float(val) except Exception: return False else: return True
72d6095c32f3bd89c0ae8bda22dc4b9a6461468b
3,651,924
def expand_options(sent, as_strings=True): """ ['1', '(', '2', '|', '3, ')'] -> [['1', '2'], ['1', '3']] For example: Will it (rain|pour) (today|tomorrow|)? ----> Will it rain today? Will it rain tomorrow? Will it rain? Will it pour today? Will it pour tomorrow? Will it pour?...
2b07ac0cfee7339b11016f68792500bf855df019
3,651,926
def gcd_recursive_by_divrem(m, n): """ Computes the greatest common divisor of two numbers by recursively getting remainder from division. :param int m: First number. :param int n: Second number. :returns: GCD as a number. """ if n == 0: return m return gcd_recursive_by_div...
bd25d9cea4813e523ea6bb9bd85c24bf43dd2744
3,651,927
def repeat(atoms, coord): """ Repeat atoms (:class:`AtomArray` or :class:`AtomArrayStack`) multiple times in the same model with different coordinates. Parameters ---------- atoms : AtomArray, shape=(n,) or AtomArrayStack, shape=(m,n) The atoms to be repeated. coord : ndarray, dtype...
b4f86bad25061807370d0f1eacdb0637eb8a19cc
3,651,928
def get_mzi_delta_length(m, neff=2.4, wavelength=1.55): """ m*wavelength = neff * delta_length """ return m * wavelength / neff
5bcd4b9b217c79a06b48856f7801060787f12e52
3,651,929
def yagzag2radec(yag, zag, q): """ Given ACA Y-ang, Z-ang and pointing quaternion determine RA, Dec. The input ``yag`` and ``zag`` values can be 1-d arrays in which case the output ``ra`` and ``dec`` will be corresponding arrays of the same length. :param yag: ACA Y angle (degrees) :param zag: ...
e7266f5c0dd0763238c3f12fafebea19c080022d
3,651,930
from tensorflow.keras.preprocessing.image import load_img from typing import Union def load_image( path: str, color_mode="rgb", target_size: Union[None, ImageSize] = None, normalize=False, ) -> np.ndarray: """Load an RGB image from the given path, optionally resizing it. :param path: Path to ...
9b80d39561e3ccdae778675e011ab5c52c04db4f
3,651,931
def deit_base_patch16_384(): """ DeiT base model @ 384x384 from paper (https://arxiv.org/abs/2012.12877). ImageNet-1k weights from https://github.com/facebookresearch/deit. """ cfg = ViTConfig( name="deit_base_patch16_384", url="", input_size=(384, 384), patch_size=16...
720968c8a95de30c836631fd5505c8029eaf46c0
3,651,932
def update_output( event_id, event_dividers, light_dividers, filename, geometry, do_plot_tracks, do_plot_opids, figure, ): """Update 3D event display end event id""" fig = go.Figure(figure) if event_dividers is None: return no_update, no_update, no_update, no_update,...
370f7a165ddaf870d4806564d8b86f4d5c4e90b5
3,651,933
import requests def get_containerports(marathon_url, app_id): """ Get containerports if we have portmapping. marathon_url : [string] the URL of the marathon service app_id : [string] ID of the running marathon app Method : GET Return : list of ports """ api_endpoint = '/v2/apps/' ...
eb22656e58b2b7156015b84c63755cb4f4348502
3,651,934
def backward_algorithm(O, HMM_model): """HMM Backward Algorithm. Args: O: (o1, o2, ..., oT), observations HMM_model: (pi, A, B), (init state prob, transition prob, emitting prob) Return: prob: the probability of HMM_model generating O. """ pi, A, B = HMM_model T = len(O) ...
da958ddd8d8943546030ba4306b7f632061d96bc
3,651,935
def scan_codes(code_type, image): """Get *code_type* codes from a PIL Image *code_type* can be any of zbar supported code type [#zbar_symbologies]_: - **EAN/UPC**: EAN-13 (`ean13`), UPC-A (`upca`), EAN-8 (`ean8`) and UPC-E (`upce`) - **Linear barcode**: Code 128 (`code128`), Code 93 (`code93`), Code 3...
02c70551138ffc5dc386e753d7532c28466de97e
3,651,936
def get_summoner_masteries(summoner_ids): """ https://developer.riotgames.com/api/methods#!/1017/3450 Args: summoner_ids (int | list<int>): the summoner ID(s) to get mastery pages for Returns: dict<str, MasteryPages>: the requested summoners' mastery pages """ # Can only have 4...
55b9395cd452e444f049d05af0718ca847f346d0
3,651,937
def make_pod_spec( name, image_spec, image_pull_policy, image_pull_secret, port, cmd, node_selector, run_as_uid, fs_gid, env, working_dir, volumes, volume_mounts, labels, cpu_limit, cpu_guarantee, mem_limit, mem_guarantee, lifecycle_hooks, ...
0be1782f91ab4de7a0baf0291eb3fcf9c1fc57a4
3,651,938
def preprocess(text, remove_punct=False, remove_num=True): """ preprocess text into clean text for tokenization """ # 1. normalize text = normalize_unicode(text) # 2. to lower text = text.lower() # 3. space text = spacing_punctuation(text) text = spacing_number(text) # (optio...
289ed6c3032840191ea792b01cb4b3a17535ddf2
3,651,939
def verify_ptp_calibration_states( device, states, domain, max_time=15, check_interval=5 ): """ Verify ptp parent values in show ptp parent command Args: device (`obj`): Device object states ('str): PTP calibration state domain ('str): PTP domain max_time...
648e9753b418365d8469ce17bc709ad67d814bf6
3,651,940
def get_auth_use_case(): """Get use case instance.""" return auth_use_case
a01595d40d2693ff2b4023a8d7938b4af7734ca3
3,651,941
def pagerank(G, alpha=0.85, personalization=None, max_iter=100, tol=1.0e-6, nstart=None, weight='weight', dangling=None): """Returns the PageRank of the nodes in the graph. PageRank computes a ranking of the nodes in the graph G based on the structure of the incoming links. It was...
1d6e758275a3caf33049e5c042b7bde8f4cff17d
3,651,943
from pathlib import Path import zlib import tqdm def fetch_file(name, chunksize=16 * 1024): """ Fetch a datafile from a compressed/gzipped URL source. Parameters ---------- name : :class:`str` Name of the file to fetch. chunksize : :class:`int` Number of bytes to read in a chu...
f22eb09220135b542bb3b0e599abe896664dffa3
3,651,944
def create_include(workflow_stat): """ Generates the html script include content. @param workflow_stat the WorkflowInfo object reference """ include_str = """ <script type='text/javascript' src='bc_action.js'> </script> <script type='text/javascript' src='bc_""" + workflow_stat.wf_uuid +"""_data.js'> </script> "...
24151952c9dd5bc4034916dae90a3760fc06ca44
3,651,945
import random def choose_sample_from_group( group: general.ParameterListType, ) -> general.ParameterValuesType: """ Choose single sample from group DataFrame. """ # Make continous index from 0 indexes = [idx for idx in range(len(group))] assert len(indexes) > 0 # Choose from indexes ...
27f1c8a9ca4640b881f5bdd3faca0db4b1b882da
3,651,946
def path_available(filepath): # type: (str) -> bool """Return true if filepath is available""" parent_directory = dirname(filepath) if not exists(parent_directory): raise ParentDirectoryDoesNotExist(parent_directory, filepath) return not exists(filepath)
efd506d2028f2c55e88dfc618395620571205773
3,651,947
from typing import Dict from typing import Any from typing import Callable def memory_item_to_resource(urn: URN, items: Dict[str, Any] = None, loader: Callable = None) -> CloudWandererResource: """Convert a resource and its attributes to a CloudWandererResource. Arguments: urn (URN): The URN of the r...
0bf680574f2ef3038d9d29c656a657e4e7a172ec
3,651,948
def sample_user(email='test@something.dev', password='testpass'): """Create a sample user""" return get_user_model().objects.create_user(email, password)
deb5c45287a8ff546e2631c4409d10015b550e5c
3,651,949
import PIL import random def ShearX(img: Image, magnitude: float) -> Image: """Shear the image on x-axis.""" return img.transform( img.size, PIL.Image.AFFINE, (1, magnitude * random.choice([-1, 1]), 0, 0, 1, 0), PIL.Image.BICUBIC, fillcolor=FILLCOLOR, )
9d534cfc8f7cc5497356b8e07115d42f666aac5d
3,651,950
import numpy def read_onsets(onsets_path: PathLike) -> numpy.array: """ Read a text file containing onsets. Return it as a list of floats. """ with open(onsets_path, "r") as io: lines = io.readlines() onsets = numpy.array([float(line) for line in lines]) return onsets
cbfa38ce0a5e2ea4d6c465251ee8c3e6ec47d04f
3,651,952
def format_specific_efficacy(method, type_1: str, type_2: str = None): """ Format the efficacy string specifically for defense or attack. """ effective, ineffective, useless = format_damage(method, type_1, type_2) type_name = format_type(type_1, type_2) s = "**{}** \N{EN DASH} **{}**\n".format(type_name...
095f943cda0dfdf1803ae38b16c6b9d7f8fd3e1f
3,651,953
def getSuffixes(algorithm, seqType) : """ Get the suffixes for the right algorithm with the right sequence type """ suffixes = {} suffixes['LAST'] = {} suffixes['BLAST'] = {} suffixes['BLAST']['nucl'] = ['nhr', 'nsq', 'nin'] suffixes['BLAST']['prot'] = ['phr', 'psq', 'pin'] s...
9ab699a71be73381c4dff555f0ef19201589e82f
3,651,955
import tempfile from robocorp_code.path_operations import get_user from robocorp_code.path_operations import make_numbered_dir_with_cleanup from robocorp_code.path_operations import LOCK_TIMEOUT from typing import Optional from pathlib import Path def make_numbered_in_temp( keep: int = 10, lock_timeout: float...
9ba3d08d933d961099d5169afc25c152177857b3
3,651,956
def handle_server_api(output, kwargs): """ Special handler for API-call 'set_config' [servers] """ name = kwargs.get('keyword') if not name: name = kwargs.get('name') if name: server = config.get_config('servers', name) if server: server.set_dict(kwargs) ...
0c4396619c1aee1151642de3edeb4b28d76acb9c
3,651,957
def compare_names(namepartsA, namepartsB): """Takes two name-parts lists (as lists of words) and returns a score.""" complement = set(namepartsA) ^ set(namepartsB) intersection = set(namepartsA) & set(namepartsB) score = float(len(intersection))/(len(intersection)+len(complement)) return score
87cbceaaa0acce0b83b5faf66cbe909ad52382eb
3,651,958
def Normal_VaR(return_matrix, theta,Horizon): #500 datas needed """ Compute the Value-at-Risk and Conditional Value-at-Risk Parameters ---------- risk_returns : np.ndarray theta : np.float64 Horizon : np.int16 Returns ---------- np.ndarra...
a2b911d647c942724dc30480bb90db7c83e200bb
3,651,959
def oscillator_amplitude(state, ders, period, floquet, zero_phase_lc, phase_warmup_periods=5, thr=0.0, dt=0.005): """calculates the isostable amplitude of the oscillator from dynamical equations :param state: state of the system :param ders: a list of state variable derivatives :param period: oscillator period :...
b6a55d9965eea712be2f49dbbc1f186d268f82bf
3,651,960
def commonprefix(a, b): """Find longest common prefix of `a` and `b`.""" pos = 0 length = min(len(a), len(b)) while pos < length and a[pos] == b[pos]: pos += 1 return pos, b
75e2f9ac6c3d0c38986cba5f8409ddc87fe8edbe
3,651,961
def parse_datetime(strtime): """ Parse a string date, time & tz into a datetime object: 2003-03-20 05:00:00-07 """ offset = int(strtime[-3:]) date_time = dt.strptime(strtime[:-4], '%Y-%m-%d %H:%M:%S') offset = timedelta(hours=offset) return (date_time + offset).replace(tzinfo=utc)
c7537ed913a4d0b20a71b7253725231c32c9f60b
3,651,962
from typing import List from typing import cast from typing import Iterable def traverse_depth_first(base: AnyDependency) -> List[AnyDependency]: """Performs a depth first traversal of the dependency tree. """ def _traverse_tree_2(base: AnyDependency) -> List[AnyDependency]: queue: List[AnyDepende...
1172f3b97110cc41c68631d3e6a91a0ea8d20627
3,651,963
def update_config( client, key, *, value=None, remove=False, global_only=False, commit_message=None ): """Add, update, or remove configuration values.""" section, section_key = _split_section_and_key(key) if remove: value = client.remove_value( section, sectio...
59f71b2608ddcfb38cdf1845720d782b7858607f
3,651,964
from datetime import datetime def parse_time(t): """ parse a date time string, or a negative number as the number of seconds ago. returns unix timestamp in MS """ try: tint = int(t) if tint <= 0: return int(nowms() + (tint * 1000)) except ValueError: pass ...
68189b1d0aa2f73152a77a1a790fc6a291e5ff25
3,651,965
def _get_duration(tmin: np.datetime64, tmax: np.datetime64) -> str: """ Determine the duration of the given datetimes. See also: `ISO 8601 Durations <https://en.wikipedia.org/wiki/ISO_8601#Durations>`_ :param tmin: Time minimum :param tmax: Time maximum :return: Temporal resolution formatted a...
e56c399402a1325bc519443ea4caea57be2806e7
3,651,966
import math def get_polyend_circle_angles(a, b, isLeft): """ theta0 = pi/2 + betta, theta1 = 2 * pi + betta; betta = pi/2 - alpha; alpha = atan(a) """ if a is None and b is None: return None, None alpha = math.pi / 2.0 if a is None else math.atan(a) betta = math.pi / 2.0 - a...
9547ba4ea9f74cba3d52d90bb24dc8c4b246fbff
3,651,967
import re def get_search_cache_key(prefix, *args): """ Generate suitable key to cache twitter tag context """ key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg])) not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)])) key = not_allowed.sub('', key) retur...
f3ff5baa13e4e84deb5c13cd8d5b618ba75c8699
3,651,969
def main(argv=None): """Run pragma-no-mutate filter with specified command line arguments. """ return PragmaNoMutateFilter().main(argv)
f268a010b454fe28307e8e304dca3d57fe1e635a
3,651,970
import math def independence_single_value(values, sigma=0.70): """ This calculates the independence of the models for a given metric where the metric is single valued, e.g. the slope of a gradient. ------Input------ values (list) : The single values for each model. sigma (float) : The value of...
0802966fed4d9cb5b9e2d525d10593534c5c51a0
3,651,971
def extract_fingerprints(atoms, i_jbond_dict, radius): """Extract the r-radius subgraphs (i.e., fingerprints) from a molecular graph using Weisfeiler-Lehman algorithm.""" if (len(atoms) == 1) or (radius == 0): fingerprints = [fingerprint_dict[a] for a in atoms] else: nodes = atoms ...
beaa457e0eb514ca7fbfaca846378a0d23c2b94c
3,651,972