content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
def sum_per_agent(df: pd.DataFrame, columns: List[str]) -> pd.DataFrame:
"""Calculates summed values per agent for each given column individually"""
all_values_per_agent = pd.DataFrame(columns=columns)
for column in columns:
function = calc_sum(column)
value_per_age... | b828e68a2f2555b9b12f4c17376a7f88211611d4 | 3,644,000 |
import logging
async def vcx_ledger_get_fees() -> str:
"""
Get ledger fees from the sovrin network
Example:
fees = await vcx_ledger_get_fees()
:return: JSON representing fees
{ "txnType1": amount1, "txnType2": amount2, ..., "txnTypeN": amountN }
"""
logger = logging.getLogger(__nam... | ba801ec57b57354b9bdb3a033b02860e8daed450 | 3,644,001 |
def calc_one_sample_metric(sample):
""" 计算 V1 数据一个样本的 rouge-l 和 bleu4 分数 """
if len(sample['best_match_scores']) == 0: # bad case
return -1, -1
pred_answers, ref_answers = [], []
pred_answers.append({'question_id': sample['question_id'],
'question_type': sample['quest... | 37ce17d36e2d6b31e0fdae29172de442d87fd676 | 3,644,002 |
def ta_1d(x, a, w_0, w_1):
"""1d tanh function."""
return a * np.tanh(w_0 + (w_1 * x)) | ce062d87f3040d95d8bc5360a58b0b7c4625e877 | 3,644,003 |
def get_flat_topic_df(all_topics, n_topics):
"""
Get df with Multiindex to plot easier
:param all_topics: the IDs of the topics as list
:param n_topics: the number of topics in the model
:return: df with index [TopicID, Word] and weight
"""
init_topic = all_topics.columns[0]
# TODO refat... | 3d1ccb1919a70b4c738fa8f49fda0343035329cd | 3,644,004 |
import yaml
def loadConfig(filename):
"""Load and parse .yaml configuration file
Args:
filename (str): Path to system configuration file
Returns:
dict: representing configuration information
Raises:
BdsError: if unable to get configuration information
"""
try:
... | 099d1892bf6f6798a77dcc59067afa59af770745 | 3,644,005 |
def scale_t50(t50_val = 1.0, zval = 1.0):
"""
Change a t50 value from lookback time in Gyr at a given redshift
to fraction of the age of the universe.
inputs: t50 [Gyr, lookback time], redshift
outputs: t50 [fraction of the age of the universe, cosmic time]
"""
return (1 - t50_val... | 43d7fa07a59c4b66c7db7caca3c138800ca8db4e | 3,644,006 |
def get_car_changing_properties(car):
"""
Gets cars properties that change during a trip
:param car: car info in original system JSON-dict format
:return: dict with keys mapped to common electric2go format
"""
result = {mapped_key: car.get(original_key, None)
for mapped_key, origi... | 540dbd0b6d08cc08a950946dda018c3296d8c51d | 3,644,007 |
def get_metadata(record):
"""
Calls DNZ's API to retrieve the metadata for a given record.
"""
id = record['id']
url = DNZ_URL + '{id}.json?api_key={key}'.format(id=id, key=DNZ_KEY)
try:
metadata = get(url).json()['record']
metadata['hash'] = record['hash']
except KeyError... | 522e2aed2f7d71bcf9d397036c764c90c67b6184 | 3,644,008 |
def _expand_one_dict(cfg, shared):
"""expand a piece of config
Parameters
----------
cfg : dict
Configuration
shared : dict
A dict of shared objects
Returns
-------
dict, list
Expanded configuration
"""
if shared['default_config_key'] is not None:
... | d8d00bfede1bdca504f3d643836947363d8914ac | 3,644,009 |
import six
def _api_decrypt():
"""
Return the response dictionary from the KMS decrypt API call.
"""
kms = _kms()
data_key = _cfg_data_key()
try:
return kms.decrypt(CiphertextBlob=data_key)
except botocore.exceptions.ClientError as orig_exc:
error_code = orig_exc.response.g... | b0b01e9a71dfaf594dd9526072b77f2a5c6363c1 | 3,644,010 |
def hide_panel(panel_name, base_url=DEFAULT_BASE_URL):
"""Hide a panel in the UI of Cytoscape.
Other panels will expand into the space.
Args:
panel_name (str): Name of the panel. Multiple ways of referencing panels is supported:
(WEST == control panel, control, c), (SOUTH == table panel... | 5e8ead9f8ca51d4629c4c4dbd605ad2257cfa147 | 3,644,011 |
def user_tickets(raffle_prize, user):
"""return the allocate ticket for user"""
return raffle_prize.allocated_tickets(user) | a29c578713664018f639088539f2404fc7a63171 | 3,644,012 |
def init_container(self, **kwargs):
"""Initialise a container with a dictionary of inputs
"""
for k, v in kwargs.iteritems():
try:
setattr(self, k, v)
except Exception as e:
# Deal with the array -> list issue
if isinstance(getattr(self, k), list) and isin... | 888f5fc1cfc2b7718b8712360f86b5fd51fd25d2 | 3,644,013 |
def optimize(nn_last_layer, correct_label, learning_rate, num_classes):
"""
Build the TensorFLow loss and optimizer operations.
:param nn_last_layer: TF Tensor of the last layer in the neural network
:param correct_label: TF Placeholder for the correct label image
:param learning_rate: TF Placeholde... | 0c1f50c3148a87206fff9473f2ecd78793aef630 | 3,644,014 |
def setIamPolicy(asset_id, policy):
"""Sets ACL info for an asset.
Args:
asset_id: The asset to set the ACL policy on.
policy: The new Policy to apply to the asset. This replaces
the current Policy.
Returns:
The new ACL, as an IAM Policy.
"""
return _execute_cloud_call(
_get_cloud_ap... | 2501565aee420cd3b66eaf204ecd756d51e30b4f | 3,644,015 |
def get_corners(n):
"""Returns corner numbers of layer n"""
end = end = (2*n + 1) * (2*n + 1)
return [end-m*n for m in range(0,8,2)] | 8d78135f13675d01fc2b6736b7c1fb1e7cf3e5f5 | 3,644,016 |
def plot_single_hist(histvals, edges, legend=None, **kwds):
""" Bokeh-based plotting of a single histogram with legend and tooltips.
**Parameters**\n
histvals: 1D array
Histogram counts (e.g. vertical axis).
edges: 1D array
Histogram edge values (e.g. horizontal axis).
legend: str
... | 24a91ed6e3653dde35a27bba26530f47ec11bcd2 | 3,644,017 |
import torch
def resnet50(alpha, beta,**kwargs):
"""Constructs a ResNet-50 based model.
"""
model = ResNet(Bottleneck, [3, 4, 6, 3], alpha, beta, **kwargs)
checkpoint = torch.load(model_dirs['resnet50'])
layer_name = list(checkpoint.keys())
for ln in layer_name:
if 'conv' in ln or 'downsample.0.weight' in ln:... | 165f0bfd357af96004edcc5d73224d8efcb98943 | 3,644,018 |
from datetime import datetime
def datetime_to_timestamp(dt, epoch=datetime(1970,1,1)):
"""takes a python datetime object and converts it to a Unix timestamp.
This is a non-timezone-aware function.
:param dt: datetime to convert to timestamp
:param epoch: datetime, option specification of start of ep... | 2fbd5b3d6a56bc04066f7aaa8d4bef7c87a42632 | 3,644,019 |
def connectivity_dict_builder(edge_list, as_edges=False):
"""Builds connectivity dictionary for each vertex (node) - a list
of connected nodes for each node.
Args:
edge_list (list): a list describing the connectivity
e.g. [('E7', 'N3', 'N6'), ('E2', 'N9', 'N4'), ...]
as_edges (b... | 58f24c6465fa1aaccca92df4d06662b0ce1e1e77 | 3,644,020 |
def get_confusion_matrix(*, labels, logits, batch_mask):
"""Computes the confusion matrix that is necessary for global mIoU."""
if labels.ndim == logits.ndim: # One-hot targets.
y_true = jnp.argmax(labels, axis=-1)
else:
y_true = labels
# Set excluded pixels (label -1) to zero, because the confusion ... | 664f08446ea25000c77a78b133fc749fbb919376 | 3,644,021 |
import socket
def init_socket():
"""Returns a fresh socket"""
return socket.socket() | 429d790f3007a357d4a14d57066d890f14f42178 | 3,644,022 |
def semitone_frequencies(fmin, fmax, fref=A4):
"""
Returns frequencies separated by semitones.
Parameters
----------
fmin : float
Minimum frequency [Hz].
fmax : float
Maximum frequency [Hz].
fref : float, optional
Tuning frequency of A4 [Hz].
Returns
-------... | b4a29dcb0ae53f2876d01f4a084d577219db1e47 | 3,644,023 |
from typing import Mapping
from typing import Any
from typing import Sequence
def dict_get_value(dict: Mapping, name: str) -> Any:
"""Gets data from a dictionary using a dotted accessor-string
:param dict: source dictionary
:param name: dotted value name
"""
current_data = dict
for chunk in n... | c77c4fbfd8677fc53510a1dfe565e3496d57f8ef | 3,644,024 |
def get_files_from_split(split):
""" "
Get filenames for real and fake samples
Parameters
----------
split : pandas.DataFrame
DataFrame containing filenames
"""
files_1 = split[0].astype(str).str.cat(split[1].astype(str), sep="_")
files_2 = split[1].astype(str).str.cat(split[0].... | 951c8e73952017db2d29b6b1e4944ddf832516e3 | 3,644,025 |
def dedupBiblioReferences(doc):
"""
SpecRef has checks in its database preventing multiple references from having the same URL.
Shepherd, while it doesn't have an explicit check for this,
should also generally have unique URLs.
But these aren't uniqued against each other.
So, if you explicitly b... | 4fbbb6eb85b1136c5addc5421ff9be083cc3429d | 3,644,026 |
def check_percent(mask_arr, row, col, sz, percent):
"""
:param mask_arr: mask数组
:param row:
:param col:
:param sz:
:param percent: 有效百分比
:return:
"""
upper_bound = mask_arr.max()
area = np.sum(mask_arr[row:row + sz, col:col + sz]) / upper_bound
if area / (sz ** 2) > percent:... | 0d84e511d6895145dc4a7f8f150ae907a4884f90 | 3,644,027 |
def find_center_pc(proj1, proj2, tol=0.5, rotc_guess=None):
"""
Find rotation axis location by finding the offset between the first
projection and a mirrored projection 180 degrees apart using
phase correlation in Fourier space.
The ``register_translation`` function uses cross-correlation in Fourier... | 4bc9a25bb6bd041d9d5cb8ae46bfd91dfa7c97ff | 3,644,028 |
def emce_comparison(nus, n_reps=100):
"""Simulation comparing ECME algorithm with M-estimates.
We compare the estimates obtained by the ECME algorithm against two Huber
M-estimates with tuning parameters 1 and 4.
Args:
nus, iter: Iterator of values for the degrees of freedom.
n_reps, i... | 1d79ae528d8bffb694e1718f037d880f46d8c597 | 3,644,029 |
import sys
def to_dot(g, stream=sys.stdout, options=None):
"""
Args:
- g (rdflib.graph): RDF graph to transform into `dot` representation
- stream (default: sys.stdout | file): Where to write the output
Returns:
- (graph): `dot` representation of the graph
"""
digraph = pr... | 6a5bf119e1c7249deddff2ce4d938daff534dba4 | 3,644,030 |
def seconds(seconds_since_epoch: int) -> date:
"""Converts a seconds offset from epoch to a date
Args:
seconds_since_epoch (int): The second offset from epoch
Returns:
date: The date the offset represents
"""
return EPOCH + timedelta(seconds=seconds_since_epoch) | 1dd1559e3f971922bad3d618ff4db8b1e0012c42 | 3,644,031 |
def check_presence(user):
"""
Gets user presence information from Slack ("active" or "away")
:param user: The identifier of the specified user
:return: True if user is currently active, False if user is away
"""
if not settings.SLACK_TOKEN:
return None
client = WebClient(token=set... | acdeae9b80613edcfbfb05ea594260d1f99473ff | 3,644,032 |
import os
def FindUpwardParent(start_dir, *desired_list):
"""Finds the desired object's parent, searching upward from the start_dir.
Searches within start_dir and within all its parents looking for the desired
directory or file, which may be given in one or more path components. Returns
the first directory i... | 7cdaa4340944178ec78d16d433440d98a26213ef | 3,644,033 |
def adjust_position_to_boundaries(positions, bounds, tolerance=DEFAULT_TOLERANCE):
"""
Function to update boid position if crossing a boundary (toroid boundary condition)
:param positions: vector of (x,y) positions
:param bounds: (xmin,xmax,ymin,ymax) boundaries
:param tolerance: optional tolerance ... | 3354a0e19d085e0e02595866deac7a035b364e58 | 3,644,034 |
def residual_mlp_layer(x_flat, intermediate_size, initializer_range=0.02, hidden_dropout_prob=0.1):
"""
:param x_flat: The attention output. It should be [batch_size*seq_length, dim]
:param intermediate_size: the hidden projection. By default this is the input_dim * 4.
in the original GPT we would retu... | 03e04c074080b54c4a8bc71a0fbef9e6e025f71f | 3,644,035 |
def _delete_project_repo(repo_name):
"""Deletes the specified repo from AWS."""
client = boto3.client('codecommit')
response = client.delete_repository(repositoryName=repo_name)
return response | 8410302fc419cbe9c13b9f73ef6af63f588ede76 | 3,644,036 |
def score_items(X, U, mu,
scoremethod='lowhigh',
missingmethod='none',
feature_weights=[]):
"""score_items(X, U, scoremethod, missingmethod, feature_weights)
Calculate the score (reconstruction error) for every item in X,
with respect to the SVD model in U and ... | 9355665670ff7b3a49d0abeacc9cfbaab8d586b1 | 3,644,037 |
def get_output_specs(output):
""" Get the OpenAPI specifications of a SED output
Args:
output (:obj:`Output`): output
Returns:
:obj:`dict` with schema `SedOutput`
"""
if isinstance(output, Report):
specs = {
'_type': 'SedReport',
'id': output.id,
... | 26617aa635fd97408e9d27e2972bcd9d7bd4340a | 3,644,038 |
def logggnfw_exact(x, x0, y0, m1, m2, alpha):
"""
exact form, inspired by gNFW potential
OverFlow warning is easily raised by somewhat
large values of m1, m2, and base
"""
base = 1. + np.exp(alpha)
x = x - x0
return np.log((base ** x) ** m1 *
(1 + base ** x) ** (m2 - m1... | f6b1c5511b2bfe337402b2342484d1b642329f00 | 3,644,039 |
import os
def get_file_size(path: str):
"""
Return the size of a file, reported by os.stat().
Args:
path: File path.
"""
return os.path.getsize(path) | f6e7dc89c1fc046f1492bad43eae8c8a14e335af | 3,644,040 |
def is_lepton(pdgid):
"""Does this PDG ID correspond to a lepton?"""
if _extra_bits(pdgid) > 0:
return False
if _fundamental_id(pdgid) >= 11 and _fundamental_id(pdgid) <= 18:
return True
return False | 086d7cebee19cfb7a91d4fc09417f168c53942de | 3,644,041 |
import os
def process_data():
"""process data"""
# prepare cur batch data
image_names, labels = get_labels_from_txt(
os.path.join(IMAGE_PATH, 'image_label.txt'))
if len(labels) < CALIBRATION_SIZE:
raise RuntimeError(
'num of image in {} is less than total_num{}'
... | 7ae058491718e0bc788c4dff35c79cbf54a4b21c | 3,644,042 |
def complex_fields_container(real_field, imaginary_field, server = None):
"""Create a fields container with two fields (real and imaginary) and only one time set.
Parameters
----------
real_fields : Field
Real :class:`ansys.dpf.core.Field` entity to add to the fields container.
imaginary_fi... | f20cee35cff2d86801446faca4e60777c3fab429 | 3,644,043 |
def get_time_slots(s : pd.Series, time_interval : str = 'daily'):
"""Convert timestamps to time slots"""
if time_interval.lower() not in (
'hourly', 'daily', 'weekly', 'monthly',
'quarterly', 'yearly'):
raise ValueError
return pd.to_datetime(s)\
.dt.to_period(time_interval[0]... | f67c076fc3f946e4b41df9d6d79dac6f19634ea5 | 3,644,044 |
def build_optimising_metaclass(
builtins=None, builtin_only=False, stoplist=(), constant_fold=True,
verbose=False
):
"""Return a automatically optimising metaclass for use as __metaclass__."""
class _OptimisingMetaclass(type):
def __init__(cls, name, bases, dict):
super(_Optimis... | 678454e3c45b0f4ccbaef77427776485ddb07815 | 3,644,045 |
def get_ensembl_id(hgnc_id):
"""Return the Ensembl ID corresponding to the given HGNC ID.
Parameters
----------
hgnc_id : str
The HGNC ID to be converted. Note that the HGNC ID is a number that is
passed as a string. It is not the same as the HGNC gene symbol.
Returns
-------
... | d815259b553c022f5400b34e5ae5f9ddaff6193e | 3,644,046 |
import torch
def predict(model, dataloader):
"""Returns: numpy arrays of true labels and predicted probabilities."""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
model.eval()
labels = []
probs = []
for batch_idx, batch in enumerate(dataloader):
... | 1e4b6e1f72127174a8bdbc693665ace8cbe8e4af | 3,644,047 |
import re
def _ProcessMemoryAccess(instruction, operands):
"""Make sure that memory access is valid and return precondition required.
(only makes sense for 64-bit instructions)
Args:
instruction: Instruction tuple
operands: list of instruction operands as strings, for example
['%eax', '(... | 922489dca706ba5c88132f9676c7b99bfc966947 | 3,644,048 |
def minimizeMeshDimensions(obj, direction, step, epsilon):
"""
Args:
obj:
direction:
step:
epsilon:
Returns:
"""
stepsum = 0
while True:
before, after = compareOrientation(obj, direction * step)
if before < after:
# bpy.ops.transform.rot... | ba1f7e2cf66e6665042307b9fe50c7728d68157d | 3,644,049 |
from importlib import import_module
def gimme_dj(mystery_val: int, secret_val: int) -> str:
"""Play that funky music."""
# If youre worried about what this is doing, and NEED TO KNOW. Check this gist:
# https://gist.github.com/SalomonSmeke/2dfef1f714851ae8c6933c71dad701ba
# its nothing evil. just an i... | e14680d5a73e3ea3a3651bbeccd8af18a07a5907 | 3,644,050 |
def pluecker_from_verts(A,B):
"""
See Hartley & Zisserman (2003) p. 70
"""
if len(A)==3:
A = A[0], A[1], A[2], 1.0
if len(B)==3:
B = B[0], B[1], B[2], 1.0
A=nx.reshape(A,(4,1))
B=nx.reshape(B,(4,1))
L = nx.dot(A,nx.transpose(B)) - nx.dot(B,nx.transpose(A))
return Lmat... | 7af9f779e1c00ffeee035bc76a8333d36e2ed5be | 3,644,051 |
def MAP_score(source_id, target_labels, prediction):
""" Function to compute the Mean Average Precision score of a given ranking.
Args:
source_id (array): Array containing the source_id of our given queries.
target_labels (array): Array containing the target labels of our query-docu... | ad279df4b28bceff52af98d6f7e71f34b564db55 | 3,644,052 |
def get_model_config(model):
"""Returns hyper-parameters for given mode"""
if model == 'maml':
return 0.1, 0.5, 5
if model == 'fomaml':
return 0.1, 0.5, 100
return 0.1, 0.1, 100 | dcdfb3c00026a172b22611ad3203a7c32d8e59d7 | 3,644,053 |
import pandas
import os
def split_train_test_cresus_data(tables, outfold, ratio=0.20, fLOG=fLOG): # pylint: disable=W0621
"""
Splits the tables into two sets for tables (based on users).
@param tables dictionary of tables,
@see fn prepare_cresus_data
@pa... | 7c496a7016fc264567dc54743c923c13821ebb38 | 3,644,054 |
def find_longest_substring(s: str, k: int) -> str:
"""
Speed: ~O(N)
Memory: ~O(1)
:param s:
:param k:
:return:
"""
# longest substring (found)
lss = ""
# current longest substring
c_lss = ""
# current list of characters for the current longest substring
c_c = []
... | 78936d140ea1e54945c6b4dd849b38f0c5604a36 | 3,644,055 |
def _fixTool2(scModel,gopLoader):
"""
:param scModel:
:param gopLoader:
:return:
@type scModel: ImageProjectModel
"""
def replace_tool(tool):
return 'jtui' if 'MaskGenUI' in tool else tool
modifier_tools = scModel.getGraph().getDataItem('modifier_tools')
if modifier_tools ... | 3eb3bf8a47514a28c2e699a2eeefb084f9f7923b | 3,644,056 |
from io import StringIO
def mol_view(request):
"""Function to view a 2D depiction of a molecule -> as PNG"""
my_choice = request.GET['choice'].split("_")[0]
try:
mol = Chem.MolFromSmiles(str(InternalIDLink.objects.filter(internal_id=my_choice)[0].mol_id.smiles))
except IndexError:
mol ... | 91f202b34fe63c8b89e1250bb54222120410f9c2 | 3,644,057 |
def rotation_matrix_about(axis, theta):
"""Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
Taken from: https://stackoverflow.com/a/6802723
"""
if np.shape(axis) != (3,):
raise ValueError("Shape of `axis` must be (3,)!")
scala... | f65fdc6e40ad7712521fbb6db662827401f82aca | 3,644,058 |
def zc_rules():
"""catch issues with zero copy streaming"""
return (
case("SSTableReader"),
rule(
capture(
r"Could not recreate or deserialize existing bloom filter, continuing with a pass-through bloom filter but this will significantly impact reads performance"
... | e4847d95b0565d5cb9213cfca9e8e3f28657041c | 3,644,059 |
import re
def name_convert_to_camel(name: str) -> str:
"""下划线转驼峰"""
contents = re.findall('_[a-z]+', name)
for content in set(contents):
name = name.replace(content, content[1:].title())
return name | 109a1035a3efa98861b6a419206823b1114268e2 | 3,644,060 |
def triangle_as_polynomial(nodes, degree):
"""Convert ``nodes`` into a SymPy polynomial array :math:`B(s, t)`.
Args:
nodes (numpy.ndarray): Nodes defining a B |eacute| zier triangle.
degree (int): The degree of the triangle. This is assumed to
correctly correspond to the number of `... | 20c0bc7021673ac375018a387926ae25bdfda2e5 | 3,644,061 |
import decimal
def as_decimal(dct):
"""Decodes the Decimal datatype."""
if '__Decimal__' in dct:
return decimal.Decimal(dct['__Decimal__'])
return dct | d25b3ff73d7559a9018666d5f2cd189e6503a268 | 3,644,062 |
def input_layer(features,
feature_columns,
weight_collections=None,
trainable=True,
cols_to_vars=None,
cols_to_output_tensors=None):
"""Returns a dense `Tensor` as input layer based on given `feature_columns`.
Generally a single exampl... | 89fda325ec1afb98a772d7238386471bf4484141 | 3,644,063 |
def log_sum_exp(x):
"""Utility function for computing log_sum_exp while determining
This will be used to determine unaveraged confidence loss across
all examples in a batch.
Args:
x (Variable(tensor)): conf_preds from conf layers
"""
log_reduce_sum = P.ReduceSum()
log = P.Log()
e... | 72a39a81fa3959e73c096732a86e843b5330e27d | 3,644,064 |
import os
def data_dir():
"""
:return: data directory in the filesystem for storage, for example when downloading models
"""
return os.getenv('CNOCR_HOME', data_dir_default()) | 196e30d66c7598e10af93268d6de2c1192132b3c | 3,644,065 |
def prepareRepoCharts(url, name, auths):
"""
NOTE: currently not support git
"""
charts_info, charts_info_hash = _prepareHelmRepoPath(url, name, auths)
return charts_info, charts_info_hash | 7d2a6af1cae019020cd0921155fcdc749585d32c | 3,644,066 |
def num_ini_spaces(s):
"""Return the number of initial spaces in a string.
Note that tabs are counted as a single space. For now, we do *not* support
mixing of tabs and spaces in the user's input.
Parameters
----------
s : string
Returns
-------
n : int
"""
ini_spaces = ... | 9870aa42020b56f765f0ed74f73edda21b1786b1 | 3,644,067 |
def make_filename_template(schema, **kwargs):
"""Create codeblocks containing example filename patterns for a given
datatype.
Parameters
----------
schema : dict
The schema object, which is a dictionary with nested dictionaries and
lists stored within it.
kwargs : dict
K... | bb1d8eb776d8e248ca7fb67167594639a02c92cb | 3,644,068 |
import os
def lambda_handler(event, context):
"""
Generate a pre-signed URL that allows a save file to be uploaded to S3 in the player's specified save slot. If the
slot is new, will verify that MAX_SAVE_SLOTS_PER_PLAYER has not been reached.
Parameters:
Request Context:
custom:gk_user_i... | f4202aaad5bdd91779eb0ee72780ba0cf1fe330f | 3,644,069 |
def getLanguageLevel() -> dict:
"""
Takes the user input and returns the found documents as dictionary.
:text: String
:language: String
:return: Dictionary
"""
text: str = request.params.get('text')
language: str = request.params.get('language')
# check API Key
if str(request.pa... | 967b4244f7406c82715bdfb112cd82c652c9c68e | 3,644,070 |
import oci.exceptions
def list_networks(**kwargs):
"""Lists all networks of the given compartment
Args:
**kwargs: Additional options
Keyword Args:
public_subnet (bool): Whether only public or private subnets should be
considered
compartment_id (str): OCID of the pare... | 32a816b595d45102a393be8a548f48414509f865 | 3,644,071 |
def ed_affine_to_extended(pt):
"""Map (x, y) to (x : y : x*y : 1)."""
new_curve = EllipticCurve(pt.curve, ED_EXT_HOM_PROJ, Edwards_ExtProj_Arithm)
return new_curve((pt.x, pt.y, pt.x * pt.y, new_curve.field(1))) | ee949c7c0487fb580d79764e3f0c10d2a2080943 | 3,644,072 |
import os
import shutil
def _download(path, url, archive_name, hash_, hash_type='md5'):
"""Download and extract an archive, completing the filename."""
full_name = op.join(path, archive_name)
remove_archive = True
fetch_archive = True
if op.exists(full_name):
logger.info('Archive exists (%... | 3df4c134734e62474ed4a36d710cc9140c267329 | 3,644,073 |
import joblib
def do_setup(experiment_folder, path_to_additional_args):
""" Setup Shell Scripts for Experiment """
additional_args = joblib.load(path_to_additional_args)
# Setup Data
logger.info("Setting Up Data")
data_args = setup_train_test_data(experiment_folder, **additional_args)
# Setu... | 9489b5abab6335de4c5909d718b5ccb3bcc0f3c7 | 3,644,074 |
import requests
def getorgadmins(apikey, orgid, suppressprint=False):
"""
Args:
apikey: User's Meraki API Key
orgid: OrganizationId for operation to be performed against
suppressprint:
Returns:
"""
__hasorgaccess(apikey, orgid)
calltype = 'Organization'
geturl = '{... | 640ca97bf7213b2b0e24190b7f1b6658c53332b6 | 3,644,075 |
def calc_recall(TP, FN):
"""
Calculate recall from TP and FN
"""
if TP + FN != 0:
recall = TP / (TP + FN)
else:
recall = 0
return recall | 8f3513e11f8adad111eee32740c271aad31fbe28 | 3,644,076 |
def lookup_last_report_execution(job_type, work_ids=None):
"""Lookup in the database when the report/job chunk last executed
This is the expected table schema from the database (id and timestamp columns
are omitted),
---------------------------------------------------
| work_id | history ... | bcc7715d416820dcc9f065b952e0a751255c9929 | 3,644,077 |
def get_course_goal_options():
"""
Returns the valid options for goal keys, mapped to their translated
strings, as defined by theCourseGoal model.
"""
return {goal_key: goal_text for goal_key, goal_text in GOAL_KEY_CHOICES} | 6f8fc2bd812a216abcff6a82107cf28bfc2fcbf4 | 3,644,078 |
def to_dataframe(y):
"""
If the input is not a dataframe, convert it to a dataframe
:param y: The target variable
:return: A dataframe
"""
if not isinstance(y, pd.DataFrame):
return pd.DataFrame(y)
return y | 1fc302b1acb264bce5778c9c2349100f799da397 | 3,644,079 |
def url_equal(first, second, ignore_scheme=False, ignore_netloc=False, ignore_path=False, ignore_params=False,
ignore_query=False, ignore_fragment=False):
"""
Compare two URLs and return True if they are equal, some parts of the URLs can be ignored
:param first: URL
:param second: URL
... | caea2185db83c5938f48e8d2de432c5e74540014 | 3,644,080 |
def test_struct(n: cython.int, x: cython.double) -> MyStruct2:
"""
>>> test_struct(389, 1.64493)
(389, 1.64493)
>>> d = test_struct.__annotations__
>>> sorted(d)
['n', 'return', 'x']
"""
assert cython.typeof(n) == 'int', cython.typeof(n)
if is_compiled:
assert cython.typeof(x... | 1bf5e97719d80c8327c44bfea66f7ef26b3f7400 | 3,644,081 |
def build_document(json_schema: dict) -> list:
"""
Returns a list of lines to generate a basic adoc file, with the format:
Title
A table for the data properties
A table for the data attributes and nested attributes if any
"""
lines = []
"""
Title and description of schema
""... | d92038392d23047130c6f981cb848f3f7ca9dd19 | 3,644,082 |
import os
def remove_potential_nonlipids_bad_esi_mode():
"""
remove_potential_nonlipids_bad_esi_mode
description:
ESI mode of the dataset is not 'pos' or 'neg'
returns:
(bool) -- test pass (True) or fail (False)
"""
dset = Dataset(os.path.join(os.path.dirname(__file__), 'real_data_1.cs... | 1b675faf7e90d5bf2695d6e64e8df4ca353c0850 | 3,644,083 |
def is_oasis_db():
""" Is this likely an OASIS database? Look at the table names to see
if we have the more specific ones.
Return "yes", "no", or "empty"
"""
expect = ['qtvariations', 'users', 'examqtemplates', 'marklog', 'qtattach',
'questions', 'guesses', 'exams', 'qtemplate... | 330da79c63afe4905c9469e54d61d5de6a8fa575 | 3,644,084 |
def make_segment(segment, discontinuity=False):
"""Create a playlist response for a segment."""
response = []
if discontinuity:
response.append("#EXT-X-DISCONTINUITY")
response.extend(["#EXTINF:10.0000,", f"./segment/{segment}.m4s"]),
return "\n".join(response) | 8419b100409934f902c751734c396bc72d8a6917 | 3,644,085 |
def seq_aggregate_with_reducer(x, y):
"""
Sequencing function that works with the dataframe created by get_normal_frame
:param x:
:param y:
:return:
"""
res = []
for i in range(0, len(x)):
res.append((x[i][0], x[i][1], get_aggregation_func_by_name(x[i][0])(x[i][2], y[i][2])))
... | 6faed81fd925656c2984e9d78df3b88e98fcb035 | 3,644,086 |
from typing import Any
def from_dicts(key: str, *dicts, default: Any = None):
"""
Returns value of key in first matchning dict.
If not matching dict, default value is returned.
Return:
Any
"""
for d in dicts:
if key in d:
return d[key]
return ... | 508febc48fd22d3a23dc0500b0aa3824c99fdbc3 | 3,644,087 |
def time_in_words(h, m):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/the-time-in-words/problem
Given the time in numerals we may convert it into words, as shown below:
----------------------------------------------
| 5:00 | -> | five o' clock |
| 5:01 | -> | one m... | 85f2247f01df36ef499105a9940be63eee189100 | 3,644,088 |
def majorityElement(nums):
"""超过三分之一的数,最多不超过两个数"""
num1, num2 = -1, -1
count1, count2 = 0, 0
for i in range(len(nums)):
curNum = nums[i]
if curNum == num1:
count1 += 1
elif curNum == num2:
count2 += 1
elif count1 == 0:
num1 = curNum
... | ef71fa445c3bc16bbaf79a1ab4e9548125e71b7b | 3,644,089 |
def calcDensHeight(T,p,z):
"""
Calculate the density scale height H_rho
Parameters
----------
T: vector (float)
temperature (K)
p: vector (float) of len(T)
pressure (pa)
z: vector (float) of len(T
height (m)
Returns
-------
Hb... | c45d47d4f3dffe0e1706f979a9a6eb5028c7b775 | 3,644,090 |
import os
def Signal_figure(name,I,mask):
"""Plots a figure designed to show the influences of the image parameters and creates a .png image of it.
Parameters
----------
name: string
Desired name of the image.
I: array
MRI image.
mask: array
Region of inter... | c294d8c9f167935b6402e1573acb68ed6c23fbc2 | 3,644,091 |
def load_many_data(filenames, clean=True, first_seconds_remove=2, bandpass_range=(5, 50)):
"""
Loads several files and cleans data if clean is True. Returns a concatenated set of data (MNE object).
"""
# TODO: check for matching channels and other errors
raw_data = []
if filenames is None:
... | b9b8e5351419642b7b3e8b462df42e171a3564ce | 3,644,092 |
import re
def extract_push_target(push_target: str):
"""
Extract push target from the url configured
Workspace is optional
"""
if not push_target:
raise ValueError("Cannot extract push-target if push-target is not set.")
match_pattern = re.compile(
r"(?P<http_scheme>https|http)... | 3fe11ac218c0cfc7c6211cfe76fd11bd248c4588 | 3,644,093 |
import os
def main(global_config, **settings):
"""This function returns a Pyramid WSGI application."""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
authn_policy = AuthTktAuthenticationPolicy('sosecret', callback=groupfinder,
... | 5ba2332214a77b485bc3f72d01578ff1299d6b52 | 3,644,094 |
def dish_gain(radius, freq):
"""
Dish radar gain.
Inputs:
- radius [float]: Dish radius (m)
- freq [float]: Transmit frequency (Hz)
Outputs:
- g: Gain
"""
return 4*pi**2*radius**2/wavelen(freq)**2 | a20d963f9acc839a811aefaa942aaeaedce0689c | 3,644,095 |
import os
def _collect_files(gold_dir, system_dir, limit):
"""Return the list of files to run the comparison on."""
gold_files = os.listdir(gold_dir)
system_files = os.listdir(system_dir)
# don't assume the directory content is the same, take the intersection
fnames = sorted(list(set(gold_files).i... | a940d6f958fe770580cc9a9a3327579e5f1b2633 | 3,644,096 |
def center_img(img, size=None, fill_value=255):
"""
center img in a square background
"""
h, w = img.shape[:2]
if size is None:
size = max(h, w)
shape = (size, size) + img.shape[2:]
background = np.full(shape, fill_value, np.uint8)
center_x = (size - w) // 2
center_y = (size ... | 838d6185230fbb8184925a31e0f3334dc4bda627 | 3,644,097 |
def concat_files(*files):
"""
Concat some files together. Returns out and err to keep parity with shell commands.
Args:
*files: src1, src2, ..., srcN, dst.
Returns:
out: string
err: string
"""
out = ''
err = ''
dst_name = files[-1]
sources = [files[f] for f ... | 101c37e5b3955c153c8c2210e7575a62341c768a | 3,644,098 |
def distribution_quality( df, refdata, values, ascending, names, fig):
"""Locate the quantile position of each putative :class:`.DesingSerie`
in a list of score distributions.
:param df: Data container.
:type df: :class:`~pandas.DataFrame`
:param grid: Shape of the grid to plot the values in the f... | 33a762ed659df4767b5a05c5005ca4d1213e7d0a | 3,644,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.