content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def bassGura(A, B, desiredPoles, C=None, E=None): """ use Bass-Gura formalism to compute gain matrix, G, that places poles of the closed-loop meta-system \hat A- \hat B*G at desired locations Inputs: A (numpy matrix/array, type=real) - system state matrix B (numpy matrix/array, type=rea...
df3dffdfddebd0681835aff1939103c210198852
3,629,300
import os def dwarf(allstar,mhrange=[-2.5,1.0],loggrange=[3.8,5.5],teffrange=[3000,7500],apokasc_cat='APOKASC_cat_v4.4.2.fits',out='logg',calib=False) : """ logg calibration for dwarfs, from asteroseismic and isochrones """ if calib : param = 'PARAM' else : param = 'FPARAM' gd=aps...
3fae8ce5dddafbde7d5dd64c56f50aa46a6e4717
3,629,301
def get_marks(record, transcript): """ (str, str) -> list of float Return a list of final course marks from transcript that can be used for admission, computed based on information in record. >>> record = 'Eyal de Lara,Fort McMurray Composite High,2016,MAT,90,92,ENG,92,NE,BIO,77,85,BSci' >>> trans...
5737dc0c05a20bc5bbdd5f10206b3eb3ed690a11
3,629,302
from typing import Any from typing import Tuple from re import T def zip(*iterables: Any) -> "Iter[Tuple[T, ...]]": """ Replacement for the builtin ``zip`` function. This version returns an instance of Iter_ to allow further iterable chaining.""" return Iter(_zip(*iterables))
589c44a2976240c7bebb5d4d52203c081b6dce6c
3,629,303
def loadConversations(fileName, lines, fields=["character1ID", "character2ID", "movieID", "utteranceIDs"], delimiter=" +++$+++ "): """ Args: fileName (str): file to load field (set<str>): fields to extract Return: dict<dict<str>>: the extra...
9f6da36dd648d1b64cabc7725701a3704dc938a9
3,629,304
from typing import OrderedDict def optimize_schedule_rotations(schedule, sregistry): """ Transform the schedule such that the tensor temporaries "rotate" along the outermost Dimension. This trades a parallel Dimension for a smaller working set size. """ # The rotations Dimension is the outermo...
2a36d58774e5e5bad6893815fa9b058bdb93c70e
3,629,305
def parse_config(config_fn): """Deprecated. Called from pbsmrtpipe, for now. """ return parse_cfg_file(config_fn)
c6e0505b2d664c5302ccf8a85e72571429f6326d
3,629,306
def transformer_decoder_layers(name, n_layers, decoder_input, **kwargs): """A transformation block composed of transformer decoder layers.""" with tf.variable_scope(name, reuse=tf.AUTO_REUSE): hparams = kwargs["hparams"...
7d47acb38cd1f6b0e77b4901ab80c040c169b331
3,629,307
import os import logging import re def group_filenames(filenames): """Given a list of JWST filenames, group together files from the same exposure. These files will share the same ``program_id``, ``observation``, ``visit``, ``visit_group``, ``parallel_seq_id``, ``activity``, ``exposure``, and ``suffix`...
15e002ac6d34c54f3116d3232a7b253a5567a1a2
3,629,308
def check_can_unpublish_activity(user, activity_rights): """Checks whether the user can unpublish given activity. Args: user: UserActionsInfo. Object having user_id, role and actions for given user. activity_rights: ActivityRights or None. Rights object for the given act...
6de5451497e75cb369fab5b1c8d09d809fa41929
3,629,309
def gql_add_user_attendance(time: str, user_id: int = None, date: str = None, attendance_id: int = None, is_clock_in: bool = True, comment: str = None): """ GQL mutation to insert/update attendance :param time: time string in HH:MM:SS format :param user_id: unique user id ...
7dd070824486408dcdab15fa29f385a83d2ad826
3,629,310
def make_pipeline(steps, params): """ Args: steps (dict): (name, module_name, method_name) Tuples to specify steps of the pipeline to fit. params (dict): string -> object. Parameters passed to the fit method of each step, where each parameter name is ...
feffe00156f0735bf0a59ef6cb0733b3f332a453
3,629,311
def format_fields(field_data, include_empty=True): """Format field labels and values. Parameters ---------- field_data : |list| of |tuple| 2-tuples of field labels and values. include_empty : |bool|, optional Whether fields whose values are |None| or an empty |str| should be...
cce4b5279e01c33fec0f83c6f86141c33012fc4c
3,629,312
def loadDecomposition(name): """Load a tree decomposition in the PACE-2016 format""" B = 0 # number of bags TW = 0 Bags = [] f = open(name, "r") lines = f.readlines() for l in lines: s = l.split() if len(s) < 1: continue if s[0] == "c": cont...
7463ee6117bacc2fe07f6937fbdbd35073fea5f0
3,629,313
def testing_report(): """ Testing Site Daily Summary Report: RESTful CRUD Controller """ return crud_controller()
9dbe01c4e5cd490dc3dd9b507320efd7bce2c798
3,629,314
def virtual_network_present( name, address_prefixes, resource_group, dns_servers=None, tags=None, connection_auth=None, **kwargs ): """ .. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: ...
fea32c4afa44b1e1c1b9d72290e4892e9dd2c484
3,629,315
def parse_config_yaml(current_config, first_run=False): """This function parses the configuration values contained in the configuration dictionary obtained by reading the YAML file.""" config_options = current_config used_options = {} if config_options is None: return validate_config( ...
74f021f3f8b1c290d32527b931da863a23958706
3,629,316
def acf(x, length=20): """ Compute autocorrelation. """ return np.array([1] + [np.corrcoef(x[:-i], x[i:])[0,1] for i in range(1, length)])
7d32fdc2365b621b53c4c91ff4191781f0350c02
3,629,317
def normalizeInfinity(a): """ Normalize array a so that the maximum absolute value is 1. Parameters ---------- a : ndarray of float The array to be normalized. Returns ------- ndarray of float, same shape as a The normalized array. """ return a / xplib.xp.ma...
449e437925f28181aacd62d22896edb8a3670c6a
3,629,318
def getConfigPath(): """ Returns the config location (either default or user defined) """ global args, ConfigPathDefault if args.config_location: return args.config_location return ConfigPathDefault
b53f1dc76f08859bd261f5f76ab6832a5193fe5a
3,629,319
import re def only_bf(txt): """ Strip a string from all characters, except brainfuck chars """ return re.sub(r"[^\.,<>\+-\]\[]", "", txt)
8c32b11d511f5c7b92d7454dcbfea09627ddf172
3,629,320
import subprocess def run_hidef_cmd(cmd): """ Runs hidef command as a command line process :param cmd_to_run: command to run as list :type cmd_to_run: list :return: (return code, standard out, standard error) :rtype: tuple """ p = subprocess.Popen(cmd, stdout=s...
10ccaefedf262039d2cd7725fc3e8cb0c7f904d6
3,629,321
def create_ice_connection(user_token): """Creates an instance of the ICE API using common settings.""" # Use getattr to load settings without raising AttributeError key_id = getattr(settings, "ICE_KEY_ID", None) url = getattr(settings, "ICE_URL", None) verify = getattr(settings, "ICE_VERIFY_CERT", F...
04a81fd1c1b6a55d68bc854e942c8cbd2b5e3306
3,629,322
def make_uris(sids, start, end): """Make the URIs for all stations Args: sids (list): List of IACO station identifiers (str) start (str): Starting date in YYYY-mm-dd end (str): ending date in YYYY-mm-dd Returns: a list of URIs, one for each dataset """ service = BAS...
86b891dd09989c60ed94368a928f280e809d5791
3,629,323
import os def is_valid_slack_app(qs): """ Checks to see if the request is being made by a valid Slack app. """ data = parse_qs(qs) return safe_list_get(data["api_app_id"], 0) == os.environ.get("SLACK_APP_ID")
91628d0453c073b5a749eea6cfdea3b6f0ffdccd
3,629,324
def sr_inverse_org(J, k=1.0): """Return SR-inverse of given J Definition of SR-inverse is following. :math:`J^* = J^T(JJ^T + kI_m)^{-1}` Parameters ---------- J : numpy.ndarray jacobian k : float coefficients Returns ------- sr_inverse : numpy.ndarray ...
63d2dc829be258c32ba00f345124a0d0a36472ea
3,629,325
def get_embeddingset(veclist, textlist): """gets a whatlies.embeddingset from the encoding given by the language model Args: veclist (numpy.ndarray): ndarray of all encodings textlist (list): vector of encoded texts Returns: whatlies.EmbeddingSet: whatlies EmbeddingSet for easier t...
e5a48d817d5195ce5f6c02f8d66453e22821fa3d
3,629,326
from typing import Sequence from typing import List def render_quoted_form(compiler, form, level): """ Render a quoted form as a new hy Expression. `level` is the level of quasiquoting of the current form. We can unquote if level is 0. Returns a two-tuple (`expression`, `splice`). The `spli...
e3ec7a37e1d00fb185a7bfd7e22d07716a33213c
3,629,327
def get_index_portfolio_deposit_file(date: str, ticker: str) -> list: """지수구성종목을 리스트로 반환 Args: date (str): 조회 일자 (YYMMDD) ticker (str): 인덱스 ticker Returns: list: ['005930', '000660', '051910', ...] """ df = 지수구성종목().fetch(date, ticker[1:], ticker[0]) if df.empty: ...
2336fcf17e1bd6c00581c41e41354f3e50bc7b59
3,629,328
from typing import Optional def get_account_by_path( path_string: str, dongle: Optional[Dongle] = None ) -> LedgerAccount: """Return an account for a specific `BIP-44`_ derivation path :param path_string: (:code:`str`) - HID derivation path for the account to sign with. :param dongle: (:class...
043ac11f355c939ce18c5b0ee675454a863a0e45
3,629,329
import os def _search_path(file_path): """Completes the file path if given a filename and not a directory. If only given a file name and not a directory, the system will search for it in the library folder. The library folder is defined either in rosparam:`/baxter/playback_library_dir` or if doesn't exis...
60303fc28b7c8a7c2f6b0d3f0e8597e98f0839c9
3,629,330
def down_capture_nb(returns, factor_returns, ann_factor): """2-dim version of `down_capture_1d_nb`.""" result = np.empty(returns.shape[1], dtype=np.float_) for col in range(returns.shape[1]): result[col] = down_capture_1d_nb(returns[:, col], factor_returns[:, col], ann_factor) return result
f59aeda7483dcf5b615223fa34a1a4fc0a5d10f4
3,629,331
import re import string def validate_word(word, text): """Check if something is a valid "word" submission with previous existing text. Return (valid, formatted_word, message), where valid is a boolean, formatted_word is the word ready to be added to existing text (adding a space if applicable for example)...
658873c8cbf446cbe53ec5f806db668ceecaa2cf
3,629,332
def process_content_updates(results): """Process Content Updates Args: results (Element): XML results from firewall Returns: max_app_version (str): A string containing the latest App-ID version """ app_version_list = [] version_list = results.findall('./result/content-updates/e...
021c9ac9246034874a1fe274fb49aabfa0f15d61
3,629,333
import pickle def load_synthetic(name): """ Loads expression data from pickle file with the given name (produced by save_synthetic function) :param name: name of the pickle file in SYNTHETIC_DIR containing the expression data :return: np.array of expression with Shape=(nb_samples, nb_genes) and list o...
62d85dd427b0e233572eab44d43ecef33e9e2d23
3,629,334
def cell_count(ring): """ >>> cell_count(0) == contour_len(0) True >>> cell_count(1) == contour_len(0) + contour_len(1) True >>> cell_count(2) == contour_len(0) + contour_len(1) + contour_len(2) True >>> cell_count(2) 25 >>> cell_count(3) 49 """ if ring == 0: ...
90eaaaea4544f0db6f3216bea4971ce82004a9c4
3,629,335
def exponential_search(ordered_list, x): """ implementation of an exponential search algorithm taken from: https://en.wikipedia.org/wiki/Exponential_search """ list_size = len(ordered_list) bound = 1 while bound*2 < list_size and ordered_list[2*bound-1] < x: bound = bound ...
5cf0870c00807405a5b4df8811b9ecf95aa34aaa
3,629,336
import base64 def verify(payload, signature, public_key): """ Verify payload using (base64 encoded) signature and verification key. public_key should be obtained from load_public_key Uses RSA-PSS with SHA-512 and maximum salt length. The corresponding openssl command to create signatures that this fun...
10491642bf5f793d776931ae212141c395049d86
3,629,337
import os def get_models_from_api_spec( api_spec: dict, model_dir: str = "/mnt/model" ) -> CuratedModelResources: """ Only effective for predictor:model_path, predictor:models:paths or for predictor:models:dir when the dir is a local path. It does not apply for when predictor:models:dir is set to an S...
65899ac0d5cbc63a35eb91d71335367615b7e2a6
3,629,338
from re import T import torch def prepare_segment(net, source, dev='cuda'): """ Prepares target image before foreground and background separation Parameters: net (pytorch_vision.model): Segmentation Model source (cv2.Mat): Hand image dev (str): Computation device, default GPU R...
ec5ebdb822494c655b674d34a86345b258501512
3,629,339
import csv import json def extract_information_per_turker(filename): """ Extracts dictionary with turker's details Returns: user_information: dictionary with user details """ user_information = {} with open(filename) as file: csv_reader = csv.DictReader(file) for row in...
8e5fb7ee742f1ca9456b5b4b35faaee48d66ad6c
3,629,340
def upload_str(name: str, content: str, bucket_name: str): """ :param name: Name of file including directories i.e. /my/path/file.txt :param content: UTF-8 encoded file content :param bucket_name: Name of GCS bucket, i.e. deepdriveio :return: Url of the public file """ key = name bucket...
7a7eabb207f95257bd9e917290e70338ced8d173
3,629,341
import os def main(orig_dir, new_dir, blocksize, comparison_operator): """ main source of pain """ if not os.path.isdir(orig_dir): raise comparisonException("Directory {d} does not exist".format(d=orig_dir)) if not os.path.isdir(new_dir): raise comparisonException("Directory {d} does not e...
1621012523d765eeabbc04af705d06b1255a7fdf
3,629,342
def inverso(x): """ El inverso de un número. .. math:: \\frac{1}{x} Args: x (float): Número a invertir. Returns: float: El inverso. """ return 1 / x
16f2cb9466efa661d3ee8b10b6a0d637273f6b7c
3,629,343
from typing import Union def _scale(scale:bool,X:Union[pd.Series,np.ndarray]): """ Normalization of the Time Serie Parameters ---------- scale : bool X : pd.Serie or Numpy Array Returns ------- global_mean : float, mean of the Time Serie global_sdt : float, sdt of the Time Serie X : numpy ...
b86149deddefc22f1776f5de424f413790f8b2d2
3,629,344
def update_user_count_eponymous(set_of_contributors, anonymous_coward_comments_counter): """ Eponymous user count update. Input: - set_of_contributors: A python set of user ids. - anonymous_coward_comments_counter: The number of comments posted by anonymous user(s). Output: - user_count: ...
4d96d5f22c489a9bae9e0958bd83346df9d60b6c
3,629,345
import argparse def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( description='Translate DNA/RNA to proteins', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( 'positional', metavar='str', help='DNA/RNA sequence') p...
3271d81d31b247bd4291224486e7d823acb45a58
3,629,346
def translation(component, direction=1, kernel=interpolation.lanczos, padding=3): """Shift the morphology by a given amount """ dy, dx = component.shift dy *= direction dx *= direction _kernel, _, _ = interpolation.get_separable_kernel(dy, dx, kernel=kernel) component.morph[:] = interpolatio...
a185fb15eaa92f46a4ee66f344044f02fbda51a0
3,629,347
from typing import Optional def workflow( user_id: Optional[int] = None, screen_name: Optional[str] = None, total_followers: int = 100000, batch_size: int = 5000, output_csv: Optional[str] = None ) -> pd.DataFrame: """ Pull a user's Twitter following and map each follow...
a70524d21d83de7c2a24948e2aaec16353c5556a
3,629,348
def dcaFuse(X, Y, L): """ X (p*n) Y (q*n) L (n) """ # X = np.array([[1,2,3,4], # [4,5,6,7], # ]) # Y = np.array([[4,4,4,4], # [1,1,1,1]] # ) # L = np.array([0,1,2,2]) p, n = X.shape q = Y.shape[0] # N...
2ae41b829de7bde8d8d4b55c91806ac65b05ba1e
3,629,349
def flowRate(t): """ gives fixed flow rate as a function of time notice that it depends on pump coastdown time constant, so be sure to change that if needed. right now, it's set to 5s """ tau = 5.0 return 21.7 * np.exp(-t/tau)
9b72b58e6e1334e6813b115876d71fac69898fed
3,629,350
def generator_from_atom_argument(arg: AtomSpec) -> IndexGenerator: """ Returns a generator function for selecting a subset of sites from a pymatgen :obj:`Structure` object. Args: arg (various): Argument used to construct the generator function. Returns: (func): Generator function that ...
64216cf7dcd0328d9cad2df9ca35881417fc13f1
3,629,351
def get_total_memory(): """ get_total_memory() Returns the total memory in GBs """ total_memory = shell_tools.run('sysctl -a | grep hw.memsize')['stdout'] return (int(total_memory.split('=')[-1]) / (1024 * 3))
eb977d7aad8ced4d0e824a5a6e4b7f28f312c860
3,629,352
import os def generate_arg_defaults(): """Return a dict of programmatically determined argument defaults.""" return {'user': os.getlogin(), 'uid': os.getuid(), 'gid': os.getgid(), 'tag': 'latest', 'dockerfile': './docker/escadrille'}
5865501d2355c92d0a8447bb36e9afc70ac84d66
3,629,353
from labml_nn.transformers.primer_ez import MultiDConvHeadAttention def _d_conv_mha(c: TransformerConfigs): """ Add the [option](https://docs.labml.ai/api/configs.html#labml.configs.option) of [**Multi-DConv-Head Attention**](index.html) to [configurable transformer](../configs.html#TransformerConfi...
2e2e73d20da2082c120cd5737ecca3343eb82190
3,629,354
def c_commands(context, commands): """ The c in c_commands refers to the c file. This function filters a list of commands for the generated .c file. WGL core functions are not dynamically loaded but need to be linked, this functions filters out wgl core functions for the .c file. :param contex...
06ddacdcd01c7dada78f814175ff484ceaeea2da
3,629,355
import asyncio async def get_job_status(job_id: int, request: Request, response: Response): """Get the status of a previously-submitted job. **Arguments:** - **job_id**: Identifier of the submitted job, as returned by the "Submit Job" endpoint. """ loop = asyncio.get_running_loop() try: ...
c13c0bdb1d07cd7be3dfd7c91e4625f8e739953a
3,629,356
import os import re def replace_tool(string_file, old_tool_file, new_tool_file, old_tool_name='', new_tool_name='', N=0): """Swaps old_tool_file for new_tool_file in string_file. Also replaces the tools Name field. Parameters ---------- string_file : str Path to an Adams Drill string fil...
87e2518d65bebfcb5989877a69938a9cc8bdd08d
3,629,357
from util import Stack def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple ...
f9263a944574c902a7a9c2122cf6d03c4307f53b
3,629,358
from distributed.client import default_client import tokenize def read_bytes(urlpath, delimiter=None, not_zero=False, blocksize=2**27, sample=True, compression=None, **kwargs): """ Convert path to a list of delayed values The path may be a filename like ``'2015-01-01.csv'`` or a globstring ...
f65dc33b8fbc699187ffd49483b07363c94d1bf0
3,629,359
from dials.algorithms.scaling.scaler_factory import TargetScalerFactory def scale_against_target( reflection_table, experiment, target_reflection_table, target_experiment, params=None, model="KB", ): """Determine scale factors for a single dataset, by scaling against a target reflectio...
619952e066470f66b334791989d901892d51765d
3,629,360
from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.cluster import DBSCAN def billing_pattern(data, params, hitlist): """ In this model, outliers from the general billing pattern (see below) are flagged, based on how far away from the nearest cluster they are. The p...
567ad6cef171d5055dc13a0af879575f52704189
3,629,361
def partition_annots_into_singleton_multiton(ibs, aid_list): """ aid_list = aid_list_ """ aids_list = ibs.group_annots_by_name(aid_list)[0] singletons = [aids for aids in aids_list if len(aids) == 1] multitons = [aids for aids in aids_list if len(aids) > 1] return singletons, multitons
7d062644923b12a59ef2e4bffd76ec4caf0bcaeb
3,629,362
def teaser_block(parser, token): """ Template tag that takes a model instance and returns the given instance as a template-formatted block. Inserts two objects into the context: ``instance`` - The model instance ``fields`` - A list of (name, label, value) tuples representing the ...
481eba0978cd052575975295ad6d10197265fa5a
3,629,363
def galeshapley(suitor_pref_dict, reviewer_pref_dict, max_iteration): """ The Gale-Shapley algorithm. This is known to provide a unique, stable suitor-optimal matching. The algorithm is as follows: (1) Assign all suitors and reviewers to be unmatched. (2) Take any unmatched suitor, s, and their most p...
5b52cb165d15a0992b58c38958daf222d8d642cd
3,629,364
def geom_bar(mapping=None, *, data=None, stat=None, position=None, show_legend=None, sampling=None, tooltips=None, **other_args): """ Display a bar chart which makes the height of the bar proportional to the number of observed variable values, mapped to x axis. Parameters ---------- ...
818e8ba7cd30913168acf11a8267a630dbd2d8d3
3,629,365
def diff_string(old, new): """given a old and new int value, return a string representing the difference """ diff = abs(old - new) diff_str = "%s%s" % (CMPS[cmp(old, new)], diff and ('%.2f' % diff) or '') return diff_str
dc6d4a6456c6399307aca8cd4c609e64fd6ad02a
3,629,366
def _tile_grid_to_cesium1x_source_options(tile_grid: TileGrid, url: str): """ Convert TileGrid into options to be used with Cesium.UrlTemplateImageryProvider(options) of Cesium 1.45+. See * https://cesiumjs.org/Cesium/Build/Documentation/UrlTemplateImageryProvider.html?classFilter=UrlTemplateImageryPr...
24363d34f1d0fe590eac648fc1a1d1c584dd069f
3,629,367
def update_code(code_id: int, code: schemas.CodeUpdate, db: Session = Depends(get_db)): """ Update Code """ db_code = crud.get_code(db=db, code_id=code_id) if db_code is None: raise HTTPException(status_code=404, detail="Code not found") db_device = crud.get_device(db=db, device_id=code...
5a9be20a25a584d2ea95e057049d8b354848ca81
3,629,368
def vgg19_lstar(): """ Setup the VGG19 neural network, protect it using Gu and Rigazio's L* defense mechanism and perform an inference on an example input. """ model = networks.VGG19() dm = dms.GuRigazio( keras_model = model.wrapped_model(), noise_stddev = 4.71e-4, how = ...
ad5c1a0cd57e40aff24e6fe2b2eaf2edc418fcdc
3,629,369
def find_setting(group, key, site=None): """Get a setting or longsetting by group and key, cache and return it.""" siteid = _safe_get_siteid(site) setting = None use_db, overrides = get_overrides(siteid) ck = cache_key('Setting', siteid, group, key) if use_db: try: setting...
0088610e08d78316d036551fd58984b48bc49b6a
3,629,370
def isoslice(var,prop,isoval, grd, Cpos='rho', masking=True, vert=False): """ isoslice, lon, lat = isoslice(variable,property, isoval, grd) optional switch: - Cpos='rho', 'u' or 'v' specify the C-grid position where the variable rely - masking=True mask the output...
50bbac87cfadcd3aa1a280b17551721788456723
3,629,371
def get_solution(x): """ Args: x (numpy.ndarray) : binary string as numpy array. Returns: numpy.ndarray: graph solution as binary numpy array. """ return 1 - x
dd4c92baeaab0d3231f9b24cd950a42d589218aa
3,629,372
from typing import Any async def async_get_config_entry_diagnostics( hass: HomeAssistant, config_entry: ConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" controller = hass.data[DOMAIN][config_entry.entry_id] diag: dict[str, Any] = {} diag["entry"]: dict[str, Any] = {} ...
af70d72e804c8946015e5a3d6e74ec0105de6168
3,629,373
from pathlib import Path def create_upload_file(tmp_path): """Create temporary text file for upload.""" file_path = Path(tmp_path, "test_upload_1.txt") with open(file_path, "w") as f: f.write("Hello World") return file_path
50b707f59736ae1b1e06018aedec451b578eafc8
3,629,374
def makeFigure(): """Get a list of the axis objects and create a figure""" ax, f = getSetup((10, 8), (3, 4), multz={8: 1, 10: 1}) subplotLabel(ax) Tcell_pathname = path_here + "/data/flow/2019-11-08 monomer IL-2 Fc signaling/CD4 T cells - IL2-060 mono, IL2-060 dimeric" NK_CD8_pathname = path_here ...
6849598c09e9367c2702b0ee47232e9f2c69d1a3
3,629,375
def KimKim2011(medium="Water", p_steam=120, deltaT_sub=5, Theta=90, CAH=10, Theta_a=None, Theta_r=None, k_coat=15, delta_coat=0, h_i=None, c=1, N_s=250, print_properties=False, **kwargs): """ main function, calculates dropwise condensation heat flux as described in: Kim, S., & Kim,...
b2723d279ef8eee3a51fabde4462cbcad2ccd521
3,629,376
def cumall(series): """ Calculates cumulative all of values. Equivalent to `series.expanding().apply(np.all).astype(bool)`. Args: series: column to compute cumulative all for. """ alls = series.expanding().apply(np.all).astype(bool) return alls
6d660dae0760f1157d91a21739729d91880761c1
3,629,377
def manhattan_distance(a: Point, b: Point) -> int: """Return the Manhattan distance between two points.""" return abs(a[0] - b[0]) + abs(a[1] - b[1])
627d846b6aaea04d98d75dd04ca082578c090b5d
3,629,378
import json def gen_new_dns_json(): """ Generate json file with IPs and their respective domains. :return: Stats about domains """ json_dict = [] for ip in DATA.keys(): entry = {'ip': ip, 'domain': DATA.get(ip)} json_dict.append(entry) dist = {"domains": json_dict} with...
69ca6e7471f864cb0e3f224f93a24546fa314b6e
3,629,379
def recorderLocations(year = 2014): """ This function returns all survey locations and recorder abbreviations for a given year. Only valid from 2009 onwards. """ if year > 2009: stryear = str(year) groups = loadTable('groups') recorderids = loadTable('recorderinstall') ...
759ad3de6369ed7ee20e1f02fba5e06b54373294
3,629,380
def ensure_rng(rng=None): """Simple version of the ``kwarray.ensure_rng`` Args: rng (int | numpy.random.RandomState | None): if None, then defaults to the global rng. Otherwise this can be an integer or a RandomState class Returns: (numpy.random.RandomState) : rng - ...
a58d9aac689e89dfda7fa0b0b389a3a1e2a913e0
3,629,381
def def_grad_surf(surf, u, v): """" Compute deformation gradient via a NURBS surface interpolation of control point displacement at u, v parametric coordinates :param surf: NURBS surface interpolating control point displacements :type surf: NURBS surface object :param u: u parametric location ...
892e1a9adc825e784b17b98cd400963e45ca949c
3,629,382
def assign(tensor, val): """ Compatibility assignment operation Args: tensor: Tensor, to be assigned value of T2. val: Tensor or python value, which will be assigned to T1. Returns: Assigned Tensor """ if _VERSION == 1: tf.assign(tensor, val) else: ...
d5ef567bad80f663c04d53214578a798a10adb22
3,629,383
from django.contrib.auth import get_user_model def get_v3_users_from_v2_user_ids(v2_user_ids): """ Get v3 users with last_login==null and has a matching v2 user id """ return get_user_model().objects\ .filter(last_login__isnull=True)\ .filter(id__in=v2_user_ids)
378ad4e1e8904fe57d91b8657994f5965d5bebbb
3,629,384
def filter_intersection(data, hoax_pages, print_results=False): """returns the dataset filtered with only the users who liked at least one post belonging to a hoax page and one post belonging to a non-hoax page print_results: if True, prints the filtering effect output: sparse like_matrix and page/hoax ...
6ebaec0eb520098ad9f85ce79bf4a93e75ea70f0
3,629,385
def get_path_up_down(path_source, path_target): """paths for up/down NOTE: both lists always show the LOWER level element even for the so for path up, it shows the source, for path down the target! Args: path_source(list) path_target(list) """ # find common part of pat...
ba4719b42e0703ea0ac885de29b36466b7eb3676
3,629,386
def hsitogramEqualize(imgOrig: np.ndarray) -> (np.ndarray, np.ndarray, np.ndarray): """ Equalizes the histogram of an image :param imgOrig: Original Histogram :return """ num_of_pixels = imgOrig.shape[0] * imgOrig.shape[1] if len(imgOrig.shape) == 2: norm_255 = normalize_image(imgOri...
b196d3ffe8b6323883591960e0627a9e7eb40735
3,629,387
import os def topic_arn(): """ Get the SNS topic ARN from environment variable :return: The SNS topic ARN """ return os.environ["SNS_TOPIC_ARN"]
e4729fbb47a4efefb2037dd5e590fba2706e43dc
3,629,388
def findCentroid(points): """ Compute the centroid for the vectors of a group of Active Site instance Input: n ActiveSite instances Output: the centroid vector """ centroid = [0.0,0.0,0.0] for item in points: centroid = [centroid[0]+item.vector[0],centroid[1]+item.vector[1],centroid[...
16f0c4b0052edad8c37ca4abee93bff7c1d5937b
3,629,389
def setup_view(f): """Decorator for setup views.""" def new_function(*args, **kwargs): request = args[0] if not settings.DEBUG: raise Http404("Site is not in DEBUG mode.") if request.kbsite and request.kbsite.is_setup: raise Http404("Site is already setup, wizard...
7ab1eade1426893b70895dee4cd032feb3c21dc7
3,629,390
def weth_instance(web3_eth): # pylint: disable=redefined-outer-name """Get an instance of the WrapperEther contract.""" return web3_eth.contract( address=to_checksum_address( NETWORK_TO_ADDRESSES[NetworkId.GANACHE].ether_token ), abi=abi_by_name("WETH9"), )
d0dbbeb33e9d0679196b9e1c6f0c2cdac3a3dc30
3,629,391
def get_editops_stats(alignment, gap_char): """Get stats for character level edit operations that need to be done to transform the source string to the target string. Inputs must not be empty and must be the result of calling the runing the align function. Args: alignment (tuple(str, str)): the...
90a902fa3dadd05c064f9853ce94fc680e5177a9
3,629,392
def conv(inputs, out_filters, ksize=(3, 3), strides=(1, 1), dilation=(1, 1), use_bias=True): """ Convolution layer Parameters ---------- inputs: Input tensor out_filters: Number of output filters ksize: Kernel size. One integer of tuple of two integers strides: Strides for movi...
e8e6ca7be7463106e1bbe67381b36eeffeebb7f2
3,629,393
def is_active(host, port): """Check if server is active. Send HTTP GET for a fake /style.css which server will respond to if it's alive. Args: host: server ip address port: server port Returns: Boolean for server state. """ try: url = 'http://{}:{}/style.c...
8c6af3307326ddcf9c57bc7745d26103ed5ded2e
3,629,394
def norm_lrelu_conv(feat_in, feat_out): """InstanceNorm3D + LeakyReLU + Conv3D block""" return nn.Sequential( nn.InstanceNorm3d(feat_in), nn.LeakyReLU(), nn.Conv3d(feat_in, feat_out, kernel_size=3, stride=1, padding=1, bias=False) )
d62c2becb6f88b1f925c2ddbb8395937eadc2174
3,629,395
import pandas from typing import Optional def dataframe_divisions( request: Request, reader=Depends(reader), format: Optional[str] = None, serialization_registry=Depends(get_serialization_registry), ): """ Fetch the Apache Arrow serialization of the index values at the partition edges. """...
c42e6208e5fbbe1cf8383d2df66f8f0899c35f90
3,629,396
import requests import sys def get_key_volumes( svm_name: str, volume_name: str, cluster: str, headers_inc: str): """ get volume keys""" print() url = "https://{}/api/storage/volumes?name={}&svm.name={}".format( cluster, volume_name, svm_name) try: respo...
fcc081051541fa5f13446709eea26df02a00bb4e
3,629,397
def get_integer_array(obj,name): """ Retrieves the value of a resource that uses a one-dimensional integer array. iarr = Ngl.get_integer_array(plotid, resource_name) plotid -- The identifier returned from Ngl.open_wks, or any PyNGL function that returns a PlotId. resource_name -- The name of the resource...
fb694d87e7de8f674be5a5d3326b94b2127d071b
3,629,398
import os def test(model, dataloader, use_cuda, criterion, full_return=False, log_path=None): """ Computes the balanced accuracy of the model :param model: the network (subclass of nn.Module) :param dataloader: a DataLoader wrapping a dataset :param use_cuda: if True a gpu is used :param full...
84d3be88dbe8ae6f6d23eba86f1427a37f26d8f3
3,629,399