content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import pkg_resources def get_electricity_generation_data(): """Read in electricity generation and fuel use by individual power plants in the US for 2015. :return: dataframe of electricity generation and fuel use values """ data = pkg_resources.resource_filename('interflow', "i...
423b250e84518f3cc33914ab3bdc56e55910c68d
3,618,600
def is_whitelist_violation(rules, policy): """Checks if the policy is not a subset of those allowed by the rules. Args: rules (list): A list of FirewallRule that the policy must be a subset of. policy (FirweallRule): A FirewallRule. Returns: bool: If the policy is a subset of one of the ...
00320174323d0827a201944a11a24be0bf0ce204
3,618,601
def main(args): """Start the upload command and return exit status code.""" return upload_command(args.directory, args.site, args.user, args.token)
aac3d8bfa44c17f6f3c6fecc1c34674f1f409c0f
3,618,602
def get_k_mesh_by_cell(cell, kspace_per_in_ang=0.10): """ Args: cell: kspace_per_in_ang: Returns: """ latlens = [np.linalg.norm(lat) for lat in cell] kmesh = np.ceil(np.array([2 * np.pi / ll for ll in latlens]) / kspace_per_in_ang) kmesh[kmesh < 1] = 1 return kmesh
e25d67116e45ea747cffe62cc2b8060f5c0cdbba
3,618,603
def _required_params(param_list): """ return params without a default""" # params with defaults come last for i, p in enumerate(param_list): if p.default is not Parameter.empty: return param_list[:i] # no defaults return param_list
0002dec0d0156713ef4b127ea7f9cdf6682563cf
3,618,604
from sys import path def write_out_email_attachments(message) -> list: """ Write out email attachments from the passed message and return the list of written files :param message: Message associated with email request :return: list of paths to attachment files """ email = message.data["email"]...
de618b0384ecba182087669d4d32663a483e8859
3,618,605
def valid_token(response): """ Checks if token is valid. """ if ('detail' in response): if (response['detail'] == 'Invalid token'): echo("The authentication token you are using isn't valid. Please try again.") return False if (response['detail'] == 'Token has exp...
e44598c21f9a3a66681bd32f24fe32424f2e25c2
3,618,606
def register(name, func, weight=0): """ Register a function to a hook. The function will be called, in order of weight, when the hook is run. :param name: The name of the hook to register too. I.e. ``pre_setup``, ``post_run``, etc. :param func: The function to register to the hook. Th...
54f22a4259de0914a1423fdc2da37a8b9196c93b
3,618,607
from cuml.utils.import_utils import has_treelite, has_xgboost import treelite import treelite.runtime import xgboost as xgb def _build_treelite_classifier(m, data, arg={}, tmpdir=None): """Setup function for treelite classification benchmarking""" if has_treelite(): else: raise ImportError("No tre...
db7fcb17be72034c5ef12e994e5bfa875fbea7af
3,618,608
from typing import Dict def name2fips(loc: Dict[str, str]) -> Dict[str, str]: """name2fips converts a dictionary with keys corresponding to geography types ("state", "msa", "county", "city"). Values are english names of locations. Note that the state must be included in each geography. It's annoying, but ...
bac02e6b8a13e03648f07db9f05ef177a2bc5cc6
3,618,609
import os def recon_brainstem_plus_cerebellum_surface(name, mask=None, regions=None, region_id_array=_region_id_array, cortex_mask_array=_cortex_mask_array, temp=None): """Reconstruc...
a03795089d658a7875c24b6373c835e12f30dbe4
3,618,610
def filter_local_hams(new_hams: pd.DataFrame) -> pd.DataFrame: """ Return the subset of hams that are within 30km of Seattle downtown. Parameters ---------- new_hams : pd.DataFrame A dataframe containing new ham callsigns and email addresses. Returns ------- pd.DataFrame ...
d97e2a6f837d2512c6b999a7f0547860594cef69
3,618,611
import argparse def main_api(config: argparse.Namespace) -> str: """ Main API entrypoint. """ executor = Executor(config) try: return executor.execute() except ExecutorError as e: raise CLIError(e)
e03ed07fa9ef6b5d5dbb5e8fa0f1047e73276756
3,618,612
def cria_peca(peca): """ cria_peca: str -> peca Recebe um identificador de jogador (ou peca livre) e devolve um dicionario que corresponde ah representacao interna da peca. R[peca] -> {'peca': peca} """ if type(peca) != str or len(peca) != 1 or peca not in 'XO ': raise ValueError('cr...
6a74212f49695addab80c68f41a1e7e7d45e1ed6
3,618,613
import shlex import os def _compile_shline(shline, argv): """Return a callable to interpret argv""" # Fail fast if no input line parsed if argv is None: how = _compile_return_error() # hope crash in _parse_shline printed a message return how # Plan to call a built-in verb ve...
231ff73afe3f1520f736d46177b79f533a99e7db
3,618,614
def get_multiple_sources(filenames, **kwargs): """ Load multiple sources at once using multprocessing Parameters: filenames=filenames kwargs: keyword arguemnts """ source_type=kwargs.get('source_type', 'source') if source_type=='spectrum': method=partial(getter_function...
f50633ed8cf79ef51636237ff31a0927852fdc4e
3,618,615
def bin_data(array, binning, debugging=False): """ Rebin a 1D, 2D or 3D array. If its dimensions are not a multiple of binning, the array will be cropped. Adapted from PyNX. :param array: the array to resize :param binning: the rebin factor - pixels will be summed by groups of binning (x ...
b159aaf4b9b9d189b08b097bc11ba679b0be16a6
3,618,616
def basic(s, coeffs): """Performs the "standard" de Casteljau algorithm.""" r = 1 - s degree = len(coeffs) - 1 pk = list(coeffs) for k in range(degree): new_pk = [] for j in range(degree - k): new_pk.append(r * pk[j] + s * pk[j + 1]) # Update the "current" values...
cd12b21a0b35752b67f26eba10ee54650d45c49d
3,618,617
from typing import List def min_max_normalize(mri_imgs: List[np.memmap]): """ Function which normalize the mri images with the min max method Parameters ---------- mri_imgs: list of images Returns ------- list of normalized images """ for i in range(len(mri_imgs)): ...
9c280a84ba3e3092b9b3858fb51fb7a62dd62ffd
3,618,618
import logging import math def check_lorentz_process(process, evaluator,options=None): """Check gauge invariance for the process, unless it is already done.""" amp_results = [] model = process.get('model') for i, leg in enumerate(process.get('legs')): leg.set('number', i+1) logger.info(...
68064d91db23376b7ba7353077a90f7d9448706f
3,618,619
def create_credential(account, user_name, account_password): """ Function to create new credential """ new_credential = Credentials(account, user_name, account_password) return new_credential
55972d09ecb2b8460241497e3688ff9af96bde58
3,618,620
import logging import numpy def form_stars_from_group_older_version( group_index, sink_particles, newly_removed_gas, lower_mass_limit=settings.stars_lower_mass_limit, upper_mass_limit=settings.stars_upper_mass_limit, local_sound_speed=0.2 | units.kms, minimum_sink_mass=0.01 | units.MSun, ...
035042e822a312bcce137d52227fe6d1a87cd696
3,618,621
def format_sentence_about_nodes(sentence, nodes): """ example 1: input: sentence = '%s seems(seem) dead.', nodes = ['rpi0'] output: 'Node rpi0 seems dead.' example 2: input: sentence = '%s seems(seem) dead.', nodes = ['rpi0', 'rpi1', 'rpi2'] output: 'Nodes rpi0, rpi1 and rpi2...
7dbf470f807a09111ddec65c14d089255773d78e
3,618,622
from ray.autoscaler._private.util import fillout_defaults from typing import Dict from typing import Any def fillout_defaults(config: Dict[str, Any]) -> Dict[str, Any]: """Fillout default values for a cluster_config based on the provider.""" return fillout_defaults(config)
a7ccaa357742bf02e8c2fcad6a24945b33b5a39e
3,618,623
def get_system(context, system_id=None): """ Finds a system matching the given identifier and returns its resource Args: context: The Redfish client object with an open session system_id: The system to locate; if None, perform on the only system Returns: The system resource ...
4a4b5634016a98019ec03ea226cbe6fd000366b5
3,618,624
def has_group(user, group_name): """Tests if a user belongs to a given group. Source: https://www.abidibo.net/blog/2014/05/22/check-if-user-belongs-group-django-templates/#sthash.vGVYYdzi.dpuf """ group = Group.objects.get(name=group_name) return True if group in user.groups.all() else Fals...
94d3b3a599a7546d4cc679f1fcbfb6578f835123
3,618,625
def create_matrix(dataset, column_names=None, column_roles=None, receiver=None): """Returns a new Matrix object from the provided dataset. Parameters: $dataset_parameters $receiver_parameter """ if receiver is None: receiver = Receiver() matrix = _create_matrix(dataset, co...
b38a3f217ee431372630f22124fba030adda2886
3,618,626
def function_call(f, *args, **kwargs): """Execute the function `f` with given arguments. Intended to be used in conjunction with :func:`call`. Arguments of type :class:`ObjectId` are transparently mapped to the object they refer to. """ return f(*((get_object(arg) if type(arg) is ObjectId else ...
40d5a4643c44ce7f54d6c9425e9aa0f3dbff469e
3,618,627
def new_flow_logs(ec2, vpc_id, log_group_name, role_arn): """ Enable VPC Flow Logs """ try: flow_logs = ec2.create_flow_logs( ResourceIds = [vpc_id], ResourceType = 'VPC', TrafficType = 'ALL', LogGroupName = log_group_name, DeliverLogsPermissionArn = role_arn ) except Cl...
7c088a3ebf343a8a1ff5df0d0489367de7604946
3,618,628
def prime_vars(vrs): """Return `list` of primed variables from `vrs`.""" return [prime(var) for var in vrs]
7d8fd77fa5331f7ec432bc35d632dde1a38d9267
3,618,629
def is_teacher_or_staff(original_function=None): """ Security decorator to detect if the user is teacher or part of the staff team. :returns: Boolean pair .. versionadded:: 0.1 """ def decorated(request, course_slug=None, *args, **kwargs): course = get_object_or_404(Course, slug=...
809334a2a6eace208f138a105505eb0384878687
3,618,630
def ring_substituents(gra): """ Determine substituent groups on a ring to produce a graph of graphs where the top level key of a ring_gra is the order of the atm keys that define the ring aka (a1, a2, a3, a4, a5, a6) a1 is the 0th position of the ring so a3-a5 have a 1-3 in...
6865482c12b1486c9f7fcabdcaefc0ef70f5e988
3,618,631
def matchnocase(word, vocab): """ Match a word to a vocabulary while ignoring case :param word: Word to try to match :param vocab: Valid vocabulary :return: >>> matchnocase('mary', {'Alice', 'Bob', 'Mary'}) 'Mary' """ lword = word.lower() listvocab = list(vocab) # this trick catc...
ba0354d7669d08fbdedc926c11f446c26f401e89
3,618,632
def table_start_fn(ctx, token): """Handler for table start token "{|".""" if ctx.pre_parse: return text_fn(ctx, token) close_begline_lists(ctx) _parser_push(ctx, NodeKind.TABLE)
b3eb77ac5a1b90c3c8c1ab97f3d9341fdf921f77
3,618,633
from typing import cast def theory_atom(s: str, mode: int=0) -> AST: """ Convert string to theory term. """ if mode==2: v = Extractor(parse=True) else: v = Extractor() def visit(stm): v(stm) if mode==0 or mode==2: clingo.ast.parse_string(f"{s}.", visit) ...
a079acce8cca2fad3589640d5b248246d87eab59
3,618,634
import torch def train_non_parametric_filter(nb_epochs, train_input, train_target, e, edge, f, gamma=1e-6, alter_thresh = False): """ Training process to learn a non parametric filter. Attributes: - nb_epochs : Number of epochs to train - train_input : Initial filtered...
2ec1dd4a99d8d32b5dace4fe1e789308955b5ea4
3,618,635
def read_cobs(years=('2020'), comet=None, start=None, stop=None, allowed_methods=('S', 'B', 'M', 'I', 'E', 'Z', 'V', 'O'),): """Returns a `CometObservations` instance containing the COBS database.""" if years == 'all': years = tuple(range(2018, 2020)) # Read the data data = [] ...
6c69c556ce71eff99dbd2c774b2b17ff8344f5ad
3,618,636
from typing import Optional import typing def Position( line: _PrimitiveLineCharNumber, character: Optional[_CharNumberOrMarker] = None, *, _default_character: _CharNumberOrMarker = CharNumber(0), ) -> typing.Position: """ Returns a [Position](https://microsoft.github.io/language-server-protoc...
944094fe2ebe63c70675f064ebae3ca43fcca65b
3,618,637
from datetime import datetime def get_first_timestamp(log_file, search_text): """Get the first timestamp of `search_text' in the log_file Args: log_file search_text (str) Returns: timestamp: datetime object """ timestamp = None with open(log_file, "r") as f: c...
fbf5f00ea0810788019ec081a67664393763a95c
3,618,638
def velocity_r(trk, t_vel, r, on=True): """Randomly change the velocity of a note in a track""" time = 0 j = 0 c_t_vel = t_vel[j][0] if on: msg_t = "note_on" else: msg_t = "note_off" for msg in trk: if msg.type == msg_t: r_mod = c_t_vel*r msg.v...
0a8454443b3c3accf6c1f873bc574b2bd5763c69
3,618,639
from typing import List import os def samples2metadata_local(samples: List[str], config: dict) -> dict: """ """ sampledict = dict() for sample in samples: if os.path.exists(expand(f'{{fastq_dir}}/{sample}.{{fqsuffix}}.gz', **config)[0]): sampledict[sample] = dict() sam...
60a86577aeb36bc001ed0aa29f7fb86c64c06c6d
3,618,640
def beinflumatred(infl_mat): """ Calculate a reduced influence coefficient matrix from a complete influence coefficient matrix. Parameters ---------- infl_mat: ndarray The complete influence coefficient matrix. Returns ------- reduced_infl_mat: ndarray The reduced ...
6f51964f1339f4196fcab252f844b6627b6bae57
3,618,641
def get_fetaure_names(df, feature_name_substring) : """ Returns the list of features with name matching 'feature_name_substring' """ return [col_name for col_name in df.columns if col_name.find(feature_name_substring) != -1]
14103620e89b282da026fd9f30c7491b63820c09
3,618,642
import glob def load_data_from_experiment_root_dir(path, str_filter='/*/*/*/*/args.json', original_args=False, target_fn=None, use_hash=False, sort_best_model_fn=None): """Entry point of almost all experiments reader Here we load the full statistics of a given experiment. Parameters --...
e310ac3f805aa19f4dee1a5148f75e5536c05106
3,618,643
def gaussian_1st_deriv(sigma, t, amplitude=1, plot=False): """ Basic gaussian pulse with units in time std_time is the standard deviation of the pulse with units of t Example ------- Example 1:: dt=1e-9 t=np.arange(0,0.001+dt/2,dt) t-=t.mean() std_time=1e-4 s=gaussian_1st_deriv(sigma = std_time, ...
96e8d15a49d9fb53943461222956d37e0259166a
3,618,644
import numbers def ISNUMBER(value): """ Checks whether a value is a number. >>> ISNUMBER(17) True >>> ISNUMBER(-123.123423) True >>> ISNUMBER(False) True >>> ISNUMBER(float('nan')) True >>> ISNUMBER(float('inf')) True >>> ISNUMBER('17') False >>> ISNUMBER(None) False >>> ISNUMBER(da...
422c5bcd24a21a50bfefb1a00193387e725d435b
3,618,645
def pearson_transform( matrix: ExpMatrix, min_exp_thresh: float = 0.001) -> ExpMatrix: """Uses pearson residuals to stabilize variance.""" invalid_errstate = 'warn' if np.issubdtype(matrix.values.dtype, np.float32): if np.amin(matrix.values) >= 0: invalid_errstate = 'ignore' ...
f47be6134ba878f88d9e60ff171c4359c909f4cf
3,618,646
def get_domains_for_ip(ip): """ Get the list of domains associated with an IP address. :param ip: :return: """ return __scraper.run(ip)
fedb8ed93297ada60766a85c248f282dc05bea1c
3,618,647
def sharesnet18(**kwargs): """ ShaResNet-18 model from 'ShaResNet: reducing residual network parameter number by sharing weights,' https://arxiv.org/abs/1702.08782. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, ...
31dcdfd003b0a37da05cdd8d95fcc64abca7c6c3
3,618,648
def dgraph2adjacency(dgraph: nx.DiGraph) -> np.ndarray: """Gets the dense adjancency matrix from the graph. Args: dgraph: Directed graph to compute its adjancency matrix. Returns: Adjacency matrix of the given dgraph in dense format (np.array(n * n)). Raises: None. """ ...
dcb0bc5ca558fbc2356cc58bde9346848105b07b
3,618,649
import random def format_meters(cm): """Returns an example user-input meters string.""" if cm < 100: return format_cm(100) m = cm // 100 cm_part = format_cm(cm % 100) suffixes = ["meters", "metres", "m", "ms"] suffix = random.choice(suffixes) spacing_1 = random.randrange(3)*" " spacing_2 = random...
4521302811011d0dacb82ab969884ff7c15d13e9
3,618,650
def convert_atts_to_list_of_quats(atts): """Convert ``atts`` to a flat list of Quat objects Parameters ---------- atts : Quat, list Attitudes Returns ------- list Flat list of Quat objects """ if isinstance(atts, Quat): out = [Quat(q) for q in atts.q.reshape...
1b2f94b3e7bb167c4bf5d3319ff6d18387ee5f82
3,618,651
import torch import logging def process_evaluation_epoch(global_vars: dict, eval_metric=None, tag=None): """ Calculates the aggregated loss and WER across the entire evaluation dataset """ eloss = torch.mean(torch.stack(global_vars['EvalLoss'])).item() hypotheses = global_vars['predictions'] r...
1d53c7977d71ed8a18a4811fd41fd511e974a37e
3,618,652
async def list_pop_communities(context, limit:int=25): """List communities by new subscriber count. Returns lite community list.""" limit = valid_limit(limit, 25, 25) sql = "SELECT * FROM bridge_list_pop_communities( (:limit)::INT )" out = await context['db'].query_all(sql, limit=limit) return [(r[...
9774e3fb34e1403e2ae20ffa128edaf77dd328a3
3,618,653
def api_methods(): """ API symbols that should be available to users upon module import. """ return { 'point', 'scalar', 'scl', 'rnd', 'inv', 'smu', 'pnt', 'bas', 'mul', 'add', 'sub' }
a5f23b48509adb966e10e3309ace93c31651ebd3
3,618,654
import logging import numpy from operator import or_ import math def geo_rescore(pid, model, method): """Apply geographic rescoring.""" logging.info(str((pid, model, method))) session = SESSION() try: numpy.seterr(all='raise') session.query(Model) \ .filter_by(filename=mo...
e2623a58a34efff85594585f2b60571b49ab0805
3,618,655
def is_prime(n): """Determine if input number is prime number Args: n(int): input number Return: true or false(bool): """ for curr_num in range(2, n): # if input is evenly divisible by the current number if n % curr_num == 0: # print("current num:", curr_n...
518a0e78056668e9d8b0a708a05ba9bc9b9cf3d2
3,618,656
import os import subprocess import time import signal def create_agent_runner_fixture(agent_path, agent_name, args=None): """Create a pytest fixture for running a given OCS Agent. Parameters: agent_path (str): Relative path to Agent, i.e. '../agents/fake_data/fake_data_agent.py' a...
bed3fe53b80e5a4d60af49dfe0ee967b7fcd1a03
3,618,657
def q2m(q): """ Find the rotation matrix corresponding to a specified unit quaternion. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/q2m_c.html :param q: A unit quaternion. :type q: 4-Element Array of floats :return: A rotation matrix corresponding to q :rtype: 3x3-Element Array ...
62641e9bfbb63cbef09c8090f6aae18ddacab895
3,618,658
def eval_multiple(exprs,**kwargs): """Given a list of expressions, and keyword arguments that set variable values, returns a list of the evaluations of the expressions. This can leverage common subexpressions in exprs to speed up running times compared to multiple eval() calls. """ for e in exp...
2bc90dacb972d3315168638a4ea99f9cfbb13830
3,618,659
import matplotlib.pyplot as plt def test_trending(): """ Quick trending test for claims with different support patterns. Actually use the run() function. """ # Create a fake "claims.db" for testing # pylint: disable=I1101 dbc = apsw.Connection(":memory:") db = dbc.cursor() # Crea...
dab297f75030710cdf5bb22db4885f2a1754c5ea
3,618,660
def create_user(**params): # **: dynamic list of arguments. # we can basically add as many arguments as we want """Helper function to create new user that you're testing with""" return get_user_model().objects.create_user(**params)
9527812043af8e338985230d88113eefb63d1f38
3,618,661
import time def inner_loop_function(model, config): """ Execute single cross-validation trial """ test_set, ds = config tic = time.time() df = execute_gluonts_dataframe(model, ds, test_set ) res = execute_gluonts_json(df) toc = time.time() res['time'] = toc-tic return df, res
ec3c541202a5e114cf2abc51f9ba196ea97305b9
3,618,662
from datetime import datetime def findSEH(modulecriteria={},criteria={}): """ Performs a search for pointers to gain code execution in a SEH overwrite exploit Arguments: modulecriteria - dictionary with criteria modules need to comply with. Default settings are : ignore aslr, rebase and safeseh...
f32975e4382f03fb440d31abac9fde64fd6efefe
3,618,663
from typing import Tuple from typing import Dict from typing import Any def _to_instruction(idl_ix: _IdlInstruction, args: Tuple) -> Instruction: """Convert an IDL instruction and arguments to an Instruction object. Args: idl_ix: The IDL instruction object. args: The instruction arguments. ...
728a2aefe1c4e0af9ab1e165c69cff4958dca333
3,618,664
def sample_coordinates(mask, num_train_vols, num_val_vols, vol_dims=(96, 96, 96)): """ Sample random coordinates for train and validation volumes. The train and validation volumes will not overlap. The volumes are only sampled from foreground regions in the mask. Parameters ---------- mask...
99896662638a6589a7ba70bbefce29433d5e714f
3,618,665
import torch def get_deformation( screw_axis, # Rotation params. with_rotation = True, fix_axis_vertical = False, # Scaling params. with_isotropic_scaling = False, min_scale = 0.5, max_scale = 1.5, ): """Get screw axis encoding of per-point rigid transformation. Args: screw_ax...
09a16b5100d97cd24097a5160fb1608c557baf54
3,618,666
import yaml from pathlib import Path def load_component_entity_from_yaml( path: str, mock_machinelearning_client: MLClient, context={}, is_anonymous=False, fields_to_override=None, ) -> ParallelComponent: """Component yaml -> component entity -> rest component object -> component entity""" ...
c2539ab48671876df97472f9ffe953f042cd07f0
3,618,667
from operator import concat def nash_do_transfer_from(ctx, Caller, args): """Transfers the approved token at the specified id from the t_from address to the t_to address Only a whitelisted DEX can invoke this function :param StorageContext ctx: current store context :param list args: 0: ...
edc1f4768f8b90b00c3a267b75bfc5490a6e9be4
3,618,668
from nipype import Workflow, Node, Function from dipy.io.image import load_nifti from dipy.io.image import load_nifti_data from dipy.io.gradients import read_bvals_bvecs import numpy as np from dipy.core.gradients import gradient_table import numpy as np import dipy.reconst.dki as dki from dipy.io.image import save_nif...
282d6e1568dd17688f3c2cfa3cc618bdee210c26
3,618,669
import re def convert_numbers(data): """ Function to replace numerical numbers with their text counterparts. :param data: The text data to be searched. :return: The text data with numerical numbers replaced with textual representation. """ inf = inflect.engine() for word in data: ...
003d74415677631a1a78e45a1f57fd2d0aa1884d
3,618,670
def linear_discriminant_analysis(df): """ Determine weights for Fischer linear discriminant analysis of df. @param df pandas dataframe with output in column 'state' states must be 1 or -1; @return list of weights and weight threshold. """ # separate df in states group_by = df....
92fd43ba3771603d57a28e3f52f0e55b0d611ba9
3,618,671
from typing import List def update_sample_group_attachments(user: User, sample_group: SampleGroup, samples: List[Sample]) -> SampleGroup: """ Make the only samples attached to a group those in sample_ids :param user: :param sample_group: :param samples: :return: """ if is_write_permitt...
fe94c1a6552578c8e2f3c432a2c0750f189c3b96
3,618,672
def check_for_tokens(): """ Checks if the required API keys for Spotify has been set. :param name: Name to be cleaned up :return string containing the cleaned name """ log.debug('Checking for tokens') CLIENT_ID = getenv('SPOTIPY_CLIENT_ID') CLIENT_SECRET = getenv('SPOTIPY_CLIENT_SECRET')...
b8e2440bbff9fbff6150e69203332bf02f1e311b
3,618,673
def make_reference(mol): """ Takes an molecule graph (e.g. as read from a PDB file), and finds and returns the graph how it should look like, including all matching nodes between the input graph and the references. Requires residuenames to be correct. Notes ----- The match between h...
7472d527f3a4dd67975417f47dbe9c1ef4251e5b
3,618,674
import requests def get(url, params, proxies, headers): """Send a request with the GET method.""" response = requests.get(url, params=params, proxies=proxies, headers=headers) return response
a481a91e5f3fc71f88de8d84efaac3dd666c302e
3,618,675
from typing import Union from typing import List def _parse_input(ip: Union[List, str], network: str = '255.255.255.255', workers: int = default_processes): """ convert the ip, network into a structure containing address/masks """ # if this is list split it into worker tasks if isinstance(ip, list): ...
a53eafeeb63a0bfdfc08dc4a51a8276f68faf9cc
3,618,676
from typing import Union from typing import Any async def send( bot: "Bot", event: Event, message: Union[str, Message, MessageSegment], at_sender: bool = False, reply_message: bool = False, **params: Any, ) -> Any: """้ป˜่ฎคๅ›žๅคๆถˆๆฏๅค„็†ๅ‡ฝๆ•ฐใ€‚""" event_dict = event.dict() params.setdefault("det...
0eb27892ee3e0c712e881b4afba7a3ebb45ad72c
3,618,677
def remove_duplicate_vertices_cmd(): """ Remove duplicate vertices a CityJSON file. Only the geometry vertices are processed, and not those of the textures/templates. """ def processor(cm): print_cmd_status('Remove duplicate vertices') cm.remove_duplicate_vertices() retur...
193efbabe27b571b31207e0693a373cca0f77960
3,618,678
def account_ids_equal(account_id_a, account_id_b): """ Compare two account IDs while discarding the account prefix :return: Whether the account IDs are equal :rtype: bool """ return account_id_a[-60:-8] == account_id_b[-60:-8]
4f26d7db93fa06ce834487d1e6876c8fe8602b18
3,618,679
from os.path import isfile def add_group_predictors(dataset_id, participants): """ Adds group predictors using participants.tsv Args: participants - path to participants tsv dataset_id - Dataset model id subjects - subject ids to processed Output: Ids of group predictors ad...
5668cd0001350a7e52e81ea190baeaf523371683
3,618,680
def action_from_trinary_to_env(action) -> int: """ Maps trinary model output to int action understandable by env """ assert action in (0, 1, 2), f'Wrong action: {action}' return { 0: 0, 1: 2, 2: 5 }[action]
e2a7cd3d6c018a7112e2304f2910781b665a8247
3,618,681
def hex_value(image): """ Get the dice value of a hex. :param image: The game image. :return: An int of the hex value or None if a invalid value is found. """ grey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) _, thresh = cv2.threshold(grey, 200, 255, cv2.THRESH_BINARY_INV) value_contour = f...
f45555a0909d4fb091b34e159cb46e8d704fe816
3,618,682
def get(filename, target=None, serial=None): """ Gets a referenced file on the device's file system and copies it to the target (or current working directory if unspecified). If no serial object is supplied, microfs will attempt to detect the connection itself. Returns True for success or rais...
4d40628bd64247209e6a0de76440bb56ce3586e4
3,618,683
def get_market_name(market: str = None) -> str: """ ์ž…๋ ฅ๋œ ๊ฐ’์— ๋Œ€ํ•œ ๋งˆ์ผ“์˜ ์ข…๋ฅ˜๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜ Parameters ---------- market: str ๋งˆ์ผ“์— ๋Œ€ํ•œ ์•ฝ์–ด ํ˜น์€ ๋งˆ์ผ“์˜ ํ’€๋„ค์ž„ Returns ------- str ์ž…๋ ฅ๋œ ๊ฐ’์— ๋Œ€ํ•œ ๋งˆ์ผ“ ํƒ€์ž… Raises ------ ValueError ์ž…๋ ฅ๋œ ๊ฐ’์— ๋Œ€ํ•œ ๋งˆ์ผ“์˜ ํƒ€์ž…์„ ์•Œ ์ˆ˜ ์—†์„๋•Œ """ if market: ...
c7c60dce972be5aa07dfc19046b769d64524fe8d
3,618,684
def _get_registered_typelibs(match='HEC River Analysis System'): """ adapted from pywin32 # Copyright (c) 1996-2008, Greg Stein and Mark Hammond. """ # Explicit lookup in the registry. result = [] key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib") try: num = 0 ...
d4c809c95f4e4b6ace59bda6cb4199cd8d7170fd
3,618,685
def contact(): """ Function is invoked when requests is made to url: dommainname/contact :return: a rendered template for the about page """ # Accesses the contact form and renders it in the contact html file # Submits the filled form and sends the values in a mail to a configured e...
1a74ae188f1131d16e53414b5a03c09ba3cc63d1
3,618,686
import re def convert_rst_formatting(text): """ Convert rst syntax for formatting to markdown in a given text. """ # Remove :class:, :func: and :meth: markers. To code-links and put double backquotes # (to not be caught by the italic conversion). text = _re_func_class.sub(r"[``\1``]", text) ...
c2d5fce2a8cc1b3efc764af917b8c6a69b6097dc
3,618,687
def get_setup_file(): """Serve the SSDP setup file.""" out = "<?xml version=\"1.0\"?>\n" + \ "<root xmlns=\"urn:schemas-upnp-org:device-1-0\">\n" + \ "<specVersion>\n" + \ "<major>1</major>\n" + \ "<minor>0</minor>\n" + \ "</specVersion>\n" + \ "<URLB...
961924ce9ebb77b92fb31e587f80aca31cc30c11
3,618,688
def ofxPluginPath(): """ nuke.ofxPluginPath() -> String list List of all the directories Nuke searched for OFX plugins in. @return: String list """ return list()
9a8b7b3f69047818e7a3a31e0ff8bca50e57ed4c
3,618,689
def index_sentence_with_vocabulary(sentence, word2id, sequence_length=None, knowledge_path=None): """index sentence with vocabulary, return list of index""" # print("index_sentence_with_vocabulary:",knowledge_path) result_list = tokenize_sentence(sentence, knowledge_path=knowledge_path) result_list = re...
6d5535e85861b8ca869b17c8d1b0f54bd600e71a
3,618,690
import logging def set_android_token(request): """ Android's push notification tokens. Not sure why I can't find this function in the Android code. """ user = get_user(request) tokens = MUserNotificationTokens.get_tokens_for_user(user.pk) token = request.POST['token'] logging.use...
bcde1c1a25d9e37c84c254bdd225616fb223f237
3,618,691
import hashlib def file_md5(file_path: str) -> str: """Compute the md5 hex digest of a binary file with reasonable memory usage.""" md5_hash = hashlib.md5() with open(file_path, 'rb') as f: while True: data = f.read(65536) if not data: break md5_...
ac0576e901ca3205f824a599566e628ee29f5a7c
3,618,692
def get_parameters(model, unique_variance=False): """ Returns the true parameters of a given model. :param model: Model ID. :param unique_variance: indicates whether the variance should be unique :return: Mixture weights, means and covariances. """ if model == Model.M1: return get_p...
96e7fc6f82e673f62690409e9a4bf19354d13e83
3,618,693
import json import time def collection(request, *args, **kwargs): """ REST main collection request handler. **Supported HTTP methods:** * GET * DELETE * PUT * POST :param request: Request object :param args: arguments :param kwargs: Dictionary (keyword arguments). Known kwar...
de46656e8a67272225f902179f4b01d4cd3e982c
3,618,694
from .centrography import mean_center import numpy def _(shape: numpy.ndarray): """ Handle point arrays or bounding boxes """ if shape.ndim == 2: return mean_center(shape).squeeze() elif shape.ndim == 1: assert shape.shape == (4,) xmin, ymin, xmax, ymax = shape ret...
af866f85419d9a0d0cb9857f2cf4e7047afb38cb
3,618,695
import math def mkt(vdf, column: str, ts: str, p=1000, alpha: float = 0.05): """ --------------------------------------------------------------------------- Mann Kendall test (Time Series trend). \u26A0 Warning : This Test is computationally expensive. It is using a CROSS JOIN during the comput...
f78c3acb1eba4a854b7542e01bc3b7704a96140d
3,618,696
import os from re import DEBUG def getprofileimgtag(request): """ Function to form the img tag for profile image based on whether the user has a profile image or not. """ db = get_mongo_client() if request.COOKIES.has_key('sessioncode'): sesscode = request.COOKIES['sessioncode'] el...
4a84fba78aedbb789ca4744b14196e820472199c
3,618,697
def where2d(image): """ numpy.where for 2D matrices. :param image: Input images :return: Coordinate list where image is non-zero >>> where2d(np.array([[ 0, 0, 0], ... [ 0, 1, 1], ... [ 0, 0, 0]])) array([[1, 1], [1, 2]]) """ ...
be6041c0f4e7bd1ff6d96b1828a4d0982fc8458c
3,618,698
def continue_prompt(message=''): """Continue prompt to verify that a user wants to continue or not. This prompt's purpose is to prevent accidental changes that are difficult to reverse. Keyword Args: message (str): The message to display to the user Returns: bool: If the user want...
1c8ec8a222976ebf8d02f5690b52da75c2b20f81
3,618,699