content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import requests def requests_get(url): """Make a get request using requests package. Args: url (str): url to do the request Raises: ConnectionError: If a RequestException occurred. Returns: response (str): the response from the get request """ try: r = reque...
a438d211e6b5bf78af56783b5d22c85961a2d563
3,625,600
def get_mysensors_name(gateway, node_id, child_id): """Return a name for a node child.""" node_name = '{} {}'.format( gateway.sensors[node_id].sketch_name, node_id) node_name = next( (node[CONF_NODE_NAME] for conf_id, node in gateway.nodes_config.items() if node.get(CONF_NODE_NAME) ...
67eca81ce4af653f603687048d2cc748400cd951
3,625,601
import math def bloch_sunburst(vec, colormap): """Create a Bloch disc using a Plotly sunburst. Parameters: vec (ndarray): A vector of Bloch components. colormap (Colormap): A matplotlib colormap. Returns: go.Figure: A Plotly figure instance, Raises: ValueError: Input...
fdfc47975ff11e8fcf871a9890da94ae4b87ad56
3,625,602
def link_models(): """return settings or default""" return getattr(project_settings, 'HTML_EDITOR_LINK_MODELS', ())
abeb92515c4604fc9d301c7f70692c5b93b2ad73
3,625,603
def _join_dicts(*dicts): """ joins dictionaries together, while checking for key conflicts """ key_pool = set() for _d in dicts: new_keys = set(_d.keys()) a = key_pool.intersection(new_keys) if key_pool.intersection(new_keys) != set(): assert False, "ERROR: dicts ...
2dee7a6f6a89d310d6a58e35d14c57e8ddb5b804
3,625,604
def resolve(segments): """ given the predicts of a segment from multiple files (as a pandas Series), return a new class (as a pandas Series) """ # strategy: weight each probability by the relative size of its area # first calculate the relative size of each segment segments['area'] = segments['area']/su...
b02708acb4a19ec59a3dc0f489e81b70fe53105c
3,625,605
def getCandidates(fi, fo, sLang, dLang): """Check if a url could be a candidate or not.""" nCandidates = 0 for line in fi: line = line.rstrip() # tld url crawl<TAB>json_data url = getURL(line) url_components = normalize(url) mapS = rulesOn(url, url_components, sLan...
2b6c966f1ef38999de009d00fc26219c2c853417
3,625,606
def set_passphrase(module, **kwargs): """Adds or replace a LUKS passphrase in a give slot. Return: <result> <error>""" for req in ["device", "slot", "valid_passphrase", "new_passphrase"]: if req not in kwargs: return False, {"msg": "{0} is a required parameter".format(req)} is_keyf...
7eff574d565a7d3b93a3d607d8053b3bbe84dcc5
3,625,607
def run_train(config, data, inds): """ Sets splitter. Partitions train/val/test. Loads model from config. Trains and evals. Returns model and eval metrics. """ train_inds = inds["train_inds"] val_inds = inds["val_inds"] test_inds = inds["test_inds"] model = keras_gcn(config) los...
e0b96a3b64dc63ab94c7605198bfa8978d9f5d8b
3,625,608
import os def get_upgrades(): """ Returns nested list of available upgrade paths""" files = [x for x in os.listdir(sql_folder) if x.endswith('.sql')] versions = [(x[:-4].split('_to_')) for x in files] return [tuple(int(j) for j in i) for i in versions]
49c43cb72e0f85b725fa580d41d007115cd38b3b
3,625,609
def cases_vs_deaths(df): """Checks that death count is no more than case count.""" return (df['deaths'] <= df['cases']).all()
994ae93fb23090de50fc4069342487d0d8e621ed
3,625,610
from typing import Optional def retrieve_ledger_details_data( token_address: str, data_id: str, issuer_address: Optional[str] = Header(None), db: Session = Depends(db_session)): """Retrieve Ledger Details Data""" # Validate Headers validate_headers(issuer_address=(issuer_a...
07eafff1e68124a5ce4836e4b1c413b161b442dd
3,625,611
def sim1c_error(target_stats, cmr_stats): """ Sim 1c fits only the conditional SPCs and PFR, and uses mean squared error instead of chi-squared error because standard errors are not available. """ y = [] y_hat = [] # Fit SPC and PFR for stat in ('spc_fr1', 'spc_frl4', 'pfr'): ...
b52f592a9a31d16b622d25b1072b66a62007806f
3,625,612
from datetime import datetime def is_between(thing, start=None, end=None): """ given a thing with a date, returns true if the thing is between the start and end date Parameters ---------- thing: dict the thing that we want to know whether or not is after a date start: datetime.date obje...
6dc41a16a90d63f8f62a0c1a9a5ee57d2cacd562
3,625,613
import os def list_files_in_dir(dir_path): """ List out files only from a target directory path. """ if not os.path.isdir(dir_path): raise ValueError('`dir_path` must be a directory.') return iter(f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)))
c502799d34ba5fd1a89a574cfb78d722e6ce4a8c
3,625,614
import math def CreateBoxOnStick(point1, point2, tipRatio=0.3): """ Creates an stick with a box as tip from point1 to point2. Use tipRatio for setting the ratio for tip of the arrow. """ direction = map(lambda x, y: x - y, point2, point1) length = math.sqrt(sum(map(lambda x: x ** 2, direction))) unitDir = map...
c541d02f68e0d82811adab819943a1e7270743ff
3,625,615
import os def is_platform_file(path): """ Return True if the file is Mach-O """ if not os.path.exists(path) or os.path.islink(path): return False # If the header is fat, we need to read into the first arch with open(path, 'rb') as fileobj: bytes = fileobj.read(MAGIC_LEN) ...
3e689194339d3ffa53db828a077040d272e39fca
3,625,616
def _calcFiberLength(fiberData, fidx): """ * INTERNAL FUNCTION * Calculates the fiber length via arc length INPUT: fiberData - fiber tree containing tractography information fidx - fiber index OUTPUT: L - fength of fiber """ no_of_pts = fiberData.pts_per_fiber if n...
7d0f97ca1b13333a710d5beac66593b4b963e5a7
3,625,617
def choose_license_and_version( license_url=None, license_=None, license_version=None ): """ Returns a valid license pair, preferring one derived from license_url. If no such pair can be found, returns None, None. Three optional arguments: license_url: String URL to a CC license page....
d16a966cc0e212eb47a1a8c91abc9b8711483ff4
3,625,618
def default_options(add_flags=True, flags=None): """Creates a DeepVariantOptions proto populated with reasonable defaults. Args: add_flags: bool. defaults to True. If True, we will push the value of certain FLAGS into our options. If False, those option fields are left uninitialized. flags: obj...
2370e1242c30dc1221876040222dde0a1fff027a
3,625,619
def alert(title=None, message='', ok=None, cancel=None, other=None, icon_path=None): """Generate a simple alert window. .. versionchanged:: 0.2.0 Providing a `cancel` string will set the button text rather than only using text "Cancel". `title` is no longer a required parameter. .. version...
fb81cffedca7e2a16a3412f743c5741254e95abf
3,625,620
import os def evaluate(metric, netG, log_dir, evaluate_range=None, evaluate_step=None, num_runs=3, start_seed=0, overwrite=False, write_to_json=True, device=None, **kwargs): """ Ev...
8c15232229d0b574695e9f653d947f2701419753
3,625,621
def _split_data(data, FEATURES, sort_keys=True, TEST_SIZE=TEST_SIZE, SEED=SEED, scale=False): """ extracting features, split data """ data = featureFormat(data, FEATURES, sort_keys=sort_keys) y, x = targetFeatureSplit(data) if scale: scaler = StandardScaler() x = scaler.fit_transform(x) ...
691f70c4b64f7a619bef64150e5bfedad5f35f53
3,625,622
import os import secrets def random_quote(): """Retrieve a correctly formatted quote.""" quote_file = f"{get_full_path('etc')}/quotes" quote_list = [] if not os.path.isfile(quote_file): return '', '' else: with open(quote_file, 'r') as quote_h: for line in quote_h.readl...
8de0d0a7b8a4b8b812bea1939c544212123d49e7
3,625,623
import inspect from sys import path def get_test_loc( test_path, test_data_dir, debug=False, must_exist=True, ): """ Given a `test_path` relative to the `test_data_dir` directory, return the location to a test file or directory for this path. No copy is done. Raise an IOError if `must_...
b05e2ba7754ad0e4f2f32f2a1ca4d3e4d10eb075
3,625,624
def widget_url(widget, action='', prefix=None): """Returns the URL of the controller to perform `action` on `widget`. If no `prefix` is passed the it will be tried to be fetched from `tw.framework.request_local` where the :class:`WidgetBrowser` leaves it on every request. Example:: >>> fr...
6bf49da76a4e483b47a587f2657b84b39ea74269
3,625,625
from typing import Dict from typing import Any from typing import Union def build_transformer_block( net_part: str, block: Dict[str, Any], pw_layer_type: str, pw_activation_type: str, ) -> Union[EncoderLayer, TransformerDecoderLayer]: """Build function for transformer block. Args: net...
8a6b8659f520b6c5caa9406e6611173ebca0383f
3,625,626
def mondiode_value(fits_file, _, factor=5): """Compute the effective monitoring diode current by integrating over the pd current time history in the AMP0_MEAS_TIMES extension and dividing by the EXPTIME value. """ with fits.open(fits_file) as hdus: x = hdus['AMP0.MEAS_TIMES'].data.field('AMP...
4691418d8bf811662fb1c4552e52f9809d54fbd7
3,625,627
def get_loss_fn(loss_config, model): """Creates a loss function based on loss_config. Args: loss_config: (dict) loss config with following parameters: - name: (str) name of the loss - params: (dict) loss parameters if any model: a model which its parameters might be used for defining ...
dbab26412353850ac0a8e404d2bcddb0cfad97c5
3,625,628
import os def main(Files, FoilDyn, FoilGeo, axs, plot_col=1, dataOutput = False, cutoff = 0.15): """Go into wall shear folder and process raw data""" FoilDyn.cutoff = cutoff data_path = Files.data_path print('\n' + Files.project_name) if Files.org_path == 'None': savePath = Files.fold...
dc3009527513233808e121ff3e65d04923fa9bb4
3,625,629
import os import pandas def pick_from_log(log_path: str, min_epoch: int = 50): """Read training log from checkpoint folder.""" log_name = '-'.join(os.path.basename(os.path.dirname(log_path)).split('-')[:-3]) dataset = os.path.basename(os.path.abspath(os.path.join(log_path, '..'))).split('-')[-1] if no...
9dac79b59a967318df476dc47c72867f27c39b5c
3,625,630
import re def add_pronom_link_for_puids(text): """If text is a PUID, add a link to the PRONOM website""" PUID_REGEX = r"fmt\/[0-9]+|x\-fmt\/[0-9]+" # regex to match fmt/# or x-fmt/# if re.match(PUID_REGEX, text) is not None: return '<a href="https://nationalarchives.gov.uk/PRONOM/{}" target="_bla...
5fdc9c15895dfd75be54ad0258e66625462204a2
3,625,631
def delete_vit(request): """ Delete a vit with API """ user = KeyBackend().authenticate(request) if request.method == "POST": if request.user.is_authenticated: try: vit = Vit.objects.get(id=request.POST.get('vit_pk')) if vit.user == request.user: ...
0713a0d108745ff96fda083ae9e1413943e3a43a
3,625,632
def convert(df_column): """ Converts a DataFrame column to list """ data_list = [] for element in df_column: data_list.append(element) return data_list
6cd0f9b445573892612e01e0e3e25eb32d658be4
3,625,633
def get_model(embedding_matrix, name='baseline_model'): """ create model. :return: model """ num_class = 4 inputs = tf.keras.layers.Input(shape=(config.MAX_SEQUENCE_LENGTH,)) embedding = tf.keras.layers.Embedding(embedding_matrix.shape[0], embedding_matrix.shape[1], ...
b388d7251a8bd1b5b87bc9c55fdabb795b0500e0
3,625,634
import requests def _get_remote_svg_tile(hass, host, port, prefix, name, width_tiles, c1, c2): """Get remote SVG file.""" url_tile = URL_TILE_MASK.format(host, port, prefix, name, width_tiles) ok, r_svg, status = False, None, -1 try: r_svg = yield from hass.async_add_job( partial(r...
af34d22684b71a49c7c71de59fbe8cff479b3220
3,625,635
def sub(a: PipeNumeric, b: PipeNumeric): """ Pipeline node which subtracts b from a. Optimization is performed where possible. The return type is int if both parameters were integer and so the result is static. Otherwise a OneCycleNode is returned. :param a: parameter a :param b: parameter b...
4d80ae6b2d62a865b567924f7acc1a6cc7dca490
3,625,636
from typing import Mapping from typing import Any import textwrap def format_nested_dicts(value: Mapping[str, Mapping[str, Any]]) -> str: """ Format a mapping from string keys to sub-mappings. """ rows = [] if not value: rows.append("(empty)") else: for outer_key, outer_value i...
79d029a062f0e2545265ecdf5d8cdacb271c40c2
3,625,637
def MD5collect(signatures): """Deprecated. Use :func:`hash_collect` instead.""" _show_md5_warning("MD5collect") return hash_collect(signatures)
7124bbadfb3cea785463da15dadbc2fb4ac17c39
3,625,638
import profile def adadelta(lr, tparams, grads, inp, cost, opt_ret=None, rho=0.99, eta=1e-7): """ Adadelta optimizer :param lr: :param tparams: :param grads: :param inp: :param cost: :param opt_ret: :param rho: adadelta rho :param eta: adadelta eta :return f_grad_shared, f_...
be74e3d4f02c6a2249104a2312027f4d97dbf68d
3,625,639
import random def shuffle_string(s): """ Shuffle a string. """ if s is None: return None else: return ''.join(random.sample(s, len(s)))
25d109f11737b60cecf391fd955f2df4366de7e6
3,625,640
def get_or_create_tables(options, session, create=True): """ Load or create canonical ORM KB Core table classes. Parameters ---------- options : argparse.ArgumentParser session : sqlalchemy.orm.Session Returns ------- tables : dict Mapping between canonical table names and SQLA ORM classes. e.g. {'origin...
f9c7e12575146ea1d4c7f47302772284cc5412af
3,625,641
def dmp_zeros(n, u, K): """ Return a list of multivariate zeros. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.densebasic import dmp_zeros >>> dmp_zeros(3, 2, ZZ) [[[[]]], [[[]]], [[[]]]] >>> dmp_zeros(3, -1, ZZ) [0, 0, 0] """ if not n:...
d6f33a2a40143c6ad4f379ab242e5960c3c79294
3,625,642
def to_ea(*args): """ to_ea(reg_cs, reg_ip) -> ea_t Convert (seg,off) value to a linear address. @param reg_cs (C++: sel_t) @param reg_ip (C++: ea_t) """ return _ida_ida.to_ea(*args)
d7909944ff1852d0eb37416e67b54c8e673fbf7e
3,625,643
from fileio.spec_load_write import async_rspec_scaled, rspecLoader from fileio.utils import fns from spectrum.utils import mutli_scale from typing import Union from typing import Iterable from typing import Tuple def get_chi_analysis_pipeline( primary_spectrum: Union[ Spectrum, str ], speclist: Iterable[ Union[ Spect...
ae504bdd9f3042cb2fac85cfdb2db1b2b95525fa
3,625,644
from typing import List from typing import Counter def rank(words: List[str], exclude_stopwords: bool = False) -> Counter: """ Sort words by frequency :param list words: a list of words :param bool exclude_stopwords: exclude stopwords :return: Counter """ if not words: return None...
d80d2ea92e1aa19b0400041fd8a49576d8e91b9f
3,625,645
def get_restaurant(request): """ 通过openid获取餐厅信息 """ openid = request.GET.get('openid', None) try: restaurant = Restaurant.objects.get(openid=openid) except Restaurant.DoesNotExist: return Response('restaurant not found', status=status.HTTP_404_NOT_FOUND) serializer = Restaur...
ad00c7bc0cd273b4e93b5d22e12d798600542f4d
3,625,646
def level_info(): """Returns True if info logging is turned on.""" return get_verbosity() >= INFO
895dd82b221c0cd4514c77005968d48e53dad78f
3,625,647
def _get_low_and_high_version_from_range(version_range): """ Parse a version range into its low and high components. :param version_range: the version range :return: the low and high version components, an empty string is returned if there is no upper bound """ _method_name = '_get_low_and_high_...
7d8e82b784a2bfc0c2d51997378a769fdb8d1a36
3,625,648
def get_rule_full_description(tool_name, rule_id, test_name, issue_dict): """ Constructs a full description for the rule :param tool_name: :param rule_id: :param test_name: :param issue_dict: :return: """ issue_text = issue_dict.get("issue_text", "") # Extract just the first lin...
546dcb5ce2cbc22db652b3df2bf95f07118611cf
3,625,649
def generate_config(context): """ Entry point for the deployment resources. """ resources, outputs = create_dashboard_resource(context) return {"resources": resources, "outputs": outputs}
ef89fabe24fc63079cec06a186dc46b31ef5fc07
3,625,650
import tqdm def index_embedding_words(embedding_file): """Put all the words in embedding_file into a set.""" words = set() with open(embedding_file) as f: for line in tqdm(f, total=count_file_lines(embedding_file)): w = Vocabulary.normalize(line.rstrip().split(' ')[0]) word...
7a1378698bad45a8ba7ffff99f9e316aeb9d5b9c
3,625,651
def dst(): """Simple spatial graph nodes where all but one have been translated""" dst = np.array([[0,0], [1,0.1], [0,1.1], [1,1.1]]) return dst
488d54abb891133a67d7ff0281a99dd6468c50ef
3,625,652
import itertools def check_length(seed, random, query_words, key_max): """ Google limits searches to 32 words, so we need to make sure we won't be generating anything longer Need to consider - number of words in seed - number of words in random phrase - number of words in the lists from the qu...
14871b468454f324223673a0c57941ea9e63341a
3,625,653
def warp_from_camera_motion(R0, t0, R1, t1, normal, distance, K1, K0_inv=None): """ R0, t0: source camera pose in object frame. R1, t1: target camera pose in object frame. normal, distance: normal and distance of object's principal plane (in object frame.) K1: target camera's intrinsics K0_...
5897af5241318a943e97477dc9dfa87b240c0b8e
3,625,654
def mcar_test(df, significance_level=0.05): """ Function for performing Little's chi-square test (1988) for the assumption (null hypothesis) of missing completely at random (MCAR). Data should be multivariate and quantitative, categorical variables do not work. The null hypothesis is equivalent to sayin...
ca6c308fe76fcade214bc4e9638b1840d6eba7b3
3,625,655
def sind(x): """Trigonometric sine using :func:`np.sin <numpy.sin>`, element-wise with an input in degree. Parameters ---------- x : array_like Input array in degree. Returns ------- y : array_like The corresponding tangent values. This is a scalar if x is a scalar. ""...
010976eb7f25370c26ee0e4a4ff19828629ba68b
3,625,656
import logging def _stretch_intensity(image, smoothing_sigma=2.0): """Stretches the intensity range of the image to (0, 255).""" output = image * 1 blurred = (gaussian(output, sigma=smoothing_sigma) * 255).astype('uint8') i_max = blurred.max() i_min = blurred.min() logging.info('Stretching i...
ae129cb3fd2df883fb2b6f50a1016898dc137767
3,625,657
def is_string(val): """ Is the supplied value a string or unicode string? See: https://stackoverflow.com/a/33699705/324122 """ return isinstance(val, (str, u"".__class__))
99b082ec080f261a7485a4e8e608b7350997cf18
3,625,658
def inner_join(table_left, table_right, column): """ Inner join. If columns are repeated, the left table has preference. :param table_left: :param table_right: :param column: :return: """ if column not in table_left.keys: raise ValueError('{} not in left table'.format(column)) ...
c8ec19cc4da9bdb43091fe1867f040ac82f76104
3,625,659
from datetime import datetime def time_string(): """ Generate a string of numbers generated from now time (UTC). """ # UTC time up to microseconds time_str = datetime.utcnow().strftime("%Y%m%d%H%M%S") return time_str
c7258004db459563a1d229119b6148584cc72584
3,625,660
def colorvsn1(studydata, column, context): """Please convert numeric codes of 0 and 99 to the text strings they represent.""" return column.mask(column == 0, 'No').mask(column > 90, "Don't Know")
3f05a3a78d1368e6116fa52366079c22dd183bc3
3,625,661
from typing import Any from typing import Dict from typing import Union from typing import List def flatten_omegaconf(cfg: Any) -> Dict[Any, Any]: """Recursively flatten a nested Dict into a simple one. The difference between this function and `recurse` is that the dictionnary produced by this one doesn'...
2b5a6e4ec57b3949079aa836f74a15c0a45b608d
3,625,662
def reports(request, report, casetype='Call'): """Handle report rendering""" query = request.GET.get('q', '') datetime_range = request.GET.get("datetime_range") agent = request.GET.get("agent") category = request.GET.get("category", "") form = ReportFilterForm(request.GET) dashboard_stats = ...
9406a8421c8eb1047446e986d9ee297f41e7132c
3,625,663
def score(hand): """ Compute the maximal score for a Yahtzee hand according to the upper section of the Yahtzee score card. hand: full yahtzee hand Returns an integer score """ max_score = 0 sorted_hand_list = sorted(list(set(hand))) for i_mem in sorted_hand_list: temp_sco...
b1fae3c67793a96b040f8abae41514bef2c5b89c
3,625,664
from typing import Dict from typing import Union def mismatched_units_matching_numbers_of_integer_digits( digits: int, num_trials: int ) -> Dict[str, Union[str, float]]: """The hardest subtask. The input units and output units can all differ. The number of digits supplied to both inputs is the same. """...
b85ad67ee2c01b12f1fbf39460d40cc56a638826
3,625,665
def context_get(stack, name): """ Find and return a name from a ContextStack instance. """ return stack.get(name)
a5a9a50c54e8f0f685e0cf21991e5c71aee0c3d6
3,625,666
def get_first_published_date(organization): """ Get first publisher date from an organization. Check if the date is invalid, get the date :param organization: :return: """ _invalid_dates = ('No data published', 'Date not found', 'Date is not valid') # Check if publisher date already exists....
8b1b39352d7aa72c37599656abff4027dc716c56
3,625,667
import os def test_vars(env_vars): """Method to identify the active and inactive environment variables for a specific conda environment test_vars ========= This method is used to get the active and inactive environment variables for a specific conda environment created by ggd. Parameters: ...
f24f2b18c028984ab1dd4e11832a39fcba48d946
3,625,668
from typing import Optional def determine_redemption_annuity( months_to_legal_maturity: int, outstanding_balance: float, interest_rate: float, annuity: Optional[float] = None, ) -> float: """Calculate the redemption of an annuity mortgage. On basis of the outstanding_balance at the start ...
61dceb3d550bf58085a627fe6892ba372d05d433
3,625,669
import os def _read(fname): """Returns content of a file. """ fpath = os.path.dirname(__file__) fpath = os.path.join(fpath, fname) with open(fpath, 'r') as file_: return file_.read()
a2e3cc99b1e83d2554fd27b11b1200bcfa6a3184
3,625,670
def getversion(online=True): """Return a pywikibot version string. @param online: (optional) Include information obtained online """ data = dict(getversiondict()) # copy dict to prevent changes in 'cache' data['cmp_ver'] = 'n/a' if online: try: hsh3 = getversion_onlinerepo...
07c7b6e721b342bd7b5695e6be7a3cc9e49ad6c9
3,625,671
def euclidean_distance(X1, X2): """ Function to compute the euclidean distance between two vectors :param X1: Vector 1 :param X2: Vector 2 :return: Scalar euclidean distance between X1 and X2 """ return np.sqrt(np.sum(np.square(X1 - X2), axis=1))
738b1cf9811319a2f995fe2790d08eae6cedc138
3,625,672
import json async def get_exchanges_for_market(symbol, collections_dir='./'): """ Returns the list of exchanges on which a market is traded """ try: with open('{}collections.json'.format(collections_dir)) as f: collections = json.load(f) for market_name, exchanges in collec...
30138efa8f77b3c5f36c90bdcf82c8e79d43bf44
3,625,673
import os import pickle def load_demonstrations(demo_dir, env_name): """Load expert demonstrations. Outputs come with the following format: [ [{observation: o_1, action: a_1}, ...], # episode 1 [{observation: o'_1, action: a'_1}, ...], # episode 2 ... ] Args: demo_dir: directory ...
5a9637170595658957370e9e8d712a5ccd2989ca
3,625,674
def projectNodePosOnly(pt, upVec, p0, v1, v2): """ Project a point pt onto a triagnulated surface and the solution that is the closest in the positive direction (as defined by upVec). pt: The initial point upVec: The vector pointing in the search direction p0: A numpy array of triangle orig...
97099b485b4125a476105f654214044fd1f0a090
3,625,675
import time import csv import base64 def load_obj_tsv(fname, topk=None, hide_images=False): """Load object features from tsv file. :param fname: The path to the tsv file. :param topk: Only load features for top K images (lines) in the tsv file. Will load all the features if topk is either -1 or N...
af21bae644dac06a8458899fa562082bd43b2641
3,625,676
def get_scalar_metrics(means, logvar, Y_val, n_MC): """ Estimate predictive log likelihood: log p(y|x, D) = log int p(y|x, w) p(w|D) dw ~= log int p(y|x, w) q(w) dw ~= log 1/n_MC sum p(y|x, w_k) with w_k sim q(w) = LogSumExp log p(y|x, w_k) - log n_MC ...
9840f8b4baaa8f8d04409e996c606e79f9a3b75c
3,625,677
from typing import Counter from typing import Pattern def extract_patterns(df): """ Extracts the unique patterns of contestation in an electoral system. Mimicks Linzer 2012's `findpatterns` R function. Arguments ---------- df : data frame dataframe containing vote values ...
6c45dcfe9db2fe708b59656fdbce2233788692df
3,625,678
import uuid import json def group_api(request): """ 状态码说明: 200:成功 60001: 数据库操作异常 60002:etcd推送异常 60003: 不支持的请求 接口返回结果示例:{resultCode:200,data:response,info:u'成功'} """ """ 创建组接口 """ if not request.user.has_perm('home_application.can_add_groups'): return ...
9a95a1a2c2dc5e75e150b91211f48d826e8dc696
3,625,679
def tree_names (tree): """Get the top-level names in a tree (including files and directories).""" return [x[0] for x in list(tree.keys()) + tree[None] if x is not None]
12a5522974671f3ab81f3a1ee8e8c4db77785bd3
3,625,680
def update_information_first(update=False): """ Decorator to wrap :class:`Information <ansys.mapdl.core.misc.Information>` methods to force update the fields when accessed. Parameters ---------- update : bool, optional If ``True``, the class information is updated by calling ``/STATUS``...
a25c3c9aab10ce78bcc78819069fbd071ca5bbb2
3,625,681
def find_key(key: str, up: any): """根据key提取Value""" if dict == type(up): if key in up: return up[key] else: for dict_key, dict_value in up.items(): if dict == type(dict_value) or list == type(dict_value): result = find_key(key, dict_val...
d0a92bdb99d3c3fd3255aa1bbc68249114302a26
3,625,682
def main(): """ 适合存在可能影响最大最小值的异常点的大量数据 归一化处理异常值偏差较大的情况时容易出问题, 需要使用标准化 标准化将原始数据处理到均值为0, 标准差为1的范围 x_final = (x - avg) / sigma 也即是, (x - 该列平均值) / 标准差 标准差的计算为: 1. 计算平均值 avg 2. 计算方差, 即该列所有值 (x1 - avg)^2 + (x2 - avg)^2 + (x3 - avg)^2 + ... + (xn - avg)^2 / (n - 1) 3. 方差开方的结果即是标准差 sigma...
06f5d2171c413d0d3a18375fa4d4074239263cd5
3,625,683
def get_class_names(file_meta, aspect_table): """ Creates and looks up names for classification, i.e. classifications that are not found in the database (custom) will be generated and existing ones (non-custom) looked up in the classification_definitions table. The name is generated as a combination of ...
372613500cf6bda23b06fb983b6f52eeae02a4fd
3,625,684
from typing import Any def get_attrs(expr: relay.expr.Expr) -> Any: """Get the attributes from an expression.""" if isinstance(expr, Call): return expr.attrs if isinstance(expr, TupleGetItem): return get_attrs(expr.tuple_value) return {}
377cf7f40943e35605543f145646f36a7334abc6
3,625,685
def clastic_decorator(subdecorator): """ If a decorator needs to accept *args and/or **kwargs, this function makes that possible by precomputing the argspec of the to-be-wrapped function and propagating it to the decorated version, where it is available to clastic for computing dependencies. ...
33c55effa6a0053bb976de49281c54353ee77b4d
3,625,686
from datetime import datetime def process_snapshots(os_client, dry_run): """Delete every expired snapshot""" destroyed_snapshot = 0 errors = 0 for snapshot in os_client.block_storage.snapshots(status="available"): try: log.debug("Looking at snapshot", snapshot=snapshot.id) ...
30082fa9992f061d355a8c6a5197616793704506
3,625,687
def fixed_width_repr_of_int(value, width, pad_left=True): """ Format the given integer and ensure the result string is of the given width. The string will be padded space on the left if the number is small or replaced as a string of asterisks if the number is too big. :param int value: An inte...
adb212746dd081112ec1de2c4ea8745d2601c055
3,625,688
def _getCompiledName(fldName, clsName): """Return mangled fldName if necessary, else no change.""" # If fldName starts with 2 underscores and does *not* end with 2 underscores... if fldName[:2] == '__' and fldName[-2:] != '__': return "_%s%s" % (clsName, fldName) else: return fldName
91285b7c54e001d807850c66ac74521e55d05ca4
3,625,689
import os import pickle def get_api_client(): """Establish connection and set up an API client using credentials.""" # Disable OAuthlib's HTTPS verification when running locally. # *DO NOT* leave this option enabled in production. os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" api_service_name =...
1c5c230c9287a12cbc944fad3005b56fa02c6916
3,625,690
def backward_subd(U, y, pr): """Given a lower triangular matrix U and right-side vector y, compute the solution vector x solving Ux = y.""" # x = zerod(len(y)) x = [De(0.0) for ix in y] for i in range(len(x), 0, -1): val_i = (y[i-1] - dot(U[i-1][i:], x[i:])) / U[i-1][i-1] aa = '{}:.{...
8308c2d406c5ceb56b1b5970ac0b993f75c24874
3,625,691
from typing import Dict from typing import List def get_recoverable_databases(credentials: Credentials, subscription_id: str, server: Dict) -> List[Dict]: """ Returns details of the Recoverable databases in a server. """ try: client = get_client(credentials, subscription_id) recoverabl...
7b3ee0011089cce4d4e5c763d63798c38984cd1e
3,625,692
async def async_get_service(hass, config, discovery_info=None): """Get the Tibber notification service.""" tibber_connection = hass.data[TIBBER_DOMAIN] return TibberNotificationService(tibber_connection.send_notification)
c8f98df6b1a9a832b139c187d99aab4f03d1d9e5
3,625,693
def get_project(datasource): """Get the project info from given datasource Args: datasource: The odps url to extract project """ _, _, _, project = MaxComputeConnection.get_uri_parts(datasource) return project
2a4dc6412a0e942a1d690912efc09993eaeac147
3,625,694
def pearson_correlation_terms(co_elements, first_set, second_set, first_set_avg, second_set_avg): """ Description A function which returns the pearson correlation terms between two elements. Arguments :param co_elements: Number of co-elements. :...
9c7e723e0717e39e8dd295c2ed3e4998740cc6c8
3,625,695
import torch def train(clf, onehot_encoder, params): """ Trains the model given training data. Arguments: clf (class) : lstm model params (dict) : contains model, dimension, and batch parameters Returns: clf (class) : the trained model """ num_epochs = params['num_epoch...
a0f4da082403ab402dd9ea44cf25dc935e940893
3,625,696
def get_sorted_qlist_wstats(course_id, topic_id, user_id=None): """ Return a list of questions, sorted by position. With some statistics (may be expensive to calculate). """ def cmp_question_position(a, b): """Order questions by the absolute value of their positions since we use -...
95418a585dc73bda35a3bc5a132781d5942fbe03
3,625,697
def get_telem_values(tstop, msids, days=7): """ Fetch last ``days`` of available ``msids`` telemetry values before time ``tstop``. :param tstop: start time for telemetry (secs) :param msids: fetch msids list :param days: length of telemetry request before ``tstop`` :returns: astropy Table ...
3d11b30be1842cc9736df27a2b79c8ac62fd3ce4
3,625,698
import torch def doc_vocab2multi_hot(doc_vocab, vocab_size): """ Input doc_vocab: batch_size * max_doc_vocab_size Return multi-hot tensors: doc_vocab_mh: batch_size * vocab_size """ # logger.info('doc_vocab: {}'.format(doc_vocab.size())) doc_vocab_mh = torch.zeros([len(doc_vo...
86d9d0c4ea1ab761aa683195831f4d93e2a247ba
3,625,699