content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _init_basemap(border_colour): """Initializes basemap. :param border_colour: Colour (in any format accepted by matplotlib) of political borders. :return: narr_row_limits: length-2 numpy array of (min, max) NARR rows to plot. :return: narr_column_limits: length-2 numpy array of (min, ...
aeec84f7973972abd93bc344fc7f2028d216c4b5
25,800
def makeFigure(): """Get a list of the axis objects and create a figure""" ax, f = getSetup((9, 12), (5, 2)) cellTarget = "Treg" epitopesDF = pd.DataFrame(columns={"Classifier", "Epitope"}) posCorrs1, negCorrs = CITE_RIDGE(ax[4], cellTarget) for x in posCorrs1: epitopesDF = epitopesDF.a...
e0c4cf34630171e489f195d14a3d29f8d0fa10e1
25,801
def get_data_frame(binary_tables, all_inputs): """ Gets a data frame that needs QM reduction and further logic. Also removes the all_inputs from the DataFrame. :param binary_tables: contains a tables with True and False outputs. :param all_inputs: columns :return: Pandas DataFrame. """ ...
e40a914f19242ee82cd0c3e0f706f97f6c71e9fa
25,802
def compute_shift_delay_samples(params_delays,vector_seconds_ref,freq_sample,seconds_frame,pair_st_so,data_type=0,\ front_time=None,cache_rates=[],cache_delays=[]): """ Compute number of samples to shift signal (always positive since reference station is closest to source). ...
5cf35bd1b2187d107f8fd5809dd7db9822d5c110
25,803
from typing import Dict from typing import Tuple def classification_metrics_function( logits: jnp.ndarray, batch: base_model.Batch, target_is_onehot: bool = False, metrics: base_model.MetricNormalizerFnDict = _CLASSIFICATION_METRICS, ) -> Dict[str, Tuple[float, int]]: """Calculates metrics for the c...
defcde9e70822721a866a5af62c472386251b0e8
25,804
import _io def create_validator_delegation_withdrawal( params: DeployParameters, amount: int, public_key_of_delegator: PublicKey, public_key_of_validator: PublicKey, path_to_wasm: str ) -> Deploy: """Returns a standard withdraw delegation deploy. :param params: Standard parameters used whe...
d4395928cdc32da03775f0944b4d3d2ef802e534
25,805
def get_host_finding_vulnerabilities_hr(vulnerabilities): """ Prepare human readable json for "risksense-get-host-finding-detail" command. Including vulnerabilities details. :param vulnerabilities: vulnerabilities details from response. :return: list of dict """ vulnerabilities_list = [{ ...
8f0689441f2fef41bbd5da91c802dfb8baa2b979
25,806
from typing import Optional from typing import List import copy def train_on_file_dataset( train_dataset_path: str, valid_dataset_path: Optional[str], feature_ids: List[str], label_id: str, weight_id: Optional[str], model_id: str, learner: str, task: Optional[TaskType] = Task.CLASSIFIC...
16e692adc9e72d06678680e13ef50636e6f17450
25,807
def db_fixture(): """Get app context for tests :return: """ return db
4c780071e5a092870a676685aede295365de6ad9
25,808
def login_required(route_function): """ 这个函数看起来非常绕 是实现装饰器的一般套路 """ def f(request): u = current_user(request) if u is None: log('非登录用户') return redirect('/login') else: return route_function(request) return f
44cff97ad32257e4dc4cfe5d7e3b79ea643986ef
25,809
def cuTypeConverter(cuType): """ Converts calendar user types to OD type names """ return "recordType", CalendarDirectoryRecordMixin.fromCUType(cuType)
a4afcfe912fc1d853ee841ed215c099c352ace0c
25,810
def add_viz_sphere( sim: habitat_sim.Simulator, radius: float, pos: mn.Vector3 ) -> habitat_sim.physics.ManagedRigidObject: """ Add a visualization-only sphere to the world at a global position. Returns the new object. """ obj_attr_mgr = sim.get_object_template_manager() sphere_template = ob...
cc8f47c8b32ad2f4bf7c0e159d19dac048546aea
25,811
import torch def get_normalize_layer(dataset: str) -> torch.nn.Module: """Return the dataset's normalization layer""" if dataset == "imagenet": return NormalizeLayer(_IMAGENET_MEAN, _IMAGENET_STDDEV) elif dataset == "cifar10": return NormalizeLayer(_CIFAR10_MEAN, _CIFAR10_STDDEV)
52d5d0a744e0e10db1f54d83dfb9b7a8b779c49d
25,812
def summer_69(arr): """ Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers. :param arr: list of integers :return: int """ get_result = 0 ...
d155a739afe131025b654002bebb51b25325bd1e
25,813
def get_notebook_title(nb_json, default=None): """Determine a suitable title for the notebook. This will return the text of the first header cell. If that does not exist, it will return the default. """ cells = nb_json['cells'] for cell in cells: if cell['cell_type'] == 'heading': ...
4a20fe9890371ab107d0194e791c6faf9901d714
25,814
import os import sys def get_local_server_dir(subdir = None): """ Get the directory at the root of the venv. :param subdir: :return: """ figures_dir = os.path.abspath(os.path.join(sys.executable, '..', '..', '..')) if subdir is not None: figures_dir = os.path.join(figures_dir, subd...
1e540157786cd0ea2ffa9bd1fabdb3d48bcb37f5
25,815
import torch def extract_sequence(sent, annotations, sources, label_indices): """ Convert the annotations of a spacy document into an array of observations of shape (nb_sources, nb_bio_labels) """ sequence = torch.zeros([len(sent), len...
1d988fe82b19d583438b8bf1ceb00671de566fca
25,816
def is_valid_password_1(password): """ >>> is_valid_password_1("111111") True >>> is_valid_password_1("223450") False >>> is_valid_password_1("123789") False """ has_double = any(password[c] == password[c+1] for c in range(len(password)-1)) is_ascending = all(password[c] <= passw...
8544e15a7d50c025073a3ac51b9f5b8809341d2e
25,817
def mean(x, axis=None, keepdims=False): """Mean of a tensor, alongside the specified axis. Parameters ---------- x: A tensor or variable. axis: A list of integer. Axes to compute the mean. keepdims: A boolean, whether to keep the dimensions or not. If keepdims is False, the rank of the tensor is reduce...
9f8d1b98a5f1dd37a91493fb822437885e04468e
25,818
def frame_pass_valid_sample_criteria(frame, image_type): """Returns whether a frame matches type criteria""" return frame_image_type_match(frame, image_type)
cf5b51dfe63e7667a14b41c9793a66aa065663e8
25,819
def embed(tokenizer, text): """ Embeds a text sequence using BERT tokenizer :param text: text to be embedded :return: embedded sequence (text -> tokens -> ids) """ return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(text))
453d411d9c460dfc28cb54c7a6a807290905bed3
25,820
def exponent_fmt(x, pos): """ The two args are the value and tick position. """ return '{0:.0f}'.format(10 ** x)
46e2104e966ec452fb510a411b1907090d55daf3
25,821
def _unpack(arr, extent, order='C'): """ This is a helper method that handles the initial unpacking of a data array. ParaView and VTK use Fortran packing so this is convert data saved in C packing to Fortran packing. """ n1,n2,n3 = extent[0],extent[1],extent[2] if order == 'C': arr =...
2d7054da8ffc5773bfd151973bf3b06c84c2e735
25,822
import torch def unzip(list): """unzip the tensor tuple list Args: list: contains tuple of segemented tensors """ T, loss = zip(*list) T = torch.cat(T) mean_loss = torch.cat(loss).mean() return T, mean_loss
5ed656aa8221c7bc5bd8a43b80fe0efd07d4df24
25,823
def ergs_to_lsun(luminosity): """ From luminostiy in erg/s to Lsun """ lum = u.Quantity(luminosity, u.erg / u.s) return lum.to(u.L_sun)
fa7e572f5509b0408520e15433141e6da88daae1
25,824
def decode(code, P): """ Decode an RNS representation array into decimal number :param P: list of moduli in order from bigger to smaller [pn, .., p2, p1, p0] >>> decode(code=[5, 3, 1], P=[7,6,5]) 201 """ lcms = np.fromiter(accumulate(P[::-1], np.lcm), int)[::-1] n = code[-1] % P[-1] ...
422128ef0d0da62b404b6e8c0b927221505ead17
25,825
def is_collection(obj): """ Check if a object is iterable. :return: Result of check. :rtype: bool """ return hasattr(obj, '__iter__') and not isinstance(obj, str)
70fa0262ea7bf91a202aade2a1151d467001071e
25,826
import hashlib def file_md5(fpath): """Return the MD5 digest for the given file""" with open(fpath,'rb') as f: m = hashlib.md5() while True: s = f.read(4096) if not s: break m.update(s) return m.hexdigest()
40b355b9a628d286bf86b5199fd7e2a8bea354de
25,827
import os def strip_path(full_path): """Returns the filename part of full_path with any directory path removed. :meta private: """ return os.path.basename(full_path)
327736cb77d9aa409a5790efd51895318d970382
25,828
import os def update(): """ Updates the Database Returns ------- None. """ os.system("git submodule update --recursive --remote") return None # %% Load USA data
3c9b7817c6512fd7fe018d3642fe6e9106d85b7c
25,829
def move(column, player): """Apply player move to the given column""" index = _index_of(column, None) if index < 0: print('Entire column is occupied') return False column[index] = player return True
9c728c4c764154390478e27408f5bc25acaacf1d
25,830
def calculate_costs(points, centric_point): """ Returns the accumulated costs of all point in `points` from the centric_point """ if len(points) == 1: return points[0].hyp() _part = (points - centric_point)**2 _fin = [] for point in _part: _fin.append(point.hyp()) return (np.array(_fin)).sum()
c35e00dabb3e85d5136afc3f5696a73aad607470
25,831
def formatUs(time): """Format human readable time (input in us).""" if time < 1000: return f"{time:.2f} us" time = time / 1000 if time < 1000: return f"{time:.2f} ms" time = time / 1000 return f"{time:.2f} s"
7546db60e3977e07dbbbad0a3ab767865840c2e3
25,832
from typing import Dict from typing import List from typing import Union def parse_annotations(ann_filepath: str) -> Dict[int, List[Label]]: """Parse annotation file into List of Scalabel Label type per frame.""" outputs = defaultdict(list) for line in load_file_as_list(ann_filepath): gt = line.st...
1ef42147fa4cb44b1ebd37f861444e502d0ea9b9
25,833
import os def bel_graph_loader(from_dir: str) -> BELGraph: """Obtains a combined BELGraph from all the BEL documents in one folder. :param from_dir: The folder with the BEL documents. :return: A corresponding BEL Graph. """ logger.info("Loading BEL Graph.") files = [ os.path.join(from...
f7369c3a3abb9ab1d0d43411ca92e3edc601b8e4
25,834
from typing import Dict from typing import List from typing import Optional from typing import Union from typing import Any def apply(lang1: Dict[List[str], float], lang2: Dict[List[str], float], parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> float: """ Calculates the EMD distance between ...
c87d171018a6eddef6572a0bd3639952499fca44
25,835
import collections def reInpainting(image, ground_truth, teethColor): """ if pixel has pink color (marked for teeth) and not in range of teeth => fill by teethColor """ isTeeth, isNotTeeth = 0, 0 threshold = calculateThreshhold(image, teethColor) # print(f"Threshold: {threshold}") for ...
c5f8a71c9c1bbf6e3b4c03b477901b9669d9f72c
25,836
def data_for_cylinder_along_z(center_x, center_y, radius, height_z): """ Method for creating grid for cylinder drawing. Cylinder will be created along Z axis :param center_x: Euclidean 3 dimensional center of drawing on X axis :param center_y: Euclidean 3 dimensional center of drawing on Y axis :par...
2582860582564e7b8a4e9ba6e89d0740d44fa069
25,837
def _configure_learning_rate(num_samples_per_epoch, global_step): """Configures the learning rate. Args: num_samples_per_epoch: The number of samples in each epoch of training. global_step: The global_step tensor. Returns: A `Tensor` representing the learning rate. Raises: ValueError: if ""...
c1395b7521b6a55e8a77c50b47dca920f8c27dc0
25,838
def cpm(adata: ad.AnnData) -> ad.AnnData: """Normalize data to counts per million.""" _cpm(adata) return adata
ec0a2a0ed61965e8c78ebf59fab569f2a4954790
25,839
def argon2_key(encryption_password, salt): """ Generates an encryption key from a password using the Argon2id KDF. """ return argon2.low_level.hash_secret_raw(encryption_password.encode('utf-8'), salt, time_cost=RFC_9106_LOW_MEMORY.time_cost, memory_cost=RFC_9106_LOW_MEMORY.memory_cost, ...
eaf5a0f3ca0ee12e22b0ddb9594dcd1734ef91e8
25,840
def print_policy_analysis(policies, game, verbose=False): """Function printing policy diversity within game's known policies. Warning : only works with deterministic policies. Args: policies: List of list of policies (One list per game player) game: OpenSpiel game object. verbose: Whether to print po...
51379d78dc3dd924da41dc00e8d6236d72b68f3c
25,841
def model_fn(is_training=True, **params): """ Create base model with MobileNetV2 + Dense layer (n class). Wrap up with CustomModel process. Args: is_training (bool): if it is going to be trained or not params: keyword arguments (parameters dictionary) """ baseModel = MobileNetV2...
2a14d803c5d521f453ce30a641d8736364e64ac0
25,842
import argparse def make_arg_parser(): """ Create the argument parser. """ parser = argparse.ArgumentParser(description="Scrap WHOIS data.") parser.add_argument("--config", help="uwhoisd configuration") parser.add_argument( "--log", default="warning", choices=["critical...
f9c94b23589ed77fc3db950549d21f371e156eb1
25,843
def roundToElement(dateTime, unit): """ Returns a copy of dateTime rounded to given unit :param datetime.datetime: date time object :param DtUnit unit: unit :return: datetime.datetime """ year = dateTime.year month = dateTime.month day = dateTime.day hour = dateTime.hour minute ...
226f532e9e729d155d14135e4025015e8b00b2e0
25,844
def tuple_factory(colnames, rows): """ Returns each row as a tuple Example:: >>> from cassandra.query import tuple_factory >>> session = cluster.connect('mykeyspace') >>> session.row_factory = tuple_factory >>> rows = session.execute("SELECT name, age FROM users LIMIT 1") ...
5526647a414b397ac9d71c35173718c01385a03b
25,845
def is_error(splunk_record_key): """Return True if the given string is an error key. :param splunk_record key: The string to check :type splunk_record_key: str :rtype: bool """ return splunk_record_key == 'error'
26371ec9c5941fbf07a84c6904ea739b02eb97ba
25,846
def parse_network_info(net_bond, response_json): """ Build the network info """ out_dict = {} ip_list = [] node_count = 0 # Build individual node information for node_result in response_json['result']['nodes']: for node in response_json['result']['nodes']: if node['no...
2c83aa72d6ee0195a42339546d1fded84f85680f
25,847
async def create_or_update(hub, ctx, name, resource_group, **kwargs): """ .. versionadded:: 1.0.0 Create or update a network security group. :param name: The name of the network security group to create. :param resource_group: The resource group name assigned to the network security group...
251ee69d6077d2fd4ffda8c9da53b8ae84c9a696
25,848
def download_media_suite(req, domain, app_id): """ See Application.create_media_suite """ return HttpResponse( req.app.create_media_suite() )
fe0f5e0b5598b2368fd756a7f6bee89035813317
25,849
def non_numeric(string: str) -> str: """ Removes all numbers from the string """ return ''.join(letter for letter in string if not letter.isdigit())
fe16297c4cf1b144fb583986a5c01ea02920787e
25,850
import re def prepare_xs(path, numbergroup=1): """Prepare the needed representation of cross-section data Paramteres: ----------- path : str filename of cross-section data numbergroup : int number of energies neutron multigroup Returns: -------- energies : iter...
5f6ffd4e7954984d43ebc00c108d268797831256
25,851
def shiftField(field, dz): """Shifts the z-coordinate of the field by dz""" for f in field: if f.ID == 'Polar Data': f.set_RPhiZ(f.r, f.phi, f.z + dz) elif f.ID == 'Cartesian Data': f.set_XYZ(f.x, f.y, f.z + dz) return field
c3c592356dc21688049a94291d075879a12012ee
25,852
def pair_equality(dataframe, column_1, column_2, new_feature_name): """ Adds a new binary feature to an existing dataframe which, for every row, is 1 if and only if that row has equal values in two given columns. :param dataframe: Dataframe to add feature to :param column_1: Name of...
d82a02c49399351aa62b712664bb9500390ebf81
25,853
import networkx import itertools def compute_diagram(PhenosObj, FnameJson=None, FnameImage=None, Silent=False): """ todo: finish code todo: add unit tests computes the phenotype diagram from the phenotypes object obtained from :ref:`phenotypes_compute_json`. save the diagram as json data with *Fn...
f2cfa298807f7969d93dafd76d403d4d8bddcb11
25,854
def identity_block(input_tensor, kernel_size, filters, stage, block): """The identity block is the block that has no conv layer at shortcut. # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the fil...
3d33a0bec933697eae642199fe7b24e90e45e15b
25,855
from typing import Optional def find_linux_kernel_memory( pml4: PageTable, mem: Memory, mem_range: Interval ) -> Optional[MappedMemory]: """ Return virtual and physical memory """ # TODO: skip first level in page tables to speed up the search # i = get_index(mem_range.begin, 0) # pdt = pag...
6b08bfb2c8a0f98ef250a8268a076b72496bd89f
25,856
def cnn_encoder(inputs, is_train=True, reuse=False, name='cnnftxt', return_h3=False): """ 64x64 --> t_dim, for text-image mapping """ w_init = tf.random_normal_initializer(stddev=0.02) gamma_init = tf.random_normal_initializer(1., 0.02) df_dim = 64 with tf.variable_scope(name, reuse=reuse): ...
9c66cd9a2b9589da89572779dc01117b7f349fee
25,857
def cmp_id(cls1, cls2, idx1, idx2): """Compare same particles between two clusters and output numbers Parameters ---------- cls1,cls2: Cluster object idx1,idx2: Indices of detected particles in the clusters. Output ------ The number of same particles. """ partId1 = cls1.gas_id[...
b3ebf4a3c98da18a84545caff446e0d1732208a0
25,858
def get_clinical_cup(): """ Returns tuple with clinical cup description """ return ("8", "2", "M", "01", 25)
fac133ea74fbe30b50e551fdd7cdce349cc02a3a
25,859
def to_utm_bbox(bbox: BBox) -> BBox: """Transform bbox into UTM CRS :param bbox: bounding box :return: bounding box in UTM CRS """ if CRS.is_utm(bbox.crs): return bbox lng, lat = bbox.middle utm_crs = get_utm_crs(lng, lat, source_crs=bbox.crs) return bbox.transform(utm_crs)
80e67ce402ba1551a5282f93fc629be78255e96a
25,860
def define_actions(action): """ Define the list of actions we are using. Args action: String with the passed action. Could be "all" Returns actions: List of strings of actions Raises ValueError if the action is not included in H3.6M """ actions = ["walking", "wiping", "lifting", "co-exis...
45bfbd20971a04f566feeed0de509b21be83963b
25,861
def gen_order_history_sequence(uid, history_grouped, has_history_flag): """ 用户订单历史结果构成的序列 """ # 311 天的操作记录 sequence = ['0'] * 311 if has_history_flag == 0: return sequence df = history_grouped[uid] for i in df['days_from_now']: sequence[i] = str(df[df['days_from_now'] == i].shap...
9f9e93549ea4c35971f87957b74e44e258d79d49
25,862
def _get_plugin_type_ids(): """Get the ID of each of Pulp's plugins. Each Pulp plugin adds one (or more?) content unit type to Pulp. Each of these content unit types is identified by a certain unique identifier. For example, the `Python type`_ has an ID of ``python_package``. :returns: A set of pl...
0c31a239980a2427f1fb115d890eea9d92edf396
25,863
def scale_48vcurrent(value, reverse=False, pcb_version=0): """ Given a raw register value and the PCB version number, find out what scale and offset are needed, convert the raw value to Amps (if reverse=False), or convert a value in Amps to raw (if reverse=True). For now, raw values are hundredths of a...
562a9354f1648203ba9854f2404e00365e12f67f
25,864
import pickle def get_graph(graph_name): """Return graph, input can be string with the file name (reuse previous created graph), or a variable containing the graph itself""" # open file if its a string, or just pass the graph variable if '.p' not in graph_name: graph_name = add_extension(gra...
0efe5cb90b6f8bf1fc59853704cf7e07038fb8fb
25,865
import traceback import sys def max_function(context, nodeset, string): """ The dyn:max function calculates the maximum value for the nodes passed as the first argument, where the value of each node is calculated dynamically using an XPath expression passed as a string as the second argument. htt...
4a10eec7d82417d7950116a4f4d4313d7c81d27e
25,866
def get_transfer_encodings(): """Return a list of supported content-transfer-encoding values.""" return transfer_decoding_wrappers.keys()
c42dfd886b1080e6a49fe4dabc2616967855a7f0
25,867
def is_name_valid(name: str, rules: list) -> bool: """ Determine whether a name corresponds to a named rule. """ for rule in rules: if rule.name == name: return True return False
41e9f88d86a078ca6386f1d0d6b7123233c819b9
25,868
def fig2data(fig, imsize): """ :param fig: Matplotlib figure :param imsize: :return: """ canvas = FigureCanvas(fig) ax = fig.gca() # ax.text(0.0, 0.0, "Test", fontsize=45) # ax.axis("off") canvas.draw() image = np.fromstring(canvas.tostring_rgb(), dtype="uint8") width,...
5a8b7bf34d6aa3849f20b5ca140c572c5cad0e57
25,869
def draw_agent_trail(img, trail_data, rgb, vision): """ draw agent trail on the device with given color. Args: img : cv2 read image of device. trail_data : data of trail data of the agent rgb : (r,g,b) tuple of rgb color Returns: img : updated image ...
9524cb10cbe1ed7dceb8714c7ace443be64e8767
25,870
def get_total_received_items(scorecard): """ Gets the total number of received shipments in the period (based on Purchase Receipts)""" supplier = frappe.get_doc('Supplier', scorecard.supplier) # Look up all PO Items with delivery dates between our dates data = frappe.db.sql(""" SELECT SUM(pr_item.received_q...
856e5b42a1b572a6fa7150b789eb8754a045677d
25,871
def generate_default_filters(dispatcher, *args, **kwargs): """ Prepare filters :param dispatcher: for states :param args: :param kwargs: :return: """ filters_list = [] for name, filter_data in kwargs.items(): if filter_data is None: # skip not setted filter name...
e307b9933280bfc91ef25ac306586c3cc6cf8c94
25,872
def linear_map(x, init_mat_params=None, init_b=None, mat_func=get_LU_map, trainable_A=True, trainable_b=True, irange=1e-10, name='linear_map'): """Return the linearly transformed, y^t = x^t * mat_func(mat_params) + b^t, log determinant of Jacobian and inverse map. Args: ...
1286fc8087288f94b1ef63388fc6c8636d061b2f
25,873
def isolated_70(): """ Real Name: b'Isolated 70' Original Eqn: b'INTEG ( isolation rate symptomatic 70+isolation rate asymptomatic 70-isolated recovery rate 70\\\\ -isolated critical case rate 70, init Isolated 70)' Units: b'person' Limits: (None, None) Type: component b'' """ retur...
b1185a6a03759830f7cfeaefae34389699e62c48
25,874
def db_retry(using=None, tries=None, delay=None, max_delay=None, backoff=1, jitter=0, logger=logging_logger): """Returns a retry decorator. :param using: database alias from settings.DATABASES. :param tries: the maximum number of attempts. -1 means infinite. None - get fr...
5727bb89f55a8cc68cea2a35ea256b79b6b852da
25,875
from typing import Collection def A000142(start: int = 0, limit: int = 20) -> Collection[int]: """Factorial numbers: n! = 1*2*3*4*...*n (order of symmetric group S_n, number of permutations of n letters). """ sequence = [] colors = [] x = [] for i in range(start, start + limit): se...
c0c709529bb7926369912ea195aec5fba17f7887
25,876
import idwgopt.idwgopt_default as idwgopt_default def default(nvars): """ Generate default problem structure for IDW-RBF Global Optimization. problem=idwgopt.default(n) generate a default problem structure for a an optimization with n variables. (C) 2019 by A. Bemporad. """ problem = idw...
6e865ffdab0b3913c793357b6cb2688a6cd4dc00
25,877
from point import Point from line import Segment from polygon import Polygon def convex_hull(*args): """ Returns a Polygon representing the convex hull of a set of 2D points. Notes: ====== This can only be performed on a set of non-symbolic points. Example: ======== >>> from ...
ee1c1fd65dfe849a36a6dfc8e86a4e1e2ee8ca69
25,878
from typing import Dict def find_namespaces(tree: ElementTree) -> Dict[str, str]: """ Finds the namespaces defined in the ElementTree of an XML document. It looks for namespaces defined in the root element of the XML document. To avoid namespaces being left out, they shall all be defined in the root e...
8b2a523c9d7152280fa609563e94eda4facebe4b
25,879
def filterStories(stories, triggerlist): """ Takes in a list of NewsStory instances. Returns: a list of only the stories for which a trigger in triggerlist fires. """ filteredStories = [] for story in stories: for trig in triggerlist: if trig.evaluate(story) and story not in...
1fcf2592e22c97cd13919dbfe5b8a4acde682761
25,880
def lcs(a, b): """ Compute the length of the longest common subsequence between two sequences. Time complexity: O(len(a) * len(b)) Space complexity: O(min(len(a), len(b))) """ # This is an adaptation of the standard LCS dynamic programming algorithm # tweaked for lower memory consumption. ...
0201e9efade98aece854e05d0910192251e5f63c
25,881
def save(config, filename="image.img", host=None): """Save the Image File to the disk""" cmd = DockerCommandBuilder(host=host).save(config.getImageName()).set_output(filename).build() return execute(cmd)
628dca6307b6a5d975e90e08649f20790bc8b639
25,882
from typing import Dict from typing import Any import sys def klass_from_obj_type(cm_json: Dict) -> Any: """Get reference to class (n.b. not an instance) given the value for a key 'obj_type' in the given json dict""" module_name, klass_path = cm_json['obj_type'].rsplit('.', 1) # @todo make this load from ...
daf9c4d8579d3da7383abdfc38c9af0d4161d302
25,883
def lines2bars(lines, is_date): """将CSV记录转换为Bar对象 header: date,open,high,low,close,money,volume,factor lines: 2022-02-10 10:06:00,16.87,16.89,16.87,16.88,4105065.000000,243200.000000,121.719130 """ if isinstance(lines, str): lines = [lines] def parse_date(x): return arrow.get(...
4d2049d08f885de3b999b1537a48c03088f45da3
25,884
import torch def pgd_linf_untargeted(model, X, y, epsilon=0.1, alpha=0.01, num_iter=20, randomize=False): """ Construct FGSM adversarial examples on the examples X""" if randomize: delta = torch.rand_like(X, requires_grad=True) delta.data = delta.data * 2 * epsilon - epsilon else: ...
b19091048d269853c6b55c4d96d5919c4efcfbe6
25,885
def cal_NB_pvalue (treatTotal,controlTotal,items): """calculate the pvalue in pos of chromosome. """ pvalue = 1 (treatCount,controlCount,pos)=items pvalue = negativeBinomail(treatCount,treatTotal,controlCount,controlTotal) return (pvalue,treatCount,controlCount,pos)
f68809ffb40949c2d4ca1486870ec421d48bbfb5
25,886
def handle_watches(connection, author): """Return an array of watches for the author.""" database = connection['test'] collection = database['watches'] watches = [] # this should not except for post in collection.find({"author" : ObjectId(author)}): watches.append(cleanup_watc...
bfb765e30d249fac30fdbf567006283be1808e6c
25,887
def new_mm(*args, figsize, **kwargs): """Wrapper for plt.subplots, using figsize in millimeters :rtype: figure, axes """ return plt.subplots(*args, figsize=(figsize[0] / 25.4, figsize[1] / 25.4), **kwargs)
7111f1fd8261d3367bff03fd36ed86cc26917fe8
25,888
def compute_center_of_mass(coordinates, masses): """ Given coordinates and masses, return center of mass coordinates. Also works to compute COM translational motion. Args: coordinates ({nparticle, ndim} ndarray): xyz (to compute COM) or velocities (COM velocity) masses ({nparticle,} arr...
d190c20930209e180524c07c8bf8fef9ab95734b
25,889
def chars_count(word: str): """ :param word: string to count the occurrences of a character symbol for. :return: a dictionary mapping each character found in word to the number of times it appears in it. """ res = dict() for c in word: res[c] = res.get(c, 0) + 1 return res
30c27b23c04909a65264247d068e9e2c695c6ecc
25,890
def do_expressiondelete(**kwargs): """ Worker to remove expression from engine proexpobj: expression object profileexplist: expression list object return 0 if expression deleted """ proexpobj = kwargs.get('proexpobj') profileexplist = kwargs.get('profileexplist') if profileexplist....
4d4f26aca34417026ac326d237f817b88afe525c
25,891
import csv def read_csv_as_nested_dict(filename, keyfield, separator, quote): """ Inputs: filename - name of CSV file keyfield - field to use as key for rows separator - character that separates fields quote - character used to optionally quote fields Output: Returns a ...
b86a19e531ac2d0c815839714ee93fbc618e911d
25,892
def msgpackb(lis): """list -> bytes""" return create_msgpack(lis)
4e2667ff32c58be09620cd8360ff0207406a7871
25,893
from azureml._execution import _commands from azureml.core.runconfig import RunConfiguration from azureml._project.project import Project def prepare_compute_target(experiment, source_directory, run_config): """Prepare the compute target. Installs all the required packages for an experiment run based on run_...
d6a7f2f45483c2e0a42bcb03407791ca781318ab
25,894
def streaming_ndarray_agg( in_stream, ndarray_cols, aggregate_cols, value_cols=[], sample_cols=[], chunksize=30000, add_count_col=False, divide_by_count=False, ): """ Takes in_stream of dataframes Applies ndarray-aware groupby-sum or groupby-mean: treats ndarray_cols as ...
a47a3f82444dc1ef7d5eb5f63d7dd77c862fc605
25,895
from typing import List def get_cropped_source_data( stack_list: List[str], crop_origin: np.ndarray, crop_max: np.ndarray ) -> np.ndarray: """ Read data from the given image files in an image stack :param List[str] stack_list: List of filenames representing images in a stack :param np.ndarray cro...
40f2537417a99d070979ba206de7c6e91a313b02
25,896
def valid_random_four_channel_images() -> str: """ Make a folder with 5 valid images that have 4 channels. :return: path to the folder """ # use .png because that supports 4 channels return make_folder_with_files('.png', file_type='image', resolution=(300, 300), n_files=6, channels=4)
6b39f46467b4ded5a773964255293a3b587d9b6d
25,897
def build_template(spec) -> Template: """Build a template from a specification. The resulting template is an object that when called with a set of bindings (as produced by a matcher from `build_matcher`), returns an instance of the template with names substituted by their bound values. This is a g...
ef44befe0a937b786a48b1e1ddf729f5c1327e3b
25,898
def flatten_objective(expr): """ - Decision variable: Var - Linear: sum([Var]) (CPMpy class 'Operator', name 'sum') wsum([Const],[Var]) (CPMpy class 'Operator', name 'wsum') """ if __is_flat_var(expr): return (expr, [])...
65cea292a03bca4a8bece31e5b2b6d32ae07a77a
25,899