content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def hex_to_64(hexstr): """Convert a hex string to a base64 string. Keyword arguments: hexstr -- the hex string we wish to convert """ B64CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' ## internals # bits contains the bits read off so far that don't make enou...
ca8c48bedf4ac776288a8faad06ec80c0289c11e
32,488
def get_frozen_graph(graph_file): """Read Frozen Graph file from disk.""" with tf.gfile.FastGFile(graph_file, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) return graph_def
e3a7bb3e1abf7eb09e6e11b325176eb95109e634
32,489
def wrap_functional_unit(dct): """Transform functional units for effective logging. Turns ``Activity`` objects into their keys.""" data = [] for key, amount in dct.items(): if isinstance(key, int): data.append({"id": key, "amount": amount}) else: try: ...
9c86b5c6c4f360e86f39e2bc59ce4a34804cd7fa
32,490
def full_fuel_requirement(mass: int) -> int: """Complete fuel requirements for a single module.""" base_fuel = fuel_requirement(mass) return base_fuel + sum(additional_fuel_requirements(base_fuel))
62c9d7e11afd0805d476216bdd113081285b10c4
32,492
def is_private(name): """Check whether a Python object is private based on its name.""" return name.startswith("_")
d04dfd84884bbc8c8be179c6bc5fc1371f426a78
32,493
import warnings def get_suitable_output_file_name_for_current_output_format(output_file, output_format): """ renames the name given for the output_file if the results for current_output format are returned compressed by default and the name selected by the user does not contain the correct extension. out...
6925d721f06e52c8177c5e4f6404629043642cc4
32,494
def efficientnet_b1( num_classes: int = 1000, class_type: str = "single", dropout: float = 0.2, se_mod: bool = False, ) -> EfficientNet: """ EfficientNet B1 implementation; expected input shape is (B, 3, 240, 240) :param num_classes: the number of classes to classify :param class_type: ...
e713946ec937d0beb2069f7a273a311cad4b3305
32,495
def mark_user_authenticated(user, login): """ Modify a User so it knows it is logged in - checked via user.is_authenticated() """ setattr(user, ACTIVATED_LOGIN_KEY, login) return user
dcd706204747c526c2128a49fcf24c7ef8e075bd
32,496
def assignments(bmat, order=1, ntry=10): """Make assignments between rows and columns. The objective is to have assigments following the following conditions: - all association are allowed in bmat, - each row is associated with a unique column, - each column is associated with a unique row, ...
5d183df6b538b13f53cf4a9ec18527525b5d0383
32,497
from operator import inv def _tracemin_fiedler(L, X, normalized, tol, method): """Compute the Fiedler vector of L using the TraceMIN-Fiedler algorithm. """ n = X.shape[0] if normalized: # Form the normalized Laplacian matrix and determine the eigenvector of # its nullspace. e ...
9b14aa1a8973134846bcf31dabe8bb27d70d36fd
32,498
def default_char_class_join_with(): """ default join for char_class and combine types """ return ''
9d8f15413f56202472f2e1257382babbaa444edc
32,499
def infer_orf(pos1, pos2, corr_coeff=np.zeros(7)): """ Approximation of spatial correlations at seven angles, with borders at 30 degrees. """ if np.all(pos1 == pos2): return 1. else: eta = np.arccos(np.dot(pos1, pos2)) idx = np.round( eta / np.pi * 180/30.).astype(int) ...
9f624d42b39424ab14fefe68758403709661987f
32,500
def draw_bs_reps_ind(data, func, size=1): """Draw bootstrap replicates, resampling indices""" # Set up array of indices inds = np.arange(len(data)) # Initialize replicates bs_reps = np.empty(size) # Generate replicates for i in range(size): bs_inds = np.random.choice(inds, size=le...
39be61c2c7f3f1b67887c9f4a6159f63cc9f6c92
32,502
def get_committee_assignment( state: BeaconState, config: Eth2Config, epoch: Epoch, validator_index: ValidatorIndex, ) -> CommitteeAssignment: """ Return the ``CommitteeAssignment`` in the ``epoch`` for ``validator_index``. ``CommitteeAssignment.committee`` is the tuple array of validators i...
ad0661cb166c319fe7026199f0175de8939457ab
32,503
def from_tfp(posterior, var_names=None, *, coords=None, dims=None): """Convert tfp data into an InferenceData object.""" return TfpConverter( posterior=posterior, var_names=var_names, coords=coords, dims=dims ).to_inference_data()
b77b8fc6efbef07a3243026fa0baf40912be5950
32,504
def collection_file_fixture(config, filesystem): """Return a test CollectionFile instance""" collection_name = 'test-collection' file_name = 'index' collection_file = CollectionFile(config, filesystem, collection_name, file_name) collection_file.get_collection().get_path().mkdir(parents=True) r...
f4c8aab35727cdc345a8cd173c7f4646a66e17dc
32,505
def get_array_of_data(): """Function helps to collect all filtered data in one array and it returns that""" array_of_data = [] array_of_messages = gmail_get.get_bodies_of_messages() for msg in array_of_messages: if 'новый сотрудник' in msg: message = get_data_from_text(msg) ...
2990315722ee263922a119cba38c8e0d6e86675e
32,506
def call_blade_functions (calls): """ Call a set of system functions for each blade in the rack. The results of the calls will be aggregated together for each blade. :param calls: A list of tuples containing the functions to call, the name of the parameter that contains the blade ID, and a lis...
30acf91d9346b9bcf090388a9d2a02b26b02ce36
32,507
from typing import Callable from typing import Optional def seglearn_wrapper(func: Callable, func_name: Optional[str] = None) -> FuncWrapper: """Wrapper enabling compatibility with seglearn functions. As [seglearn feature-functions](https://github.com/dmbee/seglearn/blob/master/seglearn/feature_functions...
d13427f9c696c9ded8c412401b8879c4bbc66073
32,508
import scipy def spline_fit(output_wave,input_wave,input_flux,required_resolution,input_ivar=None,order=3,max_resolution=None): """Performs spline fit of input_flux vs. input_wave and resamples at output_wave Args: output_wave : 1D array of output wavelength samples input_wave : 1D array of i...
2a42f6c85bace99bba7897be81ecd5a779373476
32,509
def park2_3_mf(z, x): """ Computes the Park2_3 function. """ f = [z[0][0]/5000.0, z[1]/10.0] return park2_3_z_x(f, x)
801da280fd9287de6124c16a526f66d3526d054f
32,510
def make_batch_sql( table, datas, auto_update=False, update_columns=(), update_columns_value=() ): """ @summary: 生产批量的sql --------- @param table: @param datas: 表数据 [{...}] @param auto_update: 使用的是replace into, 为完全覆盖已存在的数据 @param update_columns: 需要更新的列 默认全部,当指定值时,auto_update设置无效,当dupl...
48c990994c226bc370c8c5a62694eae29ab8e6e5
32,511
import bot_config import traceback def get_dimensions(): """Returns bot_config.py's get_attributes() dict.""" # Importing this administrator provided script could have side-effects on # startup. That is why it is imported late. try: if _in_load_test_mode(): # Returns a minimal set of dimensions so i...
7e8b2c29cf43ee46df77671370fb5c6a0030643a
32,512
from pathlib import Path def find_project_root(srcs): """Return a directory containing .git, .robocop or pyproject.toml. That directory will be a common parent of all files and directories passed in `srcs`. If no directory in the tree contains a marker that would specify it's the project root, the...
87c2b40498879dccc8f5ec18c1b456390b845b44
32,513
def __virtual__(): """ Return virtual name of the module. :return: The virtual name of the module. """ if HAS_SQLI: return __virtualname__ return False, "sqlite3 module is missing"
f40a769e6376e284ddc7ab805b094e056db78d9e
32,514
def filter_contours(flist, contours, dist): """ Filter out all visual cues with a eucl_dist(P/A ratio) smaller than .05 """ n, fltr_cnts, bad_cnts = [], [], [] # loop over each frame to verify condition for i in range(len(flist)): fltr_areas = list(np.array(contours[i])[np.where(np.array(dis...
4720bd1b1c860dfe45c067602672b042f060d571
32,515
def count_ents(phrase): """ Counts the number of Named Entities in a spaCy Doc/Span object. :param phrase: the Doc/Span object from which to remove Named Entities. :return: The number of Named Entities identified in the input object. """ named_entities = list(phrase.ents) return len(named_en...
7e592442ebaf504320a903c4084454ff73896595
32,516
def version_command(argv) -> CommandResult: """Show FlakeHell version. """ print('FlakeHell', colored(flakehell_version, 'green')) print('Flake8 ', colored(flake8_version, 'green')) print('For plugins versions use', colored('flakehell plugins', 'green')) return ExitCode.OK, ''
bf541f6c049ed8c385200817912908d7f615bb17
32,517
import typing def get_oldest_employees(count_employees: int) -> typing.List[typing.Tuple[str, str]]: """ Return a list of pairs in the form of (FirstName, LastName). The list will consist of the `count` oldest employees from oldest to youngest. :param count: Number of employees to return. :type c...
9b1518ddb936d40997a0f8c5bc8770b33956e5c2
32,518
def get_Q_UT_CL_d_t_i(L_CL_d_t_i, Q_T_CL_d_t_i): """冷房設備機器の未処理冷房潜熱負荷(MJ/h)(20b)を計算する Args: Q_max_CL_d_t_i(ndarray): 最大冷房潜熱出力 L_CL_d_t_i(ndarray): 冷房潜熱負荷 Q_T_CL_d_t_i: returns: 冷房設備機器の未処理冷房潜熱負荷(MJ/h) Returns: ndarray: 冷房設備機器の未処理冷房潜熱負荷(MJ/h) """ return L_CL_d_t_i - Q_T_CL_d_...
4f46048e6df08d634153b176b241ac1caaae252f
32,519
import re def html_gscholar_to_json(soup): """ """ # Scrape just PDF links for pdf_link in soup.select('.gs_or_ggsm a'): pdf_file_link = pdf_link['href'] print(pdf_file_link) # JSON data will be collected here data = [] # Container where all needed data is located f...
cf7166650b9114e184896c10e17be4a32bc129a0
32,520
def csi_psroipooling( cls_prob, roi, spatial_scale, output_dim, group_size, out_dtype, q_params, layer_name="" ): """Quantized psroipooling. Parameters ---------- Returns ------- result : relay.Expr """ return _make.CSIPSROIPooling( cls_prob, roi, spatial_scale, output_dim, ...
864dc29d469820f6ef09a006910aacaefce7c932
32,521
import logging def short_links(link): """ Shortening a long url to a short link Byt.ly      : param link: long address      : return: string - short link Byt.ly """ url = 'https://api-ssl.bitly.com/v4/groups' res = get(url=url, headers=head) group = res.json()['groups'][0]['guid'] url = 'h...
80b6803812933b0087d5c9d5cb1d3fb3e8f04be4
32,522
def parse_page_loaded(msg_type, target, logs, log_begin_idx): """ Parse WebViewPageLoadedEvent event logs :params msg_type :params target :return: an instance of event.WebViewPageLoadedEvent """ assert len(logs) == 1 log_info = util.extract_info(logs[0]) plid, package = log_info['p...
2721155f7b38c299100eb75cec2df1c18aaefd31
32,523
def suggest_mappings_by_content(resource, pathway_id): """Return list of top matches based on gene set similarity. --- tags: - mappings parameters: - name: resource type: string description: name of the database required: true ...
0dec7c0a2759a6aabb1bae5ab22973cd74b30e7f
32,524
def animation(request): """ Controller for the streamflow animation page. """ context = {} return render(request, 'sfpt/animationmap.html', context)
d42c4d0e7d51a772c115488636bf84701b9d5ee0
32,525
def kos_lookup_cmdr_embeds(session, cmdr_name, cmdr_pic=None): """ Look up the cmdr in the KOS db, if found return embeds that match (up to 3 closest). Returns: [embed, ...]: The discord.py embeds who match the cmdr_name. [] : No matches in KOS db. """ if not cmdr_pic: cmdr_...
243f46a772e04874fd3a11c77c7ba6d3cdf439d0
32,526
def decode(s): """ Deserialize an MRS object from a SimpleMRS string. """ if hasattr(s, 'decode'): s = s.decode('utf-8') ms = next(_decode(s.splitlines())) return ms
11a5a914ab53d7de944637337b8f33315dacdb41
32,528
def fidimag_to_finitedifferencefield(sim): """ fidimag_to_finitedifferencefield(sim) This function takes a Fidimag simulation object, and constructs a Finite Difference Field object which has the magnetisation configuration from the simulation at the last time step. """ cmin = np.array([sim...
b612127c457e4d8901a7bf7558210c3ea43a19c4
32,529
from typing import Tuple def ERA_IrregularImgGrid( lons: np.ndarray, lats: np.ndarray, bbox: Tuple[float, float, float, float] = None, ) -> CellGrid: """ Create a irregular grid from the passed coordinates. """ lons_gt_180 = np.where(lons > 180.0) lons[lons_gt_180] = lons[lons_gt_180] ...
461d98eaf7de17fa5b0fb510ce7c24698872e74e
32,530
import inspect def create_enforce_validation_serializer(serializer=None, **kwargs): """ Public function that creates a copy of a serializer which enforces ``must_validate_fields``. The difference between this function and ``_create_enforce_validation_serializer`` is that this function can be used both...
63f1e05148aa3a8190316898d4b111334bebf47b
32,531
def read_FDF_cube(filename): """Read in a FDF/RMSF cube. Figures out which axis is Faraday depth and puts it first (in numpy order) to accommodate the rest of the code. Returns: (complex_cube, header,FD_axis) """ HDULst = pf.open(filename, "readonly", memmap=True) head = HDULst[0].header.copy() ...
25ab8de5ab75b7e6170a897e5bee4ec067a1c4d4
32,533
import torch def bert_vector(text, tokenizer, model, args): """ BERT-based embedding. :param text: original text to be embedded. :param tokenizer: BERT tokenizer. :param model: BERT model. :param args: args. :return: BERT embedded sentence. """ text = '[CLS] ' + text + ' [SEP]' ...
cbe2b74327d1e05761b922e4cc1f30cc399251ec
32,534
from typing import List from typing import Dict def compute_benchmark_energies(molecule: tq.chemistry.Molecule, benchmarks: List[str]) -> Dict: """ This uses psi4 to perforom the classical benchmarks. """ energy_benchmarks = {} for method in ["hf", "mp2", "ccsd", "fc...
e8350a36c51418f6dd0cd2a571c43234577ec557
32,535
def fine_paid_message(message): """Returns true if the format of paid message is fine""" return (len(message.mentions) > 0 or message.mention_everyone) and get_amount(message) is not None and message.channel.name == "expenses" and (message.content.split(" ")[0] == '!paid' or message.content.split(" ")[0] == '<@...
d545310d7606c818f9cc434db7b4caad25da9cab
32,536
def print_qa(questions, answers_gt, answers_gt_original, answers_pred, era, similarity=_dirac, path=''): """ In: questions - list of questions answers_gt - list of answers (after modifications like truncation) answers_gt_original - list of answers (before modifications) ...
523e474392c41971de1465ae15e1c12ac6b3d359
32,538
def compute_zhu(props, zhu_kwargs): """ Compute the approximate Zhu-Nakamura hopping probabilities for each geom in the dataset. Args: props (dict): dataset properties zhu_kwargs (dict): dictionary with information about how to calculate the hoppin...
7ad687145e94b8a4b6eb6a3631783583d3cefdbd
32,539
import html def disaster_type_card(): """ :return: A Div containing dashboard title & descriptions. """ return html.Div( children=[ html.H6("Disaster Type"), dcc.Dropdown( options=[ ...
8e7ddfc88c075b035be591cd6a0ba6e068f444f8
32,540
def retrieve_context_topology_node_node_rule_group_inter_rule_group_risk_characteristic_risk_characteristic(uuid, node_uuid, node_rule_group_uuid, inter_rule_group_uuid): # noqa: E501 """Retrieve risk-characteristic Retrieve operation of resource: risk-characteristic # noqa: E501 :param uuid: ID of uuid ...
73a2bcbae8cc023db6dd4378a93fb66c75d1ed11
32,541
import struct def txt2domainname(input, canonical_form=False): """turn textual representation of a domain name into its wire format""" if input == ".": d = b'\x00' else: d = b"" for label in input.split('.'): label = label.encode('ascii') if canonical_form: ...
d5312ab1333810eaba6bac2f16e15441ea290dc9
32,542
def hstack(*args): """ Stacks images horizontally If image depths are mismatched then converts grayscale images to bgr before stacking """ depths = [depth(im) for im in args] gray = [d == 1 for d in depths] if all(gray): return np.hstack(args) elif not all(gray): return ...
5e4a2278a9f5283446910d88053b52ee17e1cf6f
32,545
def sample(x, n): """ Get n number of rows as a sample """ # import random # print(random.sample(list(x.index), n)) return x.iloc[list(range(n))]
3802f976f2a97a08945d8246093784c06fb07e67
32,546
def floor_div_mul(value, factor): """Fuction to get floor number.""" return (((value) // (factor))) *(factor)
53adab5c9e0d9d5b27d36e2f77e1e7f0edd05585
32,547
def dup_div(f, g, K): """ Polynomial division with remainder in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x = ring("x", ZZ) >>> R.dup_div(x**2 + 1, 2*x - 4) (0, x**2 + 1) >>> R, x = ring("x", QQ) >>> R.dup_div(x**2 + 1, 2*x - 4) (1/2*x + ...
01541d416a08613b1b400da1c6306fdce1ad29ff
32,548
def append_Z_trace_vertical(path, new_point, height, ex, middle_layer=None, middle_taper=False): """Adds new_point to the path list plus TWO Z or S manhattan interesections. Args: path: list of tuples containing necessary info (pya.DPoint, layer, width) new_point: tuple ((x, y) or pya.DPoint, la...
17bce8bafd5c627d3e1d8b793e061816348fa086
32,549
from typing import List def batch_ext(order: pd.Series, batch: pd.Series, classes: pd.Series, class_list: List[str], ext: str) -> pd.Series: """ get minimum/maximum order of samples of classes in class_list. Auxiliary function to be used with BatchChecker / FeatureCheckerBatchCorrection ...
eb48eee2392cb8c1db3691a38e9be97a243dc730
32,550
from typing import Tuple import time def chunk_push(params: dict | None = None) -> Tuple[bool | str, ...]: """ A helper function to push the data to database in chunks. :param params: A dictionary that contains below structure. { "data_rowcount": data row count, ...
a65612d7ffbc83fa0bceb13a8d2c853aa79dcfeb
32,551
def total_error_avgAx0(y_true, y_pred): """ """ avgY = K.mean(y_true, axis=0, keepdims=True) # 0 is sample axis return K.sum(K.square(y_true - avgY))
6fd12b66b689b4ff5b26ba6f0456927e902ec36b
32,552
def var_aexp(compiler, node): """ Variable compilation """ if node.context == 'assign': gc = GC(compiler) if compiler.environment.is_exist_local_var(node.name): var = compiler.environment.get_local_var(node.name) var_type = compiler.environment.get_local_var_runtime_type...
003ad8a1db094516b9303e8769ceea48ef67a88b
32,553
from .model_store import get_model_file def resnet50_v1b(pretrained=False, root='~/.mxnet/models', ctx=cpu(0), **kwargs): """Constructs a ResNetV1b-50 model. Parameters ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.mx...
5357c998f5132b4121e0ec96f688177987139ff7
32,554
def _f_expl_5_cash_karp_adptv(x0, Y0, dx, *args, dYdx=None, econ=0.0001889568, eps=0.1, pgrow=-0.2, pshrink=-0.25, safety=0.9, **kwargs): """Explicit adaptive 5th-order Cash-Karp method Parameters ---------- x0 : Intvar Integration variable at beginning of scheme Y0 : Field Variable...
3d50e50d2c11b1e274c6e1a88b79780132e140ae
32,555
def issubset(list1, list2): """ Examples: >>> issubset([], [65, 66, 67]) True >>> issubset([65], [65, 66, 67]) True >>> issubset([65, 66], [65, 66, 67]) True >>> issubset([65, 67], [65, 66, 67]) False """ n = len(list1) for startpos in range(len(list2) - n + 1): ...
2f4acbba54b303b7041febbe485d8960baa6528f
32,556
def make_start_and_end_images_with_words(start_words, end_words, perm: bool = False, repeat=1, size=150): """ Make two images from two sets of words. :param start_words: Words to use for the first image. :param end_words: Words to use for the second image :param perm: Whether the words should be per...
7ecb10eec8a447ffbc0f5f17f596dfc55e6e822b
32,557
def bbox2corners(bbox): """ box parameters to four box corners """ x, y, w, h, _ = bbox.tolist() xy_tl = [x - w/2, y - h/2] xy_dl = [x - w/2, y + h/2] xy_dr = [x + w/2, y + h/2] xy_tr = [x + w/2, y - h/2] return np.array([xy_tl, xy_dl, xy_dr, xy_tr])
50ac1dd1172c95b1edcf458e55759c01a593759c
32,558
def clean_game_data_recent(df: pd.DataFrame, shift=False) -> dict: """Clean game data post mid-2018. Follows a slightly different format than pre-2018 data. """ month_game_data = {} game_type = "tables" if shift == True: # APR_2021, MAY_2021 had no %diff, so we need to shift add = 1 ...
c2d5127b4f8b6d4e7caa03135ce257c5f6ac02a4
32,559
from typing import Dict import re def process_data(dataframe : pd.DataFrame, label_to_id: Dict, vocab : Dict = None, vocab_size : int = 10_000, max_tokens : int = 200, max_token_size : int = 40) -> (tf.Tensor, tf.Tensor, dict, dict...
c30903af96f1157e08357daedacf67a146ed101c
32,560
def tan_to_eq(xiDeg, etaDeg, ra0Deg, dec0Deg): """Convert tangential coordinates to equatorial (RA, Dec) in degrees.""" xi = xiDeg * np.pi / 180. eta = etaDeg * np.pi / 180. ra0 = ra0Deg * np.pi / 180. dec0 = dec0Deg * np.pi / 180. ra = np.arctan(xi / (np.cos(dec0) - eta * np.sin(dec0))) + ra0 ...
a0e9bad863192dca391ae324f956562b092066c1
32,561
def type_from_tensors(tensors): """Builds a `tff.Type` from supplied tensors. Args: tensors: A nested structure of tensors. Returns: The nested TensorType structure. """ def _mapping_fn(x): if not tf.is_tensor(x): x = tf.convert_to_tensor(x) return computation_types.TensorType(x.dtype...
16821ca45a2000107069b992aac9a52638f2c5ea
32,563
from typing import Any def is_none_or_empty(obj: Any) -> bool: """Determine if object is None or empty :param obj: object :return: if object is None or empty """ return obj is None or len(obj) == 0
a90245326e4c776ca1ee0066e965a4f656a20014
32,565
def create_python27_start_cmd(app_name, login_ip, port, load_balancer_host, xmpp_ip): """ Creates the start command to run the python application server. Args: app_name: The name of the application to run login_ip: The public IP port: The local port the application server will bind to load_balanc...
5eca494233ab5c38048cc583f564247167306594
32,566
from operator import and_ import types import string def create_query_constraint(): """ Create a constraint for a query WHERE clause """ op = oneOf("= < > >= <= != <>", caseless=True).setName("operator") basic_constraint = (var + op + var_val).setResultsName("operator") between = ( var + Suppr...
92e3f2dcf87213126b70af7ae1dd302fc15b32e6
32,567
def reshape2D(x): """ Reshapes x from (batch, channels, H, W) to (batch, channels, H * W) """ return x.view(x.size(0), x.size(1), -1)
29851e54bb816fb45184d3ea20e28d786270f662
32,568
from operator import add from operator import mul from operator import sub def addNoise(s,x): """ adds s percent random noise to reduce problems with zero traces """ xdif = max(x)-min(x) n1,n2,n3 = s1.count,s2.count,s3.count r = randfloat(n1,n2,n3) x = add(mul(sub(r,0.5),s*xdif),x) return x
a951f37fd48c4cf63d167189bd5674c4dc219245
32,569
def calc_cs_face_area(lon_b, lat_b, r_sphere = 6.375e6): """Calculate area of cubed-sphere grid cells on one face Inputs must be in degrees. Edge arrays must be shaped [N+1 x N+1] """ # Convert inputs to radians lon_b_rad = lon_b * np.pi / 180.0 lat_b_rad = lat_b * np.pi / 180.0 ...
fdc33180a49552e907d2bf683a7a829f4c1f6c47
32,570
def yices_new_param_record(): """Creates a new param object, an opaque object that stores various search parameters and options that control the heuristics used by the solver.""" return libyices.yices_new_param_record()
b69bd915d1044703a5308ae1d4670e9905b7a180
32,571
def parse_multipart(input, boundary): """ Parse multipart/form-data Parse mime-encoded multipart/form-data into a python dictionary. This function returns a tuple consisting of post vars, and files. Attributes: input -- Input data to be parsed boundary -- Field bou...
0eef5559bf725654af6489e79c64e9ddc7658bf8
32,572
def get_fr_trj_ntrj(rslt, start, end, a_params): """Check whether event exhibits "blowup" behavior.""" # get spks during candidate replay event spks_evt = rslt.spks[(start <= rslt.ts) & (rslt.ts < end), :] # get mask over trj and non-trj PCs pc_mask = rslt.ntwk.types_rcr == 'PC' sgm_cu...
7cb2f0262debba36789e4e230b4d26dd096cf950
32,573
from typing import Sequence from typing import Any def gapfilling(circuit: cirq.Circuit, placeholder: Sequence[Any]) -> cirq.Circuit: """ Fill single qubit gates according to placeholder on circuit :param circuit: :param placeholder: :return: """ n_circuit = cirq.Circuit() all_qubits ...
23add843a8546bf9177da87c1bb7cb161fedc3cc
32,574
import logging def train_data_from_directory(train_path, val_path, target_size=(224, 224), batch_size=16, rescale=1. / 255, rotation_range=20, width_shift_range=0.2, height_shift_range=0.20, zoom_range=0.3, vertical_flip=True, h...
d3f6906c5fb8e6eebabc1971a1430ac4d183cfeb
32,575
def add_to_group(ctx, user, group): """Adds a user into a group. Returns ``True`` if is just added (not already was there). :rtype: bool """ result = ctx.sudo(f'adduser {user} {group}').stdout.strip() return 'Adding' in result
abb7b432f4e4206a3509d1376adca4babb02e9f0
32,576
def ifft(X): """ Inverse FFT with normalization by N, so that x == ifft(fft(x)) within round-off errors. """ N, x = len(X), fft(X, sign=1) # e^{j2\pi/N} for i in range(N): x[i] /= float(N) return x
df388803e0a7ad91136ad174dee7d82521e60ce4
32,577
from typing import List def _validate_fields(fields: List[_Field] ) -> List[mapry.validation.SchemaError]: """ Validate the correctness of the the corresponding C++ fields of a composite. Notably, we validate that there are no duplicates and no reserved keywords in the C++ field...
49dfd85d473f4934b55539e7db6a707500ead547
32,578
def frames_collection(collection): """ returns a list of frames extracted from a collection of NAF files. :param collection: collection of dictionaries with relevant info extracted from NAF files :param collection: list """ collection_frames = [] for info_dict in collection: for fra...
6255a826d24bce0e26d40e7d1dbbd093c1e43a19
32,579
def execute(*cmd, **kwargs): """Convenience wrapper around oslo's execute() method.""" if 'run_as_root' in kwargs and 'root_helper' not in kwargs: kwargs['root_helper'] = _get_root_helper() return processutils.execute(*cmd, **kwargs)
185c18c3c30305d302e8582b708e1f80069fb79a
32,580
async def async_build_devices(hass, zha_gateway, config_entry, cluster_ids): """Build a zigpy device for each cluster id. This will build devices for all cluster ids that exist in cluster_ids. They get added to the network and then the sensor component is loaded which will cause sensor entities to get ...
5fb6900fe6bdd65f6ed68da6c51df7149679f36a
32,581
import torch def load_ckp(model, ckp_path, device, parallel=False, strict=True): """Load checkpoint Args: ckp_path (str): path to checkpoint Returns: int, int: current epoch, current iteration """ ckp = torch.load(ckp_path, map_location=device) if parallel: model.modu...
4fe4e368d624583216add3eca62293d5d1539182
32,583
def show_branch_panel( on_done, local_branches_only=False, remote_branches_only=False, ignore_current_branch=False, ask_remote_first=False, local_branch=None, selected_branch=None): """ Show a quick panel with branches. The callback `on_done(branch)` will ...
b458185b63281ab1da9d6b87047e3b8145c0d52b
32,584
import torch def map_str(string,char_encoding=default_char_encoding): """ Maps """ hold = torch.Tensor([char_encoding[x] for x in string]) hold = hold.long() return hold
fd69d80d6bfa3fb7f55c17063f1878b3e9216526
32,585
def parse_section(section): """ Works out the component and section from the "Section" field. Sections like `python` or `libdevel` are in main. Sections with a prefix, separated with a forward-slash also show the component. It returns a list of strings in the form [component, section]. For ...
06ab4f4ebb874e1a5b94c5e6736b4af4a137897f
32,586
def tpm3_exon1_exon8_t_to_g(): """Create test fixture for TPM3.""" params = { "gene": "TPM3", "chr": "NC_000001.11", "start": 154192135, "end": 154170399, "exon_start": 1, "exon_end": 8, "exon_end_offset": 0, "exon_start_offset": 0, "transc...
75075a328113cf0fe3639139c2f9170e96ae9a47
32,587
def ecg_rsp(ecg_rate, sampling_rate=1000, method="vangent2019"): """**ECG-Derived Respiration (EDR)** Extract ECG-Derived Respiration (EDR), a proxy of a respiratory signal based on heart rate. * Note that this implementation is far from being complete, as the information in the related papers prevents...
d0964b33053edaf124933c762f40c1e403f7dfd7
32,588
def _get_version() -> str: """Returns the package version. Adapted from: https://github.com/deepmind/dm-haiku/blob/d4807e77b0b03c41467e24a247bed9d1897d336c/setup.py#L22 Returns: Version number. """ path = '__init__.py' version = '__version__' with open(path) as fp: for line in fp: if lin...
4811317fc7a22a11b4d074f41afebc7841577ad3
32,589
def find_misparsed_node(section_node, label, change, amended_labels): """ Nodes can get misparsed in the sense that we don't always know where they are in the tree. This uses label to find a candidate for a mis-parsed node and creates an appropriate change. """ candidates = find_candidate(section_node,...
2b6318160b8703dc963335029582f05dece42966
32,590
def degree_corrected_community_generative_model(num_nodes, class_prob, bp_mu, bp_alpha, bp_beta, node_theta, burnin, end_time, n_cores=1, seed=None): """ Degree correct...
7effbf8908ffe8e6b5f1df9ec7c7e52d0f1ce6cb
32,591
from typing import List from typing import Any from typing import Generator def neighborhood( iterable: List[Any], ) -> Generator[Any, Any, Any]: """ """ if not iterable: return iterable iterator = iter(iterable) prev_item = None current_item = next(iterator) # throws StopIteration i...
4d07ee920e4861fce88658b1fc5ce719907ba897
32,592
def grafieken(): """Deze functie maakt grafieken en plaatst ze in de template. :return: de HTML pagina """ top_3_organismen_grafiek() # Functie die grafiek aanmaakt over de database top_10_hoogste_scores() # Functie die grafiek aanmaakt over de database return render_template('grafieken.html')
04dfb1857f0095f135bf2484f738a5db3caf32ed
32,593
import time def path(): """ 传过来给定图片的路径即可,需要绝对路径 :return: :rtype: """ jsonres = request.get_json() #images是图片的路径 image_dir= jsonres.get('images', None) #识别图片的路径 image_file_list = get_image_file_list(image_dir) #把所有的图片的名字,bbox,识别结果放在一个tuple里面返回 images_result = [] for ...
c0b8f4f5df05b3153df24790c03e3904d3550f5a
32,594
from operator import lt def input_pipeline(filenames, experiment_proto, final_mbsz, hps, num_epochs=None, num_threads=1): """Using Queues create an infinite stream of training minibatches. Args: filenames: list of ...
ea5d82b0105fc59201dd2f32b60c3560ad082270
32,595
def mAP(iou_threshold=0.5, threshold=0.01) -> CallbackProtocol: """Build a callback that computes mAP. All kwargs passed to detector.mAP()""" # pylint: disable=unused-argument def callback(detector, summaries, data_dir): return { f"{split}_mAP": round( np.nanmean( ...
9802814db6a9c65648fd338c4b7dad43b60db25e
32,596
from pathlib import Path import time def run_n_experiment(src_path, target_language='es', n_train=2000, n_to_copy=None, eval_tta=False, n_test=3000, do_baseline=True, tta_langs=('et',), **classif_kwargs): """Experiment on smaller version of IMBD with different augmentatio...
52430b993954f8310e06e32466b927626dc8af3b
32,597