content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def pass_through_formatter(value):
"""No op update function."""
return value | 202ea761db9e1fa858718c61df3a7fd18f02826c | 3,639,031 |
from re import U
def instantiate(decoder, model=None, dataset=None):
""" Instantiate a full decoder config, e.g. handle list of configs
Note that arguments are added in reverse order compared to encoder (model first, then dataset)
"""
decoder = utils.to_list(decoder)
return U.TupleSequential(*[_in... | 238b97eab9a653200d0f82b92342a64bbbbc6336 | 3,639,032 |
def un_normalize(stdevs, arrList):
"""
Return an arrayList with ith column multiplied by scalar stdevs[i] if stdevs[i] is not zero,
and unmodified if it is zero.
Args:
stdevs: A list of numbers (should be the list output by normalize).
arrList: A list of list of numbers that is the (nor... | a87aa89b2f591d46b077ea26d877f1d3459df2b3 | 3,639,033 |
import json
def convert_graph(input_path):
"""
Converts a CRED-like graph into a graph format supported by the igraph library. The input graph must have been
generated by cli2 CRED command (look for credResult.json)
:param input_path: The path to the CRED graph to convert (credResult.json)
"""
... | 57037a662d033a422965f3efe13f321a5bf7f128 | 3,639,034 |
from typing import List
def get_valid_classes_from_class_input(
class_graph: class_dependency.JavaClassDependencyGraph,
class_names_input: str) -> List[str]:
"""Parses classes given as input into fully qualified, valid classes.
Input is a comma-separated list of classes."""
class_names = ... | e93edea9692ab9c461ed744a8727effbf705fdea | 3,639,035 |
def us_ppop(ppop):
""" Determines if the ppop is in a valid format to be in the US """
# return false if it's null or not 7 digits long
if not ppop or len(ppop) != 7:
return False
ppop = ppop.upper()
if ppop[:2] in g_state_by_code or ppop[:2] in g_state_code_by_fips:
return True
... | afef4e7634034709f870379cd684a37a793c7ec5 | 3,639,036 |
def get_robotstxt_parser(url, session=None):
"""Get a RobotFileParser for the given robots.txt URL."""
rp = RobotFileParser()
try:
req = urlopen(url, session, max_content_bytes=MaxContentBytes,
allow_errors=range(600))
except Exception:
# connect or timeout errors a... | f838f8284b250133a1c5f0ca5d514756ff4f1eb0 | 3,639,038 |
def init_model(config, checkpoint=None, device='cuda:0'):
"""Initialize a model from config file.
Args:
config (str or :obj:`mmcv.Config`): Config file path or the config
object.
checkpoint (str, optional): Checkpoint path. If left as None, the model
will not load any we... | 494cbcb012978d49905318d92c136bc7c6241a79 | 3,639,039 |
def estimate_period(time, y, y_err, clip=True, plot=True, **kwargs):
"""
Run a Lomb-Scargle Periodogram to find periodic signals. It's recommended
to use the allesfitter.time_series functions sigma_clip and slide_clip beforehand.
Parameters
----------
time : array of float
e.g. time ar... | 23cc58d910ff5541847fa4d5892979aa312d1609 | 3,639,040 |
def get_test_packages():
"""Get a list of packages which need tests run.
Filters the package list in the following order:
* Check command line for packages passed in as positional arguments
* Check if the the local remote and local branch environment variables
have been set to specify a remote b... | 302a3136ec84e81a68348e5ff1bffa9c916f36a1 | 3,639,041 |
def decoding_character(morse_character):
"""
Input:
- morse_character : ๋ฌธ์์ด๊ฐ์ผ๋ก get_morse_code_dict ํจ์๋ก ์ํ๋ฒณ์ผ๋ก ์นํ์ด ๊ฐ๋ฅํ ๊ฐ์ ์
๋ ฅ์ด ๋ณด์ฅ๋จ
Output:
- Morse Code๋ฅผ ์ํ๋ฒณ์ผ๋ก ์นํํจ ๊ฐ
Examples:
>>> import morsecode as mc
>>> mc.decoding_character("-")
'T'
>>> mc.decoding_character(".")
'E'
>>>... | 29c3f99da372a713d349a0c7640403ae32c08aba | 3,639,042 |
def SparsityParametersAddDimMetadata(builder, dimMetadata):
"""This method is deprecated. Please switch to AddDimMetadata."""
return AddDimMetadata(builder, dimMetadata) | 5a7604ca44fbf3f2a1d520018269c472340511e5 | 3,639,043 |
def check_branch(payload, branch):
"""
Check if a push was on configured branch.
:param payload: Payload from web hook.
:param branch: Name of branch to trigger action on.
:return: True if push was on configured branch, False otherwise.
"""
if "ref" in payload:
if payload["ref"] == b... | 88bd0ebae330ee169e97a40aee208b2f92ee4a32 | 3,639,044 |
from typing import Union
def convert(q: Quantity, new_unit: Union[str, Unit], equivalencies=None) -> Quantity:
"""Convert quantity to a new unit.
:raises InvalidUnit: When target unit does not exist.
:raises InvalidUnitConversion: If the conversion is invalid.
Customized to be a bit more universal t... | 7d28a40d3da4a6189aeb9efb252f50088838a1f3 | 3,639,045 |
def randomized_pairwise_t_test(arr1, arr2, output=True):
"""
Perform a randomized pairwise t-test on two arrays
of values of equal size.
see Cohen, P.R., Empirical Methods for Artificial Intelligence, p. 168
"""
# Make sure both arrays are the same length
assert len(arr1) == len(arr2... | 92ceb071fcc03dd952a15ffe08f2bd305c603a39 | 3,639,046 |
from typing import Dict
from datetime import datetime
import uuid
def update_metadata(radar, longitude: np.ndarray, latitude: np.ndarray) -> Dict:
"""
Update metadata of the gridded products.
Parameter:
==========
radar: pyart.core.Grid
Radar data.
Returns:
========
metadata:... | ae4b26372221262426803f40394caa06245d5afb | 3,639,047 |
import copy
def idxsel2xsel(file, isel, dimensions, order):
""" convert a index space selection object to an xSelect object
"""
if not isinstance(isel, idxSelect):
raise TypeError('wrong argument type')
xsel = {}
xsel_size = {}
xsel_dims = {}
isarray = False
interp = False
... | ff00a7705a9ae1f633e7ec19682367ccfea2b7bf | 3,639,048 |
def _retrieve_max_kb_s_sent_state(status: FritzStatus, last_value: str) -> float:
"""Return upload max transmission rate."""
return round(status.max_bit_rate[0] / 1000, 1) | e1c0a710131289e457f3c15da411a7f8d17fdfc7 | 3,639,049 |
def user_detail(request, id, format=None):
"""
Retrieve, update or delete a server assets instance.
"""
try:
snippet = User.objects.get(id=id)
except User.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = UserSeriali... | 9339c85cec0b271d5eeb8a1caec976992869174a | 3,639,050 |
def _gsmooth_img(args):
"""
HELPER FUNCTION: private!
Smooth an image with a gaussian in 2d
"""
img,kernel,use_fft,kwargs = args
if use_fft:
return convolve_fft(img, kernel, normalize_kernel=True, **kwargs)
else:
return convolve(img, kernel, normalize_kernel=True, **kwargs) | 313a0c4475935665cb0e4c55bea343adf3a9fab4 | 3,639,051 |
def __logs_by_scan_id(scan_id, language):
"""
select all events by scan id hash
Args:
scan_id: scan id hash
language: language
Returns:
an array with JSON events or an empty array
"""
try:
logs = []
for log in send_read_query(
"select hos... | 26ef72dd2e0ed974a84f2ddc67e61fd90f769f17 | 3,639,053 |
def docs():
"""Redirect to documentation on Github
Route: /docs
Methods: GET
Return: redirect to webpage
"""
return redirect("https://kinsaurralde.github.io/ws_281x-lights/#/") | 18fbbf2e4d53c66545bdf1129de5d1d4ac5944fd | 3,639,054 |
def std(a, weights=None, axis=None, dtype=None, ddof=0, keepdims=False):
"""
Compute the weighted standard deviation along the specified axis.
:param a: Array containing numbers whose standard deviation is desired. If `a` is not an
array, a conversion is attempted.
:param weights: Array contain... | 758421b85657197413ab4fe2713bf18da2ac184a | 3,639,055 |
import logging
def createOneHourCandles(markets, database):
"""
Function that creates tables for one minute candles.
:param database:
:param markets:
:return:
"""
conn = pymysql.connect(host='localhost',
user='jan',
password='17051982',
da... | c800570a4dd17acb0b588064938ccf098e6c53bb | 3,639,056 |
def coaddspectra(splist,plotsp=True,outf=None,sn_smooth_npix=10):
""" Coadd spectra
Parameters
----------
splist : list of XSpectrum1D objects
List of spectra to coadd
plotsp : bool
If True, plot the coadded spectrum
outf : str
Output file
sn_smooth_npix : float
... | 1e0c312389f566a34cca878251b7d808968e175c | 3,639,057 |
def get_rel_sim(relation, question, dataset):
"""
Get max cosine distance for relations
:param relation:
:param question:
:return:
"""
query_ngrams = generate_ngrams(question)
query_ngrams_vec = [get_avg_word2vec(phr, dataset) for phr in query_ngrams]
relation_ngram = get_avg_word2ve... | 63c313fac32ec2483979585c60cea916979aaf5d | 3,639,058 |
def mk_request(bits, cn):
"""
Create a X509 request with the given number of bits in they key.
Args:
bits -- number of RSA key bits
cn -- common name in the request
Returns a X509 request and the private key (EVP)
"""
pk = EVP.PKey()
x = X509.Request()
rsa = RSA.gen_key(bits,... | f6ac4fe385caba149b85599fa6f48fc3d0dc7ccf | 3,639,059 |
import re
def nice(name):
"""Generate a nice name based on the given string.
Examples:
>>> names = [
... "simple_command",
... "simpleCommand",
... "SimpleCommand",
... "Simple command",
... ]
>>> for name in names:
... nice(... | ab96675423812a85744bb76e7f62d08bbbac2eea | 3,639,060 |
def get_outputs():
"""Get the available outputs, excluding outputs in the EXCLUDED_OUTPUTS variable."""
outputs = []
tree = connection.get_tree()
for node in filter(
lambda node: node.type == "output" and node.name not in EXCLUDED_OUTPUTS, tree
):
workspaces = node.nodes[1].nodes
... | 6db1ea83252a7a6f4fd7f731c206c5d4a738a282 | 3,639,061 |
def get_user_owner_mailboxes_tuples(user):
"""
Return owned mailboxes of a user as tuple
"""
return ((owned_mailbox.id, owned_mailbox.email_address) for owned_mailbox in get_user_owner_mailboxes_query(user)) | e7db6658497678387f4a93237b686d29bc27d91f | 3,639,062 |
def modinv(a, m):
"""Modular Multiplicative Inverse"""
a = a % m
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m | 9ddea93398f8c96f828a8efaea36f21f6b8dd13e | 3,639,063 |
import socket
def get_ip():
"""Get the ip of the host computer"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('1.1.1.1', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP | fb4f79eaa25573d7078f69c5d5ad71c51c9d1c44 | 3,639,064 |
def available_structure_info():
""" Lists available attributes for :func:`abagen.mouse.get_structure_info`
"""
return _STRUCTURE_ATTRIBUTES.copy() | 14591c89c9f7212440da282f50408459692d1fc4 | 3,639,065 |
def centos(function):
"""Decorator to set the Linux distribution to CentOS 7"""
def wrapper(*args, **kwargs):
hpccm.config.g_linux_distro = linux_distro.CENTOS
hpccm.config.g_linux_version = StrictVersion('7.0')
return function(*args, **kwargs)
return wrapper | 9c54a7aac46bd30d490c625afa4392d5127a2be7 | 3,639,066 |
def Normalized2(p):
"""Return vector p normlized by dividing by its squared length.
Return (0.0, 1.0) if the result is undefined."""
(x, y) = p
sqrlen = x * x + y * y
if sqrlen < 1e-100:
return (0.0, 1.0)
else:
try:
d = sqrt(sqrlen)
return (x / d, y / d)
... | 42cc78350f264226c624a81ca5b0bd6457d353b0 | 3,639,067 |
def findwskeyword(keyword, sol):
"""Find and return a value for a keyword in the list of the wavelength solution"""
i = sol.index(keyword)
j = sol[i:].index('\n')
return sol[i:i + j].split('=')[1].strip() | b3cc028415d74ecfd7ec3868ae591d7b4d3b8860 | 3,639,068 |
import numpy
from typing import Tuple
from typing import Callable
from typing import Union
from typing import List
def algorithm(array: numpy.array, start: Tuple[int, int], end: Tuple[int, int],
heuristic: Callable = manhattan) -> Union[List, None]:
"""
Returns a list of all points, for the path... | 9a91e27bc0dbe78f7b2801dbdfbef6747a845aa7 | 3,639,069 |
from . import logger
def MFString(string_list):
"""
input a list of unicode strings
output: a unicode string formed by encoding, enclosing each
item in double quotes, and concatenating
27 Nov 2016: The complete case is as yet unimplemented,
to avoid sending bad X3D into the world will ins... | a068c25ab157b5537ea47e625ca8ed9aecd0f4e5 | 3,639,070 |
def re_allocate_memory(ptr: VoidPtr, size: int)-> VoidPtr:
"""
Internal memory free
ptr: The pointer which is pointing the previously allocated memory block by allocate_memory.
size: The new size of memory block.
"""
return _rl.MemRealloc(
ptr,
_to_int(size)
) | 806c17a6863db3af8c5b42474fe05c624685757c | 3,639,071 |
import json
def get_task_manager(setup_file, **kwargs):
""" Create a task manager of a correct type.
Parameters
----------
setup_file : string
File name of the setup file.
kwargs : dict
Additional kwargs.
Returns
-------
manager : TaskManager
Created task mana... | a297937fd4520549df034a22739250461cbf2c0e | 3,639,072 |
def format_time(time):
""" Converts datetimes to the format expected in SAML2 XMLs. """
return time.strftime("%Y-%m-%dT%H:%M:%SZ") | 03651b72aa0b177ac1ac3f1ccafdba6fe967a11a | 3,639,073 |
def get_delivery_voucher_discount(voucher, total_price, delivery_price):
"""Calculate discount value for a voucher of delivery type."""
voucher.validate_min_amount_spent(total_price)
return voucher.get_discount_amount_for(delivery_price) | 8ede095730c1d29d01949dff47b4a2893d29720c | 3,639,074 |
def has_admin_access(request):
# type: (Request) -> bool
"""
Verifies if the authenticated user doing the request has administrative access.
.. note::
Any request view that does not explicitly override ``permission`` by another value than the default
:envvar:`MAGPIE_ADMIN_PERMISSION` wi... | 54a109375c60354759d98177a2db275f627034b2 | 3,639,075 |
def model_selection(modelname, num_out_classes=2, pretrain_path=None):
"""
:param modelname, num_out_classes, pretrained, dropout:
:return: model, image size
"""
return TransferModel(modelchoice=modelname,
num_out_classes=num_out_classes,
pretrain_pa... | ef80dd1c5c52bc0d090801ebb1d5e17f303e48ad | 3,639,077 |
def stack1(x, filters, blocks, stride1=2, dilation=1, name=None):
"""A set of stacked residual blocks.
# Arguments
x: input tensor.
filters: integer, filters of the bottleneck layer in a block.
blocks: integer, blocks in the stacked blocks.
stride1: default 2, stride of the firs... | 43103a2bcad203b1b32f33e352960bdea8d526c9 | 3,639,078 |
def _CreateDynamicDisplayAdSettings(media_service, opener):
"""Creates settings for dynamic display ad.
Args:
media_service: a SudsServiceProxy instance for AdWords's MediaService.
opener: an OpenerDirector instance.
Returns:
The dynamic display ad settings.
"""
image = _CreateImage(media_servic... | c79145ec39a7aed97eea7efe9145eab5c706b146 | 3,639,079 |
def contacts_per_person_normal_00x30():
"""
Real Name: b'contacts per person normal 00x30'
Original Eqn: b'10'
Units: b'contact/Day'
Limits: (None, None)
Type: constant
b''
"""
return 10 | 1d0f7caaa4cceafbc34045b2983e388cd1169f8b | 3,639,080 |
def _get_scripts_shell(script_file): # type: (pathlib.Path) -> str
"""
Returns the shell used in the passed script file. If no shell is recognized exception is raised.
Depended on presence of shebang.
Supported shells: Bash, Fish, Zsh
:param script_file:
:return:
:raises exceptions.Unknow... | 74332334d9b3caf1be720d656ca6e64f4971e35e | 3,639,081 |
from shutil import which
def is_cmd_tool(name):
"""
Check whether `name` is on PATH and marked as executable.
From: https://stackoverflow.com/a/34177358
"""
return which(name) is not None | a35f84f1bf46aedac488a31402996f075fbe80e2 | 3,639,082 |
import pickle
def load_model(model: Model, language=()):
"""Load geo model and return as dict."""
log.info("Reading geomodel: %s", model)
with open(model.path, "rb") as infile:
m = pickle.load(infile)
result = defaultdict(set)
for _geonameid, l in list(m.items()):
result[l["name"]... | af77d0e0835b8be6b7b87b142141f4c50082a0ae | 3,639,083 |
def saml_metadata_generator(sp, validated=True, privacypolicy=False, tree=None, disable_entity_extensions=False):
"""
Generates metadata for single SP.
sp: ServiceProvider object
validated: if false, using unvalidated metadata
privacypolicy: fill empty privacypolicy URLs with default value
tree... | 78f065fe7962e7221626c41b81b550ceaa9e7370 | 3,639,084 |
def normalize_not_found(wrapped):
"""View decorator to make 404 error messages more readable"""
def wrapper(context, request):
# Replace incoming 404 with one that has a sensible message
response = wrapped(_standard_not_found(), request)
return response
return wrapper | 2a9a696c98b777e4f7295015840fbff6235092e7 | 3,639,087 |
def process_results(unprocessed, P, R, G):
"""Process the results returned by the worker pool, sorting them by
policy and run e.g. results[i][j][k] are the results from policy i
on run j on graph k. Parameters:
- unprocessed: Unprocessed results (as returned by the worker pool)
- P: number of po... | 24c2854723b3fc33c3fee58595f84d789e861fbc | 3,639,089 |
def make_inline_table(data):
"""Create an inline table from the given data."""
table = tomlkit.inline_table()
table.update(data)
return table | c70352de9a716ad5d3f1f33b33ea65c10ebc8f98 | 3,639,090 |
def _mi_dc(x, y, k):
"""
Calculates the mututal information between a continuous vector x and a
disrete class vector y.
This implementation can calculate the MI between the joint distribution of
one or more continuous variables (X[:, 1:3]) with a discrete variable (y).
Thanks to Adam Pocock, t... | 35b1295739d9df390980db11b7f03976c5ada3de | 3,639,091 |
def get_new_deals_intent_handler(handler_input):
"""
Purpose:
Handler for getting new deals
Args:
handler_input (Dict): Input data from the Alexa Skill
Return:
alexa_reponse (Dict): Reponse for Alexa Skill to handle
"""
feed = get_slickdeals_feed(SLICKDEALS_URL)
deal... | 7c30af6414a99193d5a7f97f58285b06571c85fa | 3,639,092 |
def analyse_dataset(imgs, lbls, name=None):
"""Analyse labelled dataset
# Arguments:
imgs: ndarray, a set of images
lbls: ndarray, labels for a set of images
"""
if name is not None:
print('Dataset: {}'.format(name))
unique_lbl, counts = np.unique(lbls, return_counts=True)
min_... | a6eabfab49b4bdc8590b64275ee2d0bcd19b9a0b | 3,639,094 |
def transform(doc, *, sort_keys=False):
"""reorder"""
heavy_defs = ["definitions", "schemas", "responses", "parameters", "paths"]
r = make_dict()
for k, v in doc.items():
if k in heavy_defs:
continue
r[k] = v
for k in heavy_defs:
if k in doc:
r[k] = do... | 3b939ac3185cdae147709bab1709dd1a39d426c9 | 3,639,095 |
from typing import Optional
from typing import List
def plot_card(
box: str,
title: str,
data: PackedRecord,
plot: Plot,
events: Optional[List[str]] = None,
commands: Optional[List[Command]] = None,
) -> PlotCard:
"""Create a card displaying a plot.
Args:
... | fe1816d045bcf59cb28e29c90e517c79df82c621 | 3,639,096 |
def get_cluster_id(url):
"""
Google assign a cluster identifier to a group of web documents
that appear to be the same publication in different places on the web.
How they do this is a bit of a mystery, but this identifier is
important since it uniquely identifies the publication.
"""
vals =... | 95a5f554560fd219cd07cbd8c8e251e9c8bd4d5e | 3,639,097 |
from typing import List
def vol_allocation_factory(covs:List, pres:List=None)->[float]:
""" Allocate capital between portfolios using either cov or pre matrices
:param covs: List of covariance matrices
:param pres: List of precision matrices
:return: Capital allocation vector
"""
if pres is ... | 82e707f6d79e0c2b02c5c6f5acb4c6cce130bd4c | 3,639,098 |
import requests
def get_inspection_page(**kwargs):
"""Fetch inspection data."""
url = KING_COUNTY_DOMAIN + DATA_PATH
params = INSPECTION_PARAMS.copy()
for key, val in kwargs.items():
print(key)
if key in INSPECTION_PARAMS:
params[key] = val
resp = requests.get(url, para... | 70c2b95ea6e829f4231c887a59f717a68ede9327 | 3,639,099 |
import requests
import json
def get_table_count(url, table_id):
"""
Count the number of rowns in a ActivityTable
:param url:
:param table_id: The ActivityTable ID to update count from and return
:return: count : count of rows from ActivityTable
"""
token = ActivitySites.objects.get(site_id... | d7243c202317f0302fb2515f09aa096f0c275619 | 3,639,100 |
def get_audio_mfcc_features(txt_files, wav_files, n_input, n_context, word_num_map, txt_labels=None):
"""
ๆๅ้ณ้ขๆฐๆฎ็MFCC็นๅพ
:param txt_files:
:param wav_files:
:param n_input:
:param n_context:
:param word_num_map:
:param txt_labels:
:return:
"""
audio_features = []
audio_fea... | bed03fb10944d00e27af400776a8efc894770e46 | 3,639,101 |
def getOffsetsFromPixelFractions(col, row):
"""
Determine just the fractional part (the intra-pixel part) of the col,row position.
For example, if (col, row) = (123.4, 987.6), then
(colFrac, rowFrac) = (.4, .6).
Function then returns the offset necessary for addressing the interleaved PRF ar... | 4f5945f4e3e6e2dd71056b615dc3571f6ece42c6 | 3,639,102 |
def all_index(request):
"""
Inventory Index View
"""
# build changelist
item_changelist = HTSChangeList(request, Item,
list_filter=[],
search_fields=[],
list_per_page=200,
model_admin=ItemAdmin(Item, None)
)
context_dict = {
'item_changelist': item_ch... | 7fdd0b5f278b55767a7918e2977315312e823e93 | 3,639,103 |
def calcSeason(ra, time):
"""Calculate the 'season' in the survey for a series of ra/dec/time values of an observation.
Based only on the RA of the point on the sky, it calculates the 'season' based on when this
point would be overhead. To convert to an integer season label, take np.floor of the returned
... | 1309a302fac9d01d7b5567d5722bf8f04dc9b88e | 3,639,104 |
def set_node_event_info(info: NodeEventInfo) -> Item:
"""Encaches an item.
:param info: Node event information.
:returns: Item to be cached.
"""
if info.event_type in (
EventType.MONIT_CONSENSUS_FINALITY_SIGNATURE,
EventType.MONIT_BLOCK_FINALIZED,
EventType.MONIT_BLOCK... | 9ee50e73b1c50172ada1b6040b675cbda5aede44 | 3,639,105 |
def check_hashtarget(bible_hash, target):
""" tests if the biblepay hash is valid for the hashtarget, means that is it lower.
True = is lower and all is fine """
rs = False
try:
rs = int(bible_hash, 16) < int(target, 16)
except:
pass
return rs | a0041d8834b2a0af0a08c2562ffed599925ed5a8 | 3,639,106 |
def assert_and_infer_cfg_fl(cfg_fl, args, make_immutable=True, train_mode=True):
"""
Calls /semantic-segmentation/config.assert_and_infer_cfg and adds additional assertions
"""
if args.manual_client_setup:
cfg_fl.CLIENT.MANUAL = args.manual_client_setup
if cfg_fl.CLIENT.MANUAL:
prin... | b779e0a5f06d06b9ebc542f3cd7c190efb70bca5 | 3,639,107 |
def replace_service(name,
metadata,
spec,
source,
template,
old_service,
saltenv,
namespace="default",
**kwargs):
"""
Replaces an existing service with ... | e363ed9d9233ff6455963edba5bfa8109f6c7260 | 3,639,108 |
from typing import Optional
from typing import Dict
from typing import Any
from typing import List
from datetime import datetime
import logging
def timesketch_add_manual_event(
data: Text, timestamp: Optional[int] = 0,
date_string: Optional[Text] = '',
timestamp_desc: Optional[Text] = '',
attributes: ... | c84f04bbd3a9344c5797e6d79be141b05f6edae0 | 3,639,109 |
def filter_vcf_by_sex(vcf_file, data):
"""Post-filter a single sample VCF, handling sex chromosomes.
Handles sex chromosomes and mitochondrial. Does not try to resolve called
hets into potential homozygotes when converting diploid to haploid.
Skips filtering on pooled samples, we still need to impleme... | 6eb6528ce4deb86b8c8ecd8746143cb0f6c82fde | 3,639,110 |
def gen_spacer(spacer_char="-", nl=2):
"""
Returns a spacer string with 60 of designated character, "-" is default
It will generate two lines of 60 characters
"""
spacer = ""
for i in range(nl):
spacer += spacer_char * 60
spacer += "\n"
return spacer | 7434f191dafdf500c2fc3e67373afc664e543ce0 | 3,639,111 |
def repo_config_factory(repo_type, repo_id, repo_label, **kwargs):
"""
Constructs a repository configuration in form of a
TTL structure utilizing the TTL templates from
./repo_types_template.
"""
# Check if the repo_type is a known template
if repo_type not in REPO_TYPES:
raise Repos... | 3840d698691f226d56d25233c3fc00db23abd5d9 | 3,639,112 |
def oil_isothermal_density(rho: NDArrayOrFloat, p: NDArrayOrFloat) -> NDArrayOrFloat:
"""Calculates the oil density for a given pressure at 15.6 degC
B&W 1992 Equation 18
Args:
rho: The oil reference density (g/cc) at 15.6 degC
can be compensated for disovled gases by running `oil_rho_... | f8184f4820b5a19525b47f357b92ea7059e2bd74 | 3,639,113 |
def get_waveform_dataset(path):
"""Loads the waveform dataset from a given path.
Args:
path: The path to the .npz file containing the waveform data set.
Returns:
An array of waveform chunks loaded from the given path.
"""
dataset = np.load(path)['arr_0']
return dataset | 3d8e13cddd7abdb3bc459b68761e4a6385208c77 | 3,639,114 |
def untranslate_module_name(module):
"""Rename module names mention in JSON to names that we can import
This reverses the translation applied by translate_module_name() to
a module name available to the current version of Python.
"""
if PY3:
# remap `__builtin__` and `exceptions` to the `b... | fae87c9fb852ff1b6b82e4ebccf9c058fb4a313f | 3,639,117 |
def RGBRamp(size=256, upperValue=.6666666666666667):
"""Generate an RGB color ramp, values range from 0.0 to 1.0"""
assert size > 0
hsv = HSVRamp(size, upperValue)
rgb = Numeric.zeros( (hsv.shape[0], 3), viewerConst.FPRECISION )
for i in xrange(hsv.shape[0]):
rgb[i] = ToRGB(hsv[i])
retu... | 10be72b654ac9e36610bc4c08fd05edbba45de8a | 3,639,118 |
def find_poly_ras_intersect(shape, raster_dir, extension='.tif'):
""" Finds all the tiles falling within raster object
the get shape geometry should be seperated from the intesect check,
currently causes a exit code 139 on unix box
:param polygon:
:param extension:
:param raster_dir:
"""
... | 8f7ae23a2c442ff5b61bde46d8b42ac4c2c8eade | 3,639,119 |
from typing import Iterable
import requests
def Session(
retries: int = 10,
backoff_factor: float = 0.3,
allowed_methods: Iterable[str] = ('HEAD', 'TRACE', 'GET', 'POST', 'PUT', 'OPTIONS', 'DELETE'),
status_forcelist: Iterable[int] = (408, 429, 500, 502, 503, 504),
) -> requests.Session:
"""Return... | ca7d5f4d3f34e24c67eae47c01a6bd63796b03be | 3,639,120 |
def tp53():
"""Create a TP53 gene fixture."""
params = {
'label': 'tumor protein p53',
'concept_id': 'hgnc:11998',
'symbol': 'TP53',
'location_annotations': [],
'strand': None,
'locations': [
{
'_id': 'ga4gh:VCL._Cl_XG2bfBUVG6uwi-jHtCHa... | d1c41af9dce6b5eee3aa475c207a669529001b7d | 3,639,121 |
def factorOrder(factors, varOrder):
"""Return an order of factors for sampling given a variable order for sampling"""
pri = [0 for x in varOrder]
for i,x in enumerate(varOrder): # first, find position of each var in sampling order
pri[x]=i
factorOrder = [ Factor() for x in varOrder ] # fill order ... | 98ec337ab126d77b854be28f937eef392b9c8144 | 3,639,122 |
def home(request):
"""
rendering ui by template for homepage
this view never cache for delivering correct translation inside template
"""
template = loader.get_template('weather/home.html')
return HttpResponse(template.render({}, request)) | b2fdf6facd633441da9d11a53a781e9e418b42de | 3,639,124 |
def plot_histogram(df, path, col_x, ax=None, size=None, save=True, suffix=None,
show=False, **kwargs):
"""Geneate a histogram plot.
Args:
df (:class:`pandas.DataFrame`): Data frame to plot.
path (str): Path to data frame to use if ``df`` is None, also used
as ... | ec97358a9b7f8c3d20dd7a15d77b588fc2bffbe0 | 3,639,125 |
def __check_interface_state(duthost, interface, state='up'):
"""
Check interface status
Args:
duthost: DUT host object
interface: Interface of DUT
state: state of DUT's interface
Returns:
Bool value which confirm port state
"""
ports_down = duthost.interface_fac... | bc17d489064e9a81ec77dad5ab3682c9a96fa88d | 3,639,126 |
def find_dateTime_in_html(text):
"""
find dateTime in html
"""
r = findall('<time dateTime="(.*?)">', text)
if r:
return r
return [] | 0ba36b69a52f421e303da4c10b70362d6d724c96 | 3,639,127 |
import torch
def get_number_of_voxels_per_class(labels: torch.Tensor) -> torch.Tensor:
"""
Computes the number of voxels for each class in a one-hot label map.
:param labels: one-hot label map in shape Batches x Classes x Z x Y x X or Classes x Z x Y x X
:return: A tensor of shape [Batches x Classes] ... | 568a91639a42cf3cd3debe365c5a963512d95dfc | 3,639,128 |
def get_columns_width(user_width):
"""define width of the report columns"""
default_width = [30, 7, 60]
if not user_width:
return default_width
try:
return [7 if user_width[i] < 7 else user_width[i] for i in range(3)]
except (TypeError, IndexError):
_LOGGER.error(
... | 96901c79ac7ba2cf6d5dc56fe26d63e81a2437d4 | 3,639,129 |
def tx_failure():
"""
Failed ```tx```.
"""
message = request.args.get('m')
protocol = request.args.get('p')
address = request.args.get('a')
command = request.args.get('c')
repeats = request.args.get('r')
bits = request.args.get('b')
response = make_response(
render_... | f5938cf59207125030502113ce3b541301279b98 | 3,639,130 |
import pydoc
def read_docstring(object_):
"""
Returns object docstring without the FILE information.
"""
fmt = "```\n{}\n```\n"
docs = pydoc.plain(pydoc.render_doc(object_)).split("FILE")[0].rstrip()
return fmt.format(docs) | 5c21f6eadf400ac9316e3f44d98464536b9b7536 | 3,639,131 |
def _bernoulli_spiral(theta, theta_offset=0., *args, **kwargs):
"""Return Equiangular (Bernoulli's) spiral
Args:
theta: array-like, angles from polar coordinates to be converted
theta_offset: float, angle offset in radians (2*pi = 0)
Kwargs:
exp_scale: growth rate of the exponential
"""
exp_scal... | 3e889bc61ab8e93daefc2feeaad40ae86c167627 | 3,639,132 |
import httpx
import copy
def _redacted_to_curl(request: httpx.Request) -> str:
"""Pass through to curlify2.to_curl that redacts the authorization in the headers
"""
if (auth_header := request.headers.get('authorization')) is None:
return curlify2.to_curl(request)
req_copy = copy.copy(request)... | e3a713c3fcf6c875af4cae6ab4c5e696eb0bd432 | 3,639,133 |
def parse_scales_line(line):
"""
Args:
- line:
Returns:
- scales_dict
"""
def advance_past_token(str, token):
return str[str.find(token) + len(token):]
scales_dict = {}
line = advance_past_token(line, 'Scales:')
pair_str = line.split(',')
for pair_str in pair_str:
dname, scale = pair_str.split(':')... | b16e1f431b878aa6418beaed3f141fe928a229e1 | 3,639,135 |
import collections
def parse_remove_configuration(configuration):
"""
Turns the configuration line of splitting into a name and a set of params.
"""
if configuration is None:
return "None", None
print('conf', configuration)
conf_dict = collections.OrderedDict(configuration)
name ... | 40bf749c2e142cef534f945179b987fd3c7ba6d8 | 3,639,136 |
def _calc_cost_grad_first(data_input, w, label, features):
"""Calculate the partial cost and gradient."""
train_data = read_stage_file(data_input, features + [label])
size_train = train_data.shape[0]
labels = train_data[label].values
train_data = train_data[features].values
if size_train > 0:
... | d7b62ac39f824f7598cc83a078bc0f5e4e49c4ea | 3,639,137 |
def subtract_dbm(dbm1: float, dbm2: float):
"""Adds two decibel values"""
watt1 = dbm_to_watt(dbm1)
watt2 = dbm_to_watt(dbm2)
return watt_to_dbm(watt1 - watt2) | ea7c6f9372182a6a39d72265428e86b26b4da765 | 3,639,138 |
def focused_evaluate(board):
"""
Given a board, return a numeric rating of how good
that board is for the current player.
A return value >= 1000 means that the current player has won;
a return value <= -1000 means that the current player has lost
"""
score = board.longest_chain(board.ge... | b2cbb91cdb048ef41a13532e400173daa05af4b8 | 3,639,140 |
def tanh(x, name=None):
"""
sparse tanh activation, requiring x to be a sparse coo or sparse csr tensor.
.. math::
out = tanh(x)
Parameters:
x (Tensor): The input Sparse Tensor with data type float32, float64.
name (str, optional): Name for the operation (optional, default is ... | 24bf0889c2e1ba642442e0d8f6b11eeeaf94bf6c | 3,639,141 |
def collector(monkeypatch):
"""
Unit test: base case
"""
col = SunPowerPVSupervisorCollector(use_device_data_timestamp=False)
attrs = [
'connect',
'disconnect',
'info_metrics',
]
mocked = MagicMock()
mocked.connect.return_value = []
mocked.disconnect.return_... | f9e99071b2dde231b4a3fc7c89e00846d26efb12 | 3,639,143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.