content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def layout_photo_5_2(photo): """ 在5寸照片上排版2寸照片 :param photo: 待处理照片2寸 :return: 处理后的照片 """ bk = Image.new("RGB", (HEIGHT_5IN, WIDTH_5IN), (255, 255, 255)) # 竖版排版 # 创建画笔 draw = ImageDraw.Draw(bk) draw.line([(0, WIDTH_5IN / 2), (WIDTH_5IN, WIDTH_5IN / 2)], fill=128) # 横线 draw.line([...
2183babdc363620c7126df810c6d7e85fdbdebe0
3,598,954
from typing import Set def get_gt_nsrts(predicates: Set[Predicate], options: Set[ParameterizedOption]) -> Set[NSRT]: """Create ground truth NSRTs for an env.""" if CFG.env in ("cover", "cover_hierarchical_types", "cover_typed_options", "cover_regrasp", "cover_multistep_opti...
1fa376eef49e0ac09b89c0a3ccfc096edd159779
3,598,955
import zlib import struct def fragments_to_schedule(fragments: list) -> dict: """Convert a set of fragments (a blob) into a schedule. May raise a `zlib.error` exception. """ raw_schedule = zlib.decompress(bytearray.fromhex("".join(fragments))) zone_idx, schedule = None, [] old_day, switchpo...
b9d436a539675333c24d174c0d7a309438b28ee4
3,598,956
def compute_scl_mask( scl, mask_vals, gdf, verbose=False, verbose_plot=False, scene_id=None, res=None, date=None, bins=100): """Compute the Red Chlorophyll Index image from band08 and band04 values Args: scl (dict): Sentinel-2-L2A Band04 raster data mask_vals (dict): Sentinel-2-...
6c19a3d188a5bff07712b6e926ece7c02c08ad21
3,598,957
def r_value(aa1, aa2, aa_dict, matrix): """ :param aa1: :param aa2: :param aa_dict: :param matrix: :return: """ return sum([(matrix[i][aa_dict[aa1]] - matrix[i][aa_dict[aa2]]) ** 2 for i in range(len(matrix))]) / len(matrix)
034d1d7eb0baa63cd5bd4572c87f86bcc8774de4
3,598,958
def init(param_test): """ Initialize class: param_test """ # initialization default_args = ['-t mt/label/ -w mt/warp_template2mt.nii.gz -gm mt/mt1_gmseg.nii.gz -wm mt/mt1_wmseg.nii.gz -manual-gm mt/mt1_gmseg_goldstandard.nii.gz -sc mt/mt1_seg.nii.gz -param step=1,type=seg,algo=centermassrot,metric=M...
cd0b7e61cabda521c0f07e72e74316e7766ea2d2
3,598,959
def compose_all(graphs, name=None): """Return the composition of all graphs. Composition is the simple union of the node sets and edge sets. The node sets of the supplied graphs need not be disjoint. Parameters ---------- graphs : list List of NetworkX graphs name : string S...
0dd2a9f4e846cc7a7410ecc04cb1f85e2776bbe9
3,598,960
def create_Q_scipy(par,sol,ast,solmethod): """ create Q for use with scipy """ def remove_small(x): I = np.abs(x) < eps_low y = x.copy() y[I] = 0 return y for iz in range(par.Nz): #order of diagionals is important to getsorted indices ast.Qs[iz] = diags( di...
4172f8c116803d2a0f030f442f647c56f67478d6
3,598,961
def init_standard(nnet, dataset): """My standard initialization for a neural network """ # use orthogonal initialization of all W's for synapse in nnet.synapses: W_start = synapse.W shape = B.eval(W_start.shape) W_final = orthogonal(shape) B.set_value(W_start, W_final) ...
882e0b886bb17877983404b3aa8232e9c499d674
3,598,965
def calculateProgressMetrics(job): """ job has the most recent values updated for the current event being processed. Calculate status and progress metrics using the new information. :param job: JSON job data struture from dynamodb """ progressMetrics = {} # BASE TIMES FROM EVENTS # cr...
73524e53f5dd77c81cd0e9f6239588e41b9bc841
3,598,966
def _ydiff_excess_equals_expected(yint, xmin, xmax, x, model): """The ExcessEqualsExpected method to compute Y (differential). y / yint = y_model / yint_model""" yint_model = _integrate(xmin, xmax, model) y_model = model(x) return y_model * (yint / yint_model)
8476fee5e720ddb45a46a9baa61b18dc235f27bc
3,598,967
def rescale_boxes(boxes, current_dim, original_shape): """ Rescales bounding boxes to the original shape """ orig_h, orig_w = original_shape # The amount of padding that was added pad_x = max(orig_h - orig_w, 0) * (current_dim / max(original_shape)) pad_y = max(orig_w - orig_h, 0) * (current_dim / m...
769264b54e0a2dc438d78942e4c86f46c1b6470e
3,598,968
def get_summary_indices(df, on='NOSC'): """ Get the summary stats for the indices: median, mean, std, weighted mean and weighted std """ samples = get_list_samples(df) samples.append(on) t = df[samples] t = t.melt(id_vars = [on], var_name = 'SampleID', value_name = 'NormIntensity') t = t[t[...
34549141bdcd7b4092748c540275d4cea4ead9cf
3,598,969
def get_eqopp_policy_from_selection_rate(selection_rate, loan_repaid_probs, pis, scores): """Return policy with specified selection rate on Y=1 for both groups.""" # compute P(X, Y=1|A) ...
bffa9b5f3d1715b21422074b1c1b4d8c08fe6583
3,598,970
def getWell(mmdict, df, size, row, column, nchannels, channels=None): """ Get every image patch in a well Parameters ---------- mmdict : dict dictionary of memmap file df : DataFrame size : int size of image patches row : int row in the plate column: int ...
4814e8b8ab636691486dc7fd73077b9a84bc403a
3,598,971
def concat_time_series_matrices(mats, t=None): """Concatenate a list of gene x cell matrices into a single matrix. Arguments --------- mats: :class:`~numpy.ndarray` A list of gene x cell matrices. The length of the list equals the number of time points t: :class:`~numpy.ndarray` or list ...
afca744f7bbb945038efa59c36d44243ac5dbaa2
3,598,972
def get_route_config(route, ifname): """ Builds a basic route config dictionary with all of the fields required to format a basic network_route puppet resource. """ if route['prefix']: name = '%s/%s' % (route['network'], route['prefix']) else: name = 'default' netmask = IPNet...
e9400f52c2647a44e88932b2d808c6f18b4169ce
3,598,973
def concat (tensors_list, axis): """ Better version. """ if len(tensors_list) == 1: return tensors_list[0] return tf.concat(tensors_list, axis)
f0316f688ff0cc3a0d18970a9d614d48db584e89
3,598,974
def redundant(src, key=None, distinct=False, sort=True): """The complement of unique(), returns non-unique values. Pass distinct=True to get a list of the *first* redundant value for each key. Results are sorted by default. >>> redundant(range(5)) [] >>> redundant([1, 2, 3, 2, 3, 3]) [[2, 2...
3b660e5ba3833c95bba97e4546b7915d6f0343ae
3,598,975
from datetime import datetime def serialize(data, maximum_depth=0, level=0): """ Serializes dicts and django models to dict :param data: The data :param maximum_depth: Maximum recursion depth :param level: Current level :return: A dict """ result = None if isinstance(data, dict): ...
48cd8a5dad8d4a200be9f56e66faf0421052dd03
3,598,977
def create_embeddings_dic(all_words, embeddings_path, num_dimensions): """ :param all_words: :param embeddings_path: :param num_dimensions: :return: """ embeddings_dic = {} print("Building embeddings dic from " + embeddings_path) with open(embeddings_path, "rb") as infile: ne...
6a621df4d55ec8c7151fbe8d105b98787414b559
3,598,978
def user_can_view_data(user): """ Determine if the user is active and authenticated. :param user: The user to lookup. :type user: str :returns: True, False """ if user.is_active: if user.has_access_to(GeneralACL.WEB_INTERFACE): return user.is_authenticated() else...
34849adc4f87892711e52542e5142a6d9fd27df7
3,598,979
def most_similar_command(command: str, command_list: set) -> (list, str): """ Determine whether its possible to suggest a similar command. The similarity is determined by the levensthein distance and a factor (currently 1/3) sets a limit where a similar command is useful to be automatically used. If the...
58fe2cca6b7194745274e6e873cde0ca2e4980fa
3,598,980
import torch def precision_score(tp: torch.Tensor, fp: torch.Tensor, reduce: bool = True) -> torch.Tensor: """Computes the precision using true positives and false positives. :param tp: true positives, dims (C,) or () :type tp: torch.Tensor :param fp: false positives, dims (C,) or () :type fp: tor...
33ba13fbf4a267c43d32b440e5aaab317e671e50
3,598,981
def gen_cp(duration, h): """ generate the CP times from the trial by successively sampling from an exponential distribution :param duration: trial duration in sec :param h: hazard rate in Hz :return: numpy array of change point times strictly positive and inferior to duration """ cp_time...
4975795a9726e73987fccd0af65aa9f6430c1005
3,598,982
import socket def tcp_socket_open(host, port): """ Returns True if there is an open TCP socket at the given host/port """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) try: return sock.connect_ex((host, port)) == 0 except socket.timeout: return...
11519e5d9f2d1de39d8091af011f0458e556021c
3,598,983
def make_color_wheel() -> np.ndarray: """ Create colour wheel. Code adapted from https://github.com/liruoteng/FlowNet/blob/master/models/flownet/scripts/flowlib.py """ red_yellow = 15 yellow_green = 6 green_cyan = 4 cyan_blue = 11 blue_magenta = 13 magenta_red = 6 ncols = re...
71e64dd033164ce6541e67365583f7d0d5d2fd7e
3,598,985
def get_geo_node_us(dirname, points, state, county, simplify): """ This function maps a each node to a geographic region. For US only. """ # Directories shapepath = dirname + '/resources/additional_info/state_'+ state + '/cb_2015_'+state+'_tract_500k' # Read in shapefile sf = shapefile.R...
33c3fb8073d2faae5faf1b632e7a64c9afe09355
3,598,986
def transparently(function): """ Wrap ``function`` so that it is called, but that the first parameter is returned. """ @wraps(function) def decorated(value, *args, **kwargs): function(value, *args, **kwargs) return value return decorated
30a0bc37093b18a36edf5b910342b229349e6582
3,598,988
import re def is_relative_import_name(import_name: str) -> bool: """Checks if an import name is relative.""" return re.fullmatch(_RELATIVE_IMPORT_NAME_REGEX, import_name) is not None
428925346bf0f710a886bc7b05174321142601a8
3,598,989
def decode_html(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS): """ Converts a `html` containing an HTML page into Unicode. Tries to guess character encoding from meta tag. """ if isinstance(html, unicode): return html if encoding: return html...
7dbb2b71a24c3a7662f2351eba516f6f0c518bb3
3,598,990
def variance(data): """ Assumes that an array of integers is passed """ mean = sum(data)/len(data) tot = 0.0 for d in data: tot += (d - mean)**2 return tot/mean
3329792cf7043ad6e68cad39d6a07bf2909d1496
3,598,991
def generalized_parity_solver_with_partial(g, partial_solver): """ Generalized parity games solver. This is an implementation of the classical algorithm used to solve generalized parity games. This is the wrapper function which complements every priority and calls the actual algorithm. :param g: the gam...
142424d5f315cdb7e9fd1f6c2fbbf4f44493aacc
3,598,993
def susceptible_60(): """ Real Name: b'Susceptible 60' Original Eqn: b'INTEG ( deimmunization rate 60-infection rate 60, init Susceptible 60)' Units: b'person' Limits: (None, None) Type: component b'' """ return _integ_susceptible_60()
0d180ea1a1523e6ee748bcf8f9e283d5e2bde2f2
3,598,994
def encode_track_results(track_results): """Encode bitmap mask to RLE code. Args: track_results (list | tuple[list]): track results. In mask scoring rcnn, mask_results is a tuple of (segm_results, segm_cls_score). Returns: list | tuple: RLE encoded mask. """ ...
371fcc456cfa21c34a9c8dab95f90b9b4f2ec7f9
3,598,996
def linear_activation_backward_reg(dA, cache, activation_fn="relu", lambd=0): """ Arguments --------- dA : 2d-array post-activation gradient for current layer l. cache : tuple values of (linear_cache, activation_cache). activation : str activation used in this layer: "sig...
a1075628dfc62969d981c4537e5b44fd44b5f461
3,598,997
import traceback def get(key, response=None): """Returns k:str to exist in the yml file, Otherwise it returns default.""" try: global CONF_FILE if CONF_FILE: if isinstance(key, str): sb = key.strip('.').split('.') p = CONF_FILE for i...
f36c0fd787966c63ce2b2f3cf1b397ffceb8f4a5
3,598,998
from typing import Union from typing import List from typing import Optional from typing import Dict from pathlib import Path import torch def train_model_pretraining( dataset_name: Union[str, List[str]] = None, dataset_sampling: Union[float, List[float]] = None, dataset_dir: str = None, ...
dd7d445e7fc1193a9e1f77086ee06f1f31784eda
3,598,999
def poor_cond_toep(n): """ :param n: size of output :returns: the top row of a randomly scaled PSDT matrix whose :math:`L^2` condition number scales exponentially with `n` """ top = np.arange(n)[::-1] * (np.random.rand() + 1e-3) while smallest_eig(top) < 0: top[0] *= 2 ...
f9645e50ade7aa76e694242fd61a4eb1bae8a443
3,599,000
from datetime import date, timedelta from numpy import ndarray, matrix, generic from pandas import DataFrame, Series, Index from spyder.pil_patch import Image def get_supported_types(): """ Return a dictionnary containing types lists supported by the namespace browser. Note: If you update this li...
51e577fbfbe97f5fc945fb906399a8ab7a5e188c
3,599,001
def view_mempool(): """insert new transaction to mempool""" return mempool.transactions
a8dbb0fd7b50a6f89c895c641aadc854e195643b
3,599,002
def calculate_profile_input_for_cluster_analysis_from_ERA5(p_profile, t_profile, td_profile, q_profile, u_profile, v_profile, h_profile, surface_p): """ takes data from ERA5 for only one time stamp for all pressure levels from 250 to 1000 hPa :param...
dd1f15c3b62ad5e6b9706b59c55fcb220340b9a0
3,599,003
def components_graph(geo, stereo=True): """ Generate a list of molecular graphs where each element is a graph that consists of fully connected (bonded) atoms. Stereochemistry is included if requested. :param geo: molecular geometry :type geo: automol geometry data structure :...
e1fbee2042601620f342578725d2eb35fc6bc7bf
3,599,004
from pathlib import Path import json def get_configured_hosts(): """Look into the user preferences to enumerate the remote ssh hosts that were configured for use with dallinger. """ hosts_dir = Path(APPDIRS.user_data_dir) / "hosts" res = {} if not hosts_dir.is_dir(): return res for...
49a7c8b4aa7ad34ad82bc5df5c196de957495fa1
3,599,005
import numpy def readValidationImages(): """ Reads in all images in the validation directories Creates a numpy array containing the pixel data of all the images in the directories of validation images. Assumes that the subdirectories "PosVal" and "NegVal" exit in the working directory Args: None ...
b110d5e20091fd09b6ef9c3cd7ca540933e3451a
3,599,006
from typing import Optional from typing import List import math import random def sample_from_range(range_max: int, sample_ratio: float, max_samples: int, preselected: Optional[List[int]]) -> List[int]: """ Given a range of numbers in 0..range_...
8be7b5ded3b6f3b54da57027a5d7629a9bf5dc9f
3,599,007
import regex import traceback def data_masking(instance, db_name, sql, sql_result): """脱敏数据""" try: keywords_count = {} # 解析查询语句,判断UNION需要单独处理 p = sqlparse.parse(sql)[0] for token in p.tokens: if token.ttype is Keyword and token.value.upper() in ['UNION', 'UNION ALL...
b92df933e5681cf729a213dd7bc92eda5962c80d
3,599,008
from typing import List def filter_single_group( molecules: pd.DataFrame, groups: List[str], exclude: bool) -> pd.DataFrame: """Check that the molecule has a single functional group.""" # First filter the molecules that have the target functional groups molecules = filter_by_functional_group(molec...
31fb07a77282c317f577ca2c0c8c935887af5894
3,599,009
def occ(s1,s2): """occ (s1, s2) - returns the number of times that s2 occurs in s1""" count = 0 start = 0 while True: search = s1.find(s2,start) if search == -1: break else: count +=1 start = search+1 return count
4f107e5552d794e9e82a8a6b19ec63992034e9f7
3,599,010
import functools import operator def prod(x): """Equivalent of sum but with multiplication.""" # http://stackoverflow.com/a/595396/1088938 return functools.reduce(operator.mul, x, 1)
31f4defa3401d6dcf05f8ec70c32650f000a1852
3,599,011
def compare_dfs(old_df, new_df, on): """ Function to compare two DataFrames with nans and return a dict with rows that have changed (diff), rows that exist in new_df but not in old_df (new), and rows that exist in old_df but not in new_df (remove). Both DataFrame must have the same columns. Parameters...
705f19b9b48827dca3baf4e31e6396f706d9136c
3,599,012
def indent(text, prefix=" "): """ Add a prefix to every line in a string. """ return "\n".join(prefix+line for line in text.splitlines())
e83cc0b14c5b8c304f6e41bf145b06b1de451e8c
3,599,013
def load(fname): """Return a `BDD` loaded from DDDMP file `fname`. If no `.orderedvarnames` appear in the file, then `.suppvarnames` and `.permids` are used instead. In the second case, the variable levels contains blanks. To avoid blanks, the levels are re-indexed here. This has no effect if `...
d81ff16bb356f00df3e795991657772ee71ca2d5
3,599,014
def get_iterator(ip, value, community_string, is_oid=False): """ Get pysnmp iterator Args: ip: The device's IP address value: MIB id or SNMP OID community_string: The community string for the network. Usually 'public' or 'private' is_oid: boolean if t...
f1fcfdb3aa772efd7448c1dec3506aa14d205731
3,599,015
from typing import Tuple from typing import Dict from typing import Union def _get_event_description( elem: etree.Element, ) -> Tuple[str, Dict[str, Union[str, int]]]: """Returns the full description of a single XML Event in the DFL format. Parameters ---------- elem: lxml.etree.Element l...
8e1af0808d570f6ce1949b8035dcb316f12c6a70
3,599,016
def deserialize(fmt, stream_or_string, **options): """ Deserialize a stream or a string. """ d = get_deserializer(fmt) return d(stream_or_string, **options)
f14c8b42f2be5a2c3301cbe1ca7bf70fe22ddc73
3,599,017
import logging def read_nitfile(path: str): """ read and parse the "nit" (config) file and return as a dict """ logging.info(f"opening nit file {path}") nit = {} with open(path) as fp: for line in fp.readlines(): if '#' in line: line, comment = line.split('#', max...
831453ee9e0bc6b4c58969ffad10cd385754fdc0
3,599,018
def get_resblock(model, layer_name): """ model is a class resnet e.g. layer_name is "layer1.0.relu2" """ obj_name, b_idx, act_name = layer_name.split(".") b_idx = int(b_idx) block = getattr(model, obj_name)[b_idx] return block
a4ae6c65df336b3dd36b53e9dd348a76b4a47b89
3,599,020
def compute_rolling_mean(df, window=30): """Return rolling mean of given values, using specified window size.""" df['SMA_{}'.format(str(window))] = df['Price'].rolling(window=window, center=False).mean() return df
36048112a720e0bdd66d2dfeeac6fb5cab62fa46
3,599,021
def fix_link_header(headers): """Replace the GitLab URL in the Link header.""" if 'Link' in headers: headers['Link'] = headers['Link'].replace( app.config['GITLAB_URL'], app.config['HOST_NAME'] ) return headers
d11d1cde6a474084a208d82d31f68d3b0b3eb44b
3,599,022
def insert(linked_list, value): """Metoda insert() vlozi na konec seznamu linked_list (za prvek last) novy uzel s hodnotou value. Vraci nove vlozeny objekt. """ n = Node() n.value = value n.prev = linked_list.last if linked_list.first is None: linked_list.first = n else: ...
82da5a2180e83d6dd66e0125ecde456bb53e6aaa
3,599,024
import torch def compute_loss(leo, metadata, train_stats, transformers, mode="meta_train"): """ Performs meta optimization across tasks returns the meta validation loss across tasks Args: metadata(dict): dictionary containing training data train_stats(ob...
ef299d9c4de41c9c97bea37f2606418e0aaeacec
3,599,025
def GetAcceleratorFlag(): """Gets the --accelerator flag.""" help_text = """\ Manage the configuration of the type and number of accelerator cards attached. *count*::: The number of pieces of the accelerator to attach to the allocation. *type*::: The specific type (e.g. nvidia-tesla-k80 for nVidia Tesla K80) of a...
b501f4fc87dea568575494a246cbc9f6f5ba940c
3,599,026
def _format_A_constraints(A, n_x, sparse_lhs=False): """Format the left hand side of the constraints to a 2D array Parameters ---------- A : 2D array 2D array such that ``A @ x`` gives the values of the upper-bound (in)equality constraints at ``x``. n_x : int The number of v...
0f5f6ce6163fde35254d9bfdb6a8f3ccad7914b8
3,599,027
def argsort(x, topn=None, reverse=False): """Get indices of the `topn` smallest elements in array `x`. Parameters ---------- x : array_like Array to sort. topn : int, optional Number of indices of the smallest(greatest) elements to be returned if given, otherwise - indices o...
6fcd896d3bbf296f818e2dcd993f75583ba880de
3,599,028
def preprocess_image(image_path: str) -> np.ndarray: """ Pre-processing steps: * Load the input image in grayscale mode (1 channel), * resize it to 224x224 pixels for the VGG19 CNN model, * transform it to an array format, * normalise the pixel intensities. :param image_path:...
2b674415e6b096381a3b3c918be46f6a86545de7
3,599,029
from typing import Sequence def is_planar_face(face: Sequence[Vec3], abs_tol=1e-9) -> bool: """ Returns ``True`` if sequence of vectors is a planar face. Args: face: sequence of :class:`~ezdxf.math.Vec3` objects abs_tol: tolerance for normals check """ if len(face) < 3: ret...
a50dcf37bec0e1c8a7a210195676ef5bdf6aff21
3,599,030
def is_campaign_config_file(file_name): """ Check if the given file is a CampaignConfig :param file_name: string :param file_name: File to check :rtype: boolean :return: If the file is a campaign config or not """ status = False try: # MUST BE xml file if file_nam...
57c9314af84ea1835fb16db54ce53d9997541254
3,599,032
def dice_coefficient(prediction, ground_truth, smooth=1.0): """ Function to calculate the dice coefficient. :param prediction: the logits (before softmax) :param ground_truth: the segmentation ground truth :param smooth: Smoothing coefficient. :return: the dice coefficient. """ y_true_f...
629d083edaa386bb6527ed498c5f4f76cd8efaa7
3,599,033
def bilinear_interpolate(data, x, y, nan_boundaries=False): """ Author: Michael Denbina (source: Kapok library) Function to perform bilinear interpolation on the input array data, at the image coordinates given by input arguments x and y. Arguments data (array): 2D array containing raster ...
5a059a31d135c3947894aa80d3b8c3d097ae5337
3,599,034
def get_data(col='close'): """ Returns a 3 x n_step array """ msft = pd.read_csv('data/msft.csv', usecols=[col]) aapl = pd.read_csv('data/aapl.csv', usecols=[col]) ibm = pd.read_csv('data/ibm.csv', usecols=[col]) # recent price are at top; reverse it return np.array([msft[col].values[::-1], ...
7bc9d759b2037cdb45db8da619d8cfab05f7ec0f
3,599,035
def GetCommentsForParams(func): """Gets the comments for the params. Args: func: The function. param: The parameter. Returns: a (string, dict) pair. The string is the comments minus the param parts. The dict is a dict of param names to comments. """ collecting_key = None param_comments = {}...
c81cc9ff3b8fb6da57c257d7a8b536cafa22bad2
3,599,036
def FindClientNode(mothership): """Search the mothership for the client node.""" nodes = mothership.Nodes() assert len(nodes) == 2 if nodes[0].IsAppNode(): return nodes[0] else: assert nodes[1].IsAppNode() return nodes[1]
06ac3bcde5571ca425d47885ad5839f2aa32ca0d
3,599,037
def index_max_maxunpooling(prev_indexes,X,pool_size,stride): """Function that return the indexes of maximum values of maxpooling operation. Args: prev_indexes: Python list with tuples of indexes in the form (batch, frame, height, width, channels). X: Input of the max...
80f0c1ad85a97c576608912af3d46c6a1300a654
3,599,038
import textwrap def to_flatimage(pathfile, to="(-3,0,0)", width=8, height=8, name="temp"): """ Adds a flat image to the canvas. """ text = rf""" \node[canvas is xy plane at z=0] ({name}) at {to}{{ \includegraphics[width={width}cm,height={height}cm]{{{pathfile}}} }}; """...
61906516d85ba3311506067ad4ec81b32786f1b9
3,599,039
def CalculateMSE(xs_, mu): """ 计算均方误差 xs_: 所有样本均值 mu: 总体均值 """ return sum([(x - mu) ** 2 for x in xs_]) / len(xs_)
45e90b003e05d54fdfa13c82b1f1332d0e68082a
3,599,040
def load_hw10_starfit(): """ Set up data for fitting """ hw10 = rd.load_hw10(as_number=True) columns_to_use = np.array([isinstance(col, (int, np.integer)) for col in hw10.columns]) hw10logN = np.log10(hw10[hw10.columns[columns_to_use]]) return hw10, hw10logN
ff7387a8d1030f477469b7f335fa8d8ef9a07786
3,599,041
def is_init_authorised(context, bushfire_id): """ Usage:: {% if is_init_authorised %} ... {% endif %} or {% for bushfire in object_list %} {% is_init_authorised bushfire.id as init_authorised %} <tr> <td>{{ bushfire.id }}</td> ...
377a4bfeffd8dc04751ad6264b3348845f638e69
3,599,042
def is_email(email: str): """Returns wether the given string is an email address or not""" return EMAIL_REGEX.fullmatch(str(email)) is not None
a0a90a5a04f065058cee18f9479553aca2eec2e7
3,599,043
def gaussian_noise(images, bounds): """ adding gaussian noise to images. Different noise for each image. :param images: RGB matrix of two input images. Nois on mask is useless :param bounds: min and max of the gaussian noise :return: RGB matrix with gaussian Noise """ noisy_images = images.c...
8c6128534caa7ebaa8f817d0b8c70e72be19c2cd
3,599,044
def voronoi(frame, data, f, parameters=None, call_num=None): """ Voronoi draws the voronoi network that surrounds each particle Notes ----- The voronoi cells must previously have been calculated in postprocessing. See "voronoi" in postprocessing. Parameters ---------- cmap_t...
85cf9db42a82de3abae48131fb9df41151dde40b
3,599,045
def _get_primary_status(row): """Get package primary status.""" try: return row.find('div', {'class': 'pack_h3'}).string except AttributeError: return None
1df5b66e9e16e17b8c5f3fc019a587a4320cf6d0
3,599,047
def calc_n_g(df_schedule, week): """Calculate list of games i.e. Ng Each row has home_id, away_id, home_total_points, away_total_points :param df_schedule: data frame with each matchup :param week: current matchup period id :return: list of games with team ids and scores for home/away """ df_scores = ( ...
1029840d28617d5de60fa499e8e6a9ae40b4ddea
3,599,048
def is_string(s): """ Portable function to answer whether a variable is a string. Parameters ---------- s : object An object that is potentially a string Returns ------- isstring : bool A boolean decision on whether ``s`` is a string or not """ return isinstance...
ed59a1b3a80f6695c971c49ff3b7936aa048523f
3,599,049
def flatten_nested_list(list_in, drop_dupes=False): """Function to take a nested list and flatten into a 1d list.""" is_nested=True if type(list_in[0]) ==type(['v','d']) else False if is_nested is True: list_out=[]; if drop_dupes is True: for list_i in list_in: ...
d3580ea22458ef794bdef280cec650f1521fda04
3,599,051
def computeIchimokuCloud(candleSet): """ compute current values of Ichimoku Cloud lines """ conversionLine = (max([x["High"] for i,x in candleSet.iloc[-9:].iterrows()]) + min([y["Low"] for i,y in candleSet.iloc[-9:].iterrows()]))/2 baseLine = (max([x["High"] for i,x in candleSet.iloc[-26:].iterrows(...
781df8f002a7fc3f5f7b3dd854a123bb3f21c142
3,599,052
def update_subfield_snippet(context, code, subfield, value): """ Replaces a new value in a subfield snippet for a MARC field :param context: Context :param code: Field code :param subfield: MARC subfield, if numeric...
67ddf74faef5295028d27725534e05c888fba36a
3,599,053
from typing import Sequence from typing import Optional def setup_minimal_example( num_companies: int = _num_companies, num_markets: int = _num_markets, market_company_connections: np.ndarray = _market_company_connections, market_capacities: np.ndarray = _market_capacities, step_sizes: Sequence[fl...
712f5b811767e37979670be001f4caf39aa18d04
3,599,054
import json def follow(request, username, template_name='relationships/relationship_add_confirm.html', success_template_name='relationships/relationship_add_success.html', mimetype='text/html'): """ Allows a user to follow another user. Templates: ``relationships...
a2baf9c1aebdda46c4879db66d3e269d13fa3c18
3,599,055
from typing import Any from typing import Optional def _strat_has_unitary_from_has_unitary(val: Any) -> Optional[bool]: """Attempts to infer a value's unitary-ness via its _has_unitary_ method.""" if hasattr(val, '_has_unitary_'): result = val._has_unitary_() if result is NotImplemented: ...
96965cfec5f5c3c29ea641c95f20a2d4b1f3b859
3,599,056
def write_keyvalue_toxlsx(worksheet, row, key, value): """Write a dictionary to excel sheet.""" if type(value).__name__ == 'dict': worksheet.write(row, 0, key) row += 1 for dictkey, dictvalue in value.items(): row = write_keyvalue_toxlsx(worksheet, row, dictkey, dictvalue) ...
c89111a35b182824664624c9b41358a15351f91d
3,599,058
def swap_index_values(series: pd.Series) -> pd.Series: """Swap index and values in series. Examples: >>> s = pd.Series({'a': 1, 'b': 2}) >>> s.name = 'val' >>> s.index.name = 'char' >>> swap_index_values(s) val 1 a 2 b Name: char, dtype: obj...
3849fd2c21bdd0782391f0030947fdcf3fca2251
3,599,059
def BFS(map_dict, start, end, verbose): """ BFS algorithm to find the shortest path between the start and end points on the map, following the map given by map_dict If an invalid end location is given then it will return the longest possible path and its length. Returns the length of t...
f6770fe8cd5f6c4ebffce2a78992c76cfbb5bd31
3,599,060
from config import get_config import socket def get_hostname(config=None): """ Get the canonical host name this agent should identify as. This is the authoritative source of the host name for the agent. Tries, in order: * agent config (config.cfg, "hostname:") * 'hostname -f' (on unix) ...
5b5eff2b65b382689586e0ed6b5e71594054f9e9
3,599,061
def ir_swap_price( pay_leg_coupon_rates, receive_leg_coupon_rates, pay_leg_notional, receive_leg_notional, pay_leg_daycount_fractions, receive_leg_daycount_fractions, pay_leg_discount_factors, receive_leg_discount_factors, dtype=None, name=None): """Computes prices of a batch o...
7c19f71c061992f17bf344ed69eaa45e01a81623
3,599,063
def construct_timeseries_cds(report): """Construct two standardized Bokeh CDS for the timeseries and scatter plot functions. One with timeseries data for all observations, aggregates, and forecasts in the report, and the other with associated metadata sharing a common `pair_index` key. Parameters ...
adeb72708a6c68c8f97a5e9006c5ff9f97029b58
3,599,064
from functools import reduce def pipeline(source, functions): """Apply an array of functions to a source iterable""" return reduce(lambda x, y: y(x), functions, source)
c79977ce46a6be15fc428530d94f8c4878a68ede
3,599,065
def compare_proj4(original, new): """compare proj4 strings""" def to_dict(proj4_str): """convert to dictionary""" proj4_split = proj4_str.strip().split(" ") proj4_dict = dict() for elem in proj4_split: elem_split = elem.strip().split("=") try: ...
c7fba2e9f9257414e681d5aa28d55bada02ef61e
3,599,066
import requests def cube_instance(connection, cube_id, body={}, offset=0, limit=1000, verbose=False): """ Create a new instance of a specific cube. This in-memory instance can be used by other requests. Args: connection: MicroStrategy REST API connection object. cube_id (str): Unique ID o...
512962af29851c87bd278088aa69d0b9db967707
3,599,067
from pathlib import Path def read_commit(wkspc_dir) -> str: """ read and return the value in the commit file :param wkspc_dir: jenkins workspace dicrectory :return: commit tag value """ commit = 'false' # confirm branch directory exists vol_dir = '/'.join(['/volumes', PurePath(wk...
f547fd7619241549060f0156012e5ca89ceb42e0
3,599,069