content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def compute_lab_volume(image): """ Compute the perceivable color volume in LAB space as a measure for the used colors (or color flatness) Parameters ---------- image: the image to compute the LAB space volume for Returns ------- LABvolume = std(L)*std(a)*std(b) """ lab = rgb2la...
303d378a7ecbbe75bb6b285462d3a39484d46517
3,598,832
import yaml def get_project_id(dataset: str) -> str: """Returns the GCP project ID associated with the given dataset.""" with open(f'../stack/Pulumi.{dataset}.yaml', encoding='utf-8') as f: return yaml.safe_load(f)['config']['gcp:project']
d951e8d2a6c96df9aa2dc15499c36f93123f8038
3,598,833
def dense_nn(x): """ Network used to classify MNIST digits. :param x: tensor with shape [batch_size, 784], input to the dense fully connected layer. :return: [batch_size, 10], logits of dense fully connected. """ dense_1 = tf.nn.dropout(tf.nn.relu(dense(x, input_dim, n_l1, 'dense_1')), keep_prob...
696eabfd1b93a269c8b63465653ab3fc18bc3b02
3,598,834
def score_state(num_answer, ans_one): """Takes in the player's answer, and ans_one (explained in question); checks if the player's choice is correct """ #assert num_answer in [1, 2] if num_answer == 1: if ans_one == True: correct = True else: correct = Fa...
123a0c5f40930fe5a6dc65220c39097a55120c19
3,598,838
from typing import List from typing import Callable def make_transformer( nlp: Language, name: str, model: Model[List[Doc], FullTransformerBatch], set_extra_annotations: Callable[[List[Doc], FullTransformerBatch], None], max_batch_items: int, ): """Construct a Transformer component, which lets...
978e31bb0cf672b4012e5dba03b67a03190747e2
3,598,839
def generate_AA_random_walks(APP_start, apk2idx, idx2apk, apk2node, node2apk, A, BP, p, q, length): """ Given a starting node, generate AA random walks that have max length of 'length' """ APP1 = apk2node[APP_start] APP_idx = apk2idx[APP_start] ser = pd.Series(A[APP_idx].toarray()[0]) API1 =...
a1e100e5f167fac3e1b9decfb130fe94e557b1cc
3,598,840
def req_add_from_template(req_id): """ Add a Request from a Template """ fieldnames = ["type", "priority", "site_id", "purpose", "requester_id", "comments", ] db = current.db s3db = c...
3786f41d789c72cf61cf4a971850ea225ab08dc2
3,598,841
def law_of_orbits_perihelion(a: radius, e: eccentricity) -> radius: """Calculate aphelion from Kepler's Law or Orbits. Where: R = Displacement from major body to perihelion a = Semimajor axis e = eccentricity """ logger.trace(f"BASE FUNCTION: \"law_of_orbits_perihelion\" invoked.") R: r...
5c1278e6fc19214f844997439dbf0a56a62e056e
3,598,842
def is_anagram_v3(s, t): """ NOTE: THIS SOLUTION DOES NOT WORK FOR ALL CASES e.g: s = 'ac', t = 'bb', or aa vs bb """ val = 0 for i in range(len(s)): val ^= ord(s[i]) print(f"val: {val}") val ^= ord(s[i]) print(f"val: {val}") return val == 0
121c4fd1841d6372fd5a03af3ae6f74e3dfb7b25
3,598,843
def register(): """ {"username" : "user1", "password": "123qwe", "type"=0} """ data = request.json username = data["username"] password = data["password"] type = int(data["type"]) user = User(username=username, password=password,type=type) db.session.add(user) try: db.ses...
3a50ecdae06a7ff02c706a33737b44ffd55a1a32
3,598,844
import hmac def verify_hmac_sha1(request): """Verify a HMAC-SHA1 signature.""" base_string = generate_signature_base_string(request) sig = hmac_sha1_signature( base_string, request.client_secret, request.token_secret) return hmac.compare_digest(sig, request.signature)
31b8c5843b4587d078d512e4f821e093e1b80543
3,598,846
from typing import Any import sympy import numpy def vyxalify(value: Any) -> Any: """Takes a value and returns it as one of the four types we use here.""" if isinstance(value, sympy.core.numbers.Integer): return int(value) elif is_sympy(value): return sympy.nsimplify(value.as_real_imag()[...
86db306af2eeec8b49cff82af878240f156a0bb2
3,598,847
def low_frequency_turn_over_power_law(v, vc, a, c, beta, v0): """power law with low-frequency turn-over: .. math:: S_v = c \\left( \\frac{v}{v0} \\right)^{a} \\exp\\left [ \\frac{a}{\\beta} \\left( \\frac{v}{vc} \\right)^{-\\beta} \\right ] Parameters ---------- v : `list` Frequenc...
d97e218f5ddfebac21dfe6eba73686aadda6457a
3,598,848
import six def OverrideProjectIdToProjectNumber(request): """Returns an updated `request` with the Cloud project number.""" resource, resource_name = GetResourceInfo(request) project_id = DeriveProjectFromResource(resource) project_number = ProjectIdToProjectNumber(project_id) setattr(request, resource_name...
595407ca014ad2152729bfb07aa27cc2f249dcaf
3,598,849
def arg_name2cli_name(arg_name: str) -> str: """ Convert a snake_case argument into a --kabob-case argument. """ return "--" + arg_name.lower().replace("_", "-")
541601ae07b09acdd2d33487517159cd3cbd6125
3,598,850
from typing import Tuple from typing import Any def _basic_computation_tracincp_fast( influence_instance: TracInCPFast, inputs: Tuple[Any, ...], targets: Tensor, ): """ For instances of TracInCPFast and children classes, computation of influence scores or self influence scores repeatedly calls...
4bf9df9d035b9d901a17a505399d3101c29d50ac
3,598,852
def get_split_counts(df: pd.DataFrame): """Returns number of rows for each data split type given dataframe.""" assert constants.SPLIT_KEY in df.columns return df[constants.SPLIT_KEY].value_counts().to_dict()
470ca5cd0cbe247e0abc32ad4a002b9538520eae
3,598,853
import requests from datetime import datetime def erc20_address_call(address): """API call to etherscan for an ethereum wallet and returns the total positive count of remaining erc-20 coins in the wallet""" address = str(address) url = "http://api.etherscan.io/api?module=account&action=t...
0bebb4c96cd49b54c70b3f54605f230a97254647
3,598,854
def get_num_lines(input_src): """Count number of lines in file. Args: input_src: input file Returns: number of lines """ # get number of lines num_lines = 0 with open(input_src, "r", encoding="utf-8") as in_file: try: for line in in_file: num_lin...
4c1e9fdc1e67bb6e26a6c342d6c1a8ff077a26c4
3,598,855
def _label_check(label_string: str, search_label: str): """ Mask labels with Booleans that appear in row """ for label in label_string.split(' '): if search_label == label: return True return False
084d23321133dfcd9d8f819e8209165d1cac2c15
3,598,857
def lp(m, n): """ Create a linear program with random equality constraints and non-negative inequality constraints """ _x = np.maximum(0.0, np.random.randn(n)) # inequality constriants A1 = -np.eye(n) b1 = np.zeros(n) # equality constraints A2 = np.random.randn(m, n) b2 = A2.dot(...
892cd6abccfe70b58d274bd2fb0f74ac3e62f495
3,598,858
def get_strategies_properties(): """ A function that returns a data frame with the strategies of the Axelrod library and for each strategy it's property. """ axl_strategies = pd.DataFrame( columns=[ "Name", "Stochastic", "Memory_depth", "Make...
ab2f2a5d8c8f2c59e211d7a6bd8550fc80215ecf
3,598,859
from scipy.optimize import minimize from scipy.spatial.distance import pdist, squareform def spring_layout(p, c0=0.2, c1=1.0): """Calculate points positions for Pharmacophore depiction using spring layout. Args: p (Pharmacophore): model to depict c0, c1 (float, optional): coefficients for s...
a3fc0bfd1451d63b28af0c2161a853469b471584
3,598,860
def flat_concat(xs): """ From SpinningUp: Merges list of tensors into one (X,) tensor. """ return tf.concat([tf.reshape(x, (-1,)) for x in xs], axis=0)
049756c1f929ab72264097c382b750602b1a61f1
3,598,861
import time import PIL def upscale_image(model, img): """Predict the result based on input image and restore the image as RGB.""" ycbcr = img.convert("YCbCr") y, cb, cr = ycbcr.split() y = img_to_array(y) y = y.astype("float32") / 255.0 input = np.expand_dims(y, axis=0) start = time.time...
f7be50cb2eff48e9727baa641d3b170ed69f4c1f
3,598,863
def _create_instantiation_proposal(tran_prop_req, chain): """Create a chaincode instantiation proposal This involves assembling the proposal with the data (chaincodeID, chaincode invocation spec, etc.) and signing it using the private key corresponding to the ECert to sign. :param tran_prop_req: se...
f4ef3cbd057c58a0fdb5ca0adf08d22f151b3709
3,598,864
def flip_nested_dict(nested_dict): """Flip nested dictionary inside out.""" flipped = dict() for key, subdict in nested_dict.items(): for k, v in subdict.items(): flipped[k] = flipped.get(k, dict()) flipped[k][key] = v return flipped
c1ddbe48a158ed4a96db3b33deb2f423afd304fe
3,598,865
def atr(df, window, high_col="High", low_col="Low", price_col="adj_close"): """Average True Range, measuring price volatility. Parameters: ----------- df : DataFrame Input dataframe. window : int Length of rolling window for calculation of the ATR. high_col : str Column ...
afb6338e33a5c1ab4d4200f43429c3ff0cb9a7cc
3,598,866
def queryConferences(self, request): """Query for conferences.""" conferences = Conference.query() # return individual ConferenceForm object per Conference return ConferenceForms( items=[self._copyConferenceToForm(conf, "") \ for conf in conferences] )
933e601a8df63564228a015412169cb214bcd65d
3,598,867
def get_users(client): """Return the db containing users metadata. Parameters ---------- client --> pymongo.mongo_client.MongoClient class, MongoDB client Returns ------- metadatafs['fs'] --> pymongo.collection.Collection, reference to collection users """ #get the MongoDb ...
bd2f0b60781e27a23f015f7a7573821a0e2b8ef0
3,598,868
def read_raw_values(datasize, datastore, test): """read the raw data for a given test""" in_file_name = str(datasize) + '/' + datastore + '_' + test + '.csv' return [int(line.strip()) for line in open(in_file_name)]
1d724b873ee0ccf50d2027df79a2d32472e7942a
3,598,869
def nwi_add_color(fc): """Converts NWI vector dataset to image and add color to it. Args: fc (object): ee.FeatureCollection Returns: object: ee.Image """ emergent = ee.FeatureCollection( fc.filter(ee.Filter.eq('WETLAND_TY', 'Freshwater Emergent Wetland'))) emergent = em...
9e01958cb02c48b9bb45bb9d4b084dde443ab1ea
3,598,870
from datetime import datetime async def calculate_maintenance_times(): """ calculate_maintenance_times: Calculates the proper times for maintenance and :return: - If there's maintenance, a list of the times as tuples as follows: [ (JST_START_TIME, JST_END_TIME), ...
fec5e1f8746dc7e3c70cb057d9f7d211732a27ca
3,598,872
def TrimMu(Stot, oldmu, thresh, norm=True): """ Remove mu measurements below the threshold and adjust mu measurements above the threshold to unity if we seek P(mu > thresh). """ trim = oldmu > thresh if norm: oldmu[:] = 0 oldmu[trim] = 1 else: oldmu = oldmu[trim] St...
2a986599a6116b104b839d8b664f0caff57b1aee
3,598,873
def getMultiData(channel, startTime, endTime): """ getting multiple values - in progress, testing mode""" channels = ["25m:guider:probe:exposureID", "25m:guider:probe:probeID", "25m:guider:probe:flags"] archiver.scan_archives() data0, data1, data2 = archiver.get(channels, startTime, end...
636388fa4341ee66b72f9da3b41ab5a32a21e8ab
3,598,874
async def async_setup(hass: HomeAssistant, yaml_config: ConfigType) -> bool: """Activate the emulated_hue component.""" local_ip = await async_get_source_ip(hass) config = Config(hass, yaml_config.get(DOMAIN, {}), local_ip) await config.async_setup() app = web.Application() app["hass"] = hass ...
6b0d929b201ede8527f3f4a56b1e93a2c7220599
3,598,875
def phase(x,period): """phase(x,period) returns the phase of location x with respect to the module with spacing period. The phase is between 0 and 1.""" return np.mod(x/float(period),1)
2b0929d892abd0444a31274adb0f574e34e46014
3,598,876
def geo_rect(pnt1, pnt2): """Generate geo string (Rectangle) for mysql""" _p1 = range(0, 2) _p2 = range(0, 2) _p1[0] = min(pnt1[0], pnt2[0]) _p1[1] = min(pnt1[1], pnt2[1]) _p2[0] = max(pnt1[0], pnt2[0]) _p2[1] = max(pnt1[1], pnt2[1]) return ' GeomFromText(\'Polygon(({0} {1}, {0} {3}, {2...
d47873a7dd1de36b229fb4e26c64a6647b2589b6
3,598,877
import numpy def eval_h(x, lagrange, obj_factor, out): """Hessian of the Lagrangian L = obj_factor * f + <lagrange, g>, where <.,.> denotes the inner product. """ out[-1] = 0.0 out[:-2:2] = obj_factor * (2.0 + 400.0 * (3.0 * x[:-1] * x[:-1] - x[1:])) out[:-4:2] -= lagrange * (2.0 + x[:-2])...
5864ec66b160a98a75c62cdafc859a87e7e7795f
3,598,878
def translate(speech): """ Translate the given speech :param speech: the string text being given :return: the returned string changed based on the language """ translator = Translator() word = translator.translate(speech, dest='zh-cn') print(word.text) return word.text
420356ce971807937fed7c9223ec0ef699c4ad6e
3,598,879
def preprocess(dataframe): """Converts categorical features to numeric. Removes unused columns. Args: dataframe: Pandas dataframe with raw data Returns: Dataframe with preprocessed data """ dataframe = dataframe.drop(columns=UNUSED_COLUMNS) # Convert integer valued (numeric) colum...
7aaf7065d5486e995701513705bb80d463e6b5e0
3,598,880
def get_training_roidb(imdb): """Returns a roidb (Region of Interest database) for use in training.""" # if cfg.TRAIN.USE_FLIPPED: # print 'Appending horizontally-flipped training examples...' # imdb.append_flipped_images() # print 'done' print 'Preparing training data...' if cf...
6fdeb92c4f968155ecb0a3b26ee501103b9503c7
3,598,881
import collections def mkparts(sequence, indices=None): """ Make some parts from sequence by indices :param sequence: indexable object :param indices: index list :return: [seq_part1, seq_part2, ...] """ indices = indices or [1] result_list = collections.deque() start = 0 seq_le...
710841ca3861a33382b6243579eec07f866eb965
3,598,882
def log_minor_tick_formatter(y: int, pos: float) -> str: """ Provide reasonable minor tick formatting for a log y axis. Provides ticks on the 2, 3, and 5 for every decade. Args: y: Tick value. pos: Tick position. Returns: Formatted label. """ ret_val = "" # The posi...
a378bd94ceab8698a45403544a728c6c29b402c9
3,598,883
def s_and_were_or_just_was(parameter): """a utility function for grammatical correctness [and DRY, i.e. Don`t Repeat Yourself]""" return ("s were" if parameter != 1 else " was")
e4d1c03565e89b9b8ecba0137e1b0b9e3bcafa40
3,598,884
from typing import Union from pathlib import Path from typing import Any from typing import TextIO def fopen(filepath: Union[str, Path], *args: Any, **kwargs: Any) -> TextIO: """Open file. Args: filepath (Union[str, Path]): filepath Returns: TextIOWrapper: buffer text stream. """ ...
fcf4ccf53c99a390ceaa9b27f86a7e3f4cff3af1
3,598,885
import html def common_null_warning_html(text, alignment="center", top_margin=50): """ Get a null warning html block which can be used across all apps. Useful for when no text is entered into a box, etc. Args: text (str): The null warning text. alignment (str): Either "center" or "lef...
cf9d15b453778d9615da60a5f208c1fbc2a20f57
3,598,886
def calc_base_rate(data, training=True): """Calculates the base-rate for intelligent parameter initialization from the training data.""" suffix = 'train' if training else 'test' in_key = suffix + '_time_in_seq' out_key = suffix + '_time_out_seq' valid_key = suffix + '_event_in_seq' dts = (data[...
372680ce7b66a1d370531ab8c3f9ee71f9a48cd9
3,598,888
def train_model(train_vectors, train_target, model_name): """ To train model based on passed data and model name :param train_vectors: A vector of training data after applying operation of preprocess.py :param train_target: Corresponding target variable for training data :param model_name: name of m...
341e8b08695110f8f6eab6d872e708a7dde6599d
3,598,889
def sql_update(sql): """ Updates data in table """ string = '' try: conn = None rows = 0 try: # connect to the PostgreSQL database and create cursor conn, cur = sql_login() # execute the UPDATE statement cur.execute(sql) #...
998d7e49d909251593071d1f2790affcfc77b80c
3,598,891
def sample_conditional(category): """Samples a drawing for the given category.""" def encode(session, eval_model, input_strokes, length): strokes = to_big_strokes(input_strokes, length).tolist() strokes.insert(0, [0, 0, 1, 0, 0]) seq_len = [len(input_strokes)] return session.run(...
a069819ad248fd27a387a05b681be44de7ef98f7
3,598,893
def wikify(value): """Makes WikiWords""" return replace_wikiwords(value)
a6f07a01eaf39cc0240f5bddde76f4e7d1153540
3,598,894
def d_dz_mid(quantity): """Derivative applied to quantity at mid level""" return_value = np.zeros( [quantity.shape[0], quantity.shape[1]+1], dtype=quantity.dtype) return_value[1:-1] = quantity[:, 1:] - quantity[:, :-1] # in CLUBB it is assumed quantities are linear outside of their range at ...
878482e4d704c97f27f9c0bb067f79f3ae186b3f
3,598,896
def merge(line): """ Helper function that merges a single row or column in 2048 line: list like [8, 0, 16, 0, 16, 8] returns: merged list [8, 32, 8, 0] loop cur pos and index in list: if two equal numbers seperated by 0s, double the previous index and replace number at current position with ...
ad43cd74f991490a2fd1ce18a68ae360534c9fd7
3,598,897
import signal def signal_number_to_name(signum): """ Given an OS signal number, returns a signal name. If the signal number is unknown, returns ``'UNKNOWN'``. """ # Since these numbers and names are platform specific, we use the # builtin signal module and build a reverse mapping. signal...
cc17db79f6e47b25e9ec5b9c33fb8d7bf7c0ad26
3,598,899
def gen_seq_obj_lst(file_contents): """ Takes the individual lines from a clustal .aln file Remove the first few lines. Make a sequence object list from the remaining. Sequence object will contain the sequence name (header), sequence and length """ sequence_list = [] for line in file_co...
6925b4c30d5c61aec9582a56894458ebf353eb27
3,598,900
import socket def sendethframe(src, dst, eth_type, payload, interface = "eth0"): """Send RAW Ethernet Frame.""" assert(len(src) == len(dst) == 6) # 48-bit ethernet addresses assert(len(eth_type) == 2) # 16-bit ethernet type s = socket(AF_PACKET, SOCK_RAW) s.bind((interface, 0)) return s.send(dst + src ...
fec62a08cbf3fc1ce1a18098ede63db9bfd43c12
3,598,901
from dynamix.correlator.event import EventCorrelator import time def gpu_ecorr_q(events, times, offsets, shape, nframes, dtype, qqmask, max_nnz): """ Calculation of the event correlation function using GPU :param events: 1D array of events values :param times: 1D array of times :param offsets: 1D arr...
0ac53f30f9a74e9f852620ef6025057f8f289e91
3,598,902
def label_contiguous_1d(X): """ WARNING: API for this function is not liable to change!!! By example: X = [F T T F F T F F F T T T] result = [0 1 1 0 0 2 0 0 0 3 3 3] Or: X = [0 3 3 0 0 5 5 5 1 1 0 2] result = [0 1 1 0 0 2 2 2 3 3 0 4] The ``0`` or ``Fal...
202e252e701d560cad3d4c86c15c48dd04bd0e7a
3,598,903
def merge_tables(tables_dict1: SINGLE_REPORT_TABLES, tables_dict2: SINGLE_REPORT_TABLES) -> MERGED_REPORT_TABLES: """Combine 2-column tables from single reports, to 3-column tables, with columns corresponding to each report.""" new_table_dict = defaultdict(list) for tab_name, tab_metrics1 in tables_dict1....
9b4514fd0b9266425f8bbd59a1427193e073c464
3,598,904
def pton_unpack6(address): """ Converts IPv6 address to int. Requires a string, returns a 128 bit int. """ try: pton = inet_pton(AF_INET6, address) except sockerror: return None unpacked = unpack("!QQ", pton) return (unpacked[0] << 64) | unpacked[1]
dbc0103d6a51f2cfa6b2cd4491e01280368d7a90
3,598,905
def _toledo8217StatusParse(status): """ Parse a scale's status, returning a `(weight, weight_info)` pair. """ weight, weight_info = None, None stat = status[status.index(b'?') + 1] if stat == 0: weight_info = 'ok' else: weight_info = [] if stat & 1 : weight_info.a...
83d8132398e740c71bdf3ac6f65f323f8c8ad65b
3,598,906
def pipe_map(n_caps, n_refs, differential=False): """ Creates the code->reference map for pipeline operation. Each column in this map contains the reference index to be used for the feedfoward capacitors. :param n_caps: Number of feedfoward capacitors with references, usually the number of stag...
93ae2866125cab889d4d3827b7b7b52341a984b6
3,598,907
import requests import dateutil def get_ninja_info(guid, customer_id, site_name): """ Pull the needed Student information from the dojo. This can be expanded but right now we are just getting the most current drop in program """ detail = requests.get( GENERAL_STUDENT_DETAIL.format( ...
aa21fb00628a357dd7015fc0e8f50ed8aa532094
3,598,908
def num_instances ( diff, flag=False ): """Counts the number of palindromic ages. Returns the number of times the mother and daughter have palindromic ages in their lives, given the difference in age. diff: int difference in ages flag: bool, if True, prints the details """ daughter = 0 ...
921953465596f9a9d5201cc62a2391880af4588e
3,598,910
def del_tx_sheet(request, sheet_id): """Deletes a treatment sheet.""" tx_sheet = get_object_or_404(TxSheet, id=sheet_id) if request.user == tx_sheet.owner: tx_sheet.delete() return redirect('/tx_sheet/') else: raise PermissionDenied
ea90ec12224f2b3e8cb3b38d872b5c1e6a834f80
3,598,912
import time def remove_unnecessary_edges(modifiedEdgeListUpdated, origin, destination): """ Function to remove any node, which is only connected to one other node and thus is unncessary. This is the case, because we have only postive edge weights. And thus, visiting the node to then just go back the node ...
1817c3a9c844f8d9753c6e086632dedc2c4829fc
3,598,913
def validateTelescopeModelName(name): """ Validate a telescope model name. Raises ------ ValueError If name is not valid. Parameters ---------- name: str Returns ------- str Validated name. """ telClass, telType = splitTelescopeModelName(name) t...
f696e9cacf45e94b376fa92b19c22483c0b9fa16
3,598,914
def seasonal_test(x_old, period = 12, alpha = 0.05): """ This function checks the Seasonal Mann-Kendall (MK) test (Hirsch, R. M., Slack, J. R. 1984). Input: x: a vector of data period: seasonal cycle. For monthly data it is 12, weekly data it is 52 (12 is the default) alpha: signi...
3f2a37e0e0bc062ad0a425afb68dd2e39a576025
3,598,915
def callform(request): """Render call form""" return render(request, 'helpline/callform.html')
e45309b30704480a79f739c82aba476d40615894
3,598,916
def model_flow_node_model_flow_id_node_id_component_put(model_flow_id, node_id): # noqa: E501 """update a node&#x27;s components information in a model flow chart update a node&#x27;s information in a model flow chart # noqa: E501 :param model_flow_id: model flow chart id :type model_flow_id: str ...
584a493efb379fecc8b7bcacfab607e2320f4f58
3,598,917
def draw_all_at_index(index): """ Draw all lotteries in the specific index Args: index(int): zero-based index that indicates the time of lottery Return: winners([[User]]): The list of list of users who won """ lotteries = Lottery.query.filter_by(index=index) ...
62816ae24ab901828c22468ee36066ef86a4beaf
3,598,918
import webbrowser def CreateOauthToken(expiration="30days", scope='read,write', key=None, secret=None, name='trellodump', output=True): """ Script to obtain an OAuth token from Trello. More info on token scope here: https://trello.com/docs/gettingstarted/#getting-a-token-from-a-user """ # Ste...
c83b85b68f2fe3f85f1455557a7a96df62a2d692
3,598,919
def mscorr(X, ref='mean'): """MSC base line correction for spectral data. Args: X (np.ndarray): The data set to correct. ref (list, np.ndarray): The reference spectrum. Returns: The data set corrected via MSC. Notes: * Implementation partially taken from: By Cleiton A....
9ed502ef9e7e10f791112da8f608a14c1f9ff88a
3,598,920
def gsl_blas_sdsdot(*args, **kwargs): """gsl_blas_sdsdot(float alpha, gsl_vector_float const * X, gsl_vector_float const * Y, float * result) -> int""" return _gslwrap.gsl_blas_sdsdot(*args, **kwargs)
4f81c22174d937ba7eb9bd7073759dda38df25e9
3,598,921
def generate_bm(df, experiment_keys): """ Given the flatten DataFrame, containing all the experiment here we extract the experiments correspondent to the dictionary experiment_keys. :param df: pandas DataFrame containing the flatten df :param experiment_keys: dictionary with all the keys. :returns d...
43f91e734419c76157920fe486db48e1c17ebdc5
3,598,923
from typing import Optional from typing import Union from typing import Iterable from typing import Dict def discover_datasets_unchecked( uuid_prefix: str, store: StoreInput, filter_ktk_cube_dataset_ids: Optional[Union[str, Iterable[str]]] = None, ) -> Dict[str, DatasetMetadata]: """ Get all known...
cdac0f0fd08801901c67d50bfecff4122ed30b0c
3,598,924
def findNextKeyForTargetEntry(ipAddr): """ Find the next available TargetEntry key """ key = "None" index = 1 while 1: key = "targetEntry{}".format(index) index += 1 keypath = cc.Path('/restconf/data/ietf-snmp:snmp/target={name}', name=key) response=aa.get(keypath) if response.ok(): if...
4358f88ac4791bb5cf36e9a50db964752501c4c5
3,598,925
def twitter_reply(reply_id, username, text): """ Args: reply_id: the tweet id that the bot is replying to username: the username of the account the bot is replying to text: what test the bot will use in its reply Returns: """ # This is a default if no text is input if...
6159aba6ec50eab18b0ccdfce35e16ceab90d425
3,598,926
def labeledFcn(fcn, paramNames): """Wraps a function with its parameter names (in-place). :type fcn: callable Python object :param fcn: function to wrap :type paramNames: list of strings :param paramNames: parameters to attach to the function :rtype: callable Python object :return: the orig...
e8885cf0cf4db4e84069ec4f0164748b0ab52ae3
3,598,927
def correct_spectra( df, correction ): """ Corrects a spectral DataFrame. :param df: DataFrame of spectra. :param correction: Series of correction with same index type as df. :returns: Corrected DataFrame. """ _, corr = std.common_reindex( [ df, correction ] ) # match index cdf = df.mu...
43c639d19753ba0fb51fba2f950f4024d43c5546
3,598,930
from traja.trajectory import _get_time_col def to_trajr(trj): """Convert trajectory to R `trajr` object. Default fps is 30. Args: trajectory (:class:`~traja.TrajaDataFrame`): trajectory Returns: traj (:class:`rpy2.robjects.vectors.DataFrame`): column names are ['x', 'y', 'time', 'displa...
9365605e5c48c853650a2573be7ff7583ceb13c1
3,598,931
def get_rfx_object(packetid): """Return the RFXObject with the packetid.""" try: binarypacket = bytearray.fromhex(packetid) except ValueError: return None pkt = rfxtrxmod.lowlevel.parse(binarypacket) if pkt is None: return None if isinstance(pkt, rfxtrxmod.lowlevel.Senso...
c60ffbbc7dee9423ddbec2107d5ae5951e78ae41
3,598,932
def get_mask(image, mask, class_ids): """Apply color overlay. image: RGB image [height, width, 3] mask: instance segmentation mask [height, width, instance count] Returns result image. """ overlay = image pd_mask = np.zeros([overlay.shape[0], overlay.shape[1], 5], dtype=np.uint8) #classchan...
d549e63904e95ac5a1e16a8bd766c15b9e106c8f
3,598,933
def sell_stock(stock, amount, limit_price, index): """ 卖出股票,并记录订单号,便于查询订单状态 :param stock: :param amount: :param limit_price: :param index: :return: """ try: sell_order = order(stock, amount, LimitOrderStyle(limit_price)) finally: g.__manager.work() if sell_or...
4c9415199b7a058e3234fe785708c9b3011989b6
3,598,934
import logging def FetchArrayByName(init_def, name): """fetch array by name""" for index, op in enumerate(init_def.op): if op.output[0] != name: continue if op.type != "GivenTensorFill": logging.error("The array {} is not contained" " by Given...
ef7d7a57ab5e72ae97a53675a0488f23e4d59564
3,598,935
from typing import Optional def calc_interpolation( val_0: pd.Series, val_1: pd.Series, wt_0: pd.Series, wt_1: Optional[pd.Series] = None, method: str = "linear", ) -> pd.Series: """Calculate interpolation between two values. Parameters ---------- val_0 : pd.Series zzz ...
81a00afbc1c5e60de3b8fd2f3b4dbf26fc20dd7b
3,598,936
def get_min_max(input_list: list) -> tuple: """ Return a tuple(min, max) out of list of unsorted integers. Args: input_list(list): list of integers containing one or more integers """ print("->get_min_max: input_list= " + str(input_list)) if len(input_list) == 0: return None, No...
26db872de57ed6c94825e089607a4bb81390b423
3,598,939
def _code_and_constants(object_): """Helper function to get python code and constants""" return _code_and_constants_attr_getter(object_.__code__)
0385a73ac2ed70e30cdaf3246ec722e4fe1d97da
3,598,940
from typing import Union def threshold_events( data: np.ndarray, threshold: Union[float, int] ) -> np.ndarray: """Apply threshold to find start and end of events. Arguments --------- data : np.ndarray Input data to apply thresholding to. threshold : float | int Threshold value...
066f799af2ecd245cd278d73aa1ce534475da571
3,598,941
import torch def value_td_residuals( rewards: torch.Tensor, values: torch.Tensor, next_values: torch.Tensor, discount: float, ) -> torch.Tensor: """Compute TD residual of state value function. All tensors must be one dimensional. This is valid only for one trajectory. Parameters ----...
723ed0f0ce651cc7da5ad9c7950972d104198888
3,598,942
from typing import List def get_dataset(organisms: List[Organism]): """ Builds a dataset with the samples associated with the given organisms """ dataset = {} filter_query = Q() for organism in organisms: filter_query = filter_query | Q(organisms=organism) experiments = Experiment.object...
af4edb3b09b8391c47efe31db83f88c2598650c5
3,598,944
async def agather(aiter): """Gather an async iterator into a list""" lst = [] async for elem in aiter: lst.append(elem) return lst
0a7f278d38237a722724572b6705deab429c8e70
3,598,945
import random def generate_Gnp_with_planted_clique(n, p, clique_size): """ Given a number of vertices n, a probability p and a clique size the method returns a networkx gnp graph with an additional planted clique i.e. from the Gnp graph we select a random subset of vertices of size clique_size and...
7ce98916c3a47e4af578474a3e83621fbf2e3c4d
3,598,946
def default_panels(institute_id, case_name): """Update default panels for a case.""" panel_ids = request.form.getlist('panel_ids') controllers.update_default_panels(store, current_user, institute_id, case_name, panel_ids) return redirect(request.referrer)
abfcffcf26e41be209eb35bf4230f0055b193ccf
3,598,948
def ParseImportLine(line): """Parse a line potentially containing an import. Note that this function does NOT properly handle: from foo.bar import FooClass It's too expensive to code for and against Python style anyway. Args: line: string, like "from x import y" or "import x.y" Returns: None:...
2f1d2fe3bd3744e09826bf2625e3bb2c6796494c
3,598,949
def client_inner_dirichlet_partition(targets, num_clients, num_classes, dir_alpha, client_sample_nums, verbose=True): """Non-iid Dirichlet partition. The method is from The method is from paper `Federated Learning Based on Dynamic Regularization <https://openreview.net/foru...
90828ef055f520d62aecb1ac92c6622121fba4ad
3,598,950
def filterTCPString(TCPMessage): """ Remove any unwanted characters from the TCP message string and truncate if necessary """ # sometimes a failed command will return html which end up in (e.g.) pilotErrorDiag, remove it if TCPMessage.upper().find("<HTML>") >= 0: # reset here. the error diag will b...
3f17c7ca4c7bb738e055127b1150bbbcbffd8653
3,598,951
from datetime import datetime import pytz def now(): """Returns the ISO 8601 formatted time in UTC""" return datetime.now(pytz.utc).isoformat()
e423e8555315f551f284c92f4fee5b3f92c1f41d
3,598,952
def carmichaellambda(n): """carmichaellambda(n) - Computer Carmichael's Lambda function of n - the smallest exponent e such that b**e = 1 for all b coprime to n. Otherwise defined as the exponent of the group of integers mod n.""" thefactors = factors(n) thefactors.sort() thefactors += [0] # Mark the end of the...
c076deb1a8216c2da32a2f83cc224bf3fe6b5040
3,598,953