content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def diff_left(l1, l2): """ Computes which elements are in l1 but not in l2 :param l1: Array :param l2: Array :return: diff -> Array """ diff = l1.copy() for e2 in l2: for e1 in l1: if e1 == e2: diff.remove(e1) return diff
aceb89661dbcad8b620876d0b34875f0670c190d
47,828
import torch def calc_gradient_penalty(params, d_model, obs_mag, g_out, conditions, true_mag): """Calculate the gradient penalty Args: params: the hyperparameters used for training d_model: the Discriminator model obs_mag: the ground truth observed galaxy magnitudes g_out: the...
169fd37cfe4b02eb4405c0864570d9d83ca1adb1
47,829
def _add_pos1(token): """ Adds a 'pos1' element to a frog token. """ result = token.copy() result['pos1'] = _POSMAP[token['pos'].split("(")[0]] return result
d98893a8b320eabea7af6c2ab2e83ad31ecbcefd
47,830
def check_JR(profile, committee): """Test whether a committee satisfies JR. Parameters ---------- profile : abcvoting.preferences.Profile approval sets of voters committee : set / list / tuple set of candidates Returns ------- bool Reference --------- Aziz,...
f417bdec5818c7ff52ce51c7683dab60eb737ea6
47,831
import re def untokenize(words): """ Untokenizing a text undoes the tokenizing operation, restoring punctuation and spaces to the places that people expect them to be. Ideally, `untokenize(tokenize(text))` should be identical to `text`, except for line breaks. """ text = ' '.join(words) step...
825fb69106e5bf8532ff98c0db0dbc8077fe634b
47,835
def ingest_running(): """ Starts up the fake ingest/metricproxy combo and also adds a write_http config to use that. Yields the final config with write_http configured and the ingest interface """ with fake_backend.run_all() as (ingest, mp_url): def render_config(config): re...
2eb915ff3d190d0bcc28231e475eebbd14e3d13d
47,836
def sexp2tree(sexp): """ Parameters ---------- sexp: list[str] Returns ------- NonTerminal Notes ----- Please note that the input ``sexp'' is assumed to be the raw version in RST-DT. So, if you want to convert a loaded S-expression after preprocessing, please use ``treetk.s...
476ad9833fc8f8bf213146b778a9954ca8e655e6
47,838
def wait_for_pool_ready( batch_client, blob_client, config, pool_id, addl_end_states=None): # type: (batch.BatchServiceClient, azure.storage.blob.BlockBlobCLient, # dict, str, List[batchmodels.ComputeNode]) -> # List[batchmodels.ComputeNode] """Wait for pool to enter steady state a...
8b7af75d32e3b6c29b1edde771bb9d7234c2d901
47,840
def create_adv_inputs(states): """ Create the input for the ADV Net: cab-positions + psng-positions """ # For testing this only works for 2 agents and 2 passengers assert len(states) == 2 assert len(states[0]) == 11 # passengers are the same for all cabs pass1_x, pass1_y = states[0][7],...
ff6f56ab112b71fc636439afb4b72b4858d098eb
47,841
def fizz_buzz(num): """ return 'Fizz', 'Buzz', 'FizzBuzz', or the argument it receives, all depending on the argument of the function, a number that is divisible by, 3, 5, or both 3 and 5, respectively. """ if not isinstance(num, int): raise TypeError("Expected integer as...
8b741800f80ebe631f6821a865c9080c33eb4e27
47,842
def get_bodylength(data, tail_tag: str='', head_tag: str=''): """ get length of mouse body at all frames and avg length""" if not tail_tag or not head_tag: print('Need to have the name of the head and tail bodyparts to extract bodylength from DLC data') return False else: # Calculate...
ca98c4aabcc3a12d25b393888bbda0bf23372ad4
47,843
def get_diagonal_quadface_from_2points(mesh,vi): """ similar to above: get_diagonal_polyline_from_2points from given 2diagonal vertices [iv1,iv3], get the whole diagonal quads [v1,v2,v3,v4] """ H = mesh.halfedges es1 = np.where(H[:,0]==vi[0])[0] es2 = np.where(H[:,0]==vi[1])[0] f1 = H[es...
eb952b6fb632617a22632824d79359be90644a05
47,844
def run_petronia(bus: EventBus, args: UserArguments) -> int: """ Run the actual Petronia program. """ if args.platform: platform_module = get_user_platform_module(args.platform) else: platform_module = get_platform_module() return run_platform_main(bus, platform_module)
145776b898fffd4e2973b270c37bb18dd79fa778
47,845
def weighted_sw_index(matrix, n_avg=1, n_iter=1): """Calculate the weighted small world coefficient omega of a matrix.""" C = weighted_clustering_coeff_z(matrix) L = weighted_characteristic_path_length(matrix) indices = [] for i in range(n_avg): random_graph = random_reference(matrix, n_iter=n_iter) ...
d415cc7be59e2e172d9effc9d4bf5cd2ae2d3b7a
47,846
def dict_to_cvode_stats_file(file_dict: dict, log_path: str) -> bool: """ Turns a dictionary into a delphin cvode stats file. :param file_dict: Dictionary holding the information for the cvode stats file :param log_path: Path to were the cvode stats file should be written :return: True """ ...
4b6d92ad610c47eed5b2e593980a74f617ed44f4
47,848
import re def isNumber(test): """ Test if the string is a valid number Return the converted number or None if string is not a number. """ try: test = str(test) if re.search('\.',test): try: return float(test) except: return N...
93f3afd1c3e8cefc64b1ff738e3f8336a1b8ffd6
47,849
def unskew_S1(S1, M, N): """ Unskew the sensivity indice (Jean-Yves Tissot, Clémentine Prieur (2012) "Bias correction for the estimation of sensitivity indices based on random balance designs.", Reliability Engineering and System Safety, Elsevier, 107, 205-213. doi:10.1016/j.ress.2012.06.010) ...
c82dfb842ff61781a45d132acd66f88ab018690c
47,852
def _inf_time_obs(rho,istate,Obs=False,delta_t_Obs=False,delta_q_Obs=False,Sd_Renyi=False,Srdm_Renyi=False,alpha=1.0): """ This function calculates various quantities (observables, fluctuations, entropies) written in the diagonal basis of a density matrix 'rho'. See also documentation of 'Diagonal_Ensemble'. The f...
006f34861de0494c7771395f70ac0a3336ecba04
47,854
def AnyListItemValidates(list_item_validator): """ Validate that at least one item in the list complies with 'list_item_validator'. """ @wraps(AnyListItemValidates) def _validate(value): if not isinstance(value, list): raise Invalid('expected a list') list_item_sche...
fd0a77b5ae3f66a63f51eea2c7f9bc385e13a88b
47,855
def get_array(pdi, field, name): """Gets an array from a vtkDataObject given its field association and name. Notes: - Point Data: 0 - Cell Data: 1 - Field Data: 2 - Row Data: 6 Args: pdi (vtkDataObject) : the input data object field (int or str) : the field ...
87fd086fa0a94ab1a836e2724862635da454de9d
47,856
from typing import Set from typing import List def power_set(numbers: Set[int]) -> List[Set[int]]: """ Finds all subsets of the given set """ indexed_numbers: List[int] = list(numbers) result: List[Set[int]] = [] result.append(set()) for i in range(0, len(indexed_numbers)): subsets: List[Set[int]] = build_s...
9cd5044c8fba38c2dc0fd1e1f02f84f36c6bd8fa
47,857
import inspect def getBaseObject(object): """Return base object and dropSelf indicator for an object.""" if inspect.isbuiltin(object): # Builtin functions don't have an argspec that we can get. dropSelf = 0 elif inspect.ismethod(object): # Get the function from the object otherwise...
8811c7ac4cfbc9b08c2b7e470289f3b48da480d1
47,858
def split_list(l, break_pts): """returns list l split up into sublists at break point indices""" l_0 = len(l) sl = [] # Return a list containing the input list if no breakpoints indices selected if len(break_pts) == 0: return [l] # Else splits the list and return a list of sub lists. A...
940fe3425e9708e1852fd4930cb5af3e96076b1f
47,859
def repr_dps(n): """Return the number of decimal digits required to represent a number with n-bit precision so that it can be uniquely reconstructed from the representation.""" dps = prec_to_dps(n) if dps == 15: return 17 return dps + 3
c352ee5baefe0dc1e10aa13e85395e880ac68fc4
47,860
def get_builder(regulation, version, inline_applier, p_applier, s_applier): """ Returns an HTML builder with the appliers, and the regulation tree. """ builder = HTMLBuilder(inline_applier, p_applier, s_applier) builder.tree = get_regulation(regulation, version) return builder
fc9530f4c9eeaf8548c2f485a422ac27a08b7a73
47,861
def get_fine_tune_model(symbol, arg_params, num_classes, layer_name, dtype='float32'): """ symbol: the pre-trained network symbol arg_params: the argument parameters of the pre-trained model num_classes: the number of classes for the fine-tune datasets layer_name: the layer name before the last full...
92192a80c7ec92f4e0198f38103bfb53ee21899a
47,862
import asyncio async def async_setup(hass, config): """Load the scripts from the configuration.""" hass.data[DOMAIN] = component = EntityComponent(_LOGGER, DOMAIN, hass) await _async_process_config(hass, config, component) async def reload_service(service): """Call a service to reload script...
4c206b561b559bc91a2d5307958513296dcc9383
47,863
import base64 def aes_decrypt(key, iv, content): """ AES解密 key,iv使用同一个 模式cbc 去填充pkcs7 :param key: :param content: :return: """ cipher = AES.new(key, AES.MODE_CBC, iv) # base64解码 encrypt_bytes = base64.b64decode(content) # 解密 decrypt_bytes = cipher.decrypt(encry...
04feb90a3f30b3c26f287ab0bf89ec8bc7930527
47,864
import requests import time import traceback from bs4 import BeautifulSoup def get_comments(code, sleep=1): """获取股票code的雪球评论 :param str code: 股票代码,如 `600122` :param float sleep: 睡眠时间, 默认值为 1 :return: """ headers = get_header() sess = requests.Session() # 访问首页,获取cookies sess.get(X...
48e64ead34ee9cdfd2c63835d573cbeb1f994324
47,865
def has_same_base_dtype(df_1, df_2, columns=None): """Check if specified columns have the same base dtypes across both DataFrames. Args: df_1 (pd.DataFrame): first DataFrame. df_2 (pd.DataFrame): second DataFrame. columns (list(str)): columns to check, None checks all columns. Retu...
6c9f7acdba47bed0c98c830958573026c4666099
47,866
def upsample(zs, labels, sampling_kwargs, priors, hps): """Upsample given already generated upper-level codes""" sample_levels = list(range(len(priors) - 1)) zs = _sample(zs, labels, sampling_kwargs, priors, sample_levels, hps) return zs
c16c812dc93afc995123d1ddd551195f86f70b26
47,867
def k_12(): """Define the k12 component of permeability tensor.""" return np.zeros((1, 1))
5692054b0ec2e4f8dea7d5b9c039a86cc859ef2f
47,868
def historical_limit(): """max days""" return 90
c152cf6638c46a537aa9659f8435e2d3d7e67baf
47,870
from sage.misc.superseded import deprecation def coxeter_matrix(t): """ This was deprecated in :trac:`17798` for :class:`CartanMatrix`. EXAMPLES:: sage: coxeter_matrix(['A', 4]) doctest:...: DeprecationWarning: coxeter_matrix() is deprecated. Use CoxeterMatrix() instead See http:...
0fda2399c6f49884bc54da6112eb88f57bf183b7
47,872
import gzip def __output_block_mtx(block_cell, nblock, ncell, block_ad_file, block_dp_file, _gzip = 0): """ @abstract Output block-cell AD & DP matrices to mtx file @param block_cell A dict of {reg_idx:{cell_idx:{ad:ad_depth, dp:dp_depth}, }} pairs [dict] @param nblock Number of t...
0d813f72c70047e0f8d12d0447a86a9c2281c861
47,875
def prep_im_for_blob(im, pixel_means, target_size, max_size): """Mean subtract and scale an image for use in a blob.""" im = im.astype(np.float32, copy=False) im -= pixel_means im_shape = im.shape #------------------------------------------------------------- interp_mode = cv2.INTER_LINEAR ...
ecd2f31f83b9c29b3c233d24f2771f31d52d2e5f
47,876
from typing import List def solve(capacities: List, waters: List) -> int: """Solve the question 1. See this module docstring. Parameters ---------- capacities : List the capacities of tankers. waters : List the amount of water in tankers. Returns ------- int t...
31b330373701afeb2a0abbe988ae54e8cfc7ead4
47,877
import csv def class_names_from_csv(class_map_csv_text): """Returns list of class names corresponding to score vector.""" class_names = [] with tf.io.gfile.GFile(class_map_csv_text) as csvfile: reader = csv.DictReader(csvfile) for row in reader: class_names.append(row['display_name']) return cl...
1bfe1690719382990d3ab983042856f5ee68baad
47,879
def np_col_vec (init_list): """Generates a Numpy-compatible column vector.""" return np_row_vec (init_list).T
b39e6b4c0d47aba460113509540a608bcf29cc76
47,880
def _gcd(a, b): """ Return greatest common divisor using Euclid's Algorithm. """ if a == 0: return b if b == 0: return a while b: a, b = b, a % b return abs(a)
2b92f47552285b3f12deb74deb780e660c44d2ab
47,881
def index(request): """renders listing main page""" listings = Listing.objects.all().order_by( '-list_date').filter(is_published=True) paginator = Paginator(listings, 3) page_number = request.GET.get('page') paged_listing = paginator.get_page(page_number) context = { "listings...
acde94fe152bc774e32458ac14130d5fae2cd9ec
47,882
def has_func(obj, fun): """check if a class has specified function: https://stackoverflow.com/a/5268474 Args: obj: the class to check fun: specified function to check Returns: A bool to indicate if obj has funtion "fun" """ check_fun = getattr(obj, fun, None) return call...
3284c1a30c3b74c93c1c34c102632beb99bf5576
47,885
def _make_interp_probe_count_for_dataset_standard_fn(probe_counts, cover_extension_scale=1.0/10): """Generate and return a function that interpolates probe count for a dataset. This operates only on the mismatches and cover_extension parameters. Args: probe_counts: dict giving number of pr...
893bce0e623a95b7a0524bd44ce7f7856ab3d9e1
47,886
import pandas def GenerateSimplePrediction(results, years): """Generates a simple prediction. results: results object years: sequence of times (in years) to make predictions for returns: sequence of predicted values """ n = len(years) inter = np.ones(n) d = dict(Intercept=inter, year...
cb51a096adc7f7d0131c2926b5bf8b2d69aeeb63
47,887
def write_file_on_mismatched_content(desired_content, target, write): """ Write the contents to a new target. The copy is atomic, ensuring that the target file never exists with partial contents. The code avoids writing the file if the contents do not need to be updated. The return value is a boo...
337cdb8c7c87a6ed6a73fbc42618f71dd411a1f0
47,888
import torch def detr_load(): """ Loads the detr model using resnet50 Returns: the detr model pretrained on COCO dataset """ model = torch.hub.load('facebookresearch/detr', 'detr_resnet50', pretrained=True) model.eval() return model
71e20ac9f29ff7211ecb36514758145d929636fc
47,889
def is_string(s): """判断是否是字符串 """ return isinstance(s, basestring)
57ef8bfc2105365aaeda7559264c98fbd9f34437
47,890
def check_if_consistent(dfs, cast_info): """ checks name and types of columns of each dataframes in 'dfs', returns False, in case any one of them if found to be inconsistent, otherwise returns True. """ index_names = np.asarray([df.index.name if df.has_index() \ else No...
ced1f0d191a4366ea9fcf6f5481d810b7200a225
47,891
def _collapse_complexes(data): """Given a list or other iterable that's a series of (real, imaginary) pairs, returns a list of complex numbers. For instance, given this list -- [a, b, c, d, e, f] this function returns -- [complex(a, b), complex(c, d), complex(e, f)] The returned list is a...
4ec889167dbe1ecc2251610f890f21ed18c2db09
47,892
def find_lottery_winner(root: SumTree, lottery_number: float) -> int: """ Find lottery winner index :param root: the root node of the sum tree :param lottery_number: float number in range of 0 to 1 :return: winner wallet index """ search_number = lottery_number * root.sum winner = root....
f0177d69cbe72390396e8daaf4a9de36fb9e4bfa
47,893
def calc_one_dissimilarity_cv(dataset, descriptor, i_des, j_des, method='euclidean', noise=None, weighting='number', prior_lambda=1, prior_weight=0.1, cv_descriptor=None, enforce_same=False): """ ...
5209d9f830733c5d8a213829a0d4672ca6752ee8
47,894
def get_cron_time_samples(start,stop,samples): """Get a comma-separated samples as a string for cron jobs. Keyword arguments: start -- start integer to sample stop -- stop integer to sample samples -- number of samples Returns: string -- comma-separated list of samples from the s...
059002fcd63b58d633c2cdeecd90dc6728b6a4e4
47,895
def round_up_to_odd(f): """round float to the nearest odd integer""" return np.asarray(np.round((f - 1) / 2) * 2 + 1, dtype=np.int64)
3a83dd2e53f12e3415441797a933743bf9c40fb8
47,896
def backend_filter(cls): """ Verify that the type proper subclass of BackendModule. :type cls: type :rtype: bool :param cls: A class object :return: True if match, else false """ return issubclass(cls, BackendModule) and cls != BackendModule
edd05f0a9cdc5f040963a894045d37ec382d6202
47,897
from typing import List from typing import Dict from typing import Tuple def group_force_by_parameter_id( handler_force: openmm.Force, parameters: List[SMIRNOFFParameterType], parameter_map: Dict[str, List[Tuple[int, ...]]], ) -> Dict[str, openmm.Force]: """Partitions the parameters in a force into a ...
e9717708d76a8f4e83137b3baf36d18cea39cfb6
47,898
def find_sol(c, ws, memo): """ Finds an optimal solution for the given instance of the subset sum problem with weight capacity c and item weights ws, provided maximum total weights for subproblems are memoized in memo. """ sol = [] for n in reversed(range(len(ws))): if c >= ws[n] and...
328c6c4d56f9a2f8823c4bd97f4791499cd8ecd3
47,900
from typing import Optional from typing import Callable from typing import cast def atomic(connection_name: Optional[str] = None) -> Callable[[F], F]: """ Transaction decorator. You can wrap your function with this decorator to run it into one transaction. If error occurs transaction will rollback. ...
a30522040dd950081ac1cc2c037f2b83ae8a2c7f
47,901
def get_rectangle_information(form): """ Функция для формирования json с полигоном для отрисовки аналитики по области :param form: форма из POST запроса с координатами области (прямоугольника) и 6 основными фильтрами :return: json с полигоном и необходимой информацией """ rectangle_information =...
443530cbc54769960d1f32b11ae46a1054bd3829
47,902
import math def distance(p0, p1): """calculate distance between two joint/3D-tuple in the XZ plane (2D)""" return math.sqrt((p0[0] - p1[0])**2 + (p0[2] - p1[2])**2)
02e1a1488c32f465f2a1817adb8dfbdb4ea26431
47,903
def cut_traces(cntfile, annotation): """cut the tracedate from a matfile given Annotations args ---- cntfile: FileName the cntfile for cutting the data. must correspond in name to the one specified in the annotation annotation: Annotations the annotations specifying e.g. onsets as we...
5aa78ed4d72835458508204c22c5be17d855c2a4
47,904
import re import click def dict_raise_on_duplicates(ordered_pairs): """Reject duplicate keys.""" d = {} schemaOrg = False for k, v in ordered_pairs: if re.search(r"\s", k): # click.secho(k) click.secho("Please remove the whitespace(s) in property name " + k+ ...
68de1c8f4b6d8d36c90c5b3446f89b67f6fe50d3
47,906
def plot_radar_chart(data, line_labels, var_labels, **kwargs): """Make a radar chart. Input data is assumed to differ in variables along the columns and differ in observations/samples along the rows. Parameters ---------- data: sequence, one- or two-dimensional Data to plot. Must be so...
8e542a6e9c49d7751850b7c38c2dec449a12af54
47,907
def cod_tapcode(mensagem: str, tipo_saida: int) -> str: # Tabela do tap code """Função para codificar em tap code""" tabela: list = [['A', 'B', 'C', 'D', 'E'], ['F', 'G', 'H', 'I', 'J'], ['L', 'M', 'N', 'O', 'P'], ['Q', 'R', 'S', 'T', 'U'], ...
4e88755e976bd24e330432d8242cab872e548eff
47,908
import copy def difference(df, cols, lag=1): """ Perform differencing on some columns in a dataframe. Input: ------ df: pandas dataframe containing the timeseries data. cols: list of strings indicating which columns to difference """ df2 = copy.deepcopy(df) # Difference based on ...
00a7edf9fc49f60736a15099b0ab2db178671dc0
47,909
def regional_indicator(c: str) -> str: """Returns a regional indicator emoji given a character.""" return chr(0x1F1E6 - ord("A") + ord(c.upper()))
9b146ae19e8d41e7c5650c2c08f1c89f1ae7af77
47,910
import random import string def reset_pw(username): """Reset a password""" password_new = ''.join(random.SystemRandom(). choice(string.ascii_uppercase + string.digits) for _ in range(6)) cursor, conn = db_sql.connect('users.db') sql = ("UPDATE user...
817d0df5b1aa460a63e482054db7f2255dada7b1
47,911
def loadSim(simdir, paramname='snapshot.param'): """ Loads a dustydiffusion simulation from a directory. In particular, this requires the runparameters to be saved in the directory. Returns ------- fs : list list of pynbody snapshots eps : fcn Estimate the dust fraction...
7de1bc65901e9d5984f936386748f148164971b1
47,912
def update_event_participant(event_id, participant_id): """Update an event participant's attendance""" if flask.request.method != "PUT": return flask.abort(405) # Return whether they're True or False based on what's in the request body return flask.jsonify({"attended": True})
9abecfad51a3799c09c0879dc297fbb3fa5b9ec0
47,913
def send_test_campaign(c: str = None, e: str = None): """ Send a test campaign """ client = get_client() if not c: global campaign_id c = campaign_id d = {"test_emails": [e], "send_type": "html", "settings": {"subject_line": "Found test"}} r = client.campaigns.actions.test(...
6e2f83a4150bacac608ae054b9e96574be3d5ab8
47,914
import uuid def _CreateFeed(client): """Creates the feed for DSA page URLs. Args: client: an AdWordsClient instance. Returns: A _DSAFeedDetails instance containing details about the created feed. """ # Get the FeedService. feed_service = client.GetService('FeedService', version='v201802') # C...
fc02bc95ac40c192f0aaf60839a01dde234b1448
47,915
def parse_amount_string(amount: str) -> float: """ Parse strings like - '1.000,00-' - '1.000,00 S' - '23,23+' - '23,23 H' to the correct amount as float :param amount: The string of an amount :return: """ # Replace H and S amount = amount.replace("H", "+").repla...
1307f753289b53bcd3f895e2582903064c9125ad
47,916
def custom_implicit_transformation(result, local_dict, global_dict): """Allows a slightly relaxed syntax. - Parentheses for single-argument method calls are optional. - Multiplication is implicit. - Symbol names can be split (i.e. spaces are not needed between symbols). - Functions can be ...
78d9e21cb5531f994fd218ce930d2a114391049f
47,917
def fractal_sda(signal, scales=None, show=False): """Standardised Dispersion Analysis (SDA) SDA is part of a family of dispersion techniques used to compute fractal dimension. The standardised time series is divided in bins of different sizes and their standard deviation (SD) is calculated. The relatio...
530bb7bc960f41d20e59bd20f2887a7f3fff088a
47,919
def _randomize_dyads(network, keep, timeout): """ This function returns a network with the same nodes and edge number as the input network. Each edge is swapped rather than moved, so the degree distribution is preserved. :param network: NetworkX object in tuple, with first item in tuple being network n...
5c9d2fc2be573267329fa66ec7cb79276a6ed9a4
47,920
def reproject(geom, from_proj='EPSG:4326', to_proj='EPSG:26942'): """Project from ESPG:4326 to ESPG:26942.""" tfm = partial(pyproj.transform, pyproj.Proj(init=from_proj), pyproj.Proj(init=to_proj)) return ops.transform(tfm, geom)
808c334bb822f37f71316222b0cf323916e070c2
47,921
def validate_xml(xml_to_check): """ validate the xml of the supplied input :param xml_to_check: bytes object which is the xml to be validated :return: True or False """ try: etree.parse(BytesIO(xml_to_check)) return True except etree.XMLSyntaxError: return False
a12c412f63c77dcab4c6623aae74b7c7805bac2f
47,922
def __scale_width(img, target_width): """__scale_width""" ow, oh = img.size # the size needs to be a multiple of this number, # because going through generator network may change img size # and eventually cause size mismatch error mult = 4 assert target_width % mult == 0, "the target width ...
aeaca67a9dbd2b71e4d62819fb5f4b3f11787edf
47,924
import re def validate_orcid_id(ctx, param, orcid_id: str): """ Check if valid ORCID iD, should be https://orcid.org/ + 16 digit in form: https://orcid.org/0000-0000-0000-0000. ctx and param are necessary `click` callback arguments """ if re.match(ORCID_ID_REGEX, orcid_id): ret...
f63cc8a5e4d753aaae73366ca8414148ade7bf06
47,925
def _get_build_modes_for_base_path(base_path): """ Returns `get_build_modes_for_cell_and_base_path()` for the specified base_path """ return _get_build_modes_for_cell_and_base_path( config.get_current_repo_name(), base_path, )
6409c1846f58dfb0e9a0f8df46b2b6e9caa91d7e
47,927
def unique_chunks(lst, n): """ Returns unique chunks of length n from lst. """ if n < 1: return set() return {tuple(lst[i:i + n]) for i in range(0, len(lst), n)}
e06758a4cb13e42394560e3fe2b4889a8e321af9
47,928
import requests def query_turtle(sparql_query): """ Make a SPARQL query with turtle format response""" data = {'query': sparql_query, 'format': 'text/turtle'} auth = (settings.SPARQL_AUTH_USR, settings.SPARQL_AUTH_PWD) headers = {'Accept': 'text/turtle'} r = requests.post(settings.SPARQL_QUERY_URI...
9f8e8496c2066dbffd2d6b2a10cb830186d53c25
47,929
def predict_note_auth(): """ BANK NOTES AUTHENTICATION This is using DOCSTRING for specifications. ---- parameters: - name : variance in: query type : number required : true - name : skewness in: query type : number required : t...
cb2bdab12d8260fd3521a90998d1b15c4c2cae17
47,930
def mse(predicted, actual): """ Mean squared error of predictions. .. versionadded:: 0.5.0 Parameters ---------- predicted : ndarray Predictions on which to measure error. May contain a single or multiple column but must match `actual` in shape. actual : ndarray ...
ddcd3e3f3f3d8a7ab865db4818ab1f9b49b1430a
47,931
def handler(): """ This function puts into memcache and get from it. Memcache is hosted using elasticache """ #r = redis.Redis( #host='datanode-001.zumykb.0001.use2.cache.amazonaws.com', #port=6379) logging.info('created redis client') queryuserid = sys.argv[1] querylat = float(sys.argv[2]) querylong = flo...
4a4975e1299813d1001f567df9a04e5aef2cf2ed
47,932
def a_view(request): """Regular unlocked view.""" return HttpResponse('A view.')
1552ae02cdead810fb60084ecd0977bab79d2818
47,933
def rotz(ang): """ Create a rotation matrix (3 x 3 np.array) in the 3D space with respect to z axis :param ang: radians. If ang <(>) 0, rotation is (anti-)clockwise with respect to z. :return: Rz: np.array of shape (3, 3) representing the rotation matrix """ Rz = np.array( [ ...
298ea0e62dbcea711cbe980e1adf0ae167a7124a
47,934
from pathlib import Path def fixture_vcf_dir(fixtures_dir: Path) -> Path: """Return the path to the vcf fixtures directory""" return fixtures_dir / "vcfs"
7a77d40a34fc05b7acb20cc60c0e7343ffd4bfa8
47,936
def init_params(units, activations): """Initialize parameters of the model. Arguments: units (list): Each item in the list is the number of units in the layer. units[0] is the number of input units and units[len(units) - 1] is the number of output units. activations (list): Each...
8d66be5bcc08c2ced30c262da788c5336a13f7e1
47,937
def pos_features(df): """ Gets several part-of-speech features: 1) Percentage of nouns and proper nouns. 2) Percentage of proper nouns 3) Percentage of pronouns 4) Percentage of conjunctions Needs features: Tokens N_words Adds features Noun_percent: percentage of no...
efcc4d006a28e71e7f9bfd9d2a1511492ef5ed66
47,938
import functools def no_cache(func): """Decorator to disable proxy response caching.""" def wrapped_function(*args, **kwargs): """Wrapper function to add required headers.""" if flask.request.method == 'OPTIONS': resp = flask.current_app.make_default_options_response() else...
f7ec88763de1a47c83aa88410bb927ce18980319
47,939
def NDArrayEnd(builder): """This method is deprecated. Please switch to End.""" return End(builder)
5dbf92416f8a6b58b8255a54cff88327ed6b00e8
47,940
def calcularPVoto(tVoto, vJogador): """ -> Calcula o percentual de voto de cada jogador que recebeu voto :param tVoto: Quantidade total de votos computados :param vJogador: Quantidade de votos do jagador a ser calculado o percentual Função criada por Jcvendrame """ return (vJogador / tVoto) ...
d21dfc72d70d6a9bdea7d5420cea3a63a57204cf
47,941
def construct_SA1_wavefront(nx, ny, ekev, q, xoff = 0, yoff = 0, mx = 0, my = 0, tiltX = 0, tiltY = 0, xMin = -400e-06, xMax = 400e-06, yMin = -400e-06, yMax = 400e-06): """ Construct a fully-coherent Gaussian source with proper...
2ff67665dfb6b474afc5ded73dcbc804fe7b8b4a
47,942
def check_sudoku_block(board, row, col): """ Check if the Sudoku board is valid. """ board_size = board.shape[0] block_size = int(np.sqrt(board_size)) row_start = row - row % block_size col_start = col - col % block_size gt = set(range(1, board_size + 1)) r = set(board[row_start:(ro...
ca33d815a7743f400ee900efe73c8dbb4a9333b1
47,943
def equalRankin(ranking, other): """Compare two rankings Args: ranking (List<CurrencyUsers>) other (List<CurrencyUsers>) Return: Boolean. True if both ranking are equals. """ if not other or not ranking: return False if len(ranking) != len(other): return ...
351fc60ad18450179d7395f7f88698acfdb2c8d4
47,944
def get_game_range_row_names(game_begin, game_end): """Get the row range containing the given games. Sample row name: g_0000000001_m001 To capture the range of all moves in the two given games, the end row will need to go up to g_00..(N+1). Args: game_begin: an integer of the beginni...
700740131dbd497af8b80832a7ad11960ccc710f
47,945
def calc_QIF(P, T): """ Quartz-Iron-Fayalite (QIF) ========================== Define QIF buffer value at P Parameters ---------- P: float Pressure in GPa T: float or numpy array Temperature in degrees K Returns ------- float or numpy array log_fO2 References ---------- B. R. Frost in Mineralogic...
550d86fb98f21f728b013f503564f5b1237ef9bb
47,946
import math def score_word_count(count: int) -> float: """Score word frequency as log of count with min of 1.0""" return max(1.0, math.log(count))
e49febcac36653a3a188c0ec3edd9cca0c18b81a
47,947
import jinja2 def render(filename, variables): """ Grabs the jinja2 file and renders it :param filename: the jinja2 file to render :param variables: :return: """ with open(filename, 'rt') as f: filename = jinja2.Template(f.read()) return filename.render(**variables)
09fcf7a6966276e2a362f64bfac84dfb5fb1dd0c
47,948
def load_genomes(UTRfilestring, firstStopsCSV, twobitfile): """ make this a separate function so that these only need to be loaded a single time """ UTRdict= rph.readindict(open(UTRfilestring, "rU")) utr3adj = pd.read_csv(firstStopsCSV, index_col=0) genome= twobitreader.TwoBitFile(twobitfile) # do we actually nee...
0a291c0b55e1f868a87a882fe95167ba829ed759
47,949