content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def config_factory(base_config, attr_list): """ Create new config files from attribute dictionary. """ configs = [] for attr in attr_list: # create deep copy of nested dict config_cp = deepcopy(base_config) # change value and append change_nested_dict(config_cp, attr[0]...
2a3852d7147fee49e408bdfa475468936609a5c3
3,605,227
def triplet_counts_to_dataframe(counts): """Convert a dictionary of counts, as returned by colorful_triplet_count, into a dataframe""" colors, motif, index, count = [], [], [], [] for k in counts.keys(): k_counts = counts[k] colors += [k] * len(k_counts) count += list(k_counts) ...
daa97d5ef9e89ba7216a27024bcf2761f80780a9
3,605,228
def _partition(sequence, size, count): """Partition sequence into count subsequences of size length, and a remainder. Return (partitions, remainder), where partitions is a sequence of count subsequences of cardinality count, and apply(append, partitions) + remainder == sequence.""" par...
e33e7eaa35e3c57f0decda50e863686f529d5afa
3,605,229
def get_style_sheet( bg: str = "", bg_lighter: str = "", text: str = "", text_button: str = "" ) -> str: """ Returns a string representing the style sheet. Usage: get_style_sheet(True) for dark mode or get_style_sheet(False) for light mode """ return f"""QWidget {{ background: {bg}...
1f760e240de493a34e4148f69ad64dc307b6dc99
3,605,230
import re def parse_docket_number(docket_number): """ Parse a Common Pleas docket number into its components. A docket number has the form "CP-46-CR-1234567-2019" This method takes a docket number as a string and returns a dictionary with the different parts as keys """ patt = re.compile( ...
8f9af7709f881cc82bb7d22b420a5361e085de70
3,605,231
def make_div(unit: str, length: int = 24, start: str = '', end: str = '', literal_unit=False) -> str: """ Generates and returns a custom divider :param unit: str containing a repeating unit :param length: The maximum length that will not be exceeded (default: 24) :param start: optional starting str...
d628123e807231cab2b1a96e907aa9bd97537974
3,605,233
def thread(n_workers): """ Decorator to execute a function in multiple threads. Example: .. doctest:: >>> import lox >>> >>> @lox.thread(4) # Will operate with a maximum of 4 threads ... def foo(x,y): ... return x*y >>> foo(3,4) 12 >>> f...
e45a32a3191ea91f809b6ecfdd9bb6efe321eb2f
3,605,234
from queue import PriorityQueue from collections import defaultdict from typing import List def _assign( datapoints: List, annotators: List, max_per_annotator: int, max_per_dp: int, blacklist_fn=None, ): """ Args: datapoints: A list of data points to assign to each annotator. ...
4eeefc5cc9bf70e35b396ab718228faac00e64c0
3,605,235
def correct_image_illumination(im, illum, stretch_quantile=0, mask=None): """Divide input image pointwise by the illumination field. Parameters ---------- im : np.ndarray of float The input image. illum : np.ndarray of float, same shape as `im` The illumination field. stretch_qu...
40c5b165d6e63a4fa5ae872bb39b2ef1476de1d1
3,605,236
def suffixes(word): """Returns the list of propper suffixes of a word :param word: the word :type word: str :rtype: list .. versionadded: 0.9.8""" return [word[i:] for i in range(1, len(word))]
551ea4d612a6c9f0ffe432701e3bde2c80899d85
3,605,237
import re def ValidateAndParsePemChain(pem_chain): """Validates and parses a pem_chain string into a list of certs. Args: pem_chain: The string represting the pem_chain. Returns: A list of the certificates that make up the chain, in the same order as the input. Raises: exceptions.InvalidArg...
1a81be58a804280f080f890be49dfc59c3725cfe
3,605,238
def tensormol_acsf(xyzs, Zs, elements, element_pairs, radial_cutoff, angular_cutoff, radial_rs, angular_rs, theta_s, zeta, eta): """ This function uses the tensormol atom centred symmetry functions. :param xyzs: tensor of shape (n_samples, n_atoms, 3) :param Zs: tensor of sha...
89a32d49264b7e5fbfb151fc9c9a3cb83dd1679c
3,605,239
def delete_task(id): """Delete a task by its ID""" TaskPersistence.delete(id) return {'success': True, 'message': 'Task has been deleted'}
65788e2d822ef9d150cbcae870d1c147205ca509
3,605,240
def get_morphological_patch(dimension, shape): """ :param dimension: dimension of the image (NOT the shape). :param shape: circle or square. :return: morphological patch as ndimage """ if shape == 'circle': morpho_patch = ndimage.generate_binary_structure(dimension, 1) elif shape == ...
50d6c2c366190a4b3d3a808053080bcb72a7a6a7
3,605,241
def get_preflight_headers(*allowed_methods, **options): """ gets all headers to set in response for cors preflight requests. it returns None if cors is not enabled or request's origin is not valid. :param str allowed_methods: all allowed http methods. :keyword bool enabled: specifies that cors he...
576dad68d523e159d665219a072a222e387ef8fd
3,605,242
def build_url(param_dict): """ Builds the URL needed to query [University of Wyoming, College of Engineering, Department of Atmospheric Science's website](http://weather.uwyo.edu/upperair/sounding.html) to get the proper sounding data. Parameters ---------- param_dict : dict A dictionar...
77825ae917650d1b832333920b6363d4dac7c36b
3,605,243
def get_signer(salt="newsletter_subscription"): """ Returns the signer instance used to sign and unsign the registration link tokens """ return signing.Signer(salt=salt)
a8f16ceeb48a57b75c171881555dc85497c9f0ee
3,605,244
def _fast_rcnn_box_loss(box_outputs, box_targets, class_targets, normalizer=1.0, delta=1.): """Computes box regression loss.""" # delta is typically around the mean value of regression target. # for instances, the regression targets of 512x512 input with 6 anchors on # P2-P6 pyramid is about [0.1, 0.1, ...
97cb886e0aa248798c6fa45cda95f1b096cb690a
3,605,245
def do_mprofile(func): """Wrapper that logs memory before and after a wrapped function call.""" @wraps(func) def decorated_func(*args, **kwargs): name = func.__name__ if hasattr( func, '__name__') else func.__class__.__name__ mem_info_before = memory_info() memory_logger...
506aa8cfab7f203a1bd6dc4e937d8cbd24de739a
3,605,246
def smooth(values, factor): """smooth non zero values (by factor) towards 0th element.""" new_values = [0] * len(values) for i in reversed(range(len(values))): if values[i] != 0: smoothed_value = values[i] j = 0 while True: if i-j < 0: break new_values[i-j] += smoothed_value ...
055c4bbe5bd1e696c69ad1ff14beb72b4abbdd11
3,605,248
from typing import Optional from typing import List def get_metrics(ticker: str) -> Optional[List[_Metric]]: """Get core metrics for ticker""" data = sentipy.parsed(ticker) return _contextualise_metrics(data, ticker, core_metrics)
64398664dc04cb4c140ba6744af43efb50d4d110
3,605,249
def apis_index_doc_view(request): """ Show a list of available APIs """ # Create a voter_device_id and voter in the database if one doesn't exist yet results = voter_setup(request) voter_api_device_id = results['voter_api_device_id'] store_new_voter_api_device_id_in_cookie = results['store_n...
85d30e2dcf3efc0cd7392031879dd721b58b98f3
3,605,250
from typing import cast def ss_projects(subject: State, query: Query) -> State: """Split a list-like mob by release format (album/single)""" if not query: query = subject.mob api = subject.api query_mob = ss_open(subject, query).mob print(' NOTE: "projects" may take a while') tracks...
4b83bb578311c40bf122bc41343b830d7825402a
3,605,251
def in_month(ref_date): """ which month contains a reference date :param ref_date: mx.DateTime reference date :rtype: range_string e.g. 2007-M12 """ return "%4d-M%02d" % (ref_date.year, ref_date.mon)
fe8126529521565e35f2012e359d7a9c57b773d1
3,605,252
def _precipitable_water(ea, pair): """Precipitable water in the atmosphere (Eq. D.3) Parameters ---------- ea : ee.Image Vapor pressure [kPa]. pair : ee.Image or ee.Number Air pressure [kPa]. Returns ------- ee.Image or ee.Number Precipitable water [mm]. N...
a56b3948167fb22bb49b6f84bd3980a2666dd345
3,605,253
from rest_framework.generics import GenericAPIView def api_view_with_serializer(http_method_names=None, input_serializer=None, serializer=None, validation=True): """ Décorateur permettant de créer une APIView à partir d'une fonction suivant la structure d'un serializer Elle remplace le décorateur @api_vie...
7d26a68922643ebf1f07ddb07da329a3e23d52eb
3,605,254
def euler3122PRV(e): """ euler3122PRV(E) Q = euler3122PRV(E) translates the (3-1-2) euler angle vector E into the principal rotation vector Q. """ return EP2PRV(euler3122EP(e))
4b8b64cc73683512e9f4f0fe3194e0af28bc80b3
3,605,255
import numpy def smooth(data,N=10,step=1): """ Smooth sequence data using a moving window of width N. Returns a list of tuples, <i, mu, stderr>, where i is the index of the last element of in the moving window, mu is the average of the window, and stderr is the standard error of the values in the...
3afbf9652d729de945b983dea756188cc410dbb1
3,605,256
def get_files_to_check(): """ :return: files to be checked string """ files = current_app.config.get('PYLINT_SETTINGS').get('include') if not files: abort(400, 'MISSING PYLINT_SETTINGS.include value') try: return ' '.join(files) except TypeError: abort(400, 'PYLINT_SE...
6b0d502cc38752ad588e7d08ef0479f894c2ab1f
3,605,258
from datetime import datetime import requests import json def env_sensor(sample): """Query environmental sensor data""" global env_sensor_response global env_sensor_query_interval global env_sensor_last_request if env_sensor_response == '' or datetime.now() - env_sensor_last_request > env_sensor_...
f925f5c2c1b2844356e85bba7eb8e4332559097b
3,605,259
import logging import tqdm def parse_dbcan_output(overview_path, hotpep_file, fasta_file): """Parse the data in the 'overview.txt' files from dbCAN. The 'overview.txt' file contains the CAZyme predicion data from HMMER, Hotpep and DIAMOND. A dbCAN consensus result is retrieved by finding predictions that...
6113912c0810e6abf647bee1ffa21a0e30f91845
3,605,260
def get_supported_server_info(mail_address, protocol): """Use user address to get server address and port.""" provider = mail_address.split('@')[1] if provider in supported_server: server_info = supported_server[provider] if protocol in server_info: return server_info[protocol] ...
aa67535c5232ca980a8b386afa6244496f57d752
3,605,261
def str2tuple(string: str): """Construct the tuple data from string for SecondQuantizedOp.""" return (string, 1)
f9b8fe56bf54d27c9aee6c7a3ec3ab797b08fcd0
3,605,262
def interpolation(points, queries, feat, points_row_splits, queries_row_splits, k=3): """Interpolation of features with nearest neighbours. Args: points: Input pointcloud (m, 3). queries: Queries for Knn (...
bde1dc11369fc1111d846ec6aa32fc0b8a9fb9e1
3,605,263
def running_covariance_init(shape: 'IntTensor', dtype: 'DTypeNest') -> 'RunningCovarianceState': """Initializes the `RunningCovarianceState`. Args: shape: Shape of the computed mean. dtype: DType of the computed statistics. Returns: state: `RunningCovarianceState`. """ ...
fc3858a41e1dcd39c2bef27fc37e0a96b36e1e6a
3,605,264
def integrate_up_to_thr(state, ders, thr, dt=0.005): """integrates state with derivative for up to x = thr :param state: state of the variables :param ders: derivative functions :param thr: threshold :param dt: time step (default 0.005) :return: state at threshold crossing""" xh = state[0] while((state[0] > t...
3559b2168bfbb2a3818dbe87837a463822b80a09
3,605,265
def engin(parameters_ex,parameters_in,k,name_file,test1=False): """ run the fitting :param parameters_ex: :param parameters_in: :param k: :param name_file: :return: """ parameters_ex['b']=6 data = np.load(name_file, encoding = 'latin1',allow_pickle=True) shift_time = 0 ma...
f0565ddd5df9bb827b48dcbf8ca050a831b8a026
3,605,266
def _encode(values, *, uniques, check_unknown=True): """Helper function to encode values into [0, n_uniques - 1]. Uses pure python method for object dtype, and numpy method for all other dtypes. The numpy method has the limitation that the `uniques` need to be sorted. Importantly, this is not check...
1bba77ef713b9a07e543165cb1e9179c560ff225
3,605,267
def adjust_mye_age(mye): """ Makes mid-year estimate/snpp data conform with census age categories: - subtract 100 from age (so that "1" means under 1) - aggregate 86,87,88,89,90,91 into 86 (meaning 85+) """ # keep track of some totals pop = mye.OBS_VALUE.sum() pop_m = mye[mye.GENDER == 1].OBS_VA...
a500ee483fb94950d95e4874ce3a183db332ccf5
3,605,268
from typing import List def check_validation_config( default_params: List, local_params: List ) -> ValidationConfig: """ Compare the passed parameter values of a validation function to its default parameter values. """ custom = False for kw in default_params: if not (default_params...
eda66672b7d1d06d53e586e310f3ee24241af16a
3,605,269
def binning(features, n_bins, strategy, encode, feature_names): """ Returns binned features and the corresponding labels for each bin 'n_bins' can either be an integer or a list/numpy array of n integers (different number of bins for n features) 'strategy' and 'encode' are inputs for Scikit-learns KBins...
295ccfb20d53002b15360593ef6ff9653db30d78
3,605,270
def to_grid(videos, size): """ Convert videos to a size x size grid video :param np.ndarray video: video (dim=5, axis=(video_len, batchsize, channel, height, width)) :param int size: size of one side of the grid """ t, bs, c, h, w = videos.shape # make (size x size) grid if bs < s...
c8ea4146d56283c17d19f988bb5ea77f426407d9
3,605,271
from typing import List from typing import Tuple import re def dexpand_string(string: str, to_replace: List[Tuple[str, str]]) -> str: """ inverse operation of expand_string :param string: output of expand_string :param to_replace: the same variable passed to expand_string :return: """ # ...
6b753bf8c8526092f89185bf136f554968d3f312
3,605,272
def _reassemble(obs_settings, num_bricks, randomize_initial_order, randomize_desired_order): """Configure and instantiate a `Reassemble` task. Args: obs_settings: `observations.ObservationSettings` instance. num_bricks: The total number of bricks; must be between 2 and 6. randomize_init...
a007ce91f4816406bd8f1a8ee308db2506cf73d1
3,605,274
def get_list_types(list_type=['organisation_type_id']): """Method to get all organisation types for js.""" try: org_units = SetupList.objects.filter(is_void=False) vals = [] orgs = {} orgs_dict = {} cnt = 0 for org_unit in org_units: field_name = org_u...
8b371bae35cd8f11d8e6b44d60ebaadc03a7475e
3,605,277
def YScaleFun(center): """ function that returns a scaling vector to scale y data to same range as x data """ # center gets ignored in this case return N.array((5e7, 1), N.float)
3314618c40db6b7954b246234aece384654a8539
3,605,278
def mesh_muvw_fz(quad_int, cryst_ptgrp, sig_type, *args): """ For given integer quadruples, the set belonging to the corresponding fundamental zone are separated out and retruned. Parameters ---------------- quad_int: numpy.array Integer quadruples cryst_ptgrp: str Proper po...
f59ed76aabe94330ca8c3662a37c34cd66d7549a
3,605,279
def atcab_aes_cmac_finish(ctx, cmac, size): """ Finish a CMAC operation returning the CMAC value. Args: ctx AES-128 CMAC context. cmac CMAC is returned here. cmac_size Size of CMAC requested in bytes (max 16 bytes). Returns: Stat...
cbc77488bc204e5b6c9b0cf35d35ae376edf4f74
3,605,280
def neg2pos(index, shape): """Make a negative index (that counts from then end) positive .. warning:: this function should be called only once -- always on user inputs -- otherwise we risk transforming back stuff that should be kept negative. Ex: neg2pos(-5, 3) = -2 ...
f863230e20af21cd6c69e8ac8d91757e692b6803
3,605,281
from typing import List from typing import Tuple from typing import Type def compare_detect_inference_frame( df: pd.DataFrame, typeset: VisionsTypeset ) -> List[Tuple[str, Type[VisionsBaseType], Type[VisionsBaseType]]]: """Compare the types given by inference on the base graph and the relational graph Ar...
d43c1e1747ec4be8136e87ebaf9edf9e2346b2e3
3,605,282
def setup_experiment(lbann): """Construct LBANN experiment. Args: lbann (module): Module for LBANN Python frontend """ # Setup the training algorithm SGD = lbann.BatchedIterativeOptimizer TSE = lbann.TruncationSelectionExchange metalearning = TSE( metric_strategies={'rando...
8a5581395f9851e6de6fa4a0477ef20214d5d3ea
3,605,283
def pointwiseFold(f,x,n,listOfLists): """This function is a generalization of the fold function to take more than one list. Keyword arguments: f -- the binary function used to accumulate some value x -- the initial value for all the values n -- the common length of the lists ...
e6c8cd5565b5554631aa55c5b42c9c50a11256e7
3,605,284
import calendar def update_pie(year, ser): """ Update the pie plot using dailyStats, as function of selected year in year-slider In case of None use Current year as default year """ year = year if year is not None else dyear dailyStats = pd.read_json(ser) min_month = dailyStats.index.m...
dcdd28754c6b77cbad266a578c4e71b92ba08bc7
3,605,285
import numpy def _n_gaussians(x, N, *params): """Sum of N Gaussian functions plus an offset from zero Parameters ---------- x : float values to calculate Gaussians function at N : int number of Gaussians params : floats 3*N + 1 parameters corresp...
afa3683316f60463a8320457754680e3da52714c
3,605,287
def posts_update(post_id): """Handle form submission for updating an existing post""" post = Post.query.get_or_404(post_id) post.title = request.form['title'] post.content = request.form['content'] db.session.add(post) db.session.commit() flash(f"Post '{post.title}' edited.") return r...
ef14c4712f1a1810bea4503358f0f93623cf0b14
3,605,288
def get_azimuth_value(label): """ Returns the angle in degrees represented by a azimuth label int. Parameters ---------- label: int Azimuth label. """ _check_is_integral('azimuth', label) if label == -1: return None else: if (label % 2) != 0 or label < 0 or la...
d33ff558b23b3dc0cc9ce411686403e4519ac59c
3,605,289
def _unpack_topk(topk, lp, hists, xok=None, sub_stts=None, attn=None): """unpack the decoder output""" beam, _ = topk.size() topks = [t for t in topk] lps = [l for l in lp] k_hists = [(hists[0][:, i, :], hists[1][:, i, :], hists[2][i, :]) for i in range(beam)] if xok is not None: ...
db9d93ef8b40390733034ce10ef7228bc4d23fbf
3,605,290
def pack_bits( longbits ): """Crunch a 64-bit int (8 bool bytes) into a bitfield.""" byte = longbits & (0x0101010101010101) byte = (byte | (byte>>7)) & (0x0003000300030003) byte = (byte | (byte>>14)) & (0x0000000f0000000f) byte = (byte | (byte>>28)) & (0x00000000000000ff) return byte
78fdf9828b4f98c9bc44233ef5f95244eefb24fc
3,605,291
from pathlib import Path def fullpath(path=""): """ Path: Expand relative paths and tildes. """ return Path.cwd() / Path(path).expanduser()
e7b7d1caa67a2a9988035713ec18347b5581406e
3,605,292
def get_engine_latest_version(request): """ Return a string with if new versions have been released. Return 'None' if the version is not available """ return HttpResponse(engine.check_obsolete_version())
4d4e1d864ec8e9a46867820959a98dbdcdb19a1a
3,605,293
def scaffold_split(data, test_size, balanced = True, random_state = 0): """ Splits a :class:`~chemprop.data.MoleculeDataset` by scaffold so that no molecules sharing a scaffold are in different splits. :param data :param test_size: the proportions...
26ec190d4ac251883be014fb4b7d71cbf071a5a3
3,605,295
import io def read_file(path): """Returns all the lines of a file at path as a List""" file_lines = [] with io.open(path, mode="rt", encoding="utf-8") as the_file: file_lines = the_file.readlines() return file_lines
8e220e0b90ded168a1d1d8d37b7451b7796b1ed5
3,605,296
def scale_by_std(df, demean=False): """ Align the columns of the df to the last value. """ df = df.copy() if demean: df -= df.dropna().mean() scale = np.abs(df.dropna().std()) return df / scale
ee6ab8359e0bf089d2f6ea40601299665024570c
3,605,297
def count_intersections(lines, *, with_diagonals): """ >>> lines = [(0,9,5,9), (8,0,0,8), (9,4,3,4), (2,2,2,1), (7,0,7,4), (6,4,2,0), (0,9,2,9), (3,4,1,4), (0,0,8,8), (5,5,8,2)] >>> count_intersections(lines, with_diagonals=False) 5 >>> count_intersections(lines, with_diagonals=True) 12 """ ...
c9a1d13e64cca408b76d5c1271be3afca0d87dcd
3,605,298
def edit_product(request, product_id): """ Edit a product in the store """ if not request.user.is_superuser: messages.error(request, 'Sorry, only store owners can do that.') return redirect(reverse('home')) product = get_object_or_404(Product, pk=product_id) if request.method == 'POST':...
17578c3210d9f84d1746d8a55cee1efcf8755fbb
3,605,299
import asyncio def pool_get_verifiers(pool_handle: PoolHandle) -> asyncio.Future: """Fetch the set of active verifiers for an opened pool instance.""" return do_call_async( "indy_vdr_pool_get_verifiers", pool_handle, return_type=lib_string, post_process=str, )
8c673a35e618529af719c550919002e870ab8f6d
3,605,300
def format_dir_list_recurse(curdir, search=""): """Format the list of directories.""" total = [] for item in curdir.contents: if isinstance(item, ListDir): total.extend(format_dir_list_recurse(item, search=search)) if item.used: total.append(item) elif...
7d0aa9bb99b2a5bc75729622c449b74a218758c9
3,605,301
def _load_config_file(config_file_path: str) -> Config: """Reformats and validates the config file """ parsed_config = _parse_config_file(config_file_path) reformatted_config = _reformat_dict(parsed_config["transient"]) reformatted_config["qemu_args"] = parsed_config["qemu"]["qemu-args"] trans...
2cb6fa16af3cd2d4ec6d4e038d4198cb429b91cd
3,605,302
def index(): """新闻首页""" #------------------获取用户登录信息------------------ #1.获取当前登录用户的id # user_id = session.get("user_id") # user = None # type:User # #2.查询用户对象 # if user_id: # try: # # 获取到用户对象 # user = User.query.get(user_id) # except Exception as e: ...
40581da5606ce87e43ca4e897106849214b16ebd
3,605,303
from typing import Dict def r_complex(params: Dict[str, float]) -> ComplexFloat: """ Reflection coefficient, derived from transmission coefficient Magnitude from |t|^2 + |r|^2 = 1 Phase from phase(t) - phase(r) = pi/2 """ r_amp = jnp.sqrt( ( 1. - params['t_amp']**2 ) ) r_ang = params['t_an...
eb4509814007c293b549dbe8b3eb6cfa8ed5f83d
3,605,305
def get_noam_schedule(optimizer, num_warmup_steps, model_size, last_epoch=1): """Creates a Noam (inverse square root) scheduler with linear warmup and encoder gradual unfreezing. :param optimizer: torch Optimizer where some param groups have 'group_type' key if group_type starts with 'encoder_' it will...
6b9a9c9bae0bbe16e2ba3f200270349173bce0c4
3,605,306
def isvalid(message): """Verifies that a message is valid. i.e. it's similar to: 'daily-0400/20140207041736'""" r = re.compile("^[^/]+/[0-9]+") return r.match(message)
5900e566780cc17c70a9239b374b77ea1eced83e
3,605,307
def project_details(request, id): """ Show project details """ project = Project.objects.get(pk=id) voted = False if project.voters.filter(id=request.user.id).exists(): voted = True return render(request, "project_details.html", {"project": project, "voted": voted})
3fe5fef1fad53853310779cae7948e96e01f3d82
3,605,310
def target(func): """ This is a decorator function :param func: :return: """ def target_func(*original_args, **original_kwargs): # print 'before the func' # print original_kwargs retV = func(*original_args, **original_kwargs) if retV is None or retV == False: return False else: ...
0e77444acd4b3a2ba7efd49854a3c081a054d337
3,605,311
import turtle def new_horse(image_file): """(str) -> turtle Create a new horse where <image_file> is a valid shapename Returns a turtle object """ horse = turtle.Turtle() horse.hideturtle() horse.shape(image_file) return horse
8abd7ea09cfe3340c06250f430ee6f25b03f45aa
3,605,312
from sklearn.preprocessing import StandardScaler def process_XY(bigdf_subset): """ Takes dataframe containing amalgamated data, subsetted to get rid of NaNs, and outputs training & testing X and y """ #Creating X and y y = bigdf_subset['epa_meas'] X_raw = bigdf_subset.drop(columns=['epa_me...
db2858aaaf894217ec8522dff452897d7099ba61
3,605,313
def Recall(y_true, y_pred): """Recall metric. Only computes a batch-wise average of recall. Computes the recall, a metric for multi-label classification of how many relevant items are selected. """ true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K....
fde7fa088358915590e61f0c9bfcb2ed75e9ce73
3,605,314
import re def sort_simulations(df_ts, dyn_dend_order): """ Sorts the simulations in the dataframe according to the order in the list dyn_dend_order """ # Create a dictionary with the order of each simulation row in the plot dyn_dend_order_dict = { dyn_name : dyn_dend_order.index(dyn_name) for dy...
68ae24234698803e9f5dd861d7f5255f845401c7
3,605,315
def generate_chemicals_from_fragments(smiles_list, n=10): """ reconstruct chemicals from fragments Paramters ----------------- smiles_list: list of string list of smiles of fragments n: int number of chemicals to be generated Returns --------------- smiles_list: lis...
27ca6d17279765ef68121fdfdc33af7892644623
3,605,317
import random def rand_augment_both(im, mask,magnitude, ops, n_ops=2, prob=1.0,fill=(128,128,128),ignore_value=255): """Applies random augmentation to an image.""" ops = ops if ops else RANDAUG_OPS if ops=="full": ops=RANDAUG_OPS elif ops=="reduced": ops=RANDAUG_OPS_REDUCED else: ...
3eea1f502edc18019aa2f0df5ca8cb6b21dfa113
3,605,318
import csv def load_penetration(scenario, path): """ Load penetration forecast. """ output = {} with open(path, 'r') as source: reader = csv.DictReader(source) for row in reader: if row['scenario'] == scenario.split('_')[0]: output[int(row['year'])] = f...
23a9730e9d8ec524fe79eaf50c3adb2a1641d002
3,605,319
def table_pc(): """ Generate the final table without price and moving-average adjustments. Returns: nonadj_pc (pd.DataFrame) """ gross_premiums = premiums_data() gross_claims = claims_data() wealth = wealth_data() population = pop_data() gross_precl = pd.merge(gross_premium...
222e5ed59a7c85e043ad6556aa988012ba3f45ec
3,605,320
def get4Neighbors(img, i, j): """ Get the 4 neighbours for the pixel analysed. Parameters: img, image; i, row number; j, column number. Returns: neighbors, list of neighbors. """ N, M = img.shape neighbors = [] i...
e3765a34ad02b9cf8d1be19f6e0e03db20ea28df
3,605,321
def getAllSecurityGroups(roleArn=None): """ This function grabs each security group from each region and returns a list of the security groups. If a roleArn is provided, the role is assumed before monitoring """ session = getSession(roleArn) # defaults to local aws account if arn is None a...
31c8148899bf7b4cd751a78e5c4612e6c92b9e8b
3,605,322
def get_values(source, selection, lookup): """ Returns values for a selection of values after a lookup. :param source: The array of values to select from. :param selection: An array of keys, for the selection. :param lookup: The mapping to resolve actual indices of the value array from the sele...
fcb2b09b981a85ab64079cfeff8b3db77628a434
3,605,323
import codecs import json import urllib def get_annotations(psm_row): """ Runs the Xi annotator to get the fragment annotation. """ if psm_row.SearchID > 10000: url = 'http://xi3.bio.ed.ac.uk/xiAnnotator/annotate/%s/85160-94827-76653-69142/%s/?peptide=%s&peptide=%s&link=%s&link=%s' % ( ...
d82063a94c8d222d0f1ccd5d82fb21b77ba8f066
3,605,326
def update_profile(): """User profile update.""" form = UserUpdateProfileForm() form.user_name.data = flask_login.current_user.name if form.validate_on_submit(): set_user_by_instance( db.session, user=flask_login.current_user, lastname=form.lastname.data, ...
d38e23596e2b8783901db018368d51c6a57a2095
3,605,327
def youtube_search(query, max_results, args): """Fetches youtube video links for the movie with title provided in query Fetches trailer url for movie with title in query and containing keywords "OFFICIAL" and "TRAILER" in the title. params: query: the keyword for the youtube search, for exampl...
3001b612bc156d67315e882f28aab704f8368eb5
3,605,328
def input_block(config, section): """Return the input block as a string.""" block = '' if section not in config: return '' for key in config[section]: value = config[section][key].strip() if value: block += '{} {}\n'.format(key, value) else: blo...
4f6ff5979c99171b390429bc6e90b325986d9f99
3,605,330
def fig3(data, lB_list, rho_p_fixed, rho_s_fixed, rho_p_varied, rho_s_varied, beads_2_M, kwargs, figsize=None, pad=3, vertical=True): """Plots Figure 3 of tie lines in polymer-salt plane.""" # formats figure if figsize is None: fig = plt.figure() else: fig = plt.figure(figsize=fi...
fdc51ec564ffa94941939b8b3288159679391faf
3,605,331
def broadcast_join_skewed(not_skewed_df, skewed_df, join_col, number_of_custs_to_broadcast): """ Suitable to perform a join in cases when one DF is skewed and the other is not skewed. splits both of the DFs to two parts according to the skewed keys. 1. Map-join: broadcasts the skewed-keys part of the no...
6e957d6210635faadecd1f78a4b7c0cd84f08b87
3,605,332
def remove_suffix(string, suffix): """ This function removes the given suffix from a string, if the string does indeed end with the suffix; otherwise, it returns the original string. """ # Special case: if suffix is empty, string[:0] returns ''. So, test for a non-empty suffix. if suffix and str...
f5b0782333ecd5d6a9107f9412f131145612d3a2
3,605,334
import scipy def FindZeroDoubleExp(p, x0, yshift=0.0): """ Finds the zero point of a negative double exponential function. :return: roots """ roots = scipy.optimize.fsolve(doubleExponent, x0, args=(p, yshift)) return roots
40f7a4588ed76a5dcbad88cbff75cc61d31b5ce5
3,605,335
def parent_path(value: str) -> str: """Returns the parent configuration path from a configuration path.""" return CONFIG_SEPARATOR.join(value.split(CONFIG_SEPARATOR)[:-1])
6b8fecdbf0a2de3b22bbfd0a08f5d0bb65fb7c64
3,605,336
def optimize_pushes_pops(codes): """ This finds runs of push(es) followed by pop(s) and combines them into simpler, faster mov instructions. For example: push [bp+8] push 42 pop ax pop ax Will be turned into: mov ax, 42 mov ax, ds:[bp+8] """ optimized ...
522ac834c03e84093142f7f512158220c40cf2e5
3,605,337
def permutations(values): """Return a strategy which returns permutations of the collection "values".""" values = list(values) if not values: return just(()).map(lambda _: []) def build_permutation(swaps): initial = list(values) for i, j in swaps: initial[i], ini...
c295446d72af91c6545e700c9a2181b5ffc70379
3,605,338
def get_rebaser_factory(dvcs_type, rebasers=REBASERS): """Return implementation factory for dvcs_type""" return rebasers[dvcs_type]
407c70c878eda07ed5c2e23de7b5923655695bd9
3,605,339
def address(): """ RESTful controller to allow creating/editing of address records within contacts() """ # CRUD pre-process def prep(r): person_id = request.get_vars.get("person", None) if person_id: s3mgr.configure("pr_address", c...
20164702ec09c3ba1c09d7e22d174ed3f3bf8949
3,605,340
import re def get_gpm_orbit(gpmfile: str) -> int: """ Parameters: ----------- gpmfile: str GPM data file. Returns: -------- orbit: int GPM Granule Number. """ try: with h5py.File(gpmfile) as hid: grannb = [s for s in hid.attrs["FileHeader"].spli...
f8a56dcf27f335b5d39121331d8ea2bc59ff6ce6
3,605,341
def load_single_file_regression(directory, file_name, word_to_indices_map, nb_words=None): """ Loads a single file and returns a tuple of x vectors and y labels :param directory: dir :param file_name: file name :param word_to_indices_map: words to their indices :param nb_words: maximum word inde...
e971f76512b0aa67ce8842a9bf664df74c1b18cf
3,605,342