content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def GetImmediateSupertypes(n, layers='core'): """Get this type's immediate supertypes, i.e. that we are subClassOf.""" if n==None: return None sups = GetTargets( Unit.GetUnit("rdfs:subClassOf", True), n, layers=layers) if (n.isDataType() or n.id == "DataType"): sups += GetTargets( Unit.G...
36dc4a623a639590602cd2828638bfff3d9c266c
3,614,600
def get_engine_sqlite(path) -> Engine: """Get a SQLite on-disk database engine.""" return create_engine(f"sqlite+pysqlite:///{path}", echo=True, future=True)
cb8148af8304ecdce4c6303ecddf4f8120dc4cf7
3,614,601
def view_file(parent, title, filename, encoding, modal=True, wrap='word', _utest=False): """Create text viewer for text in filename. Return error message if file cannot be read. Otherwise calls view_text with contents of the file. """ try: with open(filename, 'r', encoding=en...
0a564938fbbdcde2bb36ca6766839bbd9e4e7c96
3,614,602
def transform_poses_to_base(config, poses): """ Transform the poses to the base frame with settings specified in the config :param config: :param poses: :return: """ ## initialize base to cam transformation tf_t_BC = Vector3(config['base_to_cam_pose']['translation']['x'], config['base_to...
caf234a92aed7078e5e4ef342de0b8bcdc5b5aef
3,614,603
def create_occurrence(create_reservation): """Return a callable which lets you create reservation occurrences.""" def _create_occurrence(start_dt=None, end_dt=None, room=None): params = {} if start_dt is not None: params['start_dt'] = start_dt if end_dt is not None: ...
1b11afb19e8e1b266532dd9198c2d93010351f97
3,614,604
def register_corrector(cls=None, *, name=None): """A decorator for registering corrector classes.""" def _register(cls): if name is None: local_name = cls.__name__ else: local_name = name if local_name in _CORRECTORS: raise ValueError(f'Already regist...
eabb694cb6df359308c9f49b1ad66da007b22e5a
3,614,605
def general_net_center(feat_model, identity_model, center_model, img_shape): """Returns a keras Model for training with classification, metric learning and center losses Args: feat_model: keras Model for feature extracting identity_model: keras Model for classification img_shape: t...
5abaf9bc8f2421d622b5e4ac2d9f48b354b7e4c8
3,614,606
def make_cache_key(path=None, key_prefix="view/%s"): """ This function mostly emulates Flask-Caching's `make_cache_key` function so we can delete cached api responses. Over time this function may be replaced with a cleaner custom cache implementation. :param path: :param key_prefix: :return: ...
af8be0416144ff1daec2981b8549623b53f36dc1
3,614,607
def orient_tract_kmeans(bundle): """Ensure the startpoints to be always higher than the endpoints. """ points = compute_endpoints(bundle) kmeans = KMeans(n_clusters=2, random_state=0).fit(points) class0_up = (kmeans.cluster_centers_[0][2] > kmeans.cluster_centers_[1][2]) #constraint on the z axis oriented_bundle ...
5e0ba68df10a57dabd1d4d5bbc9e20f9efd63c26
3,614,608
def create_flagellum(idx, phase, phase_speed, translation, rotation, flag_radius, longitude_grid, azimuth_grid): """ :param phase_speed: integer; will be multiplied by default frequency :param longitude_grid: how man :param azimuth_grid: number of grid points (integer) :return: ...
a4742ae6deacb2a4e7fcf8a181c96d3e3479dac9
3,614,609
from typing import Literal def _pretty_print_literal(literal: Literal): """Render a literal.""" return render_literal_value(literal.value)
986a98bb39a60af7e13efba89a66281408fd9855
3,614,610
def make_point(x, y, as_geom=False): """ Make a GeoJSON point. if as_geom, then return a shapely geometry instead. """ geojson = {"type": "Point", "coordinates": [x, y]} return geometry.shape(geojson) if as_geom else geojson
551c85fb1bb531b10e1540ebcef141d95ea1ee55
3,614,611
from datetime import datetime import json def two_week_working_hour(dept_info): """ convert workingHour into two week's everyday slot """ today = datetime.datetime.today() weekday = today.weekday() workingHour = json.loads(dept_info.workingHour) schedule = [] for i in range(14): ...
a7afa25a2912e2917da9e5a86f5407c7b4d8e9cf
3,614,612
import functools import operator def bot_has_role_permissions(perm1: hikari.Permissions, *perms: hikari.Permissions) -> Check: """ Prevents the command from being used if the bot is missing any of the required role permissions. Args: perm1 (:obj:`hikari.Permissions`): Permission to check for....
38baaeedd08998dac996eb984c5d8b49b9726d09
3,614,613
def make_data(T, fs): """ Function to make data args: T: time fs: sampling rate return: t: number of samples x: data """ nsamples = int(T * fs) t = np.linspace(0, T, nsamples, endpoint=False) a = 0.025 f0 = 550.0 x = 0.07 * np.sin(2 * np.pi * 1.2 *...
9d76554e27008825d2999ba9a3582ed411c2afc5
3,614,614
def parse_veh_comp(xmldoc): """parses the vehicle composition from the VISSIM data :param xmldoc: input VISSIM xml :type xmldoc: xml.dom.minidom.Document :return: relevant VISSIM vehicleComposition data :rtype: dict of list of dict """ veh_cmp_d = dict() # local vehicle co...
195b2c8dcbd055d5c8e8fdb4f6b68f360c60c961
3,614,615
def obscore_loader_gama_sdss(fname): """ This is a specutils loader which adds obscore information to a SDSS spectra in the GAMA survey """ spec = Spectrum1D.read(fname, format="SDSS-I/II spSpec") spec.meta["obscore"] = {} obscore = spec.meta["obscore"] hdr = spec.meta["header"] ob...
95ca112ba6de00d3ad920b02d3f8dab26989fff8
3,614,616
from typing import NamedTuple def get_conn(config: NamedTuple) -> connector.MySQLConnection: """ Accept parsed configuration data and create mysql connector :param config: :return: """ return connector.connect( host=config.db.host, database=config.db.database, user=config.db...
03ae0c3c2239806d5dbd54c9e1c02dba621919d1
3,614,617
import time def uniq_table_id(): """Return a unique table ID based on the current time in ms. Returns: str: in format `U<timestamp_ns>` """ return f'U{time.time_ns()}'
cffe47d5e8dfff192e2a754347534e02d4ba6a68
3,614,618
import inspect def _get_real_env_hack_hack_hack(): """ Get the real, currently-being-configured libtbx.env environment. This is not libtbx.env, because although libtbx.env_config.environment.cold_start does: self.pickle() libtbx.env = self the first time there is an "import libtbx...
f0fe71b5c0a3922300f9d6d81aeb6057e39dd4c3
3,614,619
from mapproxy.srs import bbox_equals def wms_query_eq(expected, actual): """ >>> wms_query_eq('bAR=baz&foo=bizz&bbOX=0,0,100000,100000', 'foO=bizz&BBOx=-.0001,0.01,99999.99,100000.09&bar=baz') True >>> wms_query_eq('bAR=baz&foo=bizz&bbOX=0,0,100000,100000', 'foO=bizz&BBOx=-.0001,0.01,99999.99,100000.1...
fd4e7ff53c5cc0b6e5545775e47092b743635917
3,614,620
import os def get_server_url_for_path(p): """ gets the url corresponding to a given file or directory path p : path to convert into a url returns the url path for the filepath p """ load_environment() fname = os.path.basename(p) rel_path = os.path.relpath(p, os.environ['NOTEBOOK_HOME...
27058007a12035719be2e7d32de95c486b9a67f7
3,614,621
import argparse import os from datetime import datetime def parse_args(): """ parse command line arguments :return dict: dictionary of parameters """ argparser = argparse.ArgumentParser() argparser.add_argument('--config_file', type=str, default=os.path.join('./configs/', 'turtlebot_navigat...
ba6cd305eb00926e3613eb73976b6b6f111833e3
3,614,622
def split_dataframe_by_position(df, splits): """ Takes a dataframe and an integer of the number of splits to create. Returns a list of dataframes. """ dataframes = [] index_to_split = len(df) // splits #print(index_to_split) start = 0 end = index_to_split for split in range(split...
7536920125fa33fafd420c4fe7ef24aff2fa6ff3
3,614,623
def address_in_network(ip: str, net: str) -> bool: """Is an address in a network """ # If IP and net mask are not compatible, return False if is_ipv6(ip) != is_ipv6(net): return False # Convert ips to int i_ip = ip_to_bits(ip) total_bits = 32 if not is_ipv6(ip) else 128 netpart...
2bd77242cc458680076c49ddff0d5dcb215d6999
3,614,624
def get_service_url(host, port, path=constants.PATH): """ Construct a service URL from host, port and path :param host: (string) the service host (aka server) IP :param port: (int) port on which to connect to the service :param path: (string) API endpoint (default to /mnist/classify/) :return: (...
b0ef07f50866a87c4e5b3e85bd179db1fd46fab0
3,614,625
def eigcov(data): """ Return eigen values and vectors of covariance matrix """ eigenValues, eigenVectors = np.linalg.eig(np.cov(data)) idx = eigenValues.argsort()[::-1] eigenValues = eigenValues[idx] eigenVectors = eigenVectors[:,idx] return eigenValues, eigenVectors
5355d40fc006a8ebeb6f566998666feb7e533c6b
3,614,626
import torch def index_relation_types(dataset): """Classify relations into 1-N, M-1, 1-1, M-N. According to Bordes et al. "Translating embeddings for modeling multi-relational data.", NIPS13. Adds index `relation_types` with list that maps relation index to ("1-N", "M-1", "1-1", "M-N"). """...
639059ecf319ce367a62db64edc1efebc8ef5050
3,614,627
def init_celery(celery, app): """ initial celery object wraps the task execution in an application context """ celery.config_from_object(celeryconfig) class ContextTask(celery.Task): def __call__(self, *args, **kwds): with app.app_context(): return self.run(*args...
1331438c9b6cb01bf96dcf7465d7444fbb985937
3,614,628
import logging def _validate(submission): """ Validates submission against a set of rules. """ title = submission.title.lower() if ShowerThought.objects.filter(post_id=submission.id).exists(): # sometimes posts are chosen for two days because they fall right on the cusp logging.war...
c95944036cbb45e7acf024f1966dcbf3c4b980d9
3,614,629
def display_codes(codes, indv_stem_plots=True, input_and_recon=None, data_pt_per_fig=None, plot_title=""): """ Visualizes tranform codes Parameters ---------- codes : ndarray(float32, size=(b, s) OR size=(b, s, sh, sw) The codes for a batch of size b. b shouldn't be too large unless y...
1c53b5aadf2fc7c46320018d7d2bf3c46bb66068
3,614,630
def java_tokenize(snippets, labels=None): """ This function parses a list of java code snippets into a list of lists of tokens. Args: snippets: Java code snippets in a list of strings. labels: (Default value = None) a list of labels for code snippets Returns: X: a list of lists of...
dc38ad8f3e070917865007b5e2cccdebf18afaa6
3,614,631
import os def patch_load_cfg(monkeypatch): """ A fixture that returns a function which will patch 'utils.load_cfg_file' when called in a test The caller can specify the dict that should be returned when 'load_cfg_file' is called against these two paths: * "templatesTEST/_cfg.yml" * "templates...
0fb6436a7bc57e547542c92f8c51b62be7bb286e
3,614,632
from typing import Union from typing import Dict from typing import Any from typing import List from typing import Mapping def _get_instance_shape( instance_dict: Union[TaggedDict, Dict[str, Any]] ) -> Union[List[int], None]: """Get the shape of an ASDF instance from its tagged dict form. Parameters ...
db69deffc213a7120969fa0444a0ad42b0a44823
3,614,633
def decode_cobs(in_bytes): """Decode a string using Consistent Overhead Byte Stuffing (COBS). Input should be a byte string that has been COBS encoded. Output is also a byte string. A cobs.DecodeError exception will be raised if the encoded data is invalid.""" if isinstance(in_bytes, s...
32ebeec26f1a72960514d9670502dca4b1e761e2
3,614,634
def validate_enum(datum, schema, **kwargs): """ Check that the data value matches one of the enum symbols. i.e "blue" in ["red", green", "blue"] Parameters ---------- datum: Any Data being validated schema: dict Schema kwargs: Any Unused kwargs """ retur...
689fef653b757435d45e76afbf16245d0d53839f
3,614,635
import pprint def plot_fleur_sn(node, show_dict=False, **kwargs): """ This methods takes any single AiiDA node and starts the standard visualization for if it finds one """ plot_nodes, workflow_name, _ = classify_node(node) if show_dict: pprint(plot_nodes[0]) try: plotf ...
a11c4ebe9fc8d3dcfec851b7541836f265f414ed
3,614,636
import seaborn as sns def confounds_correlation_plot( confounds_file, columns=None, figure=None, max_dim=20, output_file=None, reference="global_signal", ): """ Generate a bar plot with the correlation of confounds. Parameters ---------- confounds_file: :obj:`str` ...
2f9f6b06633086a21368c04068dba47fd734bb27
3,614,637
import argparse def _run_cli(cls, *args): """Handle command line interface invocation of this script""" # Create argument parser from fields parser = argparse.ArgumentParser(description=cls.__doc__) used_prefixes = set("-h") # keep track of -X options used; -h -> help for name, field in cls.decla...
2856dc1645ebdd7069cb2ba949770d2686d0cf8f
3,614,638
def create_user(user_data, status=200): """Create a new user throught the API""" user_data = user_data res = app.post_json('/v1/users', user_data, status=status, expect_errors=status != 200) return res
d52e80b2c34d0a816c04ff7a021231b749e04e39
3,614,639
def get_google( query, n_answers=3, best_so=False, mute=False, break_on_best=False ): """ Prints links to the top hits on google given a search query (str) and returns a link to the top one. :param query: str, search query :param n_answers: int, number of max results to get :param best_so: ...
3f1fb739a10506232c24576ebb2231468384cbcd
3,614,640
def eval_triangle(x, h, n): """ Compute triangle histogram for given latent variables Input: x [num_batch, num_latent] latent values h [num_latent, num_tri] triangle heights n [num_tri] number of triangles to use x is broadcasted to [num_batch, num_latent, num_tri] (replicated nu...
e3df13591c4409a5071dc4f495495490f6544291
3,614,641
def makePartialJac(spec_pair, varnames, select=None): """Use this when parameters have been added to a modified Generator which might clash with aux fn argument names. (E.g., used by find_nullclines). 'select' option (list of varnames) selects those entries from the Jac of the varnames, e.g. for con...
e7f4cc1a902dae15232073a98786da35a9e7d4b6
3,614,642
import re def get_valid_filename(s): """Sanitize string to make it reasonable to use as a filename. From https://github.com/django/django/blob/master/django/utils/text.py Parameters ---------- s : string Examples -------- >>> print get_valid_filename(r'A,bCd $%#^#*!()"\' .ext ') ...
a8161a16d0bd8ad0c5d9ff20c56b52fbdba2d859
3,614,643
def merge_lists(config, path, base, nxt): """ a list strategy to merge lists """ for i in range(len(nxt)): base[i]=my_merger.merge(base[i], nxt[i]) return base
78dd343a41895253b46a4baaa6350ad7538b8142
3,614,644
def normalize_shape(shape): """Normalize a shape ``tuple`` or ``array`` to a shape ``tuple``. Parameters ---------- shape : tuple of int or ndarray The input to normalize. May optionally be an array. Returns ------- tuple of int Shape ``tuple``. """ if isinstance(s...
e7b874a2aeeed662678fea68d0f49e3085984f38
3,614,645
def getLogger(name: str, event_handlers=[]): """Creates a logger with . :type name: str :param name: the name of the logger to be constructed. :type event_handlers: list :param name: list of event handlers :rtype: :class:`logging.Logger` :returns: Logger created. """ return logger...
0b9a797f281a4c1406a94525fdafb27a527beafb
3,614,646
def parse_shortform_block_annotation(description): """Parses shortform version of the block annotation from a string. Parameters ---------- description : str Returns ------- dict Returns a dictionary with keys 'ref_version', 'chromosome', 'chromosome_scaffold', 'genome_pos'...
48925f3d7280f6e336f2045694674e868b489c07
3,614,647
def main(inmap, medianfilter): """Load input paramters, remove cosmic rays and NaNs, then make all off-limb pixels zero, and clean up limb, rotate map and do a cosine correction. """ ## Load configuration file config = ConfigParser() config.read("config.ini") ## Rotate inmap = inmap....
034a6be4edf9bbe2c13ec7b8c47420a74c705b41
3,614,648
def clean_data(data: DataFrame) -> DataFrame: """ Clean the titanic data by converting all the data into int64s. Drops the passenger id since it does not contribute to survivability. We drop the ticket attribute since the vast majority of them are unique, which makes it tough to convert th...
25529dafd51bbb44759678f5a7dfe9d32bb328ea
3,614,649
def get_days_where_1percent_plus_of_requests_lead_to_errors(): """Return days which more than 1% of requests lead to errors.""" conn = psycopg2.connect("dbname=news") cur = conn.cursor() cur.execute(days_which_more_than_1percent_of_requests_lead_to_errors) results = cur.fetchall() conn.close() ...
5d1bc225185710de64ac05410ce4c3e699502c2c
3,614,650
import torch def warp(x, flow): """ x: [B, C, H, W] (im2) flo: [B, 2, H, W] flow """ n, c, h, w = x.size() # mesh grid w_grid = torch.linspace(0., w-1, w).view(1, 1, 1, w).expand(n, 1, h, w).cuda() h_grid = torch.linspace(0., h-1, h).view(1, 1, h, 1).expand(n, 1, h, w).cuda() grid ...
d362228b3b7c21ca1037f4eba8dd081a256e41bc
3,614,651
import numpy def utils_fft(series): """ Computes the inverse fast foyer transform. Parameters Input series : array_like Output The transformed array. """ return numpy.fft.fft(series)
a9c9dd3b405b7ef185125576386ac9fc008ea76f
3,614,652
from typing import Union def not_operator(a: PrimitiveExpression) -> Union[HTCBool, Undefined, Error]: """ Logical not operator as defined by classad specification. .. code:: python3 parse("!False").evaluate() # result: HTCBool(True) """ return a.__htc_not__()
2cf5ba61d7cc169c6fa9922a2be418497d70a8bf
3,614,653
import os def create_inception_graph(): """ 저장된 GraphDef 파일에서 그래프를 만들고 Graph 오브젝트를 리턴한다. """ with tf.Graph().as_default() as graph: model_filename = os.path.join(model_dir, 'classify_image_graph_def.pb') with gfile.FastGFile(model_filename, 'rb') as f: graph_def = tf.G...
597cabb1afd64081bac54e3958d61074678c98ef
3,614,654
def BackwardElimination(x, y, Threshold): """ This function apply a backard elimination for a linear regression model, based on P Value level. Argument: ---------- - x: pandas dataframe The dependent variables - y: pandas dataframe The independent variable ...
0835efdccbd0404be5e333467732017ee7520649
3,614,655
def ListToString(list_items): """Convert a list of items into a unicode string of a comma-separated.""" str_list = [unicode(v) for v in list_items] return u', '.join(str_list)
79fa415561dd55380f84d3f238c0c33ef350bfec
3,614,656
def doubleFromQString(string): """ Return a double precision floating point conversion of a QString object. """ d, ok = string.toDouble() if not ok: raise ValueError('ValueError converting : %s' % string) return d
030c6dfc65f84a88e1299f394303219c0a4d644b
3,614,657
import re def load_primers_as_re(primer_fasta, mm, rc=False): """Load primers as regular expressions. Read primer file and record all specified sequences. """ primers = set() in_handle = open(primer_fasta, "rU") reader = fastaReader(in_handle) count = 0 for record in reader: i...
19bc389b975d3eed2cbc4de7489cdefadd891a32
3,614,658
from typing import Literal from typing import List def get_foot_marker(foot: Literal["left", "right"]) -> List[str]: """Get the names of all markers that are attached ot a foot (left or right)""" sensors = ["{}_fcc", "{}_toe", "{}_fm5", "{}_fm1"] return [s.format(foot[0]) for s in sensors]
518fbb3f68cbf8622b2bf1fa85f9ecae8008c456
3,614,659
def get_price_history(data, date, beta_window, sid, benchmark): """ Create a DataFrame containing the data for the necessary sids within that time frame """ if not beta_window: history_index = data.index.searchsorted(date) history_index_start = data.index.searchsorted(data[data[sid] != 0...
cddb1e59dbc783e4b36c0246e1d90e78169c6445
3,614,660
import six def _validate_string(s, accept_none = False): """ A validation method to convert input s to string or raise error if it is not convertable """ if s is None and accept_none : return None try: if isinstance(s,list): return [six.text_type(item) for item in s] elif isinstance(s,dict): return ...
0c7b20884a27714acb0c16bddcbc113bd3a8c60e
3,614,661
from .Geocode import Geocode def geocode(**kwds): """A factory for Geocode""" return Geocode(**kwds)
6e28b21e47a9801de3ac21f9c23aabebf4b30b88
3,614,662
def mfn_multiply_slepc(mat, vec, fntype='exp', MFNType='AUTO', comm=None, isherm=False): """Compute the action of ``func(mat) @ vec``. Parameters ---------- mat : operator Operator to compute function ac...
b40109e0578f5d7991d04994944d5566e543ff1a
3,614,663
def sdffile2selfies_lst(sdf): """convert sdffile into a list of SELFIES strings. Args: sdffile: str, file Returns: selfies_lst: a list of SELFIES strings. """ smiles_lst = sdffile2smiles_lst(sdf) selfies_lst = list(map(smiles2selfies, smiles_lst)) return selfies_lst
38027842a6900c44658d365e15669e21afb476c2
3,614,664
import json import base64 def get_gl_handle(schema, vineyard_id, engine_hosts, engine_config): """Dump a handler for GraphLearn for interaction. Fields in :code:`schema` are: + the name of node type or edge type + whether the graph is weighted graph + whether the graph is labeled graph + the...
0ea81c5d09013e55272582825b541ad3df4d9336
3,614,665
def has_single_gpu() -> bool: """Return whether there is only a GPU available.""" return get_available_gpus_number() == 1
32c186b538020ff9b14ca6fde4c61ce724d33cd4
3,614,666
def is_config_or_test(example, scan_width=5, coeff=0.05): """Check if file is a configuration file or a unit test by : 1- looking for keywords in the first few lines of the file. 2- counting number of occurence of the words 'config' and 'test' with respect to number of lines. """ keywords = ["unit ...
0e2823897b72a916afd9672beed904190bb2c1c2
3,614,667
def ParseVariationsCmdFromFile(filename): """Parses commandline switches string into internal representation. Same as ParseVariationsCmdFromString(), except the commandline switches string comes from a file. """ with open(filename, 'r') as f: data = f.read().replace('\n', ' ') return ParseVariationsCmd...
a74fe9a015622d30132ad16bae646f5ff8651db9
3,614,668
def select_period(xr_data: xr.DataArray, period: TimePeriod) -> xr.DataArray: """Function to temporally subset an xarray dataset from a tuple of start date and end date """ return xr_data.sel(time=slice(period.start, period.end))
b785137f3bea5bf55e3f1065db37e6f9884e0e2b
3,614,669
def process_snr(procstatus, dscfg, radar_list=None): """ Computes SNR Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, 2 post-processing dscfg : dictionary of dictionaries data set configuration. Accepted Configuration Keywor...
798c04ad55f4290875bb1ebec0a0540339503804
3,614,670
from typing import List from pydantic import BaseModel # noqa: E0611 def norm_router(synset_mappings: dict[str, list], category_mappings: dict[str, list]): """Generate node-normalization router.""" router = APIRouter() def normalize_one(curie): """Get normalizer response for CURIE.""" if...
4aff9b580037b7d82ac0d94e90cb7a94a098c078
3,614,671
import os def print_bbclex_instructions(fname,size): """Print suitable instructions for a BBC Micro lexicon of the given filename and size (the exact nature of the instructions depends on the size). If appropriate, create a .key file containing keystrokes for transferring to an emulator.""" if os.environ.get("MAKE...
836e4fe3bc510fef070b5c2bbf02f4214d409131
3,614,672
import sys def getROI(arr, win ='ROI selector', title = "", preview=True, crop = True, form="rect"): """ :param arr: array to crop :param win: window title or instance :param title: cropping image title :param preview: (True) if true it shows the resulting ROI before cropping. It coul...
d78ab857a5b998a1a7d2e30f8f7733d5b06f50fa
3,614,673
def generate_trappingtable(data): """Generates master table of when each plot has been sampled or missed. Input: Pandas Dataframe with the containing the following columns plot - plot number period - portal project period code, unique for each month of trapping yr - year sample occured mo - mon...
0d1bf0345ffd5aeb48f5ba7718d4aa8b203ebf16
3,614,674
def get_by_slug(*, db_session, slug: str) -> Plugin: """Fetches a given plugin or creates a new one.""" return db_session.query(Plugin).filter(Plugin.slug == slug).one_or_none()
7c1db90a9afb52e6ef3e208c2835ae01ec39f180
3,614,675
def authentication(req, required_roles, doctorid='', patientid=''): """ required_roles is a list of role's string TODO: change back to the decorator way of authentication may get params value (value of field expression) here by: params['doctorid'], see docstring in falcon.hooks.before(action) ...
1bc0318bb33bde9ff76620921d16afdfb8df56ca
3,614,676
import json def get_payment_url(order_id): """This method will pass order data (customer details, item data) to the GetUrl API (iCredit) and get payment url :param order_id: Sales Order No. :return: payment url(iCredit) (String)""" try: order = frappe.get_doc("Sales Order", order_id) icredit_settings = fra...
49b51fefb7c4dd548feda9d63f9fca7a4e5438dc
3,614,677
import torch def estimate_snn(model_dat, do_print=True): """estimate direct effects in identified structural form using PyTorch AD automatic differentiation forcasting y is done by reduced form since it is already solved for dy structural form: dy = my @ dy + mx @ dx mx, my is a linea...
22c8680b084371b48c543e06ea138d207a6b392f
3,614,678
def plot_var( data_frame, x_var="flow", y_var="CO_TP", label_var="mpr", pivot="distance", x_label="Flow [veh/m]", y_label="CO2 %", t_label="Distance [m]: ", legends=[r"0 \%", r"10 \%", r"20 \%", r"30 \%", r"40 \%"], fnt_size={"fontsize": 16}, x_size=5, y_size=7.5, tra...
f0c02e2d1c704935bd88220e5ddbac78ce1bc792
3,614,679
from typing import Optional from typing import Tuple async def decide_content_and_extension( accept_header: Optional[str] = None, accept_language_header: Optional[str] = None ) -> Tuple[str, str, str]: """Return content_language, content_type and extension based on request.""" # Default content-type/conte...
c35b898c2810113bc016acb36abcc65714c3760f
3,614,680
def score_segmented_edges(pred_seg, pred_edges, lbl_seg, lbl_edges): """ Find the precision & recall scores for a set of predictions tied to segments within a volume. Each predicted segment is mapped to its maximally overlapping segment within the label segments. """ overlaps, pred_ids, lbl_ids ...
3b69a820916258b5e1d417d70b87c99cd6826021
3,614,681
import json def bundle_to_json(fh): """ Convert the received HG10xx data stream (a mercurial 1.0 bundle created using hg push from the command line) to a json object. """ # See http://www.wstein.org/home/wstein/www/home/was/patches/hg_json hg_unbundle10_obj = readbundle(get_configured_ui(), fh...
c99b7311b7844549e8f1d754ed5c7f74bb0ff2cf
3,614,682
def rotate_velocities(a,d,mua,mud): """eq 3.68, """ mu = return_muicrs(a,d,mua,mud) mugal = np.dot(return_gaia_Agprime(),mu) # eq. 3.68 # solve for positions ricrs = return_ricrs(a,d) rgal = np.dot(return_gaia_Agprime(),ricrs) # implement eq 3.63 ell,b = np.arctan2(rgal[1],rgal[0])...
49d4edb52f5dffa64232db3fba0475db9a1b61f5
3,614,683
import os def save_fig_filebox_button(fig, filename): """ Create ipython widgets to allow the user to save a figure to the specified file. Parameters ---------- fig : matplotlib.Figure The figure to be saved. filename : str The filename the figure should be saved to R...
6091869b38d6f1aa632e86e6f1777af91203d218
3,614,684
import logging def open_api(version): """ :param version: :return: """ def fn(method): @wraps(method) def wrapper(*args, **kwargs): openClass = get_api(version) code, msg = openClass.check_header() if code != 0: return response_js...
2bda139c6d85268030cd2477d7e6f874b781a968
3,614,685
from typing import Iterable import calendar def calc_eomday(year, month): """end of month day""" if isinstance(year, Iterable): assert isinstance(month, Iterable) return np.array([calendar.monthrange(y, m)[-1] for y, m in zip(year, month)]) else: return calendar.monthrange(year, mo...
ef9adb0ee054a51d9ad39e5ddb0e2ce5fb7465be
3,614,686
import json def prepare_clean_listing_record(listing_serializer_record): """ Clean Record Sample Record (record_json) after clean { "id": 316, "title": "JotSpot 28", "description": "Jot things down", "unique_name": "ozp.test.jotspot.28", "description_short": "Jot stuff d...
7330b24f90345be14966f28d61e7665b0785a9e6
3,614,687
def retrieve_path_dict(parse_tree, path): """ retrieves the parameter values of an path instance :param parse_tree: the json parse tree of the swagger document :param path: path value of the dict to find :return: """ keys = path.split("/") my_tree = parse_tree for key in keys: ...
f1d1163b15d2d114b1024650f4e459e6142f513e
3,614,688
def has_shape(data, shape, allow_empty=False): """ Determine if a data object has the provided shape At any level, the object in `data` and in `shape` must have the same type. A dict is the same shape if all its keys and values have the same shape as the key/value in `shape`. The number of keys/val...
f04add860bb6b886bb693ddc85b3d4877245d749
3,614,689
from typing import List def get_unmatched(repo_path: str, language: str, original_commit: str, translated_commit: str) -> List[PropEntry]: """ Get all original key values that have not been translated. :param repo_path: Path to repo. :param language: The language identifier (i.e. 'ja') :param orig...
4fe4540f901bbaff010ec09c3b55ecbffa42c7da
3,614,690
from onto.database.firestore import FirestoreReference def to_ref(dm_cls, dm_doc_id): """ TODO: check doc_ref._document_path alternatives that are compatible with firestore listeners :param val: :return: """ doc_ref: FirestoreReference = dm_cls._get_collection() / dm_doc_id retu...
4f272ef038915f3e42fc7a12dc38147039ac7eca
3,614,691
def augment_specs(prefix, specs, pinned=True): """ Include additional specs for conda and (optionally) pinned packages. Parameters ---------- prefix : str Environment prefix. specs : list of MatchSpec List of package specifications to augment. pinned : bool, optional ...
f45063448ceca11a31375a97e4a64c95830ce291
3,614,692
def Pendulum(a0=0, v0=0): """ Main function for calling matplotlib animation a0: float starting angle (rad) v0: float starting angular velocity """ aVec = [a0] vVec = [v0] fig, ax = plt.subplots(figsize=(12,12)) line, = ax.plot([0, np.sin(aVec[0])], [0, np.cos(aVec[0])]) ax.set_xlim(-1.2,1.2) ...
7350d08002018a385f7674a4ce6dafac0b5c4c21
3,614,693
import requests def metrics(self, **kwargs): """ History of your Blockfrost usage metrics in the past 30 days. https://docs.blockfrost.io/#tag/Metrics/paths/~1metrics~1/get :param return_type: Optional. "object", "json" or "pandas". Default: "object". :type return_type: str :returns A list o...
bc53dcb7024373dd1f99acadcfbc9902b2810218
3,614,694
def build_word_pattern(word, language): """Given a word and a language, calculate the word pattern and the number of unique character is has.""" pattern = "" unique = 0 char_map = {} for char in word: if char not in char_map.keys(): char_map[char] = unique unique += 1...
deaffe957935cc9659e9b88e8908bb56c8a3ffad
3,614,695
import getopt import os def validate_arguments(sys_param): """ Validate command line arguments passed to the script :param sys_param: Command line arguments : Script Name, File Path, Build Information, Deployment Type, Deactivate Old Product are required and Options...
05087cd7483fda436762a30cf9dd7cf88d3a2e5a
3,614,696
def plot_spectra_by_type(frequency, spectra, classes, title=''): """Plot mean spectrum with its variance for a given class. Parameters ---------- frequency : pandas Series, shape (n_freq_points,) Frequencies for which the Raman spectra were acquired. spectra : pandas DataFrame, shape (n_sp...
ccdf36c05da7d68f3d0e27560921cddb0c1b94a0
3,614,697
def RR_calc(classes, TOP): """ Calculate Global performance index (RR). :param classes: confusion matrix classes :type classes: list :param TOP: number of positives in predict vector per class :type TOP: dict :return: RR as float """ try: class_number = len(classes) ...
814a11c339b25dc687d537efd3244ddad9c0f8fd
3,614,698
def isctime(sys, strict=False): """ Check to see if a system is a continuous-time system Parameters ---------- sys : LTI system System to be checked strict: bool (default = False) If strict is True, make sure that timebase is not None """ # Check to see if this is a con...
02825d5664a066966ff4763b7edb7401b6dd14af
3,614,699