content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def gradient(P, Q, Y): """ Calculates the gradient of the Kullback-Leibler divergence between P and Q :param P: the joint probability matrix :param Q: the Student-t based joint probability distribution matrix :param Y: low dimensional matrix representation of high dimensional matrix X :return: a...
b08116b5bca764b1b9149eaf03f7b3525c99ce3e
72,745
def _exclude_loop_arguments_variables( param: _pipeline_param.PipelineParam) -> str: """Gets the pipeline param name excluding loop argument variables. Args: param: The pipeline param object which may or may not be a loop argument. Returns: The full name of the pipeline param without loop arguments ...
5c7d55c75db12afe6862a79d7fc8745443a650b6
72,746
def get_integration_filter(args, targets): # type: (IntegrationConfig, t.List[IntegrationTarget]) -> t.Set[str] """Return a list of test targets to skip based on the host(s) that will be used to run the specified test targets.""" invalid_targets = sorted(target.name for target in targets if target.target_type ...
46a936aa797b928506ba2328034c1319da3f821a
72,749
def callback(func): """Decorator for non blocking functions.""" setattr(func, "_pyhap_callback", True) return func
6b1f2297dda8c7b3df5a75142a921e20fd4768f8
72,750
def docker_compose_project_name(): """Set a consistent project name to enable optional reuse of containers.""" return "pytest-python-gitlab"
0c8ed2e63692fec969c042b4e2e8094459045c5b
72,751
def midi_to_seq( midi_obj, dtype=np.int16, rate=22050, pitch_aug_factor=0, time_aug_factor=1, mode="format", time_shift=0.0125 ): """method for midi_obj. Input: miditoolkit_object, sampling rate Output: note_seq: np.array([pitch1,pitch2....]), which length is equal to note.time*rate ...
ab4f6dad327e1b1c5e7715fb765aaefc33146115
72,752
def units_LexiconFormula(*args): """ * Return a unique instance of LexiconFormula. :rtype: Handle_Units_Lexicon """ return _Units.units_LexiconFormula(*args)
63240baa2e30e3ed0d6fa7ead3768741b57bfb7f
72,753
def stop(backupplan_name, p5_connection=None): """ Syntax: BackupPlan <name> stop Description: Removes the plan <name> from the scheduler Return Values: -On Success: the string "1" (the plan was successfully removed) the string "0" (the plan was not removed or is running) ...
e73dbe04bc0fc8824d144ff12361a03d30ab5c1b
72,754
def heron(_a, tol, _x0=None, termination_criterion='x'): """ Method for finding the non-negative, square root of a real number. """ def func(_x): return _x**2 - _a def dfunc(_x): return 2*_x if _x0 is None: _x0 = _a return newton(func, dfunc, _x0, tol, ...
f0580093f1fa5b0d008c290c74b3e5403f36aa30
72,756
def shopping_graphplan(): """Solves the shopping problem using GraphPlan""" return GraphPlan(shopping_problem()).execute()
c0a1cf31ebf796ec2b0b879780661113e6691ed9
72,757
from operator import gt def _nodes2dataframe(G: gt.Graph) -> NodeDataFrame: """ Takes a Graph-tool graph object and returns nodes data frame. """ expect_nodes(G) if len(G.vp) != 0: prop_dfs = [] for prop in G.vp: prop_dfs.append(NodeDataFrame({f"{prop}": list(G.vp[f"{pr...
a517e8ee8aaedde3ebaeb4a916eec35260b49352
72,758
import bisect def clause_b_1_3_3_T_m_i_beam( I_z_1, I_z_2, I_z_3, I_z_4, I_f_1, I_f_2, I_f_3, I_f_4, alpha, T_z_1, T_z_2, sigma: float = 5.67e-11, *_, **__ ): """ :param I_z: :param I_f: :param alpha: :param sigma: :return: """ ...
9e0b2f32641c905aedb019ec4bb986297371f198
72,760
def _partition(entity, sep): """Python2.4 doesn't have a partition method so we provide our own that mimics str.partition from later releases. Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the...
0172ce09bd0451eb538122bd9566a3e70d0dcc15
72,761
def get_config_bool(name, fallback=False): """Checks if a config value is set to a valid bool value.""" cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX) return cli_config.getboolean('servicefabric', name, fallback)
3e18b97b12dd7446b973ffb3215d823d75857d26
72,762
def get_user_access_rights(username: str, is_vendor: bool = False): """ Query Redis for information about the user by given username. Arguments: :param username (str) authorized user's username :param is_vendor (bool) whether method should return vendor or SDO accessRigt """ ...
90d230129a2a09ea848ef11eb0b7e83cbe8624e8
72,763
def safe_email(email): """Scrub email address before using it.""" if EMAIL_REGEX.match(email) is not None: return not email.startswith(".") and ".." not in email logger.warning("Invalid email address: %s.", email) return False
68868e5bdfb413caf2f94edb096f319292fe064c
72,764
def read_data(byte_data_directory, x_filename, y_filename=None): """ reads in byte date from a list of filenames given in file located at x_filename. if y_filename is supplied labels will be read in and a map will be created as well and a label column added to the returned dataframe """ X_files...
3566963b1f9b27957585f2de561b45b0c5d86915
72,765
def get_region_name(): """ Return EMR cluster region as string :return: """ return get_extraInstanceData()['region']
628a932cb24352b0ca72cc8741172887251ee020
72,766
def split_into_fixed_length_chunks(dataset, fixed_length, min_length=32, keep_residuals=False): """ Splits the sequences into shorter sequences with the same length. Args: dataset (dict): length: keep_residuals: Returns: """ new_data = {} # Detect <key, valu...
4ff93445170060e63ea36cdc4c6aa462b6d0e32a
72,767
def run(args): """Admin function used to set the cluster that will be used to actually perform jobs """ try: authorisation = Authorisation.from_data(args["authorisation"]) except: authorisation = None try: passphrase = str(args["passphrase"]) except: pass...
9bbdf9a618c682ef58a1f8f9e4e62c892362b2f3
72,768
def get_phe_title(db, phename): """ Search bar SciDBnew: res = str(list(phef[phef['description'] == "asthma_diagnosed_by_doctor"]['title'])[0]) """ phef = db.get_phenotype_fields(association_set=str(db.list_association_sets()['name'][0])) if phef.empty: return None else: ...
93ef978e9b79760d0226cc0fd00d827f7b3872ff
72,769
import random def make_graceful(ex: Exception, ex_uuid: UUID) -> str: """ makes the incoming exception graceful Args: ex (Exception): the raised exception to make graceful ex_uuid(UUID): uuid identifying exception in the logs Returns: str: graceful error message """ ...
af53769ec9ac3880cbab4d7c143549d4f5fc3aa5
72,771
def run_model(data, labels, return_coef=False): """ Runs provided LogisticRegressionCV model with the provided data and labels. Parameters: data (pandas.DataFrame): DataFrame of CMTF components labels (pandas.Series): Labels for provided data return_coef (bool, default: False): ...
99eab8e415bbd5e4f26ef5741292b42510a89e8e
72,772
def hpo_disease_file(request): """Get the path to the hpo disease file""" print('') return hpo_phenotype_to_terms_reduced_path
9075f371366428dc8634edf5d35e148ad777652c
72,773
import warnings def check_already_dropped(labels, dropped_cols, name, dropped_by='numeric_only', warn=True): """Check if columns have already been dropped and return only those that haven't. Args: labels (single label or list-like): Column labels to check. droppe...
d584691cf2cd073641625b6358000cbe72f736ae
72,774
import uuid import string def plot(df, map_widget=None, name=None, renderer_type=None, symbol_type=None, symbol_style=None, col=None, colors='jet', alpha=1, **kwargs): """ Plot draws the data on a web map. The user can describe ...
ae9a30a7e5bc0e333ecc96e184739e09610a2085
72,775
import json def LoadWorkerOutput(output): """Load output from worker processes to our internal format. Args: output: list of strings. The stdouts of all worker processes. Returns: A tuple of start_time, latency, size. Each of these is a list of numpy arrays, one array per worker process. start_tim...
554ffd0821764f6ddc312e93575c56713bc45ac2
72,776
import requests import json def req(method, url, headers={}, payload=None, status_code=False, timeout=30): """ Request function with error handlers (output: dict) """ pass_headers = {} const_headers = { 'User-Agent': '{}/{}'.format( __prog__, __version__ ) }...
aca322eaec9df33e870563d3672b002213d13a3f
72,777
def wrn40_8_cifar10(classes=10, **kwargs): """ WRN-40-8 model for CIFAR-10 from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pre...
73214a88ff2b9500326f889278cea7c99ab97fd8
72,779
from typing import List def gen_from_dataframe(df: DataFrame, caption: str = None, header: List[str] = None, line_names: List[str] = None, index: bool = False, index_start: int = 1, horizontal: bool = False) -> str: """ Генерирует таблицу latex из DataFame. Ну...
47c8720ee89def6b616641eca510acedbe8210c5
72,780
def perform_extended_GST_on_data(filename_data_input, filename_target_gateset, filename_fiducials, filename_germs, maxlength_germseq): """Performs extended/long GST on data -------------------------------------------------------------------------...
4ba557ac2e1d9258837660b5949ddcf3c6cb2173
72,781
def custom_x_bounds_max(current_shooting_point: int, n_elements: int, n_shooting: int) -> np.ndarray: """ The custom function for the x bound (this particular one mimics linear interpolation) Parameters ---------- current_shooting_point: int The current point to return the value, it is defi...
7e2faeee8750966674f976be317c0f9a775d51e5
72,782
def compatibility_g_m(gen_1, gen_2, name_1, name_2): """Check compatibility.""" print("Checking compatibility of {} with {}.".format(name_1, name_2)) r_code = 0 for seq in gen_1: if seq not in gen_2: print("FAIL\t{} sequence not found in {}.".format(seq, name_2)) r_code =...
0ce34eb6ebe97bca179425939c95a2a6a19f6e6a
72,783
def review_list(request, resource_type): """ :param request: :param resource_type: The type of resource to generate a review list for. :return: Returns a list of reviews of that particular resource_type. """ resources = Review.objects.filter(resource_type__slug__exact=resource_type.lower()) ...
c4d83b403d1b60c80f61f11998b1f1f4b3fe1e7c
72,784
def meanPtVersusPartonicPt(histFile='./combined.sum.hist.root', trigKey='notrig', subProcess=''): """note: errors are absolutely fake""" f = ROOT.TFile(histFile) m = MiniMcHistos(trigKey, subProcess, f) c = ROOT.TCanvas() m['partonicPt'].GetZaxis().SetRangeUser(m['partonicPt'].GetMinimum(1e-10...
709d9f8624c5115e0a954eb5a51b9a097f4aeb5d
72,785
def create_regional_summary (results): """Creates the regional summary Parameters ---------- results : dictionary results from the model, dictionary with each community or project as key Returns ------- DataFrame containing regional results ...
c90d3ac11919ce6330c52a2133f2733193a78373
72,787
import socket def getaddrinfo(host, port=None, family=0, socktype=0, proto=0, flags=0): """return (family, socktype, proto, canonname, sockaddr) >>> socket.getaddrinfo("www.python.org", 80, 0, 0, socket.SOL_TCP) [(2, 1, 6, '', ('82.94.164.162', 80)), (10, 1, 6, '', ('2001:888:2000:d::a2', 80...
5fde1bc04887e002199e119b24cde08227d14c0b
72,788
def scatter_element_add(tensor, index, value, like=None): """In-place addition of a multidimensional value over various indices of a tensor. Args: tensor (tensor_like[float]): Tensor to add the value to index (tuple or list[tuple]): Indices to which to add the value value (float or ...
2bc08d37be6948a820e3b2edd408547b14948516
72,789
from typing import Optional from typing import Sequence def get_volume_backups(compartment_id: Optional[str] = None, display_name: Optional[str] = None, filters: Optional[Sequence[pulumi.InputType['GetVolumeBackupsFilterArgs']]] = None, source_volum...
4cc5d688b2af608b17ea8ecf3d2844be176fa95f
72,790
def getParam(prompt, default, helpMessage="No help implemented yet!"): """Get a parameter from the user interactively. Also sets a default and displays a help message if a user types "h" or "help". """ print "\n" + bcolors.OKBLUE + helpMessage + bcolors.ENDC + "\n" param = raw_input(prompt) if ...
ed9d2afd663f1c4d1bc36e4470de0f4c15adf2a7
72,792
def showCategories(): """ Display the main catalog page using any of the listed routes.""" lCategories = session.query(Category).order_by(Category.name).all() if len(lCategories)==0: sMsg = "" if 'username' not in login_session: sMsg = "There are currently no categories in the system. " sMsg += "Please ...
f7bd569ba132445e7ea072c136c96d18cec0b0d9
72,793
def docker_registry_username() -> str: """Retrieve the name of the user to use for authentication to the secure registry service.""" return _docker_registry_username(scale_factor=1)[0]
d02a1f870305b6b8c30f69068dbd301b70d7ba55
72,794
def diaresnet110_cifar100(classes=100, **kwargs): """ DIA-ResNet-110 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, defa...
82021a5cc88ec5c3c470fafe6790da6dc1eae387
72,795
def multiple(op1: int, op2: int) -> int: """ :param op1: :param op2: :return: """ return float(op1 * op2)
c9681de0655ba07c051a8bd64515e826df82a18d
72,798
def dense_layer(x, config): """Configurable dense layer. Supports scale layer. Args: x: Input tensorflow tensor. config: network_config.DenseLayer object. Returns: An output tensor. """ if config.num_outputs < 0: raise ValueError('Please set num_outputs to a positive number:' ...
6b77b50598dd19f0632dbb100c3119bf2793ce25
72,799
def summary_of_datasets_by_user(username): """Return summary information of datasets the user has access to. Return dictionary of summary information. Raises AuthenticationError if user is invalid. """ # Get all the datasets the user has access to. datasets = search_datasets_by_user(username, ...
9e69e5bef72e37659b0fb45476f4004bdb4e7c30
72,800
def simplevolume(flist, distances, voxel, g): """estimate the volume by the fraction of interior points""" res = options.ics_partial_volume_resolution distance_threshold = options.ics_distance_threshold sx, sy, sz = g["dx"] / res, g["dy"] / res, g["dz"] / res res1 = res + 1 # count up...
8623754e3d5bad7a4bff9c7a4e814b2b34648b07
72,802
import collections def expand_realms(db, project_id, realms_cfg): """Expands realms_config_pb2.RealmsCfg into a flat realms_pb2.Realms. The returned realms_pb2.Realms contains realms and permissions of a single project only. Permissions not mentioned in the project's realms are omitted. All realms_pb2.Permis...
68ee2027d1c848386162ca68bd39a5e623b80041
72,803
def _vm_replica_cb_detail(repname, action, jsons, key_json_idx=None): """Create tasklog detail""" res = {'repname': repname} if not jsons: return res for out in jsons: if 'msg' in out: res['msg'] = out['msg'] res['rc'] = out['rc'] if key_json_idx is None: ...
083a2c96563d173a1cca2f2ad26e0e44875afb1e
72,805
def create_test_bot(config_settings: dict, chatbot_engine_name: str = "") -> ChatbotEngine: """Create a bot for testing.""" if not config_settings: config_settings = load_configuration(get_configuration_path(), "BBOT_ENV", "testing") r...
257b1cb51d23e4f5cc60be146270b21053417c2b
72,806
def coref_cleaning(t, new_coref_np, current_coref): """Assign the correct coreference tag according to Args: t (token), new_coref_np (Boolean), current_coref (int) Return: new_coref_np (Boolean), current_coref (int) """ if t.coref.startswith('(') and t.coref.endswith(')')...
9e2d1db3316c6ddd2c09050b64838cc92d5dd651
72,807
def topsort(order): """Given a binary array defining a partial order (o[i,j]==True means i<j), compute a topological sort. This is a quick and dirty implementation that works for up to a few thousand elements.""" n = len(order) visited = np.zeros(n) L = [] def visit(k): if visited[k...
2b09b5589655e7e3391c9802d993cd565061a4b8
72,808
def bipartite_modularity(B,m,R,T,CO): """Computation of the bipartite modularity as described in ""Modularity and community detection in bipartite networks" by Michael J. Barber." """ RtBT = R.transpose().dot(B.dot(T)) Qcoms = (1/m)*(np.diagonal(RtBT)) Q = sum(Qcoms) Qcoms = Qcoms[Qcoms>0] CO[...
cc5aac25c51136511af693bd54978f83ee9a9707
72,809
def calculate_interval(s): """ Expand intervals expressed as nI, where I is one of: s: seconds m: minutes h: hours d: days (24 hours) w: weeks (7 days) """ m = INTERVAL_RE.search(s) if not m: raise InvalidInterval("No match: %s" % s) n = int(m....
10c4ccac0e09e1d23de7486b8dc30b459ff9a1f6
72,810
def get_default_tokenizer(): """Only support split tokenizer """ def _split_tokenizer(x, delimiter=None): if delimiter == "": return list(x) return x.split(delimiter) return _split_tokenizer
91cc23378d230d9cb47fbe0c47cf7a33cbce5265
72,811
def admin_guard(f): """ Middleware (guard): checks if the current authorized user is election officer or not. """ @wraps(f) def decorated_function(*args, **kwargs): if 'eid' not in kwargs.keys() or F.g.user.username \ not in meta.Election(kwargs['eid']).get()['election_of...
e5d5fce9c5b2a0d2197c78f50d54f5d75e4cf7cc
72,812
def prt_or_rsl(damage_type: str, prt: int, rsl: int) -> int: """ Depending on the given damage type, returns Prt or Rsl respectively, whichever is more appropriate :param damage_type: The DamageType being dealt :param prt: a unit's Prt :param rsl: a unit's Rsl :return: whichever of Prt and R...
ee74909d887a58b7f5c7817992663b46737a3d82
72,814
from typing import Optional def paginate( items_query: Select, count_query: Select, page: int, per_page: int, *, scalar_result: bool = False, unique_result: bool = False, item_mapper: Optional[Mapper] = None, ) -> Pagination: """Return `per_page` items from page `page`.""" if p...
8a3c1ad51c5ab7be5f790662330bf64098593a83
72,815
from ubinascii import hexlify def get_upp_payload(upp: bytes) -> bytes: """ Get the payload of a Ubirch Protocol Message :param upp: received UPP :return: payload of the UPP """ if upp[0] == 0x95 and upp[1] == 0x22: # signed UPP payload_start_idx = 23 elif upp[0] == 0x96 and upp[1...
d645f584c4650c055202760cbb9f1d3795f9e5cc
72,816
def _lineage_ngs_define(seq, proto): """ Given local sequence and protospacer sequence, define a local region of indel/SNV analysis. Determines 20bp flanking sequences to the left and right of cut site. Helper function of lineage_ngs_dict2csv(). :param seq: local genomic sequence :param prot...
314c4909bba78b78848db9f6c2d710b960bcbeaf
72,817
def servers_element(settingsXml): """Get or create the <servers> element from the passed "settings.xml".""" try: serversElement = firstElement(settingsXml, '/{%(ns)s}servers') except IndexError: serversElement = etree.Element('servers') settingsXml.getroot().append(serversElement) ...
5151dff14b50bc58353c1e97a9a08c4b1f70ceb0
72,818
def index(request): """ View function for home page. """ return render( request, 'index.html', context={}, )
67bd739eb23b0930f25b2956c006dcbfd2e0d3bd
72,819
def grant_user(cursor, **userArgs): """ Grant the "user" role to a user Parameters: ----------- cursor: Psycopg2 cursor Cursor of type RealDict in the postgres database userArgs: Dict dictionary with the different element: username: Str name of the user ...
6b37258ab78d239c7f54425c3967303ba61f48bb
72,820
def ReadSAMnoMem(ref, art, output, compareList, readdic, rankdic,phredoffset): """ Main function for comparing to mappings. This functions takes the complete alignments for artificial and reference genome and goes through them in parallel. Since the mappings are sorted the function alternates the parsing of...
6aba18586a54d4a514b8fd515ec2a5b629fea708
72,821
def crext_ExtendedMasterSecret(): """Create an Extended Master Secret extension""" return ExtensionType.extended_master_secret.value + lenprefix(b"")
0ac971c78328637043df54cd8660f79ae5840bd0
72,822
import uuid import random def set_facility_code(facility_id): """ Generate and set a unique facility code Args: facility_id: the facility ID Returns: the facility code """ db = current.db s3db = current.s3db table = s3db.org_facility query = ...
ec432fb0620ed92557c3f2a1f06ea15dce9f9820
72,823
import json def load_dict_from_json(filename: str) -> dict: """ Load the given file as a python `dict` Parameters ---------- filename: `str` an absolute path to the json file to be loaded. Returns ------- `dict` The loaded json file as a python dictionary. """ with open(filen...
1d55e5dbcf33e7f1d21063be7b722a5ed5bc6bb3
72,824
import random import string def metadata(time, shape_type=None, coords=None, attributes=None): """ Create single VIA metadata record. :param time: time in seconds :param shape_type: see VIA_RSHAPE :param coords: RECTANGLE: [x,y,w,h], LINE: [x1,y1,x2,y2], ... :param attributes: {attribute id: ...
85bf0bcec544baf7fff6ced20c46a62806d5f601
72,825
def create_test_function( test_file_loc, tested_function, test_name, regen=REGEN_TEST_FIXTURES, ): """ Return a test function closed on test arguments to run `tested_function(test_file_loc)`. """ def test_proper(self): test_loc = self.get_test_loc(test_file_loc, must_exist=T...
b4cb7eb723daa4451315e9770a2470b8ccd8902b
72,826
def _Run(args, version): """Deploy a model to an existing Vertex AI endpoint.""" validation.ValidateDisplayName(args.display_name) if version != constants.GA_VERSION: validation.ValidateAutoscalingMetricSpecs(args.autoscaling_metric_specs) endpoint_ref = args.CONCEPTS.endpoint.Parse() args.region = endpo...
b655027d1020b01600c6160f73c76ba85dedb470
72,827
def user_group_required(*required_groups): """ Decorate a view function to check if user belongs to one of the groups passed as an arguments. Can decorate a simple view function as well as dispatch method of generic view class. """ def wrapper(func): def wrapped_function(*args, **kwargs): ...
fe0f0bbf75279233f4b96a3ae156b2fa666e9803
72,828
import json def edit_notes_simple(*args): """ Render a list of Notes as simply as possible Still tries to exercise the same codepaths as a normal endpoint, though. """ def render_n2_desc(n: Note): return n.desc def render_n2_json(n: Note) -> str: return escape(json.dumps(n.as...
45b3d51d52208929672ba1b52b7d15b5e0562a9f
72,829
import shutil def prepare_empty_dirs(dirs: list): """ 建立空目录。若已经存在,则删除后创建。 parents=True Args: dirs: Path list Returns: dirs 中各个目录的句柄 """ result = [] for d in dirs: if d.exists(): shutil.rmtree(d.as_posix()) d.mkdir(parents=True, exist_ok=Fal...
a672542576ea7eeff8b99aa43d223cfe48069ecc
72,830
def collect_not_null_kwargs(**kwargs) -> dict: """ Collect not null key value pair from keyword arguments. .. versionadded:: 1.0.1 """ return { k: v for k, v in kwargs.items() if v is not None }
84e3438b5a4f0a48a4b558cc50b65a21e5883af9
72,832
def get_axislabels(fluor="dff", area=False, scale=False, datatype="roi", x_ax=None, y_ax=None): """ get_axislabels() Returns appropriate labels for x and y axes. If y_ax is None, y axis is assumed to be fluorescence, and label is inferred from fluor and dff parameters. If...
5d95cae0846235451adb125a7773bc83652c64e1
72,833
def multiple_data_analysis(model_location, data_locations, **kwargs): """Run model analysis for a single model on multiple data sets. Args: model_location: The location of the exported eval saved model. data_locations: A list of data set locations. **kwargs: The args used for...
a6c1004c9073549102f30b47cbb31207c3387f53
72,835
def terminate_instance(): """ Terminate an instance. @return: Response. """ helpers.require_parameters(['InstanceId.1']) instance_id = helpers.get('InstanceId.1') previous_state = describe_instance_by_id(instance_id) new_state = _terminate_instance_request(instance_id) return _modif...
1e28248c2efb7c21f9bc0b3abb32d4405958b780
72,836
def get_n_neighborhood_start_stop_indices_3D(volume_shape, point, n): """ Compute the start and stop indices along the 3 dimensions for the n-neighborhood of the point within the 3D volume. Note that this returns an index range where the end is *non-inclusive*! So for a point at x,y,z with 0-neighborhood (...
6eb1c6f0b4ff537b3d0eb1b647b019a2d61480b7
72,837
def find_declaration( declarations, decl_type=None, name=None, parent=None, recursive=True, fullname=None): """ Returns single declaration that match criteria, defined by developer. If more the one declaration was found None will be returned. For more inf...
a3e534029a38e3547756790ab7703507a835f90a
72,838
from typing import Dict from typing import Any def add_to_dict_with_swapped_keys(old_dict: Dict[Any, Dict], new_dict: Dict[Any, Dict]) -> Dict[Any, Dict]: """ Swap the keys of two nested dictionaries in a new dictionary. {'Key1': {'Key2': 42}} -> {'Key2': {'Key1': 42}} ...
2b4d0a0d8bd2734d8c0bc7abde1fa659454f1464
72,839
def wet_bulb_globe_temperature_BoM(base): """Calculate Wet Bulb Globe Temperature approximations. Parameters ---------- base : dict of array_like dict containing CMIP-style variables, which should contain the following keys: tas : near-surface air temperature...
7c384dd4bbab659b7a2bda6a3ffea98957212590
72,840
import typing import functools def build_simple_validator(func: typing.Callable, *args, **kwargs) -> typing.Callable[[typing.Any], typing.Any]: """Build a ready-to-use simple validator out of a function. Args: - func: callable, the function to be called to validate an input - args: list, args...
cc8227cce228579e51aa05ceb25d9020d51eb199
72,842
from typing import Optional def assign(new_value: NodeInput, variable_id: str, name: Optional[str] = None) -> Node: """Return a node which produces the Assign operation. @param new_value: Node producing a value to be assigned to a variable. @param variable_id: Id of a variable to be updated. @par...
9b641c32a8d0ed88eb8666e088f6a7b37b39e083
72,844
def is_scipy_stats_cont(arg, scipy_stats_cont=SCIPY_STATS_CONT): """ Returns if arg belongs to scipy.stats.continuous """ return isinstance(arg, tuple(scipy_stats_cont))
cc3001ce242f87072e6ec9014b64c7fa02a75dbd
72,845
def oph_to_gal(): """ Compute the transformation from heliocentric Ophiuchus coordinates to spherical Galactic. """ return matrix_transpose(gal_to_oph())
387b1f27c1e0ebdfc4cff5573e58f246a68f25aa
72,847
import torch def NMTCriterion(vocabSize, opt): """ Construct the standard NMT Criterion """ weight = torch.ones(vocabSize) weight[constants.PAD] = 0 crit = nn.NLLLoss(weight, size_average=False) #crit = nn.NLLLoss(size_average=False, ignore_index=onmt.Constants.PAD) if opt.gpus: ...
2550cc0579800e02c3bdcf27bd0599dca3d7576d
72,848
import torch def quat_conjugate(a: torch.Tensor) -> torch.Tensor: """Computes the conjugate of a quaternion. Args: a: quaternion to compute conjugate of, shape (N, 4) Returns: Conjugated `a`, shape (N, 4) """ shape = a.shape a = a.reshape(-1, 4) return torch.cat((-a[:, :3...
530eb2a8d8b9b87de2bfcaeb48729704908131cc
72,849
def insert_audio_clip(background, audio_clip, previous_segments): """ Insert a new audio segment over the background noise at a random time step, making sure that the audio segment does not overlap with existing segments. Arguments: background -- a 10 second background audio recording. a...
42253d611f32418085f1ac13299d9ba0c59e3f4b
72,850
def image_example(img_string, mask_string): """Returns tf.Example containing image and mask as byteslist Args: img_string: bytes string of image mask_string: bytes string of mask Returns: tf.train.Example which will be serialized and written to tfrecord """ feature = {...
8c23bf03591598695314edd4d0def5a4e59e5efb
72,851
import re import uuid def add_new_mol(rdmol, target): """Function to add a new bound Molecule object Takes an RDKit molecule and a Target Returns None""" new_mol = Molecule() rdProps = rdmol.GetProp("_Name").split("_") comp_ref = add_new_comp(rdmol) if comp_ref is None: return None...
750e78ba56a2cc967b205f72a6cb315a9c5df71d
72,853
def compute_dominant_color(image, n_clusters=3, max_iter=10, threshold_error=1.0, attempts=10): """ Compute the dominant color of an input image using the kmeans clustering. The centers of the clusters are the dominant colors of the input image :param image: input image. Either a multi-channel color im...
85c386487115398e2bebb3b57f19486ab39f3ee7
72,854
def createUnits(version): """Create a dictionary with units.""" try: units = Units(codata[version]) except KeyError: raise NotImplementedError("Codata {0} not found".format(version)) # Define all units # permittivity of vacuum units["_eps0"] = 1 / units["_mu0"] / units["_c"] **...
56583dd1470b523d3655c041ef93dc5f960c91ab
72,855
def low_cut_filter(x, fs, cutoff=70): """ Low-cut filter Args: x (ndarray): Waveform sequence fs (int): Sampling frequency cutoff (float): Cutoff frequency of low cut filter Return: (ndarray): Low cut filtered waveform sequence """ nyquist = fs // 2 norm_cutoff = ...
0ece15d02adaa39a0c85b2efe854b83afd67194a
72,856
def interpret_model( X, model, interpreter=RIPPER(), model_predict_function=None, score_function=score_accuracy, ): """Interpret another model. Parameters ---------- model : trained classifier, e.g. sklearn, keras, pytorch, etc. X : DataFrame, numpy a...
93a78e6ff8c8e446e1f567a7b5a0dcc78b8ac02f
72,857
def week_from_start(in_path, col, identifier): """ Description:\n Calculate the number of weeks for each logging since the first day of the logging for each participant(identifier). The returned values for loggings from the first week are 1. Input:\n - in_path (str, panda...
983b2bd618306eb466df0dc952530ec4b7a4a8f4
72,858
import statistics def extract_chords_for_melodies(quantized_sequence, melodies): """Extracts a chord progression from the quantized NoteSequence for melodies. This function will extract the underlying chord progression (encoded as text annotations) from `quantized_sequence` for each monophonic melody in `mel...
40beafe48c224651d18ba8700b1bae526400f5d6
72,860
def readSSHORT(stream): """ Read short signed integer :type stream: FileIO or ByteIO :param stream: Where to read from :return: result :rtype: int """ return _read_struct(stream, S_SSHORT)[0]
94bce8ee3cbd8d488b8d3e994959894559c4f6e8
72,862
def send_to_left_side(targets, values): """Send the given target values to the left of all other values. Example: targets = ["b", "x","c"] values = ["a", "b", "c", "x", "y", "z"] send_to_left_side(targets, values) # -> ["b", "x", "c", "a", "y", "z"] Args: targets: Values to send t...
c19f5476e1c0294595aafb7647c418b0e63f8f0e
72,863
def padding(sound_stft): """Apply reflection padding to ensure that number of time frames of `sound`'s STFT representation is multiple of 64. Args: sound_stft (torch.Tensor): Spectrogram to be padded. Returns: Tuple[torch.Tensor, Tuple[int, int]]: Reflection padded spectrogram and ...
ff7134764ded3b83f7ecd93c0077fe243b4e171b
72,864
import random def generate_id(): """Generates a new unique id for new user""" id_s = connect_to_sql("select unique_id from user_data") while True: new_id = random.randint(100000, 999999) if new_id not in id_s: return new_id
10adcbf2f16ed58baf2de493d4e040f6fb8e06eb
72,865