content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def build_delete(table, where): """ Build a delete request. Parameters ---------- table : str Table where query will be directed. where: iterable The list of conditions to constrain the query. Returns ------- str Built query. """ sql_q = "DELETE " ...
1f065b5905b6c7af4e19863ae48e228358278f06
32,370
def filter_resources_sets(used_resources_sets, resources_sets, expand_resources_set, reduce_resources_set): """ Filter resources_set used with resources_sets defined. It will block a resources_set from resources_sets if an used_resources_set in a subset of a resources_set""" resources_expand = [expand_...
2ecd752a0460fff99ecc6b8c34ed28782e848923
32,371
def get_index_base(): """获取上海及深圳指数代码、名称表""" url_fmt = 'http://quotes.money.163.com/hs/service/hsindexrank.php?host=/hs/service/' url_fmt += 'hsindexrank.php&page={page}&query=IS_INDEX:true;EXCHANGE:CNSE{ex}&fields=no,SYMBOL,NAME&' url_fmt += 'sort=SYMBOL&order=asc&count={count}&type=query' one_big_i...
4639e94d9412967c0a5403a5e49fc43c8033c40b
32,372
def merge_list_of_dicts(old, new, key): """ Merge a list of dictionary items based on a specific key. Dictionaries inside the list with a matching key get merged together. Assumes that a value for the given key is unique and appears only once. Example: list1 = [{"name": "one", "data": "stuff"...
a56c0b3476ea67d6b77126a34c14005aad345cfa
32,373
from masci_tools.util.schema_dict_util import read_constants, eval_simple_xpath from masci_tools.util.schema_dict_util import evaluate_text, evaluate_attribute from masci_tools.util.xml.common_functions import clear_xml def get_kpoints_data_max4(xmltree, schema_dict, logger=None, convert_to_angstroem=True): """ ...
23001a430e8cb1b2434fce7de67e5249f345806c
32,374
def contains_badwords(string): """ Return whether a string contains bad words """ return any([x in string for x in bad_words])
499e338599441e24845a19ba8504a77bd7838d8e
32,376
def _learn_individual_mixture_weights(n_users, alpha, multinomials, max_iter, tol, val_mat, prior_strength, num_proc): """ Learns the mixing weights for each individual user, uses multiple-processes to make it faster. :param n_users: Int, total number of users. :param alpha: prior (learned through glob...
7ee9020685ec8fc0538ce4695fcefedc6280d55e
32,379
def banana(cls): """ A decorator for a class that adds the ability to create Permissions and Handlers from their Checks. """ cls.__checks = set() # Basically tell checks that we are the class, not a medium to pass things through cls.__banana = True cls_annotations = cls.__dict__.get("_...
6392d5a7e029dca556c92f4d7546fb6f76078858
32,380
def residual_v2_conv( kernel_size: int, stride: int, depth: int, is_deconv: bool, add_max_pool: bool, add_bias: bool, is_train: bool, input_op: tf.Tensor, name: str = None, ) -> tf.Tensor: """Creates a residual convolution in the style of He et al. April 2016. This is the second...
63d7589caed876ed9b0d3617442e6d676555c791
32,381
def dump_cups_with_first(cups: list[int]) -> str: """Dump list of cups with highlighting the first one :param cups: list of digits :return: list of cups in string format """ dump_cup = lambda i, cup: f'({cup})' if i == 0 else f' {cup} ' ret_val = ''.join([dump_cup(i, cup) for i, cup in enumerat...
5fe4111f09044c6afc0fbd0870c2b5d548bd3c1a
32,382
def init(strKernel, iKernelPar=1, iALDth=1e-4, iMaxDict=1e3): """ Function initializes krls dictionary. |br| Args: strKernel (string): Type of the kernel iKernelPar (float): Kernel parameter [default = 1] iALDth (float): ALD threshold [default = 1e-4] iMaxDict (int): Max...
652e0c498b4341e74bcd30ca7119163345c7f2cc
32,383
def prune_scope(): """Provides a scope in which Pruned layers and models can be deserialized. For TF 2.X: this is not needed for SavedModel or TF checkpoints, which are the recommended serialization formats. For TF 1.X: if a tf.keras h5 model or layer has been pruned, it needs to be within this scope to b...
64569464611640ac5c13cbb0bf41c3f7ba16424a
32,384
import re def is_valid_br_cnpj(cnpj): """ Accept an string parameter cnpj and Check if is brazilian CNPJ valid. Return True or False """ # Extract dots, stroke, slash cnpj = re.sub('[.|\-/|/]', '', str(cnpj)) # if does not contain numerical characters if not re.match(r'^\d{14}$',...
f41f9814cfef7d75e287834ac2a5514d03cd8fdb
32,386
def get_supported_locales(): """ Returns a list of Locale objects that the Web Interfaces supports """ locales = BABEL.list_translations() locales.append(Locale("en")) sorted_locales = sorted(locales, key=lambda x: x.language) return sorted_locales
3068889d0c7888b23f207d3397e0aec58418cef2
32,387
from typing import Optional from pathlib import Path import site def get_pipx_user_bin_path() -> Optional[Path]: """Returns None if pipx is not installed using `pip --user` Otherwise returns parent dir of pipx binary """ # NOTE: using this method to detect pip user-installed pipx will return # N...
ccf9b886af41b73c7e2060704d45781938d8e811
32,388
def _normalize_int_key(key, length, axis_name=None): """ Normalizes an integer signal key. Leaves a nonnegative key as it is, but converts a negative key to the equivalent nonnegative one. """ axis_text = '' if axis_name is None else axis_name + ' ' if key < -length o...
9b58b09e70c20c9ac5ee0be059333dd5058802ef
32,389
def create_interview_in_jobma(interview): """ Create a new interview on Jobma Args: interview (Interview): An interview object """ client = get_jobma_client() url = urljoin(settings.JOBMA_BASE_URL, "interviews") job = interview.job first_name, last_name = get_first_and_last_name...
36834c0e6557627a52a179b9d8529d5693cc92cb
32,390
def get_solutions(N, K, W_hat, x): """ Get valid indices of x that sum up to S """ # Scalar form of y = W_hat * x S = scalar(W_hat @ x) # print(f'Scalar value = {S}') solutions = [] for partition in sum_to_S(S, K): if len(set(partition)) == len(partition) and max(partition) < N: ...
6de6b0f77070b40f6e0028009f9b96264f6daa64
32,391
def get_actual_order(geometry, order): """ Return the actual integration order for given geometry. Parameters ---------- geometry : str The geometry key describing the integration domain, see the keys of `quadrature_tables`. Returns ------- order : int If `order...
876c9a70418de7d4768ab0234abb86bf676884c0
32,392
def getcwd(*args,**kw): """getcwd() -> path Return a unicode string representing the current working directory.""" return __BRYTHON__.brython_path
1d0e9491a2a35b326ec87314887fb1dede23c927
32,393
def sample_graph(B, logvars, n_samp): """ Generate data given B matrix, variances """ p = len(logvars) N = np.random.normal(0, np.sqrt(np.exp(logvars)), size=(n_samp, p)) return (np.linalg.inv(np.eye(p) - B.T)@N.T).T
2e798035bcb807e670ff9b9f4a39236ffe6b1157
32,394
def rotate_ne_rt(n, e, ba): """ Rotates horizontal components of a seismogram. The North- and East-Component of a seismogram will be rotated in Radial and Transversal Component. The angle is given as the back-azimuth, that is defined as the angle measured between the vector pointing from the statio...
c374ad762e122b519698bd1c199e2aa773e295cb
32,395
def pwgen(pw_len=16): """ Generate a random password with the given length. Allowed chars does not have "I" or "O" or letters and digits that look similar -- just to avoid confusion. """ return get_random_string(pw_len, 'abcdefghjkmnpqrstuvwxyz' 'ABCDEFGH...
747bb049ad3cca47d3898f0ea6b52108938aa2b2
32,396
import requests from bs4 import BeautifulSoup def get_property_data(sch=""): """Get property id and return dictionary with data Attributes: sch: property id """ property_url = "http://ats.jeffco.us/ats/displaygeneral.do?sch={0}".format(sch) r = requests.get(property_url) property_page = ...
d7a0f462340c75d14f00a1712923988b415258fb
32,398
def tcl_delta_remote(curef): """ Prepare remote version for delta scanning. :param curef: PRD of the phone variant to check. :type curef: str """ remotedict = networkutilstcl.remote_prd_info() fvver = remotedict.get(curef, "AAA000") if fvver == "AAA000": print("NO REMOTE VERSION...
65d1aeb25ce58c066465c3b7eb3e560a54224ba7
32,400
from typing import Iterable def prodi(items: Iterable[float]) -> float: """Imperative product >>> prodi( [1,2,3,4,5,6,7] ) 5040 """ p: float = 1 for n in items: p *= n return p
3b8e52f40a760939d5b291ae97c4d7134a5ab450
32,401
def transformer_prepare_encoder(inputs, target_space, hparams): """Prepare one shard of the model for the encoder. Args: inputs: a Tensor. target_space: a Tensor. hparams: run hyperparameters Returns: encoder_input: a Tensor, bottom of encoder stack encoder_self_attention_bias: a Tensor, con...
af9c5e2ab8fe3508722af822f19671461e92e62d
32,402
from typing import Tuple def get_bottom_left_coords( text_width: int, text_height: int, text_x: int, text_y: int, ) -> Tuple[TextOrg, BoxCoords]: """Get coordinates for text and background in bottom left corner. Args: text_width: Width of the text to be drawn. text_height: Hei...
8cf1f88f98990bb727de86152ea5239b725c0fbc
32,403
def read_gcs_zarr(zarr_url, token='/opt/gcsfuse_tokens/impactlab-data.json', check=False): """ takes in a GCSFS zarr url, bucket token, and returns a dataset Note that you will need to have the proper bucket authentication. """ fs = gcsfs.GCSFileSystem(token=token) store_path = fs.get_map...
f6ac1e149639afbc10af052a288eb6536a43a13a
32,404
import operator def bor(*args: int) -> int: """Bitwise or. Example: bor(0x01, 0x10) == 0x01 | 0x10 Returns: int: Inputs. """ return list(accumulate(args, operator.or_))[-1]
6e40612b0117fef5584857c947910fa4a0fa865f
32,405
from Scikit.ML.DocHelperMlExt import MamlHelper def mlnet_components_kinds(): """ Retrieves all kinds. """ kinds = list(MamlHelper.GetAllKinds()) kinds += ["argument", "command"] kinds = list(set(kinds)) titles = { 'anomalydetectortrainer': 'Anomaly Detection', 'binarycla...
f5a365f2054a263786ca17a96d58d9f39c7061fe
32,406
def hexString(s): """ Output s' bytes in HEX s -- string return -- string with hex value """ return ":".join("{:02x}".format(ord(c)) for c in s)
22c1e94f0d54ca3d430e0342aa5b714f28a5815b
32,410
def hydrate_board_from_model(a, radius, rect_width): """ :type a: ndarray :type radius: int :return: Board """ b = Board(radius) for cellId in b.cells: thid = get_thid_from_cellId(cellId, rect_width) value = a[thid.y][thid.x] b.change_ownership(cellId, get_player_name_from_resource(value), in...
d7486e43beb2676aed32da627d03f018b4b91d65
32,411
from pathlib import Path def tree_walk(): """Walk the source folder using pathlib. Populate 3 dicts, a folder dict, a file dict, and a stats dict. - Returns: - [dict]: k: folders; v: size - [dict]: k: files; v: size - [dict]: 'file_size' 'num_dirs' ...
e7edf9897560ee5d0ddab5344e0993e4185e6009
32,412
def handle_response(response, content_type, file_path=None): """handle response. Extract, transform and emit/write to file""" if content_type == "application/json": if file_path is None: return response.json() else: save_json(response.json(), file_path) elif conte...
43291fdf367f27ee3c982235518d6bf28d600691
32,413
import random def randomCaptchaText(char_set=CAPTCHA_LIST, captcha_size=CAPTCHA_LENGTH): """ 随机生成定长字符串 :param char_set: 备选字符串列表 :param captcha_size: 字符串长度 :return: 字符串 """ captcha_text = [random.choice(char_set) for _ in range(captcha_size)] return ''.join(captcha_text)
ee426c26051e720636659cd013617abce2f77a5e
32,415
def integral_total(Nstrips): """ The total integral. """ return integral_4(Nstrips) + integral_1(Nstrips)
cc2468c69a3e6c98ee139125afc2f4a571cc588b
32,416
def calculate_amplitude(dem, Template, scale, age, angle): """Calculate amplitude and SNR of features using a template Parameters ---------- dem : DEMGrid Grid object of elevation data Template : WindowedTemplate Class representing template function scale : float Scale o...
b286ed97952667052a8ecfacb152b70a7a1be2ba
32,417
from typing import OrderedDict def number_limit_sub_validator(entity_config: OrderedDict) -> OrderedDict: """Validate a number entity configurations dependent on configured value type.""" value_type = entity_config[CONF_TYPE] min_config: float | None = entity_config.get(NumberSchema.CONF_MIN) max_conf...
96c33af5e3764cc6cfe0f355de216945b0ab3920
32,419
from typing import Tuple from typing import Union def patch_2D_aggregator( patches: np.ndarray, orig_shape: Tuple[int], patch_loc: np.array, count_ndarray: Union[np.array, None] = None, ) -> np.ndarray: """ Aggregate patches to a whole 2D image. Args: patches: shape is [patch_num,...
3fd7d98c7b792cb3df646045ad32d0cde2c94e56
32,420
from typing import Callable def vmap_grad(forward_fn: Callable, params: PyTree, samples: Array) -> PyTree: """ compute the jacobian of forward_fn(params, samples) w.r.t params as a pytree using vmapped gradients for efficiency """ complex_output = nkjax.is_complex(jax.eval_shape(forward_fn, params...
411a3ce1a38c31fef9422ed740d1a7d0a4cf887b
32,421
def random_crop_list(images, size, pad_size=0, order="CHW", boxes=None): """ Perform random crop on a list of images. Args: images (list): list of images to perform random crop. size (int): size to crop. pad_size (int): padding size. order (string): order of the 'height', 'wi...
e4e7933a02c356c509bbd3d7dbc54814ec1f7bc1
32,422
from typing import List def normalize_resource_paths(resource_paths: List[str]) -> List[str]: """ Takes a list of resource relative paths and normalizes to lowercase and with the "ed-fi" namespace prefix removed. Parameters ---------- resource_paths : List[str] The list of resource re...
ec7e5020ae180cbbdc5b35519106c0cd0697a252
32,423
def GetDegenerateSites(seq1, seq2, degeneracy=4, position=3): """returns two new sequenes containing only degenerate sites. Only unmutated positions are counted. """ new_seq1 = [] new_seq2 = [] for x in range(0, len(seq1), 3): c1 = seq1[x:...
de9aa02b6ef46cb04e64094b67436922e86e10bb
32,424
def ransac(a, b, model: str ='rigid', inlier_threshold: float = 1.0, ransac_it: int = 100): """Estimates parameters of given model by applying RANSAC on corresponding point sets A and B (preserves handedness). :param a: nx4 array of points :param b: nx4 array of points :param model: Specify the mod...
bbbf3c7695437ef00f4fc4570033575808d84604
32,425
from typing import List from datetime import datetime def create_telescope_types(session: scoped_session, telescope_types: List, created: datetime): """Create a list of TelescopeType objects. :param session: the SQLAlchemy session. :param telescope_types: a list of tuples of telescope type id and names. ...
011a8f3950fd0f4bdd3809085d74c45ae5756716
32,426
from functools import reduce def update(*p): """ Update dicts given in params with its precessor param dict in reverse order """ return reduce(lambda x, y: x.update(y) or x, (p[i] for i in range(len(p)-1,-1,-1)), {})
de7f5adbe5504dd9b1be2bbe52e14d11e05ae86f
32,427
def alphabet_to_use(three_letter_code, parity, direction): """Return tuple of alphabet to be used for glue in given direction on tile of given parity. Note that this refers to the alphabet used for the CANONICAL direction, which may be the opposite of direction.""" if not parity in (0,1): r...
b7bb02d5a5b9d5144ab8a6026600bd16096680aa
32,428
def get_tipranks_sentiment(collection): """ :param collection: "100-most-popular", "upcoming-earnings", "new-on-robinhood", "technology", "oil-and-gas", "finance", "software-service", "energy", "manufacturing", "consumer-products", "etf", "video-games", "social-media", "health", "entertainme...
a6a6527314d2610f20de640aa8e17ad9234d5664
32,429
def lBoundedForward(x, lower): """ Transform from transformed (unconstrained) parameters to physical ones with upper limit Args: x (float): vector of transformed parameters lower (float): vector with lower limits Returns: Float: transformed variables and log Jacobian ...
af3b7613f4b08917c835c51c38b6e506f619ab6a
32,430
from datetime import datetime def date_range(begin_date, end_date): """ :param begin_date: 起始日期,string :param end_date: 结束日期,string :return: dates: 指定日期范围内日期列表,元素类型string """ dates = [] dt = datetime.datetime.strptime(begin_date, "%Y-%m-%d") date = begin_date[:] while date <= e...
e168f291226fa00806992f85b3ac2c89f96b8426
32,431
import collections def createNeighDict(rP, lP, b, c): """Finds the neighbours nearest to a lost packet in a particular tensor plane # Arguments rP: packets received in that tensor plane lp: packets lost in that tensor plane b,c : batch and channel number denoting the tensor plane ...
0b67024dac04678b8cb084eb18312ed8df468d93
32,433
def get_norm_3d(norm: str, out_channels: int, bn_momentum: float = 0.1) -> nn.Module: """Get the specified normalization layer for a 3D model. Args: norm (str): one of ``'bn'``, ``'sync_bn'`` ``'in'``, ``'gn'`` or ``'none'``. out_channels (int): channel number. bn_momentum (float): the ...
2def355c8b775512fec9d58a4fa43a0b54734f96
32,434
import json def cancel_cheque(): """取消支票""" user_id = '96355632' sn = request.values['sn'] result = pay_client.app_cancel_cheque(user_id, sn, ret_result=True) return render_template('sample/info.html', title='取消支票结果', msg=json.dumps({'status_code': result.status_code, '...
6734aa86a1300f678a22b45407a8597255ad0a33
32,435
def to_relative_engagement(lookup_table, duration, wp_score, lookup_keys=None): """ Convert watch percentage to relative engagement. :param lookup_table: duration ~ watch percentage table, in format of dur: [1st percentile, ..., 1000th percentile] :param duration: target input duration :param wp_score: ...
cfecebe5830a7681417d6fbd14485adc6908cb5d
32,436
import dmsky.factory def factory(ptype, **kwargs): """Factory method to build `DenityProfile` objects Keyword arguments are passed to class c'tor Parameters ---------- ptype : str Density profile type Returns ------- profile : `DensityProfile` Newly created object ...
9acb4b93fc3e82e22ec0360a38def9058cea5640
32,437
def r2_score(y, y_predicted): """Calculate the R2 score. Parameters ---------- y : array-like of shape = number_of_outputs Represent the target values. y_predicted : array-like of shape = number_of_outputs Target values predicted by the model. Returns ------- loss : flo...
00e8004f076e8147f70896bd5304cd73c389522e
32,439
def vcg_solve(goal): """Compute the verification conditions for a hoare triple, then solves the verification conditions using SMT. """ assert goal.is_comb("Valid", 3), "vcg_solve" P, c, Q = goal.args T = Q.get_type().domain_type() pt = vcg_norm(T, goal) vc_pt = [ProofTerm("z3", vc,...
9f496edd1a3725640582f4016a086fd5dfe70d72
32,440
def ism_extinction(av_mag: float, rv_red: float, wavelengths: np.ndarray) -> np.ndarray: """ Function for calculating the optical and IR extinction with the empirical relation from Cardelli et al. (1989). Parameters ---------- av_mag : float Extinct...
cb2bba0cbb396fbac900492fe9b49d70646a4255
32,441
def rangify(values): """ Given a list of integers, returns a list of tuples of ranges (interger pairs). :param values: :return: """ previous = None start = None ranges = [] for r in values: if previous is None: previous = r start = r elif r ==...
672b30d4a4ce98d2203b84db65ccebd53d1f73f5
32,442
def load_balancers_with_instance(ec2_id): """ @param ec2_id: ec2 instance id @return: list of elb names with the ec2 instance attached """ elbs = [] client = boto3.client('elb') paginator = client.get_paginator('describe_load_balancers') for resp in paginator.paginate(): for elb ...
b9ad53b7cafdbc44f88044e976a700a187605b2d
32,443
def parse_json_frequency_high(df, column, key): """ Takes a JETS dataframe and column containing JSON strings and finds the highest 'Mode' or 'Config' frequency. Excludes intermediate frequencies Parameters ---------- df : pandas dataframe JETS dataframe column : str ...
e8489ed7bca2357d4be3421932898696daf27bac
32,444
def adapter_checker(read, args): """ Retrieves the end sequences and sorts adapter information for each end. """ cigar = read.cigartuples seq = read.query_sequence leftend, check_in_softl, left_match = get_left_end(seq, cigar, args) rightend, check_in_softr, right_match = get_right_end(seq, ...
096fff89eafe7ce7915daac55e95a2ea51e7f302
32,445
def create_pane(widgets, horizontal, parent_widget=None, compact=False, compact_spacing=2): """Create a widget containing an aligned set of widgets. Args: widgets (list of `QWidget`). horizontal (bool). align (str): One of: - 'left', 'right' (horizontal); ...
f291b6482c8d5bb8ecb312b5f5747cf6c4e36e53
32,446
def image_TOKEN_search_by_word_query_TOKEN(query_snd_ix, multi_distances, snd_fnames, img_fnames, id2pic): """map a word token query into the embedding space and find images in the same space return rank of first neighbor whos...
81fcd8ef466e4712cbab396ed55626e61f297fac
32,448
from packaging import version def _evolve_angles_forwards( mass_1, mass_2, a_1, a_2, tilt_1, tilt_2, phi_12, f_start, final_velocity, tolerance, dt, evolution_approximant ): """Wrapper function for the SimInspiralSpinTaylorPNEvolveOrbit function Parameters ---------- mass_1: float pri...
b4a000db741aab65076ca2257230aaac45634465
32,451
import logging def get_execution(execution): """Get an execution""" logging.info('[ROUTER]: Getting execution: '+execution) include = request.args.get('include') include = include.split(',') if include else [] exclude = request.args.get('exclude') exclude = exclude.split(',') if exclude else [...
dfaba70a41e74423f86eca2c645f71dd2c4117ac
32,452
def fz_Kd_singlesite(K: float, p: np.ndarray, x: np.ndarray) -> np.ndarray: """Fit function for Cl titration.""" return (p[0] + p[1] * x / K) / (1 + x / K)
8054447e87c70adb4d6f505c45336ccd839a69c9
32,453
def show_exam_result(request, course_id, submission_id): """ Returns exam result template """ course_obj = get_object_or_404(Course, pk=course_id) submission_obj = get_object_or_404(Submission, pk=submission_id) submission_choices = submission_obj.choices.all() choice_ids = [choice_obj.id for choic...
e61ffc8748e3a9aa2cb62e4ed277a08f0be05c07
32,454
def createInvoiceObject(account_data: dict, invoice_data: dict) -> dict: """ example: https://wiki.wayforpay.com/view/852498 param: account_data: dict merchant_account: str merchant_password: str param: invoice_data reqularMode -> one of [ ...
0ea61d68916c5b6f43e568cb1978bcb05b8eba04
32,455
from sklearn.cluster import KMeans def _kmeans_seed_points(points, D, d, C, K, trial=0): """A seed point generation function that puts the seed points at customer node point cluster centers using k-Means clustering.""" kmeans = KMeans(n_clusters=K, random_state=trial).fit(points[1:]) return kmean...
7131b53b9cf0c8719daa577f7a03c41f068df90d
32,456
def site_geolocation(site): """ Obtain lat-lng coordinate of active trials in the Cancer NCI API""" try: latitude = site['org_coordinates']['lat'] longitude = site['org_coordinates']['lon'] lat_lng = tuple((latitude, longitude)) return lat_lng except KeyError: # key ['org...
9fefcd3f49d82233005c88e645efd1c00e1db564
32,457
def get_scaling_desired_nodes(sg): """ Returns the numb of desired nodes the scaling group will have in the future """ return sg.get_state()["desired_capacity"]
5a417f34d89c357e12d760b28243714a50a96f02
32,458
def _BitmapFromBufferRGBA(*args, **kwargs): """_BitmapFromBufferRGBA(int width, int height, buffer data) -> Bitmap""" return _gdi_._BitmapFromBufferRGBA(*args, **kwargs)
91fc08c42726ad101e1d060bf4e60d498d1f0b0f
32,459
def get_user_analysis_choice(): """ Function gets the user input to determine what kind of data quality metrics s/he wants to investigate. :return: analytics_type (str): the data quality metric the user wants to investigate percent_bool (bool): determines whether the data will be seen ...
58ebda03cd4eb12c92951649fc946b00eb1a8075
32,460
def points_to_segments(points): """Convert a list of points, given in clockwise order compared to the inside of the system to a list of segments. The last point being linked to the first one. Args: points (list): list of lists of size 2 Returns: [np.ndarray]: 2D-array of segments - ea...
1e560d8e752d34250f73c6e2305c7741a14afe04
32,461
def resnet_v1_34(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, spatial_squeeze=True, reuse=None, scope='resnet_v1_34', **kwargs): """ResNet-34 model of [1]. See ...
26e7d866a14d6a17acf92c10e4c5d48883c6b5c7
32,462
from typing import Union def from_dlpack(x: Union[ivy.Array, ivy.NativeArray]) -> ivy.Array: """Returns a new array containing the data from another (array) object with a ``__dlpack__`` method. Parameters ---------- x object input (array) object. Returns ------- ret ...
c3213a607eb150791e74ffb8a5781e789dcd989f
32,463
def render_webpage_string(vegalite_spec: str) -> str: """ Renders the given Vega-lite specification into a string of an HTML webpage that displays the specified plots. :param vegalite_spec str: The Vega-lite plot specification to create a webpage for. :returns: A string of a webpage with th...
6b9c410046d6aba3b3de04bcb2cce4779f55b3d1
32,464
def _parse_blog(element): """ Parse and return genral blog data (title, tagline etc). """ title = element.find("./title").text tagline = element.find("./description").text language = element.find("./language").text site_url = element.find("./{%s}base_site_url" % WP_NAMESPACE).text blog_...
a2678c0e55a8db5aee042744f1f343c96c7fe6f1
32,465
def summarize_block(block): """ Return the sentence that best summarizes block. """ sents = nltk.sent_tokenize(block) word_sents = map(nltk.word_tokenize, sents) d = dict((compute_score(word_sent, word_sents), sent) for sent, word_sent in zip(sents, word_sents)) return d[max(d.k...
991d389366f0587f7dc7fe2eaf6966d0b531012f
32,466
def get_club_result() -> list: """ Returns the club's page. """ d = api_call("ion", "activities") while "next" in d and d["next"] is not None: for result in d["results"]: if "cube" in result["name"].lower(): return result d = api_call("ion", d["next"], False)
3f335aeb2c476dc29e0d335b00722e5b56eb6716
32,468
def DiffuserConst_get_decorator_type_name(): """DiffuserConst_get_decorator_type_name() -> std::string""" return _RMF.DiffuserConst_get_decorator_type_name()
97c9a68d35b079a1ecbf71a742c6799c4b6411bb
32,469
import tqdm def lemmatizer(): """ Substitutes words by their lemma """ lemmatizer = WordNetLemmatizer() preprocessor = lambda text: [lemmatizer.lemmatize(w) for w in \ text.split(" ")] def preprocess(name, dataset): description = " Running NLTK Lemmatizer - preprocessing dataset " description += "{}..."...
627ce460abb71969ac3f19832f2854a1a00db7c3
32,470
import io def convert_numpy_array(numpy_array: np.ndarray): """ Converts a numpy array into compressed bytes :param numpy_array: An array that is going to be converted into bytes :return: A BytesIO object that contains compressed bytes """ compressed_array = io.BytesIO() # np.savez_compressed...
1fe24003d00736b86361cf5eef03da304edc6bf6
32,471
def notas(* valores, sit=False): """ -> Função para analisar notas e situações de vários alunos. :param valores: uma ou mais notas dos alunos (aceita várias) :param sit: valor opcional, indicando se deve ou não adicionar a situação :return: dicionário com várias informações sobre a situação da turma...
a6915e9b7b1feef0db2be6fdf97b6f236d73f282
32,472
def append_OrbitSection(df): """Use OrbitDirection flags to identify 4 sections in each orbit.""" df["OrbitSection"] = 0 ascending = (df["OrbitDirection"] == 1) & (df["QDOrbitDirection"] == 1) descending = (df["OrbitDirection"] == -1) & (df["QDOrbitDirection"] == -1) df["OrbitSection"].mask( ...
4f2cad6cb2facf6a7a8c7a89ed7b3df0a56a54c2
32,473
def _get_old_time(request): """ Get's the alarm time the user wants to change Args: request (Request): contains info about the conversation up to this point (e.g. domain, intent, entities, etc) Returns: string: resolved 24-hour time in XX:XX:XX format """ old_time_entit...
6a2929ccffb4b397bd9f1dd044e70c871e302e33
32,474
def sxxxxx(p, nss): """ Defines a scalar wavefunction. Input momenta have shape (num events, 4). Parameters ---------- p: tf.Tensor, scalar boson four-momenta of shape=(None,4) nss: tf.Tensor, final|initial state of shape=(), values=(+1|-1) Returns ------- phi: tf.Tenso...
429fe82c9781ec8918fe57a68e899f899df8f32f
32,475
def target_risk_contributions(target_risk, cov): """ Returns the weights of the portfolio that gives you the weights such that the contributions to portfolio risk are as close as possible to the target_risk, given the covariance matrix """ n = cov.shape[0] init_guess = np.repeat(1 / n, n) ...
82d338f2bc8c6b712e7489b70a3122eee21d0aab
32,477
import urllib, datetime import xarray as xr import numpy as np def read_monthly_indices_from_CLIMEXP(name_of_index): """ Try reading various monthly indices from KNMI's Climate Explorer """ name_to_url = { 'M1i': 'http://climexp.knmi.nl/data/iM1.dat', # 1910 -> 'M2i': 'http://clim...
8ea42dbca11e587267ef8e2c13ee1787be9db430
32,478
def generate_xdataEMX(parm): """ Generate the x data from the parameters dictionary Parameters: parm: [dict] parameters Returns: xdata = nd.array[XNbPoints] """ # Extracts the x axis data from the parameter file try: xpoints = parm['SSX'] except KeyError: ...
a65b48e51f5013fe82d0b9baafe70330b15f0477
32,479
import csv def csv_2d_cartesian(filename, polar=False, scan=False): """extract 2d cartesian coordinates from a file""" x_values = [] y_values = [] with open(filename) as data_file: odom_data = csv.reader(data_file) for row in odom_data: # if scan: # row[1] =...
648a8f9bbee8b0b61284bf5a8b93c729bb085c9d
32,480
def get_edge_similarity(node_pos,neighbor_positions): """ useful for finding approximate colinear neighbors. """ displacements = get_displacement_to_neighbors(node_pos,neighbor_positions) n_neighbors = neighbor_positions.shape[0] # Quick and dirty, can reduce computation by factor 2. similar...
b1b64384d84ffbdd6a042b1e2c3a8a9a2212e61e
32,481
def high_pass_filter(x_vals, y_vals, cutoff, inspectPlots=True): """ Replicate origin directy http://www.originlab.com/doc/Origin-Help/Smooth-Algorithm "rotate" the data set so it ends at 0, enforcing a periodicity in the data. Otherwise oscillatory artifacts result at the ends This uses a ...
8a114e1868c28f1de8ee4ac445bd620cb45482ff
32,482
def hyetograph(dataframe, col="precipitation", freq="hourly", ax=None, downward=True): """Plot showing rainfall depth over time. Parameters ---------- dataframe : pandas.DataFrame Must have a datetime index. col : string, optional (default = 'precip') The name of the column in *data...
17deb837058ddd8ad8db9ed47c960cacfde957db
32,483
def objective(z, x): """ Objective. """ return park2_3_mf(z, x)
fb65c09f084b0af8848e78582703a1bb4e11e735
32,484
import json import re def validate_config(crawler_path): """ Validates config """ with open(crawler_path) as file: config = json.load(file) if 'total_articles_to_find_and_parse' not in config: raise IncorrectNumberOfArticlesError if 'seed_urls' not in config: raise I...
ba46667fcc0d75be6b28d19c0f5fa2d41f9123dd
32,485
def parse_FORCE_SETS(natom=None, filename="FORCE_SETS", to_type2=False): """Parse FORCE_SETS from file. to_type2 : bool dataset of type2 is returned when True. Returns ------- dataset : dict Displacement dataset. See Phonopy.dataset. """ with open(filename, "r") as f: ...
54b39f8b111292f53c6231facafb177109972965
32,486
import time def DeserializeFileAttributesFromObjectMetadata(obj_metadata, url_str): """Parses the POSIX attributes from the supplied metadata. Args: obj_metadata: The metadata for an object. url_str: File/object path that provides context if a warning is thrown. Returns: A POSIXAttribute object wi...
3fb3d3f4e45a622cc12ce1d65b6f02d59efd3f58
32,487