content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_chord_arpeggio(chords_duration, notes_list, density): """ コードをアルペジオで弾く場合のリズムと音を決定 Parameters chord_duration: int/float そのコードを継続する時間 0.5→1拍 notes_lsit: list[int] コードの構成音 density: 0 or 1 0: 密度低め 1: 密度高め Rerturns list(tuple(int, int/float)...
fb716d6204bc956288a863bbcd5cbbaa68cdddf6
3,596,629
def get_p_val(rank_table): """ Input: """ r = 1-rank_table["rank"]*1./(rank_table["out_of"]+1) r.sort() r.name = "p_value" return r
387b819f1a028e42bedd301e2324c0b25c159ca8
3,596,630
def shift_tokens_right(input_ids, pad_token_id, decoder_start_token_id): """ Shift input ids one token to the right. """ shifted_input_ids = input_ids.new_zeros(input_ids.shape) shifted_input_ids[:, 1:] = input_ids[:, :-1].clone() shifted_input_ids[:, 0] = decoder_start_token_id assert pad_...
c25ba549849d3781f9a03f2c25cb8c9277c201b2
3,596,631
def CasadiMeta_git_describe(*args): """ git_describe() -> char const * """ return _casadi.CasadiMeta_git_describe(*args)
d47809e0b7a627fd3831a3e71d66229e74e4c052
3,596,632
def index(request): """ 总览 :param request: :return: """ return render(request, 'overview.html', {'active_nav': 'overview'})
f9bbb5b8a5c11b01f78d90c273f263600ae75951
3,596,633
def delete_page(): """ Delete instruction document page """ return event_handler_for(request).get_response()
b71a8a124af272c0bf9ab6f8c0f0fdc5ce50bd58
3,596,634
def free_space_path_loss(freq: float, distance: float) -> float: """Calculate free-space path loss Standard formula, also known as (one of) the Friis formula(e). Args: freq: A `float` with the frequency of the transmitter. Unites are GHz. distance: A `float` with the path len...
a4cd466c27b5f6c024247413aeda2f5105803e00
3,596,635
from re import VERBOSE def migrate(engine_from, engine_to, tables, chunk_size=DEFAULT_CHUNK_SIZE, collation=None, create=True, drop=False, fill=True, filtering_cols=None, filtering_row=None, mssql_from=DEFAULT_DB_MSSQL, mssql_to=DEFAULT_DB_MSSQL, schema=DEFAULT_SCHEMA, test=ASSERT,...
ee83cc8cc23e421546ac00d8e99dd35734bba43b
3,596,637
def next_child(license): """Return the node defined at the top of the given license. A node object is returned. """ nchild, nmeta = license[:2] if nchild == 0: return Node([], license[2:2+nmeta], 2+nmeta) children = [] index = 2 for _ in range(nchild): child = next_child...
78db559221257ec7d243f809751a015f11ce62d2
3,596,638
from typing import Optional import math def viewer( structure: Structure, show_unitcell: bool = True, show_bonds: bool = True, show_outside_bonds: bool = False, show_polyhedrons: bool = True, local_env_strategy: Optional[NearNeighbors] = None, show_magmom: bool = False, magmom_scale: f...
96ec2ee0fa46940c69a3b7ca39931096723ff58d
3,596,639
def _complexity_delay_entropyratio( signal, delay_max=20, dimension_max=5, surrogate_n=5, surrogate_method="random", show=False, ): """Joint-optimization using Entropy Ratio method. * Gautama, T., Mandic, D. P., & Van Hulle, M. M. (2003, April). A differential entropy based method...
ef7bcfcff7418b20e6e7c75efd60d2cef8e62dc8
3,596,640
def _change_galician_cc_token_before_subtree(sentence, token): """Determine the token directly preceding a subtree in a sentence. Args: sentence (`Sentence`): The sentence. token (`Token`): The root token of the subtree. Returns: str: The ID of the token directly preceding the root token and all of its dep...
21eebf0ba9ec02af4a7c65e8631a95e83b68372e
3,596,641
def home_add(request, item_container): """ neues Home-Verzeichnis anlegen """ class DmsItemForm(forms.Form): name = forms.CharField(max_length=60, widget=forms.TextInput(attrs={'size':20}) ) app_name = 'home' my_title = _(u'Home-Verzeichnis anlegen') # --- Sind Daten vorha...
0aecc3b5b4a649fd1dfd40a6ee80409e534f90d0
3,596,642
import torch def get_jacobian(inputs, func, **kwargs): """ Return Jacobian matrix of size m x n of a function f: R^n -> R^m """ size = inputs.size() n = size[0] # Input dim if (len(size)) > 1: dim_input = size[1] else: dim_input = 1 test = func(inputs, **kw...
5ff764a11512ed3813956c7549562761b430092f
3,596,643
def get_active_users_this_semester() -> int: """ Count the number of users registered for at least one course this semester :return: The number of users registered for at least one course this semester """ return ( User.query.join(InCourse, User.id == InCourse.owner_id) .join(Course...
2192a61b4e3cd1a220c4839f58e7321caee2327c
3,596,644
def get_headers(file_path): """ Gets the headers. :param file_path: File path. :return: Headers. """ h = Headers() h.add('Content-Disposition', 'attachment', filename=file_path) return h
ba9301052e34370c6c090922f9ff11f6a42a8fb7
3,596,645
from typing import Callable from typing import Union from typing import List import random def padding(policy="random"): """ Overview: Fill the nested buffer list to the same size as the largest list. The default policy `random` will randomly select data from each group and fill it int...
9cd15bb122485cbcc7c5cde4c9660b7b019285f1
3,596,646
def generate_create_simulations_result_table_sql(): """ Generates an SQL statement to create a table on the database where the results of the simulations are stored. It uses the output params file defined by the user to define the schema of the table. All the columns representing an output parameter...
d2e7a115257fd1ae325ce9bfae0b5a31835e77ca
3,596,647
def write_series(all_series: str, number: int, issn: str) -> str: """ Write series information to XML snippet. :param all_series: A string containing 1+ series separated by || double pipes. Series number information, if provided, is separated by ; colon. :param number: An int or np.nan containing serie...
b9499d6f88f6db171dbb17ad653bc612e1cdf7c7
3,596,648
import torch def explained_variance(ypred,y): """ FROM: Open AI Baselines Computes fraction of variance that ypred explains about y. Returns 1 - Var[y-ypred] / Var[y] interpretation: ev=0 => might as well have predicted zero ev=1 => perfect prediction ev<0 => worse t...
e7220bbbdcf8a3918bc9f63aa6817470fd4ad160
3,596,649
from typing import Optional import array def z_snapshot(state: State, contraction_options: Optional[dict] = None) -> array: """ <state| S^z | state> for all positions of S^z """ if contraction_options is None: contraction_options = {} return expval_snapshot(state, sz, hermitian=True, **con...
51450255436086deae09e1e182bdce6049c97bd3
3,596,650
def turn(p1, p2, p3): """ 0 if the points are colinear 1 if the points define a left-turn -1 if the points define a right-turn """ # Compute the z-coordinate of the vectorial product p1p2 x p2p3 z = (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p2[1] - p1[1]) * (p3[0]- p1[0]) return 0 if z == 0 e...
2b8dccbe0111d9cd655f4a6a8bc2131b73f3a3ee
3,596,651
from typing import List from typing import Tuple def get_edge_colours_and_widths(graph: nx.Graph, path: List[Tuple[int, int]]) -> Tuple[List[str], List[int]]: """ Get properties for plotting the graph. When using networkx's graph visualization tool it is possible to customize the colour and width of ...
903644696d59a35b86674d4ef2c394547d68f4ea
3,596,652
def discriminator_output_class(input_net, class_num): """Output Layer for Domain Classification in the Discriminator. The original paper use convolution layer where the kernel size is the height and width of the Tensor. We use an equivalent operation here where we first flatten the Tensor to shape (batch_size,...
bf746e3a6e9e4ac18af5ccf15406af86a9bed6e0
3,596,653
def sign( data, pkey_buffer, pkey_pass=_ffi.NULL, digest_name="sha1"): """ Sign data with private key. Returns binary signature :param unicode data: Data to sign :param bytes pkey_buffer: Private key :param unicode pkey_pass: Private key's passphrase :param str digest_name: Message dige...
b4fabdd7daca63bb8c2b77534b5e4e512a444a31
3,596,654
def change_point_score(distances, window_size): """ Gives the change point score for each time stamp. A change point score > 0 indicates that a new segment starts at that time stamp. Args: distances: postprocessed dissimilarity measure for all time stamps window_size: window size used in TD for CPD...
6f631306d25ff0b88c45a06bfdce7a0558620e95
3,596,655
def gentorque(x, p): """ INPUTS: x: generator or rotor speed p= (RtGnSp, RtTq , Rgn2K , SlPc , SpdGenOn) RtGnSp Rated generator speed for simple variable-speed generator control (HSS side) (rpm) RtTq Rated generator torque/constant generator torque in Region 3 for simple variable-spee...
a600dbddeb232cfaef9286a2c6b8a089f1511872
3,596,656
def make_sample_her_transitions(replay_strategy, replay_k, reward_fun): """ Creates a sample function that can be used for HER experience replay. :param replay_strategy: (str) the HER replay strategy; if set to 'none', regular DDPG experience replay is used (can be 'future' or 'none'). :param r...
8351e28710c845833e147c2d2dc69e56c6d33795
3,596,657
def bjmm_depth_3_complexity(n, k, w, mem=inf, hmap=1, memory_access=0): """ Complexity estimate of BJMM algorithm in depth 3 [MMT11] May, A., Meurer, A., Thomae, E.: Decoding random linear codes in 2^(0.054n). In: International Conference on the Theory and Application of Cryptology and Information Sec...
11e6596c71cb995e123808699f4a77324589ae42
3,596,658
import asyncio async def collect_regions_prices(config: Config, regions: list[Region]) -> Box: """Get the current prices for multiple regions.""" prices_tasks = [awattprice.prices.get_current_prices(region, config, fall_back=False) for region in regions] regions_prices = await asyncio.gather(*prices_tasks...
c264179cd0d25a75e40b581252521bf984c31f42
3,596,660
def decode_bboxes(score_thresh, scores, bboxes, anchors, scale=128, best_only=False): """ wi, hi : NN input shape mediapipe/calculators/tflite/tflite_tensors_to_detections_calculator.cc # Decodes the detection tensors generated by the model, based on # the SSD anchors and the specification in the op...
a1a31c8aefd40b14554de273020d1a68e137fceb
3,596,661
def calcExpEntropy(data, feature): """ Calculate the expected entropy from splitting on the specified feature. Note: it's not guaranteed that we check all possible features--we only iterate over those feature values encountered in the data. That's okay since a feature with 0 frequency would ...
2d1628ca970c49397a21abc23fe1c746a9b7eb83
3,596,662
def get_abs_rel_destination_path(dst_root, src): """Obtain absolute path from a proto file path combined with destination root. Creates the parent directory if necessary. Args: dst_root: destination root path. src: source path. """ rel_dst_path = get_destination_path(src) dst =...
f1a3c0da2d4c68eb4cbf8f721b16b4fd37832322
3,596,663
def find(node): """Find current canonical representative equivalent to node. Adjust the parent pointer of each node along the way to the root to point directly at the root for inverse-Ackerman-fast access. """ if node.parent is None: return node root = node while root.parent is not ...
c9827af585c2bcd284640213bb92ae951659abf8
3,596,664
def is_a_shape(node): """ Checks node type to determine if the given node is a shape or not :param node: str :return: bool """ if not maya.cmds.objectType(node, isAType='shape'): return False return True
fb3590010a22a920004973f578d120a4860fc554
3,596,665
from datetime import datetime import requests import json def promapi(): """ Retun Prometheus query result in HTML """ report_date = datetime.today().strftime('%B %Y') duration = '[' + str(24) + 'h]' response = requests.get(Prometheus_URL + '/api/v1/query', params={ 'query': ...
c639f40e78eb1e61497e7dd0e93beea83fafd5d0
3,596,666
def scatter(ab): """ """ ab.sel = "TO SC BT BT BT BT SA" fr = ab.iflg("SC") a_opol, b_opol = ab.rpol_(fr=fr-1) a_npol, b_npol = ab.rpol_(fr=fr) a_odir, b_odir = ab.rdir(fr=fr-1,to=fr) a_ndir, b_ndir = ab.rdir(fr=fr,to=fr+1) a_ct = costheta_( np.cross(a_opol, a_ndir ), a_opol ) ...
06fa968915b3b903df91ddbb2e989fbf9eee328e
3,596,667
def wheel(np, pos): """ Input a value 0 to 255 to get a color value. The colours are a transition r - g - b - back to r. Source: Adafruit tutorials """ if pos < 0 or pos > 255: r = g = b = 0 elif pos < 85: r = int(pos * 3) g = int(255 - pos * 3) b = 0 ...
77212a0e7e34fe0a7a65c706820b2f7882165785
3,596,669
def make_faces(mesh, vectors): # no dep """ Initialize a dictionary of `Face` objects. Parameters ---------- mesh : `compas.Mesh` A COMPAS mesh. vectors : `dict` A mapping of face keys to vectors {fkey: vector} Notes ----- Faces and vectors keys are assumed to matc...
098950887861c060bfdd5e9cf53f301b63799e46
3,596,671
def create_unit_classes(units): """Creates an ordered list of UnitClasses. Any and all UnitClasses required for the test inputs should appear here. """ t1mex = UnitClass("T1 Mass Extractor") t1mex.set('a', units['uab1103']) t1mex.set('e', units['ueb1103']) t1mex.set('r', units['urb1103']) t...
441ec280fec7b5935f5e55c8bc4a464098aac48a
3,596,672
def forward_propagation(X, parameters, training, istanh1, istanh2, batchnorm, dropout = 1.0, regression = False): """ Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX Arguments: X -- input dataset placeholder, of shape (input size, number of exampl...
2b132731f5c3c83abb04328929a4f3239d475e43
3,596,673
def worker_number(worker_id): """Get the current worker number.""" id_as_str = "".join(ch for ch in worker_id if ch.isdigit()) if len(id_as_str) == 0: return 0 return int(id_as_str)
3cd6ca7e665fefda9427476e39de5ea23f843f72
3,596,675
def moving_average_convergence_divergence(data, short_period, long_period): """ Moving Average Convergence Divergence. Formula: EMA(DATA, P1) - EMA(DATA, P2) """ check_for_period_error(data, short_period) check_for_period_error(data, long_period) macd = ema(data, short_period) - ema(da...
bcede112c3c864f733138b516fd6fc6f7d6a1bce
3,596,676
from typing import Optional def get_team(name: Optional[str] = None, parent: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTeamResult: """ Use this data source to get information about a specific [team](https://v1.developer.pagerduty.com/documentat...
744eddff4ad555c092720ae55a038dd350379c81
3,596,677
import torch def bbox_iou(box1, box2, x1y1x2y2=True): """ Returns the IoU of two bounding boxes """ if not x1y1x2y2: # Transform from center and width to exact coordinates b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2 b1_y1, b1_y2 = box1[:, 1] - box1[:...
0ce3f23c829243f094250c7327f0e16422f3270a
3,596,679
import typing def borda_exp( num_seats, candidates: typing.List[Candidate], votes: typing.List[Vote], do_explain=False, **kwargs, ) -> typing.List[Candidate]: """Borda Count with parametrized exponential weighting.""" weight = kwargs["weight"] candidates = {c.id: BordaCandidate(c.id) ...
3235d6829e2a6f53861548c4c358c5ed671ee7e3
3,596,680
def cumulative_gaussian_distribution(z): """standard cumulative Gaussian distribution""" return 0.5*(1 + erf(z/2**0.5))
634020551c82b9b653ae3a40f3c7f43f82d8ad35
3,596,681
def load_drug_descriptors_old(ncols=None, scaling='std', add_prefix=True): """Load drug descriptor data, sub-select columns of drugs descriptors randomly if specificed, impute and scale the selected data, and return a pandas dataframe. Parameters ---------- ncols : int or None n...
a7274d177da8bb564fe498c8bc6638ebadeabb36
3,596,682
def alpha(r, w): """ Computes dimensionless parameter involving the radial distance and the beam radius for calculation convenience. Args: r: radial distance from the center axis of the beam w: radius at which the field amplitude fall to 1/e Returns: dimensionless parameter ...
0f38467042077f8771a3b456ffd753e9a009025d
3,596,684
def as_shr(data): """ Take data as either `fun`, `img`, `omegar`, `omegac`, or `mat` and convert to `omegar` (unless already). Parameters ---------- data: ndarray Returns ------- omegar: ndarray(shape=(N**2,), dtype=float) """ if data.ndim == 2: if data.shape[0] == ...
e9a80afb0f30e63f7e07fdc09a8ce90928d7de01
3,596,685
import math def calc_mach(var_lambda: float, gamma=1.4) -> float: """" Returns Mach number instead superficial velocity Parameters ---------- var_lambda: float superficial velocity of flow gamma: float isentropic exponent (default 1.4) Returns ------- M: float ...
c12aafd8d4d9fc4c544e73da890d311e3613d4d1
3,596,686
import string import re def rm_non_textual_punct(dfcol): """ Aggressively remove almost all punctuation (except .,?:;- ) """ text_punct = '.,?:;-' #this also removes + <> $ % nontext_punct = [char for char in string.punctuation if char not in text_punct] nontext_punct = re.escape(''.join(nontext_punct...
ff9dfc87ec0015b4a0d0ca5d83db3b116e476470
3,596,688
def get_reference_value_from_spec(openapi_spec: dict, reference_path: str) -> dict: """Follows the reference path passed in and returns the object at the end of the path Args: openapi_spec (dict): The openapi.json specification object reference_path (str): a path formatted as "#/foo/bar/baz" ...
c32962a3b008825de4c5108d8d1a3ad5db179b17
3,596,689
def tf_serialize_example(f0, f1, f2): """Use the tf.data.Dataset.map method to apply a function to each element of a Dataset. The mapped function must operate in TensorFlow graph mode: It must operate on and return tf.Tensors. A non-tensor function, like serialise_example, can be wrapped with tf.py_func...
7699fde753de5b873ca900f4d475027d6507f6d0
3,596,690
def hide_keys(dictionary, keys_to_hide, new_value="xxx"): """ Return a copy of the given dictionary on which specified keys will be replaced by the new_value word (or 'xxx'). :param dictionary: a dictionary :param keys_to_hide: keys to hide in the output dictionary :param new_value: replacement str...
d6b8bc7958c637212899c048a9958ac3d2755894
3,596,691
def simulate_multiple_examples(examples, method=RK4, duration=30, step_size=0.001): """Solve multiple examples. Usually used in conjunction with `create_perturbations` function. Args: examples (list of class instances): list of examples we want to solve, e.g. `DoublePendulum` me...
ff7431a79c52cec0c6e33a282d22b430efe693b9
3,596,692
def respond(request: HttpRequest): """Responds to a serverside sitetable request. :param request: """ return Table.respond(request)
a04ff149bd5ca99e9484082b968a15db1c4d8f50
3,596,693
def gen_coron_mask(self): """ Generate coronagraphic mask transmission images. Output images are in 'sci' coordinates. """ mask = self.image_mask pupil = self.pupil_mask oversample = self.oversample mask_dict = {} if (not self.is_coron) and (not self.is_lyot): mask_dict['DE...
6648ee15ce1e8a6e36600a2cafd32208143c198b
3,596,695
def get_latest_iter(wt_dir, wt_type='best'): """ Get latest weights. """ latest_iter = get_most_recent_iteration(label=wt_type, wt_dir=wt_dir) return latest_iter
5423f9ced017c6a1333712bdbb582f0a8c144fc8
3,596,696
def saveSceneIfDirty(prompt=True): """ Prompt the user to save if the scene is modified, or has never been saved. Returns True if the save was successful, or the scene has not been modified. Args: prompt (bool): If True, prompt the user, or attempt to automatically save where possible """ ...
4a14f727baf1cb203c8d208cfdaece6305e0805d
3,596,697
def verify_results(settings, rdata, expected, wrapper, model, atol, rtol): """Verify test results""" amount_species, variables = get_amount_and_variables(settings) # verify states simulated = pd.DataFrame( rdata['y'], columns=[obs['name'] for obs in w...
c4c699b43c281f75828f5c7b60c16b021f78a2da
3,596,698
def getList(sub, pred=None, db=None): """Attempts to return a list from sub (subject that is) passed in if it is a Collection or a Container (Bag,Seq or Alt)""" if not db: if isinstance(sub, rdfSubject): db = sub.db else: db = rdfSubject.db if isinstance(sub, rdfS...
98339bdb99d73b6ca026eae0653a10366f3b4257
3,596,699
from typing import Counter def construct_vocab(self, *args, remove_punctuation=True, threshold=5, startseq='<start>', endseq='<end>', unkseq='<unk>', padseq='<pad>'): """ Generate vocabulary object from all the captions Parameters: *args(pd.DataFrame): tokens dataframe r...
2fe242e835ddc3088aeadaad5cdf2fb1f273bfc6
3,596,700
def nircam_reorder(A, B, order): """Changes coefficient order from y**2 xy x**2 to x**2 xy y**2 Parameters ---------- A B order Returns ------- """ terms = (order + 1) * (order + 2) // 2 A2 = np.zeros((terms)) B2 = np.zeros((terms)) for i in range(order + 1): ...
28c4926fd11b955e71d8e8fa538ca96dfa3baa65
3,596,701
def hardness_region_competence(neighbors_idx, labels, safe_k): """Calculate the Instance hardness of the sample based on its neighborhood. The sample is deemed hard to classify when there is overlap between different classes in the region of competence. This method does not takes into account the target lab...
e2985c6d7459575346f77fe8a1458f8c574d6c60
3,596,702
def list_file_info(base, pattern, name_index=0, type=None): """ Constructs a list of tuples containing information about the files as indicated by the pattern. The name_index should correspond to the index in the resulting tuple that contains the name of the file, default is 0 @param base path for files...
41619bb1b1007dd9b5e59c56f0508bf4549531db
3,596,703
def client(app): """ Create test client for the app""" return app.test_client()
65eca0cc91d1131762cf698d32a3fe9bbf40e3d6
3,596,704
def get_seq(_seq, _start, _end): """ :param _seq: :param _start: !!! should be SSR start position on genome (begin from 1, not 0) :param _end: !!! should be SSR end position on genome (begin from 1, not 0) :return: """ if _start <= 200: return _seq.seq[0: _end+200] elif _end >= ...
c42db6e6a50fa46c30e948ac6f007d5c92e07708
3,596,705
def distance(point_p, point_q, coordinate_system="cartesian"): """ Calculate the distance between two points in Cartesian or spherical coordinates Parameters ---------- point_p : list or tuple or 1d-array List, tuple or array containing the coordinates of the first point in the foll...
e48773e3ef019cb305b503e1d05098a1027140a0
3,596,706
def storage_client(supabase: Client) -> SupabaseStorageClient: """Creates the storage client for the whole storage tests run""" return supabase.storage()
4f1d7837480b90e8a2fff4bc6fb1018393814010
3,596,708
import numpy.ma as MA import numpy as N from atmconst import AtmConst def press2alt(arg, P0=None, T0=None, missing=1e+20, invert=0): """Calculate elevation given pressure (or vice versa). Calculations are made assuming that the temperature distribution follows the 1976 Standard Atmosphere. Technically t...
f125f5228f6cd435f1ccb2c158d898c52c9289a1
3,596,709
def verifica_dirs(): """ Essa função é executada no momento da inicialização durante a barra de progresso, para verificar a existência dos di retórios necessários para salvar os arquivos PDF's. Caso algum dele ou deles não existam, os mesmos serão criados. :return: None """ outputs_directory = r...
fea200b0c7cdd560b552f13388c7c2a97eff58f6
3,596,710
def function(fn=None, **kwargs): """ Wraps a function with an AutoDiff Function instance, converting it to a symbolic representation. The function is compiled the first time it is called. Use: @function def python_function(...): return do_something() python_fun...
46dab8a3f451fd81a6b9e4e551c524b9f3972d04
3,596,711
from scipy.interpolate import interp1d import numpy as np def getFMext(wave,R,source): """ Input: wavelength in microns, nominal R = 3.1 source='f99' for Fitzpatrick 1999 or ='fmunred' for fmunred.pro source='f99 tables' reproduces common misunderstanding from that paper ...
ad33a445e4d5ff67f8d962884955ea9349379338
3,596,712
def gamma2v(gamma): """ See eq ? TT2015 """ v = (1./3.)*np.sin(3.*gamma) return v
5a500f064a679ea7ee2d3ec1040ec8427771942b
3,596,713
import re def get_weight(tail): """Given the tail of a mime type header (the bit after the first ``;``), find the ``q`` (weight, or quality) parameter. If no valid ``q`` parameter is found, default to ``1``, as per the spec. """ match = re.search(q_match, tail) if match: try: ...
352848d3d31c8dda2c17ef89d27d9c24623a8ded
3,596,714
from typing import Optional from typing import Callable def in_range(_min: Optional[Number] = None, _max: Optional[Number] = None) -> Callable[[Number], bool]: """ Creates a number range validator * It can work for any number type Args: _max (Optional[Number]): max value _min (Optiona...
2e719dd82453781738174d9707e9ad220c33228d
3,596,715
import re def login(): """ 1. 获取参数和判断是否有值 2. 从数据库查询出指定的用户 3. 校验密码 4. 保存用户登录状态 5. 返回结果 """ # 1. 获取参数和判断是否有值 mobile = request.json.get("mobile") password = request.json.get("password") if not all([mobile, password]): current_app.logger.error("参数不足") return jso...
6681780641a53a78dd6454af4ec264a806a7afa3
3,596,716
def get_crop_numpy(im: np.ndarray, pos: np.ndarray, sample_sz: np.ndarray, output_sz: np.ndarray = None, mode: str = 'constant', avg_chans=(0, 0, 0), max_scale_change=None): """Sample an image patch. args: im: Image pos: center position of crop sample_sz: size to crop...
e56d92a5f6bcf91e9dc8941ba33568c920347fcf
3,596,718
from typing import Callable from typing import Iterable import functools def folder(function: Callable[[Range, Domain], Range], initial: Range) -> Map[Iterable[Domain], Range]: """ Returns function that cumulatively applies given binary function starting from given initial object in direction f...
3e85929812974d57e94e1fbd1b6eaf925cff8d10
3,596,719
def ang2pix_hdr(coord,hdr,zero_offset=True): """ Apply forward (ra,dec)->(x,y) TAN transformation A convenience function for calling ang2pix, with the transformations described in a dictionary in the usual FITS header style for WCS transformations. Parameters ---------- coord...
227b3f0eba449d95c4fcc05c19d96d6dbe65ff1e
3,596,720
from .optuna import OptunaSuggest def collapse_suggest_config(config: dict) -> dict: """Use the default value of OptunaSuggest for config items. So that the configs can be used in the case that optuna is opted out. Args: config: The configuration dictionary Returns: The collapsed con...
f69ba41fdba0cf820a0bd22ff71a53bc13b27a8e
3,596,721
def vmprofilestable(): """ retrieves vm profiles in table """ baseconfig = Kbaseconfig() profiles = baseconfig.list_profiles() return render_template('vmprofilestable.html', profiles=profiles)
40f65ea0f60bc99e62bc63b52dc3df561d6eda73
3,596,722
import requests def get_google_sheet_df( access_token: str, google_sheet_id: str, sheet_name: str = 'portfolio', _range: str = 'A:Z' ) -> pd.DataFrame: """from: https://stackoverflow.com/questions/52365907/how-to-access-google-sheets-data-using-python-requests-module""" url = ...
35a110cc89c285329205aabfc9239ab5c37fd30f
3,596,723
import random def active_sample(network, size, evaluate): """ Sample from affected genes as null model. """ sample = random.sample(network.nodes(), size) subnet = network.subgraph(sample) result = evaluate(subnet) return result
d5f7ecf87e6b72b5930fe066e13fd593626fd352
3,596,724
def get_cluster(name=None, project=None, region=None, zone=None): """ Get info about a cluster within GKE from its name and zone. """ __args__ = dict() __args__['name'] = name __args__['project'] = project __args__['region'] = region __args__['zone'] = zone __ret__ = pulumi.runtime....
b436e38ae83f0beb3e4dbd53667a529773e986c4
3,596,727
import requests def attendance(regular=True, playoffs=True, start_season=None, end_season=None): """ Query the NHL attendance number from 1975 to 2019 from the NHL records API. The attendance represents annual attendance numbers for all teams. The user can specify to return either the ...
c3fe53193528e5bad1f1cf1bf2d0eae420e5ee57
3,596,728
def get_other_dims(da, dims_exclude): """ Returns all dimensions in provided dataset excluding dim_exclude | Author: Dougie Squire | Date: 22/04/2018 Parameters ---------- da : xarray DataArray Array to retreive dimensions from ...
506a8b7193ea95480c83e3d69a31774f77d4fbcc
3,596,729
def standard_split(text, row_length): """text = abcdefghijklmnopqrstuvwxyz and row_length = 5 abcde fghij klmno pqrst uvwxy z returns ['afkpuz', 'bglqv', 'chmrw', 'dinsx', 'ejoty'] """ output = [] text_length = len(text) # Takes output column by index in turn, taking e.g...
3a4732433b58777dcf08529b98b90f890e680a29
3,596,730
def initialize_opencv(filename, framesize, codec, fps: float = 30.0): """ wrapper around opencv VideoWriter """ if codec == 0: filename = filename + '_%06d.bmp' fourcc = 0 fps = 0 else: # filename = filename + '.avi' fourcc = cv2.VideoWriter_fourcc(*codec) # fourc...
b23eb23745b19c010581f9cb72c873c08fbe14df
3,596,732
def gen_pie_plot(df): """Generates pie plots. Shows the distribution of numbers drawn per ball (e.g. how many times the number 42 was drawn for ball n°3). Args: df(dataframe): pandas dataframe containing all the draw results for the lottery (dates/balls/stars). Returns: ...
8443adf8214e4d86b73f8104cc82b649e1e56482
3,596,733
def _process_frame_wob(frame): """ wob画面のみを切り取り、正規化する """ frame = frame[75:75+210, 10:10+160, :].astype(np.float32) frame *= (1.0 / 255.0) return frame
426143a2e2bc7493ef93f696975c787799e0bd1d
3,596,734
def lstm(num_hidden, indata, prev_state, param, seqidx, layeridx, dropout=0., num_hidden_proj=0): """LSTM Cell symbol""" if dropout > 0.: indata = mx.sym.Dropout(data=indata, p=dropout) i2h = mx.sym.FullyConnected(data=indata, weight=param.i2h_weight, ...
8e9a7388644145ced4ebc5088b802264dedd742c
3,596,735
def create_app(test_config=None): """ Returns a Flask web application with the default configuration pinging a TFX serving instance on http://localhost:8503/v1/models/alpha:predict """ app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( TFX_ENDPOINT='http://loca...
f1750fed0acc3be4c0bc1ee151bce0a6ac8df58b
3,596,736
def median(x): """Return the median of a list of values.""" m, r = divmod(len(x), 2) if r: return sorted(x)[m] return sum(sorted(x)[m - 1:m + 1]) / 2
337584e40c61bd198496355e38f4a8d4da9310fa
3,596,737
def _get_args(tp): """Backport of typing.get_args for Python 3.6""" return getattr(tp, "__args__", ())
f265cb6d8d85601d9ee6f20be8f78c8d9819c920
3,596,738
def get_field(self, field_name): """Get the value of variables stored in Solution. Parameters ---------- self : Solution an Solution object field_name : str name of the field to return Returns ------- field: array an array of field values """ ...
3d106d995a98407a64a61235d9a106e35968d20c
3,596,739
def write_index(): """Create markup for a new form submit with all tests. """ entries = [] for entry in get_tests(): if entry.title: title = "".join(entry.title) entries.append(TR_TD_COLS_4 % title) if entry.url: url = "".join(entry.url) en...
85a8bf192ce6ce4dc9414c4903a90de00ae40339
3,596,741
import json def alchemy_json_encoder(revisit_self=False, fields_to_expand=[], fields_to_include=[], fields_to_ignore=[], fields_to_replace={}, fields_to_transform={}): """Serialize SQLAlchemy result into JSon Inpsired by: http://stackoverflow.com/questions/5022066/how-to-serialize-sq...
69a7f38e3859d7d6a9675951050bf8700bf5a8d1
3,596,742
def portfolio_labels(statespace, n): """ Generate a collection of credit rating states emulating a snapshot of portfolio data. Suitable for mappings and transformations of credit rating states :type statespace: The state space to use for the simulation :param int n: The number of distinct entities to ge...
78372ca2b0321c170da22bc7388018fa51f634aa
3,596,744