uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d8a2f308655483d8b7fb21b9 | train | function | def get_time_from_rfc3339(rfc3339):
"""
return time tuple from an RFC 3339-formatted time string
:param rfc3339: str, time in RFC 3339 format
:return: float, seconds since the Epoch
"""
try:
# py 3
dt = dateutil.parser.parse(rfc3339, ignoretz=False)
return dt.timestamp... | def get_time_from_rfc3339(rfc3339):
| """
return time tuple from an RFC 3339-formatted time string
:param rfc3339: str, time in RFC 3339 format
:return: float, seconds since the Epoch
"""
try:
# py 3
dt = dateutil.parser.parse(rfc3339, ignoretz=False)
return dt.timestamp()
except NameError:
# p... | git_uri = git_uri.rstrip('/')
if git_uri.endswith("/.git"):
git_uri = git_uri[:-5]
elif git_uri.endswith(".git"):
git_uri = git_uri[:-4]
return os.path.basename(git_uri)
def get_time_from_rfc3339(rfc3339):
| 64 | 64 | 177 | 13 | 51 | hjmodi/osbs-client | osbs/utils/__init__.py | Python | get_time_from_rfc3339 | get_time_from_rfc3339 | 379 | 399 | 379 | 379 | 6af2efbe1b86fea56332eda378f0d218e77c8ca7 | bigcode/the-stack | train |
02f55ff007dfc8d911a5a4cc | train | function | def looks_like_git_hash(git_ref):
return all(ch in string.hexdigits for ch in git_ref) and len(git_ref) == 40
| def looks_like_git_hash(git_ref):
| return all(ch in string.hexdigits for ch in git_ref) and len(git_ref) == 40
| osbs.resume_builds(quota_name=quota_name)
except OsbsResponseException as e:
if ignore_quota_errors and (e.status_code == requests.codes.FORBIDDEN):
logger.warning("Ignoring resourcequota error")
else:
raise
def looks_like_git_hash(git_ref):
| 64 | 64 | 34 | 9 | 54 | hjmodi/osbs-client | osbs/utils/__init__.py | Python | looks_like_git_hash | looks_like_git_hash | 351 | 352 | 351 | 351 | d6d17458c0a30f6d69ce503cbc92a5dc90450b80 | bigcode/the-stack | train |
df72ebdf1d0c212fbd16db03 | train | function | def graceful_chain_get(d, *args):
if not d:
return None
t = copy.deepcopy(d)
for arg in args:
try:
t = t[arg]
except (IndexError, KeyError):
return None
return t
| def graceful_chain_get(d, *args):
| if not d:
return None
t = copy.deepcopy(d)
for arg in args:
try:
t = t[arg]
except (IndexError, KeyError):
return None
return t
| if ti is None:
self.close()
raise StopIteration()
return self.TarFile(ti.name, self.tarfile.extractfile(ti))
next = __next__ # py2 compatibility
def close(self):
self.tarfile.close()
def graceful_chain_get(d, *args):
| 64 | 64 | 57 | 9 | 55 | hjmodi/osbs-client | osbs/utils/__init__.py | Python | graceful_chain_get | graceful_chain_get | 138 | 147 | 138 | 138 | d2a4a43d7b6f02fc10a2ed41228d716f4c5f570a | bigcode/the-stack | train |
4908383416bbdd2ac6213f9d | train | function | def sanitize_strings_for_openshift(str1, str2='', limit=LABEL_MAX_CHARS, separator='-',
label=True):
"""
OpenShift requires labels to be no more than 64 characters and forbids any characters other
than alphanumerics, ., and -. BuildConfig names are similar, but cannot cont... | def sanitize_strings_for_openshift(str1, str2='', limit=LABEL_MAX_CHARS, separator='-',
label=True):
| """
OpenShift requires labels to be no more than 64 characters and forbids any characters other
than alphanumerics, ., and -. BuildConfig names are similar, but cannot contain /.
Sanitize and concatanate one or two strings to meet OpenShift's requirements. include an
equal number of characters from... | Return current time in UTC.
This function is created to make mocking in unit tests easier.
"""
return datetime.utcnow()
VALID_BUILD_CONFIG_NAME_CHARS = re.compile('[-a-z0-9]')
VALID_LABEL_CHARS = re.compile(r'[-a-z0-9\.]')
LABEL_MAX_CHARS = 63
def sanitize_strings_for_openshift(str1, str2='', limit=L... | 97 | 97 | 326 | 28 | 68 | hjmodi/osbs-client | osbs/utils/__init__.py | Python | sanitize_strings_for_openshift | sanitize_strings_for_openshift | 416 | 449 | 416 | 417 | 8a4961002a803f3c1053e3b378a0ad05314a032c | bigcode/the-stack | train |
fded9c5d6b84e4fb49de3d0c | train | function | def retry_on_gateway_timeout(func):
@wraps(func)
def retry(*args, **kwargs):
# Only retry when OsbsResponseException was raised due to gateway error
def should_retry_cb(ex):
return ex.status_code == http_client.GATEWAY_TIMEOUT
retry_func = RetryFunc(OsbsResponseException, sh... | def retry_on_gateway_timeout(func):
@wraps(func)
| def retry(*args, **kwargs):
# Only retry when OsbsResponseException was raised due to gateway error
def should_retry_cb(ex):
return ex.status_code == http_client.GATEWAY_TIMEOUT
retry_func = RetryFunc(OsbsResponseException, should_retry_cb=should_retry_cb,
... | OsbsResponseException, should_retry_cb=should_retry_cb,
retry_times=OS_NOT_FOUND_MAX_RETRIES,
retry_delay=OS_NOT_FOUND_MAX_WAIT)
return retry_func.go(func, *args, **kwargs)
return retry
def retry_on_gateway_timeout(func):
@wraps(func)
| 64 | 64 | 116 | 13 | 50 | hjmodi/osbs-client | osbs/utils/__init__.py | Python | retry_on_gateway_timeout | retry_on_gateway_timeout | 565 | 577 | 565 | 566 | 8355130d059ac661acaa015b466c87d81f2838c3 | bigcode/the-stack | train |
ee7a36b04a7748cb536efde0 | train | class | class RegistryURI(object):
# Group 0: URI without path -- allowing empty value -- including:
# - Group 1: optional 'http://' / 'https://'
# - Group 2: hostname and port
# Group 3: path, including:
# - Group 4: optional API version, 'v' followed by a number
versionre = re.compile(r'((https?://)?(... | class RegistryURI(object):
# Group 0: URI without path -- allowing empty value -- including:
# - Group 1: optional 'http://' / 'https://'
# - Group 2: hostname and port
# Group 3: path, including:
# - Group 4: optional API version, 'v' followed by a number
| versionre = re.compile(r'((https?://)?([^/]*))(/(v\d+)?)?$')
def __init__(self, uri):
match = self.versionre.match(uri)
if not match:
raise ValueError('Invalid registry URI {}'.format(uri))
groups = match.groups()
self.docker_uri = groups[2]
self.version = gr... | class RegistryURI(object):
# Group 0: URI without path -- allowing empty value -- including:
# - Group 1: optional 'http://' / 'https://'
# - Group 2: hostname and port
# Group 3: path, including:
# - Group 4: optional API version, 'v' followed by a number
| 77 | 69 | 232 | 77 | 0 | hjmodi/osbs-client | osbs/utils/__init__.py | Python | RegistryURI | RegistryURI | 58 | 83 | 58 | 63 | 18e0bb38dc54916ea81bc40c9dda1f6d55398627 | bigcode/the-stack | train |
5fb0ae1e33929e96ce5528eb | train | function | def make_name_from_git(repo, branch, limit=53, separator='-', hash_size=5):
"""
return name string representing the given git repo and branch
to be used as a build name.
NOTE: Build name will be used to generate pods which have a
limit of 64 characters and is composed as:
<buildname>-<buil... | def make_name_from_git(repo, branch, limit=53, separator='-', hash_size=5):
| """
return name string representing the given git repo and branch
to be used as a build name.
NOTE: Build name will be used to generate pods which have a
limit of 64 characters and is composed as:
<buildname>-<buildnumber>-<podsuffix>
rhel7-1-build
Assuming '-XXXX' (5 chars) a... | if i < len(group):
group_chars.append(group[i])
size += 1
if size >= limit:
break
else:
continue
break
final_str1 = ''.join(str1_chars).strip(separator)
final_str2 = ''.join(str2_chars).strip(separator)
... | 103 | 104 | 349 | 21 | 82 | hjmodi/osbs-client | osbs/utils/__init__.py | Python | make_name_from_git | make_name_from_git | 452 | 487 | 452 | 452 | 72a472189687a498337c74186dd21a4f375b6020 | bigcode/the-stack | train |
fe21f38e8ccfa1250818bf7f | train | function | @contextlib.contextmanager
def paused_builds(osbs, quota_name=None, ignore_quota_errors=False):
try:
logger.info("pausing builds")
try:
osbs.pause_builds(quota_name=quota_name)
except OsbsResponseException as e:
if ignore_quota_errors and (e.status_code == requests.co... | @contextlib.contextmanager
def paused_builds(osbs, quota_name=None, ignore_quota_errors=False):
| try:
logger.info("pausing builds")
try:
osbs.pause_builds(quota_name=quota_name)
except OsbsResponseException as e:
if ignore_quota_errors and (e.status_code == requests.codes.FORBIDDEN):
logger.warning("Ignoring resourcequota error")
else:... | 'rev-list', '--count', 'HEAD']
final_commit_depth = int(subprocess.check_output(cmd, cwd=target_dir)) - base_commit_depth
return commit_id, final_commit_depth
@contextlib.contextmanager
def paused_builds(osbs, quota_name=None, ignore_quota_errors=False):
| 64 | 64 | 166 | 23 | 40 | hjmodi/osbs-client | osbs/utils/__init__.py | Python | paused_builds | paused_builds | 328 | 348 | 328 | 329 | e81723923ff8f1c0e4c49230f2b2f9fa0511840a | bigcode/the-stack | train |
b24d416273dfe749dcab88d6 | train | class | class TarWriter(object):
def __init__(self, outfile, directory=None):
mode = "w|bz2"
if hasattr(outfile, "write"):
self.tarfile = tarfile.open(fileobj=outfile, mode=mode)
else:
self.tarfile = tarfile.open(name=outfile, mode=mode)
self.directory = directory or ... | class TarWriter(object):
| def __init__(self, outfile, directory=None):
mode = "w|bz2"
if hasattr(outfile, "write"):
self.tarfile = tarfile.open(fileobj=outfile, mode=mode)
else:
self.tarfile = tarfile.open(name=outfile, mode=mode)
self.directory = directory or ""
def __enter__(sel... | ] or ''
if self.version == 'v1':
raise OsbsValidationException('Invalid API version requested in {}'.format(uri))
@property
def uri(self):
return self.scheme + self.docker_uri
def __repr__(self):
return self.uri
class TarWriter(object):
| 64 | 64 | 169 | 5 | 58 | hjmodi/osbs-client | osbs/utils/__init__.py | Python | TarWriter | TarWriter | 86 | 107 | 86 | 86 | efc02737ea84239abb5c94b5ea1beb90f4ee355d | bigcode/the-stack | train |
9da6df012a762434f5cb4f5b | train | function | def sanitize_version(version):
"""
Take parse_version() output and standardize output from older
setuptools' parse_version() to match current setuptools.
"""
if hasattr(version, 'base_version'):
if version.base_version:
parts = version.base_version.split('.')
else:
... | def sanitize_version(version):
| """
Take parse_version() output and standardize output from older
setuptools' parse_version() to match current setuptools.
"""
if hasattr(version, 'base_version'):
if version.base_version:
parts = version.base_version.split('.')
else:
parts = []
else:
... | , **kwargs)
return '-'.join([prefix, name_from_git, suffix])
def get_instance_token_file_name(instance):
"""Return the token file name for the given instance."""
return '{}/.osbs/{}.token'.format(os.path.expanduser('~'), instance)
def sanitize_version(version):
| 64 | 64 | 157 | 5 | 59 | hjmodi/osbs-client | osbs/utils/__init__.py | Python | sanitize_version | sanitize_version | 511 | 534 | 511 | 511 | 82cd2e49b0050c10a713558a1f98ea8928114131 | bigcode/the-stack | train |
8e00b0a7215185c4540999f5 | train | function | def reset_git_repo(target_dir, git_reference, retry_depth=None):
"""
hard reset git clone in target_dir to given git_reference
:param target_dir: str, filesystem path where the repo is cloned
:param git_reference: str, any valid git reference
:param retry_depth: int, if the repo was cloned with --s... | def reset_git_repo(target_dir, git_reference, retry_depth=None):
| """
hard reset git clone in target_dir to given git_reference
:param target_dir: str, filesystem path where the repo is cloned
:param git_reference: str, any valid git reference
:param retry_depth: int, if the repo was cloned with --shallow, this is the expected
depth of the... | reachable in branch {}, reason: {}"
.format(commit, branch, exc))
break
except subprocess.CalledProcessError as exc:
if counter != retry_times:
logger.info("retrying command '%s':\n '%s'", cmd, exc.output)
time.sle... | 141 | 141 | 473 | 14 | 127 | hjmodi/osbs-client | osbs/utils/__init__.py | Python | reset_git_repo | reset_git_repo | 280 | 325 | 280 | 280 | fb8fc08558888fe8cfa562026f1fa46248b5a64a | bigcode/the-stack | train |
05858e818f422546cc7900db | train | class | class ImageName(object):
def __init__(self, registry=None, namespace=None, repo=None, tag=None):
self.registry = registry
self.namespace = namespace
self.repo = repo
self.tag = tag or 'latest'
@classmethod
def parse(cls, image_name):
result = cls()
if isinst... | class ImageName(object):
| def __init__(self, registry=None, namespace=None, repo=None, tag=None):
self.registry = registry
self.namespace = namespace
self.repo = repo
self.tag = tag or 'latest'
@classmethod
def parse(cls, image_name):
result = cls()
if isinstance(image_name, cls):
... | _on_exception
class RetryFunc(object):
def __init__(self, exception_type, should_retry_cb=None,
retry_times=OS_CONFLICT_MAX_RETRIES, retry_delay=OS_CONFLICT_WAIT):
self.exception_type = exception_type
self.should_retry_cb = should_retry_cb or (lambda ex: True)
self.retry_... | 201 | 201 | 671 | 5 | 195 | hjmodi/osbs-client | osbs/utils/__init__.py | Python | ImageName | ImageName | 613 | 712 | 613 | 613 | 8bd9daa5677e401dc09c99a819dd1a7e223d7796 | bigcode/the-stack | train |
e09948a322e1cb11491222b5 | train | function | def has_triggers(build_config):
return graceful_chain_get(build_config, 'spec', 'triggers') is not None
| def has_triggers(build_config):
| return graceful_chain_get(build_config, 'spec', 'triggers') is not None
| d:
return
for arg in args[:-1]:
try:
d = d[arg]
except (IndexError, KeyError):
return
try:
del d[args[-1]]
except (IndexError, KeyError):
pass
def has_triggers(build_config):
| 64 | 64 | 26 | 7 | 56 | hjmodi/osbs-client | osbs/utils/__init__.py | Python | has_triggers | has_triggers | 164 | 165 | 164 | 164 | 09b20d9c75a9d3b959741bc63c729d1c3e97d4ad | bigcode/the-stack | train |
20e9ffd31a24bc84d3ab10d0 | train | class | class MempoolPackagesTest(NeonTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.extra_args = [
[
"-maxorphantx=1000",
"-whitelist=noban@127.0.0.1", # immediate tx relay
],
[
"-maxorphantx=1000",
... | class MempoolPackagesTest(NeonTestFramework):
| def set_test_params(self):
self.num_nodes = 2
self.extra_args = [
[
"-maxorphantx=1000",
"-whitelist=noban@127.0.0.1", # immediate tx relay
],
[
"-maxorphantx=1000",
"-limitancestorcount={}".format(M... | #!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test descendant package tracking code."""
from decimal import Decimal
from test_framework.messages im... | 180 | 256 | 3,614 | 12 | 167 | neoncoin-project/neon | test/functional/mempool_packages.py | Python | MempoolPackagesTest | MempoolPackagesTest | 26 | 334 | 26 | 26 | 6ae8e6b222a89c319a5349185a8fcedc6e3ad023 | bigcode/the-stack | train |
fa4d8dde66c8f3691d72da21 | train | function | def get_skyline(buildings: list[list[int]]) -> list[list[int]]:
"""Computes a city's skyline formed by all the buildings in a given city.
A city's skyline is the outer contour of the silhouette
formed by all the buildings in that city when viewed from a distance.
You may assume all buildings are perfe... | def get_skyline(buildings: list[list[int]]) -> list[list[int]]:
| """Computes a city's skyline formed by all the buildings in a given city.
A city's skyline is the outer contour of the silhouette
formed by all the buildings in that city when viewed from a distance.
You may assume all buildings are perfect rectangles
grounded on an absolutely flat surface at heig... | """https://leetcode.com/problems/the-skyline-problem/
Examples:
>>> Solution().getSkyline([])
[]
See Also:
- https://briangordon.github.io/2014/08/the-skyline-problem.html
- https://leetcode.com/problems/the-skyline-problem/discuss/61261/10-line-Python-solution-104-ms
"""
import heapq
class Soluti... | 132 | 256 | 1,157 | 17 | 115 | TeoZosa/pytudes | pytudes/_2021/leetcode/hard/_218__the_skyline_problem.py | Python | get_skyline | get_skyline | 21 | 117 | 21 | 21 | 9190c6915266dbbff57d900aa26b208343a41198 | bigcode/the-stack | train |
84ed6519e6fc671129a8a445 | train | class | class Solution:
def getSkyline(self, buildings: list[list[int]]) -> list[list[int]]:
return get_skyline(buildings)
| class Solution:
| def getSkyline(self, buildings: list[list[int]]) -> list[list[int]]:
return get_skyline(buildings)
| []
See Also:
- https://briangordon.github.io/2014/08/the-skyline-problem.html
- https://leetcode.com/problems/the-skyline-problem/discuss/61261/10-line-Python-solution-104-ms
"""
import heapq
class Solution:
| 64 | 64 | 30 | 3 | 60 | TeoZosa/pytudes | pytudes/_2021/leetcode/hard/_218__the_skyline_problem.py | Python | Solution | Solution | 16 | 18 | 16 | 16 | e721fb68000ba67b9b18c2cf17a88566c4d37b92 | bigcode/the-stack | train |
b125e978706c2566365d6d19 | train | class | class Product(db.Model, SerializerMixin):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(140))
price = db.Column(db.Numeric())
description = db.Column(db.Text)
| class Product(db.Model, SerializerMixin):
| id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(140))
price = db.Column(db.Numeric())
description = db.Column(db.Text)
| from sqlalchemy_serializer import SerializerMixin
from dms_epicor.ext.database import db
class Product(db.Model, SerializerMixin):
| 26 | 64 | 46 | 8 | 17 | thanvanhai/DMS_Epicor | dms_epicor/models.py | Python | Product | Product | 6 | 10 | 6 | 6 | f159104da7ae266a0c3fb151e400c4e5f51645d3 | bigcode/the-stack | train |
1be781998180c41989e783dc | train | class | class User(db.Model, SerializerMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(140))
password = db.Column(db.String(512))
| class User(db.Model, SerializerMixin):
| id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(140))
password = db.Column(db.String(512))
| dms_epicor.ext.database import db
class Product(db.Model, SerializerMixin):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(140))
price = db.Column(db.Numeric())
description = db.Column(db.Text)
class User(db.Model, SerializerMixin):
| 64 | 64 | 40 | 8 | 56 | thanvanhai/DMS_Epicor | dms_epicor/models.py | Python | User | User | 13 | 16 | 13 | 13 | 4bb533b8bd95ec9dce03c108125a8750206bddd5 | bigcode/the-stack | train |
cb8bdefd78651beb9a49de2f | train | function | def set_main_options():
usage = "usage: %prog [options]"
parser = OptionParser(usage)
parser.add_option("-g", "--gateway", dest="gateway",
help="Souliss gateway host or IP")
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
(option... | def set_main_options():
| usage = "usage: %prog [options]"
parser = OptionParser(usage)
parser.add_option("-g", "--gateway", dest="gateway",
help="Souliss gateway host or IP")
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
(options, args) = parser.parse_... | """
Example for using pysouliss.
"""
import souliss.pysouliss as souliss
from optparse import OptionParser
import logging
_LOGGER = logging.getLogger(__name__)
def set_main_options():
| 44 | 64 | 150 | 5 | 39 | maoterodapena/pysouliss | main.py | Python | set_main_options | set_main_options | 12 | 29 | 12 | 12 | c884aca5e3c23c8877e619d046654104d739ab4d | bigcode/the-stack | train |
20c30dcfa993050526682453 | train | class | class Algorithm:
def __init__(self, name, bestTimeComplexity, averageTimeComplexity, worstTimeComplexity, spaceComplexity):
self.name = name
self.bestTimeComplexity = bestTimeComplexity
self.averageTimeComplexity = averageTimeComplexity
self.worstTimeComplexity = worstTimeComplexity
... | class Algorithm:
| def __init__(self, name, bestTimeComplexity, averageTimeComplexity, worstTimeComplexity, spaceComplexity):
self.name = name
self.bestTimeComplexity = bestTimeComplexity
self.averageTimeComplexity = averageTimeComplexity
self.worstTimeComplexity = worstTimeComplexity
self.spac... | .
SESSION_ENDED_MESSAGE = ("Come back next time you would like to know more about big O notation. Bye bye!")
# This is the message a user will hear when there is no intent match.
ELSE_MESSAGE = ("I'm sorry, I don't know that...")
# --------------- algorithms data
class Algorithm:
| 64 | 64 | 84 | 3 | 60 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | Algorithm | Algorithm | 19 | 25 | 19 | 19 | 4cb3ec13604ee531acb9f1989348d3552e14f174 | bigcode/the-stack | train |
74a5ff2075a2475c724342aa | train | function | def say_space_complexity(request):
a = get_sorting_algorithm(request)
m = "The space complexity of {0} is {1}".format(a.name, a.spaceComplexity)
return response(response_plain_text(m, True))
| def say_space_complexity(request):
| a = get_sorting_algorithm(request)
m = "The space complexity of {0} is {1}".format(a.name, a.spaceComplexity)
return response(response_plain_text(m, True))
| (m, True))
def say_average_time_complexity(request):
a = get_sorting_algorithm(request)
m = "The average time complexity of {0} is {1}".format(a.name, a.averageTimeComplexity)
return response(response_plain_text(m, True))
def say_space_complexity(request):
| 64 | 64 | 50 | 7 | 57 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | say_space_complexity | say_space_complexity | 110 | 113 | 110 | 110 | 9066c2af5630af9b16d615c4cb63c9e6636e0487 | bigcode/the-stack | train |
88531b2ca75678924680a5cc | train | function | def on_intent(request, session):
intent_name = request['intent']['name']
print("on_intent: " + intent_name)
try:
if intent_name == "WorstTimeComplexity":
return say_worst_time_complexity(request)
elif intent_name == "BestTimeComplexity":
return say_best_time_complexi... | def on_intent(request, session):
| intent_name = request['intent']['name']
print("on_intent: " + intent_name)
try:
if intent_name == "WorstTimeComplexity":
return say_worst_time_complexity(request)
elif intent_name == "BestTimeComplexity":
return say_best_time_complexity(request)
elif intent_n... | on_intent(event['request'], event['session'])
elif event['request']['type'] == "SessionEndedRequest":
return on_session_ended(event['request'])
# -------------- events
def on_launch():
return response(response_plain_text(WELCOME_MESSAGE, False))
def on_intent(request, session):
| 64 | 64 | 191 | 8 | 56 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | on_intent | on_intent | 58 | 82 | 58 | 58 | 3505c87521b4e21443fbeef7a5e676665658c8f8 | bigcode/the-stack | train |
0a8b376c835959f8c5583ba5 | train | function | def on_launch():
return response(response_plain_text(WELCOME_MESSAGE, False))
| def on_launch():
| return response(response_plain_text(WELCOME_MESSAGE, False))
| return on_launch()
elif event['request']['type'] == "IntentRequest":
return on_intent(event['request'], event['session'])
elif event['request']['type'] == "SessionEndedRequest":
return on_session_ended(event['request'])
# -------------- events
def on_launch():
| 64 | 64 | 16 | 4 | 59 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | on_launch | on_launch | 55 | 56 | 55 | 55 | 2e5c9ddd59cb5a348e344b710b21cf39dcee91f4 | bigcode/the-stack | train |
5b969fa0b65350aacc6ae1d7 | train | function | def say_average_time_complexity(request):
a = get_sorting_algorithm(request)
m = "The average time complexity of {0} is {1}".format(a.name, a.averageTimeComplexity)
return response(response_plain_text(m, True))
| def say_average_time_complexity(request):
| a = get_sorting_algorithm(request)
m = "The average time complexity of {0} is {1}".format(a.name, a.averageTimeComplexity)
return response(response_plain_text(m, True))
| , True))
def say_best_time_complexity(request):
a = get_sorting_algorithm(request)
m = "The best time complexity of {0} is {1}".format(a.name, a.bestTimeComplexity)
return response(response_plain_text(m, True))
def say_average_time_complexity(request):
| 64 | 64 | 53 | 8 | 56 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | say_average_time_complexity | say_average_time_complexity | 105 | 108 | 105 | 105 | da29aafc803f6b7a316e97e075ef519d0cbbba84 | bigcode/the-stack | train |
1d487d5b32da32db828ad5cb | train | function | def do_global_else():
return response(response_plain_text(ELSE_MESSAGE, True))
| def do_global_else():
| return response(response_plain_text(ELSE_MESSAGE, True))
| return response(response_plain_text(m, True))
def say_space_complexity(request):
a = get_sorting_algorithm(request)
m = "The space complexity of {0} is {1}".format(a.name, a.spaceComplexity)
return response(response_plain_text(m, True))
def do_global_else():
| 64 | 64 | 18 | 5 | 59 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | do_global_else | do_global_else | 115 | 116 | 115 | 115 | 4867b48ac3a0ec57ded0ab46873df24647d377cb | bigcode/the-stack | train |
aae21add7e1f7ef355251a02 | train | function | def say_best_time_complexity(request):
a = get_sorting_algorithm(request)
m = "The best time complexity of {0} is {1}".format(a.name, a.bestTimeComplexity)
return response(response_plain_text(m, True))
| def say_best_time_complexity(request):
| a = get_sorting_algorithm(request)
m = "The best time complexity of {0} is {1}".format(a.name, a.bestTimeComplexity)
return response(response_plain_text(m, True))
| ))
def say_worst_time_complexity(request):
a = get_sorting_algorithm(request)
m = "The worst time complexity of {0} is {1}".format(a.name, a.worstTimeComplexity)
return response(response_plain_text(m, True))
def say_best_time_complexity(request):
| 64 | 64 | 53 | 8 | 56 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | say_best_time_complexity | say_best_time_complexity | 100 | 103 | 100 | 100 | ee88d0d086e77686c8cbb423dcb904d66e918e33 | bigcode/the-stack | train |
28293f14e4a79889c9aceab5 | train | function | def response_plain_text(message, endsession):
""" create a simple json plain text response """
return {
'outputSpeech': {
'type': 'PlainText',
'text': message
},
'shouldEndSession': endsession
}
| def response_plain_text(message, endsession):
| """ create a simple json plain text response """
return {
'outputSpeech': {
'type': 'PlainText',
'text': message
},
'shouldEndSession': endsession
}
| return a
# --------------- speech response handlers
def response(speech_response, attributes={}):
""" create a simple json response """
return {
'version': '1.0',
'sessionAttributes': attributes,
'response': speech_response
}
def response_plain_text(message, endsession):
| 64 | 64 | 56 | 9 | 55 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | response_plain_text | response_plain_text | 133 | 141 | 133 | 133 | 07e115111d1d18eddc2847b98c59ba54f27d5c3d | bigcode/the-stack | train |
1b3452b8bc3935655b628837 | train | function | def lambda_handler(event, context):
""" App entry point """
if event['request']['type'] == "LaunchRequest":
return on_launch()
elif event['request']['type'] == "IntentRequest":
return on_intent(event['request'], event['session'])
elif event['request']['type'] == "SessionEndedRequest":
... | def lambda_handler(event, context):
| """ App entry point """
if event['request']['type'] == "LaunchRequest":
return on_launch()
elif event['request']['type'] == "IntentRequest":
return on_intent(event['request'], event['session'])
elif event['request']['type'] == "SessionEndedRequest":
return on_session_ended(even... | Algorithm("Counting Sort", "n+k", "n+k", "n+k", "k")
ALGORITHMS['cubesort'] = Algorithm("Cubesort", "n", "n log(n)", "n log(n)", "n")
# --------------- entry point
def lambda_handler(event, context):
| 64 | 64 | 82 | 7 | 56 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | lambda_handler | lambda_handler | 43 | 51 | 43 | 43 | a8fecb597100799c2484b1c0f35e066bf4bf9c75 | bigcode/the-stack | train |
3cd8dcf040063893d7f74c3d | train | function | def say_worst_time_complexity(request):
a = get_sorting_algorithm(request)
m = "The worst time complexity of {0} is {1}".format(a.name, a.worstTimeComplexity)
return response(response_plain_text(m, True))
| def say_worst_time_complexity(request):
| a = get_sorting_algorithm(request)
m = "The worst time complexity of {0} is {1}".format(a.name, a.worstTimeComplexity)
return response(response_plain_text(m, True))
| (request):
return response(response_plain_text(SESSION_ENDED_MESSAGE, True))
# -------------- functions
def do_help():
return response(response_plain_text(HELP_MESSAGE, False))
def do_stop():
return response(response_plain_text(SESSION_ENDED_MESSAGE, True))
def say_worst_time_complexity(request):
| 64 | 64 | 55 | 9 | 55 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | say_worst_time_complexity | say_worst_time_complexity | 95 | 98 | 95 | 95 | 17485a5a0585ab168bd19f1e4f2258ddbe2e79cb | bigcode/the-stack | train |
842a40406dae692a2d37633c | train | function | def on_session_ended(request):
return response(response_plain_text(SESSION_ENDED_MESSAGE, True))
| def on_session_ended(request):
| return response(response_plain_text(SESSION_ENDED_MESSAGE, True))
| "AMAZON.StopIntent":
return do_stop()
elif intent_name == "AMAZON.CancelIntent":
return do_stop()
else:
return do_global_else()
except Exception:
print("Exception happened during intent processing.")
return do_global_else()
def on_session_ended(reque... | 64 | 64 | 21 | 7 | 57 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | on_session_ended | on_session_ended | 84 | 85 | 84 | 84 | 5f04cc44707cfc1439c2e85baa770d6f27d7c5d1 | bigcode/the-stack | train |
a1d1f30ad67a268f5810d0ba | train | function | def do_stop():
return response(response_plain_text(SESSION_ENDED_MESSAGE, True))
| def do_stop():
| return response(response_plain_text(SESSION_ENDED_MESSAGE, True))
| except Exception:
print("Exception happened during intent processing.")
return do_global_else()
def on_session_ended(request):
return response(response_plain_text(SESSION_ENDED_MESSAGE, True))
# -------------- functions
def do_help():
return response(response_plain_text(HELP_MESSAGE, False))
de... | 64 | 64 | 18 | 4 | 60 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | do_stop | do_stop | 92 | 93 | 92 | 92 | 9af54b9d2caa6be9bbb5958faa9d0b43b3c9be5b | bigcode/the-stack | train |
576e9a52d20c2ae8bc113b7d | train | function | def response(speech_response, attributes={}):
""" create a simple json response """
return {
'version': '1.0',
'sessionAttributes': attributes,
'response': speech_response
}
| def response(speech_response, attributes={}):
| """ create a simple json response """
return {
'version': '1.0',
'sessionAttributes': attributes,
'response': speech_response
}
| return response(response_plain_text(ELSE_MESSAGE, True))
def get_sorting_algorithm(request):
slot = request['intent']['slots']['SortingAlgorithm']['value']
a = ALGORITHMS[slot.lower()]
return a
# --------------- speech response handlers
def response(speech_response, attributes={}):
| 64 | 64 | 45 | 9 | 54 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | response | response | 125 | 131 | 125 | 125 | c162b42772f198c71b622c5c885f527c329e995d | bigcode/the-stack | train |
d90563dd8204ca719de393f2 | train | function | def do_help():
return response(response_plain_text(HELP_MESSAGE, False))
| def do_help():
| return response(response_plain_text(HELP_MESSAGE, False))
| ":
return do_stop()
else:
return do_global_else()
except Exception:
print("Exception happened during intent processing.")
return do_global_else()
def on_session_ended(request):
return response(response_plain_text(SESSION_ENDED_MESSAGE, True))
# -------------- funct... | 64 | 64 | 16 | 4 | 59 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | do_help | do_help | 89 | 90 | 89 | 89 | f67f3d559d2db44265f15bc955409eeaa9b11b66 | bigcode/the-stack | train |
846278301e1cd9c68972eb24 | train | function | def get_sorting_algorithm(request):
slot = request['intent']['slots']['SortingAlgorithm']['value']
a = ALGORITHMS[slot.lower()]
return a
| def get_sorting_algorithm(request):
| slot = request['intent']['slots']['SortingAlgorithm']['value']
a = ALGORITHMS[slot.lower()]
return a
| _sorting_algorithm(request)
m = "The space complexity of {0} is {1}".format(a.name, a.spaceComplexity)
return response(response_plain_text(m, True))
def do_global_else():
return response(response_plain_text(ELSE_MESSAGE, True))
def get_sorting_algorithm(request):
| 64 | 64 | 35 | 7 | 57 | aliakseimaniuk/big-o-alexa | lambda/bigonotation.py | Python | get_sorting_algorithm | get_sorting_algorithm | 118 | 121 | 118 | 118 | 7879542cd0034341ba268031c6fae4a34ac74282 | bigcode/the-stack | train |
cf05facc883033e59c9ffc6a | train | class | class Migration(migrations.Migration):
dependencies = [
("timeline_logger", "0004_alter_fields"),
]
operations = [
migrations.AlterField(
model_name="timelinelog",
name="extra_data",
field=models.JSONField(
blank=True,
enc... | class Migration(migrations.Migration):
| dependencies = [
("timeline_logger", "0004_alter_fields"),
]
operations = [
migrations.AlterField(
model_name="timelinelog",
name="extra_data",
field=models.JSONField(
blank=True,
encoder=django.core.serializers.json.Django... | # Generated by Django 3.2.12 on 2022-04-13 07:42
import django.core.serializers.json
from django.db import migrations, models
class Migration(migrations.Migration):
| 45 | 64 | 134 | 7 | 37 | maykinmedia/django-timeline-logger | timeline_logger/migrations/0005_auto_20220413_0742.py | Python | Migration | Migration | 7 | 31 | 7 | 8 | 290905ee1e9e4659a1e2ae7a9fa5435a41d433ab | bigcode/the-stack | train |
7d0f52b234c407c91c732f95 | train | function | @api_experimental.route('/pools', methods=['GET'])
@requires_authentication
def get_pools():
"""Get all pools."""
try:
pools = pool_api.get_pools()
except AirflowException as err:
log.error(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code... | @api_experimental.route('/pools', methods=['GET'])
@requires_authentication
def get_pools():
| """Get all pools."""
try:
pools = pool_api.get_pools()
except AirflowException as err:
log.error(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response
else:
return jsonify([p.to_json() for p in pools])
| as err:
log.error(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response
else:
return jsonify(pool.to_json())
@api_experimental.route('/pools', methods=['GET'])
@requires_authentication
def get_pools():
| 64 | 64 | 93 | 23 | 41 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | get_pools | get_pools | 322 | 334 | 322 | 324 | f86bcb811c5f82a41e88d9e4ca133e002891c5ab | bigcode/the-stack | train |
ac6194501ddafbeb672e435d | train | function | @api_experimental.route('/lineage/<string:dag_id>/<string:execution_date>',
methods=['GET'])
@requires_authentication
def get_lineage(dag_id: str, execution_date: str):
# Convert string datetime into actual datetime
try:
execution_date = timezone.parse(execution_date)
except ... | @api_experimental.route('/lineage/<string:dag_id>/<string:execution_date>',
methods=['GET'])
@requires_authentication
def get_lineage(dag_id: str, execution_date: str):
# Convert string datetime into actual datetime
| try:
execution_date = timezone.parse(execution_date)
except ValueError:
error_message = (
'Given execution date, {}, could not be identified '
'as a date. Example date format: 2015-11-16T14:34:15+00:00'.format(
execution_date))
log.error(error_mess... | response
else:
return jsonify(pool.to_json())
@api_experimental.route('/lineage/<string:dag_id>/<string:execution_date>',
methods=['GET'])
@requires_authentication
def get_lineage(dag_id: str, execution_date: str):
# Convert string datetime into actual datetime
| 65 | 65 | 217 | 53 | 12 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | get_lineage | get_lineage | 368 | 394 | 368 | 372 | 8e738e7497516cea92febe8a5034804d3c627b4b | bigcode/the-stack | train |
cfa1c152bcb478f5cd1e4425 | train | function | @api_experimental.route('/dags/<string:dag_id>/code', methods=['GET'])
@requires_authentication
def get_dag_code(dag_id):
"""Return python code of a given dag_id."""
try:
return get_code(dag_id)
except AirflowException as err:
log.info(err)
response = jsonify(error="{}".format(err))
... | @api_experimental.route('/dags/<string:dag_id>/code', methods=['GET'])
@requires_authentication
def get_dag_code(dag_id):
| """Return python code of a given dag_id."""
try:
return get_code(dag_id)
except AirflowException as err:
log.info(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response
| ='OK')
@api_experimental.route('/info', methods=['GET'])
@requires_authentication
def info():
return jsonify(version=version)
@api_experimental.route('/dags/<string:dag_id>/code', methods=['GET'])
@requires_authentication
def get_dag_code(dag_id):
| 64 | 64 | 92 | 34 | 30 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | get_dag_code | get_dag_code | 152 | 162 | 152 | 154 | a734e915951dc4e823d38dde7cc2a7380a2987af | bigcode/the-stack | train |
55df46cbbe32c95f9781737e | train | function | @api_experimental.route('/dags/<string:dag_id>/dag_runs', methods=['POST'])
@requires_authentication
def trigger_dag(dag_id):
"""
Trigger a new dag run for a Dag with an execution date of now unless
specified in the data.
"""
data = request.get_json(force=True)
run_id = None
if 'run_id' in ... | @api_experimental.route('/dags/<string:dag_id>/dag_runs', methods=['POST'])
@requires_authentication
def trigger_dag(dag_id):
| """
Trigger a new dag run for a Dag with an execution date of now unless
specified in the data.
"""
data = request.get_json(force=True)
run_id = None
if 'run_id' in data:
run_id = data['run_id']
conf = None
if 'conf' in data:
conf = data['conf']
execution_date ... |
from airflow.api.common.experimental.get_task import get_task
from airflow.api.common.experimental.get_task_instance import get_task_instance
from airflow.exceptions import AirflowException
from airflow.utils import timezone
from airflow.utils.strings import to_boolean
from airflow.version import version
log = loggin... | 123 | 123 | 413 | 34 | 89 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | trigger_dag | trigger_dag | 43 | 98 | 43 | 45 | 1ee3643cd3b4b1ed6b237ee5016775cf9c753a1a | bigcode/the-stack | train |
4e3a1ac40e29acae99ce7272 | train | function | @api_experimental.route('/pools/<string:name>', methods=['GET'])
@requires_authentication
def get_pool(name):
"""Get pool by a given name."""
try:
pool = pool_api.get_pool(name=name)
except AirflowException as err:
log.error(err)
response = jsonify(error="{}".format(err))
res... | @api_experimental.route('/pools/<string:name>', methods=['GET'])
@requires_authentication
def get_pool(name):
| """Get pool by a given name."""
try:
pool = pool_api.get_pool(name=name)
except AirflowException as err:
log.error(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response
else:
return jsonify(pool.to_json())
| dag_id=dagrun.dag_id,
execution_date=dagrun.execution_date)
})
return jsonify(items=payload) # old flask versions dont support jsonifying arrays
@api_experimental.route('/pools/<string:name>', methods=['GET'])
@requires_authentication
def get_pool(name):
| 64 | 64 | 94 | 26 | 37 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | get_pool | get_pool | 307 | 319 | 307 | 309 | e5930be66f73f831e4b088f456f6922c1df6e1f3 | bigcode/the-stack | train |
61ddd7c96f7bf5b9a0d40ca8 | train | function | @api_experimental.route('/info', methods=['GET'])
@requires_authentication
def info():
return jsonify(version=version)
| @api_experimental.route('/info', methods=['GET'])
@requires_authentication
def info():
| return jsonify(version=version)
| .status_code = 400
return response
return jsonify(dagruns)
@api_experimental.route('/test', methods=['GET'])
@requires_authentication
def test():
return jsonify(status='OK')
@api_experimental.route('/info', methods=['GET'])
@requires_authentication
def info():
| 64 | 64 | 27 | 20 | 44 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | info | info | 146 | 149 | 146 | 148 | c27e8d0c0e212426851f42fda850b0e3d2bee9cd | bigcode/the-stack | train |
f6105441b28a255cfc6ab99e | train | function | @api_experimental.route('/dags/<string:dag_id>/paused/<string:paused>', methods=['GET'])
@requires_authentication
def dag_paused(dag_id, paused):
"""(Un)pauses a dag"""
is_paused = True if paused == 'true' else False
models.DagModel.get_dagmodel(dag_id).set_is_paused(
is_paused=is_paused,
)
... | @api_experimental.route('/dags/<string:dag_id>/paused/<string:paused>', methods=['GET'])
@requires_authentication
def dag_paused(dag_id, paused):
| """(Un)pauses a dag"""
is_paused = True if paused == 'true' else False
models.DagModel.get_dagmodel(dag_id).set_is_paused(
is_paused=is_paused,
)
return jsonify({'response': 'ok'})
| ()
if not k.startswith('_')}
return jsonify(fields)
# ToDo: Shouldn't this be a PUT method?
@api_experimental.route('/dags/<string:dag_id>/paused/<string:paused>', methods=['GET'])
@requires_authentication
def dag_paused(dag_id, paused):
| 64 | 64 | 101 | 39 | 25 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | dag_paused | dag_paused | 185 | 196 | 185 | 187 | a9ca39747d22d55793e454275f952209c2baa14d | bigcode/the-stack | train |
4ee4b5fa6709643b58fe00a6 | train | function | @api_experimental.route('/dags/<string:dag_id>/paused', methods=['GET'])
@requires_authentication
def dag_is_paused(dag_id):
"""Get paused state of a dag"""
is_paused = models.DagModel.get_dagmodel(dag_id).is_paused
return jsonify({'is_paused': is_paused})
| @api_experimental.route('/dags/<string:dag_id>/paused', methods=['GET'])
@requires_authentication
def dag_is_paused(dag_id):
| """Get paused state of a dag"""
is_paused = models.DagModel.get_dagmodel(dag_id).is_paused
return jsonify({'is_paused': is_paused})
| model(dag_id).set_is_paused(
is_paused=is_paused,
)
return jsonify({'response': 'ok'})
@api_experimental.route('/dags/<string:dag_id>/paused', methods=['GET'])
@requires_authentication
def dag_is_paused(dag_id):
| 63 | 64 | 76 | 34 | 29 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | dag_is_paused | dag_is_paused | 199 | 206 | 199 | 201 | 64673fb73d01e40dfc758dc06772346ea3622bee | bigcode/the-stack | train |
cb968b92cb9ecce3935985c7 | train | function | @api_experimental.route(
'/dags/<string:dag_id>/dag_runs/<string:execution_date>/tasks/<string:task_id>',
methods=['GET'])
@requires_authentication
def task_instance_info(dag_id, execution_date, task_id):
"""
Returns a JSON with a task instance's public instance variables.
The format for the exec_da... | @api_experimental.route(
'/dags/<string:dag_id>/dag_runs/<string:execution_date>/tasks/<string:task_id>',
methods=['GET'])
@requires_authentication
def task_instance_info(dag_id, execution_date, task_id):
| """
Returns a JSON with a task instance's public instance variables.
The format for the exec_date is expected to be
"YYYY-mm-DDTHH:MM:SS", for example: "2016-11-16T11:34:15". This will
of course need to have been encoded for URL in the request.
"""
# Convert string datetime into actual date... | _id):
"""Get paused state of a dag"""
is_paused = models.DagModel.get_dagmodel(dag_id).is_paused
return jsonify({'is_paused': is_paused})
@api_experimental.route(
'/dags/<string:dag_id>/dag_runs/<string:execution_date>/tasks/<string:task_id>',
methods=['GET'])
@requires_authentication
def task_ins... | 99 | 99 | 331 | 55 | 44 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | task_instance_info | task_instance_info | 209 | 247 | 209 | 213 | ae87a5eec80600ab3675e4a6267762d2094616e3 | bigcode/the-stack | train |
785d6062e62f1a9d8f1d2914 | train | function | @api_experimental.route(
'/dags/<string:dag_id>/dag_runs/<string:execution_date>',
methods=['GET'])
@requires_authentication
def dag_run_status(dag_id, execution_date):
"""
Returns a JSON with a dag_run's public instance variables.
The format for the exec_date is expected to be
"YYYY-mm-DDTHH:MM... | @api_experimental.route(
'/dags/<string:dag_id>/dag_runs/<string:execution_date>',
methods=['GET'])
@requires_authentication
def dag_run_status(dag_id, execution_date):
| """
Returns a JSON with a dag_run's public instance variables.
The format for the exec_date is expected to be
"YYYY-mm-DDTHH:MM:SS", for example: "2016-11-16T11:34:15". This will
of course need to have been encoded for URL in the request.
"""
# Convert string datetime into actual datetime
... |
# JSONify and return.
fields = {k: str(v)
for k, v in vars(info).items()
if not k.startswith('_')}
return jsonify(fields)
@api_experimental.route(
'/dags/<string:dag_id>/dag_runs/<string:execution_date>',
methods=['GET'])
@requires_authentication
def dag_run_status(dag_... | 85 | 85 | 285 | 45 | 40 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | dag_run_status | dag_run_status | 250 | 284 | 250 | 254 | a401e7b38d408fb350b4fdfa1fa0fdf76f2ea5e0 | bigcode/the-stack | train |
421566bbf5c2b5855f8e8104 | train | function | @api_experimental.route('/test', methods=['GET'])
@requires_authentication
def test():
return jsonify(status='OK')
| @api_experimental.route('/test', methods=['GET'])
@requires_authentication
def test():
| return jsonify(status='OK')
| state)
except AirflowException as err:
log.info(err)
response = jsonify(error="{}".format(err))
response.status_code = 400
return response
return jsonify(dagruns)
@api_experimental.route('/test', methods=['GET'])
@requires_authentication
def test():
| 64 | 64 | 27 | 20 | 44 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | test | test | 140 | 143 | 140 | 142 | b63beba5278cf2944f4b14072039c708bdb94831 | bigcode/the-stack | train |
562bd98562d08d025f642dba | train | function | @api_experimental.route('/pools/<string:name>', methods=['DELETE'])
@requires_authentication
def delete_pool(name):
"""Delete pool."""
try:
pool = pool_api.delete_pool(name=name)
except AirflowException as err:
log.error(err)
response = jsonify(error="{}".format(err))
respons... | @api_experimental.route('/pools/<string:name>', methods=['DELETE'])
@requires_authentication
def delete_pool(name):
| """Delete pool."""
try:
pool = pool_api.delete_pool(name=name)
except AirflowException as err:
log.error(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response
else:
return jsonify(pool.to_json())
| log.error(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response
else:
return jsonify(pool.to_json())
@api_experimental.route('/pools/<string:name>', methods=['DELETE'])
@requires_authentication
def delete_pool(name):
| 64 | 64 | 90 | 26 | 38 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | delete_pool | delete_pool | 353 | 365 | 353 | 355 | 66a00993b6905fd622c1cb7009be69a425712e7d | bigcode/the-stack | train |
2193fd76982d79e713de35a6 | train | function | @api_experimental.route('/latest_runs', methods=['GET'])
@requires_authentication
def latest_dag_runs():
"""Returns the latest DagRun for each DAG formatted for the UI. """
from airflow.models import DagRun
dagruns = DagRun.get_latest_runs()
payload = []
for dagrun in dagruns:
if dagrun.exec... | @api_experimental.route('/latest_runs', methods=['GET'])
@requires_authentication
def latest_dag_runs():
| """Returns the latest DagRun for each DAG formatted for the UI. """
from airflow.models import DagRun
dagruns = DagRun.get_latest_runs()
payload = []
for dagrun in dagruns:
if dagrun.execution_date:
payload.append({
'dag_id': dagrun.dag_id,
'execut... | except AirflowException as err:
log.info(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response
return jsonify(info)
@api_experimental.route('/latest_runs', methods=['GET'])
@requires_authentication
def latest_dag_runs():
| 64 | 64 | 177 | 24 | 40 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | latest_dag_runs | latest_dag_runs | 287 | 304 | 287 | 289 | 9b2eceebe1345d3c03c147ccf0745138502dc680 | bigcode/the-stack | train |
c36ffc609b09f21279d47e7e | train | function | @api_experimental.route('/dags/<string:dag_id>/tasks/<string:task_id>', methods=['GET'])
@requires_authentication
def task_info(dag_id, task_id):
"""Returns a JSON with a task's public instance variables. """
try:
info = get_task(dag_id, task_id)
except AirflowException as err:
log.info(err)... | @api_experimental.route('/dags/<string:dag_id>/tasks/<string:task_id>', methods=['GET'])
@requires_authentication
def task_info(dag_id, task_id):
| """Returns a JSON with a task's public instance variables. """
try:
info = get_task(dag_id, task_id)
except AirflowException as err:
log.info(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response
# JSONify and retu... | )
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response
@api_experimental.route('/dags/<string:dag_id>/tasks/<string:task_id>', methods=['GET'])
@requires_authentication
def task_info(dag_id, task_id):
| 64 | 64 | 144 | 40 | 23 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | task_info | task_info | 165 | 181 | 165 | 167 | 52680cdb9a523fa99c09633201f2e56a9ba24987 | bigcode/the-stack | train |
fe116a3a254be5a38508cf8c | train | function | @api_experimental.route('/dags/<string:dag_id>', methods=['DELETE'])
@requires_authentication
def delete_dag(dag_id):
"""
Delete all DB records related to the specified Dag.
"""
try:
count = delete.delete_dag(dag_id)
except AirflowException as err:
log.error(err)
response = j... | @api_experimental.route('/dags/<string:dag_id>', methods=['DELETE'])
@requires_authentication
def delete_dag(dag_id):
| """
Delete all DB records related to the specified Dag.
"""
try:
count = delete.delete_dag(dag_id)
except AirflowException as err:
log.error(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response
return jsoni... | (
message="Created {}".format(dr),
execution_date=dr.execution_date.isoformat(),
run_id=dr.run_id
)
return response
@api_experimental.route('/dags/<string:dag_id>', methods=['DELETE'])
@requires_authentication
def delete_dag(dag_id):
| 64 | 64 | 113 | 31 | 32 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | delete_dag | delete_dag | 101 | 114 | 101 | 103 | d6ccbe49c52b2ce072f357ea2633f894330690d7 | bigcode/the-stack | train |
4f70a67c895a348ec8fdeeed | train | function | @api_experimental.route('/dags/<string:dag_id>/dag_runs', methods=['GET'])
@requires_authentication
def dag_runs(dag_id):
"""
Returns a list of Dag Runs for a specific DAG ID.
:query param state: a query string parameter '?state=queued|running|success...'
:param dag_id: String identifier of a DAG
:... | @api_experimental.route('/dags/<string:dag_id>/dag_runs', methods=['GET'])
@requires_authentication
def dag_runs(dag_id):
| """
Returns a list of Dag Runs for a specific DAG ID.
:query param state: a query string parameter '?state=queued|running|success...'
:param dag_id: String identifier of a DAG
:return: List of DAG runs of a DAG with requested state,
or all runs if the state is not specified
"""
try:... | ))
response.status_code = err.status_code
return response
return jsonify(message="Removed {} record(s)".format(count), count=count)
@api_experimental.route('/dags/<string:dag_id>/dag_runs', methods=['GET'])
@requires_authentication
def dag_runs(dag_id):
| 64 | 64 | 176 | 33 | 31 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | dag_runs | dag_runs | 117 | 137 | 117 | 119 | c42cd6d9890d61630170b8b4a331e264622e9782 | bigcode/the-stack | train |
e4baafde1b33f8e5b93e6d5e | train | function | @api_experimental.route('/pools', methods=['POST'])
@requires_authentication
def create_pool():
"""Create a pool."""
params = request.get_json(force=True)
try:
pool = pool_api.create_pool(**params)
except AirflowException as err:
log.error(err)
response = jsonify(error="{}".forma... | @api_experimental.route('/pools', methods=['POST'])
@requires_authentication
def create_pool():
| """Create a pool."""
params = request.get_json(force=True)
try:
pool = pool_api.create_pool(**params)
except AirflowException as err:
log.error(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response
else:
... | .error(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response
else:
return jsonify([p.to_json() for p in pools])
@api_experimental.route('/pools', methods=['POST'])
@requires_authentication
def create_pool():
| 64 | 64 | 96 | 22 | 42 | jkbngl/airflow | airflow/www/api/experimental/endpoints.py | Python | create_pool | create_pool | 337 | 350 | 337 | 339 | 29006ed4e8136e96e692211fcfee922ea6aa3988 | bigcode/the-stack | train |
3d6671ed3f0ab299f766cd25 | train | class | class Migration(migrations.Migration):
dependencies = [
('studygroups', '0076_auto_20170825_1019'),
]
operations = [
migrations.AddField(
model_name='course',
name='unlisted',
field=models.BooleanField(default=False),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('studygroups', '0076_auto_20170825_1019'),
]
operations = [
migrations.AddField(
model_name='course',
name='unlisted',
field=models.BooleanField(default=False),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-08-28 15:31
from django.db import migrations, models
class Migration(migrations.Migration):
| 46 | 64 | 64 | 7 | 38 | p2pu/learning-circles | studygroups/migrations/0077_course_unlisted.py | Python | Migration | Migration | 8 | 20 | 8 | 9 | 99a790d29234650665c04b1d96fbda6545a3c52a | bigcode/the-stack | train |
1261c14c7eab284411281d1f | train | class | class UserConfig(AppConfig):
name = 'user'
def ready(self):
from . import signals
| class UserConfig(AppConfig):
| name = 'user'
def ready(self):
from . import signals
| from django.apps import AppConfig
class UserConfig(AppConfig):
| 13 | 64 | 23 | 6 | 6 | Ravishrks/examin | app/user/apps.py | Python | UserConfig | UserConfig | 4 | 8 | 4 | 4 | 5a5aaf12d260bb54abe7f90e28f1d0b3bdf5f639 | bigcode/the-stack | train |
dc6812cb7635866764bf479d | train | class | class Model(nn.Module):
def __init__(self, modules_cfg="", losses_cfg="", in_channel=3, num_classes=80):
super().__init__()
self.model, self.save = get_model(modules_cfg, in_channel=in_channel, num_classes=num_classes)
self.in_channel = in_channel
self.is_export_onnx = False
... | class Model(nn.Module):
| def __init__(self, modules_cfg="", losses_cfg="", in_channel=3, num_classes=80):
super().__init__()
self.model, self.save = get_model(modules_cfg, in_channel=in_channel, num_classes=num_classes)
self.in_channel = in_channel
self.is_export_onnx = False
detect_module = self.mo... | import torch
import torch.nn as nn
from .parse_model import get_model
from yolox.utils import check_anchor_order
from .modules import detect_type
class Model(nn.Module):
| 38 | 172 | 575 | 5 | 32 | DDGRCF/YOLOX_OBB | yolox/models/model.py | Python | Model | Model | 7 | 61 | 7 | 7 | 8d0edf4015603e220d6e0e8c31ba1cdc3212b37c | bigcode/the-stack | train |
5bf254cfc218756695682072 | train | class | class BreachEvent(BaseEvent):
breach = models.ForeignKey(Breach, on_delete=models.CASCADE)
duration = models.IntegerField(help_text="duration till maximum depth in seconds")
start = models.IntegerField(help_text="moment of breach in seconds")
width = models.FloatField(help_text="initial width in meters"... | class BreachEvent(BaseEvent):
| breach = models.ForeignKey(Breach, on_delete=models.CASCADE)
duration = models.IntegerField(help_text="duration till maximum depth in seconds")
start = models.IntegerField(help_text="moment of breach in seconds")
width = models.FloatField(help_text="initial width in meters")
| from django.db import models
from api.simulations.events.models import BaseEvent
from api.threedimodels.models import Breach
class BreachEvent(BaseEvent):
| 35 | 64 | 68 | 7 | 27 | larsclaussen/api_v3 | api/simulations/events/breaches/models.py | Python | BreachEvent | BreachEvent | 6 | 10 | 6 | 6 | 94da65d601200d10c6116d74167f9208449816fb | bigcode/the-stack | train |
f40b2b980630c866f9a598cd | train | function | def fuse_conv_and_bn(conv, bn):
# Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
fusedconv = torch.nn.Conv2d(conv.in_channels,
conv.out_channels,
kernel_size=conv.kernel_size,
stride=conv.st... | def fuse_conv_and_bn(conv, bn):
# Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
| fusedconv = torch.nn.Conv2d(conv.in_channels,
conv.out_channels,
kernel_size=conv.kernel_size,
stride=conv.stride,
padding=conv.padding,
groups=conv.groups,
bia... | # update conv
delattr(m, 'bn') # remove batchnorm
m.forward = m.fuseforward # update forward
# self.info()
return self
"""
def fuse_conv_and_bn(conv, bn):
# Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
| 75 | 75 | 250 | 34 | 41 | carlsummer/python_developer_tools | python_developer_tools/cv/deploy/model_compression/quantization/torch_fuse.py | Python | fuse_conv_and_bn | fuse_conv_and_bn | 36 | 56 | 36 | 37 | 6b149526486799851573a2645dff2f3af9f77b21 | bigcode/the-stack | train |
0e3a8513e253cdf79625a229 | train | function | def _update_confidences(
predicted_confidences: List[float],
predicted_tags: List[Text],
tag: Text,
score: float,
idx: int,
last_idx: int,
):
"""Update the confidence values.
Set the confidence value of a tag to score value if the predicated
tag changed.
Args:
predicted... | def _update_confidences(
predicted_confidences: List[float],
predicted_tags: List[Text],
tag: Text,
score: float,
idx: int,
last_idx: int,
):
| """Update the confidence values.
Set the confidence value of a tag to score value if the predicated
tag changed.
Args:
predicted_confidences: The list of predicted confidences.
predicted_tags: The list of predicted tags.
tag: The tag of the entity.
score: The score valu... | _tag.get)
score = score_per_tag[tag]
return tag, score
def _update_confidences(
predicted_confidences: List[float],
predicted_tags: List[Text],
tag: Text,
score: float,
idx: int,
last_idx: int,
):
| 64 | 64 | 212 | 47 | 16 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | _update_confidences | _update_confidences | 362 | 392 | 362 | 369 | 782b6c64dd2b92c5e2a870b524fdf98577f691db | bigcode/the-stack | train |
04037aa766d9f83af355ec99 | train | function | def bilou_prefix_from_tag(tag: Text) -> Optional[Text]:
"""Returns the BILOU prefix from the given tag.
Args:
tag: the tag
Returns: the BILOU prefix of the tag
"""
if tag[:2] in BILOU_PREFIXES:
return tag[:2]
return None
| def bilou_prefix_from_tag(tag: Text) -> Optional[Text]:
| """Returns the BILOU prefix from the given tag.
Args:
tag: the tag
Returns: the BILOU prefix of the tag
"""
if tag[:2] in BILOU_PREFIXES:
return tag[:2]
return None
| logging.getLogger(__name__)
BEGINNING = "B-"
INSIDE = "I-"
LAST = "L-"
UNIT = "U-"
BILOU_PREFIXES = [BEGINNING, INSIDE, LAST, UNIT]
def bilou_prefix_from_tag(tag: Text) -> Optional[Text]:
| 64 | 64 | 74 | 15 | 49 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | bilou_prefix_from_tag | bilou_prefix_from_tag | 34 | 44 | 34 | 34 | 9adfe5264a7dcc282cd67d696a1fdc373d024c22 | bigcode/the-stack | train |
7334d74d6280ac952655245a | train | function | def _find_bilou_end(start_idx: int, predicted_tags: List[Text]) -> int:
"""Find the last index of the entity.
The start index is pointing to a B- tag. The entity is closed as soon as we find
a L- tag or a O tag.
Args:
start_idx: The start index of the entity
predicted_tags: The list of... | def _find_bilou_end(start_idx: int, predicted_tags: List[Text]) -> int:
| """Find the last index of the entity.
The start index is pointing to a B- tag. The entity is closed as soon as we find
a L- tag or a O tag.
Args:
start_idx: The start index of the entity
predicted_tags: The list of predicted tags
Returns:
The end index of the entity
""... | _confidence_per_tag(
relevant_tags: List[Text], relevant_confidences: List[float]
) -> Dict[Text, float]:
confidences_per_tag = defaultdict(list)
for tag, confidence in zip(relevant_tags, relevant_confidences):
confidences_per_tag[tag].append(confidence)
avg_confidence_per_tag = {}
for tag... | 141 | 141 | 470 | 22 | 118 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | _find_bilou_end | _find_bilou_end | 410 | 464 | 410 | 410 | e504f143c089f4df2ba57314fa680f5a97a782cd | bigcode/the-stack | train |
be37368388d08e5d9cdd2282 | train | function | def _add_bilou_tags_to_entities(
bilou: List[Text],
entities: List[Tuple[int, int, Text]],
end_pos_to_token_idx: Dict[int, int],
start_pos_to_token_idx: Dict[int, int],
):
for start_pos, end_pos, label in entities:
start_token_idx = start_pos_to_token_idx.get(start_pos)
end_token_idx... | def _add_bilou_tags_to_entities(
bilou: List[Text],
entities: List[Tuple[int, int, Text]],
end_pos_to_token_idx: Dict[int, int],
start_pos_to_token_idx: Dict[int, int],
):
| for start_pos, end_pos, label in entities:
start_token_idx = start_pos_to_token_idx.get(start_pos)
end_token_idx = end_pos_to_token_idx.get(end_pos)
# Only interested if the tokenization is correct
if start_token_idx is not None and end_token_idx is not None:
if start_to... | _idx
)
return bilou
def _add_bilou_tags_to_entities(
bilou: List[Text],
entities: List[Tuple[int, int, Text]],
end_pos_to_token_idx: Dict[int, int],
start_pos_to_token_idx: Dict[int, int],
):
| 64 | 64 | 207 | 55 | 8 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | _add_bilou_tags_to_entities | _add_bilou_tags_to_entities | 231 | 249 | 231 | 236 | d5ea9cb282815303d60874f9dfd24d004813b876 | bigcode/the-stack | train |
99ea9ff374db8000c213396e | train | function | def bilou_tags_to_ids(
message: Message,
tag_id_dict: Dict[Text, int],
tag_name: Text = ENTITY_ATTRIBUTE_TYPE,
) -> List[int]:
"""Maps the entity tags of the message to the ids of the provided dict.
Args:
message: the message
tag_id_dict: mapping of tags to ids
tag_name: tag... | def bilou_tags_to_ids(
message: Message,
tag_id_dict: Dict[Text, int],
tag_name: Text = ENTITY_ATTRIBUTE_TYPE,
) -> List[int]:
| """Maps the entity tags of the message to the ids of the provided dict.
Args:
message: the message
tag_id_dict: mapping of tags to ids
tag_name: tag name of interest
Returns: a list of tag ids
"""
bilou_key = get_bilou_key_for_tag(tag_name)
if message.get(bilou_key):
... |
"""
if tag[:2] in BILOU_PREFIXES:
return tag[2:]
return tag
def bilou_tags_to_ids(
message: Message,
tag_id_dict: Dict[Text, int],
tag_name: Text = ENTITY_ATTRIBUTE_TYPE,
) -> List[int]:
| 64 | 64 | 195 | 38 | 25 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | bilou_tags_to_ids | bilou_tags_to_ids | 60 | 84 | 60 | 64 | 98c450318f0960246cb9ab79f58add50905aa3a5 | bigcode/the-stack | train |
7ba03c665e4773548f90f871 | train | function | def bilou_tags_from_offsets(
tokens: List[Token], entities: List[Tuple[int, int, Text]]
) -> List[Text]:
"""Creates BILOU tags for the given tokens and entities.
Args:
message: The message object.
tokens: The list of tokens.
entities: The list of start, end, and tag tuples.
... | def bilou_tags_from_offsets(
tokens: List[Token], entities: List[Tuple[int, int, Text]]
) -> List[Text]:
| """Creates BILOU tags for the given tokens and entities.
Args:
message: The message object.
tokens: The list of tokens.
entities: The list of start, end, and tag tuples.
missing: The tag for missing entities.
Returns:
BILOU tags.
"""
start_pos_to_token_idx =... | value == NO_ENTITY_TAG.
tag_value_idx = 2
return [entity for entity in entities if entity[tag_value_idx] != NO_ENTITY_TAG]
def bilou_tags_from_offsets(
tokens: List[Token], entities: List[Tuple[int, int, Text]]
) -> List[Text]:
| 64 | 64 | 185 | 31 | 33 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | bilou_tags_from_offsets | bilou_tags_from_offsets | 205 | 228 | 205 | 207 | 18621b2a6f2892653e81a5f2933681d5b4439291 | bigcode/the-stack | train |
aed47edd000725df1ec4c013 | train | function | def remove_bilou_prefixes(tags: List[Text]) -> List[Text]:
"""Removes the BILOU prefixes from the given list of tags.
Args:
tags: the list of tags
Returns:
list of tags without BILOU prefix
"""
return [tag_without_prefix(t) for t in tags]
| def remove_bilou_prefixes(tags: List[Text]) -> List[Text]:
| """Removes the BILOU prefixes from the given list of tags.
Args:
tags: the list of tags
Returns:
list of tags without BILOU prefix
"""
return [tag_without_prefix(t) for t in tags]
| """
if tag_name == ENTITY_ATTRIBUTE_ROLE:
return BILOU_ENTITIES_ROLE
if tag_name == ENTITY_ATTRIBUTE_GROUP:
return BILOU_ENTITIES_GROUP
return BILOU_ENTITIES
def remove_bilou_prefixes(tags: List[Text]) -> List[Text]:
| 64 | 64 | 73 | 18 | 45 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | remove_bilou_prefixes | remove_bilou_prefixes | 105 | 114 | 105 | 105 | 5bbfbeb4f81174b8c0a7c0606ba6f16157062c18 | bigcode/the-stack | train |
d6088bdeeb28ed574f6e1d5a | train | function | def map_message_entities(
message: Message, attribute_key: Text = ENTITY_ATTRIBUTE_TYPE
) -> List[Tuple[int, int, Text]]:
"""Maps the entities of the given message to their start, end, and tag values.
Args:
message: the message
attribute_key: key of tag value to use
Returns: a list of ... | def map_message_entities(
message: Message, attribute_key: Text = ENTITY_ATTRIBUTE_TYPE
) -> List[Tuple[int, int, Text]]:
| """Maps the entities of the given message to their start, end, and tag values.
Args:
message: the message
attribute_key: key of tag value to use
Returns: a list of start, end, and tag value tuples
"""
def convert_entity(entity: Dict[Text, Any]) -> Tuple[int, int, Text]:
re... | ),
]:
entities = map_message_entities(message, attribute)
output = bilou_tags_from_offsets(tokens, entities)
message.set(message_key, output)
def map_message_entities(
message: Message, attribute_key: Text = ENTITY_ATTRIBUTE_TYPE
) -> List[Tuple[int, int, Text]]:
| 64 | 64 | 212 | 30 | 34 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | map_message_entities | map_message_entities | 178 | 202 | 178 | 180 | 643e3e8b5c42ea543b451a3174c2447c9e5c8697 | bigcode/the-stack | train |
3ae7d28002421f853b55bedd | train | function | def _tag_to_use(
relevant_tags: List[Text], relevant_confidences: List[float]
) -> Tuple[Text, float]:
"""Decide what tag to use according to the following metric:
Calculate the average confidence per tag.
Calculate the percentage of tokens assigned to a tag within the entity per tag.
The harmonic ... | def _tag_to_use(
relevant_tags: List[Text], relevant_confidences: List[float]
) -> Tuple[Text, float]:
| """Decide what tag to use according to the following metric:
Calculate the average confidence per tag.
Calculate the percentage of tokens assigned to a tag within the entity per tag.
The harmonic mean of those two metrics is the score for the tag.
The tag with the highest score is taken as the tag ... | _idx] = f"{LAST}{tag}"
else:
predicted_tags[idx] = f"{BEGINNING}{tag}"
predicted_tags[last_idx] = f"{LAST}{tag}"
for i in range(idx + 1, last_idx):
predicted_tags[i] = f"{INSIDE}{tag}"
return predicted_tags, predicted_confidences
def _... | 105 | 105 | 353 | 31 | 73 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | _tag_to_use | _tag_to_use | 319 | 359 | 319 | 321 | fc8c60bce3a235a680f9ec82764b514338214a02 | bigcode/the-stack | train |
eb5ec996142c37718ebbdd9e | train | function | def apply_bilou_schema(training_data: TrainingData) -> None:
"""Get a list of BILOU entity tags and set them on the given messages.
Args:
training_data: the training data
"""
for message in training_data.nlu_examples:
entities = message.get(ENTITIES)
if not entities:
... | def apply_bilou_schema(training_data: TrainingData) -> None:
| """Get a list of BILOU entity tags and set them on the given messages.
Args:
training_data: the training data
"""
for message in training_data.nlu_examples:
entities = message.get(ENTITIES)
if not entities:
continue
tokens = message.get(TOKENS_NAMES[TEXT])
... | )
}
# NO_ENTITY_TAG corresponds to non-entity which should correspond to 0 index
# needed for correct prediction for padding
tag_id_dict[NO_ENTITY_TAG] = 0
return tag_id_dict
def apply_bilou_schema(training_data: TrainingData) -> None:
| 64 | 64 | 165 | 15 | 48 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | apply_bilou_schema | apply_bilou_schema | 154 | 175 | 154 | 154 | 5ee66f7c36af27d5761e49b149bf65d28ec8003b | bigcode/the-stack | train |
5cebc1cceb8007a23c3b2076 | train | function | def ensure_consistent_bilou_tagging(
predicted_tags: List[Text], predicted_confidences: List[float]
) -> Tuple[List[Text], List[float]]:
"""
Ensure predicted tags follow the BILOU tagging schema.
We assume that starting B- tags are correct. Followed tags that belong to start
tag but have a differen... | def ensure_consistent_bilou_tagging(
predicted_tags: List[Text], predicted_confidences: List[float]
) -> Tuple[List[Text], List[float]]:
| """
Ensure predicted tags follow the BILOU tagging schema.
We assume that starting B- tags are correct. Followed tags that belong to start
tag but have a different entity type are updated considering also the confidence
values of those tags.
For example, B-a I-b L-a is updated to B-a I-a L-a an... | :
start_token_idx = start_pos_to_token_idx.get(start_pos)
end_token_idx = end_pos_to_token_idx.get(end_pos)
# Only interested if the tokenization is correct
if start_token_idx is not None and end_token_idx is not None:
if start_token_idx == end_token_idx:
bil... | 179 | 180 | 600 | 38 | 141 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | ensure_consistent_bilou_tagging | ensure_consistent_bilou_tagging | 252 | 316 | 252 | 254 | d536ef21af307870b00d748a7aeefb34dce40074 | bigcode/the-stack | train |
fa7af66c905768b3726eeca0 | train | function | def _avg_confidence_per_tag(
relevant_tags: List[Text], relevant_confidences: List[float]
) -> Dict[Text, float]:
confidences_per_tag = defaultdict(list)
for tag, confidence in zip(relevant_tags, relevant_confidences):
confidences_per_tag[tag].append(confidence)
avg_confidence_per_tag = {}
... | def _avg_confidence_per_tag(
relevant_tags: List[Text], relevant_confidences: List[float]
) -> Dict[Text, float]:
| confidences_per_tag = defaultdict(list)
for tag, confidence in zip(relevant_tags, relevant_confidences):
confidences_per_tag[tag].append(confidence)
avg_confidence_per_tag = {}
for tag, confidences in confidences_per_tag.items():
avg_confidence_per_tag[tag] = round(sum(confidences) / l... | )
if tag_without_prefix(predicted_tags[i]) != tag
else predicted_confidences[i]
)
return predicted_confidences
def _avg_confidence_per_tag(
relevant_tags: List[Text], relevant_confidences: List[float]
) -> Dict[Text, float]:
| 64 | 64 | 122 | 33 | 30 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | _avg_confidence_per_tag | _avg_confidence_per_tag | 395 | 407 | 395 | 397 | 46f105406a157541d6dbc725a30d42e85807da62 | bigcode/the-stack | train |
63094e3eff7e8d12f3f389fb | train | function | def build_tag_id_dict(
training_data: TrainingData, tag_name: Text = ENTITY_ATTRIBUTE_TYPE
) -> Optional[Dict[Text, int]]:
"""Create a mapping of unique tags to ids.
Args:
training_data: the training data
tag_name: tag name of interest
Returns: a mapping of tags to ids
"""
bilo... | def build_tag_id_dict(
training_data: TrainingData, tag_name: Text = ENTITY_ATTRIBUTE_TYPE
) -> Optional[Dict[Text, int]]:
| """Create a mapping of unique tags to ids.
Args:
training_data: the training data
tag_name: tag name of interest
Returns: a mapping of tags to ids
"""
bilou_key = get_bilou_key_for_tag(tag_name)
distinct_tags = set(
[
tag_without_prefix(e)
for e... | prefixes from the given list of tags.
Args:
tags: the list of tags
Returns:
list of tags without BILOU prefix
"""
return [tag_without_prefix(t) for t in tags]
def build_tag_id_dict(
training_data: TrainingData, tag_name: Text = ENTITY_ATTRIBUTE_TYPE
) -> Optional[Dict[Text, int]]:... | 79 | 79 | 264 | 32 | 47 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | build_tag_id_dict | build_tag_id_dict | 117 | 151 | 117 | 119 | 2bca3d69c925a338dce2879eb35e061069f1d1ea | bigcode/the-stack | train |
a5ac0857b8677d2846d07fef | train | function | def tag_without_prefix(tag: Text) -> Text:
"""Remove the BILOU prefix from the given tag.
Args:
tag: the tag
Returns: the tag without the BILOU prefix
"""
if tag[:2] in BILOU_PREFIXES:
return tag[2:]
return tag
| def tag_without_prefix(tag: Text) -> Text:
| """Remove the BILOU prefix from the given tag.
Args:
tag: the tag
Returns: the tag without the BILOU prefix
"""
if tag[:2] in BILOU_PREFIXES:
return tag[2:]
return tag
| OU prefix from the given tag.
Args:
tag: the tag
Returns: the BILOU prefix of the tag
"""
if tag[:2] in BILOU_PREFIXES:
return tag[:2]
return None
def tag_without_prefix(tag: Text) -> Text:
| 64 | 64 | 70 | 11 | 52 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | tag_without_prefix | tag_without_prefix | 47 | 57 | 47 | 47 | 97072eb1367535bddaabbece133dfb356e70d1c9 | bigcode/the-stack | train |
1c7e3cf6cd3e19f8bdc725a4 | train | function | def get_bilou_key_for_tag(tag_name: Text) -> Text:
"""Get the message key for the BILOU tagging format of the provided tag name.
Args:
tag_name: the tag name
Returns:
the message key to store the BILOU tags
"""
if tag_name == ENTITY_ATTRIBUTE_ROLE:
return BILOU_ENTITIES_ROL... | def get_bilou_key_for_tag(tag_name: Text) -> Text:
| """Get the message key for the BILOU tagging format of the provided tag name.
Args:
tag_name: the tag name
Returns:
the message key to store the BILOU tags
"""
if tag_name == ENTITY_ATTRIBUTE_ROLE:
return BILOU_ENTITIES_ROLE
if tag_name == ENTITY_ATTRIBUTE_GROUP:
... | for _tag in message.get(bilou_key)
]
else:
_tags = [tag_id_dict[NO_ENTITY_TAG] for _ in message.get(TOKENS_NAMES[TEXT])]
return _tags
def get_bilou_key_for_tag(tag_name: Text) -> Text:
| 64 | 64 | 107 | 16 | 47 | ektai/rasa | rasa/nlu/utils/bilou_utils.py | Python | get_bilou_key_for_tag | get_bilou_key_for_tag | 87 | 102 | 87 | 87 | 735bf8df2ba848636dbd2ac217f51404bff22e66 | bigcode/the-stack | train |
12916478668044daf1e02a5d | train | function | def test_modify_some_group(app, db, check_ui):
if len(db.get_group_list()) == 0:
app.group.create(Group(name='test'))
old_groups = db.get_group_list()
random_group = random.choice(old_groups)
group = Group(name="update")
group.id = random_group.id
app.group.modify_group_by_id(group)
... | def test_modify_some_group(app, db, check_ui):
| if len(db.get_group_list()) == 0:
app.group.create(Group(name='test'))
old_groups = db.get_group_list()
random_group = random.choice(old_groups)
group = Group(name="update")
group.id = random_group.id
app.group.modify_group_by_id(group)
new_groups = db.get_group_list()
assert len... | # -*- coding: utf-8 -*-
from model.group import Group
import random
def test_modify_some_group(app, db, check_ui):
| 29 | 64 | 173 | 12 | 16 | mynameisalexander/python_training | test/test_modify_group.py | Python | test_modify_some_group | test_modify_some_group | 6 | 23 | 6 | 6 | b38ef3546afe516ef6697a1f3a046a2869dec237 | bigcode/the-stack | train |
680fd54408467e45557267b8 | train | class | class GuidedBackprop():
"""
Produces gradients generated with guided back propagation from the given image
"""
def __init__(self, model):
self.model = model
self.gradients = None
self.forward_relu_outputs = {}
# Put model in evaluation mode
self.model.eval()
... | class GuidedBackprop():
| """
Produces gradients generated with guided back propagation from the given image
"""
def __init__(self, model):
self.model = model
self.gradients = None
self.forward_relu_outputs = {}
# Put model in evaluation mode
self.model.eval()
self.update_relus(... | """
Created on Thu Oct 26 11:23:47 2017
@author: Utku Ozbulak - github.com/utkuozbulak
Modified on Wed Jul 24 17:37:43 2019
@author: Shiyi Lan - github.com/voidrank
"""
from IPython import embed
import torch
from torch.nn import ReLU, Module
from .misc_functions import (get_example_params,
... | 114 | 195 | 651 | 5 | 109 | voidrank/SaccadeNet | src/lib/utils/guided_backprop.py | Python | GuidedBackprop | GuidedBackprop | 20 | 95 | 20 | 20 | f8e73f6f98eb61a211f6461a019bfadbc9aa67c7 | bigcode/the-stack | train |
41989310c7ac8cac66ecfdaa | train | function | def log(text, array=None):
"""Prints a text message. And, optionally, if a Numpy array is provided it
prints it's shape, min, and max values.
"""
if array is not None:
text = text.ljust(25)
text += ("shape: {:20} ".format(str(array.shape)))
if array.size:
tex... | def log(text, array=None):
| """Prints a text message. And, optionally, if a Numpy array is provided it
prints it's shape, min, and max values.
"""
if array is not None:
text = text.ljust(25)
text += ("shape: {:20} ".format(str(array.shape)))
if array.size:
text += ("min: {:10.5f} max: {... | .8+.
from distutils.version import LooseVersion
assert LooseVersion(tf.__version__) >= LooseVersion("1.3")
assert LooseVersion(keras.__version__) >= LooseVersion('2.0.8')
############################################################
# Utility Functions
#########################################################... | 64 | 64 | 142 | 7 | 56 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | log | log | 38 | 50 | 38 | 38 | d011962c9ce18e2c4f8470f48112c5702f254207 | bigcode/the-stack | train |
6f29435a20ab318fd4b316e4 | train | function | def refine_detections_graph(rois, probs, deltas, window, config):
"""Refine classified proposals and filter overlaps and return final
detections.
Inputs:
rois: [N, (y1, x1, y2, x2)] in normalized coordinates
probs: [N, num_classes]. Class probabilities.
deltas: [N, num_classe... | def refine_detections_graph(rois, probs, deltas, window, config):
| """Refine classified proposals and filter overlaps and return final
detections.
Inputs:
rois: [N, (y1, x1, y2, x2)] in normalized coordinates
probs: [N, num_classes]. Class probabilities.
deltas: [N, num_classes, (dy, dx, log(dh), log(dw))]. Class-specific
bou... | _bbox to target_deltas for clarity
names = ["rois", "target_class_ids", "target_bbox", "target_mask"]
outputs = utils.batch_slice(
[proposals, gt_class_ids, gt_boxes, gt_masks],
lambda w, x, y, z: detection_targets_graph(
w, x, y, z, self.config),
... | 256 | 256 | 1,175 | 18 | 237 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | refine_detections_graph | refine_detections_graph | 684 | 779 | 684 | 684 | 3f0577b0004d15a41f004630b614fd5cdba6e662 | bigcode/the-stack | train |
48e86bb377e4b94e1d77c0cc | train | function | def trim_zeros_graph(boxes, name='trim_zeros'):
"""Often boxes are represented with matrices of shape [N, 4] and
are padded with zeros. This removes zero boxes.
boxes: [N, 4] matrix of boxes.
non_zeros: [N] a 1D boolean mask identifying the rows to keep
"""
non_zeros = tf.cast(tf.reduce_... | def trim_zeros_graph(boxes, name='trim_zeros'):
| """Often boxes are represented with matrices of shape [N, 4] and
are padded with zeros. This removes zero boxes.
boxes: [N, 4] matrix of boxes.
non_zeros: [N] a 1D boolean mask identifying the rows to keep
"""
non_zeros = tf.cast(tf.reduce_sum(tf.abs(boxes), axis=1), tf.bool)
boxes =... | _images, config):
"""Takes a image normalized with mold() and returns the original."""
return (normalized_images + config.MEAN_PIXEL).astype(np.uint8)
############################################################
# Miscellenous Graph Functions
###########################################################... | 64 | 64 | 124 | 14 | 49 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | trim_zeros_graph | trim_zeros_graph | 2,822 | 2,831 | 2,822 | 2,822 | 189c6715292dcd8ae33fa3d15ad3e4e906a03244 | bigcode/the-stack | train |
4f71e87b45a0d8b2e6cea339 | train | function | def fpn_classifier_graph(rois, feature_maps, image_meta,
pool_size, num_classes, train_bn=True,
fc_layers_size=1024):
"""Builds the computation graph of the feature pyramid network classifier
and regressor heads.
rois: [batch, num_rois, (y1, x1, y2, x... | def fpn_classifier_graph(rois, feature_maps, image_meta,
pool_size, num_classes, train_bn=True,
fc_layers_size=1024):
| """Builds the computation graph of the feature pyramid network classifier
and regressor heads.
rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
coordinates.
feature_maps: List of feature maps from different layers of the pyramid,
[P2, P3, P4, P5].... | the backbone feature map.
Returns a Keras Model object. The model outputs, when called, are:
rpn_class_logits: [batch, H * W * anchors_per_location, 2] Anchor classifier logits (before softmax)
rpn_probs: [batch, H * W * anchors_per_location, 2] Anchor classifier probabilities.
rpn_bbox: [batch, ... | 219 | 219 | 733 | 33 | 185 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | fpn_classifier_graph | fpn_classifier_graph | 901 | 954 | 901 | 903 | db6d449ddada4369c30d9a670e97284b8f5db087 | bigcode/the-stack | train |
a579bfac5a1ab2177d8b7aa0 | train | function | def build_rpn_targets(image_shape, anchors, gt_class_ids, gt_boxes, config):
"""Given the anchors and GT boxes, compute overlaps and identify positive
anchors and deltas to refine them to match their corresponding GT boxes.
anchors: [num_anchors, (y1, x1, y2, x2)]
gt_class_ids: [num_gt_boxes] Inte... | def build_rpn_targets(image_shape, anchors, gt_class_ids, gt_boxes, config):
| """Given the anchors and GT boxes, compute overlaps and identify positive
anchors and deltas to refine them to match their corresponding GT boxes.
anchors: [num_anchors, (y1, x1, y2, x2)]
gt_class_ids: [num_gt_boxes] Integer class IDs.
gt_boxes: [num_gt_boxes, (y1, x1, y2, x2)]
Returns:... | :
# Create a mask placeholder, the size of the image
placeholder = np.zeros(config.IMAGE_SHAPE[:2], dtype=bool)
# GT box
gt_y1, gt_x1, gt_y2, gt_x2 = gt_boxes[gt_id]
gt_w = gt_x2 - gt_x1
gt_h = gt_y2 - gt_y1
# Resize mini mask to... | 256 | 256 | 1,395 | 19 | 236 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | build_rpn_targets | build_rpn_targets | 1,446 | 1,554 | 1,446 | 1,446 | 1c4a046f029769a19c021e00d21e10a9b660fa80 | bigcode/the-stack | train |
f89550e0aed9937620780bf6 | train | function | def resnet_graph(input_image, architecture, stage5=False, train_bn=True):
"""Build a ResNet graph.
architecture: Can be resnet50 or resnet101
stage5: Boolean. If False, stage5 of the network is not created
train_bn: Boolean. Train or freeze Batch Norm layers
"""
assert architec... | def resnet_graph(input_image, architecture, stage5=False, train_bn=True):
| """Build a ResNet graph.
architecture: Can be resnet50 or resnet101
stage5: Boolean. If False, stage5 of the network is not created
train_bn: Boolean. Train or freeze Batch Norm layers
"""
assert architecture in ["resnet50", "resnet101"]
# Stage 1
x = KL.ZeroPadding2D(... | _bias)(x)
x = BatchNorm(name=bn_name_base + '2b')(x, training=train_bn)
x = KL.Activation('relu')(x)
x = KL.Conv2D(nb_filter3, (1, 1), name=conv_name_base +
'2c', use_bias=use_bias)(x)
x = BatchNorm(name=bn_name_base + '2c')(x, training=train_bn)
shortcut = KL.Conv2D(nb_f... | 210 | 210 | 701 | 17 | 192 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | resnet_graph | resnet_graph | 171 | 206 | 171 | 171 | 39bcbd9822dfc3852ffdb08a8c4bf0e0e32de465 | bigcode/the-stack | train |
a2102c42c40b3b702dd82fdb | train | function | def mrcnn_mask_loss_graph(target_masks, target_class_ids, pred_masks):
"""Mask binary cross-entropy loss for the masks head.
target_masks: [batch, num_rois, height, width].
A float32 tensor of values 0 or 1. Uses zero padding to fill array.
target_class_ids: [batch, num_rois]. Integer class ID... | def mrcnn_mask_loss_graph(target_masks, target_class_ids, pred_masks):
| """Mask binary cross-entropy loss for the masks head.
target_masks: [batch, num_rois, height, width].
A float32 tensor of values 0 or 1. Uses zero padding to fill array.
target_class_ids: [batch, num_rois]. Integer class IDs. Zero padded.
pred_masks: [batch, proposals, height, width, num_c... | = tf.stack([positive_roi_ix, positive_roi_class_ids], axis=1)
# Gather the deltas (predicted and true) that contribute to loss
target_bbox = tf.gather(target_bbox, positive_roi_ix)
pred_bbox = tf.gather_nd(pred_bbox, indices)
# Smooth-L1 Loss
loss = K.switch(tf.size(target_bbox) > 0,
... | 135 | 135 | 451 | 17 | 117 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | mrcnn_mask_loss_graph | mrcnn_mask_loss_graph | 1,144 | 1,180 | 1,144 | 1,144 | 96f5481c282c2d984857624e4aa2c7567b0f2469 | bigcode/the-stack | train |
997342fe5e1ea7c86d8e208e | train | function | def parse_image_meta(meta):
"""Parses an array that contains image attributes to its components.
See compose_image_meta() for more details.
meta: [batch, meta length] where meta length depends on NUM_CLASSES
Returns a dict of the parsed values.
"""
image_id = meta[:, 0]
original_i... | def parse_image_meta(meta):
| """Parses an array that contains image attributes to its components.
See compose_image_meta() for more details.
meta: [batch, meta length] where meta length depends on NUM_CLASSES
Returns a dict of the parsed values.
"""
image_id = meta[:, 0]
original_image_shape = meta[:, 1:4]
... | list(window) + # size=4 (y1, x1, y2, x2) in image cooredinates
[scale] + # size=1
list(active_class_ids) # size=num_classes
)
return meta
def parse_image_meta(meta):
| 65 | 65 | 218 | 6 | 58 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | parse_image_meta | parse_image_meta | 2,757 | 2,778 | 2,757 | 2,757 | 24873ee35ab1ffbaf8dceae88562db1cf982988c | bigcode/the-stack | train |
4f9835a5809090c91852e7b1 | train | function | def load_image_gt(dataset, config, image_id, augment=False, augmentation=None,
use_mini_mask=False):
"""Load and return ground truth data for an image (image, mask, bounding boxes).
augment: (deprecated. Use augmentation instead). If true, apply random
image augmentation. Current... | def load_image_gt(dataset, config, image_id, augment=False, augmentation=None,
use_mini_mask=False):
| """Load and return ground truth data for an image (image, mask, bounding boxes).
augment: (deprecated. Use augmentation instead). If true, apply random
image augmentation. Currently, only horizontal flipping is offered.
augmentation: Optional. An imgaug (https://github.com/aleju/imgaug) augment... | ]
pred_masks = tf.transpose(pred_masks, [0, 3, 1, 2])
# Only positive ROIs contribute to the loss. And only
# the class specific mask of each ROI.
positive_ix = tf.where(target_class_ids > 0)[:, 0]
positive_class_ids = tf.cast(
tf.gather(target_class_ids, positive_ix), tf.int64)
... | 256 | 256 | 1,078 | 24 | 231 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | load_image_gt | load_image_gt | 1,187 | 1,287 | 1,187 | 1,188 | 25291b2bbed4eed962634497830020c92b3bf479 | bigcode/the-stack | train |
07ee5994a405b7b0c2ec755b | train | function | def detection_targets_graph(proposals, gt_class_ids, gt_boxes, gt_masks, config):
"""Generates detection targets for one image. Subsamples proposals and
generates target class IDs, bounding box deltas, and masks for each.
Inputs:
proposals: [POST_NMS_ROIS_TRAINING, (y1, x1, y2, x2)] in normalized ... | def detection_targets_graph(proposals, gt_class_ids, gt_boxes, gt_masks, config):
| """Generates detection targets for one image. Subsamples proposals and
generates target class IDs, bounding box deltas, and masks for each.
Inputs:
proposals: [POST_NMS_ROIS_TRAINING, (y1, x1, y2, x2)] in normalized coordinates. Might
be zero padded if there are not enough proposals... | 2 = tf.split(b2, 4, axis=1)
y1 = tf.maximum(b1_y1, b2_y1)
x1 = tf.maximum(b1_x1, b2_x1)
y2 = tf.minimum(b1_y2, b2_y2)
x2 = tf.minimum(b1_x2, b2_x2)
intersection = tf.maximum(x2 - x1, 0) * tf.maximum(y2 - y1, 0)
# 3. Compute unions
b1_area = (b1_y2 - b1_y1) * (b1_x2 - b1_x1)
b2_ar... | 256 | 256 | 1,751 | 19 | 236 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | detection_targets_graph | detection_targets_graph | 486 | 619 | 486 | 486 | d2e0c9cfca6456358e5f1e28bff8eea2ca4698d2 | bigcode/the-stack | train |
47e514827bdf279188d96725 | train | function | def smooth_l1_loss(y_true, y_pred):
"""Implements Smooth-L1 loss.
y_true and y_pred are typically: [N, 4], but could be any shape.
"""
diff = K.abs(y_true - y_pred)
less_than_one = K.cast(K.less(diff, 1.0), "float32")
loss = (less_than_one * 0.5 * diff**2) + (1 - less_than_one) * (diff - 0... | def smooth_l1_loss(y_true, y_pred):
| """Implements Smooth-L1 loss.
y_true and y_pred are typically: [N, 4], but could be any shape.
"""
diff = K.abs(y_true - y_pred)
less_than_one = K.cast(K.less(diff, 1.0), "float32")
loss = (less_than_one * 0.5 * diff**2) + (1 - less_than_one) * (diff - 0.5)
return loss
| x = KL.TimeDistributed(KL.Conv2D(num_classes, (1, 1), strides=1, activation="sigmoid"),
name="mrcnn_mask")(x)
return x
############################################################
# Loss Functions
############################################################
def smooth_l1_loss(y... | 64 | 64 | 112 | 11 | 52 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | smooth_l1_loss | smooth_l1_loss | 1,013 | 1,020 | 1,013 | 1,013 | e0dc724a6b7bab2254fc6859bb76ad5977f83f03 | bigcode/the-stack | train |
5333cb4ad5ef15f29875ee9b | train | function | def data_generator(dataset, config, shuffle=True, augment=False, augmentation=None,
random_rois=0, batch_size=1, detection_targets=False,
no_augmentation_sources=None):
"""A generator that returns images and corresponding target class ids,
bounding box deltas, and masks... | def data_generator(dataset, config, shuffle=True, augment=False, augmentation=None,
random_rois=0, batch_size=1, detection_targets=False,
no_augmentation_sources=None):
| """A generator that returns images and corresponding target class ids,
bounding box deltas, and masks.
dataset: The Dataset object to pick data from
config: The model config object
shuffle: If True, shuffles the samples before every epoch
augment: (deprecated. Use augmentation instead). I... | 0] - y1y2[:, 1]) >=
threshold][:remaining_count]
x1x2 = x1x2[np.abs(x1x2[:, 0] - x1x2[:, 1]) >=
threshold][:remaining_count]
if y1y2.shape[0] == remaining_count and x1x2.shape[0] == remaining_count:
break
# Sort on axis 1 to ensure x1 <= x2... | 256 | 256 | 1,995 | 39 | 216 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | data_generator | data_generator | 1,631 | 1,814 | 1,631 | 1,633 | bf286493955bf8a0ec53fa6cebc6848792e16a1f | bigcode/the-stack | train |
c4fcff281b00056b8082a8ce | train | class | class ProposalLayer(KE.Layer):
"""Receives anchor scores and selects a subset to pass as proposals
to the second stage. Filtering is done based on anchor scores and
non-max suppression to remove overlaps. It also applies bounding
box refinement deltas to anchors.
Inputs:
rpn_probs: [... | class ProposalLayer(KE.Layer):
| """Receives anchor scores and selects a subset to pass as proposals
to the second stage. Filtering is done based on anchor scores and
non-max suppression to remove overlaps. It also applies bounding
box refinement deltas to anchors.
Inputs:
rpn_probs: [batch, num_anchors, (bg prob, fg... | ([y1, x1, y2, x2], axis=1, name="apply_box_deltas_out")
return result
def clip_boxes_graph(boxes, window):
"""
boxes: [N, (y1, x1, y2, x2)]
window: [4] in the form y1, x1, y2, x2
"""
# Split
wy1, wx1, wy2, wx2 = tf.split(window, 4)
y1, x1, y2, x2 = tf.split(boxes, 4, axis=1)... | 256 | 256 | 882 | 7 | 248 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | ProposalLayer | ProposalLayer | 255 | 332 | 255 | 255 | 70e9594c5d2e5cbab359299d8346dc85b07a2b74 | bigcode/the-stack | train |
11a19e74adabc95fb2801f7f | train | function | def mold_image(images, config):
"""Expects an RGB image (or array of images) and subtracts
the mean pixel and converts it to float. Expects image
colors in RGB order.
"""
return images.astype(np.float32) - config.MEAN_PIXEL
| def mold_image(images, config):
| """Expects an RGB image (or array of images) and subtracts
the mean pixel and converts it to float. Expects image
colors in RGB order.
"""
return images.astype(np.float32) - config.MEAN_PIXEL
| 12:]
return {
"image_id": image_id,
"original_image_shape": original_image_shape,
"image_shape": image_shape,
"window": window,
"scale": scale,
"active_class_ids": active_class_ids,
}
def mold_image(images, config):
| 64 | 64 | 60 | 7 | 57 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | mold_image | mold_image | 2,805 | 2,810 | 2,805 | 2,805 | 6c6adde88fdd8b1dbc6e50a93a0143674a88faf6 | bigcode/the-stack | train |
ccf6b71341f807a494ce0d0b | train | function | def unmold_image(normalized_images, config):
"""Takes a image normalized with mold() and returns the original."""
return (normalized_images + config.MEAN_PIXEL).astype(np.uint8)
| def unmold_image(normalized_images, config):
| """Takes a image normalized with mold() and returns the original."""
return (normalized_images + config.MEAN_PIXEL).astype(np.uint8)
| ):
"""Expects an RGB image (or array of images) and subtracts
the mean pixel and converts it to float. Expects image
colors in RGB order.
"""
return images.astype(np.float32) - config.MEAN_PIXEL
def unmold_image(normalized_images, config):
| 64 | 64 | 42 | 10 | 53 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | unmold_image | unmold_image | 2,813 | 2,815 | 2,813 | 2,813 | 85af13b67fc8f155da022fd5c70b76881d77f403 | bigcode/the-stack | train |
29aa1db82b1f8818e6a06b8d | train | function | def rpn_class_loss_graph(rpn_match, rpn_class_logits):
"""RPN anchor classifier loss.
rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive,
-1=negative, 0=neutral anchor.
rpn_class_logits: [batch, anchors, 2]. RPN classifier logits for BG/FG.
"""
# Squeeze last dim to... | def rpn_class_loss_graph(rpn_match, rpn_class_logits):
| """RPN anchor classifier loss.
rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive,
-1=negative, 0=neutral anchor.
rpn_class_logits: [batch, anchors, 2]. RPN classifier logits for BG/FG.
"""
# Squeeze last dim to simplify
rpn_match = tf.squeeze(rpn_match, -1)
... | .
"""
diff = K.abs(y_true - y_pred)
less_than_one = K.cast(K.less(diff, 1.0), "float32")
loss = (less_than_one * 0.5 * diff**2) + (1 - less_than_one) * (diff - 0.5)
return loss
def rpn_class_loss_graph(rpn_match, rpn_class_logits):
| 87 | 87 | 290 | 15 | 71 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | rpn_class_loss_graph | rpn_class_loss_graph | 1,023 | 1,045 | 1,023 | 1,023 | 3dadfa29a742d36d119f3ed109d45f229f3e5bec | bigcode/the-stack | train |
ad8cf947c7cf490d05abf895 | train | function | def rpn_graph(feature_map, anchors_per_location, anchor_stride):
"""Builds the computation graph of Region Proposal Network.
feature_map: backbone features [batch, height, width, depth]
anchors_per_location: number of anchors per pixel in the feature map
anchor_stride: Controls the density of anch... | def rpn_graph(feature_map, anchors_per_location, anchor_stride):
| """Builds the computation graph of Region Proposal Network.
feature_map: backbone features [batch, height, width, depth]
anchors_per_location: number of anchors per pixel in the feature map
anchor_stride: Controls the density of anchors. Typically 1 (anchors for
every pixel in t... | lambda x, y, w, z: refine_detections_graph(x, y, w, z, self.config),
self.config.IMAGES_PER_GPU)
# Reshape output
# [batch, num_detections, (y1, x1, y2, x2, class_id, class_score)] in
# normalized coordinates
return tf.reshape(
detections_batch,
... | 161 | 161 | 539 | 14 | 146 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | rpn_graph | rpn_graph | 831 | 872 | 831 | 831 | 051f5e6ecf3587e6caba585569b4dbd8b3fb9fc5 | bigcode/the-stack | train |
29d10c63d80d315a2992899e | train | function | def overlaps_graph(boxes1, boxes2):
"""Computes IoU overlaps between two sets of boxes.
boxes1, boxes2: [N, (y1, x1, y2, x2)].
"""
# 1. Tile boxes2 and repeat boxes1. This allows us to compare
# every boxes1 against every boxes2 without loops.
# TF doesn't have an equivalent to np.repeat()... | def overlaps_graph(boxes1, boxes2):
| """Computes IoU overlaps between two sets of boxes.
boxes1, boxes2: [N, (y1, x1, y2, x2)].
"""
# 1. Tile boxes2 and repeat boxes1. This allows us to compare
# every boxes1 against every boxes2 without loops.
# TF doesn't have an equivalent to np.repeat() so simulate it
# using tf.tile(... | _to_level)[0]).indices[::-1]
ix = tf.gather(box_to_level[:, 2], ix)
pooled = tf.gather(pooled, ix)
# Re-add the batch dimension
shape = tf.concat([tf.shape(boxes)[:2], tf.shape(pooled)[1:]], axis=0)
pooled = tf.reshape(pooled, shape)
return pooled
def compu... | 139 | 139 | 464 | 10 | 128 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | overlaps_graph | overlaps_graph | 457 | 483 | 457 | 457 | b055099ecbe95c8ee887c7eb45465fbf901db5c4 | bigcode/the-stack | train |
89ff74d2e71d960cab2029d8 | train | function | def rpn_bbox_loss_graph(config, target_bbox, rpn_match, rpn_bbox):
"""Return the RPN bounding box loss graph.
config: the model config object.
target_bbox: [batch, max positive anchors, (dy, dx, log(dh), log(dw))].
Uses 0 padding to fill in unsed bbox deltas.
rpn_match: [batch, anchors, 1... | def rpn_bbox_loss_graph(config, target_bbox, rpn_match, rpn_bbox):
| """Return the RPN bounding box loss graph.
config: the model config object.
target_bbox: [batch, max positive anchors, (dy, dx, log(dh), log(dw))].
Uses 0 padding to fill in unsed bbox deltas.
rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive,
-1=negative, 0=neu... | _logits, indices)
anchor_class = tf.gather_nd(anchor_class, indices)
# Cross entropy loss
loss = K.sparse_categorical_crossentropy(target=anchor_class,
output=rpn_class_logits,
from_logits=True)
loss = K.swit... | 97 | 97 | 325 | 19 | 77 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | rpn_bbox_loss_graph | rpn_bbox_loss_graph | 1,048 | 1,074 | 1,048 | 1,048 | f5ff133893af7d81863e61223dedb5822f3143ab | bigcode/the-stack | train |
3f04f005ff75f6ef0187ad3e | train | class | class DetectionLayer(KE.Layer):
"""Takes classified proposal boxes and their bounding box deltas and
returns the final detection boxes.
Returns:
[batch, num_detections, (y1, x1, y2, x2, class_id, class_score)] where
coordinates are normalized.
"""
def __init__(self, config=None, *... | class DetectionLayer(KE.Layer):
| """Takes classified proposal boxes and their bounding box deltas and
returns the final detection boxes.
Returns:
[batch, num_detections, (y1, x1, y2, x2, class_id, class_score)] where
coordinates are normalized.
"""
def __init__(self, config=None, **kwargs):
super(Detectio... | ([
tf.gather(refined_rois, keep),
tf.cast(tf.gather(class_ids, keep), np.float32)[..., tf.newaxis],
tf.gather(class_scores, keep)[..., tf.newaxis]
], axis=1)
# Pad with zeros if detections < DETECTION_MAX_INSTANCES
gap = config.DETECTION_MAX_INSTANCES - tf.shape(detection... | 125 | 125 | 419 | 7 | 117 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | DetectionLayer | DetectionLayer | 782 | 824 | 782 | 782 | 170c5c61ee46268e100fe1099ff7d913f287628d | bigcode/the-stack | train |
415f6860f17c18f4e3f805bb | train | function | def clip_boxes_graph(boxes, window):
"""
boxes: [N, (y1, x1, y2, x2)]
window: [4] in the form y1, x1, y2, x2
"""
# Split
wy1, wx1, wy2, wx2 = tf.split(window, 4)
y1, x1, y2, x2 = tf.split(boxes, 4, axis=1)
# Clip
y1 = tf.maximum(tf.minimum(y1, wy2), wy1)
x1 = tf.maximum... | def clip_boxes_graph(boxes, window):
| """
boxes: [N, (y1, x1, y2, x2)]
window: [4] in the form y1, x1, y2, x2
"""
# Split
wy1, wx1, wy2, wx2 = tf.split(window, 4)
y1, x1, y2, x2 = tf.split(boxes, 4, axis=1)
# Clip
y1 = tf.maximum(tf.minimum(y1, wy2), wy1)
x1 = tf.maximum(tf.minimum(x1, wx2), wx1)
y2 = t... | .5 * width
y2 = y1 + height
x2 = x1 + width
result = tf.stack([y1, x1, y2, x2], axis=1, name="apply_box_deltas_out")
return result
def clip_boxes_graph(boxes, window):
| 66 | 66 | 220 | 9 | 56 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | clip_boxes_graph | clip_boxes_graph | 237 | 252 | 237 | 237 | 733ff86e98ad4feb107a46da0d8391fa0277c3b4 | bigcode/the-stack | train |
9c0568bd4e23ff7a4a43436c | train | function | def mrcnn_bbox_loss_graph(target_bbox, target_class_ids, pred_bbox):
"""Loss for Mask R-CNN bounding box refinement.
target_bbox: [batch, num_rois, (dy, dx, log(dh), log(dw))]
target_class_ids: [batch, num_rois]. Integer class IDs.
pred_bbox: [batch, num_rois, num_classes, (dy, dx, log(dh), log(dw... | def mrcnn_bbox_loss_graph(target_bbox, target_class_ids, pred_bbox):
| """Loss for Mask R-CNN bounding box refinement.
target_bbox: [batch, num_rois, (dy, dx, log(dh), log(dw))]
target_class_ids: [batch, num_rois]. Integer class IDs.
pred_bbox: [batch, num_rois, num_classes, (dy, dx, log(dh), log(dw))]
"""
# Reshape to merge batch and roi dimensions for simp... | _with_logits(
labels=target_class_ids, logits=pred_class_logits)
# Erase losses of predictions of classes that are not in the active
# classes of the image.
loss = loss * pred_active
# Computer loss mean. Use only predictions that contribute
# to the loss to get a correct mean.
... | 106 | 106 | 355 | 17 | 88 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | mrcnn_bbox_loss_graph | mrcnn_bbox_loss_graph | 1,113 | 1,141 | 1,113 | 1,113 | a02f8a6e6e935f2b73cf26128e90262b6b9ccdf8 | bigcode/the-stack | train |
d94109f225a5d6749a89e3d2 | train | function | def norm_boxes_graph(boxes, shape):
"""Converts boxes from pixel coordinates to normalized coordinates.
boxes: [..., (y1, x1, y2, x2)] in pixel coordinates
shape: [..., (height, width)] in pixels
Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
coordinates it's inside... | def norm_boxes_graph(boxes, shape):
| """Converts boxes from pixel coordinates to normalized coordinates.
boxes: [..., (y1, x1, y2, x2)] in pixel coordinates
shape: [..., (height, width)] in pixels
Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
coordinates it's inside the box.
Returns:
[.... | Picks different number of values from each row
in x depending on the values in counts.
"""
outputs = []
for i in range(num_rows):
outputs.append(x[i, :counts[i]])
return tf.concat(outputs, axis=0)
def norm_boxes_graph(boxes, shape):
| 64 | 64 | 183 | 9 | 55 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | norm_boxes_graph | norm_boxes_graph | 2,844 | 2,858 | 2,844 | 2,844 | ff14d592a04b297c7c07ce79588e0c6c9a5d808d | bigcode/the-stack | train |
af1fb30868fda35cc089bb19 | train | function | def denorm_boxes_graph(boxes, shape):
"""Converts boxes from normalized coordinates to pixel coordinates.
boxes: [..., (y1, x1, y2, x2)] in normalized coordinates
shape: [..., (height, width)] in pixels
Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
coordinates it's... | def denorm_boxes_graph(boxes, shape):
| """Converts boxes from normalized coordinates to pixel coordinates.
boxes: [..., (y1, x1, y2, x2)] in normalized coordinates
shape: [..., (height, width)] in pixels
Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
coordinates it's inside the box.
Returns:
... | scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)
shift = tf.constant([0., 0., 1., 1.])
return tf.divide(boxes - shift, scale)
def denorm_boxes_graph(boxes, shape):
| 64 | 64 | 193 | 10 | 54 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | denorm_boxes_graph | denorm_boxes_graph | 2,861 | 2,875 | 2,861 | 2,861 | 808ad99eed3f88cabc70dce1f50632ae6f0f49c6 | bigcode/the-stack | train |
7d955404d85b38ca62076f06 | train | function | def log2_graph(x):
"""Implementation of Log2. TF doesn't have a native implementation."""
return tf.math.log(x) / tf.math.log(2.0)
| def log2_graph(x):
| """Implementation of Log2. TF doesn't have a native implementation."""
return tf.math.log(x) / tf.math.log(2.0)
| utils.batch_slice([boxes, scores], nms,
self.config.IMAGES_PER_GPU)
return proposals
def compute_output_shape(self, input_shape):
return (None, self.proposal_count, 4)
############################################################
# ROIAlign Layer
#... | 64 | 64 | 37 | 6 | 57 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | log2_graph | log2_graph | 339 | 341 | 339 | 339 | 092e2a7cad2d1e79743c2d15c94077cb96fa66e5 | bigcode/the-stack | train |
787b63af13259c6a871ee9d6 | train | function | def build_fpn_mask_graph(rois, feature_maps, image_meta,
pool_size, num_classes, train_bn=True):
"""Builds the computation graph of the mask head of Feature Pyramid Network.
rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
coordinates.
feature_... | def build_fpn_mask_graph(rois, feature_maps, image_meta,
pool_size, num_classes, train_bn=True):
| """Builds the computation graph of the mask head of Feature Pyramid Network.
rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
coordinates.
feature_maps: List of feature maps from different layers of the pyramid,
[P2, P3, P4, P5]. Each has a different r... | L.Activation("softmax"),
name="mrcnn_class")(mrcnn_class_logits)
# BBox head
# [batch, num_rois, NUM_CLASSES * (dy, dx, log(dh), log(dw))]
x = KL.TimeDistributed(KL.Dense(num_classes * 4, activation='linear'),
name='mrcnn_bbox_fc')(share... | 191 | 191 | 637 | 26 | 164 | Medicmind/Mask-RCNN-TF2 | mrcnn/model_temp.py | Python | build_fpn_mask_graph | build_fpn_mask_graph | 957 | 1,006 | 957 | 958 | 6fb74efba1c77a6ed8d5d8182ea290a794faf0a9 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.