content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def norm(x):
"""Calculate the Euclidean norm of a vector x."""
return np.sqrt(np.dot(x, x)) | c09ff946ed6248e4bf57b87f96ec4ad54ce4cdc8 | 34,923 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_palo_alto_wildfire package"""
reload_params = {"package": u"fn_palo_alto_wildfire",
"incident_fields": [],
"action_fields": [],
"function_params": [u"artifact_id", u"artifact... | 554f93deb50664db00ef59a67f76a979779cb9c9 | 34,924 |
def min_number_in_rotated_array(r_nums):
"""
:param r_nums:rotated arrat
:return: min number
"""
if not r_nums:
return None
left = 0
right = len(r_nums)-1
while left < right:
mid = (left + right) // 2
if r_nums[mid] == r_nums[right] == r_nums[left]:
ri... | 97cd37fb040a38b6c52cf816d29b97aa36c3c338 | 34,925 |
def scatter_columns(A):
"""
Performs the reverse operation as gather_columns. Thus, each prow receives
the prow'th row-slice of A.
If A had local shape(grid[0] * m_l, n_l), thre result has local shape
(m_l, n_l). If the number of local rows in A is not an even multiple
of grid[0] an error is thrown.
"""
... | 7619491aa08ee172aa77c15b44caa889b690cc54 | 34,927 |
def digitos(valor):
"""Resulta em uma string contendo apenas os dígitos da string original."""
return ''.join([d for d in valor if d.isdigit()]) | dc742d871efefa8067f33c95cc277963e3cfa201 | 34,928 |
def from_Point(ros_pt):
"""From ROS Point to Klamp't point"""
return [ros_pt.x,ros_pt.y,ros_pt.z] | 34d83ea0266883679c7e2f51c4eb555e189940d4 | 34,929 |
def greedy():
"""A greedy distribution."""
def sample_fn(key: ArrayLike, preferences: ArrayLike):
probs = _argmax_with_random_tie_breaking(preferences)
return _categorical_sample(key, probs)
def probs_fn(preferences: ArrayLike):
return _argmax_with_random_tie_breaking(preferences)
def log_prob_fn... | b99c4c2d410be42be33c38633b4b998e5db37be7 | 34,930 |
def GibbsSampler(dna_list, k, t, N, mode = 'v1', repeat=20):
"""Input a list of Dna sequence, out put the best set of motifs.
The motifs are generated by Gibbs sampling and optimized by comparing
hamming or entropy scores. Mode 'v1' returns kmer by weighted probability;
mode v2 returns the most probabl... | 767597df8b23baf09666009a90452d9d51a814fb | 34,931 |
def read_input_h5(h5):
"""
Reads astra inpu5 from h5
See: write_input_h5
"""
d = {}
for g in h5:
d[g] = dict(h5[g].attrs)
# Convert to native types
for k, v in d[g].items():
d[g][k] = native_type(v)
return d | 1bcf29418df9fcd4d49bb86e32c47febf2bb2403 | 34,932 |
import math
def to_half_life(days):
"""
Return the constant [1/s] from the half life length [day]
"""
s= 24 * 3600 * days
return -math.log(1/2)/s | 7224be1e3e460336493d49c3f2b3d8932341f575 | 34,933 |
def fit_on_batch(model, x, y, loss_fn, optimizer, metrics=["loss", "acc"]):
"""Trains the model on a single batch of examples.
This is a training function for a basic classifier. For more complex models,
you should write your own training function.
NOTE: Before you call this, make sure to do `model.tr... | 87fa7342bdf84a382fdcce5edde9458bec7bb4c8 | 34,934 |
def get_longest_common_substring(text_a, text_b):
"""Find longest common subtring."""
# isjunk=None, a='', b='', autojunk=True
seqMatch = SequenceMatcher(None, text_a, text_b, autojunk=False)
#Also:
# autojunk = True (default)
# isjunk = None (deafult), same as: lambda x: False;
# or return... | 9b4c75525aa071892aba11919aa59dae2e4a43de | 34,935 |
from typing import OrderedDict
def from_group(group, time_index=False, absolute_time=False, scaled_data=True):
"""
Converts a TDMS group object to a DataFrame. DataFrame columns are named using the channel names.
:param group: Group object to convert.
:param time_index: Whether to include a time inde... | ba2d049a8c3076e02c7a9bbb8019ef901957aa7a | 34,936 |
import time
def _bq_harness_with_result(sql, do_batch):
"""
Handles all the boilerplate for running a BQ job
"""
client = bigquery.Client()
job_config = bigquery.QueryJobConfig()
if do_batch:
job_config.priority = bigquery.QueryPriority.BATCH
location = 'US'
# API request - s... | 8546498d7e4553e5c0c74f7515db5c75ef4338ad | 34,938 |
def create_workflow(name=None, namespace=None, bucket=None, **kwargs):
"""
Args:
name: Name to give to the workflow. This can also be used to name
things associated with the workflow.
"""
builder = Builder(name=name, namespace=namespace, bucket=bucket, **kwargs)
return builder... | 58980a10d3ebe858547c71efc65c369a78373016 | 34,939 |
def validadeInequalityFilter(inequality_filters, entity):
"""Check if a entity attends all the inequality filters inputed"""
check = True
# Iterated on every the inequality filter informed
for f in inequality_filters:
if hasattr(entity, f["field"]): # Check if the entity has the attribute
... | 374174dc4b9aac720c74fdf83b55321ed6525a7b | 34,940 |
def flops_metric_map(end_points, mean_metric, total_name='Total Flops'):
"""Assembles flops-count metrics into a map for use in tf.contrib.metrics."""
metric_map = {}
total_flops = tf.to_float(end_points['flops'])
flops_map = moments_metric_map(total_flops, total_name, mean_metric,
delimiter='/', do_shift... | fd18df2d4f442e8afc9902760a864a479eefe7c5 | 34,942 |
def _is_false2(x):
"""Non-vectorized helper function"""
return (x in ("False", "false", "0") or not bool(x)) and not _is_na2(x) | 972983f25474017065128023de1011f40c319866 | 34,943 |
import re
def process_document(document, context_size, dictionary, fixed_dictionary=False):
"""
Given a dictionary, extract the tuples of words of length equal to
context_size. Each word is represented by a unique integer number.
If fixed_dictionary is True, only take consecutive tuples of words
... | 3f3531faa8c9aad63ac798e9c3e3a06230d5ecf7 | 34,944 |
def list_buckets():
"""
Lists available buckets.
:return: list of available buckets
Amazon (2019) s3-python-example-list-buckets.py
Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
"""
# create s3 client
s3 = boto3.client('s3')
# call client and get lis... | e669d1137d43ffc62d474a36be6e64c5b02eca2a | 34,945 |
def site_time_zone(request, registry, settings):
"""Expose website URL from ``tm.site_time_zone`` config variable to templates.
By best practices, all dates and times should be stored in the database using :term:`UTC` time. This setting
allows quickly convert dates and times to your local time.
Exampl... | 40d3314d35fde3d77a4e2f5fe441eee499f8de03 | 34,946 |
def qubic_spline_coeff(x_nodes, y_nodes):
"""Here underscored variables are related to the matrix equation,
whereas normal ones stand for the spline coefficients
"""
polynomials_num = len(x_nodes) - 1
coeffs = np.zeros((polynomials_num, 3))
hs = (x_nodes - np.roll(x_nodes, 1))[1:]
ys = (y_no... | 95d1f50d638919355acbe21d2564ab7a37a4b920 | 34,947 |
from bs4 import BeautifulSoup
import itertools
def load_C2O(xml_file):
"""Load a C2O decision model.
See http://www.jku.at/isse/content/e139529/e126342/e126343 for
information about the C2O (Configurator 2.0) tool.
Arguments:
xml_file: Path to a C2O XML file.
Returns:
A tuple wi... | b708e94d6a29829d0df775f784ad7070aa663edc | 34,948 |
def contact_infectivity_asymptomatic_40x50():
"""
Real Name: b'contact infectivity asymptomatic 40x50'
Original Eqn: b'contacts per person normal 40x50*infectivity per contact'
Units: b'1/Day'
Limits: (None, None)
Type: component
b''
"""
return contacts_per_person_normal_40x50() * i... | 63d1d87a35bc2eafa64b3b22993f388ce617c3b4 | 34,949 |
def freezeclass(cls):
""" Decorator to freeze a class."""
cls.__frozen = False
def frozensetattr(self, key, value):
if self.__frozen and not hasattr(self, key):
print("Class {} is frozen. Cannot set {} = {}"
.format(cls.__name__, key, value))
else:
... | 58fd3754c93dfcfa3aeb8b7ed722cd7d4bfd307e | 34,950 |
def gsc_url_keyword(prop, start, end, query, url):
"""Return position, clicks & impressions from GSC for keyword for URL."""
#API Not adapted to Pipulate yet
request = {
"startDate": start,
"endDate": end,
"dimensions": [
"query",
"page"
],
"dimensionFilterGrou... | 3fa1993e73cf8672eef232a7de12c6db1914ca51 | 34,951 |
def zerofill_net(input_size=(640, None, 1), **dummy_kwargs):
"""A net that performs a simple zero-filled reconstruction
Parameters:
input_size (tuple): the size of your input kspace
Returns:
keras.models.Model: the zerofill net model, compiled
"""
# shapes
mask_shape = input_size[:-1]
... | bde693f37097c797c8a2344ef8f196241e619147 | 34,952 |
def __useless_contour(shape, detected, last_cont,center,angle):
"""
Erase the useless contours, center, and angle.
Contours, center, and angle are erased if the shape type is ALL, PARTIAL or UNKNOWN.
Parameters
----------
shape : Shape
The shape we want to detect
detected : Shape
... | 6daa7add5ae79222853600d3e7e7f406a2d4c37e | 34,953 |
def add_b(_rb):
""" Add for Baselines
"""
def add(e):
for i in range(e["obs"].shape[0]):
_rb.add(obs_t=e["obs"][i],
action=e["act"][i],
reward=e["rew"][i],
obs_tp1=e["next_obs"][i],
done=e["done"][i])
ret... | 1b2d6bb94958a00a5c43e0b601f4999b0271f932 | 34,954 |
def get_ncfile(fname='cmip5.CSIRO-Mk3-6-0.nc'):
""" Return one netCDF file
"""
return join(get_datadir(),fname) | 1638eaa0519ac4415ea114dc6abdb760f951f3d5 | 34,955 |
def generate_complete_path(filename:str, main_folder="./temp/", subfolders='', file_extension = ".png", save_files=True):
"""
Function to create the full path of a plot based on `name`. It creates all the subfolders required to save the final file.
If `save_files=False` returns `None`, useful to control fro... | b97e7531088688d72ef3a248abedcfef3a054394 | 34,956 |
def realm_from_principal(principal):
"""
Attempt to retrieve a realm name from a principal, if the principal is fully qualified.
:param principal: A principal name: user@DOMAIN.COM
:type: principal: str
:return: realm if present, else None
:rtype: str
"""
if '@' not in principal:
... | 1880fef7b4383edc6f2ccd94958200686d500e0c | 34,957 |
from typing import List
import torch
def patch_batchnorm(module: nn.Module) -> List:
"""Patch all batchnorm instances (1d, 2d, 3d, sync_bn, etc.) of a module
so that they don't track running stats when torch.no_grad() is enabled.
This is important in activation checkpointing to ensure stats are tra... | d1456d48db5f2016716aaaa4f87f2eb77e4dcd43 | 34,958 |
import six
def _joined_names_column(df):
"""
Join data from all name columns into a single column.
"""
return df.apply(
lambda row: ','.join(set([
six.text_type(n)
for n in [row['main_name'], row['asciiname'], row['alternatenames']]
if n and n is not np.nan
... | d563971403758035bf9c57442a3d99c246f2fb92 | 34,960 |
def skip(
num_input_channels=2, num_output_channels=3, num_channels_down=[16, 32, 64, 128, 128],
num_channels_up=[16, 32, 64, 128, 128],
num_channels_skip=[4, 4, 4, 4, 4], filter_size_down=3,
filter_size_up=3, filter_skip_size=1, need_sigmoid=True, need_bias=True,
pad='zero', ups... | 4c26a931d701f1cfb439a835c1fe628569bbc24f | 34,961 |
def validate_kml(possible_files):
"""Validate uploaded KML file and a possible image companion file
KML files that specify vectorial data typers are uploaded standalone.
However, if the KML specifies a GroundOverlay type (raster) they are
uploaded together with a raster file.
"""
kml_file = [
... | e5389c7b3b9972757fb44a5c2e29af4aaede1618 | 34,962 |
import base64
def mailform():
"""Sample form for sending email via Microsoft Graph."""
# read user profile data
user_profile = MSGRAPH.get('me/', headers=request_headers()).data
user_name = user_profile['displayName']
# get profile photo
photo_data, _, profile_pic = profile_photo(client=MSGR... | e9180515b84e7f012aef576e123ea08fba3aefda | 34,963 |
def _global_query_(included_interviews=None, included_globals=None, client_as_numeric=True, exclude_reliability=True):
"""
Constructs the globals query for session-level datasets
:param included_interviews: iterable of str specifying names of interviews to include
:param included_globals:
:param cli... | dca8599fc7625f4f8a2db5321c32666b6b384c02 | 34,964 |
def basic_detokenizer(tokens):
"""Reverse the process of the basic tokenizer below."""
result = []
previous_nospace = True
for t in tokens:
if is_char(t):
result.append(t[_CHAR_MARKER_LEN:])
previous_nospace = True
elif t == _SPACE:
result.append(" ")
previous_nospace = True
... | 073a388a3a7f2133457e9c7a61a499b830d59760 | 34,965 |
def get_task_state(exit_code):
"""Interprets the exit_code and return the corresponding task status string
Parameters
----------
exit_code: int
An integer that represents the return code of the task.
Returns
-------
A task status string corresponding to the exit code.
"""
i... | 99837d42586ffacc2d2b1e8dc938add185bc0e04 | 34,967 |
def filtertime(timestamp, interval):
"""Check if timestamp is between timestamp_range - (time1,time2)
Args:
timestamp --> UNIX timestamp value.
interval --> `Tuple` of 2 UNIX timestamp values.
Returns:
`bool` --> True/False
"""
T0, T1 = interval
if (timestamp <= T1) an... | 72fe1aa9ed01e59ad7bbe5299b4c21272fab7354 | 34,968 |
def is_dataframe(value):
"""
Check if an object is a Spark DataFrame
:param value:
:return:
"""
return isinstance(value, DataFrame) | 954276a168586d7cd19846575d239a82083d3f9f | 34,969 |
from typing import Type
from typing import Dict
def reverse_enum(enum_to_reverse: Type[SMOOTHIE_GCODE]) -> Dict:
"""
Returns dictionary with keys and values switched from passed Enum
:param enum_to_reverse: The Enum that you want to reverse
:return: Reversed dictionary
"""
# I don't know what ... | 4dbb65905d2441089eb989b28733b6f4c4e0b529 | 34,970 |
def install_npm(path=None, build_dir=None, source_dir=None, build_cmd='build', force=False):
"""Return a Command for managing an npm installation.
Note: The command is skipped if the `--skip-npm` flag is used.
Parameters
----------
path: str, optional
The base path of the node package. De... | dd99c1a80f3fe3228d08c4ffad0efaf450c35aed | 34,971 |
from typing import Iterable
from typing import List
from typing import Tuple
from typing import Counter
def group_Counter(trip: Iterable[Leg]) -> List[Tuple[int, int]]:
"""Group legs into bins with distances 5 nm or less.
>>> trip = [ ('s1', 'e1', 1), ('s4', 'e4', 4.9), ('s5', 'e5', 5), ('s6', 'e6', 6)]
... | 51cf9dac6e25a4c5c3666a5ad60169304759d7c7 | 34,972 |
import time
def run_deduper(deduper, data_frame, settings_file, training_file, recall_weight = 1):
"""
Given a deduper object and a dataset, this function trains the model and
predicts which records are duplicates.
depends:
dedupe as dd
pandas as pd
time
params:
d... | 918969cf37dc948ab88e19e7239873da384bafa2 | 34,973 |
def _get_file_preferred_suffix() -> tuple:
"""Based on ontologia/core.lkg.yml + env variable LANGUAGE, build preferred
user language
Returns:
tuple: the result of file sufisex
"""
userpref_suffix = []
core_suffix = CORE_LKG['fs']['hdp']['base']
userlangs_upper = get_language_user_... | 2bb2c3a7d2543d284203467d93ea4d3c0cfedbd3 | 34,974 |
def fatorial(n, show=False):
"""
-> Call
:param n:
:param show:
:return:
"""
f = 1
for c in range (n, 0, -1):
if show:
print(c, end='')
if c>1:
print(' x ', end='')
else:
#print(f'{c} X ')
print(' = '... | edc42b1269799716d90896cdada721c33d156503 | 34,975 |
import uuid
def integrate_whole(payload, org, out_uuid, group):
"""integrates payload into whole of profile, returns dict"""
if group:
in_uuid = str(uuid.uuid4())
nested = {"PayloadContent": payload,
"PayloadEnabled": True,
"PayloadIdentifier": 'SparkleDisab... | b08cab03f0a1e3a2b74110a7829f6fc6d736d0f4 | 34,976 |
from typing import List
def search_hospitals(request_input: RequestInput, db_session) -> List[dict]:
"""
Search hospitals based on requested items. Sort them by nearest location
:param request_input: RequestInput
:param db_session: DB session
:return: List of Hospital dictionaries
"""
# Se... | 22dde6acb46fcc03e2cf6f2ef56fca05a2b4090b | 34,977 |
def get_inverse_metric():
"""Computes and returns the inverse metric
Sets the inverse metric variable, so that DendroSym knows how to compute
various derived variables. This should be done early on in the
generating script. It requires the metric to already be defined.
Returns
-------
symp... | da6399366b0b4096065dcb8ea8e2dd5f95555432 | 34,978 |
def add_towers_4G_km2_sheet(ws, cols, lnth):
"""
"""
for col in cols:
cell = "{}1".format(col)
ws[cell] = "=Towers!{}".format(cell)
for col in cols[:2]:
for i in range(1, lnth):
cell = "{}{}".format(col, i)
ws[cell] = "=Towers!{}".format(cell)
for c... | 1fe86a6ddd210c13d3e92f68a1deb9b41375d14b | 34,979 |
from typing import List
from typing import Dict
def get_all_netting_channel_events(
chain: BlockChainService,
token_network_address: Address,
netting_channel_identifier: ChannelID,
contract_manager: ContractManager,
from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,
... | bcaf2a96db7a95c3660abcc7daac4a448baad50d | 34,980 |
from typing import List
def custom_extractors(
eval_shared_model: tfma.MaybeMultipleEvalSharedModels,
eval_config: tfma.EvalConfig,
tensor_adapter_config: tensor_adapter.TensorAdapterConfig,
) -> List[tfma.extractors.Extractor]:
"""Returns default extractors plus a custom prediction extractor."""
pred... | a6efc2c15bbb6b437710d79a3b22174c19eb1083 | 34,981 |
def custom_detrending(flc):
"""Wrapper"""
f = flc.flux[np.isfinite(flc.flux)]
if np.abs(f[0]-f[-1])/np.median(f) > .2:
print("Do a coarse spline interpolation to remove trends.")
flc = fit_spline(flc, spline_coarseness=12)
flc.flux[:] = flc.detrended_flux[:]
# Iterativel... | 534e0881ccab91811128f1e7f109460321f98937 | 34,982 |
import random
def summon_blocks(board):
"""Place 1-8 circles in random places on the speed board"""
for _ in range(random.randint(1, 8)):
x = random.randint(0, 4)
y = random.randint(0, 4)
while board[x][y] != 'g':
x = random.randint(0, 4)
y = random.randint(0, 4)
board[x][y] = 'b'
return board | 0cfa703b6451e44ea8688561bc857ac70f560c90 | 34,983 |
from typing import List
from typing import Tuple
def three_sum_brute_force(array: List[int], target: int) -> Tuple[int, int, int]:
"""
args:
array:
target:
returns:
idxs
>>> s = [-1, 0, 1, 2, -1, -4]
>>> three_sum_brute_force(s, 0)
(0, 1, 2)
O(N^3)
"""
for i, ... | 4a47fae2c4f81ef654bcf21c73462cc4965b6b78 | 34,984 |
def on_cooldown(user):
"""Shortcut: Get remaining cooldown of a user."""
return Parent.GetUserCooldownDuration(ScriptName, settings["command"], user) | afadc17c45f09303d1fdcddc997c6b5d98c5e903 | 34,986 |
def get_ieconstraints(unknowns, segment):
""" Runs the mission if the inequality constraint values are needed, these are specific to a climb
Assumptions:
Time only goes forward
CL is less than a specified limit
CL is greater than zero
All altitudes are greater than zero
... | 6cdc5ce218ecdc40b792f0bf2fce8789e8577aa9 | 34,987 |
def check_file_name(file_name, file_type="", extension=""):
"""
check_file_name(file_name, file_type="", extension="")
Checks file_name for file_type or extension
"""
file_name = check_string(file_name, -1, '.', extension)
file_name = check_string(file_name, -1, '_', file_type)
return file_name | 250937094bc90e67ccf5a3d2615105b4e448dfff | 34,988 |
def render_experiments(
driver: Driver = None,
collab_id: str = "",
project_id: str = "",
form_type: str = "display",
show_details: bool = True
):
""" Renders out retrieved experiment metadata in a custom form
Args:
driver (Driver): A connected Synergos driver to communicate with... | 8f210251052081184b0e3792ed7381263a9961b2 | 34,989 |
import json
def tag_lookup(request):
"""JSON endpoint that returns a list of potential tags.
Used for upload template autocomplete.
"""
tag = request.GET['tag']
tagSlug = slugify(tag.strip())
tagCandidates = Tag.objects.values('word').filter(slug__startswith=tagSlug)
tags = json.dumps([c... | c6cca931538a30bfa2e6f356f87eaa17158f5145 | 34,990 |
def scope_to_list(scope):
"""Convert a space separated string to a list of scopes."""
if isinstance(scope, list) or scope is None:
return scope
else:
return scope.split(" ") | c806f91192f86dbc42719787d9ddfe0d79690f0c | 34,991 |
from pathlib import Path
import importlib
def import_migration_script(filepath: Path) -> ModuleType:
"""
Import migration script as if it were a module.
"""
spec = importlib.util.spec_from_file_location(filepath.stem, filepath)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_mo... | 15c8a5532d0a38d0741c3a82c299ad13e6885792 | 34,992 |
from typing import Callable
import inspect
def numargs(func: Callable) -> int:
"""Get number of arguments."""
return len(inspect.signature(func).parameters) | 2b4e068798add68323db6bd43253fbca34ea71ba | 34,993 |
def _embed(x, order=3, delay=1):
"""Time-delay embedding.
Parameters
----------
x : 1d-array, shape (n_times)
Time series
order : int
Embedding dimension (order)
delay : int
Delay.
Returns
-------
embedded : ndarray, shape (n_times - (order - 1) * delay, order... | e2834c835521e57132f67a19f4a405af752e497f | 34,994 |
def form_baseline_intro(current_law):
"""
Form final sentance of introduction paragraph
"""
if not current_law:
return f"{date()}"
else:
return (
f"{date()}, along with some modifications. A summary of these "
"modifications can be found in the \"Summary of Ba... | 8e93002290188605eb5df6992f5f41ae2352634d | 34,996 |
from typing import Any
def serialise(entry: Directive) -> Any:
"""Serialise an entry."""
if not entry:
return None
ret = entry._asdict()
ret["type"] = entry.__class__.__name__
if isinstance(entry, Transaction):
ret["payee"] = entry.payee or ""
if entry.tags:
ret... | 9ec9e1ea77011a79f8d1aac7ce4c804ef288f9f6 | 34,997 |
def MeanValueCoordinateMapping(dpoint, uv, physical_points):
"""MVC mapping from parametric uv to physical 3D
inputs:
dpoint: [list, tuple or 1D array of floats] desired uv point
uv: [2D array] of parametric uv points of polygon vertices
physic... | e5212fc953a67bc3e9827aa0d3bb4c088a6c848d | 34,998 |
import re
def _handle_discogs(url):
"""https://*discogs.com/*"""
apiurl = 'https://api.discogs.com/'
headers = {'user-agent': 'pyfibot-urltitle'}
title_formats = {
'release': '{0[artists][0][name]} - {0[title]} - ({0[year]}) - {0[labels][0][catno]}',
'artist': '{0[name]}',
'l... | 37be95755e77782ad4b6beee000a6b096a681aa9 | 34,999 |
def get_api_all_item():
"""Get map of class name to class for all ApiItem subclasses.
Returns:
:obj:`dict`
"""
return {c.__name__: c for c in ApiItem.__subclasses__()} | 621a867b0f4b28eb3d1b5721e22ea4914a5f577d | 35,000 |
def get_image_url(soup_object: object) -> str:
"""Return book image url."""
image_url = soup_object.find("img")["src"]
return image_url.replace("../..", "https://books.toscrape.com/") | 5a52145eacc2489762d3f32b63e092e26d4fc4c8 | 35,001 |
def concat_train_val(train_df, val_df):
"""Utility function to concatenate the train and validation set, while maintaining globally unique ids."""
# increment id tags
max_article_id = train_df['Article_ID'].max() + 1
max_ner_tag_id = train_df['NER_Tag_ID'].max() + 1
increment_article_id = partial(in... | b4c949e08061a724441caf0abf8a2a14f1e494c3 | 35,003 |
import math
def frequencyToMidi(frequency):
"""
Convert a given frequency in Hertz to its corresponding MIDI pitch number (60 = Middle C)
"""
return int(round(69 + 12 * math.log(frequency / 440.0, 2))) | 29d4b92b9deacb81f768b554200c4b63b632bf23 | 35,005 |
def lower(value): # Only one argument.
"""Converts a string into all lowercase
How to Use
{{ value|lower|lower|.... }}
"""
return value.lower() | a6c290276aa777cee5e948d0c89202c67a97e6d1 | 35,006 |
def stdp2rbp_non_linear_calcium(*args, **kwargs):
"""Rate-based plasticity from STDP using the non linear calcium model.
Same arguments as ~cbsp.population_1.non_linear_calcium(u, v, w0, seed)
Returns:
float: the population average change of synapse strength at time point 0
"""
w_rec, ... | 454990dc4783641c2da2da17297dd77abc95e3cd | 35,007 |
def create_RevPAR(dataframe):
"""Calculate revpar from answer_num_rooms converted to supply of
room nights divided by answer_ann_revenue"""
dataframe['CREATED_revpar'] = dataframe['ANSWER_ann_revenue'].astype(float)/(dataframe['ANSWER_num_rooms'].astype(float)*365)
return dataframe | 0d3c91ff3909ea693fdde4b0ea8baae43a31a9a0 | 35,008 |
def get_find_response_normal_field_dict(model):
"""
:param model:
:return:
"""
normal_fields = get_normal_field_list_by_model(model) # 普通字段
find_response_allow_fields = {}
for normal_field in normal_fields:
response_key = newbee_model.get_attr_by_model_field_key(model, normal_fiel... | c55da5f2a573857dc7f349bac79b467cd2345450 | 35,009 |
def predict():
"""Return Cell with Summary"""
global CLEAN_SUMMARY
global model
summary = CLEAN_SUMMARY
in_count = None
out_count = None
logger.info('Received Text Input')
if request.method == 'POST':
out = request.form['rawtext']
# preprocess text
text = prepr... | 94fbc9d75b9d488e371185912c54741596a23506 | 35,011 |
import random
import string
def id_generator(N=10):
"""
Generator a random string of characters.
"""
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) | 3e454a583f00f9218a8305dc5f7dca5d0bd27243 | 35,012 |
def transform_covariance(cov_in, transform):
"""
Apply a given transform to a covariance matrix.
:param cov_in: Covariance matrix
:param transform: The transform that will be applies
:returns: The transformed covariance matrix
"""
# Converting the Quaternion to a Rotation Matrix first
#... | 0926bf95e58702f6594de572c7eeb1be2053b0c5 | 35,013 |
def delete_vocabulary(vid):
"""
Delete an existing vocabulary
:return:
"""
try:
vocs.delete_vocabulary(vid)
except IndexError:
raise APIError('Ontology URI not found')
except vocs.UnknownVocabulary, e:
raise NotFound(e.message)
__analyse_vocabularies([vid])
_... | 49e1be4b8132d3db2533ea6e5155d9891a3c221c | 35,014 |
import numpy as np
def available_kurucz_models():
"""These hard-code the available Kurucz models, as present on Nov 22, 2019 on
'http://kurucz.harvard.edu/grids/grid'"""
T_a = np.concatenate((np.arange(3500,13250,250),np.arange(13000,1000,51000)))
logg_a = np.arange(0,5.5,0.5)
Z_a = np.round(np.co... | 2779e39e55127783986a71b65e0b7f09373551f7 | 35,015 |
import numpy as np
def draw_skill_prices(
T,
J,
pi_fun='pi_fixed',
low=-0.2,
high=0.2,
const=[0.0, 0.05]
):
""" Draws initial skill prices and simulates random prices changes.
With the normalization of wages in task 1 to zero, some parts
of this function are redundent. However, the... | a14af64fae651d3728fe4be2eae3f3e51eeecfe5 | 35,016 |
def deal_with_categorical(feasible_values, one_hot_values):
""" function to do the one hot encoding of the categorical values """
index = np.argmax(one_hot_values)
#index = one_hot_values.argmax()
return feasible_values[int(index)] | f57d4c8ae3dbe7183849eced8c42a4561ab910f0 | 35,017 |
def pretty_size(n, pow=0, b=1024, u='B', pre=[''] + [p + 'i' for p in 'KMGTPEZY']):
""" origin: https://stackoverflow.com/a/31178618 """
pow, n = min(int(m_log(max(n * b ** pow, 1), b)), len(pre) - 1), n * b ** pow
return "%%.%if %%s%%s" % abs(pow % (-pow - 1)) % (n / b ** float(pow), pre[pow], u) | dbef4901c93f240847f37755712a57a225a98900 | 35,018 |
def launch_container(container, **kwargs):
"""
Launch a specific container
:param container:
:return: the container ID
"""
# Build the container if it doesn't exist
logger.info("Building %s container..." % container)
client.images.build(path='../%s' % container,
t... | fdeda303a6bc36a3d9a0a828a69cd0bc2a31275d | 35,019 |
def collatz_function(n):
"""
This function, collatz function, takes a number n and the entire part on the division
with 2 if n is even or 3*n+1 is n is odd.
"""
if n % 2 == 0:
return n//2
else:
return 3*n+1 | bd9b061e9651e46e4c6efd3f6e45524d824040ff | 35,020 |
def has_enabled_clear_method(store):
"""Returns True iff obj has a clear method that is enabled (i.e. not disabled)"""
return hasattr(store, 'clear') and ( # has a clear method...
not hasattr(store.clear, 'disabled') # that doesn't have a disabled attribute
or not store.clear.disabled
) | 28ee30f92d44d14300e30fec0de37a2a241c8e92 | 35,021 |
def get_module_for_handler(handler_name):
"""
Gets the module for a handler using naming convention. First the name of the handler is capitalized and appended by the
string "Handler". Then it is converted from camel to snake case to get the name of the module that will be loaded. Raises an
ImportError e... | 1aace2db3658c4309501bb13deeaa0cbd3647654 | 35,023 |
def create_model(activations_outfeed_queue, gradient_accumulation_steps_per_replica):
""" Create the model using the Keras Model class.
Outfeed the activations for a single layer.
"""
input_layer = keras.layers.Input(shape=(28, 28, 1), dtype=tf.float32, batch_size=32)
x = keras.layers.Flatten()... | d7f536becc97a0cb7a4d6465b784a6ce828faeda | 35,024 |
def project_config(opts):
"""Template of project_config.yaml
Args:
opts: mapping parameters as dictionary
Returns:
str: file content as string
"""
template = get_template("project_config")
return template.safe_substitute(opts) | 12ce2cfbf967912586dd6c7a9a9dfe8e7eb00717 | 35,025 |
def _make_dense_split(quantile_accumulator_handle, stats_accumulator_handle,
stamp_token, next_stamp_token, multiclass_strategy,
class_id, feature_column_id, l1_regularization,
l2_regularization, tree_complexity_regularization,
min_... | 0d688a7290ebe05ab13488fc2ab0a04044beb29b | 35,026 |
import torchvision
import torch
def load_data(dataset='cifar10', batch_size=128, num_workers=4):
"""
Loads the required dataset
:param dataset: Can be either 'cifar10' or 'cifar100'
:param batch_size: The desired batch size
:return: Tuple (train_loader, test_loader, num_classes)
"""
print(... | 2983bb2d350c5c6b8ad613186490815f954313e7 | 35,028 |
import netrc
import errno
def get_auth_from_netrc(hostname):
"""Try to find login auth in ``~/.netrc``. Return ``(user, pwd)`` tuple. """
try:
auth = netrc(file=NETRC)
except IOError as cause:
if cause.errno != errno.ENOENT:
raise
return None, None
username, _, pas... | da35fec0c9981166b14cce8870319eb9f1fb8e87 | 35,029 |
def _add_rows_by_count(df, amount, count, alloc_id, constraint, stuff=False):
"""
Add rows to a table so that the sum of values in the `count` column
is increased by `amount`.
Parameters
----------
df : pandas.DataFrame
amount : float
Amount by which to increase sum of `count` colum... | 1bb28f8e58116c469f100c65e9ec2f703f62cc6f | 35,030 |
def rot2(theta, deg=True):
"""returns 2D rotation matrix :math:`R \in SO(2)` to rotate a vector/point in a
plane in counter-clockwise direction
Parameters
----------
theta : float
the angle of rotation
deg : bool
``True`` = degree (default), ``False`` = radians
Returns
... | 557ff9b7135c62043ff767f4a33c8ca0484832bc | 35,031 |
import torch
def coin_flip(prob):
"""
Return the outcome of a biased coin flip.
Args:
prob: the probability of True.
Returns: bool
"""
return prob > 0 and torch.rand(1).item() < prob | 672929fb49a0e65101a4bdfdd13e981ae5eae31c | 35,032 |
import warnings
def _pair_exp_cov(X, Y, span=180):
"""
Calculate the exponential covariance between two timeseries of returns.
:param X: first time series of returns
:type X: pd.Series
:param Y: second time series of returns
:type Y: pd.Series
:param span: the span of the exponential weigh... | ffd64bb660d54444b64f11fc1a46c0a7c26169b4 | 35,033 |
def _protected_division(x1, x2):
"""Closure of division (x1/x2) for zero denominator."""
with np.errstate(divide='ignore', invalid='ignore'):
return np.where(np.abs(x2) > 0.001, np.divide(x1, x2), x1) | 676e8a2f72f076773d33501d2888871674ab6346 | 35,034 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.