content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def household_activity_choices(indiv_utils, interaction_coefficients, hhsize,
trace_hh_id=None, trace_label=None):
"""
Calculate household utilities for each activity pattern alternative for households of hhsize
The resulting activity pattern for each household will be coded a... | 582c2db79e46a9941f466551234e0ff53d278eba | 3,605,100 |
def intents_to_string(intents, queryset=False):
"""
Args:
intents: [{"action": "/application/json/view"}, ...] OR
[models.Intent] (if queryset=True)
Returns:
['<intent.action', ...]
"""
if queryset:
new_intents = [i.action for i in intents]
else:
... | 55e9350d2db63de474f46836e02ae32297e2c170 | 3,605,101 |
import six
import itertools
import hashlib
def decrypt(secret, ciphertext, nosalt=False):
"""Given the first 16 bytes of splunk.secret, decrypt a Splunk password"""
plaintext = None
if isinstance(secret, six.text_type):
secret = secret.encode()
if isinstance(ciphertext, six.binary_type):
... | 1a5e7127bff016c7190a58a588a2cbf0d8b9e522 | 3,605,102 |
def velocity_prior(speed=0.5, var=0.05):
"""Isotropic velocity based on a given speed.
"""
num_mixands = np.min((np.max((1,1/var)),20))
if np.mod(num_mixands,2) != 0:
num_mixands += 1
c = np.eye(2) * var
c = np.tile(c, (num_mixands, 1, 1))
means = [[np.cos(2 * np.pi / num_mixands * ... | c2fcb0317ef60fbf16b19ff45a666b25fe87ed09 | 3,605,103 |
def probePoints(dataset, pts):
"""
Takes a ``Volume`` (or any other vtk data set)
and probes its scalars at the specified points in space.
Note that a mask is also output with valid/invalid points which can be accessed
with `mesh.getPointArray('vtkValidPointMask')`.
"""
if isinstance(pts, v... | cace69b8d387b657fe631b32e56eedaf72e6776e | 3,605,104 |
import re
def greek_to_english(string):
"""
Converts all greek letters to the corresponding english letters.
Useful for creating song slugs from greek song titles.
"""
GREEK_MAP = {
'α':'a', 'β':'b', 'γ':'g', 'δ':'d', 'ε':'e', 'ζ':'z', 'η':'h', 'θ':'th',
'ι':'i', 'κ':'k', 'λ':'l',... | 5c4752b1a1d08b0b37acc3f0e0c884d775eae637 | 3,605,105 |
def recipe_graph_from_settings(locations, settings, args):
"""
This defines the full set of recipes that are the model.
These may be a subset of all locations,
and we may execute a subset of these.
Args:
locations (nx.DiGraph): A graph of locations in a hierarchy.
settings (Configur... | 0fdf3238bd20244c84c5cf46ef0ed89d08da689c | 3,605,106 |
from typing import Union
def get_dataset_indexes(
dataset: xr.Dataset,
coord_var_name: str,
coord_values: SeriesLike,
index_dtype=np.float64
) -> Union[xr.DataArray, np.ndarray]:
"""
Compute the indexes and their fractions into a coordinate variable
*coord_var_name* of a *d... | a914a2d0d6959dd7178c52890f1352f04cc7a61a | 3,605,107 |
def addDiskImageToVM(vm_name,di_name):
"""
Attach the disk image to the 'stableVM'.
Returns the LUN if successful otherwise returns None
NOTE: azure vm show may return json matching the disk image
name yet missing the LUN. When this occurs, the LUN is '0'.
"""
cmd='azure vm disk attach --j... | 32a152dd815b3abeccc445a2c735b92f3a719bf3 | 3,605,108 |
def map_is_walkable(m: tcod.map.Map, x: int, y: int) -> bool:
"""
.. note::
This function is slow.
.. deprecated:: 4.5
Use :any:`tcod.map.Map.walkable` to check this property.
"""
return bool(lib.TCOD_map_is_walkable(m.map_c, x, y)) | d77198c91a1dbbd15a51919d8f1d2015a31d2e53 | 3,605,109 |
def VA(string):
""" Color `string` for Variable"""
return va+string+reset | 8c8a899569081c3454743650cd5e25fef4824546 | 3,605,110 |
def bootstrap(
conf: config.Configuration = config.EnvironmentThenFileConfiguration(),
client: AbstractHttpClient = OpencastHttpApiClient()
) -> services.OpencastApi:
"""Composition root to handle early initialization
returning a ready OpencastApi object.
Dependency injection makes tes... | cc83dc9daf8bcacf739b243cec15141c60fd73aa | 3,605,111 |
import six
def get_dtheta_benchmark_matrix(theta_type, theta_value, benchmarks, morpher=None):
"""Calculates matrix A_ij such that d dsigma(theta) / d theta_i = A_ij * dsigma (benchmark j)"""
if theta_type == "benchmark":
if morpher is None:
raise RuntimeError("Cannot calculate score with... | 26ae0ec494df485061800d6defa049c9fcf630a9 | 3,605,112 |
def _get_banks_to_remove(redis_server, bank, path=""):
"""
A simple tree traversal algorithm that builds the list of banks to remove,
starting from an arbitrary node in the tree.
"""
current_path = bank if not path else "{path}/{bank}".format(path=path, bank=bank)
bank_paths_to_remove = [current... | 660bf90da8ed0b0b7efc9cae0178541bfe3568f8 | 3,605,113 |
def autoCall(f, *args, stack:list=None, commands:list=None):
""" Utility function to invoke dynnamic functions """
result = f(*args)
return result if result else args[0] | 8bc2357ddb4b567a72e2046b9b40f6f90fa5dd27 | 3,605,114 |
def xw_plus_b(x, w, bias=None, transW=True, out=None):
"""Compute *matmul(x, w) + bias.*``
Parameters
----------
x : dragon.vm.torch.Tensor
The x.
w : dragon.vm.torch.Tensor
The w.
bias : dragon.vm.torch.Tensor, optional
The bias.
transW : boolean
Whether to ... | 4f41bb3095e593ff346944ac779cbfbd58a1b9a3 | 3,605,115 |
def _bytes_feature(value):
"""
Returns a bytes_list from a string / byte.
"""
return tf.train.Feature(
bytes_list=tf.train.BytesList(value=[value])
) | a3b9ddc82c52fc5b8afac18618701283b75f19d6 | 3,605,116 |
def anum(self, num="", type_="", xhot="", yhot="", **kwargs):
"""Specifies the annotation number, type, and hot spot (GUI).
APDL Command: /ANUM
Parameters
----------
num
Annotation number. ANSYS automatically assigns the lowest
available number. You cannot assign a higher number ... | be3acd32deffcd31a3a83758b64d0d6950bbd791 | 3,605,117 |
import os
def outputs_exist(output_dir, input_file):
"""Returns True if outputs exist in the target directory."""
outputs = os.listdir(output_dir)
if input_file in outputs:
logger.debug('output {} found'.format(input_file))
return True
else:
return False | c4a4509ecb8975882cef7581447ddf8c255bf94c | 3,605,118 |
def ADMM(A, y):
"""Alternating Direction Method of Multipliers
This is a python implementation of the Alternating Direction
Method of Multipliers - a method of constrained optimisation
that is used widely in statistics (http://stanford.edu/~boyd/admm.html).
This is simplified version, specifically... | 39bc4ae16d286a97bc1b9c5f7f94412db74ef2ad | 3,605,119 |
def main():
"""Manages the application root"""
return ('', 404) | cf1d676fc24d1db79c567d6d37d7d6660aaca977 | 3,605,120 |
def parse_params_arg(params_arg):
""" Parse Params Arg """
params = dict()
args = params_arg.split(',')
for arg in args:
keyvalue = arg.split('=')
params[keyvalue[0]] = keyvalue[1]
return params | 2e5673b2bbe552cb751b1250161745d7913df1be | 3,605,121 |
def nfft(ht, sampling_frequency):
"""
performs an FFT while keeping track of the frequency bins
assumes input time series is real (positive frequencies only)
ht = time series
sampling_frequency = sampling frequency
returns
hf = single-sided FFT of ft normalised to units of strain / sqrt(Hz... | e165e3845b9d51ecc283619e300b706c0997f940 | 3,605,122 |
def get_coords(doctype, filters, type):
"""Get a geojson dict representing a doctype."""
filters_sql = get_coords_conditions(doctype, filters)[4:]
coords = None
if type == "location_field":
coords = return_location(doctype, filters_sql)
elif type == "coordinates":
coords = return_coordinates(doctype, filters_... | ae926180a5d86a7e334378607369c4623b189230 | 3,605,123 |
def sign_adaptation(control: 'FloatNest',
output: 'FloatTensor',
set_point: 'FloatTensor',
adaptation_rate: 'FloatTensor' = 0.01) -> 'FloatNest':
"""A function to do simple sign-based control of a variable.
```
control = control * (1. + adaptation_rate)... | 168dc8024e30fe4c5f36da80872bfbe385336708 | 3,605,124 |
import ssl
import sys
def get_json_response(server, api, username, password):
"""
Returns the response from the URL specified
"""
try:
# lib opener
response = {}
context = ssl._create_unverified_context()
conn = HTTPSConnection(server, co... | cb08d663921924f91207c07c4740e130665e177d | 3,605,125 |
def _grouprule_compute(columns, conditions, having, df):
"""
Computes the metric result.
:param columns:
:type columns: list
:param conditions:
:type conditions: list
:param having:
:type having: list
:param df:
:type df: DataFrame
:return: Result of the metric.
:rtype: f... | 11403688664a786d8557b5cb834ee96d78b87005 | 3,605,126 |
def make_master_assignment_table(list_of_assignment_paths, min_probability=0.0, full=False):
"""Create a master assignment table from a list of assignment paths
:param list_of_assignment_paths: list of all paths to assignment.tsv files to concat
:param min_probability: minimum probabilty to keep
:retur... | e359e59679acfc246606820a4400f2f036165a80 | 3,605,127 |
import logging
def getRemoteKey(cmd, path, ip, user, passwd):
"""Uses ssh-keygen command over SSH to generate id_rsa.pub on remotehost"""
sshToOtherClient(ip, user, passwd, cmd)
showKeyCmd = 'cat %s' % (path)
remote_key = sshToOtherClient(ip, user, passwd, showKeyCmd)
logging.debug("Remote key fo... | e5d823503854c98584bc4672224389d56d9bbc33 | 3,605,128 |
def _convert_to_parser_rule(rule, terminals_to_ids, nonterminals_to_ids,
rule_idx):
"""Convert Rule to CFGRule."""
rhs = []
for token in rule.rhs.split(" "):
if token.startswith(NON_TERMINAL_PREFIX):
symbol_idx = nonterminals_to_ids[token[len(NON_TERMINAL_PREFIX):]]
rhs... | a11a80a2807d354f0e06fd992b636d51bc40d3c1 | 3,605,129 |
def login_authentication(request):
"""RBAC login API
:param request:
:return:
"""
feedback = {
'permission': True
}
data = request.data
username = data.get('username', None)
password = data.get('password', None)
try:
if username is None:
feedback['... | 1888a717dd0550a8abbe63807264f7d71db49092 | 3,605,130 |
def map_ensembl_ids(ensembl_ids):
"""Return references based on a list of Ensembl IDs."""
refs = []
for ensembl_id in ensembl_ids:
ref = {'HGNC_SYMBOL': None, 'HGNC': None, 'UP': None,
'ENSEMBL': ensembl_id}
ensembl_id = ensembl_id.split('.', maxsplit=1)[0]
hgnc_id = h... | 71e1304f14d4647ddea732636831f9c04ac965ff | 3,605,131 |
def nthUglyNumber(n: int) -> int:
"""
书中的解法
"""
q = [1]
t2, t3, t5 = 0, 0, 0
for i in range(n-1):
a2, a3, a5 = q[t2]*2, q[t3]*3, q[t5]*5
to_add = min(a2, a3, a5)
q.append(to_add)
if a2 == to_add:
t2 += 1
if a3 == to_add:
t3 += 1
... | a24806c1ff94ec1291c19bb1f1a8596e20c809b6 | 3,605,132 |
def livb_annotation():
"""Returns an annotation with species entities (LIVB) identified.
"""
annotation = {"ents": [{"text": "mouse", "label": "LIVB", "start": 0, "end": 0},
{"text": "human", "label": "LIVB", "start": 0, "end": 0}],
"text": "mouse and human",
... | 78de25feab620347e08c8bc74ecf467db3bb477a | 3,605,133 |
def check_authors_from_papers(papers,authors,silent=False,mute=False):
""" Check the given papers against a list of authors.
The authors can either be in a text file or in a list.
Returns a list of papers that contain the authors in either their
title, abstract, or author list."""
return check_keywo... | a35c4def80e36713120174f84f892c2f57ee6e4c | 3,605,134 |
def sentence_to_token_ids(sentence, vocabulary,
tokenizer=None, normalize_digits=True, normalize_name=False):
"""Convert a string to list of integers representing token-ids.
For example, a sentence "I have a dog" may become tokenized into
["I", "have", "a", "dog"] and with vocabulary {"... | 0b77631be2a4f566e619bb646c58930b0700934c | 3,605,135 |
def generate_networks(network_graph, root_ids):
"""
Parameters
----------
network_graph : DirectedGraph
graph facing upstream
root_ids : pandas.Series
Series of root IDs (downstream-most ID) for each network to be created
"""
segments = pd.Series(
network_graph.desce... | cc080248da938269aa76f64b0baef8982bb9bf4e | 3,605,136 |
def discretizer(df_list, names, method_list):
"""
Parameters
----------
df_list: pd.DataFrame type, the dataframe need to split.
names: list of column names
method_list: a dictionary contains the methods as key, and parameters as values.
key must in ['isometric','quantile','kmeans']
Like... | d84c720e6578a17a756cd4b121e05b5a953f36dd | 3,605,137 |
def stft(sig, frameSize, overlapFac=0.75, window=np.hanning):
""" short time fourier transform of audio signal """
win = window(frameSize)
hopSize = int(frameSize - np.floor(overlapFac * frameSize))
samples = np.array(sig, dtype='float64')
# cols for windowing
cols = int(np.ceil((len(samples) - ... | 9ddeff11913f64d303be916208e5e90e4ff0ae2c | 3,605,138 |
def ontology_term_parser(cell_value: str = None):
"""
Parse a line string and convert it into a dictionary {key -> value}
:param cell_value: String line
:return:
"""
term = {}
values = cell_value.split(";")
if len(values) == 1 and '=' not in values[0]:
term[TERM_NAME] = values[0]... | 222ebc183f61ef415aa2afc1b24c9f1bcbd64571 | 3,605,139 |
def fringe_to_nm(idx):
"""Convert Fringe Z to (n, m) two-term index."""
m_n = 2 * (np.ceil(np.sqrt(idx)) - 1) # sum of n+m
g_s = (m_n / 2)**2 + 1 # start of each group of equal n+m given as idx index
n = m_n / 2 + np.floor((idx - g_s) / 2)
m = (m_n - n) * (1 - np.mod(idx-g_s, 2) * 2)
return in... | c3ca0206463491455b22c84d91337fb72bc49017 | 3,605,140 |
def catalyze_one_step_reversible(enzyme, substrate, product, klist):
"""
Create fwd and reverse rules for catalysis of the form::
E + S -> E + P
P -> S
Parameters
----------
enzyme, substrate, product : Monomer or MonomerPattern
E, S and P in the above reactions.
kli... | 43988e67933f716a3eb6d59022f9314db777f5ba | 3,605,141 |
from typing import Union
import os
def ssh_get_submission_cmd(
filename: str,
cmd_line_arguments: Union[str, None],
job_arguments: dict,
ssh_settings: dict,
):
"""Create shell script string to execute on remote SSH server."""
if cmd_line_arguments is None:
cmd_line_arguments = ""
#... | 7cac49ddabcc94fdfa1ee6d13384b12ba854f61d | 3,605,142 |
import typing
def build_async_client(resource: LegionCloudResourceUpdatePair,
async_edi_client: AsyncRemoteEdiClient
) -> typing.Optional[object]:
"""
Build client for particular resource (e.g. it builds ModelTrainingClient for ModelTraining resource)
:param ... | 86cc3f235a220ad69b0a1c32df3db4433c085432 | 3,605,143 |
import math
def get_horizon(sub_height):
"""Get horizon distance."""
return math.sqrt(2 * EARTH_RADIUS_KM * 1000 * sub_height + sub_height ** 2) | fc0b034b27679952f2e87511662db306d054da6c | 3,605,144 |
def distance(p1, p2):
"""
Returns distance between the two points
"""
return mag(p1 - p2) | bf9ac1c19e361985749774b84a00ea93bc0a1b0a | 3,605,145 |
import collections
def _get_type_info(initialize_tree, before_broadcast, after_broadcast,
before_aggregate, after_aggregate):
"""Returns type information for an `tff.utils.IterativeProcess`.
This function is intended to be used by
`get_canonical_form_for_iterative_process` to create the expe... | 633843bd16afd74d5f3686dcafa6862d411999c9 | 3,605,146 |
import math
from re import M
def path3(x, y, phi):
"""
Formula 8.3: C|C|C
"""
r, theta = R(x, y)
phi = deg2rad(phi)
path = []
xi = x - math.sin(phi)
eta = y - 1 + math.cos(phi)
rho, theta = R(xi, eta)
if rho <= 4:
A = math.acos(rho / 4)
t = M(theta + math.pi/2... | 4aad4248cf478997b045aa4e2a2ce70d725f2a8f | 3,605,147 |
def compose():
""" Compose a pop song
This is currently a mock-up code.
"""
chords = [Chord("C"), Chord("F"), Chord("G"), Chord("C")]
chord_track = ChordTrack()
for i, chord in enumerate(chords):
event = ChordEvent(time_=Time(measure=i + 1), duration=Time(measure=1), chord=chord)
... | 62ff2bf66ace950c97d94a78c2f1b217d6c73806 | 3,605,148 |
import os
def load_subscriber_config(first_config):
"""Loads the config from the config file and merges it with the given
configuration.
"""
default_config = load_default_subscriber_config()
config_dir = get_config_dir()
conf_file = os.path.join(config_dir, 'supplychain_sds.toml')
toml_co... | 9330d6765ef0840b37b572202b43ae676d062ee6 | 3,605,149 |
import json
def featureset_table(meth, obj_id=None):
"""This method displays a FeatureSet gene list
along with functional annotation in a table.
:param obj_id: FeatureSet workspace object identifier.
:type obj_id: kbtypes.KBaseSearch.FeatureSet
:return: Rows for display
:rtype: kbtypes.Unicod... | afe34859ecb4c503cd0a12dafc56ec70d2c1e8b5 | 3,605,150 |
def _to_int(parsed):
"""
Transforms the received parsed value into an integer.
:param parsed: the parsed value
:return: an integer created from the value
"""
if len(parsed) > 0:
return int(parsed[0])
else:
return None | 1701648c7e42232c8be0c7451d19ffe43f322118 | 3,605,151 |
import os
import mimetypes
def file(path, name=None):
"""
Returns a file response
:param path: str
Path to the file
:param name: str
Name of the file which will be returned.
If it is None the name is like the real file name.
Default = None
:return: :class:`werkzeug... | b12d4253297c631a63b55c40e6cc8262f6908a95 | 3,605,152 |
import requests
from bs4 import BeautifulSoup
import json
def get_current_cryptocurrency_price(num_pages=5, currency="EUR") -> pd.DataFrame:
"""
Scrape current price of cryptocurrencies from https://www.coinmarketcap.com/ and convert it to Euro.
:param num_pages: Each page holds 100 cryptos with highest c... | 3d0e99519a633688df173890ffe20b7b1a756031 | 3,605,153 |
def _single_iteration_random_selection(
nb_attributes, nb_targets, fraction_missing, potential_targets
):
""" Select random combination of descriptive + target parameters for the model
Args:
nb_attributes: total number of attributes
nb_targets: number of targets
fraction_missing... | c93ee571363b2dcd3f073633672546fabc62a28a | 3,605,154 |
def ExtractSubpopulations(gList, gListClosure):
"""
Method to extract subpopulation information from results of
recursive graph segmentation
:param gList:
:param gListClosure:
:return:
"""
# Rebuild gList from all the partitions
# gList, gListClosure, iterBinPartList, iter... | 520735b97f994606e0eeb04136d2443fa82fc6c2 | 3,605,155 |
import pytz
def to_param(m):
""" Converts testkit parameter format to driver (python) parameter
"""
data = m["data"]
name = m["name"]
if name == "CypherNull":
if data["value"] is not None:
raise ValueError("CypherNull should be None")
return None
if name == "CypherS... | 7f342f4c2e32607a83bbd11c25f9de17968854f1 | 3,605,156 |
import logging
def GetEvents(last_synced_id, limit=_PULL_BATCH_SIZE):
"""Get one or more events from Bit9.
If events have been retrieved in the last five minutes, gets all recent
events. Otherwise, gets events in the oldest unseen five minute interval,
so as not to overwhelm Bit9.
Args:
last_synced_id... | 3f8a75dc22a9b490fe52d0c68917e25877fb7c80 | 3,605,157 |
def SaveToErrLog(*args):
"""
SaveToErrLog(char const * MsgCStr)
Parameters:
MsgCStr: char const *
"""
return _snap.SaveToErrLog(*args) | a4eb3cae22750a0f1ac57e48306e47fd5a0c6389 | 3,605,158 |
def get_listener_options(listener_name):
"""
Returns the options for a specified listenername from the database outside
of the normal menu execution.
"""
try:
listener_options = (
Session()
.query(models.Listener.options)
.filter(models.Listener.name == li... | 514578b7a555253f69bc892be60bdd183b95b186 | 3,605,159 |
from typing import List
def waypoints() -> List[Waypoint]:
"""Get a list of example Waypoints."""
return [
Waypoint(Point(1, 2, 3), CriticalPoint.XY_CENTER),
Waypoint(Point(4, 5, 6))
] | 739da2c33d310d20de510209560ed7cdf884ef14 | 3,605,160 |
def get_model_string(model):
"""
:param model: model
:returns: <app_label>.<model_name> string representation for the model
"""
return "{app_label}.{model_name}".format(app_label=model._meta.app_label, model_name=model._meta.model_name) | d54323680c4a15cc99bbbcea09cf319c571ff9cf | 3,605,161 |
def app_base_handlers(request, app, async_db):
"""
Fixture modifies application handlers adding base API handlers and creates table for test models
"""
app.add_handlers(".*$", [(r'^/test/api_test_model/?$', ApiListTestHandler)])
app.add_handlers(".*$", [(r'^/test/api_test_model/([^/]+)/?$', ApiItemT... | 5d81046a4df673895a15db2544533ee928f2076a | 3,605,162 |
def make_discord_object(id: int, **kwargs):
"""Make :class:`discord.Object` instance with given attributes."""
obj = discord.Object(id)
for k, v in kwargs.items():
setattr(obj, k, v)
return obj | 6340d2b4073bac311bab69e622deb46e8e2318b6 | 3,605,163 |
import torch
def get_sift_pooling_kernel(ksize=25):
"""
Returns a weighted pooling kernel for SIFT descriptor
"""
ks_2 = float(ksize) / 2.0
xc2 = ks_2 - (torch.arange(ksize).float() + 0.5 - ks_2).abs()
kernel = torch.ger(xc2, xc2) / (ks_2**2)
return kernel | 4576e97eaab4eba86c9a68edd67c00a2ede0db3f | 3,605,164 |
def default_trees():
"""
Provides a default tree to be used in testing the
putil.tree.TreeNode() class
"""
#
# Tree1 Tree2 Tree3 Tree4
# t1l1 (*) t2l1 (*) t3l1 (*) root
# ├t1l2b1 (*) ├t2l2b1 (*) ├branch1 (*)
# │├t1l... | 31bba9e6da83545d5c8768aef607e0095aaf3f82 | 3,605,165 |
from core import FS
def template():
""" RESTful CRUD controller """
s3.filter = FS("master") == "event_sitrep"
s3db.dc_template.master.default = "event_sitrep"
return crud_controller("dc", "template", rheader=s3db.dc_rheader) | e4bf62e756d4ae921b015ed435fc797a33555837 | 3,605,166 |
def check_overscan(xstart, xsize, total_prescan_pixels=24,
total_science_pixels=4096):
"""Check image for bias columns.
Parameters
----------
xstart : int
Starting column of the readout in detector coordinates.
xsize : int
Number of columns in the readout.
t... | 934d7683a710e9fe88d488398a9ad9e769470460 | 3,605,167 |
import os
def get_sites(iso3):
"""
Load data.
"""
output = {}
path = os.path.join(BASE_PATH, 'intermediate', iso3, 'sites', 'sites.csv')
data = pd.read_csv(path)
data = data[['sites_4G', 'total_estimated_sites', 'backhaul_wireless']]
data = data.sum()
output['sites_4G'] = data[... | f62e1cff80d80ab3862ee891f40edaf7f32e20e0 | 3,605,168 |
async def create(params: SwagTierCreate, db: AsyncSession = Depends(with_db)):
"""
Create a new swag tier
"""
tier = SwagTier.from_orm(params)
try:
db.add(tier)
await db.commit()
except IntegrityError:
raise HTTPException(
status_code=HTTPStatus.CONFLICT,
... | e88ff83aefe66028f852f4c12dec88ac362f6056 | 3,605,169 |
def hex_to_pixel(row, col, hex_edge_length):
"""Get pixel on surface from position of a hexagon in a grid"""
x = hex_edge_length * 3 / 2 * col
y = hex_edge_length * sqrt(3) * (row + 0.5 * (col & 1))
return x, y | d4513dbda194877bb0c9dc48c89a55f3c9ae2b8c | 3,605,170 |
import time
def pillage() -> Response:
"""Claim all unclaimed networks."""
counter = 0
t = time.time()
for network in manager.session.query(Network):
if network.report is not None:
continue
res = _help_claim_network(network, current_user)
if res:
coun... | 76f4fe577a6c245ce0f699b22ad46233dcc042b8 | 3,605,171 |
def periodic_wrap_corner(dist_arr, length, verbose=False):
"""For a box with lower left vertex at the origin."""
if verbose:
print(dist_arr)
dist_arr = dist_arr - np.around(dist_arr / length) * length
if verbose:
print(dist_arr)
return dist_arr | b65333f4e0046307557bb15388f43b24f8513f18 | 3,605,172 |
import warnings
def get_deconv_dla(base_network, pretrained=False, ctx=cpu(), scale=4.0, use_dcnv2=False, **kwargs):
"""Get resnet with deconv layers.
Parameters
----------
base_network : str
Name of the base feature extraction network.
pretrained : bool
Whether load pretrained ba... | 17118011750e5c21fe416a6f57478653fce05f92 | 3,605,173 |
import os
def get_extension_type(filename):
"""
Given a filename, try to determine the type of file from the extension into one of the categories defined as
global variables above.
Parameters
----------
file_path : str
The filename of the file in question.
Returns
-------
... | 6ffa562b3b5c2d5458730b2c3bd7009f6ce9886a | 3,605,174 |
import typing
def prepare_linear_export(V: typing.Union[dolfin.FunctionSpace,
dolfin.VectorFunctionSpace,
dolfin.TensorFunctionSpace]) -> typing.Tuple[dolfin.Function,
... | cb1ba3ce8cfcf1585fe1a575c7721d3546e153ce | 3,605,175 |
def is_python(view):
"""Cosmetic sugar."""
return view.score_selector(0, 'source.python') > 0 | 18c6f14db5b24130e0fb04718e3d81ff7749a526 | 3,605,176 |
def _helperfunction(segment, array) -> geo.Shape:
"""Calculate a shape from input.
Input segment of successive segments as strings.
Input array of the points in the correct sequence. e.g.:
array = [[x-values], [y-values]]
Parameters
----------
segment :
list of String, segment name... | 4f2a1a35bad4f80a2065a972504030bd78dc94d0 | 3,605,177 |
def get_t_neighbors(g, x, y):
"""Returns possible members of conditioning set for x---y edge consideration"""
t = set([])
all_y_neighbors = set(nx.all_neighbors(g, y))
for z in all_y_neighbors:
if has_undir_edge(g, z, y):
if adjacent(g, z, x):
continue
t.... | 340077e5a7585a4e679668c0adcac1dd21cfca90 | 3,605,178 |
def _hurst_exp_compute_rs(x):
"""Utility function for :func:`compute_hurst_exp`.
Parameters
----------
x : ndarray, shape (n_seqs, n_times)
Returns
-------
output : ndarray, shape (n_seqs, n_times - 1)
"""
n_seqs, n_times = x.shape
rs = np.zeros((n_seqs, n_times - 1), dtype=x.d... | 93605138383c8279e448f0af0fdbbfc430820c24 | 3,605,179 |
def suggestTransitionSets(mat, e0=20.0):
"""suggestTransitions(mat, e0=20.0)
Suggest a list of XRayTransitionSet objects for the specified material."""
mat = dtsa2.material(mat)
fams = ("Ka", "Kb", "La", "Lb", "Ma", "Mb")
res = []
for elm in mat.getElementSet():
for fam in fams:
... | 50a6ad2eb1a3709b908284d011c4111b41c83733 | 3,605,180 |
def get_double_grgrid_index(address_double, D_diag, PS=None):
"""Return grid point index of a double-grid address
(Generalized-regular-grid version)
Parameters
----------
address_double : array_like
Double-grid address.
shape=(3,), dtype='int_'
D_diag : array_like
Diago... | 53875965ffec52b45f59d535045e8cdf6e231be0 | 3,605,181 |
from typing import Iterable
from typing import Optional
def rows_to_layout(rows: Iterable[list[str]]) -> Layout:
"""
Takes rows (e.g., from a TSV file), and creates a well-formatted layout
file.
"""
layout: Layout = []
max_row_length = len(max(rows, key=len))
for raw_row in rows:
... | b8790995e9c6f8bb908cc0d1daeb0275f5ca2a0b | 3,605,182 |
def is_same_identifier(issuer_a: str, issuer_b: str) -> bool:
"""
check if 2 issuers string have the same identifier
:param issuer_a: issuer string a
:param issuer_b: issuer string b
:return: True if identifier are the same else False
"""
return issuer_a.split(ISSUER_SEPARATOR)[0] == issuer_... | d3aa9a1b62d9fac208c69e86808cba3ebe5f1ca8 | 3,605,183 |
import re
def is_card(content, cards):
"""
Checks whether the current line contents is a data card starting string.
"""
card = None
for icards in cards:
actual_card = icards[0]
card_regex = re.compile(icards[1])
if card_regex.match(content) is not None:
card = ... | 6c07ea6d76a77b87288903584d295e4b26220f9c | 3,605,184 |
from app.global_handlers import global_handlers
from bll.membership import register_membership
from bll.reports import register_dblogger
def setup_app(**config_overrides):
"""
This is normal setup code for a Flask app, but it's possible
to provide override configurations so that in testing, a differen... | 263063dfd80aa048c9900e3c9edc82fba5cb42ed | 3,605,185 |
def setting_check_file_read(setting_name):
"""
Wrapper to check the case of a file we just need to read.
Setting must be a non-blank string. File must exist, be a regular
file or a symlink to one, and be readable.
Dependencies:
config settings: (contents of setting_name)
globals: cf... | 779dfa65eedafb50d83536f9c0b750146e51bc66 | 3,605,186 |
import string
def unregister():
"""Unregister device for GCM
"""
if request.method == 'POST':
regID = request.form['regID']
regID = string.replace(regID, '\'', '\\\'')
regIDModel = db.GqlQuery("SELECT * FROM RegIDModel WHERE regID ='" + regID)
regIDModel.run()
regI... | 98e5e8ee5f40f083ab04b3d33e7775b225105653 | 3,605,187 |
def compose(color1, color2, blend, operator, non_seperable):
"""Blend colors using the specified blend mode."""
# Get the color coordinates
csa = util.no_nan(color1.alpha)
cba = util.no_nan(color2.alpha)
coords1 = util.no_nan(color1.coords())
coords2 = util.no_nan(color2.coords())
# Setup ... | 544e7cf4b848e656665024fd31dc0adf754c75c2 | 3,605,188 |
def gather_memories(memory_dict, gather_coordinates):
""" Gathers layer-wise memory tensors corresponding to top sequences from the provided memory dictionary
during beam search. """
# Initialize dicts
gathered_memories = dict()
# Get coordinate shapes
coords_dims = get_shape_list(gather_coordin... | f8d7ed41344c5f674d1b2568132e0ec4123a4520 | 3,605,189 |
def extract_revision_ordered_review_requests_for_documents_and_replaced(review_request_queryset, names):
"""Extracts all review requests for document names (including replaced ancestors), return them neatly sorted."""
names = set(names)
replaces = extract_complete_replaces_ancestor_mapping_for_docs(names)... | fd7437452e1401c8992da3946844794b1bbbd87f | 3,605,190 |
import logging
def retry_with_instance_list(instance_list):
"""Decorator for running an Integ test with an instance_list and
break on first success
Args:
instance_list (list): List of Compute instances for integ test.
Usage:
@retry_with_instance_list(instance_list=["ml.g3.2", "ml.g2"]... | c0a9e15b5eb60803d68cdf23189dba50587a8141 | 3,605,191 |
def _get_mode(filename):
"""
Returns the mode (from modes) with which the tarball should be read/written as
"""
ext = splitext(filename)[-1]
for key, val in modes.items():
if ext in val:
return key
raise ValueError(f"{ext} is not supported.") | 3f0f2b043bc62dc7a5194e0f82346b0a5a215e07 | 3,605,192 |
import random
def create_build_ids(dtime, count, randomness=True):
"""Returns a range of valid build ids, as integers and based on a datetime.
See Build's docstring, "Build key" section.
"""
# Build ID bits: "0N{43}R{16}V{4}"
# where N is now bits, R is random bits and V is version bits.
build_id = int(_... | 5c7e9dd88243b3eb1d11065fe5705ab1d6a7e0cf | 3,605,193 |
def vec_reverse(a):
"""
Reverses a vector
Parameters
----------
a: list[]
A vector of scalar values
Returns
-------
list[]
The reversed vector
"""
return a[::-1] | b22e13746de1fe8de60d774b1e20f5c5528507ff | 3,605,194 |
import builtins
def ensure_4d(
array: npt.NDArray[miot.DType], *, num_spatial_dims: builtins.int | None = None
) -> npt.NDArray[miot.DType]:
"""for PyTorch"""
num_dimensions = array.ndim
if num_dimensions == 4:
pass
elif num_dimensions == 5: # hope (W, H, D, 1, C)
if array.shape[-... | 6cbd515cdf6e4ee57791af5622f058f7bca046ca | 3,605,195 |
def select_environment(env_name):
""" Selects an environment.
Args:
env_name: Name (string) of the environment on which the experiment is to
be executed. Can be `HalfCheetah`.
Returns:
The class of an environment
Raises:
ValueError: If the string env_name is unknow... | 9378ac7592aecee614a42df9dcd8bd119d06be66 | 3,605,196 |
def t04_ValueDNE(C, pks, crypto, server):
"""Checks that values not stored at the server return None."""
score = 0
alice = C("alice")
score += alice.download("a") is None
score += alice.download("b") is None
score += alice.download("c") is None
alice.upload("d", "e")
score += alice.downl... | af42da60a48d407ad16da6801e847417dbcc69e9 | 3,605,197 |
def _create_ldtconfig_lsm_target(nmme_model, currentdate):
"""Create name of new ldt.config file."""
lc_nmmemodel = nmme_model.lower()
ldtconfig_nameconv_lsm = \
f"ldt.config_{_LSM_NAME}_nmme_{lc_nmmemodel}"
print("[INFO] Processing LDT ensemble restart file for " + \
f"{ldtconfig_name... | 0aebb6675faa8064635893cea9fe660e67d8825e | 3,605,198 |
import collections
def residual_experimental(model_id, sess, is_training, dimx, dimy):
"""Convolutional embedding of stimulus and response.
Args:
model_id : The variant of convolutional model to train.
sess : Tensorflow session.
is_training : Either training or evaluation mode.
dimx: X dimension ... | 69bdaf62fae4d0f5b818568a4af20df0c5e825e7 | 3,605,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.