content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _fit_seasonal_model_with_gibbs_sampling(observed_time_series,
seasonal_structure,
num_warmup_steps=50,
num_results=100,
seed=None):
"""Bui... | c13d4df3eca25f1a53ed27cd94e5f2b4b102013c | 5,227 |
import pandas as pd
import numpy as np
def rm_standard_dev(var,window):
"""
Smoothed standard deviation
"""
print('\n\n-----------STARTED: Rolling std!\n\n')
rollingstd = np.empty((var.shape))
for ens in range(var.shape[0]):
for i in range(var.shape[2]):
for j in ... | d37cfa3c756f8fc062a28ac078e4e16557282951 | 5,230 |
def visualizeTimeSeriesCategorization(dataName, saveDir, numberOfLagsToDraw=3, autocorrelationBased=True):
"""Visualize time series classification.
Parameters:
dataName: str
Data name, e.g. "myData_1"
saveDir: str
Path of directories pointing to data storage
... | b2fcac2179e3a689ee73e13519e2f4ad77c59037 | 5,232 |
from typing import Dict
def refund(payment_information: Dict, connection_params) -> Dict:
"""Refund a payment using the culqi client.
But it first check if the given payment instance is supported
by the gateway.
It first retrieve a `charge` transaction to retrieve the
payment id to refund. And r... | 75dff392c0748a1408eb801ad78ef65be988026c | 5,233 |
import numbers
def check_random_state(seed):
"""Turn `seed` into a `np.random.RandomState` instance.
Parameters
----------
seed : {None, int, `numpy.random.Generator`,
`numpy.random.RandomState`}, optional
If `seed` is None (or `np.random`), the `numpy.random.RandomState`
s... | 57390806329776c77977a27e18e78fdad298fef9 | 5,236 |
def power3_sum_2method():
"""
Input:
nothing, it have everything it needs.
Output:
sum: summ of all numbers which is power of 3
and fit in between 0 and upper bound == 1000000
"""
k = 0
sum = 0
while True:
a = 3**k
k += 1
if a < 1000000:
s... | b86bfaeb2418e183a78054d2a4b76c58d58be388 | 5,237 |
def bitwise_right_shift(rasters, extent_type="FirstOf", cellsize_type="FirstOf", astype=None):
"""
The BitwiseRightShift operation
The arguments for this function are as follows:
:param rasters: array of rasters. If a scalar is needed for the operation, the scalar can be a double or string
:param ... | 8d07a60a514466ee4aa0b15b0b442fb71b3347ed | 5,238 |
import re
def strip_comments(line):
"""Strips comments from a line and return None if the line is empty
or else the contents of line with leading and trailing spaces removed
and all other whitespace collapsed"""
commentIndex = line.find('//')
if commentIndex is -1:
commentIndex = len(line... | 09579031294d7b5787c97fa81807fa5ecfe12329 | 5,239 |
import logging
def fft_pxscale(header,wave):
"""Compute conversion scale from telescope space to sky space.
Parameters
----------
ima : array
2D Telescope pupil model.
Returns
-------
fftscale : float
The frequency scale in sky space.
Exam... | 6935bdefe96aec771704a79952cfc25ffb55e8bb | 5,240 |
def parse_git_submodules(gitmodules_data):
"""Parse a .gitmodules file to extract a { name -> url } map from it."""
result = {}
# NOTE: configparser.ConfigParser() doesn't seem to like the file
# (i.e. read_string() always returns None), so do the parsing
# manually here.
section_nam... | 78d01ec70b68164189a2ea775c6084e256116d0a | 5,241 |
import pathlib
from typing import Dict
import json
def get_model_cases(dir_path: pathlib.Path) -> Dict[str, Dict[str, str]]:
"""
Returns the Zen model case for each test if it exists.
:param dir_path: The path to the directory containing the DIFFERENCES directory.
"""
model_cases = defaultdict(di... | d35b4cf59cf9b99a6aeb9e05e0af3ee342b11f3b | 5,242 |
def _format_date(event):
"""Returns formated date json object for event"""
old_date = event["date"]
term = event["term"]
dates = old_date.split("-")
if len(dates) == 1:
is_range = False
else:
is_range = True
is_range = (len(dates) > 1)
if is_range:
start_date =... | aa8bf9a41fe30b664920e895cdc31d6993a408b2 | 5,243 |
def fetch(bibcode, filename=None, replace=None):
"""
Attempt to fetch a PDF file from ADS. If successful, then
add it into the database. If the fetch succeeds but the bibcode is
not in th database, download file to current folder.
Parameters
----------
bibcode: String
ADS bibcode ... | 7d264df3f0eab896a9cb4858e7b19e2590d8142b | 5,244 |
def crop_multi(x, wrg, hrg, is_random=False, row_index=0, col_index=1):
"""Randomly or centrally crop multiple images.
Parameters
----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.crop``.
R... | 61593029455a880d5309e8343cf4f6d1049f598f | 5,245 |
def value_loss_given_predictions(value_prediction,
rewards,
reward_mask,
gamma,
epsilon,
value_prediction_old=None):
"""Computes the value loss given the... | 5896dd57e1e9d05eb71e5b31aab4071b61d0fdbf | 5,246 |
def build_pkt(pkt):
"""Build and return a packet and eth type from a dict."""
def serialize(layers):
"""Concatenate packet layers and serialize."""
result = packet.Packet()
for layer in reversed(layers):
result.add_protocol(layer)
result.serialize()
return re... | afd84446d3bb545b03b9d4c42d80f096b6665342 | 5,247 |
def make_file_prefix(run, component_name):
"""
Compose the run number and component name into string prefix
to use with filenames.
"""
return "{}_{}".format(component_name, run) | 73ef37d75d9e187ee49ee058958c3b8701185585 | 5,248 |
from typing import Dict
def initialize_lock_and_key_ciphers() -> Dict[str, VigenereCipher]:
"""[summary]
Returns:
Dict[VigenereCipher]: [description]"""
ciphers = {}
with open(CIPHER_RESOURCE, "r") as cipher_resource_file:
cipher_data = load(cipher_resource_file, Loader=FullLoader)
... | 1c0a27b36b4c0524b77dcb5c44a3bc840797b226 | 5,250 |
def add_service():
"""
Used to register a new service
"""
form = ServiceForm()
if form.validate_on_submit():
try:
srv = Services()
srv.populate_from_form(form)
srv.authentication.value = {"db":request.form.get('authdb'),"user":request.form.get('authuser'... | 56ce52c293d42710a9d4d5ac57b21f5ba1c0c0ac | 5,251 |
def parse_resolution(resolution):
"""
return: width, height, resolution
"""
resolution = resolution.strip()
splits = resolution.split(',')
return int(splits[0]), int(splits[1]), int(splits[2]) | de937e440c4540d11cedd868e3f4a046baa99f22 | 5,253 |
import inspect
def get_arguments(func):
"""Returns list of arguments this function has."""
if hasattr(func, '__code__'):
# Regular function.
return inspect.getargspec(func).args
elif hasattr(func, '__call__'):
# Callable object.
print(func)
return _get_arguments(fun... | f93133f20c819c590c30e25b6c339c07732daebe | 5,256 |
def _check(isamAppliance, name):
"""
Check if suffix exists
"""
ret_obj = get(isamAppliance)
check_value, warnings = False, ret_obj['warnings']
if warnings == []:
for suffix in ret_obj['data']:
if suffix['name'] == name:
logger.info("Suffix found in embedded ... | be2a6226ebdccb92ec3361df79e50165a22d6981 | 5,257 |
def check_listening_address(address: str) -> bool:
"""Check entered ip address for validity."""
if address == 'localhost':
return True
return address in get_local_addresses() | eaa5cecfee4e8be2947150a537213f4159ee6baf | 5,258 |
import base64
def multibase_b64decode(data):
"""
Follow forge's base64 urlsafe encode convention to decode string
Args:
data(string): encoded string
Returns: bytes
Examples:
>>> multibase_b64decode('aGVsbG8')
b'hello'
"""
if isinstance(data, str):
data =... | fdbc0f937e33d7994737a3a515973598cac3debd | 5,259 |
from typing import List
def parse_ordering_params(param: List[str]) -> List[str]:
"""
Ignores the request to sort by "ord".
Returns a sorting order based on the params and includes "readable_id"
sorting in passed params if the sorting request contains title
otherwise, it returns the requested orde... | a6a5f4665515a292ad2367945a6b8407000d656a | 5,260 |
def file_senzing_rabbitmq():
"""#!/usr/bin/env bash
# --- Functions ---------------------------------------------------------------
function up {
echo -ne "\033[2K${CONTAINER_NAME} status: starting...\r"
mkdir -p ${RABBITMQ_DIR}
chmod 777 ${RABBITMQ_DIR}
if [ "${CONTAINER_VERSION}" == "latest" ]... | 95396425074096d17561b20cd197e77f1d550476 | 5,261 |
def mse(predictions, targets):
"""Calculate MSE: (Mean squared error)
"""
return ((predictions - targets) ** 2).mean() | 79d87a3422d4d24201cae86ee861614c83f6770f | 5,262 |
def export1d(hist):
"""Export a 1-dimensional `Hist` object to uproot
This allows one to write a coffea histogram into a ROOT file, via uproot.
Parameters
----------
hist : Hist
A 1-dimensional histogram object
Returns
-------
out
A ``uproot_methods.cla... | ffe09495a268c68d26f9861e6d732649f2f74497 | 5,263 |
def filter_words(w_map, emb_array, ck_filenames):
""" delete word in w_map but not in the current corpus """
vocab = set()
for filename in ck_filenames:
for line in open(filename, 'r'):
if not (line.isspace() or (len(line) > 10 and line[0:10] == '-DOCSTART-')):
line = lin... | efdef92093acf25c992dba86da25a4118ba728ec | 5,264 |
def get_cache_template(sources, grids, geopackage, table_name="tiles"):
"""
Returns the cache template which is "controlled" settings for the application.
The intent is to allow the user to configure certain things but impose specific behavior.
:param sources: A name for the source
:param grids: sp... | dc83a155d28e0b39f12a7dc7142b61a4bf27512b | 5,265 |
from datetime import datetime
def plotter(fdict):
""" Go """
pgconn = get_dbconn('coop')
ccursor = pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor)
ctx = get_autoplot_context(fdict, get_description())
station = ctx['station']
lagmonths = ctx['lag']
months = ctx['months']
month ... | 0f41a53336f2bf65805adaf83a8f3f17c006e161 | 5,266 |
def _action_spec():
"""Returns the action spec."""
paddle_action_spec = dm_env_rpc_pb2.TensorSpec(
dtype=dm_env_rpc_pb2.INT8, name=_ACTION_PADDLE)
tensor_spec_utils.set_bounds(
paddle_action_spec,
minimum=np.min(_VALID_ACTIONS),
maximum=np.max(_VALID_ACTIONS))
return {1: paddle_action_sp... | 130b7b2fe9f56d925d4ec1206eb3fb2752fee716 | 5,267 |
def stdin(sys_stdin):
"""
Imports standard input.
"""
inputs = [x.strip("[]\n") for x in sys_stdin]
a = [int(x) for x in inputs[0].split(",")]
x = int(inputs[1][0])
return a, x | 4c34e1bc80da31c6c7aff0d71a0c65f6fc01ed00 | 5,268 |
def _row_key(row):
"""
:param row: a normalized row from STATEMENT_METRICS_QUERY
:return: a tuple uniquely identifying this row
"""
return row['database_name'], row['user_name'], row['query_signature'], row['query_hash'], row['query_plan_hash'] | 2984e0e0b5fcc4e51a26af188e51fe65c52077a2 | 5,269 |
from io import StringIO
def get (url, user_agent=UA, referrer=None):
"""Make a GET request of the url using pycurl and return the data
(which is None if unsuccessful)"""
data = None
databuffer = StringIO()
curl = pycurl.Curl()
curl.setopt(pycurl.URL, url)
curl.setopt(pycurl.FOLLOWLOCATIO... | e18de239a598be249d81c2a15486a66af763bc85 | 5,270 |
from typing import List
from typing import Tuple
from typing import Any
def apply_filters(
stream: StreamMeta, filters: List[Tuple[str, str]], config: Any
) -> StreamMeta:
"""Apply enabled filters ordered by priority on item"""
filter_pool = get_filter_pool(filters, config)
for filter_instance in fil... | 2ff50b5d31e84ba69afe694b4beb4116dbc5fc55 | 5,272 |
def threading_d(func):
"""
A decorator to run function in background on thread
Args:
func:``function``
Function with args
Return:
background_thread: ``Thread``
"""
@wraps(func)
def wrapper(*args, **kwags):
background_thread = Thread(target=func, args=(*args,))
ba... | ff4d86ded189737d68d4cdc98c0e9ba9f1a28664 | 5,273 |
def create_anchors_3d_stride(
feature_size,
sizes=[1.6, 3.9, 1.56],
anchor_strides=[0.4, 0.4, 0.0],
anchor_offsets=[0.2, -39.8, -1.78],
rotations=[0, np.pi / 2],
velocities=[],
dtype=np.float32,
):
"""
Args:
feature_size: list [D, H, W](zyx)
sizes: [N, 3] list of list... | 6834d20f44196f5dad19d1917a673196334adf9f | 5,274 |
import hashlib
def sha1_file(filename):
"""
Return the hex string representation of the SHA1 checksum of the filename
"""
s = hashlib.sha1()
with open(filename, "rb") as f:
for line in f:
s.update(line)
return s.hexdigest() | b993ac9f025d69124962905f87b1968617bb33f5 | 5,275 |
def read_from_file(file_path):
"""
Read a file and return a list with all the lines in the file
"""
file_in_list = []
with open(file_path, 'r') as f:
for line in f.readlines():
file_in_list.append(line)
return file_in_list | 5fef3a3f50528c1a9786451666ae7e43be282bf9 | 5,277 |
def count(predicate, iterable):
"""
Iterate over iterable, pass the value to the predicate predicate and
return the number of times the predicate returns value considered True.
@param predicate: Predicate function.
@param iterable: Iterable containing the elements to count.
@return: The number o... | 1a2d9a05203f32a6f1a8349b6e31d14cb1b82b71 | 5,278 |
def get_object_from_path(path):
"""
:param path:
dot seperated path. Assumes last item is the object and first part is module
path(str) -
example:
cls = get_object_from_path("a.module.somewhere.MyClass")
you can create a path like this:
class_path = "{0}.{1}".format... | e722b040486288d53fe4a357d81ddec8dfc9820e | 5,279 |
def _get_collection_memcache_key(collection_id, version=None):
"""Returns a memcache key for the collection.
Args:
collection_id: str. ID of the collection.
version: int. Schema version of the collection.
Returns:
str. The memcache key of the collection.
"""
if version:
... | cc054d726d1d2642701803a816e214eed4d9663d | 5,280 |
def biKmeans(dataSet, k, distMeas=calcEuclideanDistance):
"""
二分K-均值算法
:param dataSet:
:param k:
:param distMeas:
:return:
"""
m = np.shape(dataSet)[0]
clusterAssment = np.mat(np.zeros((m, 2)))
centroid0 = np.mean(dataSet, axis=0).tolist()[0]
centList = [centroid0] # create... | 1421dfa95c44e046bd7d729ad343e98eb83bbbcd | 5,281 |
def cleanup(args, repo):
"""Clean up undeployed pods."""
if args.keep < 0:
raise ValueError('negative keep: %d' % args.keep)
def _is_enabled_or_started(pod):
for instance in pod.iter_instances():
if scripts.systemctl_is_enabled(instance.unit_name):
return True
... | b015c1dbfeb3ad50218afaadfe198123ff2ab6df | 5,283 |
from typing import Dict
def optimizer_builder(
config: Dict):
"""
Instantiate an optimizer.
:param config:
:return:
"""
# --- argument checking
if not isinstance(config, dict):
raise ValueError("config must be a dictionary")
# --- read configuration
decay_rate = c... | 2194408d74d4f03bc54371b98b12c8dbe85fb585 | 5,284 |
def psi(z: float, a: float, b: float) -> float:
"""Penalty function with uniformly bounded derivative (Eq. 20)
Args:
z: Relative distance
a: Cohesion strength
b: Separation strength
"""
c = np.abs(a - b) / (2 * np.sqrt(a * b))
return ((a + b) / 2) * (np.sqrt(1 + (z + c) ** 2)... | df88e57d80a32d95367f30ce52af84308349387a | 5,285 |
def caselessSort(alist):
"""Return a sorted copy of a list. If there are only strings
in the list, it will not consider case.
"""
try:
return sorted(alist, key=lambda a: (a.lower(), a))
except TypeError:
return sorted(alist) | 7558a57e28255817c71846da84230ced49553bb6 | 5,286 |
def EnableRing(serialPort):
""" Enable the ISU to listen for SBD Ring Alerts. When SBD Ring Alert indication is enabled, the 9602 asserts the RI line and issues the unsolicited result
code SBDRING when an SBD Ring Alert is received. """
... | 7036610523802f659c7a69ae192f1009401a6ac3 | 5,287 |
def render(template, **context):
"""Render the given template.
:param template: The template file name or string to render.
:param **context: Context keyword-arguments.
"""
class Undefined(BaseUndefined):
def _fail_with_undefined_error(self, *args, **kwargs):
try:
... | 6680f163e1b89424e88b1a3046784083cdbb6520 | 5,288 |
def audio(src: str) -> str:
""" Insert audio tag
The tag is currently not supported by Nuance, please use `audio_player` kit:
docs/use_kits_and_actions.md
:param src:
:return:
"""
return f'<audio src="{src}"/>' | f9396d5f82eeca27089de41187fd7d5e967cc9cf | 5,290 |
import math
def PerpendicularDistanceToFinish(point_b_angle: float,
point_b: gps_pb2.Point) -> float:
"""
cos(B) = Adjacent / Hypotenuse
https://www.mathsisfun.com/algebra/trig-finding-side-right-triangle.html
"""
return math.cos(math.radians(point_b_angle)) * point_b.star... | 3c18c323c625893ab474c48eb00d48da543956ba | 5,292 |
import requests
from typing import List
def get_revolut_stocks() -> List[str]:
"""
Gets all tickers offered on Revolut trading platform.
Returns:
list(str)
"""
req = requests.get("https://globefunder.com/revolut-stocks-list/")
tickers = list(pd.read_html(req.content)[0]["Symbol"])
... | 3e7f41a04c653a954609cee618cbf89d962fef1d | 5,293 |
from typing import Tuple
def create_rankings(
a: Dataset, b: Dataset, n_samples: int = 100, unravel: bool = False, **kwargs: int
) -> Tuple[ndarray, ndarray]:
"""
Sample a dataset 'a' with 'n' negative samples given interactions in dataset 'a'
and 'b'.
Practically, this function allows you to gen... | 28282fc14d02b7f93d58d209d143a315e7b25422 | 5,295 |
def make_even(x):
"""Make number divisible by 2"""
if x % 2 != 0:
x -= 1
return x | 10129eb6abd718414d0ada53915672dcf4d7b5b6 | 5,296 |
def get_num_vehicles(session, query_filters):
"""Gets the total number of annotations."""
# pylint: disable-msg=E1101
num_vehicles_query = session.query(
func.count(Vehicle.id)) \
.join(Photo) \
.filter(Photo.test == True) \
# pylint: enable-msg=E1101
for query_filter i... | bf626edad29b136bb595dabb7e878649c08c0d84 | 5,297 |
def task_status_edit(request, status_id, response_format='html'):
"""TaskStatus edit"""
status = get_object_or_404(TaskStatus, pk=status_id)
if not request.user.profile.has_permission(status, mode='w'):
return user_denied(request, message="You don't have access to this Task Status")
if request... | 593384ab55bf889a1e87d7909e848a2dbacad68e | 5,298 |
import platform
def is_windows_system():
"""
| ##@函数目的: 获取系统是否为Windows
| ##@参数说明:True or False
| ##@返回值:
| ##@函数逻辑:
| ##@开发人:jhuang
| ##@时间:
"""
return 'Windows' in platform.system() | 6bfe296188b9dccf8338f0b2bbaaf146d9b22243 | 5,299 |
def seepage_from_unitary(U):
"""
Calculates leakage by summing over all in and output states in the
computational subspace.
L1 = 1- sum_i sum_j abs(|<phi_i|U|phi_j>|)**2
"""
sump = 0
for i in range(2):
for j in range(2):
bra_i = qtp.tensor(qtp.ket([i], dim=[2]),
... | 8bd4185a69d7280868871dc3c62bb10abac1579c | 5,300 |
def auto_get(*args):
"""
auto_get(type, lowEA, highEA) -> ea_t
Retrieve an address from queues regarding their priority. Returns
'BADADDR' if no addresses not lower than 'lowEA' and less than
'highEA' are found in the queues. Otherwise *type will have queue
type.
@param type (C++: atype_t *)
@para... | 810ea49a414e3a044bc94cac4d780c7b624433a2 | 5,301 |
def isLineForUser(someLine=None, username=None):
"""determins if a raw output line is for a user"""
doesMatch = False
try:
doesMatch = utils.isLineForMatch(someLine, username)
except Exception as matchErr:
logs.log(str(type(matchErr)), "Error")
logs.log(str(matchErr), "Error")
logs.log(str((matchErr.args)),... | dbf6b92976c8419fc3b9271eb87871c8c7cf6a1b | 5,302 |
def create_multipart_upload(s3_obj, bucketname, object_key):
"""
Initiates Multipart Upload
Args:
s3_obj (obj): MCG or OBC object
bucketname (str): Name of the bucket on which multipart upload to be initiated on
object_key (str): Unique object Identifier
Returns:
str : M... | 375d7d04aefa0ef4f91a42e2478ae624057e1bee | 5,304 |
import sqlite3
def cn(DB):
"""Return the cursor and connection object."""
conn = sqlite3.connect(DB)
c = conn.cursor()
return (c,conn) | 76abbec283d45732213f8b94031242146cdb4ee0 | 5,305 |
def _build_category_tree(slug, reference=None, items=None):
"""
Builds a recursive tree with category relations as children.
"""
if items is None:
items = []
for key in reference:
category = reference[key]
if category["parent"] == slug:
children = _build_catego... | d06cb736b12025b862363a724b2497a71a8a8a30 | 5,306 |
import copy
def partially_matched_crossover(random, mom, dad, args):
"""Return the offspring of partially matched crossover on the candidates.
This function performs partially matched crossover (PMX). This type of
crossover assumes that candidates are composed of discrete values that
are permutations... | b0d5132cf4ca14095f3d7c637cb50db3fe37d244 | 5,307 |
import re
def regex_trim(input, regex, replace=''):
"""
Trims or replaces the regex match in an input string.
input (string): the input string to search for matches
regex (string): regex to match
replace (string - optional): a string to replace any matches with. Defaults to trimming the match.
"""
return re.s... | 169bfaa0d2bfd7a1f32c1e05a63b41993f82bf4b | 5,308 |
def LoadAllSuitesOfProject(project_name):
"""Loads all of the suites of a project."""
project_key = db.Key.from_path(bite_project.BiteProject.kind(),
project_name)
return BiteSuite.all().ancestor(project_key) | 7a1a27229542ed364dddd2cc9a9cd3343c1d934d | 5,310 |
def calc_temps(start_date, end_date):
"""TMIN, TAVG, and TMAX for a list of dates.
Args:
start_date (string): A date string in the format %Y-%m-%d
end_date (string): A date string in the format %Y-%m-%d
Returns:
TMIN, TAVG, and TMAX
"""
return session.query... | 567bc943ecfe34c0604427e0fa8cea11f10c7205 | 5,311 |
def train_model(ad, rsrc_loc, algo='IR', log_dir=None):
"""
Train a CellO model based on the genes of an
input dataset.
Parameters
----------
ad : AnnData object
Expression matrix of n cells by m genes
algo : String
The name of the algorithm used to train the model. 'IR' ... | 46c7736a4f0127ec882d54075564fd447336a332 | 5,313 |
def ps_roi_max_align_2d(
x, rois, roi_indices, outsize,
spatial_scale, group_size, sampling_ratio=None
):
"""Position Sensitive Region of Interest (ROI) Max align function.
This function computes position sensitive max value of input spatial patch
with the given region of interests. Each RO... | 394879a014d855dd71786cb0941a3aefd30b70b8 | 5,314 |
def received_date_date(soup):
"""
Find the received date in human readable form
"""
return utils.date_text(history_date(soup, date_type="received")) | 5fbba6129da8d6facc66f9ec21e9b6f45fcb399a | 5,315 |
import uuid
def get_cert_sha256_by_openssl(certraw: str) -> str:
"""calc the sha1 of a certificate, return openssl result str"""
res: str = None
tmpname = None
try:
tmpname = tmppath / f"{uuid.uuid1()}.crt"
while tmpname.exists():
tmpname = tmppath / f"{uuid.uuid1()}.crt"
... | 9cd095bd8d2d710b1cf7e4a3155a0b4fc08587f5 | 5,317 |
def analytic_pi(x, c, w, h):
"""Analytic response function for an even pair of Lorentz distributions.
Correspond to
.. math::
\\Pi(x) = \\int_{-\infty}^{\\infty}
\\frac{\\omega^2}{\\omega^2+x^2}\sigma()_{i}
where :math:`\\sigma(\\omega)` is :func:`~even_lorentzian`.
Args:
x... | fc622e79a6692105c15e05ea353ba925b8378831 | 5,318 |
def run(canvas):
""" This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas)
@Args:
--
canvas : canvas of population to run the rules on.
@returns:
--
None
"""
canvas = np.array(canvas)
next_gen_canvas = np.array(create... | 4a7ae84cf245755f51c3c7a5c22e646e452e6d7a | 5,319 |
def initialize_vocabulary(vocabulary_path):
"""Initialize vocabulary from file.
We assume the vocabulary is stored one-item-per-line, so a file:
dog
cat
will result in a vocabulary {"dog": 0, "cat": 1}, and this function will
also return the reversed-vocabulary ["dog", "cat"].
Args:
vocabulary_p... | bf56054aab47ac959fc38929445fc15a1d59b8a9 | 5,320 |
def ravel_space(space):
"""
Convert the space into a Discrete space.
"""
dims = _nested_dim_helper(space)
return Discrete(dims[0]) | baa04d3dd16e1c797bbdb83ff5f42474e77c57b4 | 5,321 |
def _add_col(dataframe, metadata, col_limits, families, weights, random_state):
"""Add a new column to the end of the dataframe by sampling a distribution
from ``families`` according to the column limits and distribution weights
and sampling the required number of values from that distribution."""
nrow... | b0a711a132f78188cc8b40fe3fb907d022aaa37a | 5,322 |
import struct
def read_and_decrypt_mylogin_cnf(f):
"""Read and decrypt the contents of .mylogin.cnf.
This decryption algorithm mimics the code in MySQL's
mysql_config_editor.cc.
The login key is 20-bytes of random non-printable ASCII.
It is written to the actual login path file. It is used
t... | 84b0831a139db80e0a8d48c7fbaacaef377c93e9 | 5,323 |
def list_files(tag=None, inst_id=None, data_path=None, format_str=None,
supported_tags=None, file_cadence=dt.timedelta(days=1),
two_digit_year_break=None, delimiter=None, file_type=None):
"""Return a Pandas Series of every file for chosen Instrument data.
Parameters
----------... | e8dd3c25c953fb6d8ccef6cbef4fd31c579826fd | 5,324 |
def is_on_top(bb1, bb2):
""" For obj 1 to be on top of obj 2:
- obj1 must be above obj 2
- the bottom of obj 1 must be close to the top of obj 2
"""
bb1_min, _ = bb1
_, bb2_max = bb2
x1,y1,z1 = bb1_min
x2,y2,z2 = bb2_max
return z1 < z2 + ONTOP_EPSILON and is_above(bb1, ... | 666b7a424fc1b8769cc436c07981ae134e6241a9 | 5,325 |
def prepare_definitions(defs, prefix=None):
"""
prepares definitions from a dictionary
With a provided dictionary of definitions in key-value pairs and builds them
into an definition list. For example, if a dictionary contains a key ``foo``
with a value ``bar``, the returns definitions will be a li... | ddc6d14cc18f8afba766efee65ab365df1d226c2 | 5,326 |
def load_training_data(mapsize=512, grfized=False, exclude_fid=False,
dense_grid=False, random_split=False,
from_files=False):
"""Load data for different training scenarios."""
if not grfized and (not dense_grid) and (not random_split):
# the default data ... | 2e2ddf93311c315f070c91af8bcc1a0df5e94343 | 5,327 |
def concat_features(args, feature_dim_name='feature'):
"""Concatenate Xs along a set of feature dimensions
Parameters
----------
args : iterable
list of tuples of the form (dims, DataArray) where dims is a tuple of dimensions that will be considered feature dimensions
Returns
-------
... | d7b44931a5b8a626ca81e5260566c60379d64fc2 | 5,328 |
def _inspect_mixin(
self, geoctx=None, format="pyarrow", file=None, timeout=30, client=None, **params
):
"""
Quickly compute this proxy object using a low-latency, lower-reliability backend.
Inspect is meant for getting simple computations out of Workflows, primarily for interactive use.
It's quick... | fd66a1728ca99806dc2c5056cf4a612ca7cac79b | 5,329 |
def list_dvs(service_instance):
"""
Returns a list of distributed virtual switches associated with a given service instance.
service_instance
The Service Instance Object from which to obtain distributed virtual switches.
"""
return utils_common.list_objects(service_instance, vim.Distributed... | 2223fe68c13868bea2884b292318e21cb1c2b99c | 5,330 |
from typing import Optional
def gdb_cli_args(request: FixtureRequest) -> Optional[str]:
"""
Enable parametrization for the same cli option
"""
return getattr(request, 'param', None) or request.config.getoption('gdb_cli_args', None) | 635c5cfd397fe286003add99e094778f835a88d9 | 5,331 |
from datetime import datetime
def coerce_rfc_3339_date(input_date):
"""This function returns true if its argument is a valid RFC 3339 date."""
if input_date:
return datetime.datetime.strptime(input_date, "%Y-%m-%dT%H:%M:%SZ")
return False | 83cc2c32b74ad896d79db1a91f4a0fd88b26731e | 5,332 |
def extract_job_url(job):
"""
parse the job data and extract the str for the URL of the job posted
params:
job str: html str representation from bs4
returns:
url str: relative URL path of the job ad
"""
return job.a["href"] | 7517badcc2814e641c04a8f880353d897d434b7f | 5,333 |
import sh
def commit(experiment_name, time):
"""
Try to commit repo exactly as it is when starting the experiment for reproducibility.
"""
try:
sh.git.commit('-a',
m='"auto commit tracked files for new experiment: {} on {}"'.format(experiment_name, time),
allow_... | a5a75cad77d605ef60905e8b36c6df9913b7bd3c | 5,334 |
def weighted_loss(class_weights):
"""
Create a weighted loss function. Penalise the misclassification
of classes more with the higher usage
"""
weight_values = list(class_weights.values())
def weighted_binary_crossentropy(y_true, y_pred):
# add another dimension to compute dot product
... | 804a643dff3916f376545a9f481edc418ebf5d8e | 5,335 |
def delete_cluster(resource_root, name):
"""
Delete a cluster by name
@param resource_root: The root Resource object.
@param name: Cluster name
@return: The deleted ApiCluster object
"""
resp = resource_root.delete("%s/%s" % (CLUSTERS_PATH, name))
return ApiCluster.from_json_dict(resp, resource_root) | 2ed12d7f927d6579cbea81765b353f0eecae8f4a | 5,336 |
def mk_test(x, alpha = 0.05):
"""This perform the MK (Mann-Kendall) test to check if there is any trend present in
data or not
Args:
x: a vector of data
alpha: significance level
Returns:
trend: tells the trend (increasing, decreasing or no trend)
h: True (if... | 8586c7ee5cf71ea79db9f57ebc6cc77d942962f7 | 5,337 |
from typing import List
def convert_event_to_boxes(event: Event) -> List[EventBox]:
"""Takes in an event and converts this into a list of boxes that when combined completely cover the time allocated
to this event. Usually, this list will contain a single EventBox as many events start and end on the same day, ... | c8f93fb2480792540e9052dd79c654e835021030 | 5,338 |
import copy
def _reduce_consecutive_layers(conv_defs, start_id, end_id, multiplier=0.5):
"""Reduce the outputs of consecutive layers with multiplier.
Args:
conv_defs: Mobilenet conv_defs.
start_id: 0-based index of the starting conv_def to be reduced.
end_id: 0-based index of the last conv_def to be ... | ffcfad4956f72cf91aeaa5e795e9568d0808417f | 5,339 |
def ajax_save_content(request):
""" Save front end edited content """
site = get_current_site(request)
content_name = request.POST['content_name']
cms_content = CmsContent.objects.get(site=site, name=content_name)
cms_content.content = request.POST['content']
cms_content.save()
return HttpRe... | f99bcfaa7ff5773870ed6ba76bfb0cc97fab248b | 5,340 |
def add_regional_group_costs(ws, data_sheet):
"""
"""
ws.sheet_properties.tabColor = "92D050"
##Color white
ws.sheet_view.showGridLines = False
#Set blue and red border strips
set_cell_color(ws, 'A1:AZ1', "004C97")
set_cell_color(ws, 'A2:AZ2', "C00000")
ws = bar_chart(ws, "Estima... | a325b33b705819be81725e6fb6c4f277c6add097 | 5,341 |
def random_data(num):
""" will return json random float, hex, int and a random password
{0: {
'float': 186.66541583209647,
'hex': '43435c553c722359e386804f6b28d2c2ee3754456c38f5e7e68f',
'int': 851482763158959204,
'password': '5AJ]-02X0J'
... | 108ebabe8b156218a452cbade729dc09356d2d0b | 5,343 |
def denied(request):
"""Authentication failed and user was denied."""
return render(request, 'djangosaml2/denied.html') | 9341e694163de3d8cd63d448ac39294003046dac | 5,344 |
import time
def monday_of_week(year, week):
"""
Returns a datetime for the monday of the given week of the given year.
"""
str_time = time.strptime('{0} {1} 1'.format(year, week), '%Y %W %w')
date = timezone.datetime(year=str_time.tm_year, month=str_time.tm_mon,
day=s... | 886c16df011f86eaa95254e360062d5530e05512 | 5,346 |
from typing import Mapping
from typing import Any
from typing import Dict
def object_meta(metadata: Metadata) -> Mapping[str, Any]:
"""
Return a minimal representation of an ObjectMeta with the supplied information.
Spec: https://github.com/argoproj/argo-workflows/blob/v3.0.4/docs/fields.md#objectmeta
... | fc4d30954f9c61c90511fbfc00b403017f41f6c9 | 5,347 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.