content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def encode_extended(values, value_range):
"""Encode data using Google's "extended" encoding for the most granularity."""
return "".join(num2chars(v, value_range) for v in values) | b5d980f26b77cb9f0ffedcfb9b5cdb7a29afa8ff | 3,630,221 |
import string
def part_b(puzzle_input, workers=5, offset=60):
"""
Calculate the answer for part_b.
Args:
puzzle_input (list): Formatted as the provided input from the website.
Returns:
string: The answer for part_b.
"""
deps = parse_deps(puzzle_input)
finished = []
qu... | b9484aa9c66d425798fa806b84e6bd7c31a4eb1f | 3,630,223 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up a National Weather Service entry."""
latitude = entry.data[CONF_LATITUDE]
longitude = entry.data[CONF_LONGITUDE]
api_key = entry.data[CONF_API_KEY]
station = entry.data[CONF_STATION]
client_session = async_get_clien... | 2a7acda783a3ee29289cec651f530281af52e199 | 3,630,224 |
def cov_hvus(data1,data2,label):
"""
Estimate the covariance of hvus between two classifiers/features based on graph theory
Parameters
----------
data1 : array-like of shape (n_samples,)
samples' value from classifier1
data2 : array-like of shape (n_samples,)
samples' value ... | 4ab273d7a94f85a55fcfe4c67255e8714f04da5f | 3,630,225 |
import re
def clean(s):
"""
remove symbols and lowercase
"""
regex = re.compile('\W+')
s = regex.sub(' ', s).strip()
return s.lower() | f0f71dacac0d792c10480f9eec605bc85bf58be0 | 3,630,226 |
def trueifset(xeval, typematch=False):
"""return True if @xeval is set, otherwise False"""
if typematch:
if not (xeval is False or xeval is None): return True
else: return False
else:
if xeval: return True
else: return False | ff9ab55f869edc0fc784d9a34f55fe46652f22b5 | 3,630,227 |
def _generate_dash_manifest(encoding, output, output_path):
# type: (Encoding, Output, str) -> DashManifestDefault
"""
Creates a DASH default manifest that automatically includes all representations configured in
the encoding.
<p>API endpoint:
https://bitmovin.com/docs/encoding/api-reference/se... | 4a2563b48ac3977b16901f735aaf719bdffe97f9 | 3,630,228 |
def shipping():
"""The webapp's page for viewing the shipping status of work orders.
This allows the employee to review existing work orders and see if they are ready to ship or not."""
# if the current user is not authenticated, redirect the user to the logged out index page
if not current_user.is_authenticated:
... | 25c6a9bb71744b63a102751dc1c675137008a514 | 3,630,229 |
def get_file_content(file: str) -> str:
"""
Get file content.
"""
try:
with open(file, 'r') as f:
content = f.read()
return content
except IOError as e:
print(e)
print('Exiting...')
exit(1) | c10407d73ba2cd2d84eb99c0f131d3895ede460d | 3,630,230 |
import types
def simplify_name_to_string(input_name):
"""
``simplify_name_to_string`` simplifies a templated C++ name with default arguments and returns a string
:param input_name: String or qualified name to be simplified
:type input_name: Union[str, QualifiedName]
:return: simplified name (or original name if... | 218b4289612849d0cc4b24b541882ba7bb9240b9 | 3,630,231 |
def _normalize_index(index, axis_size):
"""Normalizes an index value in the range [-N, N) to the range [0, N)."""
return lax.select(
lax.lt(index, _constant_like(index, 0)),
lax.add(index, _constant_like(index, axis_size)),
index) | e3175d169b2179493125b58ee49b79bb39843e51 | 3,630,232 |
def english_to_french(english_text):
#write the code here
"""class docstring
code to translate english text to french"""
translation = language_translator.translate(
text = english_text, model_id = "en-fr"
).get_result()
french_text = translation["translations"][0]["translation"]
... | a806a9b7d0beb267d02096dd21a4711aba506417 | 3,630,233 |
def get_sampling_distribution(samples):
"""
Get the sampling distribution of all samples of a population.
Parameter: a list of lists containing all possibile samples of a distribution.
Returns: sampling distribution, which is the list of means of all samples given.
"""
sampling_distribution = ... | 2f5bdfe89ed6886c4d858846c6d40b6aa04fc483 | 3,630,234 |
import torch
def compute_loss3D(embeddings, labels, device, temperature=0.7):
"""
embeddings: a B, C, D, H, W array
lables: B, 1 array
device: torch.device instance, either cuda or cpu
"""
# all of them are 3d embeddings, I again need to separate
# them and then do the dot prod... | 53cc363fe8fc9266f5143d4641e63e1f8491f0d1 | 3,630,235 |
def grad_polynomial_bases(X, N):
"""
Compute the gradients of the monomial bases.
Parameters
----------
X : ndarray
contains the points to evaluate the monomials
N : int
the maximum degree of the monomial basis
Returns
-------
dB : ndarray
contains the grad... | 5d2ae8fdbfae187b05ea1b3186e307468cabbb04 | 3,630,236 |
def hor1f(x, z, offset=1):
"""
BROKEN: Haven't quite figured this one out
Calculate the horizon pixel for all x,z
This mimics the algorthim from Dozier 1981 and the
hor1f.c from IPW
Works backwards from the end but looks forwards for
the horizon
xrange stops one index before [stop]
... | 21612c6b9b4243d57ef91c649b593e92babdde90 | 3,630,237 |
def make_multi_class_binomial_deviance(n_class, alpha=2., beta=0.5, cy=25., sim='cosine'):
""" Builder for the Binomial Deviance loss function. Ref:
https://papers.nips.cc/paper/6464-learning-deep-embeddings-with-histogram-loss.pdf
Note that the batch must be built using M exclusive classes and N images pe... | 5a5cae1f6e80060d1c81acc7e7811963f9e11771 | 3,630,238 |
import json
from collections import OrderedDict
def json_to_odict(json_series):
"""
Load a JSON series into OrderedDict
"""
odict = json.loads(js, object_pairs_hook=OrderedDict)
return odict | 20c377fef580660b583f87e2c447ed978821113d | 3,630,239 |
import typing
def sectors_performance(
apikey: str, limit: int = DEFAULT_LIMIT
) -> typing.List[typing.Dict]:
"""
Query FMP /sectors_performance/ API
:param apikey: Your API key.
:param limit: Number of rows to return
:return: A list of dictionaries.
"""
path = f"sectors-performance"
... | 03d8f1ee35f68d93c0c1536aea0d0e9d232f1782 | 3,630,240 |
from datetime import datetime
def _prepTrends(rawReport, startDt, numFiles, countMonth, granularity):
"""
Helper function which reformats data into list of lists with correct data
types. If anything is empty or has incorrect data, then an empty list is
returned.
"""
#load each rawReport into separate list
repo... | 2f416f04fc930d9729d5ef54a901963e33021fba | 3,630,241 |
def drift(ips, tau):
"""Drift operator.
"""
if ips.include_pn_corrections:
return drift_pn(ips, tau)
return drift_n(ips, tau) | 30ea7822ba8cce35e86b82deb3f92154f15d7603 | 3,630,242 |
def F1Score4(pred, groundtruth):
"""
# N A O P
# Normal AF Other Noisy Total
#Normal Nn Na No Np ∑N
# AF An Aa Ao Ap ∑A
#Other On Oa Oo Op ∑O
#Noisy Pn Pa Po Pp ∑P
#Total ∑n ∑a ∑o ∑p
"""
pred_len = len(pred)
re_table =np.zeros([4,4])
for i in range(pred_... | b3019f13939de99bda714e99894947d2de636390 | 3,630,243 |
from datetime import datetime
import tqdm
from functools import cmp_to_key
def get_point_pixel_values(
coords,
start_date: datetime = date.today() - timedelta(days=365),
end_date: datetime = date.today(),
ascending: bool = True,
orbit_number: object = None,
scale: int = 20,
n_jobs: int = 1... | e86fd02e58d23b74f64608071abf8826399c3cd3 | 3,630,244 |
from typing import Union
from typing import Optional
from typing import Tuple
from typing import List
def any(x: Union[ivy.Array, ivy.NativeArray],
axis: Optional[Union[int, Tuple[int], List[int]]] = None,
keepdims: bool = False)\
-> ivy.Array:
"""
Tests whether any input array element... | 2712ba15f571ecbe00e66a6ddb16695017ee6ccf | 3,630,245 |
def _filter_in_wet_days(da: DataArray, dry_day_value: float):
"""
Turns non wet days to NaN.
dry_day_value may be Nan or 0.
"""
precip = convert_units_to(da, "mm/d")
return precip.where(precip > 1, dry_day_value) | 739a210d772a6d124fceb50258d46012cb5b3060 | 3,630,246 |
def codemirror_field_css_assets(*args):
"""
Tag to render CodeMirror CSS assets needed for all given fields.
Example:
::
{% load djangocodemirror_tags %}
{% codemirror_field_css_assets form.myfield1 form.myfield2 %}
"""
manifesto = CodemirrorAssetTagRender()
manifesto.r... | bd127a3974ba9a12568359ed0dc0af99e31aa38f | 3,630,247 |
def for_stmt(target, iter_, body, orelse, local_writes):
"""Functional form of a for statement."""
if tf.is_tensor(iter_):
local_writes = [
var for var in local_writes if not py_defaults.is_undefined(var.val)
]
n = _tf_len(iter_)
def for_test(i, *_):
return i < n
def for_body(i... | f47a11ebee4143b0c0f92e8c7fb814ecfd79e91f | 3,630,249 |
def is_running():
"""Return if the main global loop is running."""
global __loop__
return __loop__ is not None and __loop__.is_running() | 6698c224109d8de3f95ba894a18bc420ff7e5734 | 3,630,250 |
from functools import reduce
def build_web_site(resources, site_class=None):
"""Build a Twisted web Site instance for a specified dictionary of
resources.
:param dict resources:
Dictionary of path -> resource class mappings to create the site from.
:type site_class: Sub-class of Twisted's Sit... | 1087fb6550a60e09d515ff12494ba8b7a344a489 | 3,630,251 |
def CheckExpectedOutput(output, expected):
"""Assert that expected content appears in the output.
Arguments:
output: Output from a tool to be searched for matches
expected: An iterable which contains regular expressions, a match for
each of which must appear in 'output'
Returns the nu... | 88023bb5c2884213df192491487c6d8bc909c52d | 3,630,252 |
from functools import reduce
def vector_sum(vectors):
""" sums all corresponding elements """
return reduce(vector_add, vectors) | 54fe814c07c991099b300f56a9995934069d0e5b | 3,630,253 |
async def get_all_consent_documents(environment, access_token, deployment_id):
"""
Function: [get_all_consent_documents]
:param environment: The CARP [environment].
:param access_token: The [access_token].
:param deployment_id: The [deployment_id].
:return: Lists all consents documents by [deplo... | b699a40cd11229555be8cfb07cfdf063f0e895a0 | 3,630,254 |
def convert_to_time_series(dataset, sequence_len, input_dim, output_dim):
"""
Function to convert a sequential `dataset` into time series data
:param dataset: 1-D List containing sequential data
:param sequence_len: Number of time steps in each instance
:param input_dim: Dimension of input at each t... | 87b33ee5e8205229d6804225dd5f4e943b019773 | 3,630,255 |
from typing import Tuple
def get_ip_reputation_score(classification: str) -> Tuple[int, str]:
"""Get DBot score and human readable of score.
:type classification: ``str``
:param classification: classification of ip provided from GreyNoise.
:return: tuple of dbot score and it's readable form.
:rt... | a71ec03b176425040047695e73a8046742878137 | 3,630,256 |
def _cv_input_text(cfg):
"""Configure validation helper for input box (voluptuous)."""
minimum = cfg.get(CONF_MIN)
maximum = cfg.get(CONF_MAX)
if minimum > maximum:
raise vol.Invalid('Max len ({}) is not greater than min len ({})'
.format(minimum, maximum))
state = ... | 53a6a9025e8f10857e0a558e908acf10fa0eb473 | 3,630,257 |
def map_values(e):
"""
:rtype: Column
"""
return col(MapValues(ensure_column(e))) | 6008b81c07c3d7a283b30ba7de493b27a32541eb | 3,630,258 |
from typing import List
from typing import Dict
from typing import Tuple
from typing import Set
def find_connected_pattern(variables: List[str], triples: List[Dict[str, str]]) -> Tuple[Dict[str, str],int, Set[str]]:
"""Find the first pattern in a set of triples pattern connected to a set of variables"""
pos =... | 30e2fc143b0252faad597320eb5a22a4b5ee75e9 | 3,630,259 |
import hmac
def make_secure_val(val):
"""
Creates secure value using secret.
"""
return '%s|%s' % (val, hmac.new(secret, val).hexdigest()) | ce8f1af92e91c99a7cc7dcb6c536dd56403738cb | 3,630,260 |
import itertools
def get_forced_photometry_mp(table, ra_col_name, dec_col_name, surveys,
bands, apertures, fovs, image_folder_path, n_jobs=5,
auto_download=True,
verbosity=0):
"""Calculate forced photometry in multiprocessing mode.
... | b633c5cb07a555541ae351c8fd0de682f1b506fb | 3,630,262 |
def Any(x):
"""The Any type; can also be used to cast a value to type Any."""
return x | 88abecb27317e5bf16c5bd27c306ce800c7ac760 | 3,630,263 |
def resource_name_for_resource_type(resource_type, row):
"""Return the resource name for the resource type.
Each returned row contains all possible changed fields. This function
returns the resource name of the changed field based on the
resource type. The changed field's parent is also populated but is not us... | 500bc32be1765f1e516f4f7cd386b24c3c4f373f | 3,630,264 |
from re import M
import pprint
def compute_performance_metrics_binary(model, x, y, metric_names):
"""
Given a model (TensorFlow) and (x, y).
Compute accuracy, loss, True Positive, False Negative, False Positive, True Negative, Recall, Precision,
f1 score, Average Precision Recal... | 7f8912b845b1c6e4e8083458d7e79d1eba624c1f | 3,630,265 |
import re
def to_yw7(text):
"""Convert html tags to yWriter 6/7 raw markup.
Return a yw6/7 markup string.
"""
# Clean up polluted HTML code.
text = re.sub('</*font.*?>', '', text)
text = re.sub('</*span.*?>', '', text)
text = re.sub('</*FONT.*?>', '', text)
text = re.sub('</*SPAN.*?... | 59b9b961f7a94d23e2829b9d940f63c32207600b | 3,630,266 |
def decode_labels(mask, num_images=1, num_classes=21):
"""Decode batch of segmentation masks.
Args:
mask: result of inference after taking argmax.
num_images: number of images to decode from the batch.
num_classes: number of classes to predict (including background).
Returns:
A batch with num_im... | 967da7e34e993bf2eb4a2140898309811de79330 | 3,630,267 |
def get_base_url(hostname):
"""
Constructs the GitHub API url with the given hostname.
:param str hostname: Hostname to construct the API endpoint url.
:returns: None
:raises: None
"""
if hostname and hostname.startswith('http'):
return hostname
else:
return "https://{ho... | b0a13d3054fd48a9970c639ea8730d24a67a09ed | 3,630,268 |
import array
def gauss_sqrt_cov_ft(karr: array, width: float = 1.0) -> array:
"""sqrt of FFT of KD Gaussian covariance matrix
Square root of Fourier transform of a covariance matrix that is a Gaussian
function of difference in position
Returns
-------
karr : (L1,L2,...,LK/2+1,1,K)
Ar... | 5b16b19847706b9985855e1d32df3abab95685f3 | 3,630,269 |
def get_qt_lineedit_suffix(gb, suffix):
"""Gets the line edit associated with a tab and suffix.
Args:
gb (QtWidgets.QGroupBox): Group box for the tab.
suffix (str): Text appended to UI element search query.
Returns:
QtWidgets.QLineEdit: LineEdit matching val_{tag}_{suffix}.
"""... | 01443bf3d96a89037fdf9276d8e4bbb57f4e2175 | 3,630,270 |
import logging
def response_to_invalid_request(diameter_request,
origin_host,
origin_realm):
"""
Method used to respond to invalid Diameter request.
We define an invalid Diameter request by comparing its command code
with the ones that w... | da18bd3120e55c7a0b50940e57a83edb9fab4b72 | 3,630,272 |
def lsi_model(tmp_corpus, temp_dict):
""" creates an latent semantic indexing model from
a corpus of words and a dictionary using gensim
Args:
tmp_corpus (list): a list of words from dict
temp_dict (Dictionary): a gensim Dictionary
Returns:
a list of word vectors that comprise ... | a39fa884c9eb4fe08941f1ae1d51b7a6a8403d7f | 3,630,273 |
def kmeanssample(X, k, nsample=0, **kwargs):
""" 2-pass kmeans, fast for large N:
1) kmeans a random sample of nsample ~ sqrt(N) from X
2) full kmeans, starting from those centres
"""
# merge w kmeans ? mttiw
# v large N: sample N^1/2, N^1/2 of that
# seed like sklearn ?
N, dim =... | 3853349e42b2ce29384d202a381ce26a05f49a53 | 3,630,274 |
def get_real_resolution():
"""获取真实的分辨率"""
hDC = win32gui.GetDC(0)
# 横向分辨率
w = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES)
# 纵向分辨率
h = win32print.GetDeviceCaps(hDC, win32con.DESKTOPVERTRES)
return w, h | d8eac10bc449a3e1e44f983e9b2cf76494ef56e1 | 3,630,275 |
def op_acot(x):
"""Returns the inverse cotangent of this mathematical object."""
return op_inv(op_atan(x)) | 604b989524081078ab7a40e09c36b20ad6c52be3 | 3,630,276 |
import struct
import fcntl
import termios
def terminal_size():
"""
Get terminal size
Will return width and height
"""
if os_windows:
w = 80
h = 25
else:
h, w, hp, wp = struct.unpack(
'HHHH', fcntl.ioctl(0, termios.TIOCGWINSZ,
... | a88d7f869fc0de5a310d3390091a62c2dd44c1ac | 3,630,277 |
def get_most_popular():
"""
Helper which retrieves most popular urls based on `redirects`(desc) and
`created_at`(desc)
"""
return Url.objects.order_by('-redirects', '-created_at') | 660714f455e6e425698e4e1a86635b0d12a290f6 | 3,630,279 |
def eval_genomes(genomes, substrate, vd_environment, generation):
"""
The function to evaluate fitness of the entire population against test
visual descriminator environment using the provided substrate
configuration of the descriminatorANN
Arguments:
genomes: The list of genomes in... | 7d03f265820a5ea148c8df81262927a1b6acb578 | 3,630,280 |
def cosine_similarities(a, b, transform):
"""
returns list of cosine similarities between lists of vectors
a and b. The z_score transformation is applied if transform == True
"""
a = numpy.stack(a)
b = numpy.stack(b)
#transform if requested
if transform:
print "transforming"
... | 4164dcce80ba84ceb8b468b4db2d72b2ca8a10f7 | 3,630,281 |
def element_damage_nohitbox(raw_element, sharpness):
"""
Calculate elemental damage to a monster part with the given elemental
attack, the given sharpness, and the given monster elemental weakness.
Note that this is independent of the motion value of the attack.
"""
return (raw_element * Sharpne... | 10d527e1740172e2bba4f4fe9170dfe8f4218a98 | 3,630,282 |
def getTabData(header, index):
"""Get the table data at index from above tables generator.
Expects the header string and the index of the table."""
tabStart = header.index('{', index) + 1 #start of the table, first letter after {.
tabEnd = header.index('}', tabStart) #last of the array.
return header[tabStart:tabE... | 738e6f1532129043e67e1e639a66d12e43d1e9a6 | 3,630,283 |
def get_default_input_id():
"""gets default input device number
pygame.midi.get_default_input_id(): return default_id
Return the default device ID or -1 if there are no devices.
The result can be passed to the Input()/Ouput() class.
On the PC, the user can specify a default device by
setting ... | 482a02501343d365ea05bda825bc2d8560a687b3 | 3,630,284 |
def dict_merged(d, _filter=None, **kw):
"""Update dictionary d with the items passed as kw if the value passes _filter."""
def f(s):
if _filter:
return _filter(s)
return s is not None
d = d or {}
for k, v in kw.items():
if f(v):
d[k] = v
return d | 03df2c26975f114db1b6f258a4324d0d12109126 | 3,630,286 |
def check_latest_deploy(package, region, requirements_hash):
"""
Args:
package: Name of package to query
region: region to query for
requirements_hash: hash of requirements.txt file
returns:
Boolean: False if requirements hash matches latest deployhed version (doesn't need de... | 0f74fc73e7cb01d9c0f2e466246feba44021cb3f | 3,630,287 |
def docker_images(docker_url, query):
"""Looking for local images.
:param docker_url: Docker base url
:param query: image name lookup
:type docker_url: str
:type query: str
:returns: all matching images
:rtype: set
"""
cli = Client(base_url=docker_url)
results = set()
images... | 1e9dc9f9048985503ea53f90fbb1290ba3d7be38 | 3,630,288 |
def keyword_confirm(request, name=None):
"""."""
q_objects = Q()
q_objects.add(Q(target_species__icontains=name), Q.OR)
confirm_proteins = Association.objects.filter(q_objects)
confirm_proteins = _sorted_nicely(confirm_proteins, sort_key="name")
return render(
request,
"associat... | e1d97020e2267ff96c2f5d2c37315254621aaae4 | 3,630,290 |
from typing import Union
from typing import Optional
from typing import Callable
def day_dropdown_widget(
data: Union["LogData", pd.DataFrame], callback: Optional[Callable] = None
) -> "ipywidgets.Dropdown":
"""Create dropdown widget to filter log data by a specific day.
Parameters
----------
dat... | 87f0e7d527d74de0ccec98c42ac2127fcf1143b3 | 3,630,291 |
def is_node_valid(node: dict) -> bool:
"""
Returns True if the provided node contains a directive and token.
"""
result = False
if node:
if DIR in node and TOK in node:
result = True
return result | b99329e3a76705172f88fe62ecc6aee640aa1736 | 3,630,292 |
import pytz
def pytz_version():
"""Return the version of pytz as a tuple."""
year, month = pytz.__version__.split('.')
return int(year), int(month) | 0d28f0dcceb629168a997f01a5d07b89231e0894 | 3,630,294 |
def topological_sort(self):
"""
Returns:
List(int): Topological sort of vertices of a graph.
"""
topo_order = self.depth_first_search()[1]
position = [-1] * len(self.v)
for i, v in enumerate(topo_order):
position[v] = i
for u, v in self.e:
if positi... | ccd21c7486c3b32da1203015e77c24530d1f5e56 | 3,630,296 |
def construct_start_stop_intervals(intron_intervals, d):
"""Splits a iterable of intervals into two parallel tuples of 2d bp intervals representing their start and stop"""
left_intervals = []
right_intervals = []
for i in intron_intervals:
left_intervals.append(ChromosomeInterval(i.chromosome, i... | ee46c343d0a465a3b67b9f4990ebcc9d44cef669 | 3,630,297 |
def region_growing(image,coordinate,number):
"""Give coordinate and size,return a region."""
# tmp_image store marks and rg_image store new image after region grow
nt = number
tmp_image = np.zeros_like(image)
rg_image = np.zeros_like(image)
image_shape = image.shape
x = coordinate[0]
y ... | ee495848e6d9afd4f29bc97663f8804092b51559 | 3,630,298 |
def mock_subprocess(case_tuple):
"""We perform several subprocess.check_output calls, but we want to only mock
one of them at a time. This function helps us do that.
:type case_tuple: tuple of SubprocessMock
:param case_tuple: See docstring for SubprocessMock
"""
def fn(inputs, **kwargs):
... | 0c98028464633c01808108145a462c64ce7015bd | 3,630,299 |
import time
def wait_for_job(res, ping_time=0.5):
"""
Blocks execution and waits for an async Forest Job to complete.
:param JobResult res: The JobResult object to wait for.
:param ping_time: The interval (in seconds) at which to ping the server.
:return: The completed JobResult
"""
while... | 1a7202f58affa97b0001b246fb7cd187d6a59f44 | 3,630,300 |
def _retr():
"""retrieves a list of all connected spectrometers for all backends"""
params, ids = [], []
if not _running_on_ci():
csb_serials, psb_serials = set(), set()
for serials, backend in [(csb_serials, csb), (psb_serials, psb)]:
if backend is None:
continue... | 3b418fe367ed522f376d840efc0883bfd6ea6e60 | 3,630,301 |
def get_individual_annotations(self, all=False, imported=True):
"""Returns a dict with non-empty individual annotations.
If `all` is true, also annotations with no value are included.
If `imported` is true, also include annotations defined in
imported ontologies.
"""
onto = self.namespace.onto... | c817f51d4918cc97b97c8db2a6d33ce720c6f6aa | 3,630,302 |
def numeric_type(param):
"""
Checks parameter type
True for float; int or null data; false otherwise
:param param: input param to check
"""
if ((type(param) == float or type(param) == int or param == None)):
return True
return False | a5f67a30b3128c1214d8825abbc6ae5170680d80 | 3,630,303 |
def _pre_aggregate_df(df,
dims,
aggregate_dimensions,
show_control,
ctrl_id,
sort_by=None,
auto_decide_control_vals=False,
auto_add_description=True):
"""Process a ... | 6b32b772bd6d1437160c90fff4fb965761431596 | 3,630,304 |
def search_data_start(file, identifier, encoding):
"""
Returns the line of an identifier for the start of the data in a file.
"""
if identifier is None:
return 0
search = open(file, encoding=encoding)
i = 1
for line in search:
if identifier in line:
search.close()... | 2c3c903df2162b9f6fe5452b75c4f7ac06ddd194 | 3,630,306 |
def p_sha1(secret, seed, sizes=()):
"""
Derive one or more keys from secret and seed.
(See specs part 6, 6.7.5 and RFC 2246 - TLS v1.0)
Lengths of keys will match sizes argument
"""
full_size = 0
for size in sizes:
full_size += size
result = b''
accum = seed
while len(re... | f0080c973575537691779c50dd7d89fcefe0f2f5 | 3,630,307 |
def get_workload(batch_size, num_classes=1000, image_shape=(3, 224, 224), dtype="float32"):
"""Get benchmark workload for mobilenet
Parameters
----------
batch_size : int
The batch size used in the model
num_classes : int, optional
Number of classes
image_shape : tuple, option... | 1c86d4bd4322dbd8eaa9d07461ff900def79059a | 3,630,308 |
def delete_review(review_id):
"""
It allows the user to delete the review from the page
and automatically from the database as well.
Checks that the user deleting the review is the
creator of the review, as only the that user is allowed
to delete it's own content.
"""
review = mongo.db.... | d8d343ecf09e8f6de031e440e6a20b0b4b72bbe9 | 3,630,309 |
def quotient_mealy(mealy, node_relation=None, relabel=False, outputs={'loc'}):
"""Returns the quotient graph of ``G`` under the specified equivalence
relation on nodes.
Parameters
----------
mealy : NetworkX graph
The graph for which to return the quotient graph with the specified node
... | 9eb7b5652af276d9bfd2a23774fa91a68a5c90fc | 3,630,310 |
import requests
def perform_v1_search(khoros_object, endpoint, filter_field, filter_value, return_json=False, fail_on_no_results=False,
proxy_user_object=None):
"""This function performs a search for a particular field value using a Community API v1 call.
.. versionchanged:: 4.0.0
... | 00f7d6716529ff33342104776280da9dd8c788f2 | 3,630,312 |
def get_page_generator(s,max_items=0):
"""Get the generator that returns the Page objects
that we're interested in, from Site s.
"""
page_generator = s.allpages()
if(max_items>0):
page_generator.set_maximum_items(max_items)
return page_generator | d53a890523c999df878fecc71ef1dbd8d17c188c | 3,630,313 |
def get_num_in(profile, key_path):
"""Return the value pointed by the key path in the JSON profile."""
job = __get_job_obj(profile)
obj = job
for key in key_path:
obj = obj[key]
return obj | b432721c5813bfcb5927c39806ffac16470c4a58 | 3,630,314 |
def rl_modelrl_medium():
"""Small set for larger testing."""
hparams = rl_modelrl_base()
hparams.true_env_generator_num_steps //= 2
return hparams | 6cf1a50a9b3f6d00f8f5ec1cddf33d813d9899ab | 3,630,316 |
def check_flow_information(flow, search_name, pos):
""" Try to find out the type of a variable just with the information that
is given by the flows: e.g. It is also responsible for assert checks.::
if isinstance(k, str):
k. # <- completion here
ensures that `k` is a string.
"""
... | 0ec44d86f87337d5ee0768da19a43a61d6bd1d40 | 3,630,317 |
def accuracy_measures(predictions, trues):
"""Accuracy measures for the predictions of the method vs the groundtruth.
Prints a confusion matrix, accuracy, misclassifcation rate, true positieve rate, false positive rate, specificity, precision, prevalence.
Returns the accuracy score, precision score, and rec... | 306fe745e3ff860d5d99e63d276acaa6f9d369cd | 3,630,318 |
def segment_text_to_sentences(text_file, sentence_splitter):
""" Segment text into sentences. Text is provided by BRAT in .txt
file.
Args:
text_file (str): the full path to the BRAT .txt file.
sentence_splitter (spacy LM): SpaCy EN language model.
Returns:
... | d74857a4931d162b9573b1b086a8720563b4fd41 | 3,630,319 |
def get_folder_offset(folder_list, folder_name):
"""
Check whether there is already a folder named 'folder_name' and if so, increment a counter.
"""
isExists = False
# Check whether a folder with the same name already exists
for folder in folder_list:
if folder['title'] == folder_name:... | b620e6ee6819b2b1aac6b3fd6a05775cde34838e | 3,630,320 |
def get_coords_for_radius(radius):
""" Given a radius, will return x,y coordinates with x=y.
This is useful for plotting the relation between the undistorted and distorted radius.
"""
sq = radius**2;
coord = np.sqrt(sq / 2);
return coord, coord; | 455c6afda78e1ef28980e39278bd77896957a7bf | 3,630,321 |
def _parse_array(values):
""" parse a list of (string) values representing a fortran array
and return a python list
"""
assert type(values) is list
parsed_value = []
for v in values:
if '*' in v:
# 3* "a" === "a", "a", "a"
mult, val = v.split('*')
pars... | 17888b900e06db2d6e766d90cff7184191d2c228 | 3,630,322 |
def word_frequency(text: str, use_cases: bool = False) -> dict[str,int]:
"""
Returns a dictionary of the frequency of all words in given string.
All words turned to lowercase if use_cases left unspecified.
Parameters
------------
text: str
The text to find the word frequency of.
u... | 6acfddc093c68e97c7f014ab7c93e33fd034af25 | 3,630,323 |
def param_to_string(metric) -> str:
"""Convert a list / tuple of parameters returned from IE to a string"""
if isinstance(metric, (list, tuple)):
return ', '.join([str(x) for x in metric])
else:
return str(metric) | 54476f88936336728ba73425bb57860e17fb7561 | 3,630,324 |
def showStitchedModels_Redundant(mods, ax=None,
cmin=None, cmax=None, **kwargs):
"""Show several 1d block models as (stitched) section."""
x = kwargs.pop('x', np.arange(len(mods)))
topo = kwargs.pop('topo', x*0)
nlay = int(np.floor((len(mods[0]) - 1) / 2.)) + 1
if c... | 4b2428ab7d08c54b32e22c89785b3506e24e21f5 | 3,630,327 |
def export_16(text_col, processed_col, input_filepath,
output_filepath, country):
"""Takes in a file with 8 different sheets containing extracted text.
It will perform mulitple steps to clean the extracted text
and split each sheet into two smaller sheets.
Then export them individ... | 4c6f100c7fd992078f3e9e32aba494930464f625 | 3,630,328 |
import random
def generate_signal(ders, n, sampling, initial_state=None, number_of_variables=1, number_of_perturbations=1, warmup_time=1000.0, tau=3.0, eps=0.5, dt=0.01):
"""generates signal for the oscillator driven by correlated noise from dynamical equations
:param ders: a list of state variable derivatives
:... | f7ebd99aaaf0684b0c5c7a9380b18c6f00d70a50 | 3,630,329 |
def getReviewRedirect(entity, params):
"""Returns the redirect to review the specified entity.
"""
return '/%s/review/%s' % (
params['url_name'], entity.key().id_or_name()) | f13aecf226e38809d183d5482e29fe40dfdd40c5 | 3,630,331 |
import imgaug.random
def current_random_state():
"""Get or create the current global RNG of imgaug.
Note that the first call to this function will create a global RNG.
Returns
-------
imgaug.random.RNG
The global RNG to use.
"""
return imgaug.random.get_global_rng() | 1d9064c11ca40e8dca80d456f5a27f3bc92494c6 | 3,630,332 |
def get_remote_station(s3, bucket, dataset_id=None, station_id=None, stn_key=None, version=3):
"""
"""
if isinstance(dataset_id, str):
stn_key = key_patterns[version]['station'].format(dataset_id=dataset_id, station_id=station_id)
try:
obj1 = s3.get_object(Bucket=bucket, Key=stn_key)
... | 477ca3ff9e940d5745b97c082ca36ba17058850c | 3,630,333 |
def determine_smallest_atom_index_in_torsion(atom1: 'rdkit.Chem.rdchem.Atom',
atom2: 'rdkit.Chem.rdchem.Atom',
) -> int:
"""
Determine the smallest atom index in mol connected to ``atom1`` which is not ``atom2``.
Retur... | 40ea2e151bd343fff208cb77e14122d021ee4733 | 3,630,335 |
import numpy
from typing import Optional
def structured_array_generic_full(
request: Request,
reader=Depends(reader),
slice=Depends(slice_),
expected_shape=Depends(expected_shape),
format: Optional[str] = None,
serialization_registry=Depends(get_serialization_registry),
):
"""
Fetch a ... | ffc68744741d66f36dd38b23996cf790eff10ff8 | 3,630,336 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.