content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def is_valid(zma): """ is this a valid vmatrix? """ ret = True try: assert _is_sequence_of_quadruples(zma) syms, key_mat, name_mat, val_mat = zip(*zma) automol.create.zmat.from_data(syms, key_mat, val_mat, name_mat) except AssertionError: ret = False return ret
128b5ba429b35400cccd5110ffb2a47a86e85d07
38,065
import json def copy_db_snapshot_instance(source_db_snapshot_identifier, destination_db_snapshot_identifier, snapshot_tags, option_group_name=None, kms_key=None): """Function to create a copy of a rds snapshot, copying tags by default. Args: ...
b7ea3885f87bae18325ea65b3b0766a13ed7f121
38,067
def w_alpha(): """ Real Name: b'W ALPHA' Original Eqn: b'1' Units: b'' Limits: (None, None) Type: constant b'' """ return 1
d76e0dca2ff8c6f01be262272c21fda7bf89d844
38,068
def calc_grad(X, Y, theta): """Compute the gradient of the loss with respect to theta.""" count, _ = X.shape probs = 1. / (1 + np.exp(-X.dot(theta))) grad = (Y - probs).dot(X) return grad
2469a8ce9b993cdf0d778493c358a43a10e90389
38,070
def _docsubst(f): """Perform docstring substitutions""" f.__doc__ = f.__doc__.format(**_doc_snippets) return f
570178ea04a874b14d8a0cbc2e9297ae6c5234a5
38,071
import logging def getSourceListOptDict(parser, wildcards = True): """ Get the list of tuples and the dictionary with options returns: sourceList: a list of tuples with one list element per file the first tuple entry being the root file, the second a list o...
8f478a4bc32abb63ed109047c88593300bcaa582
38,072
def get_capacities(topology): """ Returns a dictionary with all link capacities. Parameters ---------- topology : Topology The topology whose link delays are requested Returns ------- capacities : dict Dictionary of link capacities keyed by link. Examples -----...
0244eb3683139fe8dc77fee7ad9d5a44a109903f
38,073
def make_modbusmap_channel(i, chan, device_type_name): """Make a channel object for a row in the CSV.""" json_obj = { "ah": "", "bytary": None, "al": "", "vn": chan['subTitle'], # Name "ct": "number", # ChangeType "le": "16", # Length(16 or 32) "grp": ...
cd53f32f47653e791893b90bbbf27e540d741268
38,074
def select_variables(n=50): """12 August 2021 Variables excluded: ('cropland', 0.8299824473544954), """ l = [('nlcd', 0.7202826917050348), ('cultivated', 0.6893999449547821), ('slope', 0.36318373989279606), ('evi_3', 0.21911480248421414), ('nw_3', 0.21308324029642675)...
e52199ced0293f80fcb4f6b652fa04abfd20224e
38,076
def CleanData_CB(X,drop_feature): """ This function is to clean the data for training and testing with CatBoost. X : dataframe type for train y : dataframe type for test drop_feature : feature name that is wanted to be dropped , e.g., ['Time'] """ x_new = X.drop...
b6c77e29147dfbdf012f787e29ba4ac364b37fa7
38,077
def add_ind_price_plan(phone_number, ind_price_plan, exp_date=''): """ Adds an Individual Price Plan from the line """ action = 1 result = ModUserIndiPricePlan( phone_number, ind_price_plan, action, exp_date) return result
270f98d0d419559ea1a20869bf6547d3feb6a190
38,078
def EventsAsEOTimes(events): """ :param events: KernelTime's sorted by ktime.start_time_usec :return: """ TimeType = None psec_in_usec = None category_eo_times = np.empty(2*len(events), dtype=py_config.NUMPY_TIME_USEC_TYPE) for i, ktime in enumerate(events): if psec_in_us...
d4d8d878e9929a245ad18ab37ff7d0ff142848fd
38,079
def dct(A): """ params: A matrix Nx1 output: compute dct 1D of the matrix A """ N = A.shape[0] C = np.zeros(N, dtype=np.float64) for k in range(0, N): a_k = np.sqrt(1.0 / N) if k == 0 else np.sqrt(2.0 / N) sum = 0 for j in range(N): sum = sum + A[j] * np...
08429719fe737fc39cabe23d5f33b6c88a01043d
38,080
import logging def get_valid_tax_number_job(request_id: str): """ Route for retrieving job status of a tax number validity from the queue. :param request_id: the id of the job. """ try: raise NotImplementedError() except NotImplementedError: logging.getLogger().info("Could not ...
5a25793b10686833695b0ccdf5e479f6b3c1a0cc
38,081
def all_models(awhere_api_key, awhere_api_secret): """Fixture that returns a dataframe containing all aWhere models. """ # Get all models models = awm.get_models(key=awhere_api_key, secret=awhere_api_secret) # Return crops return models
79050d6706c51c3e197d2c4f835b076a57548a48
38,082
def parse_title(df: pd.DataFrame, source: str, target: str) -> pd.DataFrame: """Transformer extracting a person's title from the name string implemented as wrapped stateless function.""" def get_title(name: str) -> str: """Auxiliary method for extracting the title.""" if '.' in name: ...
d0d6d7b7889c7c794782e16b13a4b4977b854601
38,083
async def __resource_group_exists(clients, args): """ Check if the given Resource Group Exists """ try: await clients.resource_client.resource_groups.get(args.resource_group_name) except ResourceNotFoundError: return False return True
68a60c2bfc593a1b9b3b0d8d3bc1b42a19638cb2
38,087
def dca(freq_table): """ Distinctive Collexeme Analysis Parameters ---------- freq_table : dict A frequency table in the format of: { C1: {L1: freq, L2: freq, ...}, C2: {L1: freq, L2: freq, ...} } where C1 & C2 are labels fo...
ea03bf7589d0a219e521b1eb1b003827fc765fd4
38,088
import torch def get_paddings_indicator(actual_num, max_num, axis=0): """Create boolean mask by actual number of a padded tensor. Args: actual_num ([type]): [description] max_num ([type]): [description] Returns: [type]: [description] """ actual_num = torch.unsqueeze(actu...
0cf2614c2d4ddc35f90a1f6175e9e18eb59298bb
38,089
def create_ffxml_file( gaff_mol2_filenames, frcmod_filenames, ffxml_filename=None, override_mol2_residue_name=None, ): """Process multiple gaff mol2 files and frcmod files using the XML conversion and write to an XML file. Parameters ---------- gaff_mol2_filenames : list of str T...
7e4d00151aa25da765e5f3edb614804c69ae2014
38,090
def get_state_names_and_ids(zfill=False): """"! Get list of federal state names and IDs sorted according to state ID. @param zfill [Default: False] Defines whether state IDs are zero-filled to two digits and returned as a string or returned as an integer. @return List of federal names and IDs sorte...
9605d6bc9f86f225215593cc164734474b28100a
38,091
from typing import Dict def get_api_name(config: Dict[str, ConfigVO] = None) -> str: """ 获取API名字 """ key = const.Key.Api.NAME.value vo = config.get(key) if config else dao.get_config(key) return vo.value if vo and vo.value else const.Key.Api._NAME_WALLHAVEN.value
0c88d57d8c86f32e3cdec67368496458c5fc64be
38,092
import math def agree_within_layers(layer_heights, surface_normal = np.array([0, 0, 1]), cutoff_above_top = None, cutoff_below_bottom = None): """Assign mobile atoms to agreement groups based on their layer in the material. In a system with fixed layers, like a surface slab (especially one with a fixed b...
16fd10a58f2a3b479633e3bc35dd62e6d5a2f303
38,093
def split_indexes(indexes): """Split indexes list like 1 2 5 in 1 2 and 5.""" left, right = [indexes[0], ], [] left_now = True for i in range(1, len(indexes)): prev = indexes[i - 1] curr = indexes[i] if curr > prev + 1 and left_now: left_now = False if left_no...
1bdb3b57226737280b83dbdfa3226dc344eb47c0
38,094
def _build_path(source: Source, fmt: Format) -> str: """ Create the relative path for source and fmt """ return f"{_Path[fmt.name].value}/{source.value}.{fmt.value}"
15e3f17a6d5ceb845eb796c08fbfbde94a021e29
38,095
def handle_button_click(event): """Handles response based on action of 'CARD_CLICKED' Args: event: The 'CARD_CLICKED' being parsed by handler Returns: dict dictionary containing event response """ event_action = event['action']['actionMethodName'] user_data = get_us...
5395519464e042cd69db1e81dd3a3a90cac82a15
38,096
def convolve_functions(fn1, fn2, interval, dt, padding_f=0.1, name=None): """ Convolve fn1 with fn2. Parameters ---------- fn1 : sympy expr An expression that is a function of t only. fn2 : sympy expr An expression that is a function of t only. interv...
6aa1c2cd4d074f0ac40cbd12fb1b069a7034578f
38,099
from typing import Tuple def _plot_seeds(ax, df_da: TfsDataFrame, da_col: str, interpolated: bool) -> Tuple[list, list]: """Add the Seed lines to the polar plots, if df_da is given. Args: ax: Axes to plot in df_da: DataFrame with DA information da_col: Dynamic Aperture column (ALOST1 ...
9be8ff987e931e1de471128a045ffa601be4a9c2
38,100
def sockaddr_convert(val: SockaddrConvertType) -> sockaddr_base: """Try to convert address into some sort of sockaddr""" if ( isinstance(val, sockaddr_in) or isinstance(val, sockaddr_in6) or isinstance(val, sockaddr_storage) ): return val if isinstance(val, IPv4Address): ...
14eaba762bcf1a82752b5c97fa53fcfba345bd95
38,101
def scharr3_dxz( input, output=None, full=True, mode="reflect", cval=0.0): """Scharr 3 point first derivative along the 1st and last (x and z) axis of input. Applies a 3 point Scharr first derivative filter along the 1st and last (x and z) axis of the input array as per: Scharr, 2005: Optimal derivative filter ...
cadbf1421b45f074613cdf9c8dd6a4c6b69deec7
38,102
def forward_hierarchical_differences(graph, weight=None): """Returns the forward hierarchical differences over the edges of a network in the form of a weighted adjacency matrix Parameters ---------- graph : Graph, array A NetworkX graph or numpy/sparse array weight : string ...
becb91a9f535b55d304cc6db9e9f94268c5779d5
38,103
def get_exact_match(user_input, groups): """Return an exact match from the groups """ lower_groups = [group.lower() for group in groups] if user_input.lower() in lower_groups: return groups[lower_groups.index(user_input.lower())]
8d28c05106f308bc3f65e07b011003e968cee99d
38,104
def compute_perc_id(aln): """ Compute percent identity of aligned region on read """ length = len(aln.query_alignment_sequence) edit = dict(aln.tags)['NM'] return 100 * (length - edit)/float(length)
7bc172649a452fc0c26d4e40d3240d709fb76534
38,105
from datetime import datetime def getXRDExpiration(xrd_element, default=None): """Return the expiration date of this XRD element, or None if no expiration was specified. @type xrd_element: ElementTree node @param default: The value to use as the expiration if no expiration was specified in t...
50afee7f3456bfe5441f26879ff50d029a153d8a
38,106
def patient_is_account_owner_with_email(method): """ Verify if patient is a owner of request with email """ def wrap(request, email, *args, **kwargs): is_patient = hasattr(request.user, 'patient') is_owner = email == request.user.email if is_owner and is_patient: retu...
4ac0c4871da98903d4e8977a9de7746836962bbd
38,108
def get_byte_to_char_offset_mapping(text): """Get mapping from bytes positions to unicode code point positions.""" if not text: return {}, {} bytes_per_char = [len(c.encode('utf-8')) for c in text] bytes_per_char_cumsum = np.cumsum(bytes_per_char) char_begin_offset = np.roll(bytes_per_char_cumsum, 1) ch...
4b6f05199bfde789998ab889359d17085ba97d80
38,109
def get_total_time(locations: [str]) -> int: """ Gets the total time required on a trip to all of the given locations :param locations: The locations to get the total trip time for :return: An integer that is the number of minutes required to travel to all the given locations """ response = _get...
615f24f01f6d1c2fd85c3982264b5492dcf771cc
38,110
def sscf(ao_int, scf_params, e_nuc, mode = "minvar", logger_level = "normal"): """ Solve the sigma-SCF problem given AO integrals (ao_int [dict]): - T: ao_kinetic - V: ao_potential - g: ao_eri - S: ao_overlap - A: S^(-1/2) and parameters for SCF (scf_params [dict]): ...
11ddea4ac2f2d5e085f8ce17ea719a2fd420525d
38,111
def fetch_entities(project, namespace, query, datastore): """A helper method to fetch entities from Cloud Datastore. Args: project: Project ID namespace: Cloud Datastore namespace query: Query to be read from datastore: Cloud Datastore Client Returns: An iterator of entities. """ return ...
c157656a60c0854296f7d41a62b09e1631530b1f
38,112
def _add_composite_operator(A: np.ndarray, B: np.ndarray) -> np.ndarray: """Add composite operator. For more information about the add composite operator, see `Cairo Compositing Operators <https://www.cairographics.org/operators/>`_. Args: A (np.ndarray): Source image represented as 4-channel ...
02acc1c7d58393cd4056cfbe9d99ac20ec8c87b7
38,113
def select_user(allow_root=False): """ Have the user select from a list of users with home directories. Args: allow_root - (optional) Include the root user in the list (True or False) """ user_list = get_user_list(allow_root) questions = [ inquirer.List('u', ...
2dea731aeb225df0a0ada60cdee3b0ca01c516ac
38,114
from .task import delete_task import shutil def delete_project(data, workspace): """删除project和与project相关的task Args: data为dict,key包括 'pid'项目id """ proj_id = data['pid'] assert proj_id in workspace.projects, "项目ID'{}'不存在.".format(proj_id) tids = list() for key in workspace....
499cf4d161f9658b6be7b24e3c6abb01783bd9a3
38,115
from datetime import datetime def roundTime(dt=None, roundTo=60): """Round a datetime object to any time lapse in seconds dt : datetime.datetime object, default now. roundTo : Closest number of seconds to round to, default 1 minute. Author: Thierry Husson 2012 - Use it as you want but don't blame me. ...
314408b79196b96dba28fd23bf9656d63ebdb567
38,116
def neighborhood_tally(df_pop, pwmat, x_cols, df_centroids=None, count_col='count', knn_neighbors=50, knn_radius=None): """Forms a cluster around each row of df and tallies the number of instances with/without traits in x_cols. The contingency table for each cluster/row of df can be used to test for enrichments...
0adf685ca0199f0e094d1adf8d38098d1311336f
38,117
def prox_soft_plus(X, step, thresh=0): """Soft thresholding with projection onto non-negative numbers """ return prox_plus(prox_soft(X, step, thresh=thresh), step)
e96aca969d049352de5fe575b98fcda8a80ddb86
38,118
def axisym_u(Rcp, Zcp, r, z, omega_t, epsilon=0): """ Velocity field from distribution of tangential vorticity INPUTS: - Rcp, Zcp: array or control points coordinates, where velocity will be computed - r, z : 1d-array or points where vorticity is defined - omega_t : 2d-array consistent wi...
78c627eceb9b6b2a7cbd960b953c82f2cd748f96
38,119
def Expression(tokenizer, staticContext): """ Top-down expression parser for stylestyles. """ node = AssignExpression(tokenizer, staticContext) if tokenizer.match("comma"): childNode = Node.Node(tokenizer, "comma") childNode.append(node) node = childNode while True...
27dd3670a9623151df49c895c80c974317c836b2
38,120
def generate_guid(entry): """Generate missing guid for post entry.""" return md5sum("|".join(safe_encode(entry.get(key) or "") for key in GUID_FIELDS))
44238ec850d7df74fb5fa0a1430328fb8719fc56
38,121
import re def _validate_defn(value, path, val_type, val_opts): """ Validate a compound type definition. We want to validate a value against a definition like: :: cred_key: one_of: - str: str() - EnvironmentVar: str() - KeyVault: str(...
b3b2bcbfd569b95c33befb84fd6e57b5bc47d0db
38,122
from datetime import datetime def now(timeformat='date'): """ Returns the current time in the specified timeformat. :param timeformat: the target format for the time conversion. May be: '*date*' (default - outputs a ``datetime.datetime`` object), '*unix*' (outputs a long UNIXtime) or '*is...
6d390381adfe63ae4800311ec0c7b26533eccf35
38,123
from pathlib import Path def check_pfam_db(path): """Check if Pfam-A db exists else download Args: path: String, path where to check """ path = Path(path) if path.exists() and not path.is_dir(): raise FileExistsError("Expected directory") if not path.exists(): path.m...
93a5f8cd4d204e68ec32934d269fc55d145a0352
38,124
def geo_dist(point1, point2, units='deg'): """Function returns geographic distance between two points""" return np.linalg.norm(geog2ecef(point1, units) - geog2ecef(point2, units))
94558374ee788ccef29b1a2eeef6e1a21db5ff10
38,125
def prepare_models(encoder_config, transformer_config, replica_batch_size, verbose=0): """This function is used to initiate the Encoder and the Transformer with appropriate configs set by the user. After initiating the models this function returns the Encoder,Transformer and the optimizer. Args: ...
365d0f82d61d88be634cc44fc68b27a6c9dbd0eb
38,126
def part2(): """ >>> part2() 17202899 """ max_value = 50000000 buffer_size = 1 position = 0 current = None step = INPUT for value in range(1, max_value + 1): position = (position + step) % buffer_size + 1 buffer_size += 1 if position == 1: cu...
7a00628e1f4bdfde95f02f03efef55f05191e74c
38,127
import logging def test_default(): """ Example using the default settings """ logger = logging.getLogger(__name__) log_all_levels(logger) log_all_levels_decorated(logger) log_all_levels_loop(logger) return logger
ff49747ec06ff55dc2fa52d6beb75bd04d364a5d
38,128
import re def newsgroups_dictl( data_home="~/scikit_learn_data", to_remove=("headers", "footers", "quotes"), text_key="text", label_key="label", label_mapping=None, ): """ Load the 20 Newsgroups dataset into a list of dicts, deterministically. """ label_mapping = label_mapping or d...
b213014888c116a3fdfe612a42aa1afe21eba38c
38,129
def deg2rad(angle: float): """Convert degree unit to radian unit Args: angle (float): input angle. Returns: float: output angle. Usage: rad_angle = deg2rad(deg_angle) """ return angle * ONE_DIV_180 * PI
e6bcf7e830c85d397c7be45d654b26061d1ad421
38,132
def init_gns_from_files(path): """ Run GNS3 from a given set of router configs, builds GNS3 topology as well as adjacency information and starts all routers in the GNS3 project :param path: path to the configuration files, router configs are located at path/configs/ :return: GNS3 project descriptor ...
7b35446d406b39a7d91c8623223b54b2d19bbb8e
38,133
from typing import Optional from typing import Any from datetime import datetime def parse_evergreen_datetime(evg_date: Optional[Any]) -> Optional[datetime]: """ Convert an evergreen datetime string into a datetime object. :param evg_date: String to convert to a datetime. :return: datetime version of...
33fd432a361db73b5a3d2f391a5be9bf4f0e7836
38,135
def dateToQuarter(string): """takes a string of the type YYYY-MM and converts it to YYY-QN basically from month to quarter""" y,m = string.split('-') return y + '-' + QUARTER_MAP[int(m)]
f8e767cc8784cd15135911e7a464b67079973633
38,136
from typing import Optional def get_main_container_network() -> Optional[str]: """ Gets the main network of the LocalStack container (if we run in one, bridge otherwise) If there are multiple networks connected to the LocalStack container, we choose the first as "main" network :return: Network name ...
6e67904bcf43e2b888f76cd7fadd51080a77bcf2
38,137
def tri3_Bmat(zi_px, zi_py): """ Computing the B-matrix for a 3-node beam element :param list zi_px: partial derivative of zeta with respect to x :param list zi_py: partial derivative of zeta with respect to y :return: B-matrix for a 3-node element """ B = np.matrix([ [zi_px[0],...
5532d3dabadbb49462c2a500ed87cbc55b6e3e25
38,138
def fixedcase_prefix(ws, truelist=None, phrase_truelist=None): """Returns a list of 1 or more bools: True if some prefix of the tuple 'ws' should be fixed-case, False if not, None if unsure.""" # phrase_truelist is sorted in descending order by phrase length if phrase_truelist is not None: for n...
8a20b4b9eda4261b57004c94b9756caf871af077
38,139
def pipeline_dict() -> dict: """Pipeline config dict. Updating the labels is needed""" pipeline_dict = { "name": "german_business_names", "features": { "word": { "embedding_dim": 16, }, }, "head": { "type": "TextClassification"...
9505692f13759f392b930dff33ecf7ff781dcd9c
38,140
def isadmin(ctx): """Checks if the author is an admin""" if str(ctx.author.id) not in config['admins']: admin = False else: admin = True return admin
65c3039ced98ea2468afacc8e14b9c1e41c8ea38
38,142
def get_name_from_filename(filename): """Gets the partition and name from a filename""" partition = filename.split('_', 1)[0] name = filename.split('_', 1)[1][:-4] return partition, name
606cfcc998c4a8405c9ea84b95b2c63f683dd114
38,143
def threshold(threshold, utilization): """ Static threshold-based underload detection algorithm. The algorithm returns True, if the last value of the host's CPU utilization is lower than the specified threshold. :param threshold: The static underload CPU utilization threshold. :type threshold: fl...
76882479754a4b8dfaed6e6dff611b2ed0f59890
38,144
def process_html(html_page, this_parser): """ extract links from an html page """ this_parser.feed(html_page) return { "int_links": this_parser.int_links, "ext_links": this_parser.ext_links, "static_links": this_parser.static_links }
abd380ae2738bb98fdab4b5026d5cb9bdaa76efa
38,145
def sync_execute_run_grpc(api_client, instance_ref, pipeline_origin, pipeline_run): """Synchronous version of execute_run_grpc.""" return [ event for event in execute_run_grpc( api_client=api_client, instance_ref=instance_ref, pipeline_origin=pipeline_origin, ...
f81995b609e8dbd1a91b3defb80d888b729c54c0
38,146
def random_cutout_color(imgs, min_cut=10,max_cut=30): """ args: imgs: shape (B,C,H,W) out: output size (e.g. 84) """ n, c, h, w = imgs.shape w1 = np.random.randint(min_cut, max_cut, n) h1 = np.random.randint(min_cut, max_cut, n) cutouts = np.empty((n, c, h, w), ...
8861526bd34e40794d78c3aea4c341eb84dc648b
38,147
import spack.repo import spack.spec def _unknown_variants_in_dependencies(pkgs, error_cls): """Report unknown dependencies and wrong variants for dependencies""" errors = [] for pkg_name in pkgs: pkg = spack.repo.get(pkg_name) filename = spack.repo.path.filename_for_package_name(pkg_name)...
99bdfd70fe4c4d3308bef70fcc1d65a83ba8ecce
38,149
def bbox_transform(boxes, deltas, weights=(1.0, 1.0, 1.0, 1.0)): """Forward transform that maps proposal boxes to predicted ground-truth boxes using bounding-box regression deltas. See bbox_transform_inv for a description of the weights argument. """ if boxes.shape[0] == 0: return np.zeros((0, deltas.shape[1]), ...
4397e8e837c4efb6d1338224b47ebb8876cdea8d
38,150
def _get_crop(cytomine, image_inst, geometry): """ Download the crop corresponding to bounds on the given image instance from cytomine Parameters ---------- cytomine : :class:`Cytomine` The cilent holding the communication image_inst : :class:`ImageInstance` or image instance id (in...
11f541ef7f5ef95b5e251c2ef1a8b23d51fb2651
38,151
def authorship_below_random_chance(X, classifier, numAuthors): """See if the user's document features fool the classifier """ randomChance = 1 / numAuthors authorProb = classifier.predict_proba(X) print("User probability: ", authorProb[0][0]) print("numAuthors: ", numAuthors) print("Highest ...
aff15247e338c99306fffd442a90ce85d58879c0
38,152
def fnr_func_multi(threshold, preds, labels): """False rejection rate or False negative rate.""" return tf.reduce_sum( tf.multiply(tf.cast(tf.less_equal(preds, threshold), tf.float32), labels), axis=0) / tf.reduce_sum( labels, axis=0)
4989e23bc697c56c616b2841eb4f53968267d6f6
38,153
def queue() -> RedisQueue: """An empty queue""" q = RedisQueue('localhost', topics=['priority']) q.connect() q.flush() return q
5c789167729dad241f2ac4e4556953a20f9820cd
38,154
import aiohttp import asyncio async def determine_building_main(dct_lst: list): """Async cadastre units' building main :param dct_lst: dictionary to be used :return: cadastre units w/ buildings and without """ connector = aiohttp.TCPConnector(limit=c.MAX_CONNECTIONS) async with aiohttp.Client...
1b3ac451504c3b5ae73826d611ae3fe26567b08d
38,155
def pre_tax(sale): """ Args: sale: 持股平台减持价格(元/股) Returns: 需交纳税金 """ return income_tax(income(pre_price, options)) + cap_tax(all_option(options) * (sale - pre_price))
d9a1be1d6072c92681ca09307714dacd107f5fde
38,156
def _offset_to_boxes(F, center, pred, stride, transform="minmax", **kwargs): """ Change from point offset to bbox. :param center: the initial points center :param pred: the predicted point offsets :param stride: the stride of the offsets :param transform: the transform from points to bbox: "minmax",...
8d0c88ce7f3b5fff13628108babff6c2836b48a9
38,157
def poll_lldp_neighbors(dut, iteration_count=180, delay=1, interface=None): """ Poll for LLDP Neighbours Info Author: Prudvi Mangadu (prudvi.mangadu@broadcom.com) :param dut: :param iteration_count: :param delay: :param interface: :return: """ i = 1 while True: rv = g...
d1decfd8b4cc6a66cac493a25a646b460526a100
38,158
def GetForegroundControl(): """return Foreground Window""" return ControlFromHandle(Win32API.GetForegroundWindow()) #another implement #focusedControl = GetFocusedControl() #parentControl = focusedControl #controlList = [] #while parentControl: #controlList.insert(0, parentControl) ...
b74832c235a11f53a032ff0c5a095d54d25a91ad
38,159
import torch def _set_device(disable_cuda=False): """Set device to CPU or GPU. Parameters ---------- disable_cuda : bool (default=False) Whether to use CPU instead of GPU. Returns ------- device : torch.device object Device to use (CPU or GPU). """ # XXX we might ...
1d7d448dd4e4a844201b73c8da4939009e70eb5f
38,160
def adaptive_thres(img, FIL1=10, R1=100): """adaptive thresholding for picking objects with different brightness. """ bw = adaptive_thresh(img, R=R1, FILTERINGSIZE=FIL1) return label(bw)
a4903a150512f38fb2cce1ad7e430c6791fecad1
38,161
def two_way_skar_bounds(dist, rvs, crvs, rv_mode=None): """ Iteratively compute tighter bounds on the two way secret key agreement rate. Parameters ----------- dist : Distribution The distribution of interest. rvs : iterable The indices to consider as X (Alice) and Y (Bob). ...
eff69eb2c14e6479bd858914e126ae6c4270ba17
38,162
from pathlib import Path import yaml import json def print_results_from_evaluation_dirs(work_dir_path: Path, run_numbers: list, print_results_only: bool = False) -> None: """Print the aggregated results from multiple evaluation runs.""" def float_representer(dumper, val...
4be2d893da5f321390c4b49cd4283c0b6f98b4d5
38,163
def clear_crontab(owner: Owner) -> Result[Unset]: """ Clear the owning user's crontab, if one exists on the current server. """ if not get_crontab(owner): return Result(State.unchanged) command(["/usr/bin/crontab", "-u", owner_name(owner), "-r"]) return Result(State.success)
df8d46c7a8af3d482403209c3e99c3ac1fd27660
38,164
from datetime import datetime def get_stats_by_month(session, datetime_column, months, autofill=True): """获取月统计数据 :param session: db.sessoin :param datetime_column: ORM Column :param months: int, 用负数表示过去的月数 :param autofill: bool, 是否自动填充没有的数据 """ first_day, last_day = get_first_day_and_las...
8c5dacc56f5987860097bab35990a5893a13a170
38,165
import asyncio async def start_game(game_params: GameParams): """ Method used to create game instance with given parameters :param game_params: GameParams object with integer how_many_cards and list of strings with players_names :return: integer value of game_id """ game_state = game.GameState...
49422ae7892b060d96622af28a4fe7fb591aa528
38,166
def infer_Tmap_from_clonal_info_alone( adata_orig, method="naive", clonal_time_points=None, later_time_point=None, selected_fates=None, ): """ Compute transition map using only the lineage information. As in :func:`.infer_Tmap_from_multitime_clones`, we provide two modes of inference: ...
06509556bb82ddd80c8bf83bbc2e77013b69bb3d
38,167
def evaluate(input_data, predicted_output): """The function computes the accuracy for each of the datapoints that are part of the information extraction problem. Args: input_data (list): The input is a list of dictionary values from the isda json file predicted_output (list): This is a list...
9975e355a519c802773a39753b2bb36562590325
38,169
def blockInhalfSpace(conds): """ Returns a block in a halfspace model based on the inputs""" M, freqs, rx_loc, elev = getInputs() # Model ccM = M.gridCC # conds = [1e-2] groundInd = ccM[:, 2] < elev sig = simpeg.Utils.ModelBuilder.defineBlock( M.gridCC, np.array([-1000, -1000, -1500...
cc9194f7fda5246c934665514282cfce44714e4b
38,170
def build_generator(input_shape=(256, 256, 3), ngf=64, kernel_size=4, strides=2): """U-Net Generator""" image_input = Input(shape=input_shape) n_channels = input_shape[-1] # encoding blocks e1 = Conv2D(ngf, kernel_size=kernel_size, strides=2, padding='same')( image_inpu...
0a01b6a9bd0e1fb7c1391e9cf59974c39384274d
38,171
import random def randomize(img, noise_level=.03): """ given an array, randomizes the values in that array noise_level [0,1] controls the overall likelihood of a bit being flipped. This overall level is then multiplied by the levels variable, which modifies the noise level for the various...
1741413566f05c2759ff9dc7fa83fee56a59c138
38,172
def load_time_dependent_dataset(filename, cache=False, record_zero_counts=True): """ Load time-dependent (time-stamped) data as a DataSet. Parameters ---------- filename : string The name of the file cache : bool, optional Reserved to perform caching similar to `load_dataset`. ...
e3c2804ca7dc4f0c8951c3ec2d642e862263617d
38,173
def Log_SetTraceMask(*args, **kwargs): """Log_SetTraceMask(TraceMask ulMask)""" return _misc_.Log_SetTraceMask(*args, **kwargs)
3ae4c102ffab43d9e5122840decbf8f00dba1885
38,174
def find_max_burst(burst_list: list, offset_start, offset_end): """[summary] Args: burst_list (list): [description] offset_start ([type]): [description] offset_end ([type]): [description] Returns: [type]: [description] """ burst_levels = set() burst_lev...
75a15acf96324cafc806a1664e89054f6ade74d2
38,175
def center_text(baseline, text): """Return a string with the centered text over a baseline""" gap = len(baseline) - (len(text) + 2) a1 = int(gap / 2) a2 = gap - a1 return '{} {} {}'.format(baseline[:a1], text, baseline[-a2:])
c5683198cf1f28a38d307555943253bd71fe76de
38,176
def _find_executable_linenos(filename): """ A re-implementation of trace.find_executable_linenos working around compile's problems with missing EOLS """ try: prog = open(filename, "rU").read() except IOError, err: print >> sys.stderr, ("Not printing coverage data for %r: %s" ...
1a52a7511147ab3c1c5acd2295c846d8b874309e
38,177
def dict_allocations(dojo): """ input: dojo returns a dict of allocations """ rooms = list(dojo.office) + list(dojo.livingspace) # makes a dictionary, allocation with key-> roomname: -> value(occupants) allocations = {room.name: people_inroom(dojo, room.name) for room in rooms} return al...
7455f4bfa3686e0aed3d2ba2f75ac813e18c5f69
38,178
from functools import reduce def variance(lA): """ compute the variance elementwise of this list of arrays """ n = len(lA) sX = reduce(np.add, lA) sX2 = reduce(np.add, [A*A for A in lA]) s2 = (sX2 - sX*sX / n) / (n-1) return s2
2c94444f690459817e763cbbbf65af415ac2fdf0
38,179