content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import time def split_cp(model, Xtrain, Ytrain, Xtest, labels = [0,1], out_file = None, validation_split = 0.2, seed = 42): """Runs split/inductive CP for all points in Xtest """ # Split data in training and calibration set Xtrain, Xval, Ytrain, Yval = train_test_split(Xtrain, Ytrain, test_s...
b4d37eecf7afc6e4c4c3c40adb414c72de09124c
76,557
from typing import Union def np_sample_stratified( X: np.ndarray, y: np.ndarray, n: int = None, # Like df.sample and np.random.choice frac: float = None, # Like df.sample, unlike np.random.choice replace: bool = False, # Like df.sample, unlike np.random.choice random_state: Union[int, np.ra...
6171e457f529c7dcd59cce1087963660d0ba0078
76,558
from typing import Union from typing import Callable def get_shortname(x: Union[FuncBase, SymbolNode]) -> str: """Compatibility helper for mypy 0.750 vs older.""" fn: Union[str, Callable[..., str]] = x.name if callable(fn): return fn() return fn
7e1ea2370555cb7fa9a40f2bf731d6f0e426f7b4
76,560
def read_netrc(ctx, filename): """Utility function to parse at least a basic .netrc file. Args: ctx: The repository context of the repository rule calling this utility function. filename: the name of the .netrc file to read Returns: dict mapping a machine names to a dict with the...
3f80ffa81a58b7a49c323e7deae116c84f57b174
76,561
from re import T from operator import ne def tanh(x: T.Tensor) -> T.Tensor: """ Elementwise hyperbolic tangent of a tensor. Args: x: A tensor. Returns: tensor: Elementwise hyperbolic tangent. """ return ne.evaluate('tanh(x)')
f844998b6ea87f0d0b530c5a3a57c2a40a115b64
76,562
import json async def list_devices(websocket, ide): """ :param websocket: :param ide: :return: """ payload = json.dumps({ "id" : ide, "type": "hassbrain/device/list" }) res = await _send(websocket, payload) return res['device_list']
c975b235c283c4847aab747d83160e067861bff4
76,564
def compute_neighbours_matrix(src, d_matrix, radius, n_simil): """Compute the set of neighbours of each point in the brain discretization. Parameters ----------- src : :py:class:`~numpy.ndarray` of :py:class:`~float`, shape (n_verts, 3) The coordinates of the points in the brain discretization...
6ea0367897d76ac25a06a3f50d3a42176f0345bc
76,565
def team_rm_from_repository_payload(team_default_payload): """Provide a team payload for removing a team from a repository.""" removed_from_repository_payload = team_default_payload removed_from_repository_payload["action"] = "removed_from_repository" return removed_from_repository_payload
9ffd60f86fa0e4daee0b5c4d73890653e64a47c7
76,568
async def fetch_installations( requester=Security(get_current_access, scopes=[AccessType.admin, AccessType.user]), session=Depends(get_session) ): """ Retrieves the list of all installations and their information """ if await is_admin_access(requester.id): return await crud.fetch_all(ins...
854d6113f86aa31f93d0ece2ece3cd0bc0e6d7f9
76,570
def extract_parts(note): """Search a given chunk of markup for specific references. :param note: the `BeautifulSoup` version of the markup to parse :returns: a tuple of the title, headers, and content """ parts = note.find_all('div') if len(parts) == 3: title, headers, content = parts ...
cfda6dc2a8ebe51dd5c72e4bdcf2125bc1e9f60a
76,572
import json def pdf_to_html_retrieve_view(request): # pdfToHtmlRetrieve """ return a URL to a s3 file that contains the html rough equivalent of the PDF :param request: :return: """ voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id pdf_url...
911c95808e69c59cf76450f343b36246edc1904a
76,573
from typing import Dict def delete_workflow(user: User, workflow: Workflow) -> Dict[str, str]: """ Delete a workflow from the database and filesystem :param user: :param workflow: :return: """ if is_write_permitted(user, workflow): workflow_id = workflow.id db.session.delet...
a20aa19370f0c7730f22582d73b9b018fb4e94c1
76,574
def get_diffs(routes1, routes2, route_ids): """Get difference in number of routes using each segment. params - routes1: Dict{str : List[(lon, lat)]} - first set of routes - routes2: Dict{str : List[(lon, lat)]} - second set of routes - route_ids: List[str] - IDs of routes to consider return...
08853ca746adc459d5d094a4d81af4358f58607f
76,575
from pathlib import Path from typing import List def get_packages_from_requirements(basedirpath: Path,) -> List: """Extract packages from requirements.txt as Python list""" with open(basedirpath, "r") as f: lines = f.readlines() return lines
ca0c85e6175f7026781607bce06ed42d6344db1a
76,576
def setup_subscription_last_run( client, first_fetch_time, last_run, sub_name, ack_incidents ): """ Setups the subscription last run data, and seeks the subscription to a previous time if relevant :param client: PubSub client :param first_fetch_time: First fetch time provided by the user :param ...
55bb40be123c8797e965f0978a5f17f6c8880572
76,579
def get_bgp_status(): """Get BGP statuses""" cpu_status = GetThisDataFromDevice.get_bgp_status(request.json.get('ip'), request.json.get('port'), request.json.get('username'), request.json.get('password')) return {'data': cpu_status}
cdd40dd6ebc8fa519ecf69c57fe8c52481c2bb71
76,580
import binascii def create_request(version, buffer): """ Creates a request packet and returns it as a byte string. buffer is a command to be sent, version should be 2 for current versions of NRPE. """ p1 = _create_packet(version, NRPE_REQUEST, 0, NRPE_OK, buffer) crc = binascii.crc32(p1) & 0xffffffff ...
3756df012459cc46dd40041f49885eaa8f359354
76,581
def group_refs(refs): """ Group all adjecent x/y references. >>> group_refs([(0, 0), (0, 2)]) [[(0, 0)], [(0, 2)]] >>> group_refs([(0, 0), (0, 2), (0, 1)]) [[(0, 0), (0, 1), (0, 2)]] """ if not refs: return [] grouped = [[refs[0]]] for ref in refs[1:]: added_...
44110715690b47c875efc6d50011a49e0b0e7d50
76,582
def get_attributes_and_labels(data): """ :param data: The dataset to be divided :return: Two panda frames which are in order of classes and attributes """ # Here we divide our attributes and classes features for a given dataset return [data.iloc[:, -1], data.iloc[:, :-1]]
c383dad4720093b4002415b48d793bab5834c3fd
76,583
import random def get_random_user_agent(): """ Get a random user agent string. :return: Random user agent string. """ return random.choice(get_data('user_agents.txt', USER_AGENT))
aabb09773da3c1c2438717edd4546e96883c1cb6
76,584
def _read_fzx(instream): """Read FZX binary file and return as properties.""" data = instream.read() header = _FZX_HEADER.from_bytes(data) n_chars = header.lastchar - 32 + 1 # read glyph table char_table = _CHAR_ENTRY.array(n_chars).from_bytes(data, _FZX_HEADER.size) # > Notice that offsets ...
4b171d48e574dfe4f519f2b6a8d687b6c1094f45
76,585
def _code_snippet(snippet: str) -> str: """Generates a markdown code snippet based on python code. Args: snippet (str): Python code. Returns: str: Markdown code snippet. """ result = "```python\n" result += snippet + "\n" result += "```\n\n" return result
5c44bccba225dbd6d60f19c712393b291fe065b5
76,586
from scipy.optimize import leastsq def planckfit(wave, fluxd, err, guess, covar=False, epsfcn=1e-3, **kwargs): """A quick scaled Planck fitting function. The scale factor includes a factor of pi for the conversion from specific surface brightness to flux density. Parameters ---------- wave, ...
8f407198873d444efb2de657387437c0e20abdbc
76,588
def calculate_mixing_params(asm_obj): """Calculate the eddy diffusivity and swirl velocity based on the Cheng-Todreas 1986 correlation with flow regime boundaries and flow split parameters from the 2018 upgrade. Parameters ---------- asm_obj : DASSH Assembly object Contains the geometry...
4a78a4cd07dfd5943dba11e1cc03506a287cf497
76,589
def check_data(data: dict, validator: Draft7Validator) -> list: """ Проверка значения data на соответствие схеме. :param data: Словарь данных из JSON файла. :param validator: Объект Draft7Validator. :return: result Возвращает список найденных ошибок. """ result = [ error.message ...
07ad82a8e96bfdd5a2bd7a63090a30c1199aac77
76,590
def ldap_ocf(): """Context manager that provides an ldap3 Connection to OCF's LDAP server. Example usage: with ldap_ocf() as c: c.search(OCF_LDAP_PEOPLE, '(uid=ckuehl)', attributes=['uidNumber']) """ return ldap_connection(OCF_LDAP)
d588e8dbbf7e9efa24bb60d6c0907fa1e0a4850d
76,591
def check_data(X, y=None, objective='regression'): """ Make sure the data is valid. """ X = check_input_data(X) if y is not None: if objective == 'regression': y = check_regression_targets(y) elif objective in 'binary': y = check_binary_targets(y) ...
c00e8bb21426a329d69f2bd387dd710a53229f47
76,592
def preprocessed_test_dataset() -> pd.DataFrame: """A pd.DataFrame with the Amazon-Best-Sellers-Books preprocessed test dataset. """ return pd.read_csv("./tests/test_data/preprocessed_test_dataset.csv")
7081fd5962c8f99f097c42bd40333f6648cc6052
76,593
def create(url): """ Creates a webdriver. Args: url: The URL the webdriver will open on startup. """ driver = webdriver.Firefox() driver.get(url) return driver
823ae66db331d9d58538a3eb8b44dd3cead4f66e
76,594
from django.contrib.auth.views import redirect_to_login def login_and_perm_required(perm, login_url=None, unprivileged_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the user is authenticated and has permission, redirecting to the log-in page if necessary. ...
759b05186e7749cf2f08ab066a460877e3184747
76,595
def identity_decoder( grid: grids.Grid, dt: float, physics_specs: physics_specifications.BasePhysicsSpecs, ) -> DecodeFn: """Identity decoder module that returns model state as is.""" del grid, dt, physics_specs # unused. def decode_fn(inputs): return inputs return decode_fn
440e0fe84d4f9e3ab47699367d0d969b30ab30e2
76,597
import logging def build_lexicon( words: list, lang: str, depth: int, nlp_model_paths: list = [], wolf_path: str = None, wordnet: bool = False, web: bool = True, strict=False, ): """This is the main function to build lexicons. Args: words ([str]): List of words lan...
3855a6487d688216082b83eb253983023520e692
76,598
def has_tool(string_file, tool_type): """Returns true if string_file has at least one tool of type tool_type Parameters ---------- string_file : str Full path to an Adams Drill string file tool_type : str Adams Drill tool type Returns ------- bool ...
26fd4264888db4da53d3b96941b07cbd20bb1e09
76,599
def registration(father, gender): """ >>> f = registration('Donkey', 'F') >>> f("coco") 'coco-Elizabeth Donkey' >>> f = registration('Donkey', 'm') >>> f('Will') 'Will Donkey' """ def inner(name): if gender.lower() == 'f': return name + '-Elizabeth ' + father ...
6b529d556d5c8cb8658f7a7086ee6905d7e53976
76,601
def remove_conflicts(applicant, potential_editors): """ Remove editors from potential editors who might be sources of conflict of interest. These are typically by name or university. """ return [editor for editor in potential_editors if not (editor["name"] in applicant["conflicts-fac...
49fe7dc482e7f53114f78cf9ed353eded87ecba4
76,602
def _matmul_act(x): """Matmul followed by activation.""" i = array_ops.reshape(x, [8, 8]) f = _weight([8, 8]) x = math_ops.matmul(i, f) y = nn.relu(x) return y
f4b33062fb1a949ecfdec81725d745d5d5a45f54
76,604
from typing import Union import torch def whole_graph_rows_to_batch( similarity_matrix: Union[Tensor, ndarray], indecies: Union[Tensor, ndarray, list], norm_rows: bool = True, ) -> Tensor: """ Sorts matrix according to indecies and row-normalizes if desired Parameters ---------- simil...
336e86d9eb12b3a7e29090bf137f5f127f530cf9
76,605
import collections def _mechanic_re_processor_factory(re_pattern, attribute_name, attribute_mod=None): """ Generic function factory to generate regular expression based processors. :param re_pattern: Regular expression pattern object to match with. :param attribute_name: Attribute name to save the va...
be5b9ec16259d5f24d0eda809511cbb71a2be6fe
76,606
def identity_xf(N): """ Construct N identity 2x3 transformation matrices :return: array of shape (N, 2, 3) """ xf = np.zeros((N, 2, 3), dtype=np.float32) xf[:, 0, 0] = xf[:, 1, 1] = 1.0 return xf
9c778f11cc32d1ecd60a9d39e24fddf88665ee3c
76,607
def seq_one_hot(sequence, characters): """One-hot encode a sequence of characters. Each column is one character.""" # Create dictionary linking characters to indices char_to_ind = dict(zip(characters, range(len(characters)))) # Set up matrix of zeros M = np.zeros((len(characters),len(sequence))) ...
82cca2dd247350e74684c4de3bb751b8eab1edaa
76,608
import math def solve(X, Y, D): """ https://app.codility.com/demo/results/trainingP7B888-UFF/ For example, given: X = 10 Y = 85 D = 30 the function should return 3, because the frog will be positioned as follows: after the first jump, at position 10 + 30 = 40 after the seco...
842d18b2dd1b93e0edeaf1f39937abbcba464084
76,609
def compute_fundamental(x1, x2): """ 正規化8点法を使って対応点群(x1, x2: 3*n の配列)から基礎行列を計算 各列は以下のような並び [x'*xm x'*y, y'*x, y'*y, y', x, y, 1] """ n: number = x1.shape[1] if x2.shape[1] != n: raise ValueError("Number of points do not match.") # 方程式の行列を作成 A: np.ndarray = np.zeros((n, 9)) for i in ra...
e252280703cff987a4c396456bdebad44a7375c4
76,610
def create_lifetime_tech(connector, technology_list): """ This function writes the lifetime tech table in Temoa. TO DO: Update this function to handle technologies with technology lifetimes that vary by region. """ table_command = """CREATE TABLE "LifetimeTech" ( "regions" ...
86f33ecdd2a8db4a0bdceccd0ab8131b175aba14
76,611
from typing import Iterable import textwrap def replace(template: str, **replacements) -> Iterable: """A simple templating system. Rules: * Replaces `Name` nodes with either the nodes that are the replacements, or if the replacement is a string replaces the id of the `Name`. * R...
7dbe0e125b8fb8a32f3b4733a9263c302ae1297a
76,612
def balance_conversion_plus_primary_constraint_rule(backend_model, loc_tech, timestep): """ Balance energy carrier consumption and production for carrier_in and carrier_out .. container:: scrolling-wrapper .. math:: \\sum_{loc::tech::carrier \\in loc::tech::carriers_{out}} ...
5feac80f6690673cdc52f76811ea9591e687fcd0
76,614
def create_mult_token(): """Creates token for multiplication operation.""" return OperationToken("*", parser_utils.SUPPORTED_OPERATIONS.get("*", 0))
04891bfee83aef0cf4dcc7743909e149aaea95c9
76,615
import random def data_generation( lower_range=None, higher_range=None, number_of_variables=None, generation_type=None ): """Data generation method""" if generation_type == 'linear': x_value = np.linspace(lower_range,higher_range,number_of_variables) elif ge...
ee0376042eb9f0ec4198d01484bf19b58eaf3474
76,616
def adjust_learning_rate(optimizer, global_step, steps_per_epoch, args): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" # lr = args.lr * (0.98 ** (epoch / 2.5)) lr = args.lr * (0.98 ** (global_step // int(steps_per_epoch * 2.5))) for param_group in optimizer.param_groups: ...
cfbb54d5cc9b9023fd0b4af9ddafd6b37c546e91
76,617
def do_dice_check(*args, **kwargs): """ Sending stuff to Roll class for dice checks; assumed to already be run through get_partial_match. """ roll = Roll(*args, **kwargs) roll.roll() return roll.result
1710a980ebfd8a98d2daf109f1a3cc03d4821eb5
76,618
from typing import Optional def create_mapping_network(latent_code_dimension: int = 128, output_dimension: Optional[int] = None, normalize_latent_code: bool = True, relu_leakiness: float = 0.2, num_layers: int ...
3cc89cf61f94ded44d02929f964dd0c7b3b165c7
76,619
def remove_glyph_from_jp_font(_font, jp_font_name): """ JuliaMono を採用したいグリフを源柔ゴシックから削除 """ if jp_font_name == "GenJyuuGothicL-Monospace-Heavy.ttf": over_finish = 0x110618 else: over_finish = 0x11061a glyphs = ( list(range(0x0000, 0x2E7F + 0x1)) # + list(range(0x32...
0770eae9187a370e6631adf35adcefd9ea0e45ee
76,620
def del_xact(crs,environ): """delete transaction""" # get arguments qs=environ["wsgi.input"].readline().decode() q=parse_qs(qs) try: xid=q["xid"][0] aid=q["aid"][0] except KeyError as e: raise ValueError("Wrong access") from e # check accounts crs.execute("SELECT ...
a8516e36b893f4fd2fa3620c314e874b61024a90
76,621
def mat_diff(mat_a, mat_b): """ Function that subtracts two matrices: mat_a and mat_b. The subtraction can be carried out if the two matrices have same dimension, i.e. same number of rows and columns. The elements of the resulting matrix, mat_c, are c_ij = a_ij - b_ij :param mat_a: list of list...
0441ea751a3a6c9fb64e9b3a33420fd4b0f8aa3a
76,622
from typing import Union from typing import Sequence from typing import Optional def polyfit( x: Union[None, str, pd.Series, Sequence] = None, y: Union[None, str, pd.Series, Sequence] = None, data: Optional[pd.DataFrame] = None, dropna: bool = True, order: int = 1, logx: bool = False, with...
f666b739a9ffceb15eece8bccb57c9d4742932b3
76,623
def _check_and_coerce_cfg_value_type(replacement, original, key, full_key): """Checks that `replacement`, which is intended to replace `original` is of the right type. The type is correct if it matches exactly or is one of a few cases in which the type can be easily coerced. """ original_type = type...
8b4e750406742fdd4788fdaf73c0c44d95f043d4
76,625
import time def get_capture_filename_by_timestamp(start_time, stop_time): """Generate capture filename based on the specified timestamp.""" filename = 'cap-%s-%s.btt' % ( time.strftime('%y%m%d_%H%M%S', time.localtime(start_time)), time.strftime('%y%m%d_%H%M%S', time.localtime(stop_time))) return filenam...
c40f779886cf395bd6ea5cbe91d19fd5c7952b37
76,626
def skipgram(currentWord, C, contextWords, tokens, inputVectors, outputVectors, dataset, word2vecCostAndGradient = softmaxCostAndGradient): """ Skip-gram model in word2vec """ # Implement the skip-gram model in this function. # Inputs: # - ...
ec3b05fb3a62a6d51351d0fdacbcc3106d6e4573
76,627
from typing import MutableMapping def merge_hash(a, b): """ Recursively merges hash b into a so that keys from b take precedence over keys from a """ _validate_mutable_mappings(a, b) # if a is empty or equal to b, return b if a == {} or a == b: return b.copy() # if b is empty th...
7effa4f1ca834b52df9a6b962ffb3c73cb0cffc9
76,628
def get_confirm_token(response): """ Returns the confirm token from the response. Args: response: response object from the request """ for key, value in response.cookies.items(): if key.startswith('download_warning'): return value return None
da8b11c306c00056a367f35ebe2b0ffa7ff1ffe6
76,629
def default_route(): """Default route to return a simple message""" return jsonify('Please use /std URI to view content')
8467adf89a3d264e9619ab84ef4327997467f243
76,630
import re def _regex_attr(node, attr, gens, container): """ Calcs fitness based on the fact that node's target node shall have an attr with a value smaller than the given one. """ trg_nd = container.nodes[gens[node]] if attr[0] not in trg_nd: return 10.1 if not re.search(attr[1], t...
2e6e5844522cbcbfa78f87b71beb488747c4b86b
76,631
def _get_owner_identity(provider, created_by=None): """ This private method is intended to ensure that a valid identity exists for the 'owner' of an Application. If the identity cannot be found, the AccountProvider will be the author. """ if created_by: return _user_identity_lookup(str(p...
37d5af8596b97a718ee54dec32b302431db9dd5a
76,632
def get_mv_pattern(s2n): """Simple multivariate dataset""" return multiple_chunks(pure_multivariate_signal, 6, 5, s2n, 1)
175238ed32b2ca386dbb52826f7641311b76a673
76,633
def instant_process_statistics(pid): """ Return the instant jiffies and memory values for the process identified by pid. """ work = memory = 0 try: proc = Process(pid) for p in [proc] + proc.children(recursive=True): work += sum(p.cpu_times()) memory += p.memory_perce...
b21e5e1175642f605085039e89eb14ac128fa2ad
76,636
import torch def _generate_bboxes(probs, offsets, scale, threshold): """Generate bounding boxes at places where there is probably a face. Arguments: probs: a float numpy array of shape [n, m]. offsets: a float numpy array of shape [1, 4, n, m]. scale: a float number, w...
2097f69c1e6cf2665010a6dfdebb180e6c9064bd
76,637
def feq(a, b): """Test if two floating point values are 'equal'.""" t = Float("1.0E-10") return -t < a - b < t
d3183ef4eff1b7eea78e16e2533b68f6123ec416
76,639
import logging def get_pending_jobs_info(max_slots_filter=None, skip_if_state=None): """ Retrieve the list of pending jobs. :param max_slots_filter: discard jobs that require a number of slots bigger than the given value :param skip_if_state: discard jobs that are in the given state :return: the ...
4be6c029e5959b5240520479f6806353f8599eb3
76,640
def run_retrive_model(tags, database_list, base_directory): """ Retrive the real final model from the model perturbation. """ # target basedir is the last interpolated model target_basedir = join(base_directory, "interpolation", "__and__".join(database_list[:, 0])) # we...
515130d5a10ae981b8bff17c54cdc588d6009c8d
76,641
import requests def requests_post(url, expected_sc=201, **kwargs): """ Calls our above requests wrapper for a POST request, and sets the default expected status code to 201. """ return do_request_with_auth_retry(url=url, method=requests.post, expected_sc=expected_sc, **kwargs)
1ef9d2025142c346fe4440ca1b9afffeefe930da
76,643
def PorodGuinierPorod(q, a, alpha, Rg, beta): """Empirical Porod-Guinier-Porod scattering Inputs: ------- ``q``: independent variable ``a``: factor of the first power-law branch ``alpha``: exponent of the first power-law branch ``Rg``: radius of gyration ``beta``: ex...
0b081149b626865d100e489b1d88e442e8c1836e
76,644
def get_mac(): """Returns the device mac address in unix format @rtype: string @return: The mac address in unix format """ mac = EUI(getnode()) mac.dialect = mac_unix return str(mac)
6fd733c8fbdbae775a83d2c4643906f43486cc80
76,645
from datetime import datetime def build_results_list(pages, is_json): """Takes a paginated search and returns results List Handles wiki documents, questions and contributor forum posts. :arg pages: paginated S :arg is_json: whether or not this is generated results for json output :returns: list...
5758fc57b56a30b71f6b8b3511f00fc09ede8648
76,647
import logging def diff2(old_file, new_file, dest_file=None): """Do a 2-way diff, between `old_file` and `new_file`, where the differences are shown with markers like what SVN makes for a file with merge conflicts, e.g.: ''' <<<<<<< old_file old stuff ======= new stuff >>>>>>> new...
95a79f4e9dc2c392a11840ac30d396105e9590cb
76,648
def calc_woba_weights(oba,mlb): """ oba: instance of wOBAWeightSim mlb: instance of BattingSim ----------------------------------------- returns: DataFrame with columns [woba,woba_Scale,BB,HBP,S,D,T,HR] """ # Calc adjusted linear weights adjlw = oba.adjWeights() # League OBP (On Base...
87e1039416de61e60b68a94f7683de6f351cf957
76,650
def potential_from_Greens(boundary_potential, n=10, G=Greens_function_approxRW(n=10, nwalks=200, start_position=[5,5]), nwalks=200): """Computes the potential at a the position start_position. G is a Greens function computed by Greens_function_approxRW. The potential at start_position is returned.""" ...
e4c530c15ce575e4bde57132d6e7af636920aa62
76,651
def MutualInfo(labels_true, labels_pred): """Normalized Mutual Information between two clusterings. This code is modified from sklearn. Parameters ---------- labels_true : int array, shape = [n_samples] A clustering of the data into disjoint subsets. labels_pred : array, shape = [n_...
546bb1e2f9cf2913c6dbb971096a2fd90987a3e8
76,652
def _add_replication(bucket_name): """ Configures a second bucket with `-dr` suffix and replicates the primary bucket to it. Adds a lifecycle policy to the dr bucket to immediately roll data into glacier for cold storage """ logger = current_app.logger dr_bucket_name = f"{bucket_name}-dr...
b33e014ed87ccc60f104a873b6ca0fa8a5ac313c
76,653
import functools def union(*windows): """ Union windows and return the outermost extent they cover. Parameters ---------- windows: sequence One or more Windows. Returns ------- Window """ return functools.reduce(_union, windows)
d112b81c130b7b4a346a77a2d1a3b437644e214a
76,654
import torch def lne_to_nel(tensor: torch.Tensor) -> torch.Tensor: """ Convert data layout. This conversion is required to use convolution layer. Parameters ---------- tensor: torch.Tensor (L, N, E) where L is the sequence length, N is the batch size, E is the embedding dimension....
c2375a2a424f56a7d889660d20b29b244fe0328b
76,655
from functools import reduce def lcmm(args): """Computes the lowest common multiple of a list of numbers. Example: >>> lcmm([5, 15, 12]) 60 Args: args (list(int)): The list of numbers on which to compute the lowest common multiple. Returns: int: T...
e49563a0061c1d0fd958ac1f6ab01cbc9811f9aa
76,656
def cvedetails_all(): """从本地数据库中取出全部exp标记的CVE :return exist_exp:list, e.g. ['CVE-xxx','CVE-xxx'] """ so,exist_exp=cve_exists_where(db='exp',table='cvedetails',key=['cve_id'],where='label in (3,4,7)') print('[+] Searched all exp from local cve details database') return exist_exp
b41f5a9136663d269bcb0ebf794f8ad5d97c4d2e
76,657
def im_translate(im, shifts): """ Translate image by shifts :param im: An array of size L-by-L-by-n containing images to be translated. :param shifts: An array of size 2-by-n specifying the shifts in pixels. Alternatively, it can be a column vector of length 2, in which case the same shifts is a...
2d140fc742079e477090289b41b452854ff4dadb
76,658
import itertools def grouper(iterable, n, fillvalue=None): """Group lists into lists of items. grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx""" args = [iter(iterable)] * n return itertools.zip_longest(*args, fillvalue=fillvalue)
6ec8efc9d7bafe2cc09ab407fe44ed8f38e90f10
76,660
def cancel_order(shop_id: int, order_id: int): """ 取消订单 :param shop_id: :param order_id: :return: """ order = get_order_by_shop_id_and_id(shop_id, order_id) if not order: return False, "订单不存在" elif order.order_status != OrderStatus.UNPAID: return False, "订单状态已改变" ...
494b7b44d11a8322ced71cafc990c8e0853e4576
76,661
def product_detail(request, product_id): """ A view to show individual product details """ product = get_object_or_404(Product, pk=product_id) form = ReviewForm reviews = product.reviews.filter(active=True) # doesn't allow drafts new_review = None if request.method == 'POST': form = R...
66a8febedd28ffe62d892bdcc68dd6b3b59efd6e
76,662
import types from typing import NoReturn import pkgutil import importlib import inspect def walk_extensions(module: types.ModuleType) -> frozenset[str]: """ Return all extension names from the given module. Args: module (types.ModuleType): The module to look for extensions in. Returns: ...
84387bc14931a6d7d9fd798ec1aac3915ae2fd79
76,663
def frictional_resistance_coef(length, speed, **kwargs): """ Flat plate frictional resistance of the ship according to ITTC formula. ref: https://ittc.info/media/2021/75-02-02-02.pdf :param length: metres length of the vehicle :param speed: m/s speed of the vehicle :param kwargs: optional could...
02355ae2e4b6a7437f008d3edf15b1f691df3ba7
76,664
import yaml def BqTableSchemaFileProcessor(file_arg): """Convert Input JSON file into TableSchema message.""" table_schema_type = GetApiMessage('TableSchema') schema_field_type = GetApiMessage('TableFieldSchema') try: schema_json = yaml.load(file_arg) schema_json = schema_json.get('schema', None) ...
a3c981cb2333157c9456f785b96d1b931699fc9e
76,665
def return_xarray_dataset(filename,chunks=None,**kwargs): """Return an xarray dataset corresponding to filename. Parameters ---------- filename : str path to the netcdf file from which to create a xarray dataset chunks : dict-like dictionnary of sizes of chunk for creating xarray.Da...
8b9db56d1b2a5b1032c6a8ce74fbe9d9befa0989
76,666
from datetime import datetime def activate_all_records(task): """Activate all submitted task records and enqueue it for processing.""" with db.atomic(): try: status = "The record was activated at " + datetime.now().isoformat(timespec="seconds") count = task.record_model.update(...
446292c545c62b87534928eb43f1c889326b49c9
76,667
def _tag_most_likely(examples): """ Return a list of date elements by choosing the most likely element for a token within examples (context-free). """ tokenized_examples = [_tokenize_by_character_class(example) for example in examples] # We currently need the tokenized_examples to all have the ...
ac96daffc92811fd266518b53fb6712090a127e7
76,668
def decode_modified_utf8(s: bytes) -> str: """ Decodes a bytestring containing modified UTF-8 as defined in section 4.4.7 of the JVM specification. :param s: bytestring to be converted. :returns: A unicode representation of the original string. """ s_out = [] s_len = len(s) s_ix = 0...
bb51073289d8592eb71c8132f8350bad1b36bf27
76,669
def _ReferenceStaticUnroll(theta, state0, inputs, cell_fn): """Statically unrolls a `cell_fn` wrt inputs as `recurrent.Recurrent()` does. This is not a complete implementation but should work reasonably for calls that do not have a custom cell_grad, extras or accumulators and can help check expectations. Ar...
5e173c2962782880f4b394fa02b8531668fe2de7
76,670
def get_drugbank_id_from_chembl_id(chembl_id): """Return DrugBank ID from a CHEMBL ID. Parameters ---------- chembl_id : str CHEMBL ID to map. Returns ------- str or None The mapped DrugBank ID or None if not available. """ return get_drugbank_id_from_db_id('CHEMBL'...
6e812d9011840a4591fe6d9e199afea8bc455714
76,671
def has_group(user, group_name) -> bool: """ Check that a user has a specific group applied, and return either True if so, or False. """ group = Group.objects.filter(name=group_name) if not group: return False return True if group[0] in user.groups.all() else False
4085dda66e713f77924b3338a77b4cea44efe618
76,672
from pathlib import Path def check_distribution(all_methods_df, path=None, test="kstest"): """ Tests wether the data is distributed normally or not and creates different distribution plots. Parameters ---------- all_methods_df : Pandas.DataFrame path: str, Optional Path where the fig...
f7950bfb394032021be5568a31093e8ba9810d05
76,673
def add_mpc_to_vds(hail_context, vds, genome_version, root="va.mpc", info_fields=MPC_INFO_FIELDS, subset=None, verbose=True): """Add MPC annotations [Samocha 2017] to the vds""" expr = convert_vds_schema_string_to_annotate_variants_expr( root=root, other_source_fields=info_fields, other...
1f063b1785068d41bedd5a4ea78e40f1762e1960
76,674
def disagreement(map1, map2): """ "Disagreement" from Carpin et al. # of pairs which are occupied/free in each map, and vice-versa """ disagree = np.count_nonzero((map1 == OCCUPIED) & (map2 == FREE)) disagree += np.count_nonzero((map1 == FREE) & (map2 == OCCUPIED)) return disagree
e7473f95fd75b929b7b7deedba983cedf1953f3c
76,675
from typing import Optional def full_like(a: ArrayLike, fill_value: AnyScalar, shape: Optional[ShapeLike] = None, dtype: Optional[DataTypeLike] = None) -> ShapeletsArray: """ Return a full array with the same shape and type as a given array. Parameters ---------- a: ArrayLike ...
78341fe297f58d9b2dd258b5a44b71088301e87a
76,676
def get_higher_type(a: type, b: type) -> type: """ Returns the higher of the two given Number types. The types are ordered bool -> int -> float -> complex. """ # Type checking assert a in _ordered_types assert b in _ordered_types if a is b: return a for typ in _ordered_typ...
996e8f219900c75bcc9fa5b79d61dcd7488a7cb8
76,677