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
762d7c89794bfe2cb3b211c8
train
class
class DeleteView(generic.DeleteView): template_name = "media_list/categories/base/confirm_delete.html" def get_success_url(self): return reverse_lazy(f"categories:{self.model.category.path}:list")
class DeleteView(generic.DeleteView):
template_name = "media_list/categories/base/confirm_delete.html" def get_success_url(self): return reverse_lazy(f"categories:{self.model.category.path}:list")
return self.model.category raise NotImplementedError class EditInterestView(EditFieldsView): fields = ['interest'] class EditTitleView(EditFieldsView): fields = ['title'] class EditAlternateTitleView(EditFieldsView): fields = ['alternate_title'] class DeleteView(generic.DeleteView)...
64
64
44
8
56
mincem/media_list
src/media_list/views/base_views.py
Python
DeleteView
DeleteView
106
110
106
106
c32ef1723afe14f936b5ef47da8bf81f59320590
bigcode/the-stack
train
c619f2dd91924d863cf704d5
train
class
class LandingView(generic.TemplateView): template_name = 'media_list/landing.html'
class LandingView(generic.TemplateView):
template_name = 'media_list/landing.html'
from django.urls import reverse_lazy from django.views import generic from extra_views import CreateWithInlinesView, UpdateWithInlinesView from ..data_fetchers import ExternalItemFetcher from ..id_finders import ExternalIDFinder class LandingView(generic.TemplateView):
57
64
19
8
48
mincem/media_list
src/media_list/views/base_views.py
Python
LandingView
LandingView
9
10
9
9
f4f3aa8e81a2b0d0f0e853b0208ec8a568518af1
bigcode/the-stack
train
f37d5b9e51a515ec6c1c9472
train
class
class EditView(UpdateWithInlinesView): def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/edit.html"] def get_success_url(self): return reverse_lazy(f"categories:{self.model.category.path}:list", kwargs={"pk": self.object.id})
class EditView(UpdateWithInlinesView):
def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/edit.html"] def get_success_url(self): return reverse_lazy(f"categories:{self.model.category.path}:list", kwargs={"pk": self.object.id})
get_success_url(self): if "add_another" in self.request.POST: return reverse_lazy(f"categories:{self.model.category.path}:create") return reverse_lazy(f"categories:{self.model.category.path}:list", kwargs={"pk": self.object.id}) class EditView(UpdateWithInlinesView):
64
64
63
9
55
mincem/media_list
src/media_list/views/base_views.py
Python
EditView
EditView
69
74
69
69
2af5c2abb2ed9ccda7b63314ad40b7827af80244
bigcode/the-stack
train
ce74891ba2509245d35b24dd
train
class
class DetailView(generic.DetailView): def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/detail.html"]
class DetailView(generic.DetailView):
def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/detail.html"]
def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/list.html"] class GridView(CollectionView): def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/grid.html"] class DetailView(generic.DetailView):
63
64
32
8
55
mincem/media_list
src/media_list/views/base_views.py
Python
DetailView
DetailView
38
40
38
38
f06351dc727afe1579a2bac5b5bf4d5c800b22ca
bigcode/the-stack
train
2c2a6dc9260b2bb7965c2279
train
class
class EditAlternateTitleView(EditFieldsView): fields = ['alternate_title']
class EditAlternateTitleView(EditFieldsView):
fields = ['alternate_title']
: return self.category if self.model and self.model.category: return self.model.category raise NotImplementedError class EditInterestView(EditFieldsView): fields = ['interest'] class EditTitleView(EditFieldsView): fields = ['title'] class EditAlternateTitleView(EditFi...
64
64
16
9
55
mincem/media_list
src/media_list/views/base_views.py
Python
EditAlternateTitleView
EditAlternateTitleView
102
103
102
102
6fff34b69969c6d7d7d345bda479588c672fa2dc
bigcode/the-stack
train
d115e1c625fec139112c736b
train
class
class CollectionView(generic.ListView): def get_sources(self): if self.model.source_class: return self.model.source_class.objects.all() else: return [] def get_context_data(self, **kwargs): return super().get_context_data( sources=self.get_sources(), ...
class CollectionView(generic.ListView):
def get_sources(self): if self.model.source_class: return self.model.source_class.objects.all() else: return [] def get_context_data(self, **kwargs): return super().get_context_data( sources=self.get_sources(), series_id=self.kwargs.get('p...
from extra_views import CreateWithInlinesView, UpdateWithInlinesView from ..data_fetchers import ExternalItemFetcher from ..id_finders import ExternalIDFinder class LandingView(generic.TemplateView): template_name = 'media_list/landing.html' class CollectionView(generic.ListView):
64
64
76
8
56
mincem/media_list
src/media_list/views/base_views.py
Python
CollectionView
CollectionView
13
25
13
13
67bd7f935de4b57a2ea40f98b1c24d9c72555bde
bigcode/the-stack
train
16e25fcfec2dedd63bbd66d3
train
class
class EditTitleView(EditFieldsView): fields = ['title']
class EditTitleView(EditFieldsView):
fields = ['title']
.object.id} ) def get_category(self): if self.category: return self.category if self.model and self.model.category: return self.model.category raise NotImplementedError class EditInterestView(EditFieldsView): fields = ['interest'] class EditTitleView(Ed...
64
64
14
8
56
mincem/media_list
src/media_list/views/base_views.py
Python
EditTitleView
EditTitleView
98
99
98
98
04b7afadb2370e2d8fddd5cada7713ac7d8bdd32
bigcode/the-stack
train
22f029b04f926618e5eba2ee
train
class
class ListView(CollectionView): def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/list.html"]
class ListView(CollectionView):
def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/list.html"]
.source_class: return self.model.source_class.objects.all() else: return [] def get_context_data(self, **kwargs): return super().get_context_data( sources=self.get_sources(), series_id=self.kwargs.get('pk'), **kwargs ) class ListVi...
64
64
30
6
58
mincem/media_list
src/media_list/views/base_views.py
Python
ListView
ListView
28
30
28
28
40427adb13401627591c13c23b87c285a9a3a329
bigcode/the-stack
train
9d2e7b93b69c0fc1c7e29629
train
class
@XBlock.needs('settings') class VideofrontXBlock(StudioEditableXBlockMixin, XBlock): """ Play videos based on a modified videojs player. This XBlock supports subtitles and multiple resolutions. """ # Used to load open edx-specific settings block_settings_key = 'videofront-xblock' has_autho...
@XBlock.needs('settings') class VideofrontXBlock(StudioEditableXBlockMixin, XBlock):
""" Play videos based on a modified videojs player. This XBlock supports subtitles and multiple resolutions. """ # Used to load open edx-specific settings block_settings_key = 'videofront-xblock' has_author_view = True display_name = String( help=ugettext_lazy("The name studen...
import json import logging import pkg_resources from django.utils.translation import ugettext_lazy from django.template import Context, Template from xblock.core import XBlock from xblock.fields import Boolean, Scope, String, Integer from xblock.fragment import Fragment from xblockutils.studio_editable import StudioE...
113
256
4,192
24
89
anitagoel/videofront-xblock
videofront_xblock/videofront_xblock.py
Python
VideofrontXBlock
VideofrontXBlock
21
500
21
22
6d597ef8266ed44940ad38c4c144d2b4f8030f6f
bigcode/the-stack
train
b5c7c4d3c5a55cc024ac5118
train
function
def test_has_provider_support__true(): assert has_provider_support("tmdb", "movie") is True assert has_provider_support("tvdb", "television") is True
def test_has_provider_support__true():
assert has_provider_support("tmdb", "movie") is True assert has_provider_support("tvdb", "television") is True
has_provider_support, provider_factory, ) def test_has_provider__true(): assert has_provider("tmdb") is True assert has_provider("tvdb") is True def test_has_provider__missing(): assert has_provider("imdb") is False def test_has_provider_support__true():
64
64
39
8
55
jkwill87/mapi
tests/providers/test_providers.py
Python
test_has_provider_support__true
test_has_provider_support__true
26
28
26
26
9fd43aec69b52b8646cdf3c83f86bd1fd4cf44b1
bigcode/the-stack
train
b66644f15644aab4ecd187cf
train
function
def test_has_provider__missing(): assert has_provider("imdb") is False
def test_has_provider__missing():
assert has_provider("imdb") is False
from mapi.providers import ( TMDb, TVDb, has_provider, has_provider_support, provider_factory, ) def test_has_provider__true(): assert has_provider("tmdb") is True assert has_provider("tvdb") is True def test_has_provider__missing():
64
64
18
7
56
jkwill87/mapi
tests/providers/test_providers.py
Python
test_has_provider__missing
test_has_provider__missing
22
23
22
22
0697c2bcb11e9d54d320bb9051c7b58ecfaa1f85
bigcode/the-stack
train
1de00f15f5260ce83ead3568
train
function
@pytest.mark.usefixtures("tvdb_api_key") def test_provider_factory__tvdb(tvdb_api_key): client = provider_factory("tvdb", api_key=tvdb_api_key) assert isinstance(client, TVDb)
@pytest.mark.usefixtures("tvdb_api_key") def test_provider_factory__tvdb(tvdb_api_key):
client = provider_factory("tvdb", api_key=tvdb_api_key) assert isinstance(client, TVDb)
tmdb_api_key") def test_provider_factory__tmdb(tmdb_api_key): client = provider_factory("tmdb", api_key=tmdb_api_key) assert isinstance(client, TMDb) @pytest.mark.usefixtures("tvdb_api_key") def test_provider_factory__tvdb(tvdb_api_key):
64
64
47
22
42
jkwill87/mapi
tests/providers/test_providers.py
Python
test_provider_factory__tvdb
test_provider_factory__tvdb
50
53
50
51
6970c291a8fdec12f581bd227dd3a1a22067d621
bigcode/the-stack
train
ce07c87d730543241ae18a94
train
function
def test_has_provider_support__valid_mtype(): assert has_provider_support("imdb", "movie") is False
def test_has_provider_support__valid_mtype():
assert has_provider_support("imdb", "movie") is False
assert has_provider_support("tvdb", "television") is True def test_has_provider_support__missing(): assert has_provider_support("tmdb", "television") is False assert has_provider_support("tvdb", "movie") is False def test_has_provider_support__valid_mtype():
64
64
25
10
53
jkwill87/mapi
tests/providers/test_providers.py
Python
test_has_provider_support__valid_mtype
test_has_provider_support__valid_mtype
36
37
36
36
b3f0ecbdaecebd913181c710db184980d63095af
bigcode/the-stack
train
4ec7ae4073a2ea21acd68aea
train
function
def test_non_existant(): with pytest.raises(MapiException): provider_factory("yolo")
def test_non_existant():
with pytest.raises(MapiException): provider_factory("yolo")
_api_key) assert isinstance(client, TMDb) @pytest.mark.usefixtures("tvdb_api_key") def test_provider_factory__tvdb(tvdb_api_key): client = provider_factory("tvdb", api_key=tvdb_api_key) assert isinstance(client, TVDb) def test_non_existant():
64
64
21
6
58
jkwill87/mapi
tests/providers/test_providers.py
Python
test_non_existant
test_non_existant
56
58
56
56
bda5199859568bb30c042eb53ee1b97314510cd3
bigcode/the-stack
train
185ae9bddaf17d9df5357a02
train
function
@pytest.mark.usefixtures("tmdb_api_key") def test_provider_factory__tmdb(tmdb_api_key): client = provider_factory("tmdb", api_key=tmdb_api_key) assert isinstance(client, TMDb)
@pytest.mark.usefixtures("tmdb_api_key") def test_provider_factory__tmdb(tmdb_api_key):
client = provider_factory("tmdb", api_key=tmdb_api_key) assert isinstance(client, TMDb)
assert has_provider_support("imdb", "movie") is False def test_has_provider_support__invalid_mtype(): assert has_provider_support("tmdb", "media_type_subtitle") is False @pytest.mark.usefixtures("tmdb_api_key") def test_provider_factory__tmdb(tmdb_api_key):
64
64
47
22
41
jkwill87/mapi
tests/providers/test_providers.py
Python
test_provider_factory__tmdb
test_provider_factory__tmdb
44
47
44
45
1011509a008f8aa2c3c31d1e76290d4aabe0d46b
bigcode/the-stack
train
39251b635520d2eaa7f44433
train
function
def test_has_provider_support__invalid_mtype(): assert has_provider_support("tmdb", "media_type_subtitle") is False
def test_has_provider_support__invalid_mtype():
assert has_provider_support("tmdb", "media_type_subtitle") is False
has_provider_support("tmdb", "television") is False assert has_provider_support("tvdb", "movie") is False def test_has_provider_support__valid_mtype(): assert has_provider_support("imdb", "movie") is False def test_has_provider_support__invalid_mtype():
64
64
28
10
53
jkwill87/mapi
tests/providers/test_providers.py
Python
test_has_provider_support__invalid_mtype
test_has_provider_support__invalid_mtype
40
41
40
40
c86334da9e4cdda5227ef33edad9e727497c3b71
bigcode/the-stack
train
7dabe2192946e37f930a0cb2
train
function
def test_has_provider_support__missing(): assert has_provider_support("tmdb", "television") is False assert has_provider_support("tvdb", "movie") is False
def test_has_provider_support__missing():
assert has_provider_support("tmdb", "television") is False assert has_provider_support("tvdb", "movie") is False
test_has_provider__missing(): assert has_provider("imdb") is False def test_has_provider_support__true(): assert has_provider_support("tmdb", "movie") is True assert has_provider_support("tvdb", "television") is True def test_has_provider_support__missing():
64
64
39
8
55
jkwill87/mapi
tests/providers/test_providers.py
Python
test_has_provider_support__missing
test_has_provider_support__missing
31
33
31
31
149ac5398aee7328c28d214d3780c0afaedd1353
bigcode/the-stack
train
106960bfa94990fa667a8096
train
function
def test_has_provider__true(): assert has_provider("tmdb") is True assert has_provider("tvdb") is True
def test_has_provider__true():
assert has_provider("tmdb") is True assert has_provider("tvdb") is True
# coding=utf-8 """Unit tests for mapi/providers/_provider.py.""" import pytest from mapi.exceptions import MapiException from mapi.providers import ( TMDb, TVDb, has_provider, has_provider_support, provider_factory, ) def test_has_provider__true():
64
64
29
7
57
jkwill87/mapi
tests/providers/test_providers.py
Python
test_has_provider__true
test_has_provider__true
17
19
17
17
067b87978a68c5a66aa578486b62160c53ee93e6
bigcode/the-stack
train
ef500ab209407468eb4832e7
train
class
class NoVariablesFile(LoFError): def __init__(self, path: str, *args, **kwargs): default_msg = f"No variables file found on passed path {path}" if not args: args = (default_msg,) super().__init__(*args, **kwargs)
class NoVariablesFile(LoFError):
def __init__(self, path: str, *args, **kwargs): default_msg = f"No variables file found on passed path {path}" if not args: args = (default_msg,) super().__init__(*args, **kwargs)
): def __init__(self, path: str, *args, **kwargs): default_msg = f"No template file found on passed path {path}" if not args: args = (default_msg,) super().__init__(*args, **kwargs) class NoVariablesFile(LoFError):
64
64
63
9
55
mkaraev/lof
lof/errors.py
Python
NoVariablesFile
NoVariablesFile
13
18
13
13
b968e515a7dadacbbee455cc92c63cbe0b846a2d
bigcode/the-stack
train
c64580b005c93a71b7978e26
train
class
class NoTemplate(LoFError): def __init__(self, path: str, *args, **kwargs): default_msg = f"No template file found on passed path {path}" if not args: args = (default_msg,) super().__init__(*args, **kwargs)
class NoTemplate(LoFError):
def __init__(self, path: str, *args, **kwargs): default_msg = f"No template file found on passed path {path}" if not args: args = (default_msg,) super().__init__(*args, **kwargs)
class LoFError(Exception): pass class NoTemplate(LoFError):
17
64
62
8
8
mkaraev/lof
lof/errors.py
Python
NoTemplate
NoTemplate
5
10
5
5
59f418cb91761ffa7fcbe73064cf727c050f0eea
bigcode/the-stack
train
9f71c701b463b9f6e5a9fb74
train
class
class LoFError(Exception): pass
class LoFError(Exception):
pass
class LoFError(Exception):
6
64
9
6
0
mkaraev/lof
lof/errors.py
Python
LoFError
LoFError
1
2
1
1
b6da6f43659f29104d75eff7dba3feee417d3fda
bigcode/the-stack
train
a7ad462d56608c6d7c60b6cd
train
class
class SMTPTests(unittest.TestCase): def setUp(self): '''Called at the start of each test, ensures that the SMTP server is running. ''' here = os.getcwd() topdir = here.rstrip('_trial_temp') self.rundir = os.path.join(topdir, 'run') self.pidfile = os.path.join(...
class SMTPTests(unittest.TestCase):
def setUp(self): '''Called at the start of each test, ensures that the SMTP server is running. ''' here = os.getcwd() topdir = here.rstrip('_trial_temp') self.rundir = os.path.join(topdir, 'run') self.pidfile = os.path.join(self.rundir, 'bridgedb.pid') ...
text '%s'." "Full message is:\n %s" % (text, message)) def checkNoMessageReceived(self, timeoutInSecs=2.0): try: self.message_queue.get(block=True, timeout=timeoutInSecs) except Queue.Empty: ...
228
228
761
7
221
emmapeel2/bridgedb
bridgedb/test/test_smtp.py
Python
SMTPTests
SMTPTests
125
206
125
125
2f0d1e4a8301667d70f178bbe372e00290de6ea8
bigcode/the-stack
train
95a37242d6b4485a6261e29c
train
class
class EmailServer(SMTPServer): def process_message(self, peer, mailfrom, rcpttos, data): ''' Overridden from SMTP server, called whenever a message is received''' self.message_queue.put(data) def thread_proc(self): ''' This function runs in thread, and will continue looping unti...
class EmailServer(SMTPServer):
def process_message(self, peer, mailfrom, rcpttos, data): ''' Overridden from SMTP server, called whenever a message is received''' self.message_queue.put(data) def thread_proc(self): ''' This function runs in thread, and will continue looping until the _stop Event object is set...
test%d@127.0.0.1" # Minimum value used to parameterise FROM_ADDRESS_TEMPLATE MIN_FROM_ADDRESS = 1 # Max value used to parameterise FROM_ADDRESS_TEMPLATE. Needs to be pretty big # to reduce the chance of collisions MAX_FROM_ADDRESS = 10**8 TO_ADDRESS = "bridges@torproject.org" MESSAGE_TEMPLATE = """From: %s To: %s Subje...
173
173
579
8
164
emmapeel2/bridgedb
bridgedb/test/test_smtp.py
Python
EmailServer
EmailServer
46
108
46
46
9a96a9123a41f86481a571b6727593097c763627
bigcode/the-stack
train
f61c65aba8dc6616d5a2afc5
train
function
def sendMail(fromAddress): #print("Connecting to %s:%d" # % (BRIDGEDB_SMTP_SERVER_ADDRESS, BRIDGEDB_SMTP_SERVER_PORT)) client = smtplib.SMTP(BRIDGEDB_SMTP_SERVER_ADDRESS, BRIDGEDB_SMTP_SERVER_PORT) client.set_debuglevel(SMTP_DEBUG_LEVEL) #print("Sending mail TO:%s, FR...
def sendMail(fromAddress): #print("Connecting to %s:%d" # % (BRIDGEDB_SMTP_SERVER_ADDRESS, BRIDGEDB_SMTP_SERVER_PORT))
client = smtplib.SMTP(BRIDGEDB_SMTP_SERVER_ADDRESS, BRIDGEDB_SMTP_SERVER_PORT) client.set_debuglevel(SMTP_DEBUG_LEVEL) #print("Sending mail TO:%s, FROM:%s" # % (TO_ADDRESS, fromAddress)) result = client.sendmail(fromAddress, TO_ADDRESS, ME...
except Queue.Empty: return True assert False, "Found a message in the queue, but expected none" def sendMail(fromAddress): #print("Connecting to %s:%d" # % (BRIDGEDB_SMTP_SERVER_ADDRESS, BRIDGEDB_SMTP_SERVER_PORT))
64
64
141
40
24
emmapeel2/bridgedb
bridgedb/test/test_smtp.py
Python
sendMail
sendMail
110
122
110
112
c69fea6fd628ee28d8abc218ba9e54c8f3a4fea8
bigcode/the-stack
train
8ccc27e2c7d0e88f82dfc1da
train
function
def test_list_projects_method_raise_exeception_in_AzurePersistor(): def mocked_init(self, *args, **kwargs): self._project_and_model_from_filename = \ lambda x: {'blob_name': ('project',)}[x] self.blob_client = Object() # noinspection PyUnusedLocal def mocked_list_blobs( ...
def test_list_projects_method_raise_exeception_in_AzurePersistor():
def mocked_init(self, *args, **kwargs): self._project_and_model_from_filename = \ lambda x: {'blob_name': ('project',)}[x] self.blob_client = Object() # noinspection PyUnusedLocal def mocked_list_blobs( container_name, prefix=None ): ...
_list_blobs with mock.patch.object(persistor.AzurePersistor, "__init__", mocked_init): result = persistor.AzurePersistor("").list_projects() assert result == ['project'] # noinspection PyPep8Naming def test_list_projects_method_raise_exeception_in_AzurePersistor():
64
64
139
15
48
weizhenzhao/rasa_nlu
tests/base/test_persistor.py
Python
test_list_projects_method_raise_exeception_in_AzurePersistor
test_list_projects_method_raise_exeception_in_AzurePersistor
121
139
121
121
8f68dd82b46a3154e88fce54ff99a62d9b445e07
bigcode/the-stack
train
ea067cac09a0e741bee3c414
train
function
@mock_s3 def test_list_projects_method_in_AWSPersistor(component_builder, tmpdir): # artificially create a persisted model _config = utilities.base_test_conf("keyword") os.environ["BUCKET_NAME"] = 'rasa-test' os.environ["AWS_DEFAULT_REGION"] = 'us-east-1' (trained, _, persisted_path) = train( ...
@mock_s3 def test_list_projects_method_in_AWSPersistor(component_builder, tmpdir): # artificially create a persisted model
_config = utilities.base_test_conf("keyword") os.environ["BUCKET_NAME"] = 'rasa-test' os.environ["AWS_DEFAULT_REGION"] = 'us-east-1' (trained, _, persisted_path) = train( _config, data="data/test/demo-rasa-small.json", path=tmpdir.strpath, project='mytestproject', ...
ersistor_class_has_list_projects_method(): with pytest.raises(NotImplementedError): persistor.Persistor().list_projects() # noinspection PyPep8Naming @mock_s3 def test_list_projects_method_in_AWSPersistor(component_builder, tmpdir): # artificially create a persisted model
64
64
186
30
33
weizhenzhao/rasa_nlu
tests/base/test_persistor.py
Python
test_list_projects_method_in_AWSPersistor
test_list_projects_method_in_AWSPersistor
20
40
20
22
968b25e799cfa8ac50afe8a144473297142241e4
bigcode/the-stack
train
4e2df7cbf721de9ff7ffe69a
train
function
def test_list_projects_method_raise_exeception_in_GCSPersistor(): # noinspection PyUnusedLocal def mocked_init(self, *args, **kwargs): self._project_and_model_from_filename = \ lambda x: {'blob_name': ('project',)}[x] self.bucket = Object() def mocked_list_blobs(): ...
def test_list_projects_method_raise_exeception_in_GCSPersistor(): # noinspection PyUnusedLocal
def mocked_init(self, *args, **kwargs): self._project_and_model_from_filename = \ lambda x: {'blob_name': ('project',)}[x] self.bucket = Object() def mocked_list_blobs(): raise ValueError self.bucket.list_blobs = mocked_list_blobs with mock.patch.object...
CSPersistor, "__init__", mocked_init): result = persistor.GCSPersistor("").list_projects() assert result == ['project'] # noinspection PyPep8Naming def test_list_projects_method_raise_exeception_in_GCSPersistor(): # noinspection PyUnusedLocal
64
64
130
24
39
weizhenzhao/rasa_nlu
tests/base/test_persistor.py
Python
test_list_projects_method_raise_exeception_in_GCSPersistor
test_list_projects_method_raise_exeception_in_GCSPersistor
76
91
76
77
05171a3851fe6c4711e18dfbd6d257439b00490f
bigcode/the-stack
train
ee38a4b5d83d9e82a4926ed9
train
class
class Object(object): pass
class Object(object):
pass
import mock import os import pytest from moto import mock_s3 from rasa_nlu import persistor, train from tests import utilities class Object(object):
35
64
7
4
30
weizhenzhao/rasa_nlu
tests/base/test_persistor.py
Python
Object
Object
10
11
10
10
f49b1f8e8507482a8e1dc518302fd9e07fe1db42
bigcode/the-stack
train
97913e81dcf4e4a8043a92b0
train
function
def test_list_projects_method_in_GCSPersistor(): # noinspection PyUnusedLocal def mocked_init(self, *args, **kwargs): self._project_and_model_from_filename = \ lambda x: {'blob_name': ('project',)}[x] self.bucket = Object() def mocked_list_blobs(): filter_result ...
def test_list_projects_method_in_GCSPersistor(): # noinspection PyUnusedLocal
def mocked_init(self, *args, **kwargs): self._project_and_model_from_filename = \ lambda x: {'blob_name': ('project',)}[x] self.bucket = Object() def mocked_list_blobs(): filter_result = Object() filter_result.name = 'blob_name' return filter_...
1' awspersistor = persistor.AWSPersistor("rasa-test") result = awspersistor.list_projects() assert result == [] # noinspection PyPep8Naming def test_list_projects_method_in_GCSPersistor(): # noinspection PyUnusedLocal
64
64
143
20
43
weizhenzhao/rasa_nlu
tests/base/test_persistor.py
Python
test_list_projects_method_in_GCSPersistor
test_list_projects_method_in_GCSPersistor
55
72
55
56
35aa876ac40c60937dfa8c782dfb484f1730a26b
bigcode/the-stack
train
c843a9f5555f2e2d1464cdb6
train
function
def test_list_projects_method_in_AzurePersistor(): # noinspection PyUnusedLocal def mocked_init(self, *args, **kwargs): self._project_and_model_from_filename = \ lambda x: {'blob_name': ('project',)}[x] self.blob_client = Object() self.container_name = 'test' # noins...
def test_list_projects_method_in_AzurePersistor(): # noinspection PyUnusedLocal
def mocked_init(self, *args, **kwargs): self._project_and_model_from_filename = \ lambda x: {'blob_name': ('project',)}[x] self.blob_client = Object() self.container_name = 'test' # noinspection PyUnusedLocal def mocked_list_blobs( container_name, ...
.patch.object(persistor.GCSPersistor, "__init__", mocked_init): result = persistor.GCSPersistor("").list_projects() assert result == [] # noinspection PyPep8Naming def test_list_projects_method_in_AzurePersistor(): # noinspection PyUnusedLocal
64
64
168
19
44
weizhenzhao/rasa_nlu
tests/base/test_persistor.py
Python
test_list_projects_method_in_AzurePersistor
test_list_projects_method_in_AzurePersistor
95
117
95
96
8f9c26465ada06948b7ce210191d4fdaeafae95c
bigcode/the-stack
train
77844730893efa3e3370127f
train
function
@mock_s3 def test_list_projects_method_raise_exeception_in_AWSPersistor(): os.environ["AWS_DEFAULT_REGION"] = 'us-east-1' awspersistor = persistor.AWSPersistor("rasa-test") result = awspersistor.list_projects() assert result == []
@mock_s3 def test_list_projects_method_raise_exeception_in_AWSPersistor():
os.environ["AWS_DEFAULT_REGION"] = 'us-east-1' awspersistor = persistor.AWSPersistor("rasa-test") result = awspersistor.list_projects() assert result == []
or = persistor.AWSPersistor(os.environ["BUCKET_NAME"]) result = awspersistor.list_projects() assert result == ['mytestproject'] # noinspection PyPep8Naming @mock_s3 def test_list_projects_method_raise_exeception_in_AWSPersistor():
64
64
69
21
42
weizhenzhao/rasa_nlu
tests/base/test_persistor.py
Python
test_list_projects_method_raise_exeception_in_AWSPersistor
test_list_projects_method_raise_exeception_in_AWSPersistor
44
51
44
45
adeafb7c3a31afb10419909339532bc16ecd402c
bigcode/the-stack
train
81e91b107fb898ad1cf2b3df
train
function
def test_if_persistor_class_has_list_projects_method(): with pytest.raises(NotImplementedError): persistor.Persistor().list_projects()
def test_if_persistor_class_has_list_projects_method():
with pytest.raises(NotImplementedError): persistor.Persistor().list_projects()
import mock import os import pytest from moto import mock_s3 from rasa_nlu import persistor, train from tests import utilities class Object(object): pass def test_if_persistor_class_has_list_projects_method():
50
64
30
12
37
weizhenzhao/rasa_nlu
tests/base/test_persistor.py
Python
test_if_persistor_class_has_list_projects_method
test_if_persistor_class_has_list_projects_method
14
16
14
14
8ee92f736b649d28d034b7c33f2efac58bee42da
bigcode/the-stack
train
aae6dee14627c19cfbb2d17c
train
class
class TestURLTrafaret: def test_url(self): res = t.URL.check('http://example.net/resource/?param=value#anchor') assert res == 'http://example.net/resource/?param=value#anchor' res = str(t.URL.check('http://пример.рф/resource/?param=value#anchor')) assert res == 'http://xn--e1afmkfd....
class TestURLTrafaret:
def test_url(self): res = t.URL.check('http://example.net/resource/?param=value#anchor') assert res == 'http://example.net/resource/?param=value#anchor' res = str(t.URL.check('http://пример.рф/resource/?param=value#anchor')) assert res == 'http://xn--e1afmkfd.xn--p1ai/resource/?para...
return ( '2001:0db8:z000:0042:0000:8a2e:0370:7334', '2001:cdba:0:0:::0:0:3257:9652', '2001:cdba::3257:::9652', '127.0.0.1', ':ffaa:' ) class TestURLTrafaret:
91
91
306
7
84
Deepwalker/trafaret_not_forked
tests/test_internet.py
Python
TestURLTrafaret
TestURLTrafaret
54
76
54
54
2c6473f5aaca5dcc652874175c9eabc608460ad8
bigcode/the-stack
train
4047f5d044a680db531b0fe6
train
class
class TestEmailTrafaret: def test_email(self): res = t.Email.check('someone@example.net') assert res == 'someone@example.net' res = extract_error(t.Email, 'someone@example') # try without domain-part assert res == 'value is not a valid email address' res = str(t.Email.check(...
class TestEmailTrafaret:
def test_email(self): res = t.Email.check('someone@example.net') assert res == 'someone@example.net' res = extract_error(t.Email, 'someone@example') # try without domain-part assert res == 'value is not a valid email address' res = str(t.Email.check('someone@пример.рф')) # t...
://user:password@example.net/resource/?param=value#anchor')) assert res == 'http://user:password@example.net/resource/?param=value#anchor' def test_bad_str(self): with pytest.raises(t.DataError): t.URL.check(b'http://\xd0\xbf\xd1\x80\xd0\xb8\xd0\xbc\xd0\xb5\xd1\x80.\xd1\xd1\x84') class ...
95
95
318
7
88
Deepwalker/trafaret_not_forked
tests/test_internet.py
Python
TestEmailTrafaret
TestEmailTrafaret
79
100
79
79
f1f4b9ff4df23fe97112f36d9ff7ebd46da35b56
bigcode/the-stack
train
2a146852f8db8141c5cbf3d2
train
function
@pytest.fixture() def invalid_ips_v4(): return ( '32.64.128.256', '2001:0db8:0000:0042:0000:8a2e:0370:7334', '192.168.1.1 ', )
@pytest.fixture() def invalid_ips_v4():
return ( '32.64.128.256', '2001:0db8:0000:0042:0000:8a2e:0370:7334', '192.168.1.1 ', )
aret as t from trafaret import extract_error @pytest.fixture() def valid_ips_v4(): return ( '127.0.0.1', '8.8.8.8', '192.168.1.1', ) @pytest.fixture() def invalid_ips_v4():
64
64
63
9
55
Deepwalker/trafaret_not_forked
tests/test_internet.py
Python
invalid_ips_v4
invalid_ips_v4
16
22
16
17
6c336db097386b3adfb4e7a0b34030ce0e54a069
bigcode/the-stack
train
71004047bb07b8f5dc607b77
train
class
class TestHexTrafaret: def test_hex(self): res = t.Hex().check('bbd3ec7776d5684d87') assert res == 'bbd3ec7776d5684d87' res = t.Hex().check('47CCB8AEEC972') assert res == '47ccb8aeec972' res = extract_error(t.Hex(), 'apple') assert res == 'does not match pattern ^[0-9...
class TestHexTrafaret:
def test_hex(self): res = t.Hex().check('bbd3ec7776d5684d87') assert res == 'bbd3ec7776d5684d87' res = t.Hex().check('47CCB8AEEC972') assert res == '47ccb8aeec972' res = extract_error(t.Hex(), 'apple') assert res == 'does not match pattern ^[0-9a-f]*$' res = e...
True res = extract_error(t.Email, 123) assert res == 'value is not a string' def test_bad_str(self): with pytest.raises(t.DataError): t.Email.check(b'ahha@\xd0\xbf\xd1\x80\xd0\xb8\xd0\xbc\xd0\xb5\xd1\x80.\xd1\xd1\x84') class TestHexTrafaret:
87
87
292
7
80
Deepwalker/trafaret_not_forked
tests/test_internet.py
Python
TestHexTrafaret
TestHexTrafaret
103
127
103
103
f96d2d884a8094b16c240645bd99e45e71ae79d1
bigcode/the-stack
train
d0e89c388ef47a15801e9c6a
train
function
@pytest.fixture() def valid_ips_v4(): return ( '127.0.0.1', '8.8.8.8', '192.168.1.1', )
@pytest.fixture() def valid_ips_v4():
return ( '127.0.0.1', '8.8.8.8', '192.168.1.1', )
# -*- coding: utf-8 -*- import pytest import trafaret as t from trafaret import extract_error @pytest.fixture() def valid_ips_v4():
33
64
44
9
23
Deepwalker/trafaret_not_forked
tests/test_internet.py
Python
valid_ips_v4
valid_ips_v4
7
13
7
8
024c4b39dcbe6647725de5047501c95b4fbaebad
bigcode/the-stack
train
38a14bc03e9407afb6e36783
train
function
@pytest.fixture() def valid_ips_v6(): return ( '2001:0db8:0000:0042:0000:8a2e:0370:7334', '2001:0Db8:0000:0042:0000:8A2e:0370:7334', '2001:cdba:0:0:0:0:3257:9652', '2001:cdba::3257:9652', 'fe80::', '::', '::1', '2001:db8::', 'ffaa::', '...
@pytest.fixture() def valid_ips_v6():
return ( '2001:0db8:0000:0042:0000:8a2e:0370:7334', '2001:0Db8:0000:0042:0000:8A2e:0370:7334', '2001:cdba:0:0:0:0:3257:9652', '2001:cdba::3257:9652', 'fe80::', '::', '::1', '2001:db8::', 'ffaa::', '::ffff:255.255.255.0', '2001:d...
(): return ( '32.64.128.256', '2001:0db8:0000:0042:0000:8a2e:0370:7334', '192.168.1.1 ', ) @pytest.fixture() def valid_ips_v6():
64
64
182
9
55
Deepwalker/trafaret_not_forked
tests/test_internet.py
Python
valid_ips_v6
valid_ips_v6
25
40
25
26
1c2a982e9721fb85d85407a3b192333d19efdac6
bigcode/the-stack
train
9a0984978ff0c13a5c963b29
train
function
@pytest.fixture() def invalid_ips_v6(): return ( '2001:0db8:z000:0042:0000:8a2e:0370:7334', '2001:cdba:0:0:::0:0:3257:9652', '2001:cdba::3257:::9652', '127.0.0.1', ':ffaa:' )
@pytest.fixture() def invalid_ips_v6():
return ( '2001:0db8:z000:0042:0000:8a2e:0370:7334', '2001:cdba:0:0:::0:0:3257:9652', '2001:cdba::3257:::9652', '127.0.0.1', ':ffaa:' )
8::', 'ffaa::', '::ffff:255.255.255.0', '2001:db8:3:4::192.168.1.1', 'fe80::1:2%en0', ) @pytest.fixture() def invalid_ips_v6():
64
64
93
9
55
Deepwalker/trafaret_not_forked
tests/test_internet.py
Python
invalid_ips_v6
invalid_ips_v6
43
51
43
44
64619b5df2c73081cbe2eed6280cbb9a7ffc4198
bigcode/the-stack
train
cfc501f97422412dea662d38
train
class
class TestURLSafeTrafaret: def test_urlsafe(self): res = t.URLSafe().check('sB3ny_Vmu-C') assert res == 'sB3ny_Vmu-C' res = extract_error(t.URLSafe(), 'app/le') assert res == 'does not match pattern ^[0-9A-Za-z-_]*$' res = extract_error(t.URLSafe(), '') assert res == ...
class TestURLSafeTrafaret:
def test_urlsafe(self): res = t.URLSafe().check('sB3ny_Vmu-C') assert res == 'sB3ny_Vmu-C' res = extract_error(t.URLSafe(), 'app/le') assert res == 'does not match pattern ^[0-9A-Za-z-_]*$' res = extract_error(t.URLSafe(), '') assert res == 'blank value is not allowed...
=6), '1234567') assert res == 'String is longer than 6 characters' res = t.Hex(min_length=0, max_length=6, allow_blank=True).check('abc') assert res == 'abc' def test_repr(self): res = t.Hex() assert repr(res) == '<Hex>' class TestURLSafeTrafaret:
80
81
272
8
72
Deepwalker/trafaret_not_forked
tests/test_internet.py
Python
TestURLSafeTrafaret
TestURLSafeTrafaret
130
152
130
130
74f4b635658379a7f83b3c2f6d1be0503c9042e8
bigcode/the-stack
train
01bdc548eaf84c1fc105eeaa
train
function
def test_ipv4(valid_ips_v4, invalid_ips_v4): ip = t.IPv4 for data in valid_ips_v4: result = ip(data) assert result == data for data in invalid_ips_v4: with pytest.raises(t.DataError): ip(data)
def test_ipv4(valid_ips_v4, invalid_ips_v4):
ip = t.IPv4 for data in valid_ips_v4: result = ip(data) assert result == data for data in invalid_ips_v4: with pytest.raises(t.DataError): ip(data)
_length=0, max_length=6, allow_blank=True).check('a_c') assert res == 'a_c' def test_repr(self): res = t.URLSafe() assert repr(res) == '<URLSafe>' def test_ipv4(valid_ips_v4, invalid_ips_v4):
63
64
64
14
49
Deepwalker/trafaret_not_forked
tests/test_internet.py
Python
test_ipv4
test_ipv4
155
164
155
155
7027b28c9165e6bd7a4174c0c65bf2b42972c51d
bigcode/the-stack
train
a05e0de46552c1572370a19c
train
function
def test_ipv6(valid_ips_v6, invalid_ips_v6): ip = t.IPv6 for data in valid_ips_v6: result = ip(data) assert result == data for data in invalid_ips_v6: with pytest.raises(t.DataError): ip(data)
def test_ipv6(valid_ips_v6, invalid_ips_v6):
ip = t.IPv6 for data in valid_ips_v6: result = ip(data) assert result == data for data in invalid_ips_v6: with pytest.raises(t.DataError): ip(data)
ip = t.IPv4 for data in valid_ips_v4: result = ip(data) assert result == data for data in invalid_ips_v4: with pytest.raises(t.DataError): ip(data) def test_ipv6(valid_ips_v6, invalid_ips_v6):
64
64
64
14
50
Deepwalker/trafaret_not_forked
tests/test_internet.py
Python
test_ipv6
test_ipv6
167
176
167
167
e29b6e2ae4eeb10747d5a42b7d0abaf51a47d082
bigcode/the-stack
train
2025a3af3994fba938746ef0
train
class
class InlineResponse503(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). ...
class InlineResponse503(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a c...
""" Ory APIs Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. # noqa: E501 The version of the OpenAPI document: v0.0.1-alpha.19 Contact: support@ory.sh Generated by: htt...
202
256
1,958
7
194
tobbbles/sdk
clients/client/python/ory_client/model/inline_response503.py
Python
InlineResponse503
InlineResponse503
34
262
34
34
c0cec8053340b02c33614fadff97598e00bcb5f6
bigcode/the-stack
train
ea77ca3acc5909f3f5b82fb9
train
function
def getch(message=None): if message: print(message) getchfunc = _Getch() return getchfunc()
def getch(message=None):
if message: print(message) getchfunc = _Getch() return getchfunc()
setattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() def getch(message=None):
64
64
29
6
58
mathandy/EarThoseChords
getch.py
Python
getch
getch
52
56
52
52
f9b29c141142deba7277223b0f4236667f6f4e83
bigcode/the-stack
train
3dc8e4e7812218eca4ced535
train
class
class _GetchUnix: def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: ...
class _GetchUnix:
def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr...
from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix:
64
64
100
6
58
mathandy/EarThoseChords
getch.py
Python
_GetchUnix
_GetchUnix
27
40
27
27
c7a36770cc1c9a6378c6013f4811fa3afe0afac9
bigcode/the-stack
train
84dc2d2824d872c073ae0f84
train
class
class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch()
class _GetchWindows:
def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch()
() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows:
64
64
40
6
57
mathandy/EarThoseChords
getch.py
Python
_GetchWindows
_GetchWindows
43
49
43
43
ca76ae8646cf0bedd61f23e2ba87755e0e22bc20
bigcode/the-stack
train
473ecb8ff878c69f63ce994f
train
class
class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl()
class _Getch:
"""Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl()
doesn't require the user to press enter. Credit: https://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user """ # For python 3 compatibility from __future__ import division, absolute_import, print_function try: input = raw_input except: pass class _Getch:
64
64
69
5
58
mathandy/EarThoseChords
getch.py
Python
_Getch
_Getch
15
24
15
15
0d9da1c6d1ac6778ec7c38ba2ee5c8be8e16e524
bigcode/the-stack
train
7a35eb066aeab445ad4c9d09
train
class
class CreateEnvironmentVariableV2Response(SdkResponse): """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. ...
class CreateEnvironmentVariableV2Response(SdkResponse):
""" Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { ...
# coding: utf-8 import pprint import re import six from huaweicloudsdkcore.sdk_response import SdkResponse class CreateEnvironmentVariableV2Response(SdkResponse):
41
256
1,298
12
28
wuchen-huawei/huaweicloud-sdk-python-v3
huaweicloud-sdk-apig/huaweicloudsdkapig/v2/model/create_environment_variable_v2_response.py
Python
CreateEnvironmentVariableV2Response
CreateEnvironmentVariableV2Response
12
218
12
14
a2306add8885a5e6a3ca42537c16b104520cc64a
bigcode/the-stack
train
ba5a92582fb7f594f472cac8
train
class
class LoveUtilsConfig(AppConfig): name = 'love_utils' verbose_name = 'Love Utils'
class LoveUtilsConfig(AppConfig):
name = 'love_utils' verbose_name = 'Love Utils'
# -*- coding: utf-8 -*- from django.apps import AppConfig class LoveUtilsConfig(AppConfig):
22
64
22
7
14
ailove-dev/django-love-utils
love_utils/apps.py
Python
LoveUtilsConfig
LoveUtilsConfig
6
8
6
6
1de48c0a51f85a49f10ce4281f9b5ffe76aaa416
bigcode/the-stack
train
89d97939d21677e2a0419876
train
class
@make_properties class MapDimShuffle(transformation.SingleStateTransformation): """ Implements the map-dim shuffle transformation. MapDimShuffle takes a map and a list of params. It reorders the dimensions in the map such that it matches the list. """ map_entry = transformation.Pattern...
@make_properties class MapDimShuffle(transformation.SingleStateTransformation):
""" Implements the map-dim shuffle transformation. MapDimShuffle takes a map and a list of params. It reorders the dimensions in the map such that it matches the list. """ map_entry = transformation.PatternNode(nodes.MapEntry) # Properties parameters = ShapeProperty(dtype=list...
dfg import SDFG from dace.sdfg import nodes from dace.sdfg import utils as sdutil from dace.sdfg.state import SDFGState from dace.transformation import transformation from dace.properties import make_properties, ShapeProperty @make_properties class MapDimShuffle(transformation.SingleStateTransformation):
69
69
231
14
54
Walon1998/dace
dace/transformation/dataflow/map_dim_shuffle.py
Python
MapDimShuffle
MapDimShuffle
12
42
12
13
cd0f9af5cfeef0f90b961a2f1e02663565d297e1
bigcode/the-stack
train
49b7c64b4fc58722ae971432
train
class
class Migration(migrations.Migration): dependencies = [ ("core", "0002_tdsdata_file_name"), ] operations = [ migrations.CreateModel( name="TemporalData", fields=[ ( "id", models.AutoField( ...
class Migration(migrations.Migration):
dependencies = [ ("core", "0002_tdsdata_file_name"), ] operations = [ migrations.CreateModel( name="TemporalData", fields=[ ( "id", models.AutoField( auto_created=True, ...
# Generated by Django 3.1.1 on 2021-09-21 11:14 from django.db import migrations, models class Migration(migrations.Migration):
38
64
134
7
30
Hayashi-Yudai/scan_system
core/migrations/0003_temporaldata.py
Python
Migration
Migration
6
31
6
7
865581e40a67a878a66781b170e21de52000996c
bigcode/the-stack
train
884e84ef34eeca7eecf2988d
train
function
def register_blueprints(app): from app.base.routes import blueprint as base app.register_blueprint(forms) app.register_blueprint(ui) app.register_blueprint(home) app.register_blueprint(tables) app.register_blueprint(base)
def register_blueprints(app):
from app.base.routes import blueprint as base app.register_blueprint(forms) app.register_blueprint(ui) app.register_blueprint(home) app.register_blueprint(tables) app.register_blueprint(base)
forms from app.ui.routes import blueprint as ui from app.home.routes import blueprint as home from app.tables.routes import blueprint as tables db = SQLAlchemy() login_manager = LoginManager() def register_extensions(app): db.init_app(app) login_manager.init_app(app) def register_blueprints(app):
64
64
52
6
58
playerla/flask-gentelella
app/__init__.py
Python
register_blueprints
register_blueprints
21
27
21
21
272b36db5025ad255465412adf41ad3a109581ad
bigcode/the-stack
train
6f6d4780aacc5267ad35857c
train
function
def configure_database(app): @app.before_first_request def initialize_database(): db.create_all() @app.teardown_request def shutdown_session(exception=None): db.session.remove()
def configure_database(app): @app.before_first_request
def initialize_database(): db.create_all() @app.teardown_request def shutdown_session(exception=None): db.session.remove()
def register_blueprints(app): from app.base.routes import blueprint as base app.register_blueprint(forms) app.register_blueprint(ui) app.register_blueprint(home) app.register_blueprint(tables) app.register_blueprint(base) def configure_database(app): @app.before_first_request
64
64
41
12
52
playerla/flask-gentelella
app/__init__.py
Python
configure_database
configure_database
30
38
30
32
d406a4b915fb6f0b3414ee1dfb87a25c78e2c6f6
bigcode/the-stack
train
86c4c3a6dbfd7a317f5f6722
train
function
def apply_themes(app): """ Add support for themes. If DEFAULT_THEME is set then all calls to url_for('static', filename='') will modfify the url to include the theme name The theme parameter can be set directly in url_for as well: ex. url_for('static', filename='', theme='') If ...
def apply_themes(app):
""" Add support for themes. If DEFAULT_THEME is set then all calls to url_for('static', filename='') will modfify the url to include the theme name The theme parameter can be set directly in url_for as well: ex. url_for('static', filename='', theme='') If the file cannot be foun...
@app.before_first_request def initialize_database(): db.create_all() @app.teardown_request def shutdown_session(exception=None): db.session.remove() def configure_logs(app): basicConfig(filename='error.log', level=DEBUG) logger = getLogger() logger.addHandler(StreamHandler())...
71
71
237
6
65
playerla/flask-gentelella
app/__init__.py
Python
apply_themes
apply_themes
47
74
47
47
42fb8319f6ae934810c04c026ca831810198930f
bigcode/the-stack
train
ea8ac5665c379cb80dc451d8
train
function
def register_extensions(app): db.init_app(app) login_manager.init_app(app)
def register_extensions(app):
db.init_app(app) login_manager.init_app(app)
, getLogger, StreamHandler from os import path from app.forms.routes import blueprint as forms from app.ui.routes import blueprint as ui from app.home.routes import blueprint as home from app.tables.routes import blueprint as tables db = SQLAlchemy() login_manager = LoginManager() def register_extensions(app):
64
64
18
5
59
playerla/flask-gentelella
app/__init__.py
Python
register_extensions
register_extensions
16
18
16
16
0796b089adc9faa9b2d0aa05182346e9a45a9a58
bigcode/the-stack
train
624142aae230b4420707acbc
train
function
def create_app(config, selenium=False): app = Flask(__name__, static_folder='base/static') app.config.from_object(config) if selenium: app.config['LOGIN_DISABLED'] = True register_extensions(app) register_blueprints(app) configure_database(app) configure_logs(app) apply_themes(ap...
def create_app(config, selenium=False):
app = Flask(__name__, static_folder='base/static') app.config.from_object(config) if selenium: app.config['LOGIN_DISABLED'] = True register_extensions(app) register_blueprints(app) configure_database(app) configure_logs(app) apply_themes(app) return app
) if themename: theme_file = "{}/{}".format(themename, values.get('filename', '')) if path.isfile(path.join(app.static_folder, theme_file)): values['filename'] = theme_file return url_for(endpoint, **values) def create_app(config, selenium=False):
64
64
73
8
56
playerla/flask-gentelella
app/__init__.py
Python
create_app
create_app
77
87
77
77
853a4289c286f944955c8e0d2fe56258a6382e43
bigcode/the-stack
train
96d3974d063a8a71407477e5
train
function
def configure_logs(app): basicConfig(filename='error.log', level=DEBUG) logger = getLogger() logger.addHandler(StreamHandler())
def configure_logs(app):
basicConfig(filename='error.log', level=DEBUG) logger = getLogger() logger.addHandler(StreamHandler())
print(home) app.register_blueprint(tables) app.register_blueprint(base) def configure_database(app): @app.before_first_request def initialize_database(): db.create_all() @app.teardown_request def shutdown_session(exception=None): db.session.remove() def configure_logs(app):
64
64
30
5
59
playerla/flask-gentelella
app/__init__.py
Python
configure_logs
configure_logs
41
44
41
41
eacab06f4b5c7af27f7162a958874a07b4bfbb47
bigcode/the-stack
train
df7663c931f913d0cc0f7f5d
train
class
class Interpolate_twocol(object): def __init__( self, y=None, # y-grid z=None, # z-grid bs=None, # buoyancy profile in the south bn=None, # buoyancy profile in the north ): # initialize grid: if isinstance(y, np.ndarray): self.y = y else: raise Type...
class Interpolate_twocol(object):
def __init__( self, y=None, # y-grid z=None, # z-grid bs=None, # buoyancy profile in the south bn=None, # buoyancy profile in the north ): # initialize grid: if isinstance(y, np.ndarray): self.y = y else: raise TypeError('y needs to be numpy array p...
''' A class to interpolate the buoyancy field in the North along lines with constant slope - only to make fancy plots ''' import sys import numpy as np from scipy.optimize import brenth from pymoc.utils import gridit, make_func class Interpolate_twocol(object):
59
166
555
7
51
pymoc/pymoc_uf
src/pymoc/plotting/interp_twocol.py
Python
Interpolate_twocol
Interpolate_twocol
12
72
12
12
fd6966ce6caaecfd87b85e38da9351d0448cdc87
bigcode/the-stack
train
42e9bc4ad393cc4e2f787b61
train
function
def get_encoding(args): if '--output' in args: index = args.index('--output') try: encoding = args[index+1].lower() if encoding not in discord.Sink.valid_encodings: return return encoding except IndexError: return ...
def get_encoding(args):
if '--output' in args: index = args.index('--output') try: encoding = args[index+1].lower() if encoding not in discord.Sink.valid_encodings: return return encoding except IndexError: return else: return 'wa...
[index])) except IndexError: break except ValueError: break index += 1 if not users: return "You must provide at least one user, or multiple users separated by spaces." filters.update({'users': users}) return fi...
64
64
69
5
58
z404/discord.py
examples/receive_vc_audio.py
Python
get_encoding
get_encoding
44
55
44
44
11ce166bff12954ad90bec0c695934d35f0d29ec
bigcode/the-stack
train
a724d1ce4602f53fc43a36d9
train
class
class Client(discord.Client): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.connections = {voice.guild.id: voice for voice in self.voice_clients} self.playlists = {} self.commands = { '!start': self.start_recording, '!sto...
class Client(discord.Client):
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.connections = {voice.guild.id: voice for voice in self.voice_clients} self.playlists = {} self.commands = { '!start': self.start_recording, '!stop': self.stop_recording, ...
({'time': seconds}) if '--users' in args: users = [] index = args.index('--users')+1 while True: try: users.append(int(args[index])) except IndexError: break except ValueError: break in...
174
175
584
6
168
z404/discord.py
examples/receive_vc_audio.py
Python
Client
Client
58
130
58
58
2abb8b51d1c6b10914ea90f47d0d98bf7f859a00
bigcode/the-stack
train
9af337c77e48d120289c20b2
train
function
def vc_required(func): async def get_vc(self, msg): vc = await self.get_vc(msg) if not vc: return await func(self, msg, vc) return get_vc
def vc_required(func):
async def get_vc(self, msg): vc = await self.get_vc(msg) if not vc: return await func(self, msg, vc) return get_vc
import discord import os def vc_required(func):
11
64
48
5
5
z404/discord.py
examples/receive_vc_audio.py
Python
vc_required
vc_required
5
11
5
5
e828efc11f1057acb980e47381fe810aac02a743
bigcode/the-stack
train
a714e96cd921c42fa0de80d5
train
function
def args_to_filters(args): filters = {} if '--time' in args: index = args.index('--time') try: seconds = args[index+1] except IndexError: return "You must provide an amount of seconds for the time." try: seconds = int(seconds) ...
def args_to_filters(args):
filters = {} if '--time' in args: index = args.index('--time') try: seconds = args[index+1] except IndexError: return "You must provide an amount of seconds for the time." try: seconds = int(seconds) except ValueError: ...
import discord import os def vc_required(func): async def get_vc(self, msg): vc = await self.get_vc(msg) if not vc: return await func(self, msg, vc) return get_vc def args_to_filters(args):
60
64
182
6
53
z404/discord.py
examples/receive_vc_audio.py
Python
args_to_filters
args_to_filters
14
41
14
14
d93325d1cf601b673f12b709c1487806dbea4071
bigcode/the-stack
train
4cd570f41788234efce4c6e9
train
class
class KubernetesMgmtDriver(vnflcm_abstract_driver.VnflcmMgmtAbstractDriver): def __init__(self): self._init_flag() def get_type(self): return 'mgmt-drivers-kubernetes' def get_name(self): return 'mgmt-drivers-kubernetes' def get_description(self): return 'Tacker Kuber...
class KubernetesMgmtDriver(vnflcm_abstract_driver.VnflcmMgmtAbstractDriver):
def __init__(self): self._init_flag() def get_type(self): return 'mgmt-drivers-kubernetes' def get_name(self): return 'mgmt-drivers-kubernetes' def get_description(self): return 'Tacker Kubernetes VNFMgmt Driver' def instantiate_start(self, context, vnf_instance, ...
from tacker.db.nfvo import nfvo_db from tacker.nfvo.nfvo_plugin import NfvoPlugin from tacker import objects from tacker.vnflcm import utils as vnflcm_utils from tacker.vnfm.infra_drivers.openstack import heat_client as hc from tacker.vnfm.mgmt_drivers import vnflcm_abstract_driver CHECK_PV_AVAILABLE_RETRY = 5 CHECK_...
256
256
28,539
19
236
h1r0mu/tacker
samples/mgmt_driver/kubernetes_mgmt.py
Python
KubernetesMgmtDriver
KubernetesMgmtDriver
57
3,027
57
58
3c3cd5b1db296007e81171ba2d2b6bb192911752
bigcode/the-stack
train
added5a5718de204fac31c59
train
class
class WordpieceTokenizer(object): """Runs WordPiece tokenziation.""" def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=100): self.vocab = vocab self.unk_token = unk_token self.max_input_chars_per_word = max_input_chars_per_word def tokenize(self, text): ...
class WordpieceTokenizer(object):
"""Runs WordPiece tokenziation.""" def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=100): self.vocab = vocab self.unk_token = unk_token self.max_input_chars_per_word = max_input_chars_per_word def tokenize(self, text): """Tokenizes a piece of text into ...
cp <= 0x2FA1F)): # return True return False def _clean_text(self, text): """Performs invalid character removal and whitespace cleanup on text.""" output = [] for char in text: cp = ord(char) if cp == 0 or cp == 0xfffd or _is_control(char): ...
113
113
377
6
107
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
WordpieceTokenizer
WordpieceTokenizer
149
204
149
149
6b10742fcf3a10712678f537018b43dd72c0af12
bigcode/the-stack
train
9d2ca56c8298202526d4caca
train
class
class InputExample(object): def __init__(self, unique_id, text_a, text_b): self.unique_id = unique_id self.text_a = text_a self.text_b = text_b
class InputExample(object):
def __init__(self, unique_id, text_a, text_b): self.unique_id = unique_id self.text_a = text_a self.text_b = text_b
if cur_substr is None: is_bad = True break sub_tokens.append(cur_substr) start = end if is_bad: output_tokens.append(self.unk_token) else: output_tokens.extend(sub_tokens) ...
64
64
45
5
58
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
InputExample
InputExample
207
212
207
208
906da5735cdc11720bd41f3885f5cd7b0569a84f
bigcode/the-stack
train
59004b426a24530e7913ecfa
train
function
def _is_whitespace(char): """Checks whether `chars` is a whitespace character.""" # \t, \n, and \r are technically contorl characters but we treat them # as whitespace since they are generally considered as such. if char == " " or char == "\t" or char == "\n" or char == "\r": return True cat...
def _is_whitespace(char):
"""Checks whether `chars` is a whitespace character.""" # \t, \n, and \r are technically contorl characters but we treat them # as whitespace since they are generally considered as such. if char == " " or char == "\t" or char == "\n" or char == "\r": return True cat = unicodedata.category(ch...
self, unique_id, tokens, input_ids, input_mask, input_type_ids): self.unique_id = unique_id self.tokens = tokens self.input_ids = input_ids self.input_mask = input_mask self.input_type_ids = input_type_ids def _is_whitespace(char):
64
64
105
7
56
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
_is_whitespace
_is_whitespace
226
235
226
226
81b547112a8e0fd9773d3a508d963a9b6556f6bb
bigcode/the-stack
train
2c004c0766f14a3a2e5ede7d
train
function
def features_to_arrays(features): all_input_ids = [] all_input_mask = [] all_segment_ids = [] for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.input_type_ids) return (np.array(all_input...
def features_to_arrays(features):
all_input_ids = [] all_input_mask = [] all_segment_ids = [] for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.input_type_ids) return (np.array(all_input_ids, dtype='int32'), ...
m is None: text_a = line else: text_a = m.group(1) text_b = m.group(2) yield InputExample(unique_id=unique_id, text_a=text_a, text_b=text_b) unique_id += 1 def features_to_arrays(features):
64
64
96
6
57
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
features_to_arrays
features_to_arrays
441
453
441
441
a8d73cbce1080e2bed18f7234bf8f1adcd1cca89
bigcode/the-stack
train
d3afb1b1b20bf500d9045666
train
function
def _truncate_seq_pair(tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since ...
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since if one sequence is very short then each token # that...
) == seq_length features.append( InputFeatures( unique_id=example.unique_id, tokens=tokens, input_ids=input_ids, input_mask=input_mask, input_type_ids=input_type_ids)) return features def _truncate_seq_pair(tokens_a...
64
64
146
14
49
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
_truncate_seq_pair
_truncate_seq_pair
406
420
406
406
9995435b6f0f9e8b55affc060dc9d3a9604f03f3
bigcode/the-stack
train
618e6dae5e398ef7425e76cf
train
function
def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() index = 0 with tf.io.gfile.GFile(vocab_file, "r") as reader: while True: token = convert_to_unicode(reader.readline()) if not token: break ...
def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() index = 0 with tf.io.gfile.GFile(vocab_file, "r") as reader: while True: token = convert_to_unicode(reader.readline()) if not token: break token = token.strip() ...
) def printable_text(text): if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) def load_vocab(vocab_file):
63
64
93
7
56
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
load_vocab
load_vocab
284
296
284
284
be01964c6fe549067a4553ab0e625026928722ba
bigcode/the-stack
train
d3f5a2fd8b99e639425d4de3
train
function
def convert_examples_to_features(examples, seq_length, tokenizer): """Loads a data file into a list of `InputBatch`s.""" features = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: tokens...
def convert_examples_to_features(examples, seq_length, tokenizer):
"""Loads a data file into a list of `InputBatch`s.""" features = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: tokens_b = tokenizer.tokenize(example.text_b) if tokens_b: ...
Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() index = 0 with tf.io.gfile.GFile(vocab_file, "r") as reader: while True: token = convert_to_unicode(reader.readline()) if not token: break token = token.strip() ...
228
228
763
13
214
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
convert_examples_to_features
convert_examples_to_features
324
403
324
324
02aa968013f7df2c892ce64d022055a140878286
bigcode/the-stack
train
70a01f8052cad5cfe9b0fe57
train
function
def convert_to_unicode(text): if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text)))
def convert_to_unicode(text):
if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text)))
<= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)): return True cat = unicodedata.category(char) if cat.startswith("P"): return True return False def convert_to_unicode(text):
64
64
56
6
57
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
convert_to_unicode
convert_to_unicode
266
272
266
266
4c9fb76de6ad57bec8b367f4f9ae2bd1716a15eb
bigcode/the-stack
train
9d32881b361b38f3951130f4
train
function
def build_preprocessor(voc_path, seq_len, lower=True): tokenizer = FullTokenizer(vocab_file=voc_path, do_lower_case=lower) EMPTY_STR = "" PAD_STR = "pad" NULL_VAL = 0 def strings_to_arrays(str_list): str_list = np.atleast_1d(str_list).reshape((-1,)) empty_id = (str_list == EMPTY_ST...
def build_preprocessor(voc_path, seq_len, lower=True):
tokenizer = FullTokenizer(vocab_file=voc_path, do_lower_case=lower) EMPTY_STR = "" PAD_STR = "pad" NULL_VAL = 0 def strings_to_arrays(str_list): str_list = np.atleast_1d(str_list).reshape((-1,)) empty_id = (str_list == EMPTY_STR).nonzero()[0] str_list[empty_id] = PAD_STR ...
) all_segment_ids.append(feature.input_type_ids) return (np.array(all_input_ids, dtype='int32'), np.array(all_input_mask, dtype='int32'), np.array(all_segment_ids, dtype='int32')) def build_preprocessor(voc_path, seq_len, lower=True):
63
64
182
14
49
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
build_preprocessor
build_preprocessor
456
480
456
456
22a5d5bbfdb25da00db71a95f05f42e5f7ec35ec
bigcode/the-stack
train
fb53d355012ee1e04237d18d
train
function
def convert_tokens_to_ids(vocab, tokens): return convert_by_vocab(vocab, tokens)
def convert_tokens_to_ids(vocab, tokens):
return convert_by_vocab(vocab, tokens)
+= 1 return vocab def convert_by_vocab(vocab, items): """Converts a sequence of [tokens|ids] using the vocab.""" output = [] for item in items: output.append(vocab[item]) return output def convert_tokens_to_ids(vocab, tokens):
64
64
20
10
53
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
convert_tokens_to_ids
convert_tokens_to_ids
307
308
307
307
1e02d348ce9bf416cfb4ac410d56e91865cb14d8
bigcode/the-stack
train
fafd9b257f4365d03706e91f
train
class
class FullTokenizer(object): """Runs end-to-end tokenziation.""" def __init__(self, vocab_file, do_lower_case=True): self.vocab = load_vocab(vocab_file) self.inv_vocab = {v: k for k, v in self.vocab.items()} self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case) self...
class FullTokenizer(object):
"""Runs end-to-end tokenziation.""" def __init__(self, vocab_file, do_lower_case=True): self.vocab = load_vocab(vocab_file) self.inv_vocab = {v: k for k, v in self.vocab.items()} self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case) self.wordpiece_tokenizer = Wordpi...
import re import tensorflow as tf import numpy as np import collections import unicodedata class FullTokenizer(object):
26
65
219
5
20
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
FullTokenizer
FullTokenizer
8
32
8
8
13fbd3e62d53342f44ef747145f5568d1cfb54f9
bigcode/the-stack
train
41ceb4a315c3959c2a06be2c
train
class
class BasicTokenizer(object): """Runs basic tokenization (punctuation splitting, lower casing, etc.).""" def __init__(self, do_lower_case=True): """Constructs a BasicTokenizer. Args: do_lower_case: Whether to lower case the input. """ self.do_lower_case = do_lower_case...
class BasicTokenizer(object):
"""Runs basic tokenization (punctuation splitting, lower casing, etc.).""" def __init__(self, do_lower_case=True): """Constructs a BasicTokenizer. Args: do_lower_case: Whether to lower case the input. """ self.do_lower_case = do_lower_case def tokenize(self, text)...
import re import tensorflow as tf import numpy as np import collections import unicodedata class FullTokenizer(object): """Runs end-to-end tokenziation.""" def __init__(self, vocab_file, do_lower_case=True): self.vocab = load_vocab(vocab_file) self.inv_vocab = {v: k for k, v in self.vocab.ite...
245
256
981
5
240
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
BasicTokenizer
BasicTokenizer
35
146
35
35
63152bb78e10499cf0d20c8142dce9f00d81e00a
bigcode/the-stack
train
9aaf6594bbd936b8234e90d4
train
function
def convert_by_vocab(vocab, items): """Converts a sequence of [tokens|ids] using the vocab.""" output = [] for item in items: output.append(vocab[item]) return output
def convert_by_vocab(vocab, items):
"""Converts a sequence of [tokens|ids] using the vocab.""" output = [] for item in items: output.append(vocab[item]) return output
File(vocab_file, "r") as reader: while True: token = convert_to_unicode(reader.readline()) if not token: break token = token.strip() vocab[token] = index index += 1 return vocab def convert_by_vocab(vocab, items):
64
64
46
9
54
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
convert_by_vocab
convert_by_vocab
299
304
299
299
a3060547208041b8b3e083b1613ccec8f81387c4
bigcode/the-stack
train
ff75c998bc34d8e083bd5a69
train
function
def printable_text(text): if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text)))
def printable_text(text):
if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text)))
False def convert_to_unicode(text): if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) def printable_text(text):
63
64
55
5
58
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
printable_text
printable_text
275
281
275
275
4dfd99e3d31fac57d744b64814533830229545ea
bigcode/the-stack
train
8a77f1db59e447ee13c1f345
train
function
def _is_control(char): """Checks whether `chars` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char == "\t" or char == "\n" or char == "\r": return False cat = unicodedata.category(char) if cat.startswith("C"): ...
def _is_control(char):
"""Checks whether `chars` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char == "\t" or char == "\n" or char == "\r": return False cat = unicodedata.category(char) if cat.startswith("C"): return True ret...
generally considered as such. if char == " " or char == "\t" or char == "\n" or char == "\r": return True cat = unicodedata.category(char) if cat == "Zs": return True return False def _is_control(char):
64
64
83
6
57
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
_is_control
_is_control
238
247
238
238
f767aa2e12a81202a69e8eb44ae390144d75262c
bigcode/the-stack
train
c5fcc53a2d1617ba2f479d64
train
function
def convert_ids_to_tokens(inv_vocab, ids): return convert_by_vocab(inv_vocab, ids)
def convert_ids_to_tokens(inv_vocab, ids):
return convert_by_vocab(inv_vocab, ids)
verts a sequence of [tokens|ids] using the vocab.""" output = [] for item in items: output.append(vocab[item]) return output def convert_tokens_to_ids(vocab, tokens): return convert_by_vocab(vocab, tokens) def convert_ids_to_tokens(inv_vocab, ids):
64
64
20
10
54
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
convert_ids_to_tokens
convert_ids_to_tokens
311
312
311
311
b06251b4946b61f78d7e5e62b3126dac0fdfe813
bigcode/the-stack
train
95a395ddd35f4339a3ab63ba
train
function
def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a peice of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens
def whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a peice of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens
[] for item in items: output.append(vocab[item]) return output def convert_tokens_to_ids(vocab, tokens): return convert_by_vocab(vocab, tokens) def convert_ids_to_tokens(inv_vocab, ids): return convert_by_vocab(inv_vocab, ids) def whitespace_tokenize(text):
64
64
45
6
58
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
whitespace_tokenize
whitespace_tokenize
315
321
315
315
c52fb54234c7b1b0225feb6edb3ec9fe9f5a05ff
bigcode/the-stack
train
5c2734d6cdc052406494b3fc
train
function
def _is_punctuation(char): """Checks whether `chars` is a punctuation character.""" cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuation anyways, for # consistency....
def _is_punctuation(char):
"""Checks whether `chars` is a punctuation character.""" cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuation anyways, for # consistency. if ((cp >= 33 and cp <...
we count them as whitespace # characters. if char == "\t" or char == "\n" or char == "\r": return False cat = unicodedata.category(char) if cat.startswith("C"): return True return False def _is_punctuation(char):
64
64
154
7
56
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
_is_punctuation
_is_punctuation
250
263
250
250
d86b2887817df95aab7fa7d13bc07c8151d9196c
bigcode/the-stack
train
5c4375467af14e947c2d53df
train
function
def read_examples(str_list): """Read a list of `InputExample`s from a list of strings.""" unique_id = 0 for s in str_list: line = convert_to_unicode(s) line = line.strip() text_a = None text_b = None m = re.match(r"^(.*) \|\|\| (.*)$", line) if m is None: ...
def read_examples(str_list):
"""Read a list of `InputExample`s from a list of strings.""" unique_id = 0 for s in str_list: line = convert_to_unicode(s) line = line.strip() text_a = None text_b = None m = re.match(r"^(.*) \|\|\| (.*)$", line) if m is None: text_a = line ...
information than a longer sequence. while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_length: break if len(tokens_a) > len(tokens_b): tokens_a.pop() else: tokens_b.pop() def read_examples(str_list):
64
64
142
6
58
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
read_examples
read_examples
423
438
423
423
6c28921bc8e88df62e5cdd6cc2b291f4a2c665b8
bigcode/the-stack
train
47bd13ba608b8eb26e01b7ac
train
class
class InputFeatures(object): """A single set of features of data.""" def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids): self.unique_id = unique_id self.tokens = tokens self.input_ids = input_ids self.input_mask = input_mask self.input_type_ids ...
class InputFeatures(object):
"""A single set of features of data.""" def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids): self.unique_id = unique_id self.tokens = tokens self.input_ids = input_ids self.input_mask = input_mask self.input_type_ids = input_type_ids
else: output_tokens.extend(sub_tokens) return output_tokens class InputExample(object): def __init__(self, unique_id, text_a, text_b): self.unique_id = unique_id self.text_a = text_a self.text_b = text_b class InputFeatures(object):
64
64
77
5
58
AhmedYounes94/bert_experimental
bert_experimental/finetuning/text_preprocessing.py
Python
InputFeatures
InputFeatures
215
223
215
215
bc68e4970762665062922d529033e81637aac54f
bigcode/the-stack
train
58261e09ddfa4578ebf7c3a6
train
class
class RepositorioUsuario(): """Essa classe abstrata modela um Repositório de Usuários, ou seja, uma estrutura de armazenamento de Usuários (por exemplo, um BD ou armazenamento em arquivo de texto), para implementar o CRUD.""" def inserir(self, usuario): """Cria um Usuário no Reposi...
class RepositorioUsuario():
"""Essa classe abstrata modela um Repositório de Usuários, ou seja, uma estrutura de armazenamento de Usuários (por exemplo, um BD ou armazenamento em arquivo de texto), para implementar o CRUD.""" def inserir(self, usuario): """Cria um Usuário no Repositório. Deve retornar um obje...
# -*- coding: utf-8 -*- class RepositorioUsuario():
14
104
349
6
8
ESEGroup/Paraguai
domain/usuario/repositorio.py
Python
RepositorioUsuario
RepositorioUsuario
3
31
3
3
270d3bc865b030c0153e391b2bf0e7d8b5602521
bigcode/the-stack
train
95b27ebccf453ed954839f8b
train
class
class MarkovConsumerType(IndShockConsumerType): """ An agent in the Markov consumption-saving model. His problem is defined by a sequence of income distributions, survival probabilities, discount factors, and permanent income growth rates, as well as time invariant values for risk aversion, the int...
class MarkovConsumerType(IndShockConsumerType):
""" An agent in the Markov consumption-saving model. His problem is defined by a sequence of income distributions, survival probabilities, discount factors, and permanent income growth rates, as well as time invariant values for risk aversion, the interest rate, the grid of end-of-period assets, an...
------- solution : ConsumerSolution The solution to the single period consumption-saving problem. Includes a consumption function cFunc (using cubic or linear splines), a marg- inal value function vPfunc, a minimum acceptable level of normalized market resources mNrmMin, normaliz...
255
256
3,391
11
244
AMonninger/HARK
HARK/ConsumptionSaving/ConsMarkovModel.py
Python
MarkovConsumerType
MarkovConsumerType
837
1,245
837
837
f326cb884ddbffae873b54356d0e0ceab911e2db
bigcode/the-stack
train
d4e6a75f4406f6e9e0531abf
train
class
class ConsMarkovSolver(ConsIndShockSolver): """ A class to solve a single period consumption-saving problem with risky income and stochastic transitions between discrete states, in a Markov fashion. Extends ConsIndShockSolver, with identical inputs but for a discrete Markov state, whose transition r...
class ConsMarkovSolver(ConsIndShockSolver):
""" A class to solve a single period consumption-saving problem with risky income and stochastic transitions between discrete states, in a Markov fashion. Extends ConsIndShockSolver, with identical inputs but for a discrete Markov state, whose transition rule is summarized in MrkvArray. Markov ...
""" from copy import deepcopy import numpy as np from HARK import AgentType from HARK.ConsumptionSaving.ConsIndShockModel import ( ConsIndShockSolver, ConsumerSolution, IndShockConsumerType, PerfForesightConsumerType, ) from HARK.distribution import ( DiscreteDistribution, MarkovProcess, Un...
256
256
6,738
11
244
AMonninger/HARK
HARK/ConsumptionSaving/ConsMarkovModel.py
Python
ConsMarkovSolver
ConsMarkovSolver
51
735
51
51
cec903489599b37c239bf199d287e3bcc65c1bae
bigcode/the-stack
train
326fd848b2c6a1a71577f696
train
function
def _solve_ConsMarkov( solution_next, IncShkDstn, LivPrb, DiscFac, CRRA, Rfree, PermGroFac, MrkvArray, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool, ): """ Solves a single period consumption-saving problem with risky income and stochastic transitions between d...
def _solve_ConsMarkov( solution_next, IncShkDstn, LivPrb, DiscFac, CRRA, Rfree, PermGroFac, MrkvArray, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool, ):
""" Solves a single period consumption-saving problem with risky income and stochastic transitions between discrete states, in a Markov fashion. Has identical inputs as solveConsIndShock, except for a discrete Markov transitionrule MrkvArray. Markov states can differ in their interest factor, ...
0, 0.0) vNvrsP = np.insert( vNvrsP, 0, self.MPCmaxEff[i] ** (-self.CRRA / (1.0 - self.CRRA)) ) MPCminNvrs = self.MPCminNow[i] ** (-self.CRRA / (1.0 - self.CRRA)) vNvrsFunc_i = CubicInterp( mNrm_temp, vNvrs, vNvrsP, MPCminNvrs * self.hNrmNo...
246
246
820
70
175
AMonninger/HARK
HARK/ConsumptionSaving/ConsMarkovModel.py
Python
_solve_ConsMarkov
_solve_ConsMarkov
738
830
738
751
ad2cffd381c8e93ff168f1128b6f245dfef1fa3b
bigcode/the-stack
train
8ebd5d7be1223617810e0dea
train
class
class PyTorchModel(ModelWithPreprocessing): def __init__( self, model: Any, bounds: BoundsInput, device: Any = None, preprocessing: Preprocessing = None, ) -> None: import torch if not isinstance(model, torch.nn.Module): raise ValueError("expe...
class PyTorchModel(ModelWithPreprocessing):
def __init__( self, model: Any, bounds: BoundsInput, device: Any = None, preprocessing: Preprocessing = None, ) -> None: import torch if not isinstance(model, torch.nn.Module): raise ValueError("expected model to be a torch.nn.Module instance"...
, Preprocessing from .base import ModelWithPreprocessing def get_device(device: Any) -> Any: import torch if device is None: return torch.device("cuda:0" if torch.cuda.is_available() else "cpu") if isinstance(device, str): return torch.device(device) return device class PyTorchModel(...
78
78
262
9
68
Gokkulnath/foolbox
foolbox/models/pytorch.py
Python
PyTorchModel
PyTorchModel
20
57
20
20
7e44779fea8db445e631bc0db5e2d96ff69d3315
bigcode/the-stack
train
0856e86680bb554b039d3c61
train
function
def get_device(device: Any) -> Any: import torch if device is None: return torch.device("cuda:0" if torch.cuda.is_available() else "cpu") if isinstance(device, str): return torch.device(device) return device
def get_device(device: Any) -> Any:
import torch if device is None: return torch.device("cuda:0" if torch.cuda.is_available() else "cpu") if isinstance(device, str): return torch.device(device) return device
from typing import Any, cast import warnings import eagerpy as ep from ..types import BoundsInput, Preprocessing from .base import ModelWithPreprocessing def get_device(device: Any) -> Any:
45
64
56
10
34
Gokkulnath/foolbox
foolbox/models/pytorch.py
Python
get_device
get_device
10
17
10
10
f85ece6f7a2604333f206f19a81d1fc5982998e1
bigcode/the-stack
train
a1e51c3facdf0771e36da875
train
function
def is_lock_not_available_error(error: OperationalError): """Check if the Error is about not being able to acquire lock""" # DB specific error codes: # Postgres: 55P03 # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT # is set.' # MySQL:...
def is_lock_not_available_error(error: OperationalError):
"""Check if the Error is about not being able to acquire lock""" # DB specific error codes: # Postgres: 55P03 # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT # is set.' # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transac...
usage: .. code:: python with prohibit_commit(session) as guard: # ... do something with session guard.commit() # This would throw an error # session.commit() """ return CommitProhibitorGuard(session) def is_lock_not_available_error(error: Operation...
64
64
195
11
53
npodewitz/airflow
airflow/utils/sqlalchemy.py
Python
is_lock_not_available_error
is_lock_not_available_error
309
324
309
309
a88ea85c6fa4964102add188493815a50a3ab37d
bigcode/the-stack
train
6daf86e2009f8d462ca67f6a
train
class
class CommitProhibitorGuard: """Context manager class that powers prohibit_commit""" expected_commit = False def __init__(self, session: Session): self.session = session def _validate_commit(self, _): if self.expected_commit: self.expected_commit = False return...
class CommitProhibitorGuard:
"""Context manager class that powers prohibit_commit""" expected_commit = False def __init__(self, session: Session): self.session = session def _validate_commit(self, _): if self.expected_commit: self.expected_commit = False return raise RuntimeError("...
SQL dialect (Mariadb & MySQL < 8) does not support it. if USE_ROW_LEVEL_LOCKING and (dialect.name != "mysql" or dialect.supports_for_update_of): return query.with_for_update(**kwargs) else: return query class CommitProhibitorGuard:
64
64
175
7
56
npodewitz/airflow
airflow/utils/sqlalchemy.py
Python
CommitProhibitorGuard
CommitProhibitorGuard
256
284
256
256
d969b4b8f8e582a01136a165c7d2c1b363a23093
bigcode/the-stack
train
87df0e8d8d4868cb6f63ae18
train
function
def with_row_locks(query, session: Session, **kwargs): """ Apply with_for_update to an SQLAlchemy query, if row level locking is in use. :param query: An SQLAlchemy Query object :param session: ORM Session :param kwargs: Extra kwargs to pass to with_for_update (of, nowait, skip_locked, etc) :re...
def with_row_locks(query, session: Session, **kwargs):
""" Apply with_for_update to an SQLAlchemy query, if row level locking is in use. :param query: An SQLAlchemy Query object :param session: ORM Session :param kwargs: Extra kwargs to pass to with_for_update (of, nowait, skip_locked, etc) :return: updated query """ dialect = session.bind....
if session.bind.dialect.name == "postgresql": return nullsfirst(col) else: return col USE_ROW_LEVEL_LOCKING: bool = conf.getboolean('scheduler', 'use_row_level_locking', fallback=True) def with_row_locks(query, session: Session, **kwargs):
64
64
162
14
50
npodewitz/airflow
airflow/utils/sqlalchemy.py
Python
with_row_locks
with_row_locks
238
253
238
238
9d2c47df63f4fb49ede02a83247865fc85ffa13e
bigcode/the-stack
train
f2566c261257c29f04014a26
train
function
def prohibit_commit(session): """ Return a context manager that will disallow any commit that isn't done via the context manager. The aim of this is to ensure that transaction lifetime is strictly controlled which is especially important in the core scheduler loop. Any commit on the session that is _no...
def prohibit_commit(session):
""" Return a context manager that will disallow any commit that isn't done via the context manager. The aim of this is to ensure that transaction lifetime is strictly controlled which is especially important in the core scheduler loop. Any commit on the session that is _not_ via this context manager ...
exc_info): event.remove(self.session, 'before_commit', self._validate_commit) def commit(self): """ Commit the session. This is the required way to commit when the guard is in scope """ self.expected_commit = True self.session.commit() def prohibit_commit(se...
64
64
129
5
59
npodewitz/airflow
airflow/utils/sqlalchemy.py
Python
prohibit_commit
prohibit_commit
287
306
287
287
172efae8baf5b3afe60bcf8bd980554f6d99e136
bigcode/the-stack
train
4331247870107b2d777b6f84
train
function
def tuple_in_condition( columns: Tuple[ColumnElement, ...], collection: Iterable[Any], ) -> ColumnOperators: """Generates a tuple-in-collection operator to use in ``.filter()``. For most SQL backends, this generates a simple ``([col, ...]) IN [condition]`` clause. This however does not work with MS...
def tuple_in_condition( columns: Tuple[ColumnElement, ...], collection: Iterable[Any], ) -> ColumnOperators:
"""Generates a tuple-in-collection operator to use in ``.filter()``. For most SQL backends, this generates a simple ``([col, ...]) IN [condition]`` clause. This however does not work with MSSQL, where we need to expand to ``(c1 = v1a AND c2 = v2a ...) OR (c1 = v1b AND c2 = v2b ...) ...`` manually. ...
that involves # importing it. This doesn't if db_err_code in ('55P03', 1205, 3572): return True return False def tuple_in_condition( columns: Tuple[ColumnElement, ...], collection: Iterable[Any], ) -> ColumnOperators:
64
64
195
26
37
npodewitz/airflow
airflow/utils/sqlalchemy.py
Python
tuple_in_condition
tuple_in_condition
327
344
327
330
f25100ba77b366248e98c3f8f87919b4e278cc26
bigcode/the-stack
train
3235dc59a5266b7c3f058b96
train
class
class ExtendedJSON(TypeDecorator): """ A version of the JSON column that uses the Airflow extended JSON serialization provided by airflow.serialization. """ impl = Text def db_supports_json(self): """Checks if the database supports JSON (i.e. is NOT MSSQL)""" return not conf.ge...
class ExtendedJSON(TypeDecorator):
""" A version of the JSON column that uses the Airflow extended JSON serialization provided by airflow.serialization. """ impl = Text def db_supports_json(self): """Checks if the database supports JSON (i.e. is NOT MSSQL)""" return not conf.get("database", "sql_alchemy_conn").s...
as that converts to configured TIMEZONE while the DB might be running with some other setting. We assume UTC datetimes in the database. """ if value is not None: if value.tzinfo is None: value = value.replace(tzinfo=utc) else: ...
85
85
284
6
78
npodewitz/airflow
airflow/utils/sqlalchemy.py
Python
ExtendedJSON
ExtendedJSON
96
138
96
96
dfeacdde893ef08b4f4e74c15d5bf8ae57203ab4
bigcode/the-stack
train
4d41ea6cba33ae0dbc10f2fc
train
function
def nowait(session: Session) -> Dict[str, Any]: """ Return kwargs for passing to `with_for_update()` suitable for the current DB engine version. We do this as we document the fact that on DB engines that don't support this construct, we do not support/recommend running HA scheduler. If a user ignores t...
def nowait(session: Session) -> Dict[str, Any]:
""" Return kwargs for passing to `with_for_update()` suitable for the current DB engine version. We do this as we document the fact that on DB engines that don't support this construct, we do not support/recommend running HA scheduler. If a user ignores this and tries anyway everything will still w...
adb.org/browse/MDEV-13115 """ dialect = session.bind.dialect if dialect.name != "mysql" or dialect.supports_for_update_of: return {'skip_locked': True} else: return {} def nowait(session: Session) -> Dict[str, Any]:
63
64
168
13
50
npodewitz/airflow
airflow/utils/sqlalchemy.py
Python
nowait
nowait
203
220
203
203
610ec3e42a33b8de6af9d0c26066e094748690df
bigcode/the-stack
train
c4cf59af755fb563407d1f47
train
class
class Interval(TypeDecorator): """Base class representing a time interval.""" impl = Text attr_keys = { datetime.timedelta: ('days', 'seconds', 'microseconds'), relativedelta.relativedelta: ( 'years', 'months', 'days', 'leapdays', ...
class Interval(TypeDecorator):
"""Base class representing a time interval.""" impl = Text attr_keys = { datetime.timedelta: ('days', 'seconds', 'microseconds'), relativedelta.relativedelta: ( 'years', 'months', 'days', 'leapdays', 'hours', 'minutes'...
return value def process_result_value(self, value, dialect): from airflow.serialization.serialized_objects import BaseSerialization if value is None: return None # Deserialize from a string first if needed if not self.db_supports_json(): value = jso...
75
75
250
5
70
npodewitz/airflow
airflow/utils/sqlalchemy.py
Python
Interval
Interval
141
180
141
141
2a2a0ef3cac87bb8d004d27039b9c0e0093a7d8a
bigcode/the-stack
train
c18977600cca318025a5538d
train
function
def nulls_first(col, session: Session) -> Dict[str, Any]: """ Adds a nullsfirst construct to the column ordering. Currently only Postgres supports it. In MySQL & Sqlite NULL values are considered lower than any non-NULL value, therefore, NULL values appear first when the order is ASC (ascending) """...
def nulls_first(col, session: Session) -> Dict[str, Any]:
""" Adds a nullsfirst construct to the column ordering. Currently only Postgres supports it. In MySQL & Sqlite NULL values are considered lower than any non-NULL value, therefore, NULL values appear first when the order is ASC (ascending) """ if session.bind.dialect.name == "postgresql": ...
rowse/MDEV-13115 """ dialect = session.bind.dialect if dialect.name != "mysql" or dialect.supports_for_update_of: return {'nowait': True} else: return {} def nulls_first(col, session: Session) -> Dict[str, Any]:
63
64
100
16
47
npodewitz/airflow
airflow/utils/sqlalchemy.py
Python
nulls_first
nulls_first
223
232
223
223
bd9a71da47e6088ae05a88e86dd3bd063e0b50a7
bigcode/the-stack
train
7674da1ad61353a51fa7467a
train
class
class UtcDateTime(TypeDecorator): """ Almost equivalent to :class:`~sqlalchemy.types.DateTime` with ``timezone=True`` option, but it differs from that by: - Never silently take naive :class:`~datetime.datetime`, instead it always raise :exc:`ValueError` unless time zone aware value. - :class:...
class UtcDateTime(TypeDecorator):
""" Almost equivalent to :class:`~sqlalchemy.types.DateTime` with ``timezone=True`` option, but it differs from that by: - Never silently take naive :class:`~datetime.datetime`, instead it always raise :exc:`ValueError` unless time zone aware value. - :class:`~datetime.datetime` value's :attr...
Tuple import pendulum from dateutil import relativedelta from sqlalchemy import and_, event, false, nullsfirst, or_, tuple_ from sqlalchemy.exc import OperationalError from sqlalchemy.orm.session import Session from sqlalchemy.sql import ColumnElement from sqlalchemy.sql.expression import ColumnOperators from sqlalch...
138
138
461
8
130
npodewitz/airflow
airflow/utils/sqlalchemy.py
Python
UtcDateTime
UtcDateTime
43
93
43
43
a7d530bbb4c6896f1c420ee66e8a534f9d30328b
bigcode/the-stack
train
be6cee636f6ebf96cc3cc217
train
function
def skip_locked(session: Session) -> Dict[str, Any]: """ Return kargs for passing to `with_for_update()` suitable for the current DB engine version. We do this as we document the fact that on DB engines that don't support this construct, we do not support/recommend running HA scheduler. If a user ignor...
def skip_locked(session: Session) -> Dict[str, Any]:
""" Return kargs for passing to `with_for_update()` suitable for the current DB engine version. We do this as we document the fact that on DB engines that don't support this construct, we do not support/recommend running HA scheduler. If a user ignores this and tries anyway everything will still wo...
value data = json.loads(value) if isinstance(data, dict): type_map = {key.__name__: key for key in self.attr_keys} return type_map[data['type']](**data['attrs']) return data def skip_locked(session: Session) -> Dict[str, Any]:
64
64
171
13
50
npodewitz/airflow
airflow/utils/sqlalchemy.py
Python
skip_locked
skip_locked
183
200
183
183
2bfc556253079fe5d8945c34691ffe8c412ed1ed
bigcode/the-stack
train