content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import requests
def create_oauth_client():
"""
Create a new OAuth client in fidesops.
Returns the response JSON if successful, or throws an error otherwise.
See http://localhost:8000/docs#/OAuth/acquire_access_token_api_v1_oauth_token_post
See http://localhost:8000/docs#/OAuth/acquire_access_token... | 30aa8cbadb7f852184d507af1bf35510cb5e8bef | 3,602,081 |
def _get_named_patterns():
"""Returns list of (pattern-name, pattern) tuples"""
resolver = urlresolvers.get_resolver(None)
patterns = sorted([(key, value[0][0][0])
for key, value in resolver.reverse_dict.items()
if isinstance(key, string_types)
... | 26ffa4485bc5c2c7525f110c3c817b97167c419e | 3,602,082 |
def get_embeddings(sess, GNN, batch, time_steps):
"""
Givan an input batch, return a list of lists of n-dimensional vertex
embeddings produced by the GNN in 'time_steps' timesteps
"""
# Build the feed_dict
feed_dict = {}
feed_dict[ GNN["gnn"].matrix_placeholders["M"] ] = sparse_to_d... | 78dd209e5ad0c244834cfbef57933118e5fbee8c | 3,602,083 |
def name(func):
"""Decorator for name conversion.
Decorated function takes two arguments 'root' and 'filename' and returns
new filename.
Args:
func name conversion.
"""
_Funcs.instance().add_name(func)
return func | 6257562ed828cd1f2e1d38742ff005ad1ecb8f77 | 3,602,084 |
def np_to_tfrecords(X, Y, file_path_prefix, verbose=True):
"""
Converts a Numpy array (or two Numpy arrays) into a tfrecord file.
For supervised learning, feed training inputs to X and training labels to Y.
For unsupervised learning, only feed training inputs to X, and feed None to Y.
The length of ... | d8f1cf8e64904ffbf90fab8af659d47f7b787635 | 3,602,085 |
def get_pi_noise_clipped(pi, noise_scale=0.1, noise_clip=0.5, act_limit=10.):
""" Add clipped noise to sampled target action, and then clip to stay
within the valid value of the action """
clipped_noise = get_clipped_noise(
tf.shape(pi), noise_scale=noise_scale, noise_clip=noise_clip)
pi_noise =... | a189ece154738bdc6b226a024ad955c1ef09a8e2 | 3,602,087 |
def shp(arr):
""" return dimension of an array
Parameters
----------
arr : ndarray
Returns
-------
shp : tuple
Examples
--------
>>> import pylayers.util.pyutil as pyu
>>> import numpy as np
>>> from scipy import *
>>> a = np.arange(10)
>>> pyu.shp(a)
(1,... | 39e9d344cbc62da60dd1eb28c1727ab7d01ded96 | 3,602,088 |
from typing import Union
from pathlib import Path
from typing import Iterable
from typing import Any
from typing import List
def discover_attributes(
source: Union[Path, str, Module, Iterable[Module]],
signature: type = Any, # type: ignore
include_privates: bool = False,
in_private_mo... | c064969a93895e029a2c35757a65d7eee794a444 | 3,602,090 |
import torch
import logging
def config_network(scene, task, tiny, grayscale, uncertainty, fullsize, network_in, num_enc=0):
"""
Configure evaluation network.
"""
if 'urbanscape' in scene.lower() or 'naturescape' in scene.lower():
if task == 'coord':
num_task_channel = 3
eli... | 3d4c1cdca4c97c7fc2c7a95e6b6ceabe36dba666 | 3,602,091 |
import signal
def cfg_job_class(value):
"""Return job queue class based on name
Args:
value (object): May be class or str.
Returns:
object: `Background` or `Celery` class.
"""
if isinstance(value, type) and issubclass(value, (Celery, Background)):
# Already initialized b... | 5ba5ef6379db0c873913b8e63e108bd9cf27e591 | 3,602,092 |
import json
def get_team_port(duthost, pc):
"""
Dump teamd info
Args:
duthost: DUT host object
pc: PortChannel name
"""
dut_team_cfg = duthost.shell("teamdctl {} config dump".format(pc))['stdout']
dut_team_port = json.loads(dut_team_cfg)['ports'].keys()
return dut_team_port... | f60c18d1a4f8514ec0ee042a820eaec3902bfc24 | 3,602,095 |
from typing import List
from re import A
def compose(transforms_to_compose: List[BasicTransform]) -> A.Compose:
"""
Wrapper for albumentations compose func. Takes in a list of
albumentation transforms and composes them to one transformation
pipeline
Returns:
----------
A composed pi... | ba45e24d6e56facf6fe7b8ba17c4bbd793c63595 | 3,602,096 |
def varadd(a, b, undef=-9999.):
"""
Addition:
x = varadd(a, b) means x = a + b, where a and b are ndarray or float.
Parameters
----------
a : ndarray
input variable 1
b : ndarray
input variable 2
undef : float, optional
elements are excluded from the calculat... | e972799d84fa4bc96a0e6a2fdeb2195b0894f35d | 3,602,097 |
def subnet_to_string(subnet):
"""Given Subnet instance returns a string describing it."""
# Count number of least significant zero bits in the mask.
mask = subnet.mask
i = 0
while not (mask & 1) and i < subnet.bits:
mask = mask >> 1
i += 1
base_ip = IP(subnet.bits, subnet.base)
return '%s/%d' % (i... | 8a24cdf1f8133f0265a4a4d196d1ac58696c2f53 | 3,602,098 |
def parse_leaderboard_args(args, user_timezone: timezone = None):
"""Parse the leaderboard command arguments, return a dictionary with the values parsed:
dict:{
'names': [<str>] | None,
'canvas': <Boolean>,
'lines': <int>,
'speed': <Boolean>,
'last': <str> | None,
... | d5ca4deeeab5b69bc5f7c9d6963a82285422d5cd | 3,602,099 |
def FindDistance(df1, df2):
"""
Function that finds the averaged distance between the elements of two dataframes.
:param df1: first dataframe
:param df2: second dataframe
:return: averaged distance between df1 and df2
"""
d = 0
count = 0
distances = []
for i in range(len(df1))... | 38272ad72c6ef9e28bd82319ee46f0e6b407e349 | 3,602,100 |
from pathlib import Path
def _get_city(path, root):
"""Extract the city name of standard traffic4cast like data structure path
Args:
path (str): Traffic4cast path: [root + city + city_test + filename]
root (str): Root directory
Returns:
TYPE: Description
"""
city_path = P... | 322d43c1c1f43d8d59f21a67c804fc343955816d | 3,602,101 |
import torch
def encode(matched, priors, variances):
"""Encode the variances from the priorbox layers into the ground truth boxes
we have matched (based on jaccard overlap) with the prior boxes.
Args:
matched: (tensor) Coords of ground truth for each prior in point-form
Shape: [num_pri... | 9d970e18c9daa28af8baf55b32e0254e1ad14c7a | 3,602,102 |
def reverse(graph):
"""replace all arcs (u, v) by arcs (v, u) in a graph"""
rev_graph = [[] for node in graph]
for node, _ in enumerate(graph):
for neighbor in graph[node]:
rev_graph[neighbor].append(node)
return rev_graph | 5b1b0281df529676e90ba4d27d1ab554d4a50537 | 3,602,104 |
def cartesian_to_bl(x, y, z, a, v_x, v_y, v_z):
"""
Utility function (jitted) to convert cartesian to boyer lindquist.
This function should eventually result in Coordinate Transformation Graph!
"""
w = (x ** 2 + y ** 2 + z ** 2) - (a ** 2)
r = np.sqrt(0.5 * (w + np.sqrt((w ** 2) + (4 * (a ** 2) ... | 3ac7efeae6ae9b6d86e46659dfa981f172e4b517 | 3,602,105 |
def convert_bytes_to_human_readable(B: int) -> str:
"""Return the given bytes as a human friendly KB, MB, GB, or TB string."""
B = float(B)
KB = float(1024)
MB = float(KB ** 2) # 1,048,576
GB = float(KB ** 3) # 1,073,741,824
TB = float(KB ** 4) # 1,099,511,627,776
if B < KB:
retu... | 2e2ac61390834bc41c17ca4fa85c8303df45baa8 | 3,602,106 |
def calculate_all_fuel(mass):
"""So, for each module mass, calculate its fuel and add it to the total. Then, treat the fuel amount you just calculated as the input mass and repeat the process, continuing until a fuel requirement is zero or negative.
>>> calculate_all_fuel(14)
2
>>> calculate_all_fuel(1... | a3ef42a85fd76788b119552cc51ca2054f56602c | 3,602,107 |
import requests
def put_call(url, params=None, json=None, headers=None):
"""
Call api with PUT method
:param url:
:param params:
:param json:
:param headers:
:return:
"""
if params is None:
params = {}
if json is None:
json = {}
response = requests.put(url... | 58ed09d3ab33bb7bc8a34093c8339f1e84d95134 | 3,602,108 |
def conjugado (num):
"""Funcion que retorna el conjugado de un numero imaginario
(list 1D) -> list 1D"""
num1 = num[1] * -1
return (num[0], num1) | af1dfc52b5a8967ff7399f369c8ef7bf9dd2cc17 | 3,602,109 |
def query_project(conn, project_name, query_type, query):
"""
Submits a request for the execution of a query of either forecasts or truth
in a specified Zoltar project.
:param conn: a ZoltarConnection
:param project_name: name of the Project to query
:param query_type: a QueryType enum value ind... | 8e000e984eadc8d10ad51493905725d0bd2b6472 | 3,602,110 |
import scipy
def summarize_set(s):
"""
returns a vector of length 8
:param s:
:return:
"""
if len(s) == 1:
return [
1,
s[0],
s[0],
s[0],
s[0],
0,
0,
0,
]
stats = scipy.stats.de... | a68f09ea31228ebe9e69274281ff7455fcb50869 | 3,602,111 |
from unittest.mock import call
def _getPID():
"""Get PID from specified PIDFile.
Returns:
int: >0 -- OnRamp Server PID
-1 -- _pidfile contains invalid PID
-2 -- _pidfile not found
"""
pid = 0
try:
f = open(_pidfile, 'r')
pid = int(f.read())
... | ba3bb402bfd287d9381f91ae7c47a7fb58ae32f0 | 3,602,112 |
def radii_features(binary_mask, centroid):
"""Describing centroid to boundary distances(radii)
This function obtains radii from the centroid to all the points along the edge and
using this computes features that describe the morphology of the given object.
Args:
binary_mask:(image_matrix) ... | 91c562cd1b860291a2f83bbd2d06511f8ac26865 | 3,602,113 |
def _coo_matmat_mhlo(platform, gpu_sparse, data, row, col, B, *, shape,
transpose=False, compute_dtype=None, compute_type=None,
x_dtype, data_dtype, index_dtype):
"""COO from dense matrix."""
data_type, index_type, nnz = _validate_coo_mhlo(data, row, col, shape)
rows, col... | 5010779063d56909a2f17142eabd98a367bb71e8 | 3,602,114 |
def run_pyscf(molecule,
run_scf=True,
run_mp2=False,
run_cisd=False,
run_ccsd=False,
run_fci=False,
verbose=False):
"""
This function runs a pyscf calculation.
Args:
molecule: An instance of the MolecularData or Pys... | 53350e4523fd90165b462874ab3de5cdf594dda7 | 3,602,115 |
def _get_config_value_for_remote(ctx, remote, config, key):
"""
Look through config, and attempt to determine the "best" value to use
for a given key. For example, given::
config = {
'all':
{'branch': 'master'},
'branch': 'next'
}
_get_config_... | 30452cde0dcb1f09763a5b10550f59d649067b08 | 3,602,116 |
import urllib
def valid_fileproto(uri):
"""
Returns a boolean value based on whether or not the URI passed has a valid
remote file protocol designation
CLI Example:
.. code-block:: bash
salt '*' config.valid_fileproto salt://path/to/file
"""
return urllib.parse.urlparse(uri).sch... | d128b5f9131f54a03d1db864d8fbcdc688e03439 | 3,602,119 |
def new_game():
"""
Starts a new game, with a default player on level 1 of the dungeon.
Returns the player object.
"""
# Must initialize the log before we do anything that might emit a message.
log.init()
quest.display_welcome()
player = Object(None, '@', 'player', libtcod.white, blocks... | 9db70bad46d29a0b91848d43e092af144bcd6039 | 3,602,120 |
import random
def propose_any_node_flip(partition):
"""Flip a random node (not necessarily on the boundary) to a random part
"""
node = random.choice(tuple(partition.graph))
newpart = random.choice(tuple(partition.parts))
return partition.flip({node: newpart}) | 1ba9d747b92b707cad34c820abec9325913aca55 | 3,602,121 |
def _env_trans_from_sys_ts(g, nodevar, dvars):
"""Return safety assumption to prevent env from blocking sys."""
denv = {k: v for k, v in dvars.items() if k in g.env_vars}
env_trans = list()
for u in g:
# no successor states ?
if not g.succ.get(u):
continue
# collect p... | f13562be72181ce3381917a6622716366b3b42bf | 3,602,122 |
import scipy
import warnings
def best_fit_distribution(data, bins=200, ax=None):
"""Model data by finding best fit distribution to data"""
# Get histogram of original data
y, x = np.histogram(data, bins=bins, density=True)
x = (x + np.roll(x, -1))[:-1] / 2.0
# Distributions to check
DISTRIBUT... | 44272cd68f9794db202ee88ad96623ed802ffed6 | 3,602,125 |
import string
def extract_words(text):
"""Return the words in a tweet, not including punctuation.
>>> extract_words('anything else.....not my job')
['anything', 'else', 'not', 'my', 'job']
>>> extract_words('i love my job. #winning')
['i', 'love', 'my', 'job', 'winning']
>>> extract_words('mak... | cc0b7dbc548696ed74b48dec57b386fe38adfa41 | 3,602,126 |
import torch
def ScanpyObj_IO(obj, test_no_valid:bool = False, batchSize:int = 128, workers:int = 12, log:bool = False,
log_base:int = None, log_method: str ='scanpy', verbose = 0, ):
"""
The same function as above, except taking in an AnnData object (from Scanpy or Seurat) and not a path
... | 8b61d5dc893f31c1630e0b17af3fae23ceebc769 | 3,602,127 |
def mods_to_step_size(mods):
"""
Convert a set of modifier keys to a step size.
:param mods: Modifier keys.
:type mods: :class:`tuple`[:class:`str`]
:return: Step size, by name.
:rtype: :class:`str`
"""
if "alt" in mods:
return "fine"
elif "shift" in mods:
return "c... | 3c93fd11a8b5b0fad5cc26a35872e0616ebf7231 | 3,602,128 |
import itertools
def plot_shared_doubletons(counts, subpop_labels=None,
subpop_colors='bgrcmyk', axs=None,
figsize_factor=1, ylim=None, relative=False,
flip=False):
"""Plot counts of doubleton sharing between subpopulations as a bar ... | 4c12169826845c6d9d61be96bd8ef72563cc3454 | 3,602,130 |
def test_shuf():
""" SHUF function """
return _standard_test('shuf', 7) | f436b9b464dcad1c66c775e3073538630eb631ac | 3,602,131 |
from typing import Optional
def contains_symbol(text: str, symbols: Optional[str] = None) -> bool:
"""If text contains a symbol in symbols, return True."""
if symbols is None:
for character in text:
if character.isascii() and (not character.isalnum()):
return True
r... | 22c6a090c93e81969fb1f4fbcb8bb88ce1bf5714 | 3,602,132 |
from typing import List
import toml
import re
def load(dotenv: bool = True) -> List[EndpointConfig]:
"""
Loads configuration from file.
Uses AVMON_CFG environment variable to locate config file,
defaults to DEFAULT_CFG_PATH if not set.
"""
if dotenv:
load_dotenv()
with open(envir... | 32cff9daa93cf904e0a486d10fbb220f952aa41d | 3,602,133 |
def login():
"""
Tela de login.
"""
return dict(version=__version__) | e92aab04d04ede2b621aca16c9f9b4d75f74e32c | 3,602,135 |
from typing import Callable
def yield_epochs(fn: Callable):
"""A decorator function to unwrap an iterator of [epoch, item]
into successive `AdvanceTo` and `Emit` classes with the
contents of the iterator.
Use this when you have an input_builder function that returns a
generator of (epoch, item) t... | 169e37ec58355c2cd32962dd10aa6909e9883486 | 3,602,136 |
def big_dense(train_feats):
"""
creates big dense model
need to reshape input data like:
train_feats.reshape(train_feats.shape[0], -1)
by default loads weights from latest trained model on BTC_STR I think
"""
# restart keras session (clear weights)
K.clear_session()
tf.reset_de... | c422528b8fdf39a1d4e3b5ef064affe5e72a1ac9 | 3,602,137 |
import requests
import traceback
def query_label_names():
"""
Returns a list of label names
:return: Prometheus Label names
"""
try:
response = requests.get(
'{}:{}{}'.format(
config['prometheus']['url'],
config['prometheus']['port'],
... | c028b4e5f9db8d730ebb7986acbb8c4253ee1fee | 3,602,139 |
def output_loss(func):
"""Convenience decorator that takes a loss defined for the output layer
and converts it into the more general form in terms of all layers."""
@wraps(func)
def wrapped_loss(self, activities, targets):
result = [None for _ in activities[:-1]]
result += [func(self, a... | 576ce12efdee4751731ab0dd40d01d63fbb7db13 | 3,602,140 |
import re
def process(text, pattern = '(<\/?[a-zA-Z]*>)|(\n)'):
"""
process - process SGML-styled text into preferred text
Inputs:
- text : raw text
- pattern : matching pattern to remove SGML tags
Outputs:
- text : processed text
"""
# remove SGML tags
text = re.sub(pattern = pattern, repl = '', string... | 87f16159e015df0341f654d0f46fe5334cd11a8d | 3,602,141 |
def uuid_to_base58(value):
"""
Render a UUID in Base58 and return as a string
>>> uuid_to_base58(uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089'))
'7KAmj837MyuJWUYPwtqAfz'
>>> # The following UUID to Base58 encoding is from NPM uuid-base58, for comparison
>>> uuid_to_base58(uuid.UUID('d7ce8475... | 8c2d737396d4552c7e51fa4311d38bed07e4e094 | 3,602,142 |
def get_s3bucket_objects(s3bucket, s3object):
"""S3: get bucket objects."""
s3_client = boto3.client('s3')
s3_result = {}
try:
s3_result = s3_client.list_objects_v2(Bucket=s3bucket, Prefix=s3object, Delimiter = "/")
except botocore.exceptions.EndpointConnectionError as error:
s3_r... | e1d60303c501a65760fb42a2541fe3faacc203b6 | 3,602,143 |
import yaml
def read_parameter_file(parameter_file_path: str) -> dict:
"""
Reads the parameters from a yaml file into a dictionary.
Parameters
----------
parameter_file_path: Path to a parameter file.
Returns
-------
params: Dictionary containing the parameters defined in the provide... | 5f203bf596c2b1c39f14cea1e99e0c33c2f97ce2 | 3,602,144 |
def contact(request):
"""
A View to submit user contact forms
for admin to view backend.
"""
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
subject = "Website Contact Form"
body = {
'na... | 13b27926cb572f75c28d737ba37e877aaa7b70de | 3,602,145 |
from typing import Tuple
def _compute_jk_block(nu: np.ndarray, fxx: np.ndarray, dm: np.ndarray,
ao_value: np.ndarray,
weights: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Computes J and K contributions from the given block of nu integrals."""
batch_size = nu.shape[... | 2d1ebedde40e9a27d72c36edcf9cc460347e4e3c | 3,602,147 |
def obter_coluna(tab, c):
""" Recebe um tabuleiro e o valor de uma coluna devolve um vetor com os valores da coluna pretendida do tabuleiro.
:param tab: Um tuple, tabuleiro.
:param c: Um int, valor da coluna do tabuleiro (1 a 3).
:return: Um tuple, coluna do tabuleiro.
"""
if not eh_tabuleiro(t... | deb63c2f7f680c9816b4c9cc319fe3095e43291a | 3,602,148 |
from typing import List
def extract_query_toks_no_value(anonymous_query: str) -> List[str]:
""" doesn't deal with literal strings since we only use it on anonymous queries """
query_no_values = anonymous_query.replace(LITERAL_FOR_QUERY, VALUE)
query_no_values = _surround_dots_with_spaces(query_no_values)
... | 3c875a9345004dc3ec42c6ad751a50b4dda205df | 3,602,149 |
import hashlib
def make_hash(to_hash: str) -> str:
""" Return a hash of to_hash. """
new_hash = hashlib.md5()
new_hash.update(to_hash.encode("utf-8"))
return str(new_hash.hexdigest()) | 7e800f7942df23256373c221428e5c24b65cabee | 3,602,150 |
def open_termsbox(n_clicks, state):
"""Callback which displays the EULA box when clicking on the LICENSE AGREEMENT button in the bottom bar.
The EULA is located at the EULA.py file.
"""
if state is None and n_clicks != 0:
return eula.hive_termsofuse
else:
return None | 30bcedac9482fed53d6054b1404e724620bb579d | 3,602,151 |
from typing import Dict
from typing import Any
def _truncate_locals(f_locals: Dict[str, Any], free_space: int) -> FrameVariables:
"""
Truncate variable part or the entire variable in order to avoid exceeding the maximum frames size.
:param f_locals: inspect.FrameInfo.frame.f_locals
"""
locals_trun... | 73130163c1110061fa41e120c01afe02b11b04b7 | 3,602,154 |
from typing import Optional
def swiss_roll(nt: int, ns: int, freq: Optional[float] = 2.0) -> np.ndarray:
"""Draw samples from the swiss roll manifold."""
tt = np.linspace(0.0, 2.0 * np.pi, nt)
ss = np.linspace(-0.5, 0.5, ns)
t, s = np.meshgrid(tt, ss)
x = t * np.cos(freq * t)
y = t * np.sin(f... | 188e139c77283f9c3d0e7dd7369f4913b2e76734 | 3,602,155 |
def confirm(question: str, default: bool = True) -> bool:
"""
Requests confirmation of the specified question and returns that result
:param question:
The question to print to the console for the confirmation
:param default:
The default value if the user hits enter without entering a va... | 2bce30acbf921ac62afb3fefb0430b8a4cf442cd | 3,602,156 |
def resolution(liste,point,n=3):
"""fonction permettant de savoir si les coordonnées d'un point sont trop proches des coordonnées du dernier point d'une liste"""
if len(liste)==0 :
#si la liste est vide
return True
else :
point_precedent=liste[-1]
if abs(point_precedent[0]-po... | 401a3972b09f5959e7c7face45611539469e7a8f | 3,602,157 |
def incorrectSimplify(num, denom):
"""Given a numerator and denominator, reduce it incorrectly by cancelling out digits. Also return the number of pairs of digits canceled out (e.g. the 4s cancel in 34/49 to give 3/9, and returns 1 pair canceled)"""
numList = [x for x in str(num)]
denomList = [x for x in st... | 3e1df4063518ced4a727785d445073a10d0889cc | 3,602,158 |
def isDoor(case):
"""Teste si la case est une porte"""
if "special_type" in case.keys():
return case['special_type'] == "door"
else:
return False | 54a8242a8139e98867a0b3cad8597c8fe36ca685 | 3,602,159 |
def _validate_agent(client, **kwargs):
"""Check that the given neutron agent is alive
:param client: Neutron client
:param kwargs: Additional parameters to pass to the neutron client
list_agents method.
:returns: A boolean to describe the agent status, if more than one agent
returns... | 0d621d422b41018d473fdd28fa6f1052558fdc96 | 3,602,160 |
from typing import Iterator
def list_to_str_params(string, strings: Iterator[str], couple_arg='LIKE', wordjoin=' OR ') -> str:
"""Return string like: string LIKE string1 OR string LIKE string2"""
return wordjoin.join([f'%s %s "%s"' % (string, couple_arg, normalization_pagename(s)) for s in strings]) | a8152749d83899f2b695377aed3314296dda66eb | 3,602,162 |
def get_times_from_sessions(sorting_man, sessions,
sign='pos', skip_artifacts=True):
"""
retrieve index first, then times. This is just a renamed function.
"""
return get_data_from_sessions(sorting_man, sessions,
sign, ['times'], skip_artifac... | d111712e2f50e4aeb7d0eb9ebe347f12c8b81801 | 3,602,163 |
import glob
def get_scheme_dirs():
"""Return a set of all scheme directories."""
scheme_glob = rel_to_cwd("schemes", "**", "*.yaml")
scheme_groups = glob(scheme_glob)
scheme_groups = [get_parent_dir(path) for path in scheme_groups]
return set(scheme_groups) | 64faa49879f209466c088f3deef954aa65e4debd | 3,602,164 |
def _nextpow2(i):
"""Find next power of 2."""
n = 1
while n < i:
n *= 2
return n | 14c2fd0c37910ac94a55ff3caa562e68010e7f20 | 3,602,165 |
def spatial_scenario_selection(dataframe_1,
dataframe_2,
dataframe_1_columns,
dataframe_2_columns,
):
"""Intersect Polygons to collect attributes
Parameters
- dataframe_1 - Fir... | 7c7d380d141244543d9a0a840ead456996eda006 | 3,602,166 |
from typing import OrderedDict
def model_to_CPU_state(net):
"""Gets the state_dict to CPU for easier save/load later."""
if is_parallel(net):
state_dict = {k: deepcopy(v.cpu()) for k, v in net.module.state_dict().items()}
else:
state_dict = {k: deepcopy(v.cpu()) for k, v in net.state_dict(... | 872f641b32e9388d0a78ff977ff6173748de7458 | 3,602,167 |
def _subject_graph_maps_to_pom(mapping_graph):
"""
Move graph maps in subject maps to the predicate object maps of subject maps.
"""
# add the graph maps in the subject maps to every predicate object map of the subject maps
query = 'SELECT ?sm ?gm ?pom WHERE { ' \
f'?tm <{RML_STAR_SUBJE... | 24168c4d7020eae96043208aa1632f8beb4d2170 | 3,602,168 |
def symmetric_match_both(table_1, table_2, ra_col_1="ra", ra_col_2="ra",
dec_col_1="dec", dec_col_2="dec", max_sep=3.0):
"""
Matches objects from two astropy tables by ra/dec, including all objects.
This function does symmetric matching. This measns that to be defined as
a match, both objects... | 0bdf9b619d5261a2c7e0499f5cb014395bdc6791 | 3,602,169 |
from pesummary.gw.conversions import q_from_m1_m2
def lambda2_from_lambda1(lambda1, mass1, mass2):
"""Return the individual tidal parameter given samples for lambda1
"""
q = q_from_m1_m2(mass1, mass2)
lambda2 = lambda1 / q**5
return lambda2 | 84d11f21d7cc48d9d1606589701dd91b931f1971 | 3,602,171 |
def _beam_fit_fn_3(z, z0, Theta):
"""Fitting function for z0 and Theta."""
return (Theta*(z-z0))**2 | 76955c6464ae7a33927986d146e9000e9a45c12b | 3,602,172 |
from io import StringIO
def read_csv_and_index_fips_date(csv_str: str) -> pd.DataFrame:
"""Read a CSV in a str to a DataFrame and set the FIPS and DATE columns as MultiIndex."""
return pd.read_csv(
StringIO(csv_str),
parse_dates=[CommonFields.DATE],
dtype={CommonFields.FIPS: str},
... | be4fb68e037f68aee3a3897d982e2ee23180bff8 | 3,602,173 |
def stations_by_river(stations):
"""Returns a dictionary containing rivers (keys), and the stations on each river (values)"""
rivers = {}
for station in stations:
# only add the river if station.river has been set
river = station.river
if river is not None:
# add the stat... | 7feef52d4d5c14109807e1c2e559f206b420c5cc | 3,602,174 |
def generate_linear_data(dimension, num):
"""
随机产生线性模型数据
参数
----
dimension :int,自变量个数
num :int,数据个数
返回
----
x :np.array,自变量
y :np.array,因变量
"""
np.random.seed(1024)
beta = np.array(range(dimension)) + 1
x = np.random.random((num, dimension))
epsilon = np.rando... | 4fff8a8f2f1eade6510cd23412c02805d7b7798c | 3,602,175 |
def split_daterange_in_intervals(start, end, mi):
"""
Split a daterange in non overlapping intervals of mi minutes - 1 microsecond.
Parameters
----------
start: datetime.datetime
start of the daterange
end: datetime.datetime
end of the daterange
mi: int
Minutes of th... | a5516c3bddd8ccf7ac59d43e3b23cc3b6360ad42 | 3,602,176 |
def view(request, name):
"""
View Area information.
**Templates:**
* ``areas/view.html``
**Template Variables:**
* area, directors
"""
area = get_object_or_404(Group, type='area', acronym=name)
try:
area.start_date = area.groupevent_set.order_by('time')[0].time
... | 78ff40025f6e25fa4ddfafe696ed5efb9bb52278 | 3,602,177 |
def build(nick:str, user_config:dict)->tuple:
"""Construye la ventana de juego con la informacion de la configuracion de usuario.
Args:
nick (str): El nick del jugador
user_config (dict): diicionario con la configuracion del usuario
Returns:
[sg.Window]: La ventana de juego armada
... | fbeb8d3f21634cedf6a86b52ea8a4d9b7ab5de80 | 3,602,178 |
def _modulize_function(old, globals_, source_module, module_name, module_path):
"""
Changes the given function's scopes and qualname if they were defined inside of a modulized class.
Parameters
----------
old : `function`
A function present inside of a modulized class.
globals_ : `d... | bfae792a8d9f06bf12acadeb6b178e5146152643 | 3,602,179 |
def mock_device_supporting_paulis(monkeypatch):
"""A function to create a mock device with non-empty observables"""
with monkeypatch.context() as m:
m.setattr(Device, '__abstractmethods__', frozenset())
m.setattr(Device, 'operations', mock_device_paulis)
m.setattr(Device, 'observables', ... | cbd7c6ad2dc1704a11dee17acc39dafa9f8a4ec7 | 3,602,180 |
def extract_features_by_category(single_id_df, category: str, related_features: list, category_column: str):
"""
Parses the 'single id dataframe' for the desired category and it's related features (columns).
"""
lc = [[remove_accents(str(reg[i]).rstrip().lower()) for i in range(len(reg)) ]
fo... | dd14e972abf0f388cdd118ec79cec283a8570980 | 3,602,181 |
def json_citation_for_ij(query, score, doi):
"""
Because we are parsing the PDF, we cannot ensure the validity of each subfieldobtained form the parser (CERMINE) i.e title, journal, volume, authors, etc.
Instead, we join all the information obtained from the parser in plain text.
This plain text is the ... | 1f226db5420b61cd40b88015ec727ebd84a08138 | 3,602,182 |
def find_combination(value, stream):
"""
>>> find_combination(127, [35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576])
62
"""
x = 0
y = 2
while True:
total = sum(stream[x:y])
if total < value:
y += 1
elif total > ... | 17a61c6918ce78f283bc1b641edb4c235746d428 | 3,602,184 |
def model_fn(features, labels, mode, params):
"""Build Model function f(x) for Estimator."""
#------hyper parameters------
field_size = params['field_size']
feature_size = params['feature_size']
embedding_size = params['embedding_size']
l2_reg = params['l2_reg']
learning_rate = params['lear... | c6b0f1d8aeca46bd08a257300409286aeb43075a | 3,602,185 |
def edit_food(id):
"""Update a food entry if the current user is the creator"""
db = get_db()
food_entry = get_food_entry(id)
old_food_name = food_entry['food_name']
old_food_code = food_entry['food_code']
if request.method == 'POST':
if request.form['action'] == 'Update Entry':
... | 7c937421ca74ed063960fd440dc3850abd8af1f0 | 3,602,186 |
def create_pn_output(spike_trains):
"""Create stimvec and vecstim for proxy of PN spikes"""
global model_dict
cfg.logger.info('Started creating PN output vecstims and stimvecs')
stimvecs = []
vecstims = []
for st in spike_trains:
stimvecs.append(h.Vector(st))
vecstims.append(h.Ve... | b0887355bb1c60e4c2c580c70e3eef46d3f60f05 | 3,602,187 |
def mean_squared_error(obs_rate, est_rate):
"""Mean squared error across samples"""
return K.mean(K.square(est_rate - obs_rate), axis=0, keepdims=True) | b60e913266e3e301f805d63d2b2bf52bc3d9330a | 3,602,188 |
def import_patched(module_name, *additional_modules, **kw_additional_modules):
"""Imports a module in a way that ensures that the module uses "green"
versions of the standard library modules, so that everything works
nonblockingly.
The only required argument is the name of the module to be imported.
... | 11353f15500c93cd7586e125ab8348ab618ee780 | 3,602,189 |
def _create_dataset_reader(
dataset_creator,
filenames,
cycle_length=None,
num_parallel_calls=None,
deterministic=None,
block_length=1,
):
"""
This creates a dataset reader which reads records from multiple files and interleaves them together
```
dataset = Dataset.range(1, 6) # ==> [ 1,... | 8b111bc6f4926e55d4759eccf3e35b653ac1930d | 3,602,190 |
import numpy
def extractPositionsFromOEMol(molecule):
"""Get the positions from an OEMol and return in a position array with units via simtk.unit, i.e. foramtted for OpenMM.
Adapted from choderalab/openmoltools test function extractPositionsFromOEMOL
Arguments:
----------
molecule : OEMol
... | bd7b741752c9b61b1cbf77ebcfa1914e108c3bcb | 3,602,191 |
def data_pattern(data):
"""
"""
data = list(data.items())
data.sort(key=lambda x: x[1])
data.sort(key=lambda row:
[[r[i] for n, r in data].count(x)
for i, x in enumerate(row[1])])
for c in range(len(data[0][1])):
values = {row[c]: i for i, (name, row) in enu... | f3805ab18f92e60e858638f2ec60e660e1819c60 | 3,602,192 |
import csv
import json
def callback(cls, text: str, return_logs: bool = None, *args, **kwargs):
"""
:param text: The text to normalize
:param bool return_logs: Return normalization logs
"""
try:
instance = cls(*args, **kwargs)
if not return_logs:
return dict(text=instan... | d4ac3772ff41e3ceef16c1a60adef0f12c5bb7e6 | 3,602,193 |
def rekey(
old: VaultLib,
new: VaultLib,
content: bytes,
) -> bytes:
"""Rekey vaulted content to use a new vault password
:param old: ``VaultLib`` object populated with the vault password the content is
currently encrypted with
:param new: ``VaultLib`` object populated with the ... | 59de0106283b6c8f60ea557ddee3fd8800076ab3 | 3,602,194 |
def integrate_dpc(xshift, yshift, fourier_calibration=1):
"""
Integrate DPC shifts using Fourier transforms and
preventing edge effects
Parameters
----------
xshift: ndarray
Beam shift in the X dimension
yshift: ndarray
... | e37e6fe101bfbb8a347152ed583a8f0ef1962211 | 3,602,195 |
def group_by(cols, stmt):
"""
Function: Takes an existing statement and converts it into a grouped statements where operations are performed "by group".
Input: Columns to "group_by". Columns have to be in a [list].
Output: A grouped statement,
"""
s = maybe_wrap(stmt)
return s.group_by(*[ge... | dd0b07f08e3dacbd153fd5d89ae0d82b7b7fde3c | 3,602,196 |
from typing import Iterable
async def http_422_error_handler(request: Request, exc: HTTPException) -> JSONResponse:
"""
Handler for 422 error to transform default pydantic error object to gothinkster format
"""
errors = {"body": []}
if isinstance(exc.detail, Iterable) and not isinstance(
exc.detail, s... | b9c0ee806ef6a75c50e4453374a687edd902efad | 3,602,197 |
def descriptor_info(desc_id):
"""Display the descriptor info."""
descriptor = Descriptor.query.get(desc_id)
if descriptor is None:
abort(404)
is_option = len(descriptor.values) != 0
return render_template(
'descriptor/manage_descriptor.html',
desc=descriptor,
is_optio... | dc176e51418efd0e42b19438815a738a610835d6 | 3,602,198 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.