content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import math def format_float(number, decimal_places): """ Accurately round a floating-point number to the specified decimal places (useful for formatting results). """ divisor = math.pow(10, decimal_places) value = number * divisor + .5 value = str(int(value) / divisor) frac = value.sp...
e7aaa92025284489075ce053319c27310bb96a00
3,631,961
def make_mean_edisp( observations, position, e_true, e_reco, low_reco_threshold=Energy(0.002, "TeV"), high_reco_threshold=Energy(150, "TeV"), ): """Compute mean energy dispersion. Compute the mean edisp of a set of observations j at a given position The stacking is implemented in :...
3f8ba4d8f6434dd0e6711f691dc650a061ee2a9e
3,631,962
import time def formatTime ( sec, nsec, fmt ): """ Convert given time to a string presentation according to a given control sequence """ # replace %f (and its variations) with fractional seconds match = _ffmtre.search ( fmt, 0 ) while match : # make replacement string sub...
ad7e2b553545093b7834007453774bdb4cd62507
3,631,963
def CalculateChi6ch(mol): """ ################################################################# Calculation of molecular connectivity chi index for cycles of 6 ---->Chi6ch Usage: result=CalculateChi6ch(mol) Input: mol is a molecule object. ...
240d97be1740b9af691598cd71d47473ce770d53
3,631,964
def decode_transaction_filter(metadata_bytes): """Decodes transaction filter from metadata bytes Args: metadata_bytes (str): Encoded list of transaction filters Returns: decoded transaction_filter list """ transaction_filter = [] if not metadata_bytes: return None for i in...
c76638f6592fb098e2878471746152aa9df9a694
3,631,965
def get_signin_box(burl): """ xxx """ box_content = '' if user_is_login() == 0: l_app_header_title = 'Create unlimited optimized trading strategies' l_app_header_desc = 'Chart patterns, price movements, '+\ 'and news analysed using quantitative methods '+\ 'with the power of...
4181779ad6e8ce7924c2854e4e6e9b7d0d47926b
3,631,966
import json def jsonify(*args, **kwargs): """ jsonify with support for MongoDB ObjectId """ return Response( json.dumps( dict( *args, **kwargs), cls=MongoJSONEncoder), mimetype='application/json')
8001fe488e412bbf63cad7c9c359431fe9108b2c
3,631,967
def parse_variable(srcline, funcname=None): """Return a Variable for the variable declared on the line (or None).""" line = srcline.strip() # XXX Handle more than just static variables. if line.startswith('static '): if '(' in line and '[' not in line: # a function retur...
ff4027f1e3919087016c8169ff1ad8ac7ebf111b
3,631,968
def _assert_df_is_valid_cforest(candidate_model): """Assert *df* represents valid causal forest. A valid causal forest model is given by a pd.DataFrame which fulfills the following criteria: 1 (MultiIndex). The data frame *df* must have a MultiIndex with the first layer 'tree_id' and the second layer '...
cf1c52037705ce86940ca4c9e6fdf4b1055dea65
3,631,969
def is_ip(str_value: str) -> bool: """Returns True if string represents and IP address (either IPv4 or IPv6), else False. :param str str_value: String to evaluate. """ return is_ipv4(str_value) or is_ipv6(str_value)
1438148ab98ce882cd5e27961268726bae4450e0
3,631,970
def parse_ply(fin): """Parse vertex data from a PLY format Retuns a dictionary of keys to numpy arrays """ num_pts, attr_key, attr_type = parse_ply_header(fin) data = [[] for k in attr_key] for i in range(num_pts): line = next(fin) tokens = line.split() for j, t in enum...
13558f96b55d2155cc032771acda272cfa7e5d0b
3,631,971
def energy_change_charge_qa_atom( df_qc, df_qats, target_label, delta_charge, target_initial_charge=0, change_signs=False, basis_set='aug-cc-pV5Z', use_ts=True, ignore_one_row=True, considered_lambdas=None, return_qats_vs_qa=False): """Calculate the energy difference to change the charge of a target ato...
30c8b15a5e25edd0d05352066a1e3533c5182cd6
3,631,972
def load_key_string_pubkey(string, callback=util.passphrase_callback): # type: (str, Callable) -> PKey """ Load an M2Crypto.EC.PKey from a public key as a string. :param string: String containing the key in PEM format. :param callback: A Python callable object that is invoked ...
9283aff352a84cb99a382f88d6f7cca5ea0ee837
3,631,974
def merge(left, right, path=None): """Merge dicts""" if path is None: path = [] for key in right: if key in left: if isinstance(left[key], dict) and isinstance(right[key], dict): merge(left[key], right[key], path + [str(key)]) elif left[key] == right[...
cb313f153225af41626885ae0ee066215dce3b0e
3,631,976
def resize_min_side(pil_img, min_len): """ Resize image such that the shortest side length = mins_len pixels :param pil_img: :param mins_len: :return: """ # What's the min side? w, h = pil_img.size if w < h: new_w = min_len new_h = int(np.round(h * (new_w / float(w)))...
38aeeedf107bedf2c82948248fbdc2483d6d2c10
3,631,977
def get_numeric_boundaries(df: DataFrame, column_name: str) -> (float, float): """ get the min and max values in a numric column. forces a cast to float. If the column can't be casted as such then this wil throw an error which is currently not trapped :param df: :param column_name: :return: (min...
a02eefd1d6e6f2697350d5e48201e57cbb24c870
3,631,978
from typing import Optional def concatenate(data: tvm.te.Tensor, axis: Optional[int] = 0): """Join a sequence of arrays along an existing axis. Optimized for CPU exeution. Parameters ---------- data : tuple of tvm.te.Tensor The arrays to concatenate axis : int, optional The axis ...
d9bb934f9518a565dab341316247294c525ea2c1
3,631,979
def defgrad_from_strain(E, kappa, flatten=1): """Compute the deformation gradient from the strain measure Parameters ---------- E : ndarray (6,) Strain measure kappa : int or float Seth-Hill strain parameter flatten : bool, optional If True (default), return a flattened ...
3b18515562c3dd30757f9942627ac082eb3947b7
3,631,980
import hashlib def get_url_gravatar(email): """ Obtenemos una url de gravatar """ m = hashlib.md5() m.update(email.encode('utf-8')) url = "http://www.gravatar.com/avatar/{0}.jpg?s=300".format(m.hexdigest()) return url
bf48d903445869ee91c685dd1b84e11034dc528c
3,631,981
def volume_type_qos_disassociate_all(context, qos_specs_id): """Disassociate all volume types from specific qos specs.""" return IMPL.volume_type_qos_disassociate_all(context, qos_specs_id)
16ff0f985dd96d1f2a3aa32022c06c84a1c5f531
3,631,982
def create_command_at_set(command_set, command): """ create a command on set """ command_entry = CommandEntry.objects.create( command_set=command_set, command=command ) return command_entry
a4e8367077f5a42b62e27be1e66f2a4c5cf490d0
3,631,983
def get_index_image(): """Formats html. Returns: Modified index.html content """ return """<!DOCTYPE HTML><html lang="en-us"> <head> </head> <body style='margin:0'> <img src='image.[[image_ext]]'> </body> </html>"""
41ea7fbc31e49879216e46083b102294edb5c76f
3,631,984
def merge_schema(original: dict, other: dict) -> dict: """Merge two schema dictionaries into single dict Args: original (dict): Source schema dictionary other (dict): Schema dictionary to append to the source Returns: dict: Dictionary value of new merged schema """ source =...
6425b64e6ab166ac14afc2e47392745903b8fd12
3,631,985
def noise_eq_bandwidth(window, axis=-1): """ Calculate the noise equivalent bandwidth (NEB) of a windowing function as sqrt(window.size * window.max ** 2 / sum(window ** 2)) See https://analog.intgckts.com/equivalent-noise-bandwidth/ Args: window : float ndarray axis : int,...
dd13abac6b9d39b68a1b3658fe4fba90be8c82cf
3,631,986
import hashlib def hash160(s: bytes) -> bytes: """ sha256 followed by ripemd160 :param s: data :return: hashed data """ return hashlib.new('ripemd160', hashlib.sha256(s).digest()).digest()
7b18fcdf51db707a17d5408c7b364818a6c5ee0c
3,631,987
def trim_frame(fr: NDFrame, freq: str) -> NDFrame: """Trim index of frame to only keep full periods of certain frequency. Parameters ---------- fr : NDFrame The (untrimmed) pandas series or dataframe. freq : str Frequency to trim to. E.g. 'MS' to only keep full months. Returns ...
c8b87ea993510725dc8f4074eeb07ea029445f0a
3,631,988
def settings_alert_rules(request): """ To allow users to manage alert rules for given sites """ context_dict = {} sites = _get_user_sites(request) user_sites = _get_user_sites(request) context_dict['permitted'] = get_org_edit_permissions(request.user) context_dict['sites_stats'] = g...
b8e1326abdb96929f3451c6aae06093f94de0723
3,631,989
from typing import List def generate_states_1qubit(c_sys: CompositeSystem, names: List[str]) -> List[State]: """returns a list of states on a common 1-qubit system. Parameters ---------- c_sys: CompositeSystem 1-qubit system names: List[str] list of 1-qubit state names Retur...
3c4188d50181a9a7c21b50f2b655cb212249c9e2
3,631,990
def fix_columns(data, text_1_name=None, text_2_name=None, label_name=None): """ Rename columns in an input data frame to the ones bisemantic expects. Drop unused columns. If an argument is not None the corresponding column must already be in the raw data. :param data: raw data :type data: pandas.Da...
7a87e853f5f5e41afcb4ec0a40ebddea234ca289
3,631,991
def unpack_kgrid(n, vals, log=null_log): """ Unpack the 'pyramid' of values u>=v>=w into the (n,n,n) k-grid. n - the size of the grid vals - m(m+1)(m+2)/6 values in the pyramid returns out - (n,n,n) float64 array. """ lib = _initlib(log) v = require(vals, dtype=float64, require...
62d7a364d43cc2c4cf1c181aa054d94200ea53a1
3,631,993
import re def valid_email(email): """Check for a valid email address. Args: email (str): Email. Returns: bool: Return True if in valid email format and False if not. """ return bool(re.match('^[a-zA-Z0-9.!#$%&โ€™*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$', email))
01c343008229fb2fdf2af3a9a74f3059930696eb
3,631,994
import traceback def db_remove(key): """ Endpoint Function to interact with PupDB's remove() method. """ try: if not key: return {'error': 'Missing parameter \'key\''}, 400 try: result = DB.remove(key) except KeyError as key_err: return {'error': s...
e354fe2f648cd4ad5c8ff7804789488b01edbe6c
3,631,995
def rgb2gray(img): """ Given an RGB image return the gray scale image. Based on http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale img = 0.299 R + 0.587 G + 0.114 B """ print('Converting RGB image to gray scale.') return np.uint8(np.dot(img[...,:3], [0.299, 0.587, 0.114]))
37207a3f66e5008a358f3e4961e809ca658687bc
3,631,996
def search(): """่Žทๅ–้šๆœบๆŽจ่""" html = '<form action="/blog/search/" method="get" name="form" ><div class="my-search" >' \ '<input type="text" name="q" autocomplete="off" placeholder="่ฏท่พ“ๅ…ฅๆœ็ดขๅ†…ๅฎน" class="search-input">' \ '<i class="layui-icon layui-icon-search search-btn" onclick="javascript:form....
86a02c2de79476ae6bea7cd733e502658a5f7555
3,631,997
def find_number(text, ignore_spaces=False, make_int=True, ignore_chars=None): """ Find the number in the `text`. :param text: unicode or byte-string text :param ignore_spaces: if True then groups of digits delimited by spaces are considered as one number :raises: :class:`Dat...
d15c5468e965913a6b885f3f5835ed7441481e6f
3,631,998
def PeerDownHasBgpNotification(reason): """Determine whether or not a BMP Peer Down message as a BGP notification. Args: reason: the Peer Down reason code (from the draft) Returns: True if there will be a BGP Notification, False if not """ return reason == 1 or reason == 3
8ee214798f6766916e8784dd907eeb45ff6620db
3,631,999
def productos_pos(): """ Muestra las configuraciones para productos pos """ productos = db(db.maestro_pos).select() return dict(productos=productos)
87e80d5789f65df46c3178a9d83e575321b423a7
3,632,000
def _build_measurement_vectors(ppci): """ Building measurement vector z, pandapower to ppci measurement mapping and covariance matrix R :param ppci: generated ppci which contains the measurement columns :param branch_cols: number of columns in original ppci["branch"] without measurements :param bus_...
b51be7da841ce5c54942834133d64263fcf29ff1
3,632,001
import zipfile from io import StringIO import numpy import json import pickle def load(path): """Load data and reconstruct model.""" with zipfile.ZipFile(path,'r') as zf: buf = StringIO.StringIO(zf.read('weights.npy')) weights = numpy.load(buf) config = json.loads(zf.read('config.json...
bee50593f16a534c16f9961e53aaf6a31b5bd3d1
3,632,002
def env( a, import_models=False, c=None, f=None, dir='', ): """ Return web2py execution environment for application (a), controller (c), function (f). If import_models is True the exec all application models into the environment. """ request = Request() response ...
3d78e71866eb1daf06e6e20e9437a0bf39210363
3,632,003
import copy import hashlib import json def get_payload_hash(payload): """Return unique hash of HySDS job JSON payload.""" clean_payload = copy.deepcopy(payload) for k in ('_disk_usage', '_sciflo_job_num', '_sciflo_wuid'): if k in clean_payload: del clean_payload[k] return hashlib....
e5122c85c3bfc358dda0404d029d06efbe2fefde
3,632,004
def binStack(array, bins, id0=1): """ Bin a hyperstack according to a known list of frames per bin @param array: input array to be binned, hyperstack or otherwise. Binning occurs along the first axis @type array: numpy.ndarray @param bins: list of frames in each bin. Each index in bins is a...
3367566a37e6328cd8af039e91a40d176b488617
3,632,005
import torch def knn(A, B, k, distFcn): """ Returns the indices of the k-nearest neighbors of A in B Parameters ---------- A : Tensor a (N,F,) tensor B : Tensor a (M,F,) tensor k : int the number of neighbors to find distFcn : callable the distance func...
f9c3bac58ff3fcffe53bb9b2a25ffbcc57870ec9
3,632,006
def set_purpose(slack_client, channel, purpose): """ Set the purpose of a given channel. """ response = slack_client.api_call("channels.setPurpose", purpose=purpose, channel=channel) return response
786a495b55300b955e2f7ec525117be75b251a07
3,632,007
def masked_minimum(data, mask, dim=1): """Computes the axis wise minimum over chosen elements. Args: data: 2-D float `Tensor` of size [n, m]. mask: 2-D boolean `Tensor` of size [n, m]. dim: The dimension over which to compute the minimum. Returns: masked_minimum: N-D `Tensor`. The minimize...
7629c1a2ba9c2089935a68354d748a80e1eff488
3,632,009
import json def decode_stderr_json(stderr): """ return a list of decoded json messages in stderr """ # - check for blank input if not stderr: # - nothing to do return list() # - split the input (based on newlines) into list of json strings output = list() for line in stderr.spl...
d527730d8d9a77a1ec434ee6203c4e08433306c9
3,632,011
import collections def hash_params(params): """ Construct a data structure of parameters that is hashable. This requires changing any mutable data structures into immutable ones. We chose a frozenset because role parameters have to be unique. .. warning:: this does not handle unhashable scalars...
eb83122e2b1f7097917f1029e84f2053352127f4
3,632,012
def get_validate_result_form(tel_num, validate_code): """ Assemble form for get_validate_result :param tel_num: Tel number :param validate_code: Validate code from capcha image :return: Param in dict """ post_data_dict = dict() post_data_dict['source'] = 'wsyyt' post_data_dict['telno...
6340c97522a097c0cf96170e08466fb795e16dc3
3,632,013
def create_user(): """Create a new user record.""" request = flask.request.get_json() try: # NOTE(jk0): We expect all of these keys to exist to be considered a # valid user record. Ignore all others. user = _lookup_user(request["userid"]) if user: flask.abort(40...
8d98667aba51172535768d6c57d9fc8f2e2e7821
3,632,014
def softmax_cross_entropy(logits, labels): """ Cross-entropy loss applied to softmax. """ one_hot = hk.one_hot(labels, logits.shape[-1]) return -jnp.sum(jax.nn.log_softmax(logits) * one_hot, axis=-1)
c0850fdebbf69629763e94c489ed0aaf67e67184
3,632,015
def get_category_detail(comp_id, cat_id): """Retrives information about the category and the reviews in it""" json = [Category.query.filter_by(id=cat_id).filter_by(comp_id=comp_id).first_or_404().to_json()] submissions = Submission.query.filter_by(comp_id=comp_id).all() cat_submissions = [] for _, s...
d6b780a8d2c985f55a6500faf386c437669d0e9a
3,632,016
def build_input_from_segments(persona, history, reply, vocab, labels=False, with_eos=True): """ Build a sequence of input from 3 segments: persona, history and last reply. """ bos, eos, speaker1, speaker2 = vocab[SPECIAL_TOKENS[:-1]] sequence = [[bos] + list(chain(*...
3b47bbc0fb7c666188f36a1e1df520d84327d336
3,632,017
from scipy.stats import norm def dual_gaussian(x, amp1=1.0, mean1=0.0, std1=1.0, amp2=1.0, mean2=0.0, std2=1.0): """Sum of two Gaussians. Parameters ---------- x : array Function argument amp1: float Amplitude parameter of the first Gaussian mean1: float Mean parameter of th...
6d46ffcfcfd0327d06ccc8c92157bd9f82813124
3,632,018
def get_district_info(request, code): """ Get district info by 'code' """ try: district = District.objects.get(code=code) child_districts = District.objects.filter(parent=district.code) data = district_model2dict(district) children = [district_model2dict(c) for c in child...
57136fe7d77375b6d9c258b42bccf24e4c7a3750
3,632,020
def calculate_price(prices, concentrations): """ From a list of prices in $USD / kg and concentrations in mass %, calculate the price of the formulation in $USD / kg """ # Normalise ingredient concentrations concentrations = np.asarray(concentrations) / np.sum(concentrations) # Calculate a...
7131bb0aa5f9502f564e43eba76ee3b878041b22
3,632,021
def cos_convolve(evidence): """Take as input the classifier evidence for single trials in dictionary format and return alligned evidence and evidence convolved with a cosine. Input: dictionary: accuracy : ndarray dimensions: time matrix containing class predi...
cf292eb0af8d4f44a0d64c02b9a09e6b7d149eb9
3,632,022
from io import StringIO def get_image_info(real_image_type, body): """ only in webp, gif, png, jpeg, bmp """ image_fp = StringIO(body) if real_image_type == 'webp': data = image_fp.read() width, height = decode.GetInfo(data) image_pix_count = int(width) * int(height) else:...
9570de917deafdcaa2d2a2d208e40710bcb12d04
3,632,023
def estimate_ranks(layer): """ Unfold the 2 modes of the Tensor the decomposition will be performed on, and estimates the ranks of the matrices using VBMF source: https://github.com/jacobgil/pytorch-tensor-decompositions/blob/master/decompositions.py """ weights = layer.weight.data unfold_0 = ...
3c4efeb5ad56a32ad3908657c013bfb153aaf01e
3,632,024
def _add_batch_dim(img): """Many TF functions require NWHC input. Convert WHC image to NWHC of batch size 1.""" get_hwc(img) # validate dimensions return tf.expand_dims(img, 0)
53a995d6a1398f137abb69b38aa91b98257e50c3
3,632,025
def read_inventory_file(inventory): """ Read an inventory file, return the list of dicts :param str inventory: The inventory file :return list[dict, ..]: List of hostname and IP definitions """ log.info("Reading and validating inventory file") inventory_hosts = load_json(inventory) if no...
cff1d3c84b3617b12e4bee7b4726207d4d4747cd
3,632,026
def ground_truth_to_word(ground_truth): """ Return the word string based on the input ground_truth """ try: return ''.join([config.CHAR_VECTOR[np.argmax(arr)] for arr in ground_truth if np.argmax(arr) < len(config.CHAR_VECTOR)]) except Exception as ex: print(ground_truth) ...
ae07266f34f01d605705d60e7c331cefb1fb845a
3,632,027
import itertools def build_dataframe(dimension_names, dimension_members, data_values, null_values, sd_values): """Build a dataframe from dimensions and data. Adds the cartesian product of dimension members plus the series of data. Args: dimension_names (list of string) ...
1d5621d753466a69bd0bef4120c2c445e959bbb9
3,632,028
def fs_url_exists(fs_url): """ verifies for a valid fs url :param fs_url: fs_url string :return: boolean """ try: fs.open_fs(fs_url) except fs.errors.CreateFailed: return False return True
98aad242d04b169e1a1e3204bf40e0b4ac9c4018
3,632,029
def _serialize_noise_model(config): """Traverse the dictionary looking for noise_model keys and apply a transformation so it can be serialized. Args: config (dict): The dictionary to traverse Returns: dict: The transformed dictionary """ for k, v in config.items(...
f3453e174d5ba858b9eec678e7bc1574f74d50eb
3,632,030
def create_app() -> falcon.API: """ Typical application factory style setup. Returns: falcon.API: The falcon API object. """ engine = create_engine("sqlite:///") app = falcon.API(middleware=[DbSessionMiddleware(engine)]) app.add_route("/", ExampleResource()) return app
ab134f8d25644da01718a16e4887d023f5e0221f
3,632,031
def show_tracker(secure=False): """ Output the analytics tracker code. """ google = getattr(settings, 'ANALYTICS', {}) if google: analytics_code = google.get('ANALYTICS_CODE') if analytics_code: return {"analytics_code": analytics_code} return {}
32d30b031e979cf91165dba4872a93995289bbc4
3,632,032
def metric_max_over_ground_truths(metric_fn, predictions, ground_truths): """Take the average best score against all ground truth answers. This is a bit different than SQuAD in that there are multiple answers **and** predictions that we average over. For some situations (e.g., *top k* beams or multiple human r...
7c78fc1cca29bc9784a4e4687d794c1f2b6872c9
3,632,036
def parse_gsod_data(filename): """Parse Global Summary of the Day (GSOD) data from a comma separated .txt file. Source: https://www7.ncdc.noaa.gov/CDO/cdoselect.cmd?datasetabbv=GSOD&countryabbv=&georegionabbv= Format Specification: https://www7.ncdc.noaa.gov/CDO/GSOD_DESC.txt Parameters: ...
963444222e7627c25354ec6d0d891df4fee4fe8c
3,632,037
def deserialize(xml): """ Deserializes a Pubmed response into an article object.""" article = {} root = ET.fromstring(xml) article_el = root.find('.//PubmedArticle') if article_el is None: print('INFO: XML did not contain a Pubmed Article.') return None pmid_el = article_el.find('.//MedlineC...
5cdb8c622f9155eaf36659bd9cab092e3adc4c44
3,632,038
def attSummaryDict(request, reqs, flist): """ Return a dictionary summarizing the field values for the chosen most interesting fields """ sumd = {} for req in reqs: for f in flist: if f in req and req[f]: if not f in sumd: sumd[f] = {} if not req[f] i...
bafbbe51555cb46c664d33ea31a0e36c56152fa9
3,632,039
def immutable_kwargs( kwargs: tp.Dict[str, str] ) -> tp.Tuple[tp.Tuple[str, str], ...]: """ Convert str-typed kwargs into a hashable tuple. """ return tuple((k, v) for k, v in kwargs.items())
900e263e0a7928bfb2c65e3dc7f9c8e405014fb5
3,632,040
import numpy def revise_max_intake( max_intake, total_digestibility, energy_intake, energy_maintenance, degr_protein_intake, protein_req, animal_type, CRD1, CRD2): """Calculate revised maximum intake from protein content of the diet. When animals are unable to obtain enough protein from the d...
cfe61d2717fcf42104423499e1e1343873c905a0
3,632,042
from pegasusio.cylib.io import read_fcs def load_fcs_file(input_fcs: str, genome: str = None) -> MultimodalData: """Load Cyto data from a FCS file, support v2.0, v3.0 and v3.1. Parameters ---------- input_fcs : `str` The FCS file. genome : `str`, optional (default None) The genom...
232b849679c209863fdc3cc17ad1dc254ed23ab0
3,632,043
def ext_bottom_up_cut_rod(price, length): """ bottom up implementation of cut rod memoized algorithm """ incomelst = [float("-Inf") for _ in range(length + 1)] cutlst = [0 for _ in range(length + 1)] # set zero income for zero length incomelst[0] = 0 for j in range(1, length + 1): income...
7dd8c43afa9f71793d372b474963ff84d2ce607f
3,632,044
def _build_config_dict(cfg_node): """ Updates the config dict provided from the given etcd node, which should point at a config directory. """ config_dict = {} for child in cfg_node.children: key = child.key.rsplit("/").pop() value = str(child.value) config_dict[key] = va...
567fca19a6e1890c881170200ba44fc262148948
3,632,045
import time def stamp_to_ymd(timestamp): """ Caller sends a timestamp in seconds of epoch. Return string for year month day of that time as YYYYMMDD' as used by url requests, as in http://<fitsstore_server>/qaforgui/20130616 parameters: <float>, seconds of epochs. return: <string>, YYYYM...
2928e93a48f1a5c3abdddcb6285bed7b0cebb369
3,632,046
def ESMP_GridCreateCubedSphere(tilesize, regDecompPTile=None, #decompFlagPTile=None, deLabelList=None, staggerLocList=None, name=None): """ Preconditions: ESMP has been initialized.\n Postconditions: An ESMP_Grid has been created.\n Arguments...
999d9b995671af9e410f73e29b2e1af8d79ad5a4
3,632,047
def version() -> str: """็‰ˆๆœฌๅท""" return f'Version: {VERSION}'
df0dee3edebdaf24b52a9ad128b5198c89c779a5
3,632,050
import ctypes def UnpackMessage(swig_obj_pointer, msg_name): """Unpack a SWIG-wrapped memory object into an AIO message. Args: swig_obj_pointer: A SWIG-wrapped memory object pointing to the raw AIO message payload. msg_name: Name or short name of the message type. Returns: An AIO message s...
2e445f5248ba023190298eec30e0e473804f3df5
3,632,051
def a2b_hashed_base58(s): """ If the passed string is hashed_base58, return the binary data. Otherwise raises an EncodingError. """ data = a2b_base58(s) data, the_hash = data[:-4], data[-4:] if double_sha256(data)[:4] == the_hash: return data raise EncodingError("hashed base58 ha...
82276533405e952f8f89cf3caefce6e653ab5694
3,632,052
def predict(theta, X): """ computes the predictions for X using a threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1) """ return np.array([1 if theta.dot(xi) >= 0.5 else 0 for xi in X])
3a80add19d08989f94cb3f9e4c058a37bd128f20
3,632,053
def not_contains(a, b): """Evaluates a does not contain b""" result = False if b in a else True return result
a0dc087049c8e93c1acdf0e59e3530a6ff8b54e5
3,632,054
def build_positional_encoding(cfg, default_args=None): """Builder for Position Encoding.""" return build_from_cfg(cfg, POSITIONAL_ENCODING, default_args)
9db2eb7d88b5d4ceea0a9d62adc3239035a34cec
3,632,055
def create_func_result_identifier(func, params_str, key=None, key_separator="__"): """ Creates a string of the following format: If ``key`` is None: ``<FUNC_NAME><PARAMS_STR>`` If ``key`` is not None: ``<FUNC_NAME><PARAMS_STR>__key`` In both cases, ``<FUNC_NAME>`` represents the name of...
6f3a7a6a8a94629dae7817403d78ef1f970ad5b2
3,632,056
def quat_to_euler(q): """ Converts a unit quaternion: q = (w, x, y, z) = w + (x i, y j, z k) into the aircraft Euler angles (roll, pitch, yaw) = (phi, th, psi). """ R00 = 1 - 2*q[2]**2 - 2*q[3]**2 R10 = 2*q[1]*q[2] + 2*q[3]*q[0] if np.sqrt(R00**2 + R10**2) >= .000001: phi = np...
507e26d657a868bc136c901612ffba5dff62975d
3,632,057
def idc_get_local_type_name(*args): """ idc_get_local_type_name(ordinal) -> char """ return _ida_typeinf.idc_get_local_type_name(*args)
c0921c70f0f42d913bbbe4e6d41a02a58660da0e
3,632,058
import csv def import_town(data_file): """ Reads town raster data from a CSV file. Parameters ---------- data_file : str Name of CSV raster data file to use for the town. Returns ------- town : list List (cols) of lists (rows) representing raster data of the town. ...
b7749dfd4d698fddfe610c6a51c8ccc43c375cc2
3,632,059
def init_network(): """์‹ ๊ฒฝ๋ง(neural network)์—์„œ ์‚ฌ์šฉ๋˜๋Š” ๊ฐ€์ค‘์น˜ ํ–‰๋ ฌ๊ณผ bias ํ–‰๋ ฌ์„ ์ƒ์„ฑ ๊ต์žฌ p.88 ์ž…๋ ฅ์ธต: (x1, x2) -> 1x2 ํ–‰๋ ฌ ์€๋‹‰์ธต: - 1st ์€๋‹‰์ธต: ๋‰ด๋Ÿฐ 3๊ฐœ (x @ W1 + b1) - 2nd ์€๋‹‰์ธต: ๋‰ด๋Ÿฐ 2๊ฐœ ์ถœ๋ ฅ์ธต: (y1, y2) -> 1x2 ํ–‰๋ ฌ W1, W2, W3, b1, b2, b3๋ฅผ ๋‚œ์ˆ˜๋กœ ์ƒ์„ฑ 1x2 2x3 3x2 """ np.random.seed(1...
ddf727e651d46523f83d5d4e870c26e6bbc0b54c
3,632,060
def make_connection(): """Connection function to establish database connection. During development, the connection information will be hard coded, however during actual deployment to AWS, the connection information will be retrieved from other services eg aws secret manager etc. Returns: ...
fa69c2752444cbee1d5630ee829bd5ebc4c0e0c5
3,632,063
import random def a_noun(random=random, *args, **kwargs): """ Return a noun, but with an 'a' in front of it. Or an 'an', depending! >>> mock_random.seed(0) >>> a_noun(random=mock_random) 'an onion' >>> a_noun(random=mock_random, capitalize=True) 'A Chimp' >>> a_noun(random=mock_random...
1eae1f7b445017d64fc17fe0364275d73ead1b87
3,632,064
def _tree_flatten_with_names(tree): """Populates tree_flatten with leaf names. This function populates output of tree_flatten with leaf names, using a custom traversal that produces names is provided. The custom traversal does NOT have to traverse tree in the same order as jax, as we take care of automatical...
2878ece5d63d09d42d4b195706a4594b135ce849
3,632,065
def inhomogeneous_poisson_process(rate, as_array=False, refractory_period=None): """ Returns a spike train whose spikes are a realization of an inhomogeneous Poisson process with the given rate profile. Parameters ---------- rate : neo.AnalogSignal A `n...
240b04f5e5ed316d911aad0ee690516982f123cd
3,632,066
import re def enumerate_quotes(filename, encoding="utf-8", empty_name="Inconnu"): """ Enumerates quote from a filename or a stream @param filename filename or stream @param encoding applicable only if filename @param empty_name replces an empty author name @r...
51e3a406c05ab81ade918123ee4fba801fb9ef9e
3,632,067
def _params_to_df(params: Parameters) -> DataFrame: """Convert lmfit.Parameters to pandas.DataFrame.""" return DataFrame( [ (p.name, p.vary, p.value, p.stderr, p.min, p.max, p.brute_step, p.expr) for p in params.values() ], columns=( "name", ...
7485f43a474eef1ebb20ddb73bb411dad52cd918
3,632,068
def w(P, T, region = 0): """ Speed of sound [m / s]""" if region is 0: region = idRegion(P, T) if region is 1: return region1.w(P, T) elif region is 2: return region2.w(P, T) else: return 0.000
7589c57071484d0f46e67a18bd125ad46edbe777
3,632,069
def WaitForOperation(api_version, response, asynchronous): """Handles waiting for the operation and printing information about it. Args: api_version: Cloud Domains API version to call. response: Response from the API call asynchronous: If true, do not wait for the operation Returns: The last inf...
518e68421082bb3a2a90b38ae62c5be02f20d9fb
3,632,070
from datetime import datetime def generateVtBar(symbol, d): """็”ŸๆˆK็บฟ""" bar = VtBarData() bar.symbol = symbol bar.vtSymbol = symbol bar.open = d['open'] bar.high = d['high'] bar.low = d['low'] bar.close = d['close'] bar.volume = d['volume'] bar.openInterest = d['open_oi'] ...
d155bda31fba71f07af4d23d17fcaa09c6a277e4
3,632,071
def search_file(drive_service, num_of_responses, query): """ Search for files and store results of query in pd.DataFrame """ results = ( drive_service.files() .list( pageSize=num_of_responses, q=query, fields="nextPageToken, files(id, name, kind, expor...
b7bb340f0c1bb89bc76ecc420b473609a0bbbb2c
3,632,073
from datetime import datetime import numpy def L6_summary_daily(ds,series_dict): """ Purpose: Calculate the daily averages or sums of various quantities and write them to a worksheet in an Excel workbook. Usage: L6_summary_daily(ds,series_dict) where ds is an OzFluxQC data structure ...
d1f57bb364abd7c92b73eab2d9787f5893264a3c
3,632,074
def check_eol(file, eol): """Check file EOL. :param file: Path to file to check :param eol: Expected End of Line :return: Resulting error messages :rtype: str """ error = '' with open(file, 'rb') as open_file: content = open_file.read() if eol == '\n': if b'\r\n' i...
44bb060531c50ab5d072906414b8c948c9d6ecfa
3,632,075