content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_closest_chips_to(chip_x, chip_y, max_x, max_y, invalid_chips): """ Get the closest chip to a given chip coordinates :param chip_x: the chip coord in x axis for looking for closest to :param chip_y: the chip coord in y axis for looking for closest to :param max_x: the max x coord in the machine ...
a2e53bf0c433cf1653d75621a0886ae806c3e5eb
3,607,798
from typing import OrderedDict def get_partitions(comm): """ Maps partition labels (such as "recovery") to block devices (such as "mmcblk0p0"), sorted by the number in the block device. """ name_cmd = 'ls -l /dev/block/bootdevice/by-name' output = comm.call(lglaf.make_exec_request(name_cmd))[1...
8a23e37b350e6ed07ff86b34d07b5767ac2fab28
3,607,799
import torch def normalize(x: torch.Tensor) -> torch.Tensor: """Normalizes a vector with its L2-norm. Args: x: The vector to be normalized. Returns: The normalized vector of the same shape. """ norm = x.pow(2).sum(1, keepdim=True).pow(1.0 / 2) out = x.div(norm) return out
f34e664a565953e46c9cb18cc66fce0dd9903bde
3,607,800
def marginal_effect(cm_dict, reference, protected): """ Calculates the marginal effect as a percentage difference between a reference and a protected group: reference_percent - protected_percent. Prints intermediate values. Tightly coupled to cm_dict. :param cm_dict: Dict of confusion matri...
4c7ff2e6fa9746bd9b0bd152c2dba25ea3d358a9
3,607,801
def ProfileMostPKmer(sequence, k, matrix): """Input a sequence and a profile matrix, output a score-optimized motif. Loop through all substrings of the sequence. """ max_p = 0 motif = [] for i in range(len(sequence) - k + 1): p = 1 kmer = sequence[i: (i + k)] for col, le...
995581dcb1cd42d435d47c2e6bef4d1e20f107d5
3,607,802
def _create_plane_projection(proj_helper, bounds): """ Construct the PlaneProjection structure for both version 1 & 2. Parameters ---------- proj_helper : PGProjection bounds : numpy.ndarray The orthorectification pixel bounds of the form `(min row, max row, min col, max col)`. Ret...
7e9823b63305f39b3bef95afb78ddce789154b63
3,607,803
def rpn_loss(score_outputs, box_outputs, labels, params): """Computes total RPN detection loss. Computes total RPN detection loss including box and score from all levels. Args: score_outputs: an OrderDict with keys representing levels and values representing scores in [batch_size, height, width, num_an...
8cb10c5c47311435af71612b7c3bb496d95527a4
3,607,804
def ADTM(prices, timeperiod=14): """ 说明:ADTM是用开盘价的向上波动幅度和向下波动幅度的距离差值来描述人气高低的指标。 计算方法: DTM = IF(OPEN<=OPEN[1],0,MAX(HIGH-OPEN,OPEN-OPEN[1])) DBM = IF(OPEN>=OPEN[1],0,MAX(OPEN-LOW,OPEN-OPEN[1])) STM(N) = SUM(DTM,N) SBM(N) = SUM(DBM,N) ADTM = IF(STM>SBM,(STM-SBM)/STM, IF(STM<SBM, (STM-SBM)...
2c4845f18428a25364f28cec3d0709d64c4ae5d2
3,607,805
import logging async def login(form_data: OAuth2PasswordRequestForm = Depends()): """[API router to login existing user] Args: form_data (OAuth2PasswordRequestForm, optional): [User details to login the user]. Defaults to Depends(). Raises: error: [Exception in underlying controller] ...
883e9b541ea1a288d6652fb84cefbb96f05c8aac
3,607,807
def isProfile(): """*bool* = "--profile" """ return options.profile
1335ac5f3af59702a6fa12490b43aa3b22a31597
3,607,808
import warnings def check_symbols(data, obj_names, type_names): """Return a deep copy of data with each symbol checked. Warn if a symbol is used in data but cannot be found in obj_names or type_names. If a symbol cannot be found, then the item is omitted (in the case of a list) or the key, value ...
e3ef6778ec71fce053ad618d31cc5381a16f22d6
3,607,809
import importlib def find_dataset_using_name(name): """Import the module "data/[dataset_name]_dataset.py". In the file, the class called DatasetNameDataset() will be instantiated. It has to be a subclass of BaseDataset, and it is case-insensitive. """ dataset_filename = "data." + name + "_dat...
5133a1ed5bee0e970b483a30888a59264283b25c
3,607,810
def crop_canny(img): """Crops base image based on edge Canny values Parameters: img: image object Returns: cropped img """ cnt = auto_canny(img) pts = np.argwhere(cnt>0) y1,x1 = pts.min(axis=0) y2,x2 = pts.max(axis=0) return img[y1:y2, x1:x2]
cdcf07d90e1f5e57b0a76332480b256a6fac5285
3,607,811
def findflux(imcube, rmscube, mask=None, projmask=None): """ Calculate integrated spectrum and total integrated flux. Parameters ---------- imcube : SpectralCube The image cube over which to measure the flux. rmscube : SpectralCube A cube representing the noise estimate at each ...
23701de13f7c29fbe9499955128198890abe7f30
3,607,813
def get_Pair_Distances(mobile, ref, sel1="protein and name CA", sel2="protein and name CA", **kwargs): """ Aligns mobile to ref and calculates pair distances (e.g. CA-CA distances). .. Note:: single frame function. Args: mobile (universe, atomgrp): mobile structure with trajectory ref ...
8444b9c30419bd2ec744570f7dbb6e8a65f99195
3,607,814
def _right_h2(value: list, fmt: str, meta: dict) -> dict: """Right-aligned header 2.""" return Plain([RawInline(fmt, '<h2 style="text-align:right !important">')] + value + [RawInline(fmt, '</h2>')])
175e2d10b692c333c78cbd05485b6edb7c954fad
3,607,815
def Sigma_functional_form(func_type='well-behaved'): """ Get line with the correct functional form of Sigma(w) """ if func_type == 'power law': form = r'$\Sigma(w)=w^{-\frac{1}{\sigma}}$' elif func_type == 'truncated': form = (r'$\Sigma(w)' r'=\big{(}\frac{1}{w}+B\big...
691aca26f2611835fc4870cb2dd09a40c0b155e4
3,607,816
from typing import Optional from typing import Dict from typing import Any from unittest.mock import patch async def async_init_flow( hass: HomeAssistantType, handler: str = DOMAIN, context: Optional[Dict] = None, data: Any = None, ) -> Any: """Set up mock DirecTV integration flow.""" with pat...
fa6bab2d50a070998985c77307e4fe8e4e78f070
3,607,817
import uuid def label(project): """Label fixture for project label API resource tests.""" _id = uuid.uuid4().hex data = { "name": f"prjlabel{_id}", "description": f"prjlabel1 {_id} description", "color": "#112233", } return project.labels.create(data)
61d9ca8e6a9c909f3bc97135796a2cf03de99b35
3,607,819
def _read_return_type(docstring: Docstring, offset: int, parsed_values: ParsedValues) -> int: """ Parse an return type value. Arguments: docstring: The docstring. offset: The line number to start at. Returns: Index at which to continue parsing. """ parsed_directive = _p...
09377acddc27e2bc6b666d1fba3553dacd2dad83
3,607,820
def compute_implied_vol_surface(characteristic_function, market_params, strike_selector, maturity_times): """ Calculate a matrix of implied volatility. Args: characteristic_function: The characteristic f...
20240154e5504c4e93d915acc51e599e547ccb04
3,607,821
def CreateGraphFromEdge(edge): """Create a generic one-edge graph with the same properties as the given edge, but with new vertex/edge IDs.""" g = Graph() source = Vertex("1") g.vertices["1"] = source source.timestamp = edge.source.timestamp source.attributes = edge.source.attributes target ...
336c76d8e7cd8562c3c4e3239e427fa5c402f0be
3,607,822
def pacbio_option_from_dict(d): """Fundamental API for loading any PacBioOption type from a dict """ # This should probably be pushed into pbcommand/pb_io/* for consistency # Extensions are supported by adding a dispatch method by looking for required # key(s) in the dict. if "choices" in d and d.ge...
b5ad942bc99e1962e8efad2164a3d645700502b6
3,607,824
def to_pb_multibandtile(obj): """Converts an instance of ``Tile`` to ``ProtoMultibandTile``. Args: obj (:class:`~geopyspark.geotrellis.Tile`): An instance of ``Tile``. Returns: ProtoMultibandTile """ cells = obj.cells if cells.ndim == 2: cells = np.expand_dims(cells, 0...
4afa4faeec36449e79b869b0b4e17ab71ed2540c
3,607,826
import math def calculer_distance(point1, point2): """calculer la distance entre les 2 points""" diffx = math.pow(point1['x'] - point2['x'], 2) diffy = math.pow(point1['y'] - point2['y'], 2) return math.sqrt(diffx + diffy)
d4513f387ccd56f9ed535b392f6a6fa36ea2a81d
3,607,827
def inceptionresnetv1(**kwargs): """ InceptionResNetV1 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,' https://arxiv.org/abs/1602.07261. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for mod...
34fe0be682976fc77067dc9e41282b661c31bbd2
3,607,828
import torch def triu(input_, k=0): """Wrapper of `torch.triu`. Parameters ---------- input_ : DTensor Input tensor k : int, optional Offset to main diagonal, by default 0 """ return torch.triu(input_._data, k)
07d9a370e6a33eb2998d0fb4f0c97940f7e0595e
3,607,829
def resnet18(pretrained=False, progress=True, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return _resnet('resnet18', BasicBlock, [2, ...
119fc8a56c6e4f5171b8984c9fa834b6affa69f3
3,607,830
import torch def multi_scene_precision_recall( labels, pred, iou_thresh, conf_thresh, label_mask, pred_mask=None ): """ Args: labels: (B, N, 6) pred: (B, M, 6) iou_thresh: scalar conf_thresh: scalar label_mask: (B, N,) with values in 0 or 1 to indicate which GT boxe...
efcd5c3e9704957d1fafeebe650651a0a52b6199
3,607,831
def convert_tensor_to_image(image_tensor: Tensor) -> np.ndarray: """Converts image from Tensor to numpy array. Args: image_tensor (Tensor: Image Tensor. Returns: np.ndarray: Image numpy array. """ image = image_tensor.numpy() image_channel_last = np.moveaxis(image, 0, -1) ...
64c693a752a1cb901a2ec63f1733553d9b862437
3,607,833
def get_all_logical_switches_by_name(context, name): """Get logical switch that matches the supplied name.""" query = context.session.query(models.LogicalSwitches) return query.filter_by(name=name).all()
bb14c2be47765f37c810b508dc2b478de41eb5c9
3,607,834
from typing import Tuple def _set_col(tone: Tuple[int]): """ returns a colour created from a tuple with three integers. Written by Anthony Luo :param tone: :return: Colour """ r = tone[0] g = tone[1] b = tone[2] return create_color(r, g, b)
42936a8f07d823bd6374803fdd5dece70dca0a39
3,607,835
from typing import List def merge_sort(array: List[int]) -> List[int]: """ Performs a merge sort on an array. :param array: is the array to sort. :return: the sorted array. """ # Base case: The sublist cannot be split any more if len(array) <= 1: return array # Split the arra...
6ee0c47a0ab03021a7f24d6975642626aca66526
3,607,836
from typing import Any async def http_exception_handler(request: Request, exc: Any) -> PlainTextResponse: """ HTTPリクエストに起因したExceptionエラー発生時のフック処理 """ logger.error(str(exc)) return PlainTextResponse("Server Error: " + str(exc), status_code=500)
8f7347a9af151295d807ab688d2dedac48561c3a
3,607,837
def get_roles(keyname): """ Obtains roles for each ip from AppControllerClient. Args: keyname: A string representing an identifier from AppScaleFile. Returns: A dict in which each key is an ip and value is a role list. """ load_balancer_ip = LocalState.get_host_with_role(keyname, 'load_balancer') ...
44e60602c4d2f40b35c9c150c933b1815c97b030
3,607,838
def is_feature_type(feature_type: Feature.Type) -> Condition: """Generate a condition based on feature type.""" def condition(event: AddFeature, before: Submission, after: Submission) -> bool: return event.feature_type is feature_type return condition
2f1580e3ef803d1ee081e4a91cd2e34ffca68bdc
3,607,839
def truncate_sequences(maxlen, index, *sequences): """截断总长度至不超过maxlen """ sequences = [s for s in sequences if s] while True: lengths = [len(s) for s in sequences] if sum(lengths) > maxlen: i = np.argmax(lengths) sequences[i].pop(index) else: r...
449cbc9180cf70f56e21e3899fb7f6419172079e
3,607,840
def find_index(f, seq): """Return the index of the first item in sequence where f(item) == True.""" for index, item in enumerate(seq): if f(item): return index
d37f8450a2f196249a6543e1cc987444151671e3
3,607,841
import re def camel_case_to_underscore(name): """Converts string from camel case notation to underscore. :param name: String to convert to underscore. :type name: string :return: A string converted from camel case to underscore. :rtype: string """ s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1_\2'...
741753a4033c4ff08af3a55c5b600b3c08d46c8f
3,607,843
import json import struct def _xcode_target( *, id, name, label, configuration, bin_dir_path, platform, product, is_swift, test_host, build_settings, search_paths, frameworks, modulemaps, swiftmodul...
295c293f236ff3471debee116a7470bf2bf34ace
3,607,844
def décrypt(f) : """Parametre : signal a décrypter (function) Resultat : singal décrypté (function)""" return (1 + (R24/R21)) * ((R23/(R23+R22)) * f() - (R24/(R21+R24)) * x())
1157a989e904877a5bdab5684496be47084e8a4c
3,607,845
def subtract(a, b): """ Function that returns the diference of a and b """ return a - b
6085d4effbf225583b7076eb1d57f084a90e65e3
3,607,846
def __structure_melted(df_vim_melted): """Converts REFUSE_melted to REFUSE_structured. Args: - df_vim_melted: DataFrame containing at least feature names in a column called 'Feature.Name' and VIM values - vim_name: Column name for VIM values in df_vim_melted Returns: ...
bd0f193981ed543659467b1a078bede200342525
3,607,847
def binarize_categorical_feature(f): """ return binary columns for each feature value """ values = sorted(list(set(f[:,0]))) assert len(values) < 10, "too many categories" x = np.zeros((f.shape[0], 1)) for v in values: x = np.hstack((x, f == v)) return x[:,1:]
a0c80302d2a94d7e96887094ee372cb9fa212ae0
3,607,848
def compare(isamAppliance1, isamAppliance2): """ Compare the list of users between two appliances """ ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) return ibmsecurity.utilities.tools.json_compare(ret_obj1, ret_obj2)
9cb2ea6eb64c1836d9ddf93d344fd5853e8b9936
3,607,849
def vfid_set(session, vfid): """Assign a new VFDI to a session :param session: dictionary of session returned by :func:`login` :param vfid: new VFID to be assigned to the session :rtype: none """ session['vfid'] = vfid return "Success"
00f17adefa2d24bfcd6a1e1f1a24acfe88873dab
3,607,850
def gyradius(atommasses, atomcoords, method="iupac"): """Calculate the radius of gyration (or gyradius) of the molecule. Parameters ---------- atommasses : array-like Atomic masses in atomic mass units (amu). atomcoords : array-like Atomic coordinates. method : str, optional ...
c1e62378973485ab813cd437f51c73196a74713a
3,607,851
def import_list(filepath): """imports list from a file, takes a filepath, returns a list""" txt = open(filepath, "r") shuffled = txt.read().splitlines() txt.close() return shuffled
548866597e0d9899ecdd536c55ef7f9f8ce24688
3,607,852
def _FloatsTraitsBase_get_hdf5_disk_type(): """_FloatsTraitsBase_get_hdf5_disk_type() -> hid_t""" return _RMF_HDF5._FloatsTraitsBase_get_hdf5_disk_type()
da8dc84c3f6ea441183859f3bbd0b5b056a262bf
3,607,853
def get_fixed_OM_costs( b, nameplate_capacity, labor_rate=38.50, labor_burden=30, operators_per_shift=6, tech=1, fixed_TPC=None, ): """ Creates constraints for the following fixed O&M costs in $MM/yr: 1. Annual operating labor 2. Maintenance labor 3. Admin and...
c9252f5b424d6707fa784b9f2c7c02d29b292267
3,607,854
def include_changepoint_features( features: pd.DataFrame, cpd_folder_name: pd.DataFrame, lookback_window_length: int ) -> pd.DataFrame: """combine CP features and DMN featuress Args: features (pd.DataFrame): features cpd_folder_name (pd.DataFrame): folder containing CPD results look...
b0124c62ddfbc3e9add37205a2d026a6da0385a0
3,607,856
def BF16CastElimination(): """Eliminate verbose casting between fp32 and bf16 Checks if the AST has the pattern: castto32(castto16(some_fp32_op(...))) The verbose casting is generated by BF16Promote for multiple bf16 Ops in a row. e.g.: X[i] + Y[i] + T[i] => bf16((float32(bf16((float32(X[i])...
5cbaae8d78582d7675faca540cb44f035352019c
3,607,857
from typing import Optional import time import select def receive_all(senders: dict, wait_time: Optional[float] = None) -> dict: """Wait until data from all channels are received or until specified wait time :param senders: sender channels :param wait_time: maximum time to block :return: key: channel...
39194c98c4fa54ebb35f8c88720cd92a13234fd8
3,607,858
from bs4 import BeautifulSoup import re def scrape_page(url: str) -> dict: """Scrapes single page with given URL. Returns a dict containing page info: { 'previous_caption': str - last but one text element in "breadcrumb" section; 'current_caption': str - ...
3fd7f832b4b996cb384ad794c527db4bce5b101a
3,607,860
def execute_command(instance, arg, verbose=True): """ Execute the command line specified in the remote instance """ result = instance.execute(arg["command"]) if result.exit_code == int(arg["expected_exit_code"]): if verbose: print(Fore.GREEN + " Command: [ "+" ".join(arg["command"])...
7f545e014e42912c8c280c53757029d7bcdafacb
3,607,861
def gen_two_fault_model_demo(pars): """ Generate a demo model with three stratigraphic layers and two faults (15 parameters), based on some starting parameter values as provided by Mark Lindsay. :param pars: np.array of shape (15,) :return: GeoHistory instance """ (rho_0, dz_1, rho_1, dz...
d103dc9a3f0c4cec59159e1fee92c21fa485d872
3,607,862
def bool_list_item_spec(bool_item_spec): """A specification for a list of boolean items.""" return { 'my_bools': { 'required': True, 'items': bool_item_spec } }
8bb609015004b6eb12d182b07731368b107ec602
3,607,863
from typing import List def simplify_keys(keys: List[Key]) -> Key: """Simplify a list of keys. If possible return a slice. If all identical, return an integer key. Else return a list key. :raises ValueError: If keys are not all identical, or of not of type int. """ start = keys[0...
57668c6f72c534c6964b4a2102eed25b848170aa
3,607,864
def _moments(data): """Returns (height, x, y, width_x, width_y) the _gaussian parameters of a 2D distribution by calculating its _moments """ total = data.sum() xx, yy = np.indices(data.shape) x = (xx * data).sum() / total y = (yy * data).sum() / total col = data[:, int(y)] width_x =...
d5d6187bd0ada2dd9a6b1dcac98bfc58e1202984
3,607,865
import jsonschema def save(request, project_id): """ @summary: 创建或编辑app maker @param: id: id 判断是新建还是编辑 name: 名称 desc: 简介 template_id: 模板ID template_scheme_id: 执行方案ID """ try: params = request.POST.dict() jsonschema.valid...
e228c657187c38475737ce1f85c8305102426835
3,607,866
def read_one(read, **kwargs): """Return ((name, value), remainder) for the next header from read().""" lines = iter_lines_buffered(read, sep=b'\r\n', **kwargs) for line, remainder in lines: if not line: return None, remainder return decode(line), remainder
55ecc14d5462c2e400e85248b0f8053b59955312
3,607,867
def calcTotalPrice(machine_type, nom, total_hours): """ calculate price and return a fancy formatted string """ cost = search_v(MACHINES, machine_type) * nom * total_hours cost = cost/100 return cost
9ae9f100268fd29b67cf0da6f15b5fae93c934e2
3,607,868
def _switch_rows(doe_curr, column=None, col_row_pairs=()): """ Randomly switches the values of a numpy array along the second axis This is the permutation function of OptimizeLHS. Parameters ----- doe_curr : np.ndarray shape = (num_sample, n_dim) column : int The number of c...
6fd73722f936a97bba9c0bfc56bd8bb86f5291b4
3,607,869
def clear_scratch_dir(context: AbstractComputeExecutionContext) -> int: """ Given a staging bucket + prefix, deletes all blobs present at that path :return: Number of deletions """ scratch_bucket_name = context.resources.scratch_config.scratch_bucket_name scratch_prefix_name = context.resources....
8879d1439965665200b92e5fbed30351aecb705e
3,607,870
def context(): """Returns a singleton context object.""" if _context is None: _initialize_context() return _context
a905d55d996c0da07e10dae7b9537b35578ff932
3,607,871
def total_seconds(td): """Python 2.7 adds a total_seconds method to timedelta objects. See http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds This function is taken from https://bitbucket.org/jaraco/jaraco.compat/src/e5806e6c1bcb/py26compat/__init__.py#cl-26 """ try: ...
49db7ae90dd2d2d775716b86cab044964217079b
3,607,872
def dft(x, fs, nfft, axis=-1): """ Find the amplitude spectrum using a discrete Fourier transform. Parameters ---------- x : np.ndarray The data time-course fs : float Sampling rate nfft : int The number of samples in the DFT axis : int The axis of the ar...
7b5e5888300986bbc376174ce38a0c1c0fa6a054
3,607,873
def limit(value): """Validates the number of videos to fetch.""" try: value = int(value) except ValueError: raise ArgumentTypeError("must be an integer") if not 1 <= int(value) <= 100: raise ArgumentTypeError("must be between 1 and 100") return value
2b6a6a42faa5bcab48d1ebfbc6a6bcbbcef553be
3,607,874
def review_annotation_view(request, pk, task_pk, annotation_pk): """ Review annotation page. Reviewers can review annotations by writing a comment and approving or rejecting them. """ user = get_user(request.user.username) project = get_project(pk) task = get_task(task_pk) to_review_annota...
d45dbde994a4d2824f88667887860627f5f7428f
3,607,875
def semplot(mod, filename: str, inspection=None, plot_covs=False, plot_exos=True, images=None, engine='dot', latshape='circle', plot_ests=True, std_ests=False, show=False): """ Draw a SEM diagram. Parameters ---------- mod : Model | str Model instance. filename :...
a412e924336efdbf801d92a51ec3b8e243c7ee0f
3,607,876
def print_slopeline(padding,tree,skier,slopewidth,skierposition): """ This function prints a line of the slope to the screen (stdout). The line includes two trees, and a skier. Occasionally the trees are not printed due to a jump. The width of the slope is static for now, and the random number is...
b02467d4fda173e5364eeb243c24b19f43efaf4c
3,607,877
def setup_image_plane_pixelization_grid_from_galaxies_and_grid_stack(galaxies, grid_stack): """An image-plane pixelization is one where its pixel centres are computed by tracing a sparse grid of pixels from \ the image's regular grid to other planes (e.g. the source-plane). Provided a galaxy has an image-p...
2119e77171dbb9e0e36f2d2b72807f9435564115
3,607,878
def jointhist(i, j, bins=256): """Calculate the joint histogram of two grayscale images of the same size""" li, lj = np.ravel(i), np.ravel(j) # unravel ndarrays into lists assert len(li) == len(lj), "images have different sizes, please scale your data first!" nrows = min(int(np.ceil(max(li))), 255) ...
76460ec28088dcdce05a5afbcf3a86b7372265a4
3,607,879
def get_conf_status(config_name): """ Check if the configuration is running or not @param config_name: @return: Return a string indicate the running status """ ifconfig = dict(ifcfg.interfaces().items()) return "running" if config_name in ifconfig.keys() else "stopped"
21178c2fc295287a52a8278b3b3692f543c1af68
3,607,880
def is_valid_ip(ip: str) -> bool: """Checks if ip address is valid Examples: >>> assert is_valid_ip('12.255.56.1') >>> assert not is_valid_ip('1.1.1') """ octets = ip.split(".") if not octets or len(octets) != 4: return False return all(map(lambda octet: octet in map(str...
ded3fa902b869ef8320247a0cfa47f39032c38d6
3,607,882
def bar( x, y_li, labels, xlab, ylab, ax=None, ylim=None, grid=False, href=None, title=None, overlap=False, colors=_COLORS, **kwargs ): """Create a bar plot for up to 5 series/groups. Args: x (list:string): list of group labels for x axis. y_l...
0aad5c9ca659ee55fe2d4a9ef3e22e70a970ea5e
3,607,885
def scan_del(request): """ Delete Network scans. :param request: :return: """ all_ip = scan_save_db.objects.all() if request.method == 'POST': scanid = request.POST.get('scan_id') scans = scan_save_db.objects.filter(scan_id=scanid).order_by('scan_id') scans.delete() ...
0893d66cc6bb9191549fa6f8fc5ac863494a7bd6
3,607,886
def show_results(): """ Get the results only if a spider has results """ global scrape_in_progress global scrape_complete global data_list if scrape_complete: return {"Scraped": data_list} return {'Incomplete List':data_list}
3fb8edc2b2bd15cb2b940d2e07f7802bd6fbf3f4
3,607,887
import numpy def arcsec(val): """ Inverse secant """ return numpy.arccos(1. / val)
9b232ed81368a5abd2e7f340eaca697491f48074
3,607,888
def online_variance(iterator, item_shape): """Compute the elementwise variance in one pass using an online algo. See https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance Parameters ---------- iterator : iterator an iterator yielding ndarrays of the same shape item_shape :...
b90179bd10e7528d354c29f78340989d3ec7f637
3,607,889
def is_type_of(value, other): """Type check""" return isinstance(value, other)
b9c21df5cf75ec86e941182d553eaae2fec2eb38
3,607,890
from operator import xor def aes_cmac(key, M, CIPH=AES): """ AES CMAC - Cipher based Authentication Code""" ciph = CIPH.new(key) block_size = ciph.block_size assert block_size == 16 # only 128 bit (16 octet) blocks supported!! k1, k2 = subkey(key) blocks, leftover = divmod(len(M), block_s...
14612ce2637f69872868f7a1182767e27c8063c6
3,607,892
def reader(file_path, return_type): """Read a text file and return its contents.""" return TextDump(file_path).read(return_type)
d443660c8d3b2818c9c4bce606979e2f3a22e32e
3,607,893
def row(fid, body): """ Append rows to a grid. :param (str) fid: The `{username}:{idlocal}` identifier. E.g. `foo:88`. :param (dict) body: A mapping of body param names to values. :returns: (requests.Response) Returns response directly from requests. """ url = build_url(RESOURCE, id=fid, r...
9f2888cd7f650759e60f219e0b350f1393b30c7e
3,607,894
def greater_than(name): """ Returns a boolean (True) if the minion's current version code name is greater than the named version. name The release code name to check the version against. CLI Example: .. code-block:: bash salt '*' salt_version.greater_than 'Sodium' """ ...
675a241d2d27f5695667f84259a907c0a473ead5
3,607,895
def filldown(table, *fields, **kwargs): """ Replace missing values with non-missing values from the row above. E.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar', 'baz'], ... [1, 'a', None], ... [1, None, .23], ... [1, 'b', None], ...
23ed14b9c6135f192d63c9b01543bdb40757023b
3,607,896
async def remove_notification_role(ctx: Context, role_id: int, role_name: str) -> bool: """ Disable role for notification while raid collection :param ctx: discord command context :param role_id: role id to remove from notification :param role_name: role name to remove from notification :return...
15aa8e1acb79ea925573affaf5d8a93316171ec4
3,607,897
def add_book_to_home(request): """ Adds book to list of user's added books. """ validate_api_secret_key(request.data.get('app_key')) request_serializer = SelectedBookRequest(data=request.data) if request_serializer.is_valid(): user = get_object_or_404(TheUser, auth_token=request.data.ge...
53610f492b98a4c21ddd4e32811277d22803561f
3,607,898
def statistic_reserved_research_death_data(ws1, researches): """ :return: """ style_border_res = NamedStyle(name="style_border_res_rz") bd = Side(style='thin', color="000000") style_border_res.border = Border(left=bd, top=bd, right=bd, bottom=bd) style_border_res.font = Font(bold=False, size...
cd040b485d48045502aa6c10b8a3a708dd2b36ce
3,607,899
def class_fullname(obj): """Returns the full class name of an object""" return obj.__module__ + "." + obj.__class__.__name__
a7b5915e15122664943a181a48d3f52dff232c88
3,607,900
def tpr_diff(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1): """ Returns the between-group difference of True Positive Rates Args: y_true (pd.Series): true target values y_pred (pd.Series): predicted target values prtc_attr (str): name of the protected attribute ...
eeaa7799d3953fc891da5b42d3acfb64146b3948
3,607,901
import re def remember_me_login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationRememberMeForm): """ Based on login view cribbed from https://github.com/django/django/blob/1.2.7/django/contrib/auth/...
c68f164a016184a91bfe63294beb860a42b304dc
3,607,902
def extract_values_mgd(batch_evals, thetas, circuits_details, results, sample_error_mitigation=None, noise_matrix=None, value_error_mitigation=None, samples_filename=None, save_samples=False, **kwargs): ...
909efeb1d9d01f6feff3a872f8af01f8eaab22dd
3,607,903
def exists(path): """ Test whether a path exists. Returns False for broken symbolic links. """ return op.exists(path)
76431a6d898c447180a43783ea9abd1173cb3d70
3,607,904
from crds.tests import test_newcontext, tstmod import unittest def main(): """Run module tests, for now just doctests only.""" suite = unittest.TestLoader().loadTestsFromTestCase(TestNewContext) unittest.TextTestRunner().run(suite) old_state = test_config.setup() result = tstmod(test_newcontext...
1216046d1567aa1b335aeb770e3d17232731c4e6
3,607,905
def run_pca(dataset, num_components): """run_pca Reduces the dimensionality of the dataset with principle component analysis Arguments: dataset - (array_like) The data to be reduced num_components - (int) The number of principle components to keep Returns: transformed_dataset - (array_li...
f2e299936eda06fa3ec9671cacda7c34a603872a
3,607,907
from typing import List def split_users(grouped_data: List[str]) -> List[List[str]]: """ Group user groups into votes per person """ return [value.split(" ") for value in grouped_data]
ea61cedff0441a420ccbcb32584bf294348ac15a
3,607,908
def ang2vec(phi, theta): """ Get vector from spherical angles (phi, theta) :param phi: range (pi, -pi), 0 points in x-direction, pi/2 in y-direction :param theta: range (pi/2, -pi/2), pi/2 points in z-direction :return: vector of shape (3, n) """ assert np.ndim(phi) == np.ndim(theta), "Inpu...
de85a2b082c10c7b620f15328dc0e330531e52e1
3,607,909
import ctypes def __comtype_to_pywin_obj(ptr, interface): """Convert a comtypes pointer 'ptr' into a pythoncom PyI<interface> object. 'interface' specifies the interface we want; it must be a comtypes interface class. The interface must be implemented by the object; and the interface must be known t...
2233e9e0e9718d24d6208f5f154d2a45edd7196a
3,607,910
def strxor(a, b): """ Realiza a operação xor para toda a string a e b sabendo qual das duas é maior """ # xor em duas strings de tamanhos diferentes if len(a) > len(b): return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)]) else: return "".join([chr(ord(x) ^ ...
c97b7eba2ce53c9bd136ebfabc762a5e733c3c4a
3,607,911