content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def filter_tb(tbexeclist, tbinfo, tbexecgolden, tbinfogolden, id_num): """ First create filter list, then find start of filter, then call recursive filter """ filters = build_filters(tbinfogolden) tbexecpd = tbexeclist """Sort and re-index tb exec list""" tbexecpd.sort_values(by=["pos"], asc...
14efeb75479a995b61a7d8505289a6c564f6fff2
3,621,500
import html def render_controls_box(data): """Render "top left" controls for the box plot for the given ``data``.""" return html.Div( [ html.Label("select grouping"), dcc.Dropdown( id="expression_box_select_group", options=[{"label": c, "value": ...
aba30ddf43d04cc523d7b78ba3efce3cf5522381
3,621,501
def resolve_node(ib, node_id, node_description, default_timeout=None): """ Resolve node description :param str node_id: The internal unique identifier of the node. :param node_description: The description of the node type. This will be resolved to :ref:`Node Definition <nodedefinition>`, which ...
c00cf6042dbd46474ad248c979e75fdd9cf81404
3,621,502
def anc_at_rank(tax_id, tax_df, rank): """Return the ID of the parent of a taxon at a given rank.""" # Check to see if we are already at this rank if tax_df.loc[tax_id, "rank"] == rank: return tax_id # Otherwise, walk up the parents until you find it else: for anc_tax_id in path_to...
9bb2f8282623ec86897ceaced0f0df0f122def5f
3,621,503
def reverse_domain_from_network(ip_network): """Create reverse DNS zone name from network address (ipaddress.IPv4Network)""" prefixlen = ip_network.prefixlen if prefixlen % 8: return ip_network.reverse_pointer # classless else: return ip_network.network_address.reverse_pointer[(4 - (pr...
0b0b7bb6bc72cae6625e9bd024c9692253d55c88
3,621,504
def build_violations(res): """Build an expected violation. Args: res (Resource): resource to create violation from. Returns: RuleViolation: The violation. """ violation_data = { 'full_name': res.full_name, 'resource_type': res.type, 'locations': res.location...
0ec59c23817edac1fccccb9b8b1f2db7c89bd9f1
3,621,505
def use_no_vasp(original_wf, ref_dirs): """ Instead of running VASP, does nothing and pass task documents from task.json files in ref_dirs to task database. Args: original_wf (Workflow) ref_dirs(dict): key=firework name, value=path to the reference vasp calculation directory Return...
64dba2139f74c0c621e88fc239bd5d374c35683b
3,621,506
def load_model(config, shape): """Load a model.""" model = create_model(wili.n_classes, shape) print(model.summary()) return model
a41e4b5cc7f9b9bc1511df07d18b130d9c6d1476
3,621,507
import networkx as nx from networkx.utils import create_py_random_state def random_ordered_tree(n, seed=None): """ Creates a random ordered tree TODO ---- - [ ] Rename to random_ordered_directed_tree ? - [ ] Merge in with other data generators? Parameters ---------- n : int ...
1dcca06f5103b24487306cb42797f67933be0808
3,621,508
def player1(): """Return a list of sample names.""" # Use Pandas to perform the sql query stmt = db.session.query(players).statement df = pd.read_sql_query(stmt, db.session.bind) # Return a list of the column names (sample names) # return jsonify(list(df.columns)[2:]) return jsonify(list(d...
f2567bde5363cf1b43e36e075a73a326cb7c366c
3,621,509
from datetime import datetime import pytz def get_past_date(str_days_ago: str, to_date: datetime = None, tz: pytz.tzinfo = pytz.utc) -> object: """ Returns date in specified timezone relative to to_date parameter. e.g. '5 hours ago', 'yesterday', '3 days ago', '4 months ...
74e3adb335ba7e922eac2d7834a112cf9ab6ea2d
3,621,510
import math def get_cosine_similarity(text1_: str, text2_: str) -> float: """ Calculate cosine similarity between two strings This code is taken from with few modifications: https://stackoverflow.com/a/15174569 :param text1_: :param text2_: :return: """ # convert text to vector ...
61eb76fca8f8845e0ab7be15bf768c788feb3b81
3,621,511
def read_dyn(filename, natoms=None): """Read one dynamical matrix file (for 1 qpoint) produced by ``ph.x`` and extract the same as :func:`read_matdyn_modes` for this qpoint only. All arrays have one dim less compared to :func:`read_matdyn_modes`. Parameters ---------- filename : str Na...
b5b1bf300fec9c37075241e932465bf942fb7006
3,621,512
def visualise_cut(S_partition, working_graph, plt_title_string): """Plot and output the graph cut information. could be eventually removed """ # Generate the colors. coloring = [] for node in working_graph: if node in S_partition: coloring.append('blue') else: ...
2cafbe60e85af7b2c124e1fc6643c439bb9e62e0
3,621,513
from bs4 import BeautifulSoup def get_anchor_href(markup): """ Given HTML markup, return a list of hrefs for each anchor tag. """ soup = BeautifulSoup(markup, 'lxml') return ['%s' % link.get('href') for link in soup.find_all('a')]
ec75f36e0b14a1d20452a1b6c1233d789c03cd6b
3,621,514
async def get_asterisk_chan(response_json): """Get the Asterisk Channel from the JSON responses""" if response_json["type"] in ["PlaybackStarted", "PlaybackFinished"]: return str(response_json.get("playback", {}).get("target_uri")).split(":")[1] else: return response_json.get("channel", {})....
951ccc3cdea92cfb630eb24bbd9e2f2333a72f1e
3,621,515
def load_pascal_data(data_dir, max_epochs=None, thread_count=3, imsize=(128,128)): """Will use a filename queue and img_queue and load the data """ file_queue = core.FileQueue() # d = img_dict(data_dir) img_queue = core.ImageQueue(files_in_epoch=250, maxsize=1000) threads ...
c082bd36319bd3a2d1484d86a9e26663486b5a44
3,621,516
def get_valid_uuids(uuids: list, full_paths: list, valid_full_paths: list) -> list: """Returns valid uuids.""" return [uuid for uuid, full_path in zip(uuids, full_paths) if full_path in valid_full_paths]
f93d77060edd9b38d2f322bacb9e01ae69ef8e4b
3,621,517
import glob import os def test_data(images_fp, lidar_fp, use_lidar): """ Grabs the file names of all the test images. Parameters: ----------- data_set: File path given by user leading to the main folder with the data Returns: -------- img_tensor: List of file names for the images ...
614c2f9e00c416d6b52e3a5978d4a7db475356fe
3,621,518
def extract_time_invariants(cluster, template, *args): """ Extract time-invariant subexpressions, and assign them to temporaries. """ make = lambda: Scalar(name=template(), dtype=cluster.dtype).indexify() rule = make_is_time_invariant(cluster.exprs) costmodel = lambda e: estimate_cost(e, True) >...
33afe04debf5d463f4994da3938f700d4cba8ecb
3,621,519
import os def copy_remote_file(web_file, destination): """ Check if exist the destination path, and copy the online resource file to local. Args: :web_file: reference to online file resource to take. :destination: path to store the file. """ size = 0 dir_name = os.path.dir...
931197924fb2bfdbc8a2df99135822df4c186073
3,621,520
def get_pacients(): """Funkcija pogleda če ima uporabnik pravice, če jih ima potem vrne vse paciente v bolnici kjer smo prijavljeni.""" (username, ime, vloga, bolnisnica) = get_user() # Preverimo vlogo uporabnika if vloga == "zdravstveni_delavec": c = baza.cursor() # TODO izberem vse pac...
ca1c8ad6c597a8c8c0a540d9457dbb5ce8d3512a
3,621,521
def score_grammars(features, labels, config, is_training=False): """load in grammar """ # features {N, 1, M} grammars = config.get("grammars") pwms = config.get("pwms") assert grammars is not None assert pwms is not None # input - {N, 1, M}, ie 1 cell state # generate two array ...
45fd887cd7a89f84764437dcdcc913aa9a93170d
3,621,522
def _serialise(data: any, prefix: str='') -> str: """Serialise an ordered map. :arg data: An ordered map. :arg prefix: Partially serialised result. :returns: An ordered map string. """ if not isinstance(data, dict): return '{}={}\n'.format(prefix, data) result = '' for key in ...
64716229e3f71abc8ac87219958b604dbf622550
3,621,523
def massage_error_code(error_code): """Massages error codes for cleaner exception handling. Args: int Error code Returns: int Error code. If arg is not an integer, will change to 999999 """ if type(error_code) is not int: error_code = 999999 return error_code
c9c42e71aa4684e79078673baa9a7ecfe627a169
3,621,524
def LinksEff(network): """ Parameters ---------- network : PyPSA network type input network Returns ------- linkseff : array an array of the types of links that have an efficency. Used to calculate the response values """ linkseff = network.links # Save link d...
39f0044fbf3633fef71d03a85904c7abd516e6e2
3,621,525
def Tm_Wallace(seq, check=True, strict=True): """Calculate and return the Tm using the 'Wallace rule'. Tm = 4 degC * (G + C) + 2 degC * (A+T) The Wallace rule (Thein & Wallace 1986, in Human genetic diseases: a practical approach, 33-50) is often used as rule of thumb for approximate Tm calculatio...
d5ffa62f712f315297efc42d5d7ab45db1d3c788
3,621,526
def db_to_df(amount, connection=create_connection()): """ Transfer results of a SQL query to a dataframe :param amount: limit amount of entries returned :param connection: connection object :return: dataframe """ query = pd.read_sql(f"CALL select_reviews(%(amount)s)", connection, params={"am...
5a78b86192e5736ced0c52e6f0bcc10c39c11dc4
3,621,527
def alternative_floating_algae_index(Red, Rededge, Near): """transform near and short wave infrared arrays to get a algae-index Parameters ---------- Red : numpy.array, size=(m,n) red band of satellite image Rededge : numpy.array, size=(m,n) rededge band of satellite image Near ...
efb16ec7d59bd9d3b387879eb90ea714bdd7db43
3,621,528
import random def randomPartition(elems: list, bin_sizes: list) -> list: """ Randomly partition list elements into bins of given sizes """ def shuffleList(elems): random.shuffle(elems) return elems elems = shuffleList(elems) partition = [] start, end = 0, 0 for bin...
52d1d16639fa0a4566423255bb29c123879282cb
3,621,529
from typing import Dict from typing import Set from typing import Optional from typing import Tuple from typing import List def find_closest_string(string: str, options: Dict[str, Set[str]]) -> Optional[Tuple[List[str], float]]: """ :param string: string to search for :param options: {option: trigram tok...
bf5c0d4648359e2302392d29b3a3195f95f22fd0
3,621,530
def pre_process(line): """ Return line after comments and space. """ if '#' in line: line = line[:line.index('#')] stripped_data = line.strip() return stripped_data
63640048cb07376fb73b62cb6b6d2049adec5c17
3,621,531
import inspect def sum_var_positional_args(a, b, *args): """perform math operation, variable number of positional args""" inspect_simple(inspect.currentframe()) thesum = a + b for n in args: thesum += n return thesum
1d5991113f0d4b3130bac6106e811bbb941e0251
3,621,532
def get_states_counties_tracts(tract_fips): """ turn a list of tract fips codes into a nested dict keyed by state, then keyed by county, finally with tract as the value """ if not isinstance(tract_fips, pd.Series): raise TypeError("tract_fips must be a pandas series") df = pd.DataFrame...
b54a33411850e3bf6214964035e808910d2d8944
3,621,533
def gen_spline(point_params: list, verbose=False) -> Spline: """ Function to generate a spline defined by given point parameters. @param point_params: list of point parameters (dictionaries with values for time, position[, velocity, acceleration]) @param verbose: Enable verbose output if True @retur...
9d8b0fb0ef08155906f1789d06512d6d3d8add38
3,621,534
import os def download_raw_video(eid, cameras=None): """ Downloads the raw video from FlatIron or cache dir. This allows you to download just one of the three videos :param cameras: the specific camera to load (i.e. 'left', 'right', or 'body') If None all three videos are downloaded. :...
275870fbdbaf7868187851c30c0d64a00e0fe44d
3,621,535
def get_canonical_values_not_in_goals( slot_cmap: dict[str, dict], domain: str ) -> dict[str, set[str]]: """Some canonical values do not appear in the goals so they are in a special field in the canonical map. This is specific to MultiWOZ 2.1. Parameters ---------- slot_cmap Canonical ...
45ce90fbc86b8ba2be71432234a6c08d853b5e0d
3,621,536
import os def df_filters_funcgen_hsapiens_peak() -> pd.DataFrame: """Dataframe with available filters for the hsapiens_peak dataset.""" df = pd.read_pickle(os.path.join(DATADIR, "filters_hsapiens_peak.pkl")) return df
1689f8e4e470b150a4da7d6bca5a9c75f5f684ac
3,621,537
def file_tag_from_task_file(file: str, cut_num_injs: bool = False) -> str: """Returns the file tag from a task output filename. Args: file: Filename of task file with or without path. cut_num_injs: Whether to not include the number of injections per redshift bin. """ file_tag = file.rep...
2ba0180c1a06f4ae6e47659e3598c2207cca5642
3,621,538
def decodeBase58(s): """Decode a base58-encoding string, returning bytes""" if not s: return b'' # Convert the string to an integer n = 0 for c in s: n *= 58 if c not in B58_DIGITS: raise InvalidAddress('Character %r is not a valid base58 character' % c) ...
04f16c2e04e0f21753f097949d8eb8b1c51a43df
3,621,539
def insert_ones(y, segment_end_ms): """ Update the label vector y. The labels of the 50 output steps strictly after the end of the segment should be set to 1. By strictly we mean that the label of segment_end_y should be 0 while, the 50 followinf labels should be ones. Arguments: y --...
f807da86b87a88cbc9c86b97af68a8b976a1dbd4
3,621,540
def find_friends(user_id, USERS): """ return list of friends for a given user id """ for city, users in USERS.items(): for user in users: if user["user_id"] == user_id: friends = user["friends"].split() return friends
6ce53810d486364286d3600ae7817902bc8a92e2
3,621,541
def _dqc_0051_check_instance(instance, parent, child): """Checks if both parent and child are present in the instance with the same aspect values.""" child_facts = instance.facts.filter(child, allow_nil=False) for child_fact in child_facts: constraintSet = xbrl.ConstraintSet(child_fact) cons...
f2a85b3a455bd220b74aafa107558a5c371075d6
3,621,542
def PolyDiff(u, x, deg = 3, diff = 1, width = 5): """ u = values of some function x = x-coordinates where values are known deg = degree of polynomial to use diff = maximum order derivative we want width = width of window to fit to polynomial This throws out the data close to the edges ...
b0a1d10f1423f9c867fa221e91a1d99b3c02de9d
3,621,543
import os def create_app(script_info=None, db_uri=DEFAULT_DB_URI, image_dir=DEFAULT_IMAGE_DIR): """create app.""" app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = db_uri # NOQA app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SECRET_KEY'] = os.getenv('TIIS_SECRET_KEY')...
9540f0aec00d560a47b741270e1f1c6e618ed68e
3,621,544
def pw_global_align(seq1, seq2, sub_matrix, gap_penalty): """ Find pairwise global alignment of two sequences through Hirschberg's algorithm. Args: seq1: sequence of arbitrary objects. seq2: sequence of arbitrary objects. sub_matrix: SubstitutionMatrix with symbols matching sequences. gap_penalty: float|tu...
af94800a7da8b1cfbb2741dc646650809f2ee98f
3,621,545
from typing import Dict from typing import Any def vectorise_record(record: Dict[str, Any]) -> Dict[str, Any]: """ Vectorise a patient record. Each field is processed to vector format based on a vector configuration specific to the field name and data type. :param record: Dictionary of record fields ...
33b77bfbb3f51f4f03b48acd93c214fb372fa2db
3,621,546
def read_tree(nwk, outgroup=None, bold=None, types=None, label_leaves=True): """Read in a Newick format tree.""" tree = Tree(nwk) if label_leaves: add_section_annotations(tree) add_leaf_labels(tree, bold=bold, types=types) if outgroup: set_outgroup(tree, outgroup) return tree
920a559183b844218ae1133077d0ff6983bf6d3f
3,621,547
from typing import Optional def generate_richcompare_wrapper(cl: ClassIR, emitter: Emitter) -> Optional[str]: """Generates a wrapper for richcompare dunder methods.""" matches = [name for name in RICHCOMPARE_OPS if cl.has_method(name)] if not matches: return None name = '{}_RichCompare_{}'.fo...
a4cf8787c56225ae43f469de38a5de0d87b5d834
3,621,548
def AVEDEV(series, n=2): """ 平均绝对偏差 :param series: :param n: :return: """ return series.rolling(n).apply(lambda x: (np.abs(x - x.mean())).mean(), raw=True)
14803ee6d02bb5769c6379473c2302bba19d6390
3,621,549
def GaussScreen(w, x_shift, y_shift, T, Fin): """ Fout = GaussScreen(w, x_shift, y_shift, T, Fin) :ref:`Inserts a screen with a Gaussian shape in the field. <GaussScreen>` :math:`F_{out}(x,y)= \\sqrt{1-(1-T)e^{ -\\frac{ x^{2}+y^{2} }{w^{2}} }} F_{in}(x,y)` Args:: w: 1/e inten...
b5180cce2bd88e72c3bae2d9c3779f816141a9f0
3,621,550
from typing import Union import requests def GetMemberCount(GroupID: int) -> Union[int, str]: """ Returns a count of how many users are in a group """ response = requests.get(Utils.GroupAPIV1 + str(GroupID)) try: return response.json()['memberCount'] except: return response.jso...
560cea178196e7dd2248f8a0be5ead1a49ffe63d
3,621,551
import torch def cmc_score_count( distances: torch.Tensor, conformity_matrix: torch.Tensor, topk: int = 1 ) -> float: """ Function to count CMC from distance matrix and conformity matrix. Args: distances: distance matrix shape of (n_embeddings_x, n_embeddings_y) conformity_matrix: bin...
5c3d31a6455e1d8c7694a2117637e9e51478bb21
3,621,552
def signin_user_db(user_db, remember=False): """Signs in given user""" flask_user_db = FlaskUser(user_db) auth_params = flask.session.get('auth-params', { 'remember': remember, }) flask.session.pop('auth-params', None) return login.login_user(flask_user_db, remember=auth_params['remember...
60da3b7c5fb47ed87941bc0ced29bb6acdc72882
3,621,553
def id_det_noid(env, src) : """Returns detector full name for any src, e.g., XppGon.0:Cspad2x2.0""" return detector_full_name(env, src)
48063bd8f397e3cc23b8e818cf700df56405f2ee
3,621,554
import warnings def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). ...
f72ba7f5cd44fe1b3074d88c4eb1a20eeb25ec1b
3,621,555
def create_house_holds_objects(): """[summary] Creates house holds objects from the database Returns: [list]: [Two lists. One list of consumers and one list_of_prosumers] """ list_of_consumer = [] list_of_prosumer = [] try: connection = database_cred() sql_sele...
e9456e46dca4f5e673e5e49a3b71646cc8a07109
3,621,556
def regrid_get_coord_order(f, axis_keys, coord_keys): """Get the ordering of the axes for each N-d auxiliary coordinate. :Parameters: f: `Field` The source or destination field. axis_keys: sequence A sequence of axis keys. coord_keys: sequence A s...
28ecbb91d29c2638a07bf255d3daf3819f0475fc
3,621,557
def build_detection_targets(rpn_rois, gt_class_ids, gt_boxes, config): """Generate targets for training Stage 2 classifier. This is not used in normal training. It's useful for debugging or to train the Mask RCNN heads without using the RPN head. Inputs: rpn_rois: [N, (y1, x1, y2, x2)] proposal box...
ebd5e5003d906b2720e1b689b99cdfd48d6857a9
3,621,558
def getprotobyname(name): # real signature unknown; restored from __doc__ """ getprotobyname(name) -> integer Return the protocol number for the named protocol. (Rarely used.) """ return 0
2f682337380ecb3898042cf8a7af2d9ef5290887
3,621,559
def load_ccgs(path, old=False): """Read CCG parses from the output of Jigg""" child_key = 'child' if old else 'children' symbol_key = 'category' if old else 'symbol' form_key = 'surf' if old else 'form' def read_ccg(sentence): assert sentence.tag == "sentence" ccg = sentence.xpath(...
7ee5ad0488f239396b8bd5b7e62dd4589d45dec2
3,621,560
import threading def simple_thread(func, daemon=True): """ Start function in another thread, discarding return value. """ thread = threading.Thread(target=func) thread.daemon = daemon thread.start() return thread
870102cf07b92b7cdd56960a7c6da5d8521ee233
3,621,561
def clone(obj, excluded_fields=[], excluded_childrens=[], custom_values={}, recursive_custom_values={}): """ clone object using django_auto_serializer """ try: si = SerializableInstance(obj, excluded_fields=excluded_fields...
f46fef41aa8ffd74d9d5182e13568609a95a7799
3,621,562
def vmin_w(w, mw): """Minimum wimp velocity to emit a Bremsstrahlung photon w :param w: Bremsstrahlung photon energy :param mw: WIMP mass From Kouvaris/Pradler [arxiv:1607.01789v2], equation in text below eq. 10 """ return (2 * w / wr.mu_nucleus(mw))**0.5
9de2513fdec064ea888a589a77bc8a86292a238e
3,621,563
def subblockify(data: bytes, terminate: bool = True) -> bytes: """ Properly segments data into 255-byte-max sub-blocks. `terminate` indicates whether to end with a 0x00 terminator. """ # TODO: make less inefficient. ba, idx = bytearray(), 0 # insert 0xff byte before every 255-byte run fo...
202e7a1760633d7fb5fcfbe48e119a7c845e0d22
3,621,564
def get_hash(x): """hash x and digest""" return hash_func(x).hexdigest()
4ef0bc8aac8bae333be4f3451c77316559748fd7
3,621,565
def parameters_hook(net, modules=None, match_names=None, param_names=None, tag='', save_path='.', replace=True, histogram=True, bins=100): """Registers a forward hook to a network's modules for vizualization of its parameters. When net.forward() is called, the hook saves an image grid or a ...
128f6c6c93b0f76a2d60830b61e5bae403955cda
3,621,566
def create_engine(db: str, **kwargs) -> sa.engine.Engine: """Returns sqlalchemy engine for designated database. Args: db (str): Database name. Possible values : 'ocan', 'fmc', 'monitorenv_remote', 'monistorfish_local', 'cacem_local' Returns: sa.engine.Engine: sqlalchemy engine ...
86aa050a64ddce620739e4d7f1f2c44b0e1c48a2
3,621,567
from gitWebScrapper.gitlab.scrapper import gitlab_scrapper def scrape_gitlab_handler(users: list, commits=False): """ Handler for scraping GitLab users. :param users: list of users :param commits: boolean value for adding or not commits to output :return: None """ return [gitlab_scrapper(...
aeb574c5f684f61c6c9e0bef91a8d67fea44f3e0
3,621,568
def create_batch_settings( launcher, nodes=None, time="", queue=None, account=None, batch_args=None, **kwargs ): """Create a ``BatchSettings`` instance See Experiment.create_batch_settings for details :param launcher: launcher for this experiment, if set to 'auto', an attempt will...
cdfb6921e8709559e2837857356ac54372aac307
3,621,569
import yaml def list_recorded_hits(client: boto3.session.Session): """ Return all HITs stored in job.yaml """ config = get_config() with open(config['job_filename'], "r") as fid: hits = yaml.safe_load(fid) return hits
c0d95099b3fb5f273437ff8aa3c6b1fcdcb9e9ad
3,621,570
from typing import OrderedDict def build_classifier(input_size, hidden_size, output_size, p_drop=0.5): """ DESCRIPTION: The function builds a new model classifier with input- hidden- and output size defined by the input arguments. It will also include dropout using the dropout rate from the input argu...
e570c730d9e53c3c5a9833af40e71941b52669ee
3,621,571
def sample_info(session): """Query the LIMS database for sample information and return json representation""" kwargs = retrieve_args() samples = _create_samples_info(session, kwargs.get('match', {})) return [s.to_json() for s in samples]
f17e5a7a48c99560127caa852aeff527fced31f5
3,621,572
from typing import List from typing import Tuple def route_scorer(routes: List[StrDict]) -> Tuple[List[StrDict], List[float]]: """ Scores and sort a list of routes. Returns a tuple of the sorted routes and their costs. :param routes: the routes to score :return: the sorted routes and their costs ...
87adde8ab7ffed175c8efcb211d8375c1f11c0c4
3,621,573
import shutil def create_compile_cmd(harness, target, args, specification, c_version="gnu11"): """Create the compile command. :param str harness: path to harness file :param str target: path to program under test :param args: arguments as parsed by argparse :param list specification: list of prop...
44dc739cb828532cd4f2bd1ad0585a35cc9d56a3
3,621,574
import os def _render_markdown(file_path, **kwargs): """ Given a `file_path` render the Markdown and return the result of `render_template`. """ global NAV_MENU, PROJECT_LOGO, PDF_GENERATION_ENABLED default_template = 'document' with open(file_path, 'r', encoding='utf-8') as f: md = markdo...
f7b66d0adc80ab0c967e762df945f2e6ce2e2ad2
3,621,575
def get_model(implant, input_shape, num_dense=0, force_zero=False, sigmoid=False, clip=False): """ Makes a keras model for the model """ inputs = layers.Input(shape=input_shape, dtype='float32') x = tf.image.flip_up_down(inputs) # fully convolutional num_filters = [100, 1000, 100] kernel_si...
797732fc908c22d894d79f4056bb2083395a9bf5
3,621,576
def plotly_pie(svl_plot, data): """ Creates a plotly pie chart from the SVL plot and data specs. Parameters ---------- svl_plot : dict The SVL plot specifier. data : dict The SVL data specifier. Returns ------- dict The d...
842614b2e0a8e44497a60ed8b9b3d68f0ccd64a8
3,621,577
def plot_gamma_components(*args, colorbar=True, dpi=FIG_DPI, **kwargs): """See _plot_gamma_components for function signature""" fig, ax_im, ax_cbar = make_image_figure(colorbar, dpi) _plot_gamma_components(fig, ax_im, ax_cbar, *args, **kwargs) return figure2array(fig)
f0e212da1c86013b842fb536e2bdde7882d0a1b0
3,621,578
def reverse_zone(z,domain_out): """ Generate reverse lookup entries (IP -> FQDN) for a zone file Retains the SOA file """ z2=dns.zone.Zone(dns.name.from_text(domain_out)) z2.replace_rdataset("@",z.find_rdataset(z.origin,'SOA')) z2.replace_rdataset(domain_out,z.find_rdataset(z.origin,'NS')) for k,o in...
1753cfd19740ffcd441f435187137886a1b5a338
3,621,579
def pRDP_asymp_subsampled_gaussian(params, alpha): """ :param params: :param alpha: The order of the Renyi Divergence :return: Evaluation of the pRDP's epsilon See Example 19 of Wang, Balle, Kasiviswanathan (2018) """ sigma = params['sigma'] prob = params['prob'] assert((prob<1) and...
513d9e42d7ba25b0f4d5c2ec484d9dcf9e8d889e
3,621,580
def ismissing(x): """ Return True if x is a missing datum. """ return x == MISSING
9ebc21cac21fa83c76edafcd5685c2879ebb78b6
3,621,581
def get_heuristics_cheating(): """ Grab the heuristic cheating results. """ acc, f1, prec, rec = run_hr_cheating() hr = ["Heuristics", "{:.2f}".format(acc), "{:.2f}".format(prec), "{:.2f}".format(rec), "{:.2f}".format(f1)] return hr
229a62794566901456f8315e4bff3b3d5a180a9a
3,621,582
def extract_name(declaration): """ Extract name from the declarator of the declaration. :param declaration: Declaration string or ast. :return: Declarator string or None if there is no declarator. """ if isinstance(declaration, str): try: ast = parse_declaration(declaration)...
03e883017ad5355e5bb321b75c01af08bdb75baf
3,621,583
def find_geometry_groups(nexus_file): """ Find all kinds of group containing geometry information. Geometry groups themselves are often links (to reuse repeated geometry) so look for parents of geometry groups instead and return parent and child dictionary pairs. :param nexus_file: NeXus file input...
3abfa0cba2fe1ea41fecc6ed91d01a6bfcfad353
3,621,584
def ifftn(x, shape=None, axes=None, overwrite_x=False, planner_effort=None, threads=None, auto_align_input=True, auto_contiguous=True): """ Perform an nD inverse FFT. The first three arguments are as per :func:`scipy.fftpack.ifftn`; the rest of the arguments are documented in the ...
5a40dfb6dee475163c69c14ab0ce2ed7f88b768f
3,621,585
def hass_admin_user(hass, local_auth): """Return a Home Assistant admin user.""" admin_group = hass.loop.run_until_complete(hass.auth.async_get_group( GROUP_ID_ADMIN)) return MockUser(groups=[admin_group]).add_to_hass(hass)
ef66cdcbe1a37e9304081e168e53f4cc8096ae0f
3,621,586
from re import A def get_lonlatalt(pos, utc_time): """Calculate sublon, sublat and altitude of satellite, considering the earth an ellipsoid. http://celestrak.com/columns/v02n03/ """ (pos_x, pos_y, pos_z) = pos / XKMPER lon = ((np.arctan2(pos_y * XKMPER, pos_x * XKMPER) - astronomy.gmst(utc_time...
ac1fc7a8b47f438d619f0d6b6c224d3965ffc4ab
3,621,587
def _compute_tau(eigenvalues, sig2b): """Compute the tau that gives Hanwen Huang's soft thresholded eigenvalues, which maximizes the relative size of the largest eigenvalue""" # NOTE: tau is found by searching between 0 and Ming Yuan's tilde_tau. tilde_tau = _compute_tilde_tau(eigenvalues, sig2b) t...
576603b34449befdba923d829e22e22277342979
3,621,588
import os def sshkeys_post(body: SshkeysPost = None) -> SshkeyPair: # noqa: E501 """Create a public/private SSH Key Pair Create a public/private SSH Key Pair # noqa: E501 :param body: Create a public/private SSH Key Pair :type body: dict | bytes :rtype: SshkeyPair """ try: # ge...
8d9c2f89b39039e30fb9df521a75280d7d5700d5
3,621,589
import requests def request(endpoint, auth_token, data=None, files=None, raise_for_status=True, req_type='post'): """ Method to send the request to Snapchat's API. Automatically adds two common fields: `req_token` and `timestamp`. :param endpoint: the api endpoint. :param data: dict c...
42e5bad57ecc5d27dc2ff5c0e0f014d3b266c4b3
3,621,590
def save_config(environ, start_response, lines, rhost): """Config files will be stored in <CFG_DIR> as 'FQDN.cfg'. We don't care about over-writing files, or do we? Since this will be multi-threaded, we should utilize .lock, shouldn't we? """ cfg_file = '%s/%s.cfg' % (config.CFG_DIR, rhost) ...
7963003bf66aad7ed7ed89b5c507498e6399f6c5
3,621,591
def signed_normalint(value, area=4): """ Returns signed value """ # TODO: accept cache arg and depend on int_unpack_fmt return pack('!i', value)
cd271a9eb4d89e359ac2b76aeaa482c4b0b1e3fd
3,621,592
def add_gms_group( self, group_name: str, parent_pk: str = "", background_image_file: str = "", ) -> bool: """Update appliance group in Orchestrator .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - group - POST ...
c92cd932070913af2b98608822ad03ff4a59506e
3,621,593
from re import UNICODE def style_string(string, ansi_style, colormode, nested=False): """ Style the given string according to the given ANSI style string. :param str string: the string to style :param tuple ansi_style: the styling string returned by ``translate_style`` :param int colormode: t...
6d09af73f9a5074fe60415e2d90588a2e5f32ac2
3,621,594
def valid_email(emailaddress, domains=GENERIC_DOMAINS): """Checks for a syntactically valid email address.""" # Email address must be at least 6 characters in total. # Assuming noone may have addresses of the type a@com if len(emailaddress) < 6: return False # Address too short. # Split u...
7db0a3aa04e0043a00f50d0fb6cf5c878872d737
3,621,595
def checkobj(obj,wf=True): """ local conversion. everything sent to the server needs to be a string if wf is True, we also check for well-formed-ness... '{' and '}' are special delimiters in XQuery and need to be escaped by doubling """ if not wf: if isinstance(obj,basestring): ...
c4b6d3afa7c070869696f959bf00f0465bdd84c1
3,621,596
def _which_h5_group(h5_path): """ Used internally in get_ functions to indentify type of H5_path parameter. H5_path can be passed as string (to h5 location), or as an existing variable in the workspace. This tries If this is a Dataset, it will try and return the parent as that is by default where all rele...
5289ab80fedecc4683ca5c40c04627301dde9787
3,621,597
def transformation() -> Response: """ Transformation view. Performs no validation, just passes given JSON to :func:`backend.logic_layer.transformation` for transformation. :return: instance of :class:`~flask.Response` representing JSON response (structure of JSON depends on output type) """ ...
232118174d6e2215f8a1f9f39d494ee9ae70a3dc
3,621,598
def get_dataset(opts): """ Dataset And Augmentation """ resize_scales = [300 / 720, 375 / 720, 450 / 720, 525 / 720, 1000 / 1280] # TRAIN basic_transform = transform.Compose([ transform.ToTensor(), transform.Normalize(mean=[0.485, 0.456, 0.406], std=[0.22...
94cc488835811dadcd655684ef89a76d5e6869c2
3,621,599