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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f26c2c1cb4f7cf5a97636b26 | train | class | class SetupApp4Site2Test(SetupAppBaseTest):
config = App4Config
module = "tests.sample_app_4"
app_name = "App4"
def setUp(self):
super().setUp()
Site.objects.create(name="domain2", domain="www.example2.com", id=2)
def test_setup_from_cmsapp(self):
with self.settings(SITE_ID... | class SetupApp4Site2Test(SetupAppBaseTest):
| config = App4Config
module = "tests.sample_app_4"
app_name = "App4"
def setUp(self):
super().setUp()
Site.objects.create(name="domain2", domain="www.example2.com", id=2)
def test_setup_from_cmsapp(self):
with self.settings(SITE_ID=1):
self._setup_from_cmsapp(sit... | = "App3"
def test_setup_from_cmsapp(self):
self._setup_from_cmsapp()
def test_setup_filled(self):
self._setup_filled()
class SetupApp4Test(SetupAppBaseTest):
config = App4Config
module = "tests.sample_app_4"
app_name = "App4"
def test_setup_from_cmsapp(self):
self._... | 207 | 207 | 691 | 13 | 194 | nephila/djangocms-apphook-setup | tests/test_setup.py | Python | SetupApp4Site2Test | SetupApp4Site2Test | 169 | 225 | 169 | 169 | 492d5c7fd9642ac748d8fe229c716123f133a6a0 | bigcode/the-stack | train |
dc791fbefc8a7f790c476451 | train | class | class SetupApp6Site2Test(SetupAppBaseTest):
config = App6Config
module = "tests.sample_app_6"
app_name = "App6"
def setUp(self):
super().setUp()
Site.objects.create(name="domain2", domain="www.example2.com", id=2)
def test_setup_from_cmsapp(self):
with self.settings(SITE_ID... | class SetupApp6Site2Test(SetupAppBaseTest):
| config = App6Config
module = "tests.sample_app_6"
app_name = "App6"
def setUp(self):
super().setUp()
Site.objects.create(name="domain2", domain="www.example2.com", id=2)
def test_setup_from_cmsapp(self):
with self.settings(SITE_ID=1):
self._setup_from_cmsapp(sit... | auto setup
with self.settings(SITE_ID=1):
__import__(self.module, fromlist=("cms_apps",))
config = self.config.objects.first()
self.assertEqual(set(config.get_available_languages()), {"en", "it", "fr"})
self.assertTrue(config.random_option)
config.set... | 190 | 190 | 634 | 13 | 177 | nephila/djangocms-apphook-setup | tests/test_setup.py | Python | SetupApp6Site2Test | SetupApp6Site2Test | 228 | 278 | 228 | 228 | ff00a65e050e1f32a0b48ca39019cdc9d8d440e8 | bigcode/the-stack | train |
73075dcd3570b0a4e319c492 | train | class | class SetupApp1Test(SetupAppBaseTest):
config = AppConfig
module = "tests.sample_app_1"
app_name = "App1"
def test_setup_from_cmsapp(self):
self._setup_from_cmsapp()
def test_setup_filled(self):
self._setup_filled()
def test_config_values(self):
# importing cms_app tri... | class SetupApp1Test(SetupAppBaseTest):
| config = AppConfig
module = "tests.sample_app_1"
app_name = "App1"
def test_setup_from_cmsapp(self):
self._setup_from_cmsapp()
def test_setup_filled(self):
self._setup_filled()
def test_config_values(self):
# importing cms_app triggers the auto setup
__import__... | :
self.assertEqual(self.config.objects.count(), configs_final)
self.assertEqual(Page.objects.filter(application_urls=self.app_name).count(), blog_final)
home = Page.objects.get_home(site)
self.assertEqual(home.get_title(), "a new home")
class SetupApp1Test(SetupAppBaseTest):
| 64 | 64 | 120 | 11 | 53 | nephila/djangocms-apphook-setup | tests/test_setup.py | Python | SetupApp1Test | SetupApp1Test | 108 | 123 | 108 | 108 | 815ae29ab78be8ae3d63926def6e60c010fd0d8d | bigcode/the-stack | train |
0b93ae7cc694784afde4f3bf | train | class | class SetupApp2Test(SetupAppBaseTest):
module = "tests.sample_app_2"
app_name = "App2"
def test_setup_from_cmsapp(self):
self._setup_from_cmsapp()
def test_setup_filled(self):
self._setup_filled()
| class SetupApp2Test(SetupAppBaseTest):
| module = "tests.sample_app_2"
app_name = "App2"
def test_setup_from_cmsapp(self):
self._setup_from_cmsapp()
def test_setup_filled(self):
self._setup_filled()
| illed()
def test_config_values(self):
# importing cms_app triggers the auto setup
__import__(self.module, fromlist=("cms_apps",))
config = self.config.objects.first()
self.assertEqual(config.app_title, "app title")
class SetupApp2Test(SetupAppBaseTest):
| 64 | 64 | 63 | 11 | 53 | nephila/djangocms-apphook-setup | tests/test_setup.py | Python | SetupApp2Test | SetupApp2Test | 126 | 134 | 126 | 126 | 3adc5122574a39630e86a455e5eb2b90a6160e63 | bigcode/the-stack | train |
d7d84e6e58ab3a0f0d7c8e72 | train | class | class SetupApp5Test(SetupAppBaseTest):
module = "tests.sample_app_5"
app_name = "App5"
def test_setup_empty(self):
# Tests starts with no page and no config
self.assertFalse(Page.objects.exists())
self.assertEqual(Page.objects.filter(application_urls=self.app_name).count(), 0)
... | class SetupApp5Test(SetupAppBaseTest):
| module = "tests.sample_app_5"
app_name = "App5"
def test_setup_empty(self):
# Tests starts with no page and no config
self.assertFalse(Page.objects.exists())
self.assertEqual(Page.objects.filter(application_urls=self.app_name).count(), 0)
# importing cms_app triggers the au... | .count(), 1)
config = self.config.objects.first()
self.assertEqual(set(config.get_available_languages()), {"en"})
self.assertTrue(config.random_option)
config.set_current_language("en")
self.assertEqual(config.object_name, "name")
class SetupApp5Test(SetupAppB... | 64 | 64 | 142 | 11 | 53 | nephila/djangocms-apphook-setup | tests/test_setup.py | Python | SetupApp5Test | SetupApp5Test | 281 | 297 | 281 | 281 | ca273ccccea5ed8d0f358b42a87c5bf97b01bf97 | bigcode/the-stack | train |
347a8560dc4a2428cca23688 | train | class | class SetupAppBaseTest(BaseTest):
config = None
module = None
app_name = None
def setUp(self):
super().setUp()
Page.objects.all().delete()
if self.config:
self.config.objects.all().delete()
self._delete_modules()
def _delete_modules(self):
from c... | class SetupAppBaseTest(BaseTest):
| config = None
module = None
app_name = None
def setUp(self):
super().setUp()
Page.objects.all().delete()
if self.config:
self.config.objects.all().delete()
self._delete_modules()
def _delete_modules(self):
from cms.apphook_pool import apphook_poo... | import sys
from cms.api import create_page, create_title
from cms.models import Page, Site, warnings
from cms.utils import get_language_list
from django.utils.translation import override
from .base import BaseTest
from .sample_app_1.cms_appconfig import AppConfig
from .sample_app_4.cms_appconfig import App4Config
fro... | 94 | 222 | 740 | 8 | 85 | nephila/djangocms-apphook-setup | tests/test_setup.py | Python | SetupAppBaseTest | SetupAppBaseTest | 14 | 105 | 14 | 14 | 6dcab195c80de7ad0bd8f5e0180bcab6a63c42ee | bigcode/the-stack | train |
75afd5a5c8b107c0ebc3b34c | train | function | def pub():
producer = KafkaProducer()
key = bytes('key', encoding='utf-8')
start = datetime.datetime.now()
cnt = 0
while True:
value = bytes(str(time.time()), encoding='utf-8')
producer.send("test", value=value, key=key)
cnt+=1
if datetime.datetime.now() > start + dat... | def pub():
| producer = KafkaProducer()
key = bytes('key', encoding='utf-8')
start = datetime.datetime.now()
cnt = 0
while True:
value = bytes(str(time.time()), encoding='utf-8')
producer.send("test", value=value, key=key)
cnt+=1
if datetime.datetime.now() > start + datetime.timed... | import os
from os.path import dirname
import sys
sys.path.append((dirname(sys.path[0])))
from arguments import argparser
import time
import datetime
from kafka import KafkaProducer
def pub():
| 43 | 64 | 101 | 3 | 39 | jsrimr/redis-kafka-rabbit-bench | kafka/kafka_pub_throughput.py | Python | pub | pub | 10 | 21 | 10 | 10 | 95b5116eed5e57c66a46dbd8886d98b6a8f4d598 | bigcode/the-stack | train |
f653af4d2d1128d0be8a8f8f | train | function | @functools.lru_cache
def parse_tag(
template: str, pointer: int, left_delimiter: str, right_delimiter: str
) -> Tuple[Tuple[Token, str], int]:
"""Parse a tag from a template"""
tag_pointer = pointer + len(left_delimiter)
try:
token = TOKENS[template[tag_pointer]]
tag_pointer += 1
ex... | @functools.lru_cache
def parse_tag(
template: str, pointer: int, left_delimiter: str, right_delimiter: str
) -> Tuple[Tuple[Token, str], int]:
| """Parse a tag from a template"""
tag_pointer = pointer + len(left_delimiter)
try:
token = TOKENS[template[tag_pointer]]
tag_pointer += 1
except KeyError:
token = Token.VARIABLE
if token is Token.NO_ESCAPE_BRACE:
right_delimiter = f'}}{right_delimiter}'
toke... | return (template[pointer:], len(template))
return (template[pointer:split_index], split_index)
@functools.lru_cache
def parse_tag(
template: str, pointer: int, left_delimiter: str, right_delimiter: str
) -> Tuple[Tuple[Token, str], int]:
| 68 | 68 | 227 | 45 | 23 | michaelrccurtis/moosetash | moosetash/tokenizer.py | Python | parse_tag | parse_tag | 47 | 75 | 47 | 50 | 41bc81e301388c583f2bfa31b97e27d593617aaf | bigcode/the-stack | train |
331aadd294c7d64d38b6df7f | train | function | @functools.lru_cache
def find_next_pointer(
template: str, tag_start_pointer: int, tag_end_pointer: int
) -> Tuple[bool, int, int]:
"""Find the next parsing pointer, based on the current tag and whether it is a standalone"""
pre_tag_line = template.rfind('\n', 0, tag_start_pointer)
post_tag_line = templ... | @functools.lru_cache
def find_next_pointer(
template: str, tag_start_pointer: int, tag_end_pointer: int
) -> Tuple[bool, int, int]:
| """Find the next parsing pointer, based on the current tag and whether it is a standalone"""
pre_tag_line = template.rfind('\n', 0, tag_start_pointer)
post_tag_line = template.find('\n', tag_end_pointer)
indentation_pointer = pre_tag_line
if pre_tag_line == -1:
pre_tag_line = 0
inde... | on line {line_number}', template, pointer
)
tag = template[tag_pointer:tag_end_pointer]
return ((token, tag.strip()), tag_end_pointer + len(right_delimiter))
@functools.lru_cache
def find_next_pointer(
template: str, tag_start_pointer: int, tag_end_pointer: int
) -> Tuple[bool, int, int]:
| 80 | 80 | 268 | 40 | 40 | michaelrccurtis/moosetash | moosetash/tokenizer.py | Python | find_next_pointer | find_next_pointer | 78 | 108 | 78 | 81 | a860bfa3d6c359dfce492d14138b9c493b822e22 | bigcode/the-stack | train |
cd45de930b48d7d51fad2229 | train | function | def tokenize(
template: str, pointer: int = 0, left_delimiter: str = '{{', right_delimiter: str = '}}'
) -> Iterator[Tuple[Tuple[Token, str, str], int]]:
"""Generate tokens from a template string"""
while pointer < len(template):
literal, tag_start_pointer = find_next_tag(template, pointer, left_de... | def tokenize(
template: str, pointer: int = 0, left_delimiter: str = '{{', right_delimiter: str = '}}'
) -> Iterator[Tuple[Tuple[Token, str, str], int]]:
| """Generate tokens from a template string"""
while pointer < len(template):
literal, tag_start_pointer = find_next_tag(template, pointer, left_delimiter)
indentation = ''
if tag_start_pointer == len(template):
# Reached the end of the template - return the final literal and... | 1:
post_tag_line = len(template)
else:
# Skip the newline character
post_tag_line += 1
return (
is_standalone,
post_tag_line if is_standalone else tag_end_pointer,
indentation_pointer if is_standalone else tag_start_pointer,
)
def tokenize(
template: str, ... | 114 | 114 | 381 | 48 | 66 | michaelrccurtis/moosetash | moosetash/tokenizer.py | Python | tokenize | tokenize | 111 | 155 | 111 | 113 | 12ce1966a91394488e5b3694468a7ab7fe4c978b | bigcode/the-stack | train |
b234c5162b247e2e256c410d | train | class | class Token(IntEnum):
"""Mustache token type"""
LITERAL = 1
VARIABLE = 2
COMMENT = 3
SECTION = 4
INVERTED = 5
END = 6
PARTIAL = 7
SET_DELIMITER = 8
NO_ESCAPE_BRACE = 9
NO_ESCAPE = 10
| class Token(IntEnum):
| """Mustache token type"""
LITERAL = 1
VARIABLE = 2
COMMENT = 3
SECTION = 4
INVERTED = 5
END = 6
PARTIAL = 7
SET_DELIMITER = 8
NO_ESCAPE_BRACE = 9
NO_ESCAPE = 10
| """Generate tokens from a mustache template"""
from typing import Iterator, Tuple
from enum import IntEnum
import functools
from .exceptions import MustacheSyntaxError
class Token(IntEnum):
| 39 | 64 | 82 | 5 | 33 | michaelrccurtis/moosetash | moosetash/tokenizer.py | Python | Token | Token | 8 | 20 | 8 | 8 | 628e3b14877ed634d6dcd99b0fc297fb84093b11 | bigcode/the-stack | train |
d099014ebede207ffc21441d | train | function | @functools.lru_cache
def find_next_tag(template: str, pointer: int, left_delimiter: str) -> Tuple[str, int]:
"""Find the next tag, and the literal between current pointer and that tag"""
split_index = template.find(left_delimiter, pointer)
if split_index == -1:
return (template[pointer:], len(temp... | @functools.lru_cache
def find_next_tag(template: str, pointer: int, left_delimiter: str) -> Tuple[str, int]:
| """Find the next tag, and the literal between current pointer and that tag"""
split_index = template.find(left_delimiter, pointer)
if split_index == -1:
return (template[pointer:], len(template))
return (template[pointer:split_index], split_index)
| '>': Token.PARTIAL,
'=': Token.SET_DELIMITER,
'{': Token.NO_ESCAPE_BRACE,
'&': Token.NO_ESCAPE,
}
@functools.lru_cache
def find_next_tag(template: str, pointer: int, left_delimiter: str) -> Tuple[str, int]:
| 64 | 64 | 92 | 32 | 32 | michaelrccurtis/moosetash | moosetash/tokenizer.py | Python | find_next_tag | find_next_tag | 35 | 44 | 35 | 36 | 82c789588a44d55fb8f5130b1663caf467a1f33f | bigcode/the-stack | train |
43dcc35c5a8e2eee99970937 | train | function | def test_template_filter_with_template():
bp = flask.Blueprint('bp', __name__)
@bp.app_template_filter()
def super_reverse(s):
return s[::-1]
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('te... | def test_template_filter_with_template():
| bp = flask.Blueprint('bp', __name__)
@bp.app_template_filter()
def super_reverse(s):
return s[::-1]
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('template_filter.html', value='abcd')
rv ... | _blueprint(bp, url_prefix='/py')
assert 'strrev' in app.jinja_env.filters.keys()
assert app.jinja_env.filters['strrev'] == my_reverse
assert app.jinja_env.filters['strrev']('abcd') == 'dcba'
def test_template_filter_with_template():
| 64 | 64 | 101 | 7 | 57 | spappier/flask | tests/test_blueprints.py | Python | test_template_filter_with_template | test_template_filter_with_template | 421 | 432 | 421 | 421 | 5ffce393529425f8ce25b51f064c4cc175028988 | bigcode/the-stack | train |
0cc0c3eb3631cf5a9dc86384 | train | function | def test_template_filter_after_route_with_template():
app = flask.Flask(__name__)
@app.route('/')
def index():
return flask.render_template('template_filter.html', value='abcd')
bp = flask.Blueprint('bp', __name__)
@bp.app_template_filter()
def super_reverse(s):
return s[::-1]
... | def test_template_filter_after_route_with_template():
| app = flask.Flask(__name__)
@app.route('/')
def index():
return flask.render_template('template_filter.html', value='abcd')
bp = flask.Blueprint('bp', __name__)
@bp.app_template_filter()
def super_reverse(s):
return s[::-1]
app.register_blueprint(bp, url_prefix='/py')
rv ... | __)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('template_filter.html', value='abcd')
rv = app.test_client().get('/')
assert rv.data == b'dcba'
def test_template_filter_after_route_with_template():
| 64 | 64 | 103 | 9 | 55 | spappier/flask | tests/test_blueprints.py | Python | test_template_filter_after_route_with_template | test_template_filter_after_route_with_template | 434 | 445 | 434 | 434 | b743edb63c4e34704dac44a5c207e564e5619f80 | bigcode/the-stack | train |
1ec357e331af55a7f2c23f56 | train | function | def test_dotted_names_from_app():
app = flask.Flask(__name__)
app.testing = True
test = flask.Blueprint('test', __name__)
@app.route('/')
def app_index():
return flask.url_for('test.index')
@test.route('/test/')
def index():
return flask.url_for('app_index')
app.regist... | def test_dotted_names_from_app():
| app = flask.Flask(__name__)
app.testing = True
test = flask.Blueprint('test', __name__)
@app.route('/')
def app_index():
return flask.url_for('test.index')
@test.route('/test/')
def index():
return flask.url_for('app_index')
app.register_blueprint(test)
with app.t... | (backend)
c = app.test_client()
assert c.get('/fe').data.strip() == b'/be'
assert c.get('/fe2').data.strip() == b'/fe'
assert c.get('/be').data.strip() == b'/fe'
def test_dotted_names_from_app():
| 64 | 64 | 105 | 8 | 56 | spappier/flask | tests/test_blueprints.py | Python | test_dotted_names_from_app | test_dotted_names_from_app | 238 | 255 | 238 | 238 | fb0bc406fd7bad517ecd712592e9a0f764945593 | bigcode/the-stack | train |
5f0586de1bdef691de18bb88 | train | function | def test_add_template_test_with_name():
bp = flask.Blueprint('bp', __name__)
def is_boolean(value):
return isinstance(value, bool)
bp.add_app_template_test(is_boolean, 'boolean')
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'boolean' in app.jinja_env.te... | def test_add_template_test_with_name():
| bp = flask.Blueprint('bp', __name__)
def is_boolean(value):
return isinstance(value, bool)
bp.add_app_template_test(is_boolean, 'boolean')
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'boolean' in app.jinja_env.tests.keys()
assert app.jinja_env.test... | ask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'boolean' in app.jinja_env.tests.keys()
assert app.jinja_env.tests['boolean'] == is_boolean
assert app.jinja_env.tests['boolean'](False)
def test_add_template_test_with_name():
| 64 | 64 | 106 | 8 | 56 | spappier/flask | tests/test_blueprints.py | Python | test_add_template_test_with_name | test_add_template_test_with_name | 519 | 528 | 519 | 519 | 879125a4b5f01cee50e9c45d9632584c3c5af934 | bigcode/the-stack | train |
8894ac76b380dc13618d1a17 | train | function | def test_add_template_test():
bp = flask.Blueprint('bp', __name__)
def is_boolean(value):
return isinstance(value, bool)
bp.add_app_template_test(is_boolean)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'is_boolean' in app.jinja_env.tests.keys()
ass... | def test_add_template_test():
| bp = flask.Blueprint('bp', __name__)
def is_boolean(value):
return isinstance(value, bool)
bp.add_app_template_test(is_boolean)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'is_boolean' in app.jinja_env.tests.keys()
assert app.jinja_env.tests['is_bo... | (__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'is_boolean' in app.jinja_env.tests.keys()
assert app.jinja_env.tests['is_boolean'] == is_boolean
assert app.jinja_env.tests['is_boolean'](False)
def test_add_template_test():
| 64 | 64 | 104 | 6 | 58 | spappier/flask | tests/test_blueprints.py | Python | test_add_template_test | test_add_template_test | 497 | 506 | 497 | 497 | 0640cd5e1a7c29ff4d46314220b37975680b5766 | bigcode/the-stack | train |
c9ed04a1f58972b621fea61e | train | function | def test_route_decorator_custom_endpoint():
bp = flask.Blueprint('bp', __name__)
@bp.route('/foo')
def foo():
return flask.request.endpoint
@bp.route('/bar', endpoint='bar')
def foo_bar():
return flask.request.endpoint
@bp.route('/bar/123', endpoint='123')
def foo_bar_foo... | def test_route_decorator_custom_endpoint():
| bp = flask.Blueprint('bp', __name__)
@bp.route('/foo')
def foo():
return flask.request.endpoint
@bp.route('/bar', endpoint='bar')
def foo_bar():
return flask.request.endpoint
@bp.route('/bar/123', endpoint='123')
def foo_bar_foo():
return flask.request.endpoint
... | def something(page):
return str(page)
app = flask.Flask(__name__)
app.register_blueprint(bp)
c = app.test_client()
assert c.get('/').data == b'1'
assert c.get('/page/2').data == b'2'
def test_route_decorator_custom_endpoint():
| 67 | 67 | 226 | 8 | 59 | spappier/flask | tests/test_blueprints.py | Python | test_route_decorator_custom_endpoint | test_route_decorator_custom_endpoint | 272 | 304 | 272 | 273 | 871c89cb4326b9438d4c68e05957e083f8a50012 | bigcode/the-stack | train |
517cb0d311f68db8efd7c5dd | train | function | def test_template_test():
bp = flask.Blueprint('bp', __name__)
@bp.app_template_test()
def is_boolean(value):
return isinstance(value, bool)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'is_boolean' in app.jinja_env.tests.keys()
assert app.jinja_env... | def test_template_test():
| bp = flask.Blueprint('bp', __name__)
@bp.app_template_test()
def is_boolean(value):
return isinstance(value, bool)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'is_boolean' in app.jinja_env.tests.keys()
assert app.jinja_env.tests['is_boolean'] == is... | .Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('template_filter.html', value='abcd')
rv = app.test_client().get('/')
assert rv.data == b'dcba'
def test_template_test():
| 64 | 64 | 101 | 5 | 59 | spappier/flask | tests/test_blueprints.py | Python | test_template_test | test_template_test | 486 | 495 | 486 | 486 | 05237f8ca473b1809e9e80aacb9d93aabcf1c461 | bigcode/the-stack | train |
48efe1efe4dea911581293d0 | train | function | def test_template_filter():
bp = flask.Blueprint('bp', __name__)
@bp.app_template_filter()
def my_reverse(s):
return s[::-1]
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'my_reverse' in app.jinja_env.filters.keys()
assert app.jinja_env.filters['my_r... | def test_template_filter():
| bp = flask.Blueprint('bp', __name__)
@bp.app_template_filter()
def my_reverse(s):
return s[::-1]
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'my_reverse' in app.jinja_env.filters.keys()
assert app.jinja_env.filters['my_reverse'] == my_reverse
a... | def foobar():
return flask.request.endpoint
app.register_blueprint(bp, url_prefix='/bp_prefix')
c = app.test_client()
assert c.get('/foo').data == b'bar'
assert c.get('/bp_prefix/bar').status_code == 404
def test_template_filter():
| 64 | 64 | 105 | 5 | 58 | spappier/flask | tests/test_blueprints.py | Python | test_template_filter | test_template_filter | 377 | 386 | 377 | 377 | 1189f91d30b99f68636734c9ddb4a124bafc5e34 | bigcode/the-stack | train |
ec933caffe92e5dd4201b936 | train | function | def test_blueprint_specific_error_handling():
frontend = flask.Blueprint('frontend', __name__)
backend = flask.Blueprint('backend', __name__)
sideend = flask.Blueprint('sideend', __name__)
@frontend.errorhandler(403)
def frontend_forbidden(e):
return 'frontend says no', 403
@frontend.r... | def test_blueprint_specific_error_handling():
| frontend = flask.Blueprint('frontend', __name__)
backend = flask.Blueprint('backend', __name__)
sideend = flask.Blueprint('sideend', __name__)
@frontend.errorhandler(403)
def frontend_forbidden(e):
return 'frontend says no', 403
@frontend.route('/frontend-no')
def frontend_no():
... | ~~~~~~~
Blueprints (and currently modules)
:copyright: (c) 2015 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import pytest
import flask
from flask._compat import text_type
from werkzeug.http import parse_cache_control_header
from jinja2 import TemplateNotFound
def test_blueprint_... | 82 | 82 | 276 | 9 | 72 | spappier/flask | tests/test_blueprints.py | Python | test_blueprint_specific_error_handling | test_blueprint_specific_error_handling | 21 | 59 | 21 | 21 | 01816887f317a7970b550cab8416fd459e526083 | bigcode/the-stack | train |
431cedc5de50ed566103bc5f | train | function | def test_add_template_filter_with_name_and_template():
bp = flask.Blueprint('bp', __name__)
def my_reverse(s):
return s[::-1]
bp.add_app_template_filter(my_reverse, 'super_reverse')
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
... | def test_add_template_filter_with_name_and_template():
| bp = flask.Blueprint('bp', __name__)
def my_reverse(s):
return s[::-1]
bp.add_app_template_filter(my_reverse, 'super_reverse')
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('template_filter.h... | app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('template_filter.html', value='abcd')
rv = app.test_client().get('/')
assert rv.data == b'dcba'
def test_add_template_filter_with_name_and_template():
| 64 | 64 | 110 | 10 | 54 | spappier/flask | tests/test_blueprints.py | Python | test_add_template_filter_with_name_and_template | test_add_template_filter_with_name_and_template | 473 | 484 | 473 | 473 | c7ef23a14f90c18fcc618bad182e3e672353658a | bigcode/the-stack | train |
af0287fbc82f7194f63a6497 | train | function | def test_add_template_test_with_name_and_template():
bp = flask.Blueprint('bp', __name__)
def is_boolean(value):
return isinstance(value, bool)
bp.add_app_template_test(is_boolean, 'boolean')
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def... | def test_add_template_test_with_name_and_template():
| bp = flask.Blueprint('bp', __name__)
def is_boolean(value):
return isinstance(value, bool)
bp.add_app_template_test(is_boolean, 'boolean')
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('templ... | __)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('template_test.html', value=False)
rv = app.test_client().get('/')
assert b'Success!' in rv.data
def test_add_template_test_with_name_and_template():
| 64 | 64 | 109 | 10 | 53 | spappier/flask | tests/test_blueprints.py | Python | test_add_template_test_with_name_and_template | test_add_template_test_with_name_and_template | 582 | 593 | 582 | 582 | 661545b6f8065d0b40932302615dbe9a064ba2e3 | bigcode/the-stack | train |
bff24134a3cafad27bd8061a | train | function | def test_dotted_names():
frontend = flask.Blueprint('myapp.frontend', __name__)
backend = flask.Blueprint('myapp.backend', __name__)
@frontend.route('/fe')
def frontend_index():
return flask.url_for('myapp.backend.backend_index')
@frontend.route('/fe2')
def frontend_page2():
re... | def test_dotted_names():
| frontend = flask.Blueprint('myapp.frontend', __name__)
backend = flask.Blueprint('myapp.backend', __name__)
@frontend.route('/fe')
def frontend_index():
return flask.url_for('myapp.backend.backend_index')
@frontend.route('/fe2')
def frontend_page2():
return flask.url_for('.fron... | finally:
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default
def test_templates_list(test_apps):
from blueprintapp import app
templates = sorted(app.jinja_env.list_templates())
assert templates == ['admin/index.html', 'frontend/index.html']
def test_dotted_names():
| 64 | 64 | 186 | 6 | 58 | spappier/flask | tests/test_blueprints.py | Python | test_dotted_names | test_dotted_names | 213 | 236 | 213 | 213 | a1738e8018b9f612ad5a1136c2c2221a9ffcfe86 | bigcode/the-stack | train |
8ff3f59ea43cb7f4add1aa83 | train | function | def test_template_test_with_name_and_template():
bp = flask.Blueprint('bp', __name__)
@bp.app_template_test('boolean')
def is_boolean(value):
return isinstance(value, bool)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
r... | def test_template_test_with_name_and_template():
| bp = flask.Blueprint('bp', __name__)
@bp.app_template_test('boolean')
def is_boolean(value):
return isinstance(value, bool)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('template_test.html',... | name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('template_test.html', value=False)
rv = app.test_client().get('/')
assert b'Success!' in rv.data
def test_template_test_with_name_and_template():
| 64 | 64 | 105 | 9 | 54 | spappier/flask | tests/test_blueprints.py | Python | test_template_test_with_name_and_template | test_template_test_with_name_and_template | 569 | 580 | 569 | 569 | 2cd920eef9254e1230bb42855ce701b71bb251f5 | bigcode/the-stack | train |
08dfcb1d90783af900c591b9 | train | function | def test_endpoint_decorator():
from werkzeug.routing import Rule
app = flask.Flask(__name__)
app.url_map.add(Rule('/foo', endpoint='bar'))
bp = flask.Blueprint('bp', __name__)
@bp.endpoint('bar')
def foobar():
return flask.request.endpoint
app.register_blueprint(bp, url_prefix='/b... | def test_endpoint_decorator():
| from werkzeug.routing import Rule
app = flask.Flask(__name__)
app.url_map.add(Rule('/foo', endpoint='bar'))
bp = flask.Blueprint('bp', __name__)
@bp.endpoint('bar')
def foobar():
return flask.request.endpoint
app.register_blueprint(bp, url_prefix='/bp_prefix')
c = app.test_cl... | /foo').data == b'bp.foo'
# The rule's didn't actually made it through
rv = c.get('/py/bar')
assert rv.status_code == 404
rv = c.get('/py/bar/123')
assert rv.status_code == 404
def test_endpoint_decorator():
| 64 | 64 | 115 | 6 | 57 | spappier/flask | tests/test_blueprints.py | Python | test_endpoint_decorator | test_endpoint_decorator | 359 | 374 | 359 | 359 | 4ef9e3e43663ea4020f626e4b9f9d848449b66dd | bigcode/the-stack | train |
07fd3b9e0292ab0c9742a7ce | train | function | def test_template_filter_with_name():
bp = flask.Blueprint('bp', __name__)
@bp.app_template_filter('strrev')
def my_reverse(s):
return s[::-1]
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'strrev' in app.jinja_env.filters.keys()
assert app.jinja_env... | def test_template_filter_with_name():
| bp = flask.Blueprint('bp', __name__)
@bp.app_template_filter('strrev')
def my_reverse(s):
return s[::-1]
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'strrev' in app.jinja_env.filters.keys()
assert app.jinja_env.filters['strrev'] == my_reverse
a... | _blueprint(bp, url_prefix='/py')
assert 'my_reverse' in app.jinja_env.filters.keys()
assert app.jinja_env.filters['my_reverse'] == my_reverse
assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'
def test_template_filter_with_name():
| 64 | 64 | 110 | 7 | 57 | spappier/flask | tests/test_blueprints.py | Python | test_template_filter_with_name | test_template_filter_with_name | 399 | 408 | 399 | 399 | ced6f1909374bec8af51639526254f73f03ac649 | bigcode/the-stack | train |
df15bbc9b558ece67afe7e6a | train | function | def test_default_static_cache_timeout():
app = flask.Flask(__name__)
class MyBlueprint(flask.Blueprint):
def get_send_file_max_age(self, filename):
return 100
blueprint = MyBlueprint('blueprint', __name__, static_folder='static')
app.register_blueprint(blueprint)
# try/finally,... | def test_default_static_cache_timeout():
| app = flask.Flask(__name__)
class MyBlueprint(flask.Blueprint):
def get_send_file_max_age(self, filename):
return 100
blueprint = MyBlueprint('blueprint', __name__, static_folder='static')
app.register_blueprint(blueprint)
# try/finally, in case other tests use this app for Blu... | pytest.raises(TemplateNotFound) as e:
flask.render_template('missing.html')
assert e.value.name == 'missing.html'
with flask.Flask(__name__).test_request_context():
assert flask.render_template('nested/nested.txt') == 'I\'m nested'
def test_default_static_cache_timeout():
| 65 | 65 | 217 | 7 | 58 | spappier/flask | tests/test_blueprints.py | Python | test_default_static_cache_timeout | test_default_static_cache_timeout | 184 | 206 | 184 | 184 | 38f7dd559284dc34c088c1358f2c282aebcb8ddd | bigcode/the-stack | train |
5395333fe2fbe105babe352f | train | function | def test_blueprint_url_definitions():
bp = flask.Blueprint('test', __name__)
@bp.route('/foo', defaults={'baz': 42})
def foo(bar, baz):
return '%s/%d' % (bar, baz)
@bp.route('/bar')
def bar(bar):
return text_type(bar)
app = flask.Flask(__name__)
app.register_blueprint(bp, ... | def test_blueprint_url_definitions():
| bp = flask.Blueprint('test', __name__)
@bp.route('/foo', defaults={'baz': 42})
def foo(bar, baz):
return '%s/%d' % (bar, baz)
@bp.route('/bar')
def bar(bar):
return text_type(bar)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': ... | raise MyFunctionException()
app = flask.Flask(__name__)
app.register_blueprint(blue)
c = app.test_client()
assert c.get('/decorator').data == b'boom'
assert c.get('/function').data == b'bam'
def test_blueprint_url_definitions():
| 64 | 64 | 188 | 8 | 56 | spappier/flask | tests/test_blueprints.py | Python | test_blueprint_url_definitions | test_blueprint_url_definitions | 94 | 113 | 94 | 94 | 623aad99bf2fde41d15f20a630b24553c73e2659 | bigcode/the-stack | train |
828eedd17fd1bb9faef04a05 | train | function | def test_template_filter_with_name_and_template():
bp = flask.Blueprint('bp', __name__)
@bp.app_template_filter('super_reverse')
def my_reverse(s):
return s[::-1]
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flas... | def test_template_filter_with_name_and_template():
| bp = flask.Blueprint('bp', __name__)
@bp.app_template_filter('super_reverse')
def my_reverse(s):
return s[::-1]
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('template_filter.html', value='ab... | __)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('template_filter.html', value='abcd')
rv = app.test_client().get('/')
assert rv.data == b'dcba'
def test_template_filter_with_name_and_template():
| 64 | 64 | 106 | 9 | 55 | spappier/flask | tests/test_blueprints.py | Python | test_template_filter_with_name_and_template | test_template_filter_with_name_and_template | 460 | 471 | 460 | 460 | 79e0a0e9261dcafdd8f5009b45fab80fd975e63b | bigcode/the-stack | train |
393fc027e6d2f6b55e997b7a | train | function | def test_template_test_after_route_with_template():
app = flask.Flask(__name__)
@app.route('/')
def index():
return flask.render_template('template_test.html', value=False)
bp = flask.Blueprint('bp', __name__)
@bp.app_template_test()
def boolean(value):
return isinstance(value, b... | def test_template_test_after_route_with_template():
| app = flask.Flask(__name__)
@app.route('/')
def index():
return flask.render_template('template_test.html', value=False)
bp = flask.Blueprint('bp', __name__)
@bp.app_template_test()
def boolean(value):
return isinstance(value, bool)
app.register_blueprint(bp, url_prefix='/py'... | name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('template_test.html', value=False)
rv = app.test_client().get('/')
assert b'Success!' in rv.data
def test_template_test_after_route_with_template():
| 64 | 64 | 102 | 9 | 54 | spappier/flask | tests/test_blueprints.py | Python | test_template_test_after_route_with_template | test_template_test_after_route_with_template | 543 | 554 | 543 | 543 | 6b5ade793197a3783ef7c4532d811aa29b132401 | bigcode/the-stack | train |
48fa7f1e31e38ee2b89e9c9b | train | function | def test_template_test_with_name():
bp = flask.Blueprint('bp', __name__)
@bp.app_template_test('boolean')
def is_boolean(value):
return isinstance(value, bool)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'boolean' in app.jinja_env.tests.keys()
asse... | def test_template_test_with_name():
| bp = flask.Blueprint('bp', __name__)
@bp.app_template_test('boolean')
def is_boolean(value):
return isinstance(value, bool)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'boolean' in app.jinja_env.tests.keys()
assert app.jinja_env.tests['boolean'] ==... | name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'is_boolean' in app.jinja_env.tests.keys()
assert app.jinja_env.tests['is_boolean'] == is_boolean
assert app.jinja_env.tests['is_boolean'](False)
def test_template_test_with_name():
| 64 | 64 | 102 | 7 | 57 | spappier/flask | tests/test_blueprints.py | Python | test_template_test_with_name | test_template_test_with_name | 508 | 517 | 508 | 508 | 1cd9318c664f6a6808ce719cc15d5abd19ecf947 | bigcode/the-stack | train |
34dd0c6910cf6f6f4032fdb6 | train | function | def test_add_template_test_with_template():
bp = flask.Blueprint('bp', __name__)
def boolean(value):
return isinstance(value, bool)
bp.add_app_template_test(boolean)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return f... | def test_add_template_test_with_template():
| bp = flask.Blueprint('bp', __name__)
def boolean(value):
return isinstance(value, bool)
bp.add_app_template_test(boolean)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('template_test.html', v... | ('bp', __name__)
@bp.app_template_test()
def boolean(value):
return isinstance(value, bool)
app.register_blueprint(bp, url_prefix='/py')
rv = app.test_client().get('/')
assert b'Success!' in rv.data
def test_add_template_test_with_template():
| 64 | 64 | 102 | 8 | 55 | spappier/flask | tests/test_blueprints.py | Python | test_add_template_test_with_template | test_add_template_test_with_template | 556 | 567 | 556 | 556 | 5f45a2f1eb2612cd6583c1b72c223c852e669103 | bigcode/the-stack | train |
55c6c3dceef319c06d94d29b | train | function | def test_add_template_filter_with_template():
bp = flask.Blueprint('bp', __name__)
def super_reverse(s):
return s[::-1]
bp.add_app_template_filter(super_reverse)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask... | def test_add_template_filter_with_template():
| bp = flask.Blueprint('bp', __name__)
def super_reverse(s):
return s[::-1]
bp.add_app_template_filter(super_reverse)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('template_filter.html', value... | ('bp', __name__)
@bp.app_template_filter()
def super_reverse(s):
return s[::-1]
app.register_blueprint(bp, url_prefix='/py')
rv = app.test_client().get('/')
assert rv.data == b'dcba'
def test_add_template_filter_with_template():
| 64 | 64 | 104 | 8 | 56 | spappier/flask | tests/test_blueprints.py | Python | test_add_template_filter_with_template | test_add_template_filter_with_template | 447 | 458 | 447 | 447 | cc4f8cb5637465f47b1922e59be3d1e4195dcff7 | bigcode/the-stack | train |
2c85cc34335441e52b6a9cff | train | function | def test_blueprint_url_processors():
bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')
@bp.url_defaults
def add_language_code(endpoint, values):
values.setdefault('lang_code', flask.g.lang_code)
@bp.url_value_preprocessor
def pull_lang_code(endpoint, values):
fl... | def test_blueprint_url_processors():
| bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')
@bp.url_defaults
def add_language_code(endpoint, values):
values.setdefault('lang_code', flask.g.lang_code)
@bp.url_value_preprocessor
def pull_lang_code(endpoint, values):
flask.g.lang_code = values.pop('lang_co... | .get('/1/foo').data == b'23/42'
assert c.get('/2/foo').data == b'19/42'
assert c.get('/1/bar').data == b'23'
assert c.get('/2/bar').data == b'19'
def test_blueprint_url_processors():
| 64 | 64 | 171 | 7 | 57 | spappier/flask | tests/test_blueprints.py | Python | test_blueprint_url_processors | test_blueprint_url_processors | 115 | 140 | 115 | 115 | 5c68a92ff757b04abd7c3f6dffbf59c29e053755 | bigcode/the-stack | train |
a514ff5a58191e4174e4d006 | train | function | def test_blueprint_specific_user_error_handling():
class MyDecoratorException(Exception):
pass
class MyFunctionException(Exception):
pass
blue = flask.Blueprint('blue', __name__)
@blue.errorhandler(MyDecoratorException)
def my_decorator_exception_handler(e):
assert isinstan... | def test_blueprint_specific_user_error_handling():
| class MyDecoratorException(Exception):
pass
class MyFunctionException(Exception):
pass
blue = flask.Blueprint('blue', __name__)
@blue.errorhandler(MyDecoratorException)
def my_decorator_exception_handler(e):
assert isinstance(e, MyDecoratorException)
return 'boom'
... | .test_client()
assert c.get('/frontend-no').data == b'frontend says no'
assert c.get('/backend-no').data == b'backend says no'
assert c.get('/what-is-a-sideend').data == b'application itself says no'
def test_blueprint_specific_user_error_handling():
| 64 | 64 | 201 | 10 | 54 | spappier/flask | tests/test_blueprints.py | Python | test_blueprint_specific_user_error_handling | test_blueprint_specific_user_error_handling | 61 | 92 | 61 | 61 | 872654cdeffc059b5f4c427a30f2543b981c81a3 | bigcode/the-stack | train |
daaf60460e1f14a068367722 | train | function | def test_empty_url_defaults():
bp = flask.Blueprint('bp', __name__)
@bp.route('/', defaults={'page': 1})
@bp.route('/page/<int:page>')
def something(page):
return str(page)
app = flask.Flask(__name__)
app.register_blueprint(bp)
c = app.test_client()
assert c.get('/').data == b... | def test_empty_url_defaults():
| bp = flask.Blueprint('bp', __name__)
@bp.route('/', defaults={'page': 1})
@bp.route('/page/<int:page>')
def something(page):
return str(page)
app = flask.Flask(__name__)
app.register_blueprint(bp)
c = app.test_client()
assert c.get('/').data == b'1'
assert c.get('/page/2')... | .url_for('test.index')
@test.route('/test/')
def index():
return flask.url_for('app_index')
app.register_blueprint(test)
with app.test_client() as c:
rv = c.get('/')
assert rv.data == b'/test/'
def test_empty_url_defaults():
| 63 | 64 | 101 | 6 | 57 | spappier/flask | tests/test_blueprints.py | Python | test_empty_url_defaults | test_empty_url_defaults | 257 | 270 | 257 | 257 | 4f4e6cfd12403872758af343f187674efcd74730 | bigcode/the-stack | train |
dac6be67a4073ff2a22ec9ad | train | function | def test_add_template_filter():
bp = flask.Blueprint('bp', __name__)
def my_reverse(s):
return s[::-1]
bp.add_app_template_filter(my_reverse)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'my_reverse' in app.jinja_env.filters.keys()
assert app.jinja_... | def test_add_template_filter():
| bp = flask.Blueprint('bp', __name__)
def my_reverse(s):
return s[::-1]
bp.add_app_template_filter(my_reverse)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'my_reverse' in app.jinja_env.filters.keys()
assert app.jinja_env.filters['my_reverse'] == my_... | .register_blueprint(bp, url_prefix='/py')
assert 'my_reverse' in app.jinja_env.filters.keys()
assert app.jinja_env.filters['my_reverse'] == my_reverse
assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'
def test_add_template_filter():
| 64 | 64 | 108 | 6 | 58 | spappier/flask | tests/test_blueprints.py | Python | test_add_template_filter | test_add_template_filter | 388 | 397 | 388 | 388 | 1f029ba29b43b00ad158e0a1d60a8b6129374518 | bigcode/the-stack | train |
9f0639e9dd11e4977be707cc | train | function | def test_route_decorator_custom_endpoint_with_dots():
bp = flask.Blueprint('bp', __name__)
@bp.route('/foo')
def foo():
return flask.request.endpoint
try:
@bp.route('/bar', endpoint='bar.bar')
def foo_bar():
return flask.request.endpoint
except AssertionError:
... | def test_route_decorator_custom_endpoint_with_dots():
| bp = flask.Blueprint('bp', __name__)
@bp.route('/foo')
def foo():
return flask.request.endpoint
try:
@bp.route('/bar', endpoint='bar.bar')
def foo_bar():
return flask.request.endpoint
except AssertionError:
pass
else:
raise AssertionError('ex... | = app.test_client()
assert c.get('/').data == b'index'
assert c.get('/py/foo').data == b'bp.foo'
assert c.get('/py/bar').data == b'bp.bar'
assert c.get('/py/bar/123').data == b'bp.123'
assert c.get('/py/bar/foo').data == b'bp.bar_foo'
def test_route_decorator_custom_endpoint_with_dots():
| 94 | 94 | 314 | 11 | 83 | spappier/flask | tests/test_blueprints.py | Python | test_route_decorator_custom_endpoint_with_dots | test_route_decorator_custom_endpoint_with_dots | 306 | 356 | 306 | 306 | 7c25edcdfc7a7e8524dc24d5d3a6fd5f4a66092f | bigcode/the-stack | train |
be0acbf3a99ab6575e09016a | train | function | def test_templates_list(test_apps):
from blueprintapp import app
templates = sorted(app.jinja_env.list_templates())
assert templates == ['admin/index.html', 'frontend/index.html']
| def test_templates_list(test_apps):
| from blueprintapp import app
templates = sorted(app.jinja_env.list_templates())
assert templates == ['admin/index.html', 'frontend/index.html']
|
rv = blueprint.send_static_file('index.html')
cc = parse_cache_control_header(rv.headers['Cache-Control'])
assert cc.max_age == 100
rv.close()
finally:
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default
def test_templates_list(test_apps):
| 64 | 64 | 39 | 7 | 56 | spappier/flask | tests/test_blueprints.py | Python | test_templates_list | test_templates_list | 208 | 211 | 208 | 208 | 0bd4d78b2d96f6f728a359f39959675db1b42da8 | bigcode/the-stack | train |
e1bdccd32f7439fb511265a9 | train | function | def test_add_template_filter_with_name():
bp = flask.Blueprint('bp', __name__)
def my_reverse(s):
return s[::-1]
bp.add_app_template_filter(my_reverse, 'strrev')
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'strrev' in app.jinja_env.filters.keys()
a... | def test_add_template_filter_with_name():
| bp = flask.Blueprint('bp', __name__)
def my_reverse(s):
return s[::-1]
bp.add_app_template_filter(my_reverse, 'strrev')
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'strrev' in app.jinja_env.filters.keys()
assert app.jinja_env.filters['strrev'] == m... | print(bp, url_prefix='/py')
assert 'strrev' in app.jinja_env.filters.keys()
assert app.jinja_env.filters['strrev'] == my_reverse
assert app.jinja_env.filters['strrev']('abcd') == 'dcba'
def test_add_template_filter_with_name():
| 64 | 64 | 114 | 8 | 56 | spappier/flask | tests/test_blueprints.py | Python | test_add_template_filter_with_name | test_add_template_filter_with_name | 410 | 419 | 410 | 410 | 414735103a52093afdff3ef04b3568166522bde0 | bigcode/the-stack | train |
0aab1088311613e78a8319f9 | train | function | def test_template_test_with_template():
bp = flask.Blueprint('bp', __name__)
@bp.app_template_test()
def boolean(value):
return isinstance(value, bool)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_te... | def test_template_test_with_template():
| bp = flask.Blueprint('bp', __name__)
@bp.app_template_test()
def boolean(value):
return isinstance(value, bool)
app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
@app.route('/')
def index():
return flask.render_template('template_test.html', value=False... | .Flask(__name__)
app.register_blueprint(bp, url_prefix='/py')
assert 'boolean' in app.jinja_env.tests.keys()
assert app.jinja_env.tests['boolean'] == is_boolean
assert app.jinja_env.tests['boolean'](False)
def test_template_test_with_template():
| 64 | 64 | 100 | 7 | 57 | spappier/flask | tests/test_blueprints.py | Python | test_template_test_with_template | test_template_test_with_template | 530 | 541 | 530 | 530 | 8d9bb0812d0f7dd9ae13fdc91d71925a5b442e1e | bigcode/the-stack | train |
f48211239602112581bcca69 | train | function | def test_templates_and_static(test_apps):
from blueprintapp import app
c = app.test_client()
rv = c.get('/')
assert rv.data == b'Hello from the Frontend'
rv = c.get('/admin/')
assert rv.data == b'Hello from the Admin'
rv = c.get('/admin/index2')
assert rv.data == b'Hello from the Admin'... | def test_templates_and_static(test_apps):
| from blueprintapp import app
c = app.test_client()
rv = c.get('/')
assert rv.data == b'Hello from the Frontend'
rv = c.get('/admin/')
assert rv.data == b'Hello from the Admin'
rv = c.get('/admin/index2')
assert rv.data == b'Hello from the Admin'
rv = c.get('/admin/static/test.txt')
... | _code(endpoint, values):
flask.g.lang_code = values.pop('lang_code')
@bp.route('/')
def index():
return flask.url_for('.about')
@bp.route('/about')
def about():
return flask.url_for('.index')
app = flask.Flask(__name__)
app.register_blueprint(bp)
c = app.test_clie... | 113 | 114 | 380 | 8 | 105 | spappier/flask | tests/test_blueprints.py | Python | test_templates_and_static | test_templates_and_static | 142 | 182 | 142 | 142 | 5663891dfda427dec0f848ead9e63cbf3312326b | bigcode/the-stack | train |
03779b191e6d6c5659d0dec4 | train | class | class TestLoadResnetModel(unittest.TestCase):
def setUp(self):
if enable_gpu == "ON":
self.target = DefaultNVGPUTarget()
else:
self.target = DefaultHostTarget()
self.model_dir = model_dir
self.x_shape = [1, 3, 224, 224]
self.target_tensor = 'save_infer... | class TestLoadResnetModel(unittest.TestCase):
| def setUp(self):
if enable_gpu == "ON":
self.target = DefaultNVGPUTarget()
else:
self.target = DefaultHostTarget()
self.model_dir = model_dir
self.x_shape = [1, 3, 224, 224]
self.target_tensor = 'save_infer_model/scale_0'
self.input_tensor = 'i... | copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the spec... | 199 | 199 | 664 | 10 | 189 | hp03/CINN | python/tests/test_resnet18.py | Python | TestLoadResnetModel | TestLoadResnetModel | 39 | 106 | 39 | 39 | ce169637a565ac57cdf67788ca1e35467f136df3 | bigcode/the-stack | train |
e71c46cc5aa4f8cea9ec016c | train | function | def list_dir(dir_name, traversed = [], results = []):
dirs = os.listdir(dir_name)
results.append(dir_name)
if dirs:
for f in dirs:
new_dir = dir_name + f + '/'
if os.path.isdir(new_dir) and new_dir not in traversed:
traversed.append(new_dir)
l... | def list_dir(dir_name, traversed = [], results = []):
| dirs = os.listdir(dir_name)
results.append(dir_name)
if dirs:
for f in dirs:
new_dir = dir_name + f + '/'
if os.path.isdir(new_dir) and new_dir not in traversed:
traversed.append(new_dir)
list_dir(new_dir, traversed, results)
else:
... | import os
def list_dir(dir_name, traversed = [], results = []):
| 18 | 64 | 99 | 15 | 2 | Dan767/CMPUT404-assignment-webserver | test.py | Python | list_dir | list_dir | 3 | 14 | 3 | 3 | 87b58339c2d8d9fc4c26695f80f88eed80bfb734 | bigcode/the-stack | train |
c410a7c4464c7bc88fdd633b | train | class | class QueryFailure(Model):
"""Error response.
:param error: Error definition.
:type error: ~azure.mgmt.policyinsights.models.QueryFailureError
"""
_attribute_map = {
'error': {'key': 'error', 'type': 'QueryFailureError'},
}
def __init__(self, **kwargs):
super(QueryFailure,... | class QueryFailure(Model):
| """Error response.
:param error: Error definition.
:type error: ~azure.mgmt.policyinsights.models.QueryFailureError
"""
_attribute_map = {
'error': {'key': 'error', 'type': 'QueryFailureError'},
}
def __init__(self, **kwargs):
super(QueryFailure, self).__init__(**kwargs)
... | project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
from msrest.exc... | 64 | 64 | 96 | 5 | 58 | JonathanGailliez/azure-sdk-for-python | azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/query_failure.py | Python | QueryFailure | QueryFailure | 16 | 29 | 16 | 16 | 21b6c53f73be7caf9ad12b3c8d0e4373d3f89955 | bigcode/the-stack | train |
0625ad3568bf323a67e67707 | train | class | class QueryFailureException(HttpOperationError):
"""Server responsed with exception of type: 'QueryFailure'.
:param deserialize: A deserializer
:param response: Server response to be deserialized.
"""
def __init__(self, deserialize, response, *args):
super(QueryFailureException, self).__i... | class QueryFailureException(HttpOperationError):
| """Server responsed with exception of type: 'QueryFailure'.
:param deserialize: A deserializer
:param response: Server response to be deserialized.
"""
def __init__(self, deserialize, response, *args):
super(QueryFailureException, self).__init__(deserialize, response, 'QueryFailure', *arg... | _map = {
'error': {'key': 'error', 'type': 'QueryFailureError'},
}
def __init__(self, **kwargs):
super(QueryFailure, self).__init__(**kwargs)
self.error = kwargs.get('error', None)
class QueryFailureException(HttpOperationError):
| 64 | 64 | 80 | 8 | 56 | JonathanGailliez/azure-sdk-for-python | azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/query_failure.py | Python | QueryFailureException | QueryFailureException | 32 | 41 | 32 | 32 | c82a2af176d9b0ff56bb9b311ee0c37d64e7f311 | bigcode/the-stack | train |
0092a6b570ee88f4b739baad | train | function | @pytest.fixture(autouse=True)
def media_storage(settings, tmpdir):
settings.MEDIA_ROOT = tmpdir.strpath
| @pytest.fixture(autouse=True)
def media_storage(settings, tmpdir):
| settings.MEDIA_ROOT = tmpdir.strpath
| import pytest
from bus_system.users import User
from bus_system.users.tests.factories import UserFactory
@pytest.fixture(autouse=True)
def media_storage(settings, tmpdir):
| 36 | 64 | 25 | 15 | 20 | pygabo/bus_system | bus_system/conftest.py | Python | media_storage | media_storage | 7 | 9 | 7 | 8 | 57985b231dcf247fa2d908d24e4650023040d349 | bigcode/the-stack | train |
9669cd97a5aab32bd5052271 | train | function | @pytest.fixture
def user() -> User:
return UserFactory()
| @pytest.fixture
def user() -> User:
| return UserFactory()
| import pytest
from bus_system.users import User
from bus_system.users.tests.factories import UserFactory
@pytest.fixture(autouse=True)
def media_storage(settings, tmpdir):
settings.MEDIA_ROOT = tmpdir.strpath
@pytest.fixture
def user() -> User:
| 55 | 64 | 14 | 9 | 45 | pygabo/bus_system | bus_system/conftest.py | Python | user | user | 12 | 14 | 12 | 13 | 0b768ce4cb75c79feee8fee925edac82673c1d4e | bigcode/the-stack | train |
d2ec32501a40f0090ca1b7f3 | train | class | class IPCMessageClient(IPCClient):
"""
Salt IPC message client
Create an IPC client to send messages to an IPC server
An example of a very simple IPCMessageClient connecting to an IPCServer. This
example assumes an already running IPCMessage server.
IMPORTANT: The below example also assumes a... | class IPCMessageClient(IPCClient):
| """
Salt IPC message client
Create an IPC client to send messages to an IPC server
An example of a very simple IPCMessageClient connecting to an IPCServer. This
example assumes an already running IPCMessage server.
IMPORTANT: The below example also assumes a running IOLoop process.
# Imp... | , to prevent
leaks.
"""
if self._closing:
return
self._closing = True
log.debug("Closing %s instance", self.__class__.__name__)
if self.stream is not None and not self.stream.closed():
try:
self.stream.close()
except ... | 103 | 103 | 346 | 8 | 94 | me-coder/salt | salt/transport/ipc.py | Python | IPCMessageClient | IPCMessageClient | 380 | 435 | 380 | 380 | 93680afa6a57c2954d0671ca931067e9bbd5708a | bigcode/the-stack | train |
f9e31b95d9280bd5b11e16bb | train | class | class IPCMessageSubscriber(IPCClient):
"""
Salt IPC message subscriber
Create an IPC client to receive messages from IPC publisher
An example of a very simple IPCMessageSubscriber connecting to an IPCMessagePublisher.
This example assumes an already running IPCMessagePublisher.
IMPORTANT: The... | class IPCMessageSubscriber(IPCClient):
| """
Salt IPC message subscriber
Create an IPC client to receive messages from IPC publisher
An example of a very simple IPCMessageSubscriber connecting to an IPCMessagePublisher.
This example assumes an already running IPCMessagePublisher.
IMPORTANT: The below example also assumes the IOLoop ... | s",
(self.opts["ipc_write_buffer"]),
)
with salt.utils.asynchronous.current_ioloop(self.io_loop):
stream = IOStream(connection, **kwargs)
self.streams.add(stream)
def discard_after_closed():
self.streams.discard(str... | 256 | 256 | 1,195 | 8 | 247 | me-coder/salt | salt/transport/ipc.py | Python | IPCMessageSubscriber | IPCMessageSubscriber | 599 | 755 | 599 | 599 | 49d3260582099665d8980a7d25f43422f47f825c | bigcode/the-stack | train |
39ad283303d337605c1bc8a4 | train | class | class FutureWithTimeout(salt.ext.tornado.concurrent.Future):
def __init__(self, io_loop, future, timeout):
super().__init__()
self.io_loop = io_loop
self._future = future
if timeout is not None:
if timeout < 0.1:
timeout = 0.1
self._timeout_han... | class FutureWithTimeout(salt.ext.tornado.concurrent.Future):
| def __init__(self, io_loop, future, timeout):
super().__init__()
self.io_loop = io_loop
self._future = future
if timeout is not None:
if timeout < 0.1:
timeout = 0.1
self._timeout_handle = self.io_loop.add_timeout(
self.io_loop.... |
from salt.ext.tornado.locks import Lock
log = logging.getLogger(__name__)
# 'tornado.concurrent.Future' doesn't support
# remove_done_callback() which we would have called
# in the timeout case. Due to this, we have this
# callback function outside of FutureWithTimeout.
def future_with_timeout_callback(future):
... | 106 | 106 | 355 | 12 | 94 | me-coder/salt | salt/transport/ipc.py | Python | FutureWithTimeout | FutureWithTimeout | 35 | 77 | 35 | 35 | c2979a223ffef0fd7d048b9789cffa7d46077341 | bigcode/the-stack | train |
5709031ca0909c3881af829e | train | class | class IPCServer:
"""
A Tornado IPC server very similar to Tornado's TCPServer class
but using either UNIX domain sockets or TCP sockets
"""
async_methods = [
"handle_stream",
]
close_methods = [
"close",
]
def __init__(self, socket_path, io_loop=None, payload_handle... | class IPCServer:
| """
A Tornado IPC server very similar to Tornado's TCPServer class
but using either UNIX domain sockets or TCP sockets
"""
async_methods = [
"handle_stream",
]
close_methods = [
"close",
]
def __init__(self, socket_path, io_loop=None, payload_handler=None):
... | ._timeout_handle = None
if hasattr(self._future, "_future_with_timeout"):
# Reusing a future that has previously been used.
# Due to this, no need to call add_done_callback()
# because we did that before.
self._future._future_with_timeout = self
if se... | 256 | 256 | 1,184 | 4 | 252 | me-coder/salt | salt/transport/ipc.py | Python | IPCServer | IPCServer | 80 | 234 | 80 | 80 | 6143f8d18d8b878d38845db14bf893e5dd44732b | bigcode/the-stack | train |
c9e8fe89129a93237b963f59 | train | class | class IPCMessageServer(IPCServer):
"""
Salt IPC message server
Creates a message server which can create and bind to a socket on a given
path and then respond to messages asynchronously.
An example of a very simple IPCServer which prints received messages to
a console:
# Import Tornad... | class IPCMessageServer(IPCServer):
| """
Salt IPC message server
Creates a message server which can create and bind to a socket on a given
path and then respond to messages asynchronously.
An example of a very simple IPCServer which prints received messages to
a console:
# Import Tornado libs
import salt.ext.torn... | msg: The message to be sent
:param int timeout: Timeout when sending message (Currently unimplemented)
"""
if not self.connected():
yield self.connect()
pack = salt.transport.frame.frame_msg_ipc(msg, raw_body=True)
yield self.stream.write(pack)
class IPCMessageServer... | 67 | 67 | 225 | 8 | 59 | me-coder/salt | salt/transport/ipc.py | Python | IPCMessageServer | IPCMessageServer | 438 | 469 | 438 | 438 | bdd872ef253938b94e38d94b01737bb2e756d341 | bigcode/the-stack | train |
9c081eec01897ab13a459f68 | train | function | def future_with_timeout_callback(future):
if future._future_with_timeout is not None:
future._future_with_timeout._done_callback(future)
| def future_with_timeout_callback(future):
| if future._future_with_timeout is not None:
future._future_with_timeout._done_callback(future)
| ocks import Lock
log = logging.getLogger(__name__)
# 'tornado.concurrent.Future' doesn't support
# remove_done_callback() which we would have called
# in the timeout case. Due to this, we have this
# callback function outside of FutureWithTimeout.
def future_with_timeout_callback(future):
| 64 | 64 | 31 | 8 | 56 | me-coder/salt | salt/transport/ipc.py | Python | future_with_timeout_callback | future_with_timeout_callback | 30 | 32 | 30 | 30 | 8575dc97ab894c4e2d1e8b700aa86021766b9d60 | bigcode/the-stack | train |
82bf63926fe8ffeaf9920cc7 | train | class | class IPCClient:
"""
A Tornado IPC client very similar to Tornado's TCPClient class
but using either UNIX domain sockets or TCP sockets
This was written because Tornado does not have its own IPC
server/client implementation.
:param IOLoop io_loop: A Tornado ioloop to handle scheduling
:par... | class IPCClient:
| """
A Tornado IPC client very similar to Tornado's TCPClient class
but using either UNIX domain sockets or TCP sockets
This was written because Tornado does not have its own IPC
server/client implementation.
:param IOLoop io_loop: A Tornado ioloop to handle scheduling
:param str/int socket... | pylint: disable=broad-except
log.error("Exception occurred while " "handling stream: %s", exc)
def handle_connection(self, connection, address):
log.trace("IPCServer: Handling connection " "to address: %s", address)
try:
with salt.utils.asynchronous.current_ioloop(self.... | 256 | 256 | 991 | 4 | 251 | me-coder/salt | salt/transport/ipc.py | Python | IPCClient | IPCClient | 239 | 377 | 239 | 239 | d2a012780794153130b06f77b0e6f03133e333e1 | bigcode/the-stack | train |
43ad88512b3fd77dba17a02f | train | class | class IPCMessagePublisher:
"""
A Tornado IPC Publisher similar to Tornado's TCPServer class
but using either UNIX domain sockets or TCP sockets
"""
def __init__(self, opts, socket_path, io_loop=None):
"""
Create a new Tornado IPC server
:param dict opts: Salt options
... | class IPCMessagePublisher:
| """
A Tornado IPC Publisher similar to Tornado's TCPServer class
but using either UNIX domain sockets or TCP sockets
"""
def __init__(self, opts, socket_path, io_loop=None):
"""
Create a new Tornado IPC server
:param dict opts: Salt options
:param str/int socket_path... | .connect()
pack = salt.transport.frame.frame_msg_ipc(msg, raw_body=True)
yield self.stream.write(pack)
class IPCMessageServer(IPCServer):
"""
Salt IPC message server
Creates a message server which can create and bind to a socket on a given
path and then respond to messages asynchronou... | 255 | 256 | 936 | 5 | 250 | me-coder/salt | salt/transport/ipc.py | Python | IPCMessagePublisher | IPCMessagePublisher | 472 | 594 | 472 | 472 | bb1de69ee8fb1007f2d6e328504753b35e2f39fb | bigcode/the-stack | train |
6bebdc2104c87c25036e4470 | train | function | def validate_replicate_to(replicate_to):
if replicate_to not in VALID_REPLICATION_DESTINATION:
raise ValueError("DeploymentStrategy ReplicateTo must be one of: %s" %
', '.join(VALID_REPLICATION_DESTINATION))
return replicate_to
| def validate_replicate_to(replicate_to):
| if replicate_to not in VALID_REPLICATION_DESTINATION:
raise ValueError("DeploymentStrategy ReplicateTo must be one of: %s" %
', '.join(VALID_REPLICATION_DESTINATION))
return replicate_to
| validate_growth_type(growth_type):
if growth_type not in VALID_GROWTH_TYPE:
raise ValueError("DeploymentStrategy GrowthType must be one of: %s" %
', '.join(VALID_GROWTH_TYPE))
return growth_type
def validate_replicate_to(replicate_to):
| 64 | 64 | 58 | 11 | 52 | ayfallen/urler | venv/lib/python3.8/site-packages/troposphere/appconfig.py | Python | validate_replicate_to | validate_replicate_to | 24 | 28 | 24 | 24 | 918f86337b3a669872755404077bc470208ba3fa | bigcode/the-stack | train |
7e05eec6a7a425436cbcce42 | train | class | class DeploymentStrategy(AWSObject):
resource_type = "AWS::AppConfig::DeploymentStrategy"
props = {
'DeploymentDurationInMinutes': (double, True),
'Description': (str, False),
'FinalBakeTimeInMinutes': (double, False),
'GrowthFactor': (double, True),
'GrowthType': (valid... | class DeploymentStrategy(AWSObject):
| resource_type = "AWS::AppConfig::DeploymentStrategy"
props = {
'DeploymentDurationInMinutes': (double, True),
'Description': (str, False),
'FinalBakeTimeInMinutes': (double, False),
'GrowthFactor': (double, True),
'GrowthType': (validate_growth_type, False),
'Nam... | def validate_validator_type(validator_type):
if validator_type not in VALID_VALIDATOR_TYPE:
raise ValueError("ConfigurationProfile Validator Type must be one of: %s" % # NOQA
', '.join(VALID_VALIDATOR_TYPE))
return validator_type
class DeploymentStrategy(AWSObject):
| 64 | 64 | 115 | 7 | 56 | ayfallen/urler | venv/lib/python3.8/site-packages/troposphere/appconfig.py | Python | DeploymentStrategy | DeploymentStrategy | 38 | 50 | 38 | 38 | fe1eba4624ab6b6e6bc1ec5e4bb071724ea4ebba | bigcode/the-stack | train |
b3daba241f4a38659dee02fd | train | class | class Environment(AWSObject):
resource_type = "AWS::AppConfig::Environment"
props = {
'ApplicationId': (str, True),
'Description': (str, False),
'Monitors': ([Monitors], False),
'Name': (str, True),
'Tags': (Tags, False),
}
| class Environment(AWSObject):
| resource_type = "AWS::AppConfig::Environment"
props = {
'ApplicationId': (str, True),
'Description': (str, False),
'Monitors': ([Monitors], False),
'Name': (str, True),
'Tags': (Tags, False),
}
| ReplicateTo': (validate_replicate_to, True),
'Tags': (Tags, False),
}
class Monitors(AWSProperty):
props = {
'AlarmArn': (str, False),
'AlarmRoleArn': (str, False),
}
class Environment(AWSObject):
| 64 | 64 | 72 | 6 | 58 | ayfallen/urler | venv/lib/python3.8/site-packages/troposphere/appconfig.py | Python | Environment | Environment | 60 | 69 | 60 | 60 | eadd6060c1904ff5b566fd4a902b1349dcf77f1c | bigcode/the-stack | train |
c96635d16e11a1b6fe0718f5 | train | class | class Application(AWSObject):
resource_type = "AWS::AppConfig::Application"
props = {
'Description': (str, False),
'Name': (str, True),
'Tags': (Tags, False),
}
| class Application(AWSObject):
| resource_type = "AWS::AppConfig::Application"
props = {
'Description': (str, False),
'Name': (str, True),
'Tags': (Tags, False),
}
| Description': (str, False),
'LocationUri': (str, True),
'Name': (str, True),
'RetrievalRoleArn': (str, False),
'Tags': (Tags, False),
'Validators': ([Validators], False)
}
class Application(AWSObject):
| 64 | 64 | 51 | 6 | 58 | ayfallen/urler | venv/lib/python3.8/site-packages/troposphere/appconfig.py | Python | Application | Application | 107 | 114 | 107 | 107 | 085fc4267515478acb614ab11c43b0cf37123de7 | bigcode/the-stack | train |
12f99040333bae6c4a921fbd | train | function | def validate_validator_type(validator_type):
if validator_type not in VALID_VALIDATOR_TYPE:
raise ValueError("ConfigurationProfile Validator Type must be one of: %s" % # NOQA
', '.join(VALID_VALIDATOR_TYPE))
return validator_type
| def validate_validator_type(validator_type):
| if validator_type not in VALID_VALIDATOR_TYPE:
raise ValueError("ConfigurationProfile Validator Type must be one of: %s" % # NOQA
', '.join(VALID_VALIDATOR_TYPE))
return validator_type
| _replicate_to(replicate_to):
if replicate_to not in VALID_REPLICATION_DESTINATION:
raise ValueError("DeploymentStrategy ReplicateTo must be one of: %s" %
', '.join(VALID_REPLICATION_DESTINATION))
return replicate_to
def validate_validator_type(validator_type):
| 64 | 64 | 57 | 8 | 55 | ayfallen/urler | venv/lib/python3.8/site-packages/troposphere/appconfig.py | Python | validate_validator_type | validate_validator_type | 31 | 35 | 31 | 31 | 17567c4a78600c718d40a2230f79bbeed47e8eaa | bigcode/the-stack | train |
288b8a907fdbc9f76e699419 | train | class | class Deployment(AWSObject):
resource_type = "AWS::AppConfig::Deployment"
props = {
'ApplicationId': (str, True),
'ConfigurationProfileId': (str, True),
'ConfigurationVersion': (str, True),
'DeploymentStrategyId': (str, True),
'Description': (str, False),
'Enviro... | class Deployment(AWSObject):
| resource_type = "AWS::AppConfig::Deployment"
props = {
'ApplicationId': (str, True),
'ConfigurationProfileId': (str, True),
'ConfigurationVersion': (str, True),
'DeploymentStrategyId': (str, True),
'Description': (str, False),
'EnvironmentId': (str, True),
... | Config::Environment"
props = {
'ApplicationId': (str, True),
'Description': (str, False),
'Monitors': ([Monitors], False),
'Name': (str, True),
'Tags': (Tags, False),
}
class Deployment(AWSObject):
| 64 | 64 | 94 | 6 | 58 | ayfallen/urler | venv/lib/python3.8/site-packages/troposphere/appconfig.py | Python | Deployment | Deployment | 72 | 83 | 72 | 72 | 3e0d215ba21f6940a6102fb9c815f6a2ed8b25c8 | bigcode/the-stack | train |
4e22e5b662c203f3b788b57a | train | function | def validate_growth_type(growth_type):
if growth_type not in VALID_GROWTH_TYPE:
raise ValueError("DeploymentStrategy GrowthType must be one of: %s" %
', '.join(VALID_GROWTH_TYPE))
return growth_type
| def validate_growth_type(growth_type):
| if growth_type not in VALID_GROWTH_TYPE:
raise ValueError("DeploymentStrategy GrowthType must be one of: %s" %
', '.join(VALID_GROWTH_TYPE))
return growth_type
| import AWSObject, AWSProperty, Tags
from .validators import (
double
)
VALID_GROWTH_TYPE = ('LINEAR')
VALID_REPLICATION_DESTINATION = ('NONE', 'SSM_DOCUMENT')
VALID_VALIDATOR_TYPE = ('JSON_SCHEMA', 'LAMBDA')
def validate_growth_type(growth_type):
| 64 | 64 | 54 | 8 | 56 | ayfallen/urler | venv/lib/python3.8/site-packages/troposphere/appconfig.py | Python | validate_growth_type | validate_growth_type | 17 | 21 | 17 | 17 | af23fa1edce966fd57129ffd934d0b8ac5f68b07 | bigcode/the-stack | train |
3dd6b6c5e0743fc09dbe14e5 | train | class | class ConfigurationProfile(AWSObject):
resource_type = "AWS::AppConfig::ConfigurationProfile"
props = {
'ApplicationId': (str, True),
'Description': (str, False),
'LocationUri': (str, True),
'Name': (str, True),
'RetrievalRoleArn': (str, False),
'Tags': (Tags, Fa... | class ConfigurationProfile(AWSObject):
| resource_type = "AWS::AppConfig::ConfigurationProfile"
props = {
'ApplicationId': (str, True),
'Description': (str, False),
'LocationUri': (str, True),
'Name': (str, True),
'RetrievalRoleArn': (str, False),
'Tags': (Tags, False),
'Validators': ([Validator... | str, False),
'EnvironmentId': (str, True),
'Tags': (Tags, False),
}
class Validators(AWSProperty):
props = {
'Content': (str, False),
'Type': (validate_validator_type, False),
}
class ConfigurationProfile(AWSObject):
| 64 | 64 | 94 | 7 | 57 | ayfallen/urler | venv/lib/python3.8/site-packages/troposphere/appconfig.py | Python | ConfigurationProfile | ConfigurationProfile | 93 | 104 | 93 | 93 | 368cd5ac59b3d8526513d6cc57ac0fa0c0150a49 | bigcode/the-stack | train |
93aef223f3733e8be7e4fff0 | train | class | class Monitors(AWSProperty):
props = {
'AlarmArn': (str, False),
'AlarmRoleArn': (str, False),
}
| class Monitors(AWSProperty):
| props = {
'AlarmArn': (str, False),
'AlarmRoleArn': (str, False),
}
| 'GrowthFactor': (double, True),
'GrowthType': (validate_growth_type, False),
'Name': (str, True),
'ReplicateTo': (validate_replicate_to, True),
'Tags': (Tags, False),
}
class Monitors(AWSProperty):
| 64 | 64 | 34 | 7 | 57 | ayfallen/urler | venv/lib/python3.8/site-packages/troposphere/appconfig.py | Python | Monitors | Monitors | 53 | 57 | 53 | 53 | 96311b466fd66116d67e227ec1feaff68ada2f52 | bigcode/the-stack | train |
d95b4168952ee3aecd81d605 | train | class | class Validators(AWSProperty):
props = {
'Content': (str, False),
'Type': (validate_validator_type, False),
}
| class Validators(AWSProperty):
| props = {
'Content': (str, False),
'Type': (validate_validator_type, False),
}
| Id': (str, True),
'ConfigurationVersion': (str, True),
'DeploymentStrategyId': (str, True),
'Description': (str, False),
'EnvironmentId': (str, True),
'Tags': (Tags, False),
}
class Validators(AWSProperty):
| 64 | 64 | 32 | 6 | 58 | ayfallen/urler | venv/lib/python3.8/site-packages/troposphere/appconfig.py | Python | Validators | Validators | 86 | 90 | 86 | 86 | 9161a62caecf65d02a180476543f5fc0375509b7 | bigcode/the-stack | train |
93ef3b5a74d872f168af0826 | train | function | def test_evoked():
with tempfile.TemporaryDirectory() as dirpath:
sample_folder = mne.datasets.sample.data_path()
sample_fname = os.path.join(sample_folder, 'MEG', 'sample', 'sample_audvis_raw.fif')
name = 'TestEvoked'
cond_name = 'cond_1'
evoked_dir = os.path.join(dirpath,... | def test_evoked():
| with tempfile.TemporaryDirectory() as dirpath:
sample_folder = mne.datasets.sample.data_path()
sample_fname = os.path.join(sample_folder, 'MEG', 'sample', 'sample_audvis_raw.fif')
name = 'TestEvoked'
cond_name = 'cond_1'
evoked_dir = os.path.join(dirpath, 'evoked')
... | import tempfile
import os
import mne
from meggie.datatypes.evoked.evoked import Evoked
from meggie.utilities.events import find_events
from meggie.utilities.filemanager import ensure_folders
def test_evoked():
| 48 | 84 | 281 | 5 | 42 | Teekuningas/meggie | meggie/datatypes/evoked/tests/test_evoked.py | Python | test_evoked | test_evoked | 11 | 41 | 11 | 11 | 851c4bad6c98008eb1dc051ba596bd6d529b65e3 | bigcode/the-stack | train |
369bc14b3feb94a9133b66e6 | train | class | class Automovil:
def __init__(self,marca,modelo,tipo):
self.marca = marca | class Automovil:
| def __init__(self,marca,modelo,tipo):
self.marca = marca | class Automovil:
| 4 | 64 | 23 | 4 | 0 | gcardosov/PythonAprendeOrg | ActividadLeccion3.py | Python | Automovil | Automovil | 3 | 5 | 3 | 3 | 6bfff3261666b8d53f3be394b46a1f57e7007e1f | bigcode/the-stack | train |
48b64297a05e513a0e18b0ee | train | function | def _handle_tunnel_args(port: Optional[int], ssl: bool, authenticate: bool) -> Tuple[int, bool]:
default_port: int
if ssl:
default_port = 443
elif authenticate:
default_port = 80
else:
default_port = 9999
return (default_port if port is None else port, ssl or authenticate)
| def _handle_tunnel_args(port: Optional[int], ssl: bool, authenticate: bool) -> Tuple[int, bool]:
| default_port: int
if ssl:
default_port = 443
elif authenticate:
default_port = 80
else:
default_port = 9999
return (default_port if port is None else port, ssl or authenticate)
| return int(remote_timeout)
warnings.warn(DecodeWarning(f"Invalid {field.packet_type} {field.name} LINK param: {remote_timeout!r}"))
return 0
def _handle_tunnel_args(port: Optional[int], ssl: bool, authenticate: bool) -> Tuple[int, bool]:
| 64 | 64 | 80 | 25 | 38 | CRFS/python3-ncplib | ncplib/connection.py | Python | _handle_tunnel_args | _handle_tunnel_args | 110 | 118 | 110 | 110 | c41e0abcf70bc30ee34465bfa5bfe2dbf192fc1b | bigcode/the-stack | train |
f055126fbfd2369146f818f0 | train | class | class Connection(AsyncIteratorMixin):
"""
A connection between a :doc:`client` and a :doc:`server`.
Connections can be used as *async iterators* to loop over each incoming :class:`Field`:
.. code:: python
async for field in connection:
pass
.. important::
The *async ... | class Connection(AsyncIteratorMixin):
| """
A connection between a :doc:`client` and a :doc:`server`.
Connections can be used as *async iterators* to loop over each incoming :class:`Field`:
.. code:: python
async for field in connection:
pass
.. important::
The *async for loop* will only terminate when the ... | :`Field` received in reply to the sent :term:`NCP packet`.
:raises ncplib.NCPError: if a field could not be retrieved from the connection.
:return: The next :class:`Field` received.
:rtype: Field
"""
while True:
field = await self._connection.recv()
if (
... | 256 | 256 | 2,419 | 7 | 248 | CRFS/python3-ncplib | ncplib/connection.py | Python | Connection | Connection | 283 | 557 | 283 | 284 | 912bba60476bac0978b4abec62ec4e31b78b0375 | bigcode/the-stack | train |
3f1d47ea5f95cda562618917 | train | function | async def _wait_for(coro: Awaitable[T], ms: int) -> T:
try:
async with timeout(ms):
return await coro
except asyncio.CancelledError: # pragma: no cover
raise # Propagate cancels, not needed in Python3.8+.
except asyncio.TimeoutError as ex: # pragma: no cover
raise Netw... | async def _wait_for(coro: Awaitable[T], ms: int) -> T:
| try:
async with timeout(ms):
return await coro
except asyncio.CancelledError: # pragma: no cover
raise # Propagate cancels, not needed in Python3.8+.
except asyncio.TimeoutError as ex: # pragma: no cover
raise NetworkTimeoutError(ex) from ex
except OSError as ex: ... | '\x00\x00\x00\x00\xaa\xbb\xcc\xdd'))
# ID generation.
_gen_id = cycle(range(2 ** 32)).__next__
DEFAULT_TIMEOUT: int = 60
async def _wait_for(coro: Awaitable[T], ms: int) -> T:
| 64 | 64 | 113 | 19 | 44 | CRFS/python3-ncplib | ncplib/connection.py | Python | _wait_for | _wait_for | 90 | 99 | 90 | 90 | 24977cd3b8ba9da04a4656aaa2f7280315a74e2e | bigcode/the-stack | train |
7e371bcbd3bc03d3b55149b6 | train | class | class Field(Dict[str, Param]):
"""
A :term:`NCP field` received by a :class:`Connection`.
Access :term:`NCP parameter` values using item access:
.. code:: python
print(field["PDAT"])
.. attribute:: connection
The :class:`Connection` that created this field.
.. attribute:: ... | class Field(Dict[str, Param]):
| """
A :term:`NCP field` received by a :class:`Connection`.
Access :term:`NCP parameter` values using item access:
.. code:: python
print(field["PDAT"])
.. attribute:: connection
The :class:`Connection` that created this field.
.. attribute:: packet_type
The type of... | # pragma: no cover
raise NetworkError(ex) from ex
def _decode_remote_timeout(field: Field) -> int:
remote_timeout = field.get("LINK", 0)
if isinstance(remote_timeout, (int, float)) and remote_timeout >= 0:
return int(remote_timeout)
warnings.warn(DecodeWarning(f"Invalid {field.packet_type... | 185 | 185 | 618 | 9 | 176 | CRFS/python3-ncplib | ncplib/connection.py | Python | Field | Field | 121 | 197 | 121 | 122 | 00f3fd072310ebf79b223ea303677d08dd8e8585 | bigcode/the-stack | train |
64b060c77009301444232159 | train | function | def _decode_remote_timeout(field: Field) -> int:
remote_timeout = field.get("LINK", 0)
if isinstance(remote_timeout, (int, float)) and remote_timeout >= 0:
return int(remote_timeout)
warnings.warn(DecodeWarning(f"Invalid {field.packet_type} {field.name} LINK param: {remote_timeout!r}"))
return 0... | def _decode_remote_timeout(field: Field) -> int:
| remote_timeout = field.get("LINK", 0)
if isinstance(remote_timeout, (int, float)) and remote_timeout >= 0:
return int(remote_timeout)
warnings.warn(DecodeWarning(f"Invalid {field.packet_type} {field.name} LINK param: {remote_timeout!r}"))
return 0
| .8+.
except asyncio.TimeoutError as ex: # pragma: no cover
raise NetworkTimeoutError(ex) from ex
except OSError as ex: # pragma: no cover
raise NetworkError(ex) from ex
def _decode_remote_timeout(field: Field) -> int:
| 64 | 64 | 81 | 12 | 51 | CRFS/python3-ncplib | ncplib/connection.py | Python | _decode_remote_timeout | _decode_remote_timeout | 102 | 107 | 102 | 102 | bd8f9118183da3eb9c3f58c990e5dad4f5354005 | bigcode/the-stack | train |
a6b79ce93090ee7ac0aacda5 | train | class | class AsyncIteratorMixin:
__slots__ = ()
def __aiter__(self) -> AsyncIterator[Field]:
return self
async def __anext__(self) -> Field:
try:
return await self.recv() # type: ignore
except ConnectionClosed:
raise StopAsyncIteration
| class AsyncIteratorMixin:
| __slots__ = ()
def __aiter__(self) -> AsyncIterator[Field]:
return self
async def __anext__(self) -> Field:
try:
return await self.recv() # type: ignore
except ConnectionClosed:
raise StopAsyncIteration
| the parameter values were invalid.
:raises TypeError: if any of the parameter values were not one of the supported
:doc:`value types <values>`.
"""
return self.connection._send_packet(self.packet_type, ((self.name, self.id, params.items()),))
class AsyncIteratorMixin:
| 64 | 64 | 67 | 5 | 59 | CRFS/python3-ncplib | ncplib/connection.py | Python | AsyncIteratorMixin | AsyncIteratorMixin | 200 | 211 | 200 | 201 | 89cb1f93175cc277a610eb8fc334e35f75b912e5 | bigcode/the-stack | train |
5033d94631c3018d8fb7dc3b | train | class | class Response(AsyncIteratorMixin):
"""
A response to a :term:`NCP packet`, returned by :meth:`Connection.send`, :meth:`Connection.send_packet` and
:meth:`Field.send`.
Provides access to any :class:`Field` received in reply to the sent packet.
Responses can be used as *async iterators* to loop ov... | class Response(AsyncIteratorMixin):
| """
A response to a :term:`NCP packet`, returned by :meth:`Connection.send`, :meth:`Connection.send_packet` and
:meth:`Field.send`.
Provides access to any :class:`Field` received in reply to the sent packet.
Responses can be used as *async iterators* to loop over each incoming :class:`Field`:
... | were not a valid :term:`identifier`, or any
of the parameter values were invalid.
:raises TypeError: if any of the parameter values were not one of the supported
:doc:`value types <values>`.
"""
return self.connection._send_packet(self.packet_type, ((self.name, self.id, ... | 147 | 147 | 492 | 7 | 139 | CRFS/python3-ncplib | ncplib/connection.py | Python | Response | Response | 214 | 280 | 214 | 215 | 29aeee6e2b51822fe50581cb0fda308f6df69098 | bigcode/the-stack | train |
1012b7fb171e86c5e75d44b9 | train | class | class Parent():
def instance_method(self: T, x: int) -> T:
return self
@classmethod
def class_method(cls: Type[T]) -> T:
return cls()
| class Parent():
| def instance_method(self: T, x: int) -> T:
return self
@classmethod
def class_method(cls: Type[T]) -> T:
return cls()
| from typing import TypeVar, Type
T = TypeVar("T", bound="Parent")
class Parent():
| 22 | 64 | 42 | 3 | 19 | gcollard/lightbus | lightbus_experiments/pycharm_completion.py | Python | Parent | Parent | 6 | 12 | 6 | 6 | ebb54043869e38a5a79c2c78233797215392dde8 | bigcode/the-stack | train |
bada949ffe726fb77208b15d | train | class | class Child(Parent):
def foo(self):
pass
| class Child(Parent):
| def foo(self):
pass
| import TypeVar, Type
T = TypeVar("T", bound="Parent")
class Parent():
def instance_method(self: T, x: int) -> T:
return self
@classmethod
def class_method(cls: Type[T]) -> T:
return cls()
class Child(Parent):
| 64 | 64 | 13 | 5 | 59 | gcollard/lightbus | lightbus_experiments/pycharm_completion.py | Python | Child | Child | 15 | 17 | 15 | 15 | ba29e51c3fd0430b871d961f800adb98aa39e296 | bigcode/the-stack | train |
e5af16bba1e0b72579827493 | train | class | class Builder(workflow_utils.ArgoTestBuilder):
def __init__(self, name=None, namespace=None, bucket=None,
test_target_name=None, **kwargs):
super().__init__(name=name, namespace=namespace, bucket=bucket,
test_target_name=test_target_name, **kwargs)
def build(se... | class Builder(workflow_utils.ArgoTestBuilder):
| def __init__(self, name=None, namespace=None, bucket=None,
test_target_name=None, **kwargs):
super().__init__(name=name, namespace=namespace, bucket=bucket,
test_target_name=test_target_name, **kwargs)
def build(self):
"""Build the Argo workflow graph""... | """"Argo Workflow for testing notebook-server-jupyter-tensorflow-full OCI images"""
from kubeflow.kubeflow.ci import workflow_utils
from kubeflow.testing import argo_build_util
class Builder(workflow_utils.ArgoTestBuilder):
| 52 | 120 | 403 | 10 | 41 | phvalguima/kubeflow | py/kubeflow/kubeflow/ci/notebook_servers/notebook_server_jupyter_tensorflow_full_tests.py | Python | Builder | Builder | 6 | 42 | 6 | 6 | 50d8e056a2bfeacd5d22ce6bc1616ffdcca9cd8a | bigcode/the-stack | train |
7ee609b7034a59bf162dc122 | train | function | def create_workflow(name=None, namespace=None, bucket=None, **kwargs):
"""
Args:
name: Name to give to the workflow. This can also be used to name
things associated with the workflow.
"""
builder = Builder(name=name, namespace=namespace, bucket=bucket, **kwargs)
return builder... | def create_workflow(name=None, namespace=None, bucket=None, **kwargs):
| """
Args:
name: Name to give to the workflow. This can also be used to name
things associated with the workflow.
"""
builder = Builder(name=name, namespace=namespace, bucket=bucket, **kwargs)
return builder.build()
| workflow_utils.E2E_DAG_NAME,
kaniko_task_cuda, [self.mkdir_task_name])
# Set the labels on all templates
workflow = argo_build_util.set_task_template_labels(workflow)
return workflow
def create_workflow(name=None, namespace=None, bucket=None, **kwargs):... | 64 | 64 | 71 | 16 | 47 | phvalguima/kubeflow | py/kubeflow/kubeflow/ci/notebook_servers/notebook_server_jupyter_tensorflow_full_tests.py | Python | create_workflow | create_workflow | 45 | 53 | 45 | 45 | 23f47a2b8675ad13348cb88ed706f8eb076aaa7e | bigcode/the-stack | train |
096d2e59d8b26e89dbb3d258 | train | function | def _build_faster_rcnn_model(frcnn_config, is_training, add_summaries):
"""Builds a Faster R-CNN or R-FCN detection model based on the model config.
Builds R-FCN model if the second_stage_box_predictor in the config is of type
`rfcn_box_predictor` else builds a Faster R-CNN model.
Args:
frcnn_config: A fa... | def _build_faster_rcnn_model(frcnn_config, is_training, add_summaries):
| """Builds a Faster R-CNN or R-FCN detection model based on the model config.
Builds R-FCN model if the second_stage_box_predictor in the config is of type
`rfcn_box_predictor` else builds a Faster R-CNN model.
Args:
frcnn_config: A faster_rcnn.proto object containing the config for the
desired Faste... | training. This is required for batch norm to work correctly on TPUs. When
this is false, user must add a control dependency on
tf.GraphKeys.UPDATE_OPS for train/loss op in order to update the batch
norm moving average parameters.
Returns:
faster_rcnn_meta_arch.FasterRCNNFeatureExtractor based ... | 256 | 256 | 1,726 | 21 | 235 | kichiro09/object-detection | research/object_detection/builders/model_builder.py | Python | _build_faster_rcnn_model | _build_faster_rcnn_model | 353 | 514 | 353 | 353 | 70be253acc80d6170013e69c5e3a0b95dcf5b74c | bigcode/the-stack | train |
4a875145d4748aeb9e62d52e | train | function | def _build_faster_rcnn_feature_extractor(
feature_extractor_config, is_training, reuse_weights=None,
inplace_batchnorm_update=False):
"""Builds a faster_rcnn_meta_arch.FasterRCNNFeatureExtractor based on config.
Args:
feature_extractor_config: A FasterRcnnFeatureExtractor proto config from
faster... | def _build_faster_rcnn_feature_extractor(
feature_extractor_config, is_training, reuse_weights=None,
inplace_batchnorm_update=False):
| """Builds a faster_rcnn_meta_arch.FasterRCNNFeatureExtractor based on config.
Args:
feature_extractor_config: A FasterRcnnFeatureExtractor proto config from
faster_rcnn.proto.
is_training: True if this feature extractor is being built for training.
reuse_weights: if the feature extractor should r... | normalize_loc_loss_by_codesize=normalize_loc_loss_by_codesize,
freeze_batchnorm=ssd_config.freeze_batchnorm,
inplace_batchnorm_update=ssd_config.inplace_batchnorm_update,
add_background_class=ssd_config.add_background_class,
random_example_sampler=random_example_sampler,
expected_classifi... | 105 | 105 | 353 | 31 | 74 | kichiro09/object-detection | research/object_detection/builders/model_builder.py | Python | _build_faster_rcnn_feature_extractor | _build_faster_rcnn_feature_extractor | 314 | 350 | 314 | 316 | 79cee0926b2b974daaf0796368df2d870c44e731 | bigcode/the-stack | train |
cb3c272de9fd33fabf0328a6 | train | function | def build(model_config, is_training, add_summaries=True):
"""Builds a DetectionModel based on the model config.
Args:
model_config: A model.proto object containing the config for the desired
DetectionModel.
is_training: True if this model is being built for training purposes.
add_summaries: Wheth... | def build(model_config, is_training, add_summaries=True):
| """Builds a DetectionModel based on the model config.
Args:
model_config: A model.proto object containing the config for the desired
DetectionModel.
is_training: True if this model is being built for training purposes.
add_summaries: Whether to add tensorflow summaries in the model graph.
Retur... | 'faster_rcnn_resnet101':
frcnn_resnet_v1.FasterRCNNResnet101FeatureExtractor,
'faster_rcnn_resnet152':
frcnn_resnet_v1.FasterRCNNResnet152FeatureExtractor,
}
def build(model_config, is_training, add_summaries=True):
| 69 | 69 | 233 | 14 | 55 | kichiro09/object-detection | research/object_detection/builders/model_builder.py | Python | build | build | 100 | 122 | 100 | 100 | 5c52738f6ce6c45ab71369066ee75acc4da09aac | bigcode/the-stack | train |
f63781267cc59ac5b88be4e6 | train | function | def _build_ssd_model(ssd_config, is_training, add_summaries):
"""Builds an SSD detection model based on the model config.
Args:
ssd_config: A ssd.proto object containing the config for the desired
SSDMetaArch.
is_training: True if this model is being built for training purposes.
add_summaries: Wh... | def _build_ssd_model(ssd_config, is_training, add_summaries):
| """Builds an SSD detection model based on the model config.
Args:
ssd_config: A ssd.proto object containing the config for the desired
SSDMetaArch.
is_training: True if this model is being built for training purposes.
add_summaries: Whether to add tf summaries in the model.
Returns:
SSDMeta... | 'is_training':
is_training,
'depth_multiplier':
depth_multiplier,
'min_depth':
min_depth,
'pad_to_multiple':
pad_to_multiple,
'use_explicit_padding':
use_explicit_padding,
'use_depthwise':
use_depthwise,
'override_base_feat... | 256 | 256 | 948 | 18 | 238 | kichiro09/object-detection | research/object_detection/builders/model_builder.py | Python | _build_ssd_model | _build_ssd_model | 214 | 311 | 214 | 214 | 124a3df3256b0a6ea8538c54e7dcc9dc45486efd | bigcode/the-stack | train |
cd22deb5d0c67faedc058916 | train | function | def _build_ssd_feature_extractor(feature_extractor_config,
is_training,
freeze_batchnorm,
reuse_weights=None):
"""Builds a ssd_meta_arch.SSDFeatureExtractor based on config.
Args:
feature_extractor_config: A SSDF... | def _build_ssd_feature_extractor(feature_extractor_config,
is_training,
freeze_batchnorm,
reuse_weights=None):
| """Builds a ssd_meta_arch.SSDFeatureExtractor based on config.
Args:
feature_extractor_config: A SSDFeatureExtractor proto config from ssd.proto.
is_training: True if this feature extractor is being built for training.
freeze_batchnorm: Whether to freeze batch norm parameters during
training or n... | this model is being built for training purposes.
add_summaries: Whether to add tensorflow summaries in the model graph.
Returns:
DetectionModel based on the config.
Raises:
ValueError: On invalid meta architecture or model.
"""
if not isinstance(model_config, model_pb2.DetectionModel):
raise V... | 205 | 205 | 686 | 27 | 178 | kichiro09/object-detection | research/object_detection/builders/model_builder.py | Python | _build_ssd_feature_extractor | _build_ssd_feature_extractor | 125 | 211 | 125 | 128 | 2b7b146a92f7c25500a3ae52d20e0abfb2a69ef5 | bigcode/the-stack | train |
a27a63e3346d66df6cd5e3f0 | train | class | class Migration(migrations.Migration):
dependencies = [
('contenttypes', '__first__'),
]
operations = [
migrations.CreateModel(
name='Permission',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=Tru... | class Migration(migrations.Migration):
| dependencies = [
('contenttypes', '__first__'),
]
operations = [
migrations.CreateModel(
name='Permission',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.Cha... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core import validators
from django.db import models, migrations
from django.utils import timezone
class Migration(migrations.Migration):
| 43 | 210 | 700 | 7 | 35 | dnozay/django | django/contrib/auth/migrations/0001_initial.py | Python | Migration | Migration | 9 | 66 | 9 | 10 | 2e9364141303f7caa9fe3df4b09bba7cf2d86617 | bigcode/the-stack | train |
b50d98112ef4668109912db5 | train | function | def read_input(timeout_ms: float = 1000) -> str:
start_time: int = int(time.time() * 1000)
input_str: str = ''
while True:
if msvcrt.kbhit():
byte_arr = msvcrt.getche()
if ord(byte_arr) == 13: # enter_key
break
elif ord(byte_arr) >= 32: ... | def read_input(timeout_ms: float = 1000) -> str:
| start_time: int = int(time.time() * 1000)
input_str: str = ''
while True:
if msvcrt.kbhit():
byte_arr = msvcrt.getche()
if ord(byte_arr) == 13: # enter_key
break
elif ord(byte_arr) >= 32: # space_char
input_str += "".joi... | import time
import msvcrt
__all__ = ['read_input']
def read_input(timeout_ms: float = 1000) -> str:
| 31 | 64 | 140 | 15 | 16 | Tombmyst/Empire | Python/empire/python/stdin.py | Python | read_input | read_input | 8 | 23 | 8 | 8 | ec11d034d33246651c5c3ed5334add080157967b | bigcode/the-stack | train |
9fed96991046cef8993bf451 | train | class | class TestCdau(unittest.TestCase):
def setUp(self):
self.m_cdau = mock.MagicMock()
def test_cod_mun_cat2ine(self):
self.assertEqual(cdau.cod_mun_cat2ine('04030'), '04030')
self.assertEqual(cdau.cod_mun_cat2ine('04040'), '04901')
self.assertEqual(cdau.cod_mun_cat2ine('04103'), '... | class TestCdau(unittest.TestCase):
| def setUp(self):
self.m_cdau = mock.MagicMock()
def test_cod_mun_cat2ine(self):
self.assertEqual(cdau.cod_mun_cat2ine('04030'), '04030')
self.assertEqual(cdau.cod_mun_cat2ine('04040'), '04901')
self.assertEqual(cdau.cod_mun_cat2ine('04103'), '04103')
self.assertEqual(cda... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from builtins import str
import unittest
import mock
import os
from catatom2osm import config, cdau, layer
from catatom2osm.app import QgsSingleton
from catatom2osm.compat import install_gettext
qgs = QgsSingleton()
os.environ['LANGUAGE'] = 'C'
install_ge... | 116 | 256 | 1,610 | 8 | 108 | OSM-es/CatAtom2Osm | test/test_cdau.py | Python | TestCdau | TestCdau | 19 | 140 | 19 | 20 | 0527f3cf4205e77febde2d7b504f4bb6910e7e09 | bigcode/the-stack | train |
04e61c34b8d0380919605723 | train | function | def get_func(f):
return getattr(f, '__func__', f)
| def get_func(f):
| return getattr(f, '__func__', f)
| atom2osm import config, cdau, layer
from catatom2osm.app import QgsSingleton
from catatom2osm.compat import install_gettext
qgs = QgsSingleton()
os.environ['LANGUAGE'] = 'C'
install_gettext('catato2osm', '')
def get_func(f):
| 63 | 64 | 16 | 5 | 58 | OSM-es/CatAtom2Osm | test/test_cdau.py | Python | get_func | get_func | 16 | 17 | 16 | 16 | 34ccc2cccedc9099659e1305660a8a33833616c6 | bigcode/the-stack | train |
0a6a9d4891486f9869651dd9 | train | class | class UtilGp:
@staticmethod
def clear():
if name == 'nt': #windows
_ = system('cls')
else: #mac,linux
_ = system('clear')
@staticmethod
def dateToStr(valueDate,formatStr = '%d-%m-%Y'):
strDate = valueDate.strftime(formatStr)
return strDate
@sta... | class UtilGp:
@staticmethod
| def clear():
if name == 'nt': #windows
_ = system('cls')
else: #mac,linux
_ = system('clear')
@staticmethod
def dateToStr(valueDate,formatStr = '%d-%m-%Y'):
strDate = valueDate.strftime(formatStr)
return strDate
@staticmethod
def strToDate(strD... | from datetime import datetime,timedelta
from os import system, name
from time import sleep
import re
import random
class UtilGp:
@staticmethod
| 33 | 256 | 1,770 | 8 | 24 | PacktPublishing/Python-Programming | expenseManager/app/UtilGp.py | Python | UtilGp | UtilGp | 7 | 201 | 7 | 8 | 73acd7f9f3889077617270773bf1072cac6159f5 | bigcode/the-stack | train |
39e792cc96e8996e8563fe6d | train | class | class SubscriptionList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin):
view_name = 'notification-subscription-list'
view_category = 'notification-subscriptions'
serializer_class = SubscriptionSerializer
model_class = NotificationSubscription
permission_classes = (
drf_permissions.Is... | class SubscriptionList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin):
| view_name = 'notification-subscription-list'
view_category = 'notification-subscriptions'
serializer_class = SubscriptionSerializer
model_class = NotificationSubscription
permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
)
required_read_... |
from api.base.filters import ListFilterMixin
from api.base import permissions as base_permissions
from api.subscriptions.serializers import SubscriptionSerializer
from api.subscriptions.permissions import IsSubscriptionOwner
from osf.models import NotificationSubscription
class SubscriptionList(JSONAPIBaseView, generi... | 64 | 64 | 148 | 17 | 46 | tsukaeru/RDM-osf.io | api/subscriptions/views.py | Python | SubscriptionList | SubscriptionList | 16 | 34 | 16 | 16 | cc69cb5643331f473f55d0a48de07f548626ccd1 | bigcode/the-stack | train |
f0f65fed52956eaca2435ada | train | class | class SubscriptionDetail(JSONAPIBaseView, generics.RetrieveUpdateAPIView):
view_name = 'notification-subscription-detail'
view_category = 'notification-subscriptions'
serializer_class = SubscriptionSerializer
permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenH... | class SubscriptionDetail(JSONAPIBaseView, generics.RetrieveUpdateAPIView):
| view_name = 'notification-subscription-detail'
view_category = 'notification-subscriptions'
serializer_class = SubscriptionSerializer
permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
IsSubscriptionOwner,
)
required_read_scopes = [Co... | _default_queryset(self):
user = self.request.user
return NotificationSubscription.objects.filter(Q(none=user) | Q(email_digest=user) | Q(email_transactional=user))
def get_queryset(self):
return self.get_queryset_from_request()
class SubscriptionDetail(JSONAPIBaseView, generics.RetrieveUpda... | 64 | 64 | 154 | 15 | 49 | tsukaeru/RDM-osf.io | api/subscriptions/views.py | Python | SubscriptionDetail | SubscriptionDetail | 37 | 57 | 37 | 37 | 6d134111529b47ca21187731c3123bc313d1b527 | bigcode/the-stack | train |
68793f3ef8e1bfc92882b923 | train | function | def fuse_conv_bn(model: nn.Module, replace_bn_with_identity: bool = False):
"""
Fuses consecutive nn.Conv2d and nn.BatchNorm2d layers recursively inplace in all of the model
:param replace_bn_with_identity: if set to true, bn will be replaced with identity. otherwise, bn will be removed
:param model: th... | def fuse_conv_bn(model: nn.Module, replace_bn_with_identity: bool = False):
| """
Fuses consecutive nn.Conv2d and nn.BatchNorm2d layers recursively inplace in all of the model
:param replace_bn_with_identity: if set to true, bn will be replaced with identity. otherwise, bn will be removed
:param model: the target model
:return: the number of fuses executed
"""
childre... |
class ExportableSiLU(nn.Module):
"""
Export-friendly version of nn.SiLU()
From https://github.com/ultralytics/yolov5
"""
@staticmethod
def forward(x):
return x * torch.sigmoid(x)
def fuse_conv_bn(model: nn.Module, replace_bn_with_identity: bool = False):
| 74 | 74 | 249 | 18 | 56 | Deci-AI/super-gradients | src/super_gradients/training/utils/export_utils.py | Python | fuse_conv_bn | fuse_conv_bn | 26 | 46 | 26 | 26 | e2a597d89e9048adf2488de54032756c6f3e4c74 | bigcode/the-stack | train |
5d61c04232e6dbb5d2d556ac | train | class | class ExportableHardswish(nn.Module):
'''
Export-friendly version of nn.Hardswish()
'''
@staticmethod
def forward(x):
return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX
| class ExportableHardswish(nn.Module):
| '''
Export-friendly version of nn.Hardswish()
'''
@staticmethod
def forward(x):
return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX
| import torch
import torch.nn as nn
import torch.nn.functional as F
class ExportableHardswish(nn.Module):
| 25 | 64 | 67 | 9 | 15 | Deci-AI/super-gradients | src/super_gradients/training/utils/export_utils.py | Python | ExportableHardswish | ExportableHardswish | 6 | 13 | 6 | 6 | b12a82c4096e79c234f628be63f82af4a6111f9f | bigcode/the-stack | train |
5772b90b58c7613ed0b18325 | train | class | class ExportableSiLU(nn.Module):
"""
Export-friendly version of nn.SiLU()
From https://github.com/ultralytics/yolov5
"""
@staticmethod
def forward(x):
return x * torch.sigmoid(x)
| class ExportableSiLU(nn.Module):
| """
Export-friendly version of nn.SiLU()
From https://github.com/ultralytics/yolov5
"""
@staticmethod
def forward(x):
return x * torch.sigmoid(x)
| Export-friendly version of nn.Hardswish()
'''
@staticmethod
def forward(x):
return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX
class ExportableSiLU(nn.Module):
| 64 | 64 | 55 | 8 | 55 | Deci-AI/super-gradients | src/super_gradients/training/utils/export_utils.py | Python | ExportableSiLU | ExportableSiLU | 16 | 23 | 16 | 16 | bd06a50d53d1ed197016db073948ba567de79673 | bigcode/the-stack | train |
f18e2565106f05d38d3c33e8 | train | class | class DotDict(dict):
def __getattr__(self, name):
value = self[name]
if isinstance(value, dict):
value = DotDict(value)
return value
| class DotDict(dict):
| def __getattr__(self, name):
value = self[name]
if isinstance(value, dict):
value = DotDict(value)
return value
| class DotDict(dict):
| 5 | 64 | 39 | 5 | 0 | samuel930930/Dual_Manifold_Adversarial_Training | config.py | Python | DotDict | DotDict | 3 | 8 | 3 | 3 | 1ada727bf80c3f188fe4676817be13e3ba142064 | bigcode/the-stack | train |
48c4ef3a24399ec03d836c06 | train | class | class BackTranslated(object):
"""BackTranslate result object
:param src: source langauge
:param mid: mid language
:param src_text: original source text
:param mid_text: mid-translated text
:param text: backtranslated text
"""
def __init__(self, src, mid, src_text, mid_text, text):
... | class BackTranslated(object):
| """BackTranslate result object
:param src: source langauge
:param mid: mid language
:param src_text: original source text
:param mid_text: mid-translated text
:param text: backtranslated text
"""
def __init__(self, src, mid, src_text, mid_text, text):
self.src = src
sel... | # -*- coding: utf-8 -*-
class BackTranslated(object):
| 13 | 64 | 207 | 5 | 8 | monologg/py-backtrans | pybacktrans/models.py | Python | BackTranslated | BackTranslated | 2 | 26 | 2 | 2 | 9885c75fe8723ed71b695600f02d11e4112787f7 | bigcode/the-stack | train |
dbbdfa8e28790e549362f3fd | train | function | def validar_entero_m():
"""
"""
try:
m = int(input('m= '))
except:
print ('Número no válido')
return False
else:
return m
| def validar_entero_m():
| """
"""
try:
m = int(input('m= '))
except:
print ('Número no válido')
return False
else:
return m
| las entradas.
"""
def validar_entero_n():
"""
"""
try:
n = int(input('n= ')) #si es un float también funciona el programa
except:
print ('Número no válido')
return False
else:
return n
def validar_entero_m():
| 64 | 64 | 43 | 6 | 57 | lauram15a/Fundamentos_de_programacion | CUADERNOS DE TRABAJO/CUADERNO 3/ej 2 cuaderno 3 suma componentes lista.py | Python | validar_entero_m | validar_entero_m | 22 | 31 | 22 | 22 | 2ddd80d6003be5f4d3a3c6165ba1f54839424c0d | bigcode/the-stack | train |
850295c897c0db26f0f1afec | train | function | def multiplicacion_por_suma(n,m):
"""
int, int --> int
OBJ: crear una lista con m elementos (0,m-1), rellenar los elementos con n y sumar los elementos
"""
if m==0 or n==0:
return 0
elif m==1:
return n
elif n==1:
return m
elif n>0 and m>0: #n y m positivos
... | def multiplicacion_por_suma(n,m):
| """
int, int --> int
OBJ: crear una lista con m elementos (0,m-1), rellenar los elementos con n y sumar los elementos
"""
if m==0 or n==0:
return 0
elif m==1:
return n
elif n==1:
return m
elif n>0 and m>0: #n y m positivos
lista=[] #creo lista
suma... | que cero, debiendo validar las entradas.
"""
def validar_entero_n():
"""
"""
try:
n = int(input('n= ')) #si es un float también funciona el programa
except:
print ('Número no válido')
return False
else:
return n
def validar_entero_m():
"""
"""
try:
... | 116 | 116 | 389 | 9 | 106 | lauram15a/Fundamentos_de_programacion | CUADERNOS DE TRABAJO/CUADERNO 3/ej 2 cuaderno 3 suma componentes lista.py | Python | multiplicacion_por_suma | multiplicacion_por_suma | 34 | 77 | 34 | 34 | 7e7f8e9b500949fdc146e30a23e0409ad6b5f081 | bigcode/the-stack | train |
6fad0b484bc7a6311185abec | train | function | def validar_entero_n():
"""
"""
try:
n = int(input('n= ')) #si es un float también funciona el programa
except:
print ('Número no válido')
return False
else:
return n
| def validar_entero_n():
| """
"""
try:
n = int(input('n= ')) #si es un float también funciona el programa
except:
print ('Número no válido')
return False
else:
return n
| : si recibe 2 y 3
devuelve 6; si recibe 2 y 0 devuelve 0; si recibe -3 y 2 dará -6. El programa no
asumirá que los números son mayores que cero, debiendo validar las entradas.
"""
def validar_entero_n():
| 64 | 64 | 54 | 6 | 58 | lauram15a/Fundamentos_de_programacion | CUADERNOS DE TRABAJO/CUADERNO 3/ej 2 cuaderno 3 suma componentes lista.py | Python | validar_entero_n | validar_entero_n | 11 | 20 | 11 | 11 | 1c65491560469e12f50057c8940b8472fc34b438 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.