blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ebe2df7950a0c0e7af5541ed4f2ff3d2cd33d1ba | [
"self.start_word = w1\nself.end_word = w2\nself.word_set = wordlist",
"if len(self.start_word) != len(self.end_word):\n return None\nif self.start_word not in self.word_set:\n return None\nif self.end_word not in self.word_set:\n return None\npath_queue = Queue()\npath_stack = Stack()\npath_stack.push(se... | <|body_start_0|>
self.start_word = w1
self.end_word = w2
self.word_set = wordlist
<|end_body_0|>
<|body_start_1|>
if len(self.start_word) != len(self.end_word):
return None
if self.start_word not in self.word_set:
return None
if self.end_word not ... | A class providing functionality to create word ladders | WordLadder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordLadder:
"""A class providing functionality to create word ladders"""
def __init__(self, w1, w2, wordlist):
"""Construct a WordLadder"""
<|body_0|>
def make_ladder(self):
"""Find the shortest path from start word to end word None -> stack object"""
<|b... | stack_v2_sparse_classes_36k_train_008400 | 1,651 | no_license | [
{
"docstring": "Construct a WordLadder",
"name": "__init__",
"signature": "def __init__(self, w1, w2, wordlist)"
},
{
"docstring": "Find the shortest path from start word to end word None -> stack object",
"name": "make_ladder",
"signature": "def make_ladder(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020836 | Implement the Python class `WordLadder` described below.
Class description:
A class providing functionality to create word ladders
Method signatures and docstrings:
- def __init__(self, w1, w2, wordlist): Construct a WordLadder
- def make_ladder(self): Find the shortest path from start word to end word None -> stack ... | Implement the Python class `WordLadder` described below.
Class description:
A class providing functionality to create word ladders
Method signatures and docstrings:
- def __init__(self, w1, w2, wordlist): Construct a WordLadder
- def make_ladder(self): Find the shortest path from start word to end word None -> stack ... | 778d79fe826588d888df654b0b6548340abb31ff | <|skeleton|>
class WordLadder:
"""A class providing functionality to create word ladders"""
def __init__(self, w1, w2, wordlist):
"""Construct a WordLadder"""
<|body_0|>
def make_ladder(self):
"""Find the shortest path from start word to end word None -> stack object"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordLadder:
"""A class providing functionality to create word ladders"""
def __init__(self, w1, w2, wordlist):
"""Construct a WordLadder"""
self.start_word = w1
self.end_word = w2
self.word_set = wordlist
def make_ladder(self):
"""Find the shortest path from s... | the_stack_v2_python_sparse | hw09/word_ladder_starter/word_ladder.py | sry19/python5001 | train | 0 |
5ac2dcc82b88e970d6a90cc69f91423b1a236eb9 | [
"SCons.Warnings._enabled = []\nSCons.Warnings._warningAsException = 0\nto = TestOutput()\nSCons.Warnings._warningOut = to\nSCons.Warnings.enableWarningClass(SCons.Warnings.SConsWarning)\nSCons.Warnings.warn(SCons.Warnings.DeprecatedWarning, 'Foo')\nassert to.out == 'Foo', to.out\nSCons.Warnings.warn(SCons.Warnings.... | <|body_start_0|>
SCons.Warnings._enabled = []
SCons.Warnings._warningAsException = 0
to = TestOutput()
SCons.Warnings._warningOut = to
SCons.Warnings.enableWarningClass(SCons.Warnings.SConsWarning)
SCons.Warnings.warn(SCons.Warnings.DeprecatedWarning, 'Foo')
asser... | WarningsTestCase | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WarningsTestCase:
def test_Warning(self) -> None:
"""Test warn function."""
<|body_0|>
def test_WarningAsExc(self) -> None:
"""Test warnings as exceptions."""
<|body_1|>
def test_Disable(self) -> None:
"""Test disabling/enabling warnings."""
... | stack_v2_sparse_classes_36k_train_008401 | 4,552 | permissive | [
{
"docstring": "Test warn function.",
"name": "test_Warning",
"signature": "def test_Warning(self) -> None"
},
{
"docstring": "Test warnings as exceptions.",
"name": "test_WarningAsExc",
"signature": "def test_WarningAsExc(self) -> None"
},
{
"docstring": "Test disabling/enabling... | 3 | stack_v2_sparse_classes_30k_train_014707 | Implement the Python class `WarningsTestCase` described below.
Class description:
Implement the WarningsTestCase class.
Method signatures and docstrings:
- def test_Warning(self) -> None: Test warn function.
- def test_WarningAsExc(self) -> None: Test warnings as exceptions.
- def test_Disable(self) -> None: Test dis... | Implement the Python class `WarningsTestCase` described below.
Class description:
Implement the WarningsTestCase class.
Method signatures and docstrings:
- def test_Warning(self) -> None: Test warn function.
- def test_WarningAsExc(self) -> None: Test warnings as exceptions.
- def test_Disable(self) -> None: Test dis... | b2a7d7066a2b854460a334a5fe737ea389655e6e | <|skeleton|>
class WarningsTestCase:
def test_Warning(self) -> None:
"""Test warn function."""
<|body_0|>
def test_WarningAsExc(self) -> None:
"""Test warnings as exceptions."""
<|body_1|>
def test_Disable(self) -> None:
"""Test disabling/enabling warnings."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WarningsTestCase:
def test_Warning(self) -> None:
"""Test warn function."""
SCons.Warnings._enabled = []
SCons.Warnings._warningAsException = 0
to = TestOutput()
SCons.Warnings._warningOut = to
SCons.Warnings.enableWarningClass(SCons.Warnings.SConsWarning)
... | the_stack_v2_python_sparse | SCons/WarningsTests.py | SCons/scons | train | 1,827 | |
22fcc0cd69accb362d71f418cc4e41c05f9ee297 | [
"author_list = list(set(map(lambda article: article.author, Article.objects.all())))\nfor author in author_list:\n yield (author.id, author.nickname or author.username)",
"author_id = self.value()\nif author_id:\n return queryset.filter(author__id=author_id)\nelse:\n return queryset"
] | <|body_start_0|>
author_list = list(set(map(lambda article: article.author, Article.objects.all())))
for author in author_list:
yield (author.id, author.nickname or author.username)
<|end_body_0|>
<|body_start_1|>
author_id = self.value()
if author_id:
return que... | 自定义查询的过滤器-根据文章作者过滤文章 | ArticleAuthorListFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleAuthorListFilter:
"""自定义查询的过滤器-根据文章作者过滤文章"""
def lookups(self, request, model_admin):
"""Must be overridden to return a list of tuples (value, verbose value)"""
<|body_0|>
def queryset(self, request, queryset):
"""Return the filtered queryset."""
<... | stack_v2_sparse_classes_36k_train_008402 | 10,733 | permissive | [
{
"docstring": "Must be overridden to return a list of tuples (value, verbose value)",
"name": "lookups",
"signature": "def lookups(self, request, model_admin)"
},
{
"docstring": "Return the filtered queryset.",
"name": "queryset",
"signature": "def queryset(self, request, queryset)"
}... | 2 | stack_v2_sparse_classes_30k_train_013326 | Implement the Python class `ArticleAuthorListFilter` described below.
Class description:
自定义查询的过滤器-根据文章作者过滤文章
Method signatures and docstrings:
- def lookups(self, request, model_admin): Must be overridden to return a list of tuples (value, verbose value)
- def queryset(self, request, queryset): Return the filtered q... | Implement the Python class `ArticleAuthorListFilter` described below.
Class description:
自定义查询的过滤器-根据文章作者过滤文章
Method signatures and docstrings:
- def lookups(self, request, model_admin): Must be overridden to return a list of tuples (value, verbose value)
- def queryset(self, request, queryset): Return the filtered q... | 0fcf3709fabeee49874343b3a4ab80582698c466 | <|skeleton|>
class ArticleAuthorListFilter:
"""自定义查询的过滤器-根据文章作者过滤文章"""
def lookups(self, request, model_admin):
"""Must be overridden to return a list of tuples (value, verbose value)"""
<|body_0|>
def queryset(self, request, queryset):
"""Return the filtered queryset."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArticleAuthorListFilter:
"""自定义查询的过滤器-根据文章作者过滤文章"""
def lookups(self, request, model_admin):
"""Must be overridden to return a list of tuples (value, verbose value)"""
author_list = list(set(map(lambda article: article.author, Article.objects.all())))
for author in author_list:
... | the_stack_v2_python_sparse | blog/admin.py | enjoy-binbin/Django-blog | train | 113 |
f02c31581094d31a2f3bf1a3bfa09cb4a67b9694 | [
"self._state = VoidPointer()\nresult = raw_cfb_lib.CFB_start_operation(block_cipher.get(), c_uint8_ptr(iv), c_size_t(len(iv)), c_size_t(segment_size), self._state.address_of())\nif result:\n raise ValueError('Error %d while instantiating the CFB mode' % result)\nself._state = SmartPointer(self._state.get(), raw_... | <|body_start_0|>
self._state = VoidPointer()
result = raw_cfb_lib.CFB_start_operation(block_cipher.get(), c_uint8_ptr(iv), c_size_t(len(iv)), c_size_t(segment_size), self._state.address_of())
if result:
raise ValueError('Error %d while instantiating the CFB mode' % result)
se... | *Cipher FeedBack (CFB)*. This mode is similar to CFB, but it transforms the underlying block cipher into a stream cipher. Plaintext and ciphertext are processed in *segments* of **s** bits. The mode is therefore sometimes labelled **s**-bit CFB. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Secti... | CfbMode | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CfbMode:
"""*Cipher FeedBack (CFB)*. This mode is similar to CFB, but it transforms the underlying block cipher into a stream cipher. Plaintext and ciphertext are processed in *segments* of **s** bits. The mode is therefore sometimes labelled **s**-bit CFB. An Initialization Vector (*IV*) is requ... | stack_v2_sparse_classes_36k_train_008403 | 10,801 | permissive | [
{
"docstring": "Create a new block cipher, configured in CFB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : bytes/bytearray/memoryview The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be unpr... | 3 | null | Implement the Python class `CfbMode` described below.
Class description:
*Cipher FeedBack (CFB)*. This mode is similar to CFB, but it transforms the underlying block cipher into a stream cipher. Plaintext and ciphertext are processed in *segments* of **s** bits. The mode is therefore sometimes labelled **s**-bit CFB. ... | Implement the Python class `CfbMode` described below.
Class description:
*Cipher FeedBack (CFB)*. This mode is similar to CFB, but it transforms the underlying block cipher into a stream cipher. Plaintext and ciphertext are processed in *segments* of **s** bits. The mode is therefore sometimes labelled **s**-bit CFB. ... | fa82044a2dc2f0f1f7454f5394e6d68fa923c289 | <|skeleton|>
class CfbMode:
"""*Cipher FeedBack (CFB)*. This mode is similar to CFB, but it transforms the underlying block cipher into a stream cipher. Plaintext and ciphertext are processed in *segments* of **s** bits. The mode is therefore sometimes labelled **s**-bit CFB. An Initialization Vector (*IV*) is requ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CfbMode:
"""*Cipher FeedBack (CFB)*. This mode is similar to CFB, but it transforms the underlying block cipher into a stream cipher. Plaintext and ciphertext are processed in *segments* of **s** bits. The mode is therefore sometimes labelled **s**-bit CFB. An Initialization Vector (*IV*) is required. See `NI... | the_stack_v2_python_sparse | venv/lib/python3.6/site-packages/Crypto/Cipher/_mode_cfb.py | masora1030/eigoyurusan | train | 11 |
e39421dd55bb1495e0ded5efeb68c3159f0dedb7 | [
"angle, angular_velocity = torch.split(states_, 1, dim=-1)\nstates_ = torch.cat((torch.cos(angle), torch.sin(angle), angular_velocity), dim=-1)\nreturn states_",
"cos, sin, angular_velocity = torch.split(states_, 1, dim=-1)\nangle = torch.atan2(sin, cos)\nstates_ = torch.cat((angle, angular_velocity), dim=-1)\nre... | <|body_start_0|>
angle, angular_velocity = torch.split(states_, 1, dim=-1)
states_ = torch.cat((torch.cos(angle), torch.sin(angle), angular_velocity), dim=-1)
return states_
<|end_body_0|>
<|body_start_1|>
cos, sin, angular_velocity = torch.split(states_, 1, dim=-1)
angle = torc... | Transform pendulum states to cos, sin, angular_velocity. | StateTransform | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StateTransform:
"""Transform pendulum states to cos, sin, angular_velocity."""
def forward(self, states_):
"""Transform state before applying function approximation."""
<|body_0|>
def inverse(self, states_):
"""Inverse transformation of states."""
<|body_... | stack_v2_sparse_classes_36k_train_008404 | 23,678 | permissive | [
{
"docstring": "Transform state before applying function approximation.",
"name": "forward",
"signature": "def forward(self, states_)"
},
{
"docstring": "Inverse transformation of states.",
"name": "inverse",
"signature": "def inverse(self, states_)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014460 | Implement the Python class `StateTransform` described below.
Class description:
Transform pendulum states to cos, sin, angular_velocity.
Method signatures and docstrings:
- def forward(self, states_): Transform state before applying function approximation.
- def inverse(self, states_): Inverse transformation of state... | Implement the Python class `StateTransform` described below.
Class description:
Transform pendulum states to cos, sin, angular_velocity.
Method signatures and docstrings:
- def forward(self, states_): Transform state before applying function approximation.
- def inverse(self, states_): Inverse transformation of state... | c144aeecba5f35ccfb4ec943d29d7092c0fa20e3 | <|skeleton|>
class StateTransform:
"""Transform pendulum states to cos, sin, angular_velocity."""
def forward(self, states_):
"""Transform state before applying function approximation."""
<|body_0|>
def inverse(self, states_):
"""Inverse transformation of states."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StateTransform:
"""Transform pendulum states to cos, sin, angular_velocity."""
def forward(self, states_):
"""Transform state before applying function approximation."""
angle, angular_velocity = torch.split(states_, 1, dim=-1)
states_ = torch.cat((torch.cos(angle), torch.sin(angle... | the_stack_v2_python_sparse | exps/inverted_pendulum/util.py | tzahishimkin/extended-hucrl | train | 0 |
83890d7d89fc2f23ebcb0b63470ff06916289702 | [
"result = list(super().get_field_names(declared_fields, model_info))\nmodel = self.Meta.model\npermissioned_fields = set(list(model_info.fields.keys()) + list(model_info.forward_relations.keys())) & set(result)\nif issubclass(model, PermByFieldMixin):\n user = self.context['request'].user\n view_fields = mode... | <|body_start_0|>
result = list(super().get_field_names(declared_fields, model_info))
model = self.Meta.model
permissioned_fields = set(list(model_info.fields.keys()) + list(model_info.forward_relations.keys())) & set(result)
if issubclass(model, PermByFieldMixin):
user = self... | Apply permission validation on field level. This class should be used as a mixin to `rest_framework.serializers.BaseSerializer` subclasses. | PermissionsPerFieldSerializerMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PermissionsPerFieldSerializerMixin:
"""Apply permission validation on field level. This class should be used as a mixin to `rest_framework.serializers.BaseSerializer` subclasses."""
def get_field_names(self, declared_fields, model_info):
"""Remove fields for which user doesn't have a... | stack_v2_sparse_classes_36k_train_008405 | 7,771 | permissive | [
{
"docstring": "Remove fields for which user doesn't have access. Fields declared in serializer which aren't related from model are always passed here (for any user) - it's `declared_fields` in DRF nomenclature.",
"name": "get_field_names",
"signature": "def get_field_names(self, declared_fields, model_... | 4 | null | Implement the Python class `PermissionsPerFieldSerializerMixin` described below.
Class description:
Apply permission validation on field level. This class should be used as a mixin to `rest_framework.serializers.BaseSerializer` subclasses.
Method signatures and docstrings:
- def get_field_names(self, declared_fields,... | Implement the Python class `PermissionsPerFieldSerializerMixin` described below.
Class description:
Apply permission validation on field level. This class should be used as a mixin to `rest_framework.serializers.BaseSerializer` subclasses.
Method signatures and docstrings:
- def get_field_names(self, declared_fields,... | b4a72356f527b1f12c7babd7465d2d7fa3ffb0d3 | <|skeleton|>
class PermissionsPerFieldSerializerMixin:
"""Apply permission validation on field level. This class should be used as a mixin to `rest_framework.serializers.BaseSerializer` subclasses."""
def get_field_names(self, declared_fields, model_info):
"""Remove fields for which user doesn't have a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PermissionsPerFieldSerializerMixin:
"""Apply permission validation on field level. This class should be used as a mixin to `rest_framework.serializers.BaseSerializer` subclasses."""
def get_field_names(self, declared_fields, model_info):
"""Remove fields for which user doesn't have access. Fields... | the_stack_v2_python_sparse | src/ralph/lib/permissions/api.py | allegro/ralph | train | 1,970 |
068f2d0dde5b13031c7c69a1be098f7f96b208c0 | [
"used_words = set()\nsuggests = []\nfor text, weight in info_tuple:\n if text:\n words = es.indices.analyze(index=index, analyzer='ik_max_word', params={'filter': ['lowercase']}, body=text)\n analyzed_words = set([r['token'] for r in words['tokens'] if len(r['token']) > 1])\n new_words = ana... | <|body_start_0|>
used_words = set()
suggests = []
for text, weight in info_tuple:
if text:
words = es.indices.analyze(index=index, analyzer='ik_max_word', params={'filter': ['lowercase']}, body=text)
analyzed_words = set([r['token'] for r in words['tok... | 将数据写入到es中 | ElasticSearchPipeline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElasticSearchPipeline:
"""将数据写入到es中"""
def gen_suggests(self, index, info_tuple):
"""根据字符串生成搜索建议数组 :param index: :param info_tuple: :return:"""
<|body_0|>
def process_item(self, item, spider):
"""将item转换为es的数据格式 :param item: :param spider: :return:"""
<|b... | stack_v2_sparse_classes_36k_train_008406 | 4,853 | no_license | [
{
"docstring": "根据字符串生成搜索建议数组 :param index: :param info_tuple: :return:",
"name": "gen_suggests",
"signature": "def gen_suggests(self, index, info_tuple)"
},
{
"docstring": "将item转换为es的数据格式 :param item: :param spider: :return:",
"name": "process_item",
"signature": "def process_item(self... | 2 | stack_v2_sparse_classes_30k_train_003385 | Implement the Python class `ElasticSearchPipeline` described below.
Class description:
将数据写入到es中
Method signatures and docstrings:
- def gen_suggests(self, index, info_tuple): 根据字符串生成搜索建议数组 :param index: :param info_tuple: :return:
- def process_item(self, item, spider): 将item转换为es的数据格式 :param item: :param spider: :r... | Implement the Python class `ElasticSearchPipeline` described below.
Class description:
将数据写入到es中
Method signatures and docstrings:
- def gen_suggests(self, index, info_tuple): 根据字符串生成搜索建议数组 :param index: :param info_tuple: :return:
- def process_item(self, item, spider): 将item转换为es的数据格式 :param item: :param spider: :r... | 926002c7d66db2456fea94f1b50fdbf364d66836 | <|skeleton|>
class ElasticSearchPipeline:
"""将数据写入到es中"""
def gen_suggests(self, index, info_tuple):
"""根据字符串生成搜索建议数组 :param index: :param info_tuple: :return:"""
<|body_0|>
def process_item(self, item, spider):
"""将item转换为es的数据格式 :param item: :param spider: :return:"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElasticSearchPipeline:
"""将数据写入到es中"""
def gen_suggests(self, index, info_tuple):
"""根据字符串生成搜索建议数组 :param index: :param info_tuple: :return:"""
used_words = set()
suggests = []
for text, weight in info_tuple:
if text:
words = es.indices.analyze(... | the_stack_v2_python_sparse | ArticleSpider/ArticleSpider/pipelines.py | JayZhou5299/search_engine | train | 1 |
09d37a4f8d77fdada6b0df5e52594a0c66d6ac12 | [
"self.X = X_init\nself.Y = Y_init\nself.l = l\nself.sigma_f = sigma_f\nself.K = self.kernel(X_init, X_init)",
"σ2 = self.sigma_f ** 2\nl2 = self.l ** 2\nsqr_sumx1 = np.sum(X1 ** 2, 1).reshape(-1, 1)\nsqr_sumx2 = np.sum(X2 ** 2, 1)\nsqr_dist = sqr_sumx1 - 2 * np.dot(X1, X2.T) + sqr_sumx2\nkernel = σ2 * np.exp(-0.5... | <|body_start_0|>
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(X_init, X_init)
<|end_body_0|>
<|body_start_1|>
σ2 = self.sigma_f ** 2
l2 = self.l ** 2
sqr_sumx1 = np.sum(X1 ** 2, 1).reshape(-1, 1)
sqr_sumx2... | Represents a noiseless 1D Gaussian process | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Instantiation methid Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function Y_init is a numpy.ndarray ... | stack_v2_sparse_classes_36k_train_008407 | 1,540 | no_license | [
{
"docstring": "Instantiation methid Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function Y_init is a numpy.ndarray of shape (t, 1) representing the outputs of the black-box function for each input in X_init l is the length parameter for the kernel ... | 2 | stack_v2_sparse_classes_30k_train_007165 | Implement the Python class `GaussianProcess` described below.
Class description:
Represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): Instantiation methid Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampl... | Implement the Python class `GaussianProcess` described below.
Class description:
Represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): Instantiation methid Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampl... | bb980395b146c9f4e0d4e9766c4a36f67de70d2e | <|skeleton|>
class GaussianProcess:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Instantiation methid Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function Y_init is a numpy.ndarray ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianProcess:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Instantiation methid Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function Y_init is a numpy.ndarray of shape (t, ... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/0-gp.py | AndrewKalil/holbertonschool-machine_learning | train | 0 |
cb8475bc7f0fa167be67ad9cfbcd2b1c71a8c96d | [
"def func(x, y, z):\n return x + y + z\nself.assertEqual(None, xla.check_function_argument_count(func, 3, None))\nself.assertEqual('exactly 3 arguments', xla.check_function_argument_count(func, 2, None))\nqueue = tpu_feed.InfeedQueue(2)\nself.assertEqual(None, xla.check_function_argument_count(func, 1, queue))\n... | <|body_start_0|>
def func(x, y, z):
return x + y + z
self.assertEqual(None, xla.check_function_argument_count(func, 3, None))
self.assertEqual('exactly 3 arguments', xla.check_function_argument_count(func, 2, None))
queue = tpu_feed.InfeedQueue(2)
self.assertEqual(Non... | CheckFunctionArgumentCountTest | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckFunctionArgumentCountTest:
def test_simple(self):
"""Tests that arg checker works for functions with no varargs or defaults."""
<|body_0|>
def test_default_args(self):
"""Tests that arg checker works for a function with no varargs."""
<|body_1|>
def... | stack_v2_sparse_classes_36k_train_008408 | 12,981 | permissive | [
{
"docstring": "Tests that arg checker works for functions with no varargs or defaults.",
"name": "test_simple",
"signature": "def test_simple(self)"
},
{
"docstring": "Tests that arg checker works for a function with no varargs.",
"name": "test_default_args",
"signature": "def test_defa... | 4 | null | Implement the Python class `CheckFunctionArgumentCountTest` described below.
Class description:
Implement the CheckFunctionArgumentCountTest class.
Method signatures and docstrings:
- def test_simple(self): Tests that arg checker works for functions with no varargs or defaults.
- def test_default_args(self): Tests th... | Implement the Python class `CheckFunctionArgumentCountTest` described below.
Class description:
Implement the CheckFunctionArgumentCountTest class.
Method signatures and docstrings:
- def test_simple(self): Tests that arg checker works for functions with no varargs or defaults.
- def test_default_args(self): Tests th... | a7f3934a67900720af3d3b15389551483bee50b8 | <|skeleton|>
class CheckFunctionArgumentCountTest:
def test_simple(self):
"""Tests that arg checker works for functions with no varargs or defaults."""
<|body_0|>
def test_default_args(self):
"""Tests that arg checker works for a function with no varargs."""
<|body_1|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckFunctionArgumentCountTest:
def test_simple(self):
"""Tests that arg checker works for functions with no varargs or defaults."""
def func(x, y, z):
return x + y + z
self.assertEqual(None, xla.check_function_argument_count(func, 3, None))
self.assertEqual('exactl... | the_stack_v2_python_sparse | tensorflow/python/compiler/xla/xla_test.py | tensorflow/tensorflow | train | 208,740 | |
b584d290246dd6ca47e5fe2af577913137fae924 | [
"Process.__init__(self, *args, **kwds)\nself.queue = queue\nDATABASE_CONNECTION_INFO = URL(**db_settings)\nengine = create_engine(DATABASE_CONNECTION_INFO, pool_size=20, pool_recycle=3600, convert_unicode=True, encoding='latin1', echo=ENABLE_DEBUG)\nself.db_session = scoped_session(sessionmaker(autocommit=False, au... | <|body_start_0|>
Process.__init__(self, *args, **kwds)
self.queue = queue
DATABASE_CONNECTION_INFO = URL(**db_settings)
engine = create_engine(DATABASE_CONNECTION_INFO, pool_size=20, pool_recycle=3600, convert_unicode=True, encoding='latin1', echo=ENABLE_DEBUG)
self.db_session = ... | Thread that consumes WorkUnits from a queue to process them | PoolWorker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PoolWorker:
"""Thread that consumes WorkUnits from a queue to process them"""
def __init__(self, queue, *args, **kwds):
"""\\param workq: Queue object to consume the work units from"""
<|body_0|>
def run(self):
"""Process the work unit, or wait for sentinel to ex... | stack_v2_sparse_classes_36k_train_008409 | 5,442 | permissive | [
{
"docstring": "\\\\param workq: Queue object to consume the work units from",
"name": "__init__",
"signature": "def __init__(self, queue, *args, **kwds)"
},
{
"docstring": "Process the work unit, or wait for sentinel to exit",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006260 | Implement the Python class `PoolWorker` described below.
Class description:
Thread that consumes WorkUnits from a queue to process them
Method signatures and docstrings:
- def __init__(self, queue, *args, **kwds): \\param workq: Queue object to consume the work units from
- def run(self): Process the work unit, or wa... | Implement the Python class `PoolWorker` described below.
Class description:
Thread that consumes WorkUnits from a queue to process them
Method signatures and docstrings:
- def __init__(self, queue, *args, **kwds): \\param workq: Queue object to consume the work units from
- def run(self): Process the work unit, or wa... | b38843a6cdc19a406e6f709c53767bdaaa2fef96 | <|skeleton|>
class PoolWorker:
"""Thread that consumes WorkUnits from a queue to process them"""
def __init__(self, queue, *args, **kwds):
"""\\param workq: Queue object to consume the work units from"""
<|body_0|>
def run(self):
"""Process the work unit, or wait for sentinel to ex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PoolWorker:
"""Thread that consumes WorkUnits from a queue to process them"""
def __init__(self, queue, *args, **kwds):
"""\\param workq: Queue object to consume the work units from"""
Process.__init__(self, *args, **kwds)
self.queue = queue
DATABASE_CONNECTION_INFO = URL(... | the_stack_v2_python_sparse | csmserver/multi_process/process_pool.py | csm-aut/csm | train | 16 |
43c6aa72a23d19d87b7a43a5cf0a26d6bbfd83fb | [
"if hash_string is None:\n hash_string = self.get_hash(uploaded_file)\nuploaded_file.name = str(uuid4())\nimage = self.model(hash=hash_string, image_file=uploaded_file)\nimage.save()\nreturn image",
"hash_string = self.get_hash(uploaded_file)\ntry:\n return self.get(hash=hash_string)\nexcept self.model.Does... | <|body_start_0|>
if hash_string is None:
hash_string = self.get_hash(uploaded_file)
uploaded_file.name = str(uuid4())
image = self.model(hash=hash_string, image_file=uploaded_file)
image.save()
return image
<|end_body_0|>
<|body_start_1|>
hash_string = self.g... | Model manager for the ProductImage model. | ProductImageManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductImageManager:
"""Model manager for the ProductImage model."""
def add_image(self, uploaded_file, hash_string=None):
"""Add an image to the database."""
<|body_0|>
def get_or_add_image(self, uploaded_file):
"""Check if an image exists in the database and re... | stack_v2_sparse_classes_36k_train_008410 | 9,551 | no_license | [
{
"docstring": "Add an image to the database.",
"name": "add_image",
"signature": "def add_image(self, uploaded_file, hash_string=None)"
},
{
"docstring": "Check if an image exists in the database and return or create it.",
"name": "get_or_add_image",
"signature": "def get_or_add_image(s... | 3 | null | Implement the Python class `ProductImageManager` described below.
Class description:
Model manager for the ProductImage model.
Method signatures and docstrings:
- def add_image(self, uploaded_file, hash_string=None): Add an image to the database.
- def get_or_add_image(self, uploaded_file): Check if an image exists i... | Implement the Python class `ProductImageManager` described below.
Class description:
Model manager for the ProductImage model.
Method signatures and docstrings:
- def add_image(self, uploaded_file, hash_string=None): Add an image to the database.
- def get_or_add_image(self, uploaded_file): Check if an image exists i... | ba51d4e304b1aeb296fa2fe16611c892fcdbd471 | <|skeleton|>
class ProductImageManager:
"""Model manager for the ProductImage model."""
def add_image(self, uploaded_file, hash_string=None):
"""Add an image to the database."""
<|body_0|>
def get_or_add_image(self, uploaded_file):
"""Check if an image exists in the database and re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductImageManager:
"""Model manager for the ProductImage model."""
def add_image(self, uploaded_file, hash_string=None):
"""Add an image to the database."""
if hash_string is None:
hash_string = self.get_hash(uploaded_file)
uploaded_file.name = str(uuid4())
i... | the_stack_v2_python_sparse | inventory/models/product_image.py | stcstores/stcadmin | train | 0 |
05e9fc04cecf5935ddee67bc03ec1cb03d36d5b2 | [
"helpers.abort_if_invalid_parameters(pid, sid)\nproject = Project.query.get(pid)\nannotations = UserAnnotationModel.query.filter_by(session_id=sid).all()\nannotations = UserAnnotationSchema(many=True).dump(annotations)\nif project.is_public:\n return custom_response(200, data=annotations)\nhelpers.abort_if_unaut... | <|body_start_0|>
helpers.abort_if_invalid_parameters(pid, sid)
project = Project.query.get(pid)
annotations = UserAnnotationModel.query.filter_by(session_id=sid).all()
annotations = UserAnnotationSchema(many=True).dump(annotations)
if project.is_public:
return custom_... | Mapped to: /api/projects/<int:pid>/sessions/<string:sid>/annotations/ | UserAnnotations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAnnotations:
"""Mapped to: /api/projects/<int:pid>/sessions/<string:sid>/annotations/"""
def get(self, pid, sid):
"""Returns a list of all annotations for an existing session"""
<|body_0|>
def post(self, pid, sid):
"""Create a new annotation on an existing se... | stack_v2_sparse_classes_36k_train_008411 | 3,199 | no_license | [
{
"docstring": "Returns a list of all annotations for an existing session",
"name": "get",
"signature": "def get(self, pid, sid)"
},
{
"docstring": "Create a new annotation on an existing session",
"name": "post",
"signature": "def post(self, pid, sid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021352 | Implement the Python class `UserAnnotations` described below.
Class description:
Mapped to: /api/projects/<int:pid>/sessions/<string:sid>/annotations/
Method signatures and docstrings:
- def get(self, pid, sid): Returns a list of all annotations for an existing session
- def post(self, pid, sid): Create a new annotat... | Implement the Python class `UserAnnotations` described below.
Class description:
Mapped to: /api/projects/<int:pid>/sessions/<string:sid>/annotations/
Method signatures and docstrings:
- def get(self, pid, sid): Returns a list of all annotations for an existing session
- def post(self, pid, sid): Create a new annotat... | 716fa5a6e905380cb206c57868e87556805f2b7f | <|skeleton|>
class UserAnnotations:
"""Mapped to: /api/projects/<int:pid>/sessions/<string:sid>/annotations/"""
def get(self, pid, sid):
"""Returns a list of all annotations for an existing session"""
<|body_0|>
def post(self, pid, sid):
"""Create a new annotation on an existing se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserAnnotations:
"""Mapped to: /api/projects/<int:pid>/sessions/<string:sid>/annotations/"""
def get(self, pid, sid):
"""Returns a list of all annotations for an existing session"""
helpers.abort_if_invalid_parameters(pid, sid)
project = Project.query.get(pid)
annotations ... | the_stack_v2_python_sparse | gabber/api/annotations.py | joseplj/GabberAPI | train | 0 |
401f469d870af734a199eb7395b4c9fd190a5245 | [
"logger.info(f'Trainer arguments: {pl_trainer_args}')\nif pl_trainer_args['resume_from_checkpoint'] is not None and (not pl_trainer_args['resume_from_checkpoint'].endswith('.ckpt')):\n pl_trainer_args['resume_from_checkpoint'] = None\npl_trainer_args['callbacks'] = {'model_checkpoint_callback': {'save_top_k': pl... | <|body_start_0|>
logger.info(f'Trainer arguments: {pl_trainer_args}')
if pl_trainer_args['resume_from_checkpoint'] is not None and (not pl_trainer_args['resume_from_checkpoint'].endswith('.ckpt')):
pl_trainer_args['resume_from_checkpoint'] = None
pl_trainer_args['callbacks'] = {'mode... | gflownet training pipelines. | GFlowNetTrainingPipeline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GFlowNetTrainingPipeline:
"""gflownet training pipelines."""
def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetDataset, environment: GraphBuildingEnv, context: GraphBuildingEnvCont... | stack_v2_sparse_classes_36k_train_008412 | 16,893 | permissive | [
{
"docstring": "Generic training function for PyTorch Lightning-based training. Args: pl_trainer_args: pytorch lightning trainer arguments passed to the configuration. model_args: model arguments passed to the configuration. dataset_args: dataset arguments passed to the configuration. dataset: dataset to be use... | 2 | stack_v2_sparse_classes_30k_val_001037 | Implement the Python class `GFlowNetTrainingPipeline` described below.
Class description:
gflownet training pipelines.
Method signatures and docstrings:
- def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetD... | Implement the Python class `GFlowNetTrainingPipeline` described below.
Class description:
gflownet training pipelines.
Method signatures and docstrings:
- def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetD... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class GFlowNetTrainingPipeline:
"""gflownet training pipelines."""
def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetDataset, environment: GraphBuildingEnv, context: GraphBuildingEnvCont... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GFlowNetTrainingPipeline:
"""gflownet training pipelines."""
def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetDataset, environment: GraphBuildingEnv, context: GraphBuildingEnvContext, task: GF... | the_stack_v2_python_sparse | src/gt4sd/training_pipelines/pytorch_lightning/gflownet/core.py | GT4SD/gt4sd-core | train | 239 |
234d5beee030e0ba83a55e4ef6efca4d99cfcd97 | [
"if n <= 0:\n return [x, y]\nlargest = pow(2, n)\nif x < largest and y < largest:\n return [y, x]\nif x == y:\n return [x, y]\ni = 0\nwhile i < n:\n curr_bit = pow(2, i)\n if x & curr_bit != y & curr_bit:\n if x & curr_bit:\n x = x ^ curr_bit\n y = y | curr_bit\n e... | <|body_start_0|>
if n <= 0:
return [x, y]
largest = pow(2, n)
if x < largest and y < largest:
return [y, x]
if x == y:
return [x, y]
i = 0
while i < n:
curr_bit = pow(2, i)
if x & curr_bit != y & curr_bit:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swap(self, x, y, n):
""":type x,y,n: int :rtype: List[int]"""
<|body_0|>
def swap2(self, x, y, n):
""":type x,y,n: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n <= 0:
return [x, y]
large... | stack_v2_sparse_classes_36k_train_008413 | 4,682 | no_license | [
{
"docstring": ":type x,y,n: int :rtype: List[int]",
"name": "swap",
"signature": "def swap(self, x, y, n)"
},
{
"docstring": ":type x,y,n: int :rtype: List[int]",
"name": "swap2",
"signature": "def swap2(self, x, y, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swap(self, x, y, n): :type x,y,n: int :rtype: List[int]
- def swap2(self, x, y, n): :type x,y,n: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swap(self, x, y, n): :type x,y,n: int :rtype: List[int]
- def swap2(self, x, y, n): :type x,y,n: int :rtype: List[int]
<|skeleton|>
class Solution:
def swap(self, x, y,... | b155895c90169ec97372b2517f556fd50deac2bc | <|skeleton|>
class Solution:
def swap(self, x, y, n):
""":type x,y,n: int :rtype: List[int]"""
<|body_0|>
def swap2(self, x, y, n):
""":type x,y,n: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def swap(self, x, y, n):
""":type x,y,n: int :rtype: List[int]"""
if n <= 0:
return [x, y]
largest = pow(2, n)
if x < largest and y < largest:
return [y, x]
if x == y:
return [x, y]
i = 0
while i < n:
... | the_stack_v2_python_sparse | swap_n_bits.py | claytonjwong/Sandbox-Python | train | 0 | |
043b1a0e573a27db5c05be879b7c747e6f1a5e91 | [
"if candidates == [] or min(candidates) > target:\n return []\ncandidates.sort()\nres = []\nn = len(candidates)\n\ndef helper(i, rem, cur):\n if rem == 0:\n res.append(cur)\n return\n elif rem < 0:\n return\n for j in range(i, n):\n if candidates[j] > rem:\n break\... | <|body_start_0|>
if candidates == [] or min(candidates) > target:
return []
candidates.sort()
res = []
n = len(candidates)
def helper(i, rem, cur):
if rem == 0:
res.append(cur)
return
elif rem < 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
... | stack_v2_sparse_classes_36k_train_008414 | 1,694 | no_license | [
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]",
"name": "combinationSum",
"signature": "def combinationSum(self, candidates, target)"
},
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]",
"name": "combinationSum",
... | 2 | stack_v2_sparse_classes_30k_train_006418 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]]
- def combinationSum(self, candidates, target): :type candidat... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]]
- def combinationSum(self, candidates, target): :type candidat... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
if candidates == [] or min(candidates) > target:
return []
candidates.sort()
res = []
n = len(candidates)
def helper(... | the_stack_v2_python_sparse | 0039_Combination_Sum.py | bingli8802/leetcode | train | 0 | |
acccf0b305a7ac607754abc40cc2cb1f0e8c122b | [
"if not root:\n return ''\nresult = str(root.val)\nstack = [root]\ncount = 1\nwhile count != 0:\n node = stack.pop(0)\n count -= 1\n if node.left:\n stack.append(node.left)\n result += ',' + str(node.left.val)\n else:\n result += ',' + 'null'\n if node.right:\n stack.ap... | <|body_start_0|>
if not root:
return ''
result = str(root.val)
stack = [root]
count = 1
while count != 0:
node = stack.pop(0)
count -= 1
if node.left:
stack.append(node.left)
result += ',' + str(node.... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_008415 | 1,827 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 08500c39e14f3bf140db82a3dd2df4ca18705845 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
result = str(root.val)
stack = [root]
count = 1
while count != 0:
node = stack.pop(0)
count -= ... | the_stack_v2_python_sparse | python/297_serialize-and-deserialize-binary-tree/serializeAndDeserializeBinaryTree.py | kfrancischen/leetcode | train | 2 | |
cf80ab8c0390dcb1c01ba6d69ca95b2e605c1685 | [
"super().__init__()\nself.margin = margin\nself.reduction = reduction or 'none'",
"bs = len(distance_true)\nmargin_distance = self.margin - distance_pred\nmargin_distance_ = torch.clamp(margin_distance, min=0.0)\nloss = (1 - distance_true) * torch.pow(distance_pred, 2) + distance_true * torch.pow(margin_distance_... | <|body_start_0|>
super().__init__()
self.margin = margin
self.reduction = reduction or 'none'
<|end_body_0|>
<|body_start_1|>
bs = len(distance_true)
margin_distance = self.margin - distance_pred
margin_distance_ = torch.clamp(margin_distance, min=0.0)
loss = (1 ... | The Contrastive distance loss. @TODO: Docs. Contribution is welcome. | ContrastiveDistanceLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContrastiveDistanceLoss:
"""The Contrastive distance loss. @TODO: Docs. Contribution is welcome."""
def __init__(self, margin=1.0, reduction='mean'):
"""Args: margin: margin parameter reduction (str): criterion reduction type"""
<|body_0|>
def forward(self, distance_pred... | stack_v2_sparse_classes_36k_train_008416 | 4,346 | permissive | [
{
"docstring": "Args: margin: margin parameter reduction (str): criterion reduction type",
"name": "__init__",
"signature": "def __init__(self, margin=1.0, reduction='mean')"
},
{
"docstring": "Forward propagation method for the contrastive loss. Args: distance_pred: predicted distances distance... | 2 | stack_v2_sparse_classes_30k_train_018838 | Implement the Python class `ContrastiveDistanceLoss` described below.
Class description:
The Contrastive distance loss. @TODO: Docs. Contribution is welcome.
Method signatures and docstrings:
- def __init__(self, margin=1.0, reduction='mean'): Args: margin: margin parameter reduction (str): criterion reduction type
-... | Implement the Python class `ContrastiveDistanceLoss` described below.
Class description:
The Contrastive distance loss. @TODO: Docs. Contribution is welcome.
Method signatures and docstrings:
- def __init__(self, margin=1.0, reduction='mean'): Args: margin: margin parameter reduction (str): criterion reduction type
-... | a35297ecab8d1a6c2f00b6435ea1d6d37ec9f441 | <|skeleton|>
class ContrastiveDistanceLoss:
"""The Contrastive distance loss. @TODO: Docs. Contribution is welcome."""
def __init__(self, margin=1.0, reduction='mean'):
"""Args: margin: margin parameter reduction (str): criterion reduction type"""
<|body_0|>
def forward(self, distance_pred... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContrastiveDistanceLoss:
"""The Contrastive distance loss. @TODO: Docs. Contribution is welcome."""
def __init__(self, margin=1.0, reduction='mean'):
"""Args: margin: margin parameter reduction (str): criterion reduction type"""
super().__init__()
self.margin = margin
self... | the_stack_v2_python_sparse | catalyst/contrib/nn/criterion/contrastive.py | saswat0/catalyst | train | 2 |
20b9250cb1bcb81d1c15b62d3f5d9bf66f07cf55 | [
"Parametre.__init__(self, 'jeter', 'drop')\nself.aide_courte = \"jète l'ancre présente\"\nself.aide_longue = \"Cette commande jète l'ancre présente dans la salle où vous vous trouvez.\"",
"salle = personnage.salle\nif 'ancre' in personnage.etats:\n personnage << 'Vous cessez de peser sur le cabestan.'\n sal... | <|body_start_0|>
Parametre.__init__(self, 'jeter', 'drop')
self.aide_courte = "jète l'ancre présente"
self.aide_longue = "Cette commande jète l'ancre présente dans la salle où vous vous trouvez."
<|end_body_0|>
<|body_start_1|>
salle = personnage.salle
if 'ancre' in personnage.e... | Commande 'ancre jeter'. | PrmJeter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmJeter:
"""Commande 'ancre jeter'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametre.__ini... | stack_v2_sparse_classes_36k_train_008417 | 3,468 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmJeter` described below.
Class description:
Commande 'ancre jeter'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmJeter` described below.
Class description:
Commande 'ancre jeter'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmJeter:
"""Commande 'ancre jeter'.... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmJeter:
"""Commande 'ancre jeter'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmJeter:
"""Commande 'ancre jeter'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'jeter', 'drop')
self.aide_courte = "jète l'ancre présente"
self.aide_longue = "Cette commande jète l'ancre présente dans la salle où vous vous trouvez."
... | the_stack_v2_python_sparse | src/secondaires/navigation/commandes/ancre/jeter.py | vincent-lg/tsunami | train | 5 |
6aa3148a5099b11f1608536b75a68faace1a94be | [
"record = None\nrolesDao = RolesDao()\nid = request.uid\nrecord = rolesDao.getById(id)\nreturn record",
"roles = None\nrolesDao = RolesDao()\ntry:\n roles = rolesDao.add(args)\nexcept Exception as e:\n abort(500, e)\nreturn roles",
"result = False\nids = args.get('ids')\nrolesDao = RolesDao()\ntry:\n r... | <|body_start_0|>
record = None
rolesDao = RolesDao()
id = request.uid
record = rolesDao.getById(id)
return record
<|end_body_0|>
<|body_start_1|>
roles = None
rolesDao = RolesDao()
try:
roles = rolesDao.add(args)
except Exception as e:... | RolesAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RolesAPI:
def get(self):
"""view"""
<|body_0|>
def post(self, args):
"""add"""
<|body_1|>
def delete(self, args):
"""del"""
<|body_2|>
def put(self, args):
"""edit"""
<|body_3|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_008418 | 3,396 | permissive | [
{
"docstring": "view",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "add",
"name": "post",
"signature": "def post(self, args)"
},
{
"docstring": "del",
"name": "delete",
"signature": "def delete(self, args)"
},
{
"docstring": "edit",
"name": "... | 4 | null | Implement the Python class `RolesAPI` described below.
Class description:
Implement the RolesAPI class.
Method signatures and docstrings:
- def get(self): view
- def post(self, args): add
- def delete(self, args): del
- def put(self, args): edit | Implement the Python class `RolesAPI` described below.
Class description:
Implement the RolesAPI class.
Method signatures and docstrings:
- def get(self): view
- def post(self, args): add
- def delete(self, args): del
- def put(self, args): edit
<|skeleton|>
class RolesAPI:
def get(self):
"""view"""
... | 0fb1b604185a8bd8b72c1d2d527fb94bbaf46a86 | <|skeleton|>
class RolesAPI:
def get(self):
"""view"""
<|body_0|>
def post(self, args):
"""add"""
<|body_1|>
def delete(self, args):
"""del"""
<|body_2|>
def put(self, args):
"""edit"""
<|body_3|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RolesAPI:
def get(self):
"""view"""
record = None
rolesDao = RolesDao()
id = request.uid
record = rolesDao.getById(id)
return record
def post(self, args):
"""add"""
roles = None
rolesDao = RolesDao()
try:
roles = ... | the_stack_v2_python_sparse | app/modules/roles/resource.py | daitouli/baoaiback | train | 0 | |
e05abbef9c25320578f58a3065230ba6d8503014 | [
"if not root:\n return 'null'\nelse:\n return str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)",
"data = data.split(',')\n\ndef dfs(data):\n temp = data.pop(0)\n if temp == 'null':\n return None\n res = TreeNode(int(temp))\n res.left = dfs(data)\n res.... | <|body_start_0|>
if not root:
return 'null'
else:
return str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)
<|end_body_0|>
<|body_start_1|>
data = data.split(',')
def dfs(data):
temp = data.pop(0)
if temp =... | Codec_2 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec_2:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_008419 | 3,372 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec_2` described below.
Class description:
Implement the Codec_2 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rt... | Implement the Python class `Codec_2` described below.
Class description:
Implement the Codec_2 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rt... | a81007908e3c2f65a6be3ff2d62dfb92d0753b0d | <|skeleton|>
class Codec_2:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec_2:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return 'null'
else:
return str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)
def deserialize(self, da... | the_stack_v2_python_sparse | algo_probs/jzoffer/jz37.py | Jackthebighead/recruiment-2022 | train | 0 | |
be9af56f449fee7bca8ae45631eb110321075705 | [
"self.access_zone = access_zone\nself.cluster = cluster\nself.mount_point = mount_point\nself.name = name\nself.mtype = mtype",
"if dictionary is None:\n return None\naccess_zone = cohesity_management_sdk.models.isilon_access_zone.IsilonAccessZone.from_dictionary(dictionary.get('accessZone')) if dictionary.get... | <|body_start_0|>
self.access_zone = access_zone
self.cluster = cluster
self.mount_point = mount_point
self.name = name
self.mtype = mtype
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
access_zone = cohesity_management_sdk.models.i... | Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only when the entity type is 'kZone'. cluster (IsilonCluster): Specifies information of an Isi... | IsilonProtectionSource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsilonProtectionSource:
"""Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only when the entity type is 'kZone'. cluste... | stack_v2_sparse_classes_36k_train_008420 | 3,446 | permissive | [
{
"docstring": "Constructor for the IsilonProtectionSource class",
"name": "__init__",
"signature": "def __init__(self, access_zone=None, cluster=None, mount_point=None, name=None, mtype=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): ... | 2 | stack_v2_sparse_classes_30k_train_011921 | Implement the Python class `IsilonProtectionSource` described below.
Class description:
Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only ... | Implement the Python class `IsilonProtectionSource` described below.
Class description:
Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class IsilonProtectionSource:
"""Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only when the entity type is 'kZone'. cluste... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IsilonProtectionSource:
"""Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only when the entity type is 'kZone'. cluster (IsilonClus... | the_stack_v2_python_sparse | cohesity_management_sdk/models/isilon_protection_source.py | cohesity/management-sdk-python | train | 24 |
0407ade7ac509ee86b1a8ebe84396c8cfd24763a | [
"if amount == 0:\n return 0\ndp = [-1 for _ in range(amount + 1)]\ndp[0] = 0\nfor i in range(1, amount + 1):\n for j in range(len(coins)):\n if i - coins[j] >= 0 and dp[i - coins[j]] != -1:\n if dp[i] == -1 or dp[i] > dp[i - coins[j]] + 1:\n dp[i] = dp[i - coins[j]] + 1\n'\\n ... | <|body_start_0|>
if amount == 0:
return 0
dp = [-1 for _ in range(amount + 1)]
dp[0] = 0
for i in range(1, amount + 1):
for j in range(len(coins)):
if i - coins[j] >= 0 and dp[i - coins[j]] != -1:
if dp[i] == -1 or dp[i] > dp[i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coin_change(coins, amount):
"""动态规划 已知不同面值的钞票,求如何用最少数量的钞票组成某个金额,求可以使用的最少钞票数量。如果任意数量的已知面值钞票都无法组成该金额,则返回-1。 :type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coin_change_(coins, amount):
"""动态规划 比如说demo例子 递归逻辑为: f(11) = min(f(10), f(9... | stack_v2_sparse_classes_36k_train_008421 | 1,981 | no_license | [
{
"docstring": "动态规划 已知不同面值的钞票,求如何用最少数量的钞票组成某个金额,求可以使用的最少钞票数量。如果任意数量的已知面值钞票都无法组成该金额,则返回-1。 :type coins: List[int] :type amount: int :rtype: int",
"name": "coin_change",
"signature": "def coin_change(coins, amount)"
},
{
"docstring": "动态规划 比如说demo例子 递归逻辑为: f(11) = min(f(10), f(9), f(6)) + 1 :para... | 2 | stack_v2_sparse_classes_30k_train_006090 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coin_change(coins, amount): 动态规划 已知不同面值的钞票,求如何用最少数量的钞票组成某个金额,求可以使用的最少钞票数量。如果任意数量的已知面值钞票都无法组成该金额,则返回-1。 :type coins: List[int] :type amount: int :rtype: int
- def coin_change_... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coin_change(coins, amount): 动态规划 已知不同面值的钞票,求如何用最少数量的钞票组成某个金额,求可以使用的最少钞票数量。如果任意数量的已知面值钞票都无法组成该金额,则返回-1。 :type coins: List[int] :type amount: int :rtype: int
- def coin_change_... | 6479c0ad862a18d1021f35493e5e7d18d1ced5e4 | <|skeleton|>
class Solution:
def coin_change(coins, amount):
"""动态规划 已知不同面值的钞票,求如何用最少数量的钞票组成某个金额,求可以使用的最少钞票数量。如果任意数量的已知面值钞票都无法组成该金额,则返回-1。 :type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coin_change_(coins, amount):
"""动态规划 比如说demo例子 递归逻辑为: f(11) = min(f(10), f(9... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def coin_change(coins, amount):
"""动态规划 已知不同面值的钞票,求如何用最少数量的钞票组成某个金额,求可以使用的最少钞票数量。如果任意数量的已知面值钞票都无法组成该金额,则返回-1。 :type coins: List[int] :type amount: int :rtype: int"""
if amount == 0:
return 0
dp = [-1 for _ in range(amount + 1)]
dp[0] = 0
for i in r... | the_stack_v2_python_sparse | dp/CoinChange.py | Batman001/leetcode_in_python | train | 3 | |
05b655479137133b8a1209060873ac77b67ac0a2 | [
"def get_query():\n if np.random.rand() < prob:\n query_idx = np.random.randint(0, len(queries))\n query = queries[query_idx]\n else:\n query_idx = len(queries)\n query = np.random.choice([foo_token, bar_token, baz_token], size=3, replace=False)\n query = query.tolist()\n ... | <|body_start_0|>
def get_query():
if np.random.rand() < prob:
query_idx = np.random.randint(0, len(queries))
query = queries[query_idx]
else:
query_idx = len(queries)
query = np.random.choice([foo_token, bar_token, baz_token... | Utility that: - accepts user-specified queries and actions for those queries (that should be rewarded). - this requires specifying the vocab of tokens, and specifying the queries / actions for queries in terms of those vocab tokens - augments representations (i.e. builds out numpy.ndarray for DQN, torch.Tensor for SPG)... | RepresentationBuilder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepresentationBuilder:
"""Utility that: - accepts user-specified queries and actions for those queries (that should be rewarded). - this requires specifying the vocab of tokens, and specifying the queries / actions for queries in terms of those vocab tokens - augments representations (i.e. builds... | stack_v2_sparse_classes_36k_train_008422 | 14,400 | no_license | [
{
"docstring": "Args: queries (list of lists of ints): queries actions_per_query (list of list of ints): actions for corresponding queries to be rewarded K (int): size of state / query representation prob (float): probability with which to sample from queries (vs. random query)",
"name": "build_dqn",
"s... | 2 | stack_v2_sparse_classes_30k_train_008417 | Implement the Python class `RepresentationBuilder` described below.
Class description:
Utility that: - accepts user-specified queries and actions for those queries (that should be rewarded). - this requires specifying the vocab of tokens, and specifying the queries / actions for queries in terms of those vocab tokens ... | Implement the Python class `RepresentationBuilder` described below.
Class description:
Utility that: - accepts user-specified queries and actions for those queries (that should be rewarded). - this requires specifying the vocab of tokens, and specifying the queries / actions for queries in terms of those vocab tokens ... | 0d325b8cf5baed45edd4cbfcbe3c8366566b534a | <|skeleton|>
class RepresentationBuilder:
"""Utility that: - accepts user-specified queries and actions for those queries (that should be rewarded). - this requires specifying the vocab of tokens, and specifying the queries / actions for queries in terms of those vocab tokens - augments representations (i.e. builds... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RepresentationBuilder:
"""Utility that: - accepts user-specified queries and actions for those queries (that should be rewarded). - this requires specifying the vocab of tokens, and specifying the queries / actions for queries in terms of those vocab tokens - augments representations (i.e. builds out numpy.nd... | the_stack_v2_python_sparse | src/spg_agent/repr.py | jerwelborn/rlautoindex | train | 0 |
8408216e543fc05b4318910210dd6c3edfb12359 | [
"base_url = 'https://www.mylearningplan.com/DistrictAdmin/'\ndata = {'cbo_SelectDate1': 0, 'cbo_SelectDate2': 0, 'rad_FileFormat': 'Excel', 'DownloadKey': 'Download'}\nfor table in table_list:\n data['chk_' + table] = 'on'\nif date1 != None and date2 != None:\n data['cbo_DateLogic1'] = 'After'\n data['cbo_... | <|body_start_0|>
base_url = 'https://www.mylearningplan.com/DistrictAdmin/'
data = {'cbo_SelectDate1': 0, 'cbo_SelectDate2': 0, 'rad_FileFormat': 'Excel', 'DownloadKey': 'Download'}
for table in table_list:
data['chk_' + table] = 'on'
if date1 != None and date2 != None:
... | This mixin provides routines for downloading table data from PG | DownloadMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownloadMixin:
"""This mixin provides routines for downloading table data from PG"""
async def _get_tables(self, table_list, date1=None, date2=None):
"""Submits a POST request to download tables as an excel sheet, parses the result to follow the link, downloads the link and returns a... | stack_v2_sparse_classes_36k_train_008423 | 3,559 | no_license | [
{
"docstring": "Submits a POST request to download tables as an excel sheet, parses the result to follow the link, downloads the link and returns an xlrd book",
"name": "_get_tables",
"signature": "async def _get_tables(self, table_list, date1=None, date2=None)"
},
{
"docstring": "Creates orm ob... | 3 | null | Implement the Python class `DownloadMixin` described below.
Class description:
This mixin provides routines for downloading table data from PG
Method signatures and docstrings:
- async def _get_tables(self, table_list, date1=None, date2=None): Submits a POST request to download tables as an excel sheet, parses the re... | Implement the Python class `DownloadMixin` described below.
Class description:
This mixin provides routines for downloading table data from PG
Method signatures and docstrings:
- async def _get_tables(self, table_list, date1=None, date2=None): Submits a POST request to download tables as an excel sheet, parses the re... | 8645aa06581a83c7bfd307cf6600c4b9b86e9da5 | <|skeleton|>
class DownloadMixin:
"""This mixin provides routines for downloading table data from PG"""
async def _get_tables(self, table_list, date1=None, date2=None):
"""Submits a POST request to download tables as an excel sheet, parses the result to follow the link, downloads the link and returns a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DownloadMixin:
"""This mixin provides routines for downloading table data from PG"""
async def _get_tables(self, table_list, date1=None, date2=None):
"""Submits a POST request to download tables as an excel sheet, parses the result to follow the link, downloads the link and returns an xlrd book""... | the_stack_v2_python_sparse | AR/PG/download_mixin.py | FalconPD/alwaysRostering | train | 1 |
9ff447e29b7d616b66e8ceb1c5b981d0c4128e5b | [
"self.start_delay = True\nself.persistent = True\nself.db.time_format = None\nself.db.event_name = 'time'\nself.db.number = None",
"if self.db.time_format:\n seconds = self.ndb.usual\n if seconds is None:\n seconds, usual, details = get_next_wait(self.db.time_format)\n self.ndb.usual = usual\n... | <|body_start_0|>
self.start_delay = True
self.persistent = True
self.db.time_format = None
self.db.event_name = 'time'
self.db.number = None
<|end_body_0|>
<|body_start_1|>
if self.db.time_format:
seconds = self.ndb.usual
if seconds is None:
... | Gametime-sensitive script. | TimeEventScript | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeEventScript:
"""Gametime-sensitive script."""
def at_script_creation(self):
"""The script is created."""
<|body_0|>
def at_repeat(self):
"""Call the event and reset interval. It is necessary to restart the script to reset its interval only twice after a reloa... | stack_v2_sparse_classes_36k_train_008424 | 23,990 | permissive | [
{
"docstring": "The script is created.",
"name": "at_script_creation",
"signature": "def at_script_creation(self)"
},
{
"docstring": "Call the event and reset interval. It is necessary to restart the script to reset its interval only twice after a reload. When the script has undergone down time,... | 2 | null | Implement the Python class `TimeEventScript` described below.
Class description:
Gametime-sensitive script.
Method signatures and docstrings:
- def at_script_creation(self): The script is created.
- def at_repeat(self): Call the event and reset interval. It is necessary to restart the script to reset its interval onl... | Implement the Python class `TimeEventScript` described below.
Class description:
Gametime-sensitive script.
Method signatures and docstrings:
- def at_script_creation(self): The script is created.
- def at_repeat(self): Call the event and reset interval. It is necessary to restart the script to reset its interval onl... | b3ca58b5c1325a3bf57051dfe23560a08d2947b7 | <|skeleton|>
class TimeEventScript:
"""Gametime-sensitive script."""
def at_script_creation(self):
"""The script is created."""
<|body_0|>
def at_repeat(self):
"""Call the event and reset interval. It is necessary to restart the script to reset its interval only twice after a reloa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeEventScript:
"""Gametime-sensitive script."""
def at_script_creation(self):
"""The script is created."""
self.start_delay = True
self.persistent = True
self.db.time_format = None
self.db.event_name = 'time'
self.db.number = None
def at_repeat(self)... | the_stack_v2_python_sparse | evennia/contrib/base_systems/ingame_python/scripts.py | evennia/evennia | train | 1,781 |
172bf8e0ff332e0e65e18ecdceff3f7371c44626 | [
"super().__init__(_id, keyword_ref, keyword_string, language, text, timestamp, CrawlTypes.TWITTER.value, score, entities, categories)\nif categories is None:\n categories = []\nif entities is None:\n entities = []\nself.tweet_id = tweet_id\nself.likes = likes\nself.retweets = retweets",
"if not dict_input:\... | <|body_start_0|>
super().__init__(_id, keyword_ref, keyword_string, language, text, timestamp, CrawlTypes.TWITTER.value, score, entities, categories)
if categories is None:
categories = []
if entities is None:
entities = []
self.tweet_id = tweet_id
self.li... | This class serves the purpose of holding Twitter crawl result data | TwitterResult | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwitterResult:
"""This class serves the purpose of holding Twitter crawl result data"""
def __init__(self, _id, tweet_id, keyword_ref, keyword_string, language, text, timestamp, likes=0, retweets=0, score=None, entities=None, categories=None):
"""Set up all attributes :param ObjectId... | stack_v2_sparse_classes_36k_train_008425 | 2,857 | no_license | [
{
"docstring": "Set up all attributes :param ObjectId _id: The Object ID given by mongodb :param long tweet_id: The ID of the tweet given by Twitter :param ObjectId keyword_ref: The ID of the keyword which was used to generate the tweet :param str keyword_string: The target keyword that was used to generate the... | 2 | stack_v2_sparse_classes_30k_train_009203 | Implement the Python class `TwitterResult` described below.
Class description:
This class serves the purpose of holding Twitter crawl result data
Method signatures and docstrings:
- def __init__(self, _id, tweet_id, keyword_ref, keyword_string, language, text, timestamp, likes=0, retweets=0, score=None, entities=None... | Implement the Python class `TwitterResult` described below.
Class description:
This class serves the purpose of holding Twitter crawl result data
Method signatures and docstrings:
- def __init__(self, _id, tweet_id, keyword_ref, keyword_string, language, text, timestamp, likes=0, retweets=0, score=None, entities=None... | 3d775976f2ed26e944083112464aa62c6aea043e | <|skeleton|>
class TwitterResult:
"""This class serves the purpose of holding Twitter crawl result data"""
def __init__(self, _id, tweet_id, keyword_ref, keyword_string, language, text, timestamp, likes=0, retweets=0, score=None, entities=None, categories=None):
"""Set up all attributes :param ObjectId... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwitterResult:
"""This class serves the purpose of holding Twitter crawl result data"""
def __init__(self, _id, tweet_id, keyword_ref, keyword_string, language, text, timestamp, likes=0, retweets=0, score=None, entities=None, categories=None):
"""Set up all attributes :param ObjectId _id: The Obj... | the_stack_v2_python_sparse | common/mongo/data_types/crawling/crawl_results/twitter_result.py | alex1431999/APOA-Common | train | 0 |
81de6ce8f58ed927997d62da1ed88cf5e380606d | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | DishMadeServiceServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DishMadeServiceServicer:
"""Missing associated documentation comment in .proto file."""
def FindDishMades(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def ExecuteOrder(self, request, context):
"""Missing assoc... | stack_v2_sparse_classes_36k_train_008426 | 4,227 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "FindDishMades",
"signature": "def FindDishMades(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "ExecuteOrder",
"signature": "def ExecuteOrde... | 2 | stack_v2_sparse_classes_30k_train_015849 | Implement the Python class `DishMadeServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def FindDishMades(self, request, context): Missing associated documentation comment in .proto file.
- def ExecuteOrder(self, request, co... | Implement the Python class `DishMadeServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def FindDishMades(self, request, context): Missing associated documentation comment in .proto file.
- def ExecuteOrder(self, request, co... | 3259155c80e62dbb03e3afa1c53d162fbfb0a44c | <|skeleton|>
class DishMadeServiceServicer:
"""Missing associated documentation comment in .proto file."""
def FindDishMades(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def ExecuteOrder(self, request, context):
"""Missing assoc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DishMadeServiceServicer:
"""Missing associated documentation comment in .proto file."""
def FindDishMades(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not impleme... | the_stack_v2_python_sparse | services/pb/service_dish_made_pb2_grpc.py | guilhermealvess/distributed-systems-example | train | 0 |
6e5e2e7023706bffe94ddd681a96bb4fdc596442 | [
"self.batch_cmds = batch.batch_cmds\nself.set_status = set_status_func\nself.started = False\nself.success = False",
"can_continue = True\nself.started = True\nself.set_status('STARTED')\nlogger.info('Batch:\\n{0}'.format(self.batch_cmds))\nfor next_cmd in self.batch_cmds:\n logger.info('CWD=={0}'.format(next_... | <|body_start_0|>
self.batch_cmds = batch.batch_cmds
self.set_status = set_status_func
self.started = False
self.success = False
<|end_body_0|>
<|body_start_1|>
can_continue = True
self.started = True
self.set_status('STARTED')
logger.info('Batch:\n{0}'.fo... | BatchProcess | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchProcess:
def __init__(self, batch, set_status_func):
"""Initialize an instance of BatchProcess"""
<|body_0|>
def execute(self):
"""Start to execute a batch process"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.batch_cmds = batch.batch_cm... | stack_v2_sparse_classes_36k_train_008427 | 2,630 | permissive | [
{
"docstring": "Initialize an instance of BatchProcess",
"name": "__init__",
"signature": "def __init__(self, batch, set_status_func)"
},
{
"docstring": "Start to execute a batch process",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010715 | Implement the Python class `BatchProcess` described below.
Class description:
Implement the BatchProcess class.
Method signatures and docstrings:
- def __init__(self, batch, set_status_func): Initialize an instance of BatchProcess
- def execute(self): Start to execute a batch process | Implement the Python class `BatchProcess` described below.
Class description:
Implement the BatchProcess class.
Method signatures and docstrings:
- def __init__(self, batch, set_status_func): Initialize an instance of BatchProcess
- def execute(self): Start to execute a batch process
<|skeleton|>
class BatchProcess:... | 777db7d5dacf3ecf29a991f50d2ac78bb5bef66a | <|skeleton|>
class BatchProcess:
def __init__(self, batch, set_status_func):
"""Initialize an instance of BatchProcess"""
<|body_0|>
def execute(self):
"""Start to execute a batch process"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchProcess:
def __init__(self, batch, set_status_func):
"""Initialize an instance of BatchProcess"""
self.batch_cmds = batch.batch_cmds
self.set_status = set_status_func
self.started = False
self.success = False
def execute(self):
"""Start to execute a ba... | the_stack_v2_python_sparse | pyapi/addins-api/localapi/deploy/batch.py | dockerian/pyapi | train | 0 | |
2e2f0fbca08ab0eb24ded72cffff8ee06a57f478 | [
"l_obj = MqttBrokerData()\ntry:\n XmlConfigTools.read_base_object_xml(l_obj, p_xml)\n l_obj.BrokerAddress = PutGetXML.get_text_from_xml(p_xml, 'BrokerAddress')\n l_obj.BrokerPort = PutGetXML.get_int_from_xml(p_xml, 'BrokerPort')\n l_obj.UserName = PutGetXML.get_text_from_xml(p_xml, 'BrokerUser')\n l_... | <|body_start_0|>
l_obj = MqttBrokerData()
try:
XmlConfigTools.read_base_object_xml(l_obj, p_xml)
l_obj.BrokerAddress = PutGetXML.get_text_from_xml(p_xml, 'BrokerAddress')
l_obj.BrokerPort = PutGetXML.get_int_from_xml(p_xml, 'BrokerPort')
l_obj.UserName = P... | Xml | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Xml:
def _read_one_broker(p_xml):
"""@param p_xml: XML information for one Broker. @return: an IrrigationZone object filled in with data from the XML passed in"""
<|body_0|>
def read_mqtt_xml(p_pyhouse_obj):
"""Read all the broker information. Allow for several broke... | stack_v2_sparse_classes_36k_train_008428 | 3,772 | permissive | [
{
"docstring": "@param p_xml: XML information for one Broker. @return: an IrrigationZone object filled in with data from the XML passed in",
"name": "_read_one_broker",
"signature": "def _read_one_broker(p_xml)"
},
{
"docstring": "Read all the broker information. Allow for several brokers. @retu... | 4 | null | Implement the Python class `Xml` described below.
Class description:
Implement the Xml class.
Method signatures and docstrings:
- def _read_one_broker(p_xml): @param p_xml: XML information for one Broker. @return: an IrrigationZone object filled in with data from the XML passed in
- def read_mqtt_xml(p_pyhouse_obj): ... | Implement the Python class `Xml` described below.
Class description:
Implement the Xml class.
Method signatures and docstrings:
- def _read_one_broker(p_xml): @param p_xml: XML information for one Broker. @return: an IrrigationZone object filled in with data from the XML passed in
- def read_mqtt_xml(p_pyhouse_obj): ... | 6444ed0b4c38ab59b9e419e4d54d65d598e6a54e | <|skeleton|>
class Xml:
def _read_one_broker(p_xml):
"""@param p_xml: XML information for one Broker. @return: an IrrigationZone object filled in with data from the XML passed in"""
<|body_0|>
def read_mqtt_xml(p_pyhouse_obj):
"""Read all the broker information. Allow for several broke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Xml:
def _read_one_broker(p_xml):
"""@param p_xml: XML information for one Broker. @return: an IrrigationZone object filled in with data from the XML passed in"""
l_obj = MqttBrokerData()
try:
XmlConfigTools.read_base_object_xml(l_obj, p_xml)
l_obj.BrokerAddress... | the_stack_v2_python_sparse | src/Modules/Computer/Mqtt/mqtt_xml.py | bopopescu/PyHouse_1 | train | 0 | |
0c7c692536dc5e58d65661314e16b826ad56779f | [
"self.object = self.get_object()\nimages = self.object.simple_image_assets.all()\nform = SimpleImageForm()\nreturn {'images': images, 'form': form}",
"self.object = self.get_object()\ndocuments = self.object.simple_document_assets.all()\nform = SimpleDocumentForm()\nreturn {'documents': documents, 'form': form}",... | <|body_start_0|>
self.object = self.get_object()
images = self.object.simple_image_assets.all()
form = SimpleImageForm()
return {'images': images, 'form': form}
<|end_body_0|>
<|body_start_1|>
self.object = self.get_object()
documents = self.object.simple_document_assets... | Show assignment details. | AssignmentDetailView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssignmentDetailView:
"""Show assignment details."""
def simple_images(self):
"""Return simple images."""
<|body_0|>
def simple_documents(self):
"""Return simple documents."""
<|body_1|>
def simple_audio(self):
"""Return simple audio."""
... | stack_v2_sparse_classes_36k_train_008429 | 28,644 | permissive | [
{
"docstring": "Return simple images.",
"name": "simple_images",
"signature": "def simple_images(self)"
},
{
"docstring": "Return simple documents.",
"name": "simple_documents",
"signature": "def simple_documents(self)"
},
{
"docstring": "Return simple audio.",
"name": "simpl... | 4 | stack_v2_sparse_classes_30k_train_021292 | Implement the Python class `AssignmentDetailView` described below.
Class description:
Show assignment details.
Method signatures and docstrings:
- def simple_images(self): Return simple images.
- def simple_documents(self): Return simple documents.
- def simple_audio(self): Return simple audio.
- def simple_video(sel... | Implement the Python class `AssignmentDetailView` described below.
Class description:
Show assignment details.
Method signatures and docstrings:
- def simple_images(self): Return simple images.
- def simple_documents(self): Return simple documents.
- def simple_audio(self): Return simple audio.
- def simple_video(sel... | dc6bc79d450f7e2bdf59cfbcd306d05a736e4db9 | <|skeleton|>
class AssignmentDetailView:
"""Show assignment details."""
def simple_images(self):
"""Return simple images."""
<|body_0|>
def simple_documents(self):
"""Return simple documents."""
<|body_1|>
def simple_audio(self):
"""Return simple audio."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AssignmentDetailView:
"""Show assignment details."""
def simple_images(self):
"""Return simple images."""
self.object = self.get_object()
images = self.object.simple_image_assets.all()
form = SimpleImageForm()
return {'images': images, 'form': form}
def simple... | the_stack_v2_python_sparse | project/editorial/views/contractors.py | ProjectFacet/facet | train | 25 |
4465bedab331f4fc1378cddb2d4933ed199d76f4 | [
"super(Generator, self).__init__()\nself.stage = stage\nself.gf_dim = ngf\nself.ef_dim = nef\nself.nz = nz\nself.text_dim = text_dim\nself.define_module()",
"self.ca_net = CA_NET(self.text_dim, self.ef_dim)\nself.baw_net = BAW(self.gf_dim * 32, self.ef_dim, self.nz)\nif self.stage > 1:\n for p in self.baw_net.... | <|body_start_0|>
super(Generator, self).__init__()
self.stage = stage
self.gf_dim = ngf
self.ef_dim = nef
self.nz = nz
self.text_dim = text_dim
self.define_module()
<|end_body_0|>
<|body_start_1|>
self.ca_net = CA_NET(self.text_dim, self.ef_dim)
s... | Network Generator class. Args: - stage (int): generator's stage (1,2 or 3) - ngf (int): dimension of the generators filters - nef (int): condition dimension - nz (int): noise dimension - text_dim (int): original embedding dimension | Generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""Network Generator class. Args: - stage (int): generator's stage (1,2 or 3) - ngf (int): dimension of the generators filters - nef (int): condition dimension - nz (int): noise dimension - text_dim (int): original embedding dimension"""
def __init__(self, stage, ngf, nef, nz, tex... | stack_v2_sparse_classes_36k_train_008430 | 22,492 | no_license | [
{
"docstring": "Initialize the Generator's init stage.",
"name": "__init__",
"signature": "def __init__(self, stage, ngf, nef, nz, text_dim)"
},
{
"docstring": "Define the generator module.",
"name": "define_module",
"signature": "def define_module(self)"
},
{
"docstring": "Forwa... | 3 | stack_v2_sparse_classes_30k_train_017866 | Implement the Python class `Generator` described below.
Class description:
Network Generator class. Args: - stage (int): generator's stage (1,2 or 3) - ngf (int): dimension of the generators filters - nef (int): condition dimension - nz (int): noise dimension - text_dim (int): original embedding dimension
Method sign... | Implement the Python class `Generator` described below.
Class description:
Network Generator class. Args: - stage (int): generator's stage (1,2 or 3) - ngf (int): dimension of the generators filters - nef (int): condition dimension - nz (int): noise dimension - text_dim (int): original embedding dimension
Method sign... | 70d344d80425e7bbcc7984737dbe50a6638293c9 | <|skeleton|>
class Generator:
"""Network Generator class. Args: - stage (int): generator's stage (1,2 or 3) - ngf (int): dimension of the generators filters - nef (int): condition dimension - nz (int): noise dimension - text_dim (int): original embedding dimension"""
def __init__(self, stage, ngf, nef, nz, tex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
"""Network Generator class. Args: - stage (int): generator's stage (1,2 or 3) - ngf (int): dimension of the generators filters - nef (int): condition dimension - nz (int): noise dimension - text_dim (int): original embedding dimension"""
def __init__(self, stage, ngf, nef, nz, text_dim):
... | the_stack_v2_python_sparse | TeleGAN/model.py | ails-lab/teleGAN | train | 1 |
d2ee2110825937d5f5ba7031954c137f235f8100 | [
"if net is None:\n raise ValueError('Please provide input value for net. Currently set to None.')\nself.net = net\nself.nets = {'net': self.net}\nself.opt = Adam(self.net.parameters(), lr=lr)",
"_, actions = self.net.get_action(state)\nif self.device == 'gpu':\n actions = actions.cpu().numpy()\nelse:\n a... | <|body_start_0|>
if net is None:
raise ValueError('Please provide input value for net. Currently set to None.')
self.net = net
self.nets = {'net': self.net}
self.opt = Adam(self.net.parameters(), lr=lr)
<|end_body_0|>
<|body_start_1|>
_, actions = self.net.get_action... | ImitationAgent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImitationAgent:
def initialize(self, net: Union[BaseNetwork, None]=None, lr: float=0.001) -> None:
"""Initialization function for a simple BC agent. Parameters ---------- net: BaseNetwork, default=None policy network lr: float, default=0.001 learning rate Raises ------ ValueError: if `ne... | stack_v2_sparse_classes_36k_train_008431 | 3,103 | permissive | [
{
"docstring": "Initialization function for a simple BC agent. Parameters ---------- net: BaseNetwork, default=None policy network lr: float, default=0.001 learning rate Raises ------ ValueError: if `net` is not specified",
"name": "initialize",
"signature": "def initialize(self, net: Union[BaseNetwork,... | 3 | stack_v2_sparse_classes_30k_train_012411 | Implement the Python class `ImitationAgent` described below.
Class description:
Implement the ImitationAgent class.
Method signatures and docstrings:
- def initialize(self, net: Union[BaseNetwork, None]=None, lr: float=0.001) -> None: Initialization function for a simple BC agent. Parameters ---------- net: BaseNetwo... | Implement the Python class `ImitationAgent` described below.
Class description:
Implement the ImitationAgent class.
Method signatures and docstrings:
- def initialize(self, net: Union[BaseNetwork, None]=None, lr: float=0.001) -> None: Initialization function for a simple BC agent. Parameters ---------- net: BaseNetwo... | 6aecbe414f0032514ffb4206200596b8c3860b58 | <|skeleton|>
class ImitationAgent:
def initialize(self, net: Union[BaseNetwork, None]=None, lr: float=0.001) -> None:
"""Initialization function for a simple BC agent. Parameters ---------- net: BaseNetwork, default=None policy network lr: float, default=0.001 learning rate Raises ------ ValueError: if `ne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImitationAgent:
def initialize(self, net: Union[BaseNetwork, None]=None, lr: float=0.001) -> None:
"""Initialization function for a simple BC agent. Parameters ---------- net: BaseNetwork, default=None policy network lr: float, default=0.001 learning rate Raises ------ ValueError: if `net` is not spec... | the_stack_v2_python_sparse | ilpyt/agents/imitation_agent.py | mitre/ilpyt | train | 11 | |
74d5a35e0c2a2129e650edd03658e5f89ab5e4e8 | [
"self.filename = str(filename)\nself.action = action\nself.quiet = quiet\nself._last_mtime = 0\nif os.path.exists(self.filename):\n self._last_mtime = os.stat(self.filename).st_mtime",
"if not os.path.exists(self.filename):\n return False\nmtime = os.stat(self.filename).st_mtime\nif mtime <= self._last_mtim... | <|body_start_0|>
self.filename = str(filename)
self.action = action
self.quiet = quiet
self._last_mtime = 0
if os.path.exists(self.filename):
self._last_mtime = os.stat(self.filename).st_mtime
<|end_body_0|>
<|body_start_1|>
if not os.path.exists(self.filenam... | Performs action when file is modified. | FileWatcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileWatcher:
"""Performs action when file is modified."""
def __init__(self, filename, action, quiet=False):
"""Action is a function with no args. Filename is not required to exist. If quiet is True, caught exception will not be displayed."""
<|body_0|>
def check(self):
... | stack_v2_sparse_classes_36k_train_008432 | 8,222 | permissive | [
{
"docstring": "Action is a function with no args. Filename is not required to exist. If quiet is True, caught exception will not be displayed.",
"name": "__init__",
"signature": "def __init__(self, filename, action, quiet=False)"
},
{
"docstring": "If filename is updated since the last check, p... | 2 | stack_v2_sparse_classes_30k_train_020214 | Implement the Python class `FileWatcher` described below.
Class description:
Performs action when file is modified.
Method signatures and docstrings:
- def __init__(self, filename, action, quiet=False): Action is a function with no args. Filename is not required to exist. If quiet is True, caught exception will not b... | Implement the Python class `FileWatcher` described below.
Class description:
Performs action when file is modified.
Method signatures and docstrings:
- def __init__(self, filename, action, quiet=False): Action is a function with no args. Filename is not required to exist. If quiet is True, caught exception will not b... | a7e880e189bfa4793f30ff928b049e4a182a38cd | <|skeleton|>
class FileWatcher:
"""Performs action when file is modified."""
def __init__(self, filename, action, quiet=False):
"""Action is a function with no args. Filename is not required to exist. If quiet is True, caught exception will not be displayed."""
<|body_0|>
def check(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileWatcher:
"""Performs action when file is modified."""
def __init__(self, filename, action, quiet=False):
"""Action is a function with no args. Filename is not required to exist. If quiet is True, caught exception will not be displayed."""
self.filename = str(filename)
self.act... | the_stack_v2_python_sparse | lib/clckwrkbdgr/fs.py | clckwrkbdgr/dotfiles | train | 2 |
162d0fdc1f6466634341acc039c5baca02ec03f3 | [
"if isinstance(degrees, numbers.Number):\n if degrees < 0:\n raise ValueError('If degrees is a single number, it must be positive.')\n self.degrees = (-degrees, degrees)\nelse:\n if len(degrees) != 2:\n raise ValueError('If degrees is a sequence, it must be of len 2.')\n self.degrees = deg... | <|body_start_0|>
if isinstance(degrees, numbers.Number):
if degrees < 0:
raise ValueError('If degrees is a single number, it must be positive.')
self.degrees = (-degrees, degrees)
else:
if len(degrees) != 2:
raise ValueError('If degrees... | Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin is the upper left corner. Default is the ce... | RandomRotation4D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomRotation4D:
"""Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin... | stack_v2_sparse_classes_36k_train_008433 | 34,927 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, degrees, rotate_planes=[[0, 1], [0, 2], [1, 2]])"
},
{
"docstring": "Get parameters for ``rotate`` for a random rotation. Returns: sequence: params to be passed to ``rotate`` for random rotation.",
"name": "get_param... | 3 | stack_v2_sparse_classes_30k_train_008734 | Implement the Python class `RandomRotation4D` described below.
Class description:
Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optiona... | Implement the Python class `RandomRotation4D` described below.
Class description:
Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optiona... | 2c8c35a8949fef74599f5ec557d340a14415f20d | <|skeleton|>
class RandomRotation4D:
"""Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomRotation4D:
"""Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin is the upper... | the_stack_v2_python_sparse | contrib/MedicalSeg/medicalseg/transforms/transform.py | PaddlePaddle/PaddleSeg | train | 8,531 |
a0bf7ae96bd3d266e5208706424ac4bc28e1e06c | [
"assert callable(item_maker), f'{repr(item_maker)} not callable.'\nself._pool_item_maker = item_maker\nself._key_to_pool: Dict[Hashable, list] = defaultdict(list)\nself._pool_item_id_to_is_acquired: Dict[int, bool] = {}\nself._thread_lock = Lock()",
"with self._thread_lock:\n pool = self._key_to_pool[key]\n ... | <|body_start_0|>
assert callable(item_maker), f'{repr(item_maker)} not callable.'
self._pool_item_maker = item_maker
self._key_to_pool: Dict[Hashable, list] = defaultdict(list)
self._pool_item_id_to_is_acquired: Dict[int, bool] = {}
self._thread_lock = Lock()
<|end_body_0|>
<|bo... | Thread-safe **key pool** (i.e., object cache implemented as a dictionary of lists of arbitrary objects to be cached, where objects cached to the same list are typically of the same type). Key pools are thread-safe by design and thus safely usable as module-scoped globals accessed from module-scoped callables. Attribute... | KeyPool | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyPool:
"""Thread-safe **key pool** (i.e., object cache implemented as a dictionary of lists of arbitrary objects to be cached, where objects cached to the same list are typically of the same type). Key pools are thread-safe by design and thus safely usable as module-scoped globals accessed from... | stack_v2_sparse_classes_36k_train_008434 | 12,902 | permissive | [
{
"docstring": "Initialize this key pool with the passed factory callable. Parameters ---------- item_maker : Union[type, Callable[[Hashable,], Any]] Caller-defined factory callable internally called by the :meth:`acquire` method on attempting to acquire a non-existent object from an **empty pool** (i.e., eithe... | 3 | null | Implement the Python class `KeyPool` described below.
Class description:
Thread-safe **key pool** (i.e., object cache implemented as a dictionary of lists of arbitrary objects to be cached, where objects cached to the same list are typically of the same type). Key pools are thread-safe by design and thus safely usable... | Implement the Python class `KeyPool` described below.
Class description:
Thread-safe **key pool** (i.e., object cache implemented as a dictionary of lists of arbitrary objects to be cached, where objects cached to the same list are typically of the same type). Key pools are thread-safe by design and thus safely usable... | 0cfd53391eb4de2f8297a4632aa5895b8d82a5b7 | <|skeleton|>
class KeyPool:
"""Thread-safe **key pool** (i.e., object cache implemented as a dictionary of lists of arbitrary objects to be cached, where objects cached to the same list are typically of the same type). Key pools are thread-safe by design and thus safely usable as module-scoped globals accessed from... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeyPool:
"""Thread-safe **key pool** (i.e., object cache implemented as a dictionary of lists of arbitrary objects to be cached, where objects cached to the same list are typically of the same type). Key pools are thread-safe by design and thus safely usable as module-scoped globals accessed from module-scope... | the_stack_v2_python_sparse | beartype/_util/cache/pool/utilcachepool.py | beartype/beartype | train | 1,992 |
35a54e0fb129c33ad1aeb5a68fa1648a213625e9 | [
"self.id = id\nself.amount = amount\nself.posted_date = posted_date\nself.description = description\nself.normalized_payee = normalized_payee\nself.institution_transaction_id = institution_transaction_id\nself.category = category\nself.memo = memo\nself.additional_properties = additional_properties",
"if dictiona... | <|body_start_0|>
self.id = id
self.amount = amount
self.posted_date = posted_date
self.description = description
self.normalized_payee = normalized_payee
self.institution_transaction_id = institution_transaction_id
self.category = category
self.memo = memo... | Implementation of the 'Transactions Report Transaction' model. The fields used in the Transactions Report Transactions record Attributes: id (long|int): The Finicity ID of the financial transaction. amount (float): The total amount of the transaction. Transactions for deposits are positive values, and withdrawals and d... | TransactionsReportTransaction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransactionsReportTransaction:
"""Implementation of the 'Transactions Report Transaction' model. The fields used in the Transactions Report Transactions record Attributes: id (long|int): The Finicity ID of the financial transaction. amount (float): The total amount of the transaction. Transaction... | stack_v2_sparse_classes_36k_train_008435 | 4,376 | permissive | [
{
"docstring": "Constructor for the TransactionsReportTransaction class",
"name": "__init__",
"signature": "def __init__(self, id=None, amount=None, posted_date=None, description=None, normalized_payee=None, institution_transaction_id=None, category=None, memo=None, additional_properties={})"
},
{
... | 2 | stack_v2_sparse_classes_30k_val_001051 | Implement the Python class `TransactionsReportTransaction` described below.
Class description:
Implementation of the 'Transactions Report Transaction' model. The fields used in the Transactions Report Transactions record Attributes: id (long|int): The Finicity ID of the financial transaction. amount (float): The total... | Implement the Python class `TransactionsReportTransaction` described below.
Class description:
Implementation of the 'Transactions Report Transaction' model. The fields used in the Transactions Report Transactions record Attributes: id (long|int): The Finicity ID of the financial transaction. amount (float): The total... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class TransactionsReportTransaction:
"""Implementation of the 'Transactions Report Transaction' model. The fields used in the Transactions Report Transactions record Attributes: id (long|int): The Finicity ID of the financial transaction. amount (float): The total amount of the transaction. Transaction... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransactionsReportTransaction:
"""Implementation of the 'Transactions Report Transaction' model. The fields used in the Transactions Report Transactions record Attributes: id (long|int): The Finicity ID of the financial transaction. amount (float): The total amount of the transaction. Transactions for deposit... | the_stack_v2_python_sparse | finicityapi/models/transactions_report_transaction.py | monarchmoney/finicity-python | train | 0 |
b23fd02e5e145d12dbb4c79d548bdeb978710982 | [
"self.name = path\nself.action = 'read'\nif md5:\n self.attributes['md5'] = True\nif content:\n self.attributes['get_content'] = True\nreturn self.request()",
"self.name = path\nself.action = 'create'\nself.monitor = monitor\nif content:\n self.attributes['content'] = content\nif owner:\n self.attribu... | <|body_start_0|>
self.name = path
self.action = 'read'
if md5:
self.attributes['md5'] = True
if content:
self.attributes['get_content'] = True
return self.request()
<|end_body_0|>
<|body_start_1|>
self.name = path
self.action = 'create'
... | FilesApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilesApi:
def infos(self, path, md5=False, content=False):
"""Retrieves the meta data of the file. Owner, group, mode, modification time. @param path: The file path @type path: String @param md5: Set this to True if the md5 hash must be retrieved. @type md5: bool @param content: Set this... | stack_v2_sparse_classes_36k_train_008436 | 4,271 | permissive | [
{
"docstring": "Retrieves the meta data of the file. Owner, group, mode, modification time. @param path: The file path @type path: String @param md5: Set this to True if the md5 hash must be retrieved. @type md5: bool @param content: Set this to True if the file content must be retrieved. @type content: bool",
... | 6 | stack_v2_sparse_classes_30k_train_020143 | Implement the Python class `FilesApi` described below.
Class description:
Implement the FilesApi class.
Method signatures and docstrings:
- def infos(self, path, md5=False, content=False): Retrieves the meta data of the file. Owner, group, mode, modification time. @param path: The file path @type path: String @param ... | Implement the Python class `FilesApi` described below.
Class description:
Implement the FilesApi class.
Method signatures and docstrings:
- def infos(self, path, md5=False, content=False): Retrieves the meta data of the file. Owner, group, mode, modification time. @param path: The file path @type path: String @param ... | 9bc7fcc09367bc1f6ac7baff6f38fde9cbcdbf39 | <|skeleton|>
class FilesApi:
def infos(self, path, md5=False, content=False):
"""Retrieves the meta data of the file. Owner, group, mode, modification time. @param path: The file path @type path: String @param md5: Set this to True if the md5 hash must be retrieved. @type md5: bool @param content: Set this... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilesApi:
def infos(self, path, md5=False, content=False):
"""Retrieves the meta data of the file. Owner, group, mode, modification time. @param path: The file path @type path: String @param md5: Set this to True if the md5 hash must be retrieved. @type md5: bool @param content: Set this to True if th... | the_stack_v2_python_sparse | syncli/api/files.py | ethereus/synapse-client | train | 0 | |
96866b87a5c2e6e0b286fb2b7509f1177f39aec3 | [
"super().__init__()\nimport sklearn\nimport sklearn.neighbors\nself.model = sklearn.neighbors.NearestCentroid",
"specs = super().getInputSpecification()\nspecs.description = 'The \\\\xmlNode{RadiusNeighborsClassifier} is a type of instance-based learning or\\n non-generalizing learning: it... | <|body_start_0|>
super().__init__()
import sklearn
import sklearn.neighbors
self.model = sklearn.neighbors.NearestCentroid
<|end_body_0|>
<|body_start_1|>
specs = super().getInputSpecification()
specs.description = 'The \\xmlNode{RadiusNeighborsClassifier} is a type of i... | Nearest Centroid Classifier | NearestCentroid | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NearestCentroid:
"""Nearest Centroid Classifier"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class that... | stack_v2_sparse_classes_36k_train_008437 | 4,877 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 3 | null | Implement the Python class `NearestCentroid` described below.
Class description:
Nearest Centroid Classifier
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a refe... | Implement the Python class `NearestCentroid` described below.
Class description:
Nearest Centroid Classifier
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a refe... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class NearestCentroid:
"""Nearest Centroid Classifier"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class that... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NearestCentroid:
"""Nearest Centroid Classifier"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
super().__init__()
import sklearn
import sklearn.neighbors
self.model = sklearn.neighbors... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/Neighbors/NearestCentroidClassifier.py | idaholab/raven | train | 201 |
ba4618e3b8abf4ee0dd66a146f28ff1c1ff1fd1e | [
"server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver_socket.bind(('', 10086))\nserver_socket.listen(128)\nself.server_socket = server_socket",
"while True:\n client_socket, client_addr = self.server_socket.accept()\n ... | <|body_start_0|>
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('', 10086))
server_socket.listen(128)
self.server_socket = server_socket
<|end_body_0|>
<|body_start_1|>
... | 为用户提供web服务 | HTTPServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTTPServer:
"""为用户提供web服务"""
def __init__(self):
"""初始化对象的属性"""
<|body_0|>
def start(self):
"""启动web服务"""
<|body_1|>
def client_request_handler(self, client_socket):
"""专门用来处理每个客户端的HTTP请求"""
<|body_2|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_008438 | 3,487 | no_license | [
{
"docstring": "初始化对象的属性",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "启动web服务",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "专门用来处理每个客户端的HTTP请求",
"name": "client_request_handler",
"signature": "def client_request_handler... | 3 | stack_v2_sparse_classes_30k_train_014359 | Implement the Python class `HTTPServer` described below.
Class description:
为用户提供web服务
Method signatures and docstrings:
- def __init__(self): 初始化对象的属性
- def start(self): 启动web服务
- def client_request_handler(self, client_socket): 专门用来处理每个客户端的HTTP请求 | Implement the Python class `HTTPServer` described below.
Class description:
为用户提供web服务
Method signatures and docstrings:
- def __init__(self): 初始化对象的属性
- def start(self): 启动web服务
- def client_request_handler(self, client_socket): 专门用来处理每个客户端的HTTP请求
<|skeleton|>
class HTTPServer:
"""为用户提供web服务"""
def __init_... | c82b7d435dc11016e24cde2bdc4a558f507cb668 | <|skeleton|>
class HTTPServer:
"""为用户提供web服务"""
def __init__(self):
"""初始化对象的属性"""
<|body_0|>
def start(self):
"""启动web服务"""
<|body_1|>
def client_request_handler(self, client_socket):
"""专门用来处理每个客户端的HTTP请求"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HTTPServer:
"""为用户提供web服务"""
def __init__(self):
"""初始化对象的属性"""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('', 10086))
server_socket.listen(128)
s... | the_stack_v2_python_sparse | python_code/chuanzhi/python_advance/17/step_next/04_oop_version.py | googleliyang/gitbook_cz_python | train | 1 |
a8f3c7a256a5eb5b06b6988049109bae6d20b7bc | [
"self.target = target\nself.eta = eta\nself.delta0 = delta0\nself.delta1 = delta1\nself.weights_new = weights_new\nself.biases_new = biases_new",
"print('Target:')\nprint(self.target)\nprint(f'\\nEta (learning rate): {self.eta}')\nprint('\\nDelta 0 (closest to output):')\nprint(self.delta0)\nprint('\\nDelta 1 (cl... | <|body_start_0|>
self.target = target
self.eta = eta
self.delta0 = delta0
self.delta1 = delta1
self.weights_new = weights_new
self.biases_new = biases_new
<|end_body_0|>
<|body_start_1|>
print('Target:')
print(self.target)
print(f'\nEta (learning ... | Describes the results of backpropagation. | Backprop | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Backprop:
"""Describes the results of backpropagation."""
def __init__(self, target, eta, delta0, delta1, weights_new, biases_new):
"""Create starting parts of the backprop."""
<|body_0|>
def describe(self):
"""Print information about the backpropagation."""
... | stack_v2_sparse_classes_36k_train_008439 | 11,919 | no_license | [
{
"docstring": "Create starting parts of the backprop.",
"name": "__init__",
"signature": "def __init__(self, target, eta, delta0, delta1, weights_new, biases_new)"
},
{
"docstring": "Print information about the backpropagation.",
"name": "describe",
"signature": "def describe(self)"
}... | 2 | stack_v2_sparse_classes_30k_train_020814 | Implement the Python class `Backprop` described below.
Class description:
Describes the results of backpropagation.
Method signatures and docstrings:
- def __init__(self, target, eta, delta0, delta1, weights_new, biases_new): Create starting parts of the backprop.
- def describe(self): Print information about the bac... | Implement the Python class `Backprop` described below.
Class description:
Describes the results of backpropagation.
Method signatures and docstrings:
- def __init__(self, target, eta, delta0, delta1, weights_new, biases_new): Create starting parts of the backprop.
- def describe(self): Print information about the bac... | bdde45fc936783fd80589c53e23aa3aabd11cc88 | <|skeleton|>
class Backprop:
"""Describes the results of backpropagation."""
def __init__(self, target, eta, delta0, delta1, weights_new, biases_new):
"""Create starting parts of the backprop."""
<|body_0|>
def describe(self):
"""Print information about the backpropagation."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Backprop:
"""Describes the results of backpropagation."""
def __init__(self, target, eta, delta0, delta1, weights_new, biases_new):
"""Create starting parts of the backprop."""
self.target = target
self.eta = eta
self.delta0 = delta0
self.delta1 = delta1
se... | the_stack_v2_python_sparse | Artificial Intelligence and Deep Learning/Training X-OR with Backpropagation/Codes/results_xor.py | yfeng47/Data-Science-Portfolio | train | 1 |
c7c0d475d7f359322f3080ceccd7a4f111d528d9 | [
"temp = 0\ny = x\nif x < 0:\n return False\nelif x == 0:\n return True\nelif x > 0:\n while x:\n temp = temp * 10 + x % 10\n x = int(x / 10)\n if temp == y:\n return True\n else:\n return False",
"new_x = x\nres = 0\nif x < 0:\n return False\nwhile new_x >= 1:\n a ... | <|body_start_0|>
temp = 0
y = x
if x < 0:
return False
elif x == 0:
return True
elif x > 0:
while x:
temp = temp * 10 + x % 10
x = int(x / 10)
if temp == y:
return True
els... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, x: int) -> bool:
"""思路是设置一个为0的整数tmp,输入的数(x)取余拿到末尾数 tmp*10拿到首位数字加上末尾数得到新的tmp的第一个数 以此类推完整的倒序整个输入的x。 需要注意的有两点 1、每次过后x必须除以10再取整,保证每次都取到的是最后一位数字 2、必须要把x备份一下,否则过程中因为除以10了,x的结果会变成0 :param x: :return:"""
<|body_0|>
def isPalindrome2(self, x: int) -> ... | stack_v2_sparse_classes_36k_train_008440 | 1,619 | no_license | [
{
"docstring": "思路是设置一个为0的整数tmp,输入的数(x)取余拿到末尾数 tmp*10拿到首位数字加上末尾数得到新的tmp的第一个数 以此类推完整的倒序整个输入的x。 需要注意的有两点 1、每次过后x必须除以10再取整,保证每次都取到的是最后一位数字 2、必须要把x备份一下,否则过程中因为除以10了,x的结果会变成0 :param x: :return:",
"name": "isPalindrome",
"signature": "def isPalindrome(self, x: int) -> bool"
},
{
"docstring": "2020年6月1... | 2 | stack_v2_sparse_classes_30k_train_016639 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, x: int) -> bool: 思路是设置一个为0的整数tmp,输入的数(x)取余拿到末尾数 tmp*10拿到首位数字加上末尾数得到新的tmp的第一个数 以此类推完整的倒序整个输入的x。 需要注意的有两点 1、每次过后x必须除以10再取整,保证每次都取到的是最后一位数字 2、必须要把x备份一下,否则过程中因... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, x: int) -> bool: 思路是设置一个为0的整数tmp,输入的数(x)取余拿到末尾数 tmp*10拿到首位数字加上末尾数得到新的tmp的第一个数 以此类推完整的倒序整个输入的x。 需要注意的有两点 1、每次过后x必须除以10再取整,保证每次都取到的是最后一位数字 2、必须要把x备份一下,否则过程中因... | 578cacff5851c5c2522981693c34e3c318002d30 | <|skeleton|>
class Solution:
def isPalindrome(self, x: int) -> bool:
"""思路是设置一个为0的整数tmp,输入的数(x)取余拿到末尾数 tmp*10拿到首位数字加上末尾数得到新的tmp的第一个数 以此类推完整的倒序整个输入的x。 需要注意的有两点 1、每次过后x必须除以10再取整,保证每次都取到的是最后一位数字 2、必须要把x备份一下,否则过程中因为除以10了,x的结果会变成0 :param x: :return:"""
<|body_0|>
def isPalindrome2(self, x: int) -> ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, x: int) -> bool:
"""思路是设置一个为0的整数tmp,输入的数(x)取余拿到末尾数 tmp*10拿到首位数字加上末尾数得到新的tmp的第一个数 以此类推完整的倒序整个输入的x。 需要注意的有两点 1、每次过后x必须除以10再取整,保证每次都取到的是最后一位数字 2、必须要把x备份一下,否则过程中因为除以10了,x的结果会变成0 :param x: :return:"""
temp = 0
y = x
if x < 0:
return False... | the_stack_v2_python_sparse | 回文数.py | cjrzs/MyLeetCode | train | 8 | |
52ddaa0a584115434cd4de02da4cc3118a7a2b63 | [
"try:\n res = requests.get(url, params=params, **kwargs)\nexcept Exception:\n logging.info('访问get请求不成功')\nelse:\n return res",
"try:\n res = requests.post(url, data=data, json=json, **kwargs)\nexcept Exception:\n logging.info(url, data, json, **kwargs)\n logging.info('访问post请求不成功')\nelse:\n r... | <|body_start_0|>
try:
res = requests.get(url, params=params, **kwargs)
except Exception:
logging.info('访问get请求不成功')
else:
return res
<|end_body_0|>
<|body_start_1|>
try:
res = requests.post(url, data=data, json=json, **kwargs)
exce... | 不需要记住cookie信息的请求类 | RequestsHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestsHandler:
"""不需要记住cookie信息的请求类"""
def get(self, url, params=None, **kwargs):
"""发送get请求 params 传递参数就是放到URL里面传递 data 在form表单中传递参数"""
<|body_0|>
def post(self, url, data=None, json=None, **kwargs):
"""发送post请求"""
<|body_1|>
def visit(self, metho... | stack_v2_sparse_classes_36k_train_008441 | 4,741 | no_license | [
{
"docstring": "发送get请求 params 传递参数就是放到URL里面传递 data 在form表单中传递参数",
"name": "get",
"signature": "def get(self, url, params=None, **kwargs)"
},
{
"docstring": "发送post请求",
"name": "post",
"signature": "def post(self, url, data=None, json=None, **kwargs)"
},
{
"docstring": "访问 get 和 ... | 4 | stack_v2_sparse_classes_30k_train_018687 | Implement the Python class `RequestsHandler` described below.
Class description:
不需要记住cookie信息的请求类
Method signatures and docstrings:
- def get(self, url, params=None, **kwargs): 发送get请求 params 传递参数就是放到URL里面传递 data 在form表单中传递参数
- def post(self, url, data=None, json=None, **kwargs): 发送post请求
- def visit(self, method, u... | Implement the Python class `RequestsHandler` described below.
Class description:
不需要记住cookie信息的请求类
Method signatures and docstrings:
- def get(self, url, params=None, **kwargs): 发送get请求 params 传递参数就是放到URL里面传递 data 在form表单中传递参数
- def post(self, url, data=None, json=None, **kwargs): 发送post请求
- def visit(self, method, u... | cfadd3132c2c7c518c784589e0dab6510a662a6c | <|skeleton|>
class RequestsHandler:
"""不需要记住cookie信息的请求类"""
def get(self, url, params=None, **kwargs):
"""发送get请求 params 传递参数就是放到URL里面传递 data 在form表单中传递参数"""
<|body_0|>
def post(self, url, data=None, json=None, **kwargs):
"""发送post请求"""
<|body_1|>
def visit(self, metho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestsHandler:
"""不需要记住cookie信息的请求类"""
def get(self, url, params=None, **kwargs):
"""发送get请求 params 传递参数就是放到URL里面传递 data 在form表单中传递参数"""
try:
res = requests.get(url, params=params, **kwargs)
except Exception:
logging.info('访问get请求不成功')
else:
... | the_stack_v2_python_sparse | yiqihai/tebiemiao/Interface/common/requests_handler.py | songyongzhuang/PythonCode_office | train | 0 |
fcf5376c81d87f208227a8f2781511082bc43701 | [
"re = cloudparking_service(centerMonitorLogin).mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])\nresult = re\nAssertions().assert_in_text(result, expect['mockCarInMessage'])",
"re = CarInOutHandle(centerMonitorLogin).checkCarIn(send_data['carNum'])\nresult = re['status']\nAssertions().assert_text(res... | <|body_start_0|>
re = cloudparking_service(centerMonitorLogin).mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMessage'])
<|end_body_0|>
<|body_start_1|>
re = CarInOutHandle(centerMonitorLogin).checkCarIn(sen... | TestDutyRoomHandleCarInOut | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDutyRoomHandleCarInOut:
def test_mockCarIn(self, centerMonitorLogin, send_data, expect):
"""模拟车辆进场"""
<|body_0|>
def test_dutyRoomCheckCarIn(self, centerMonitorLogin, send_data, expect):
"""值班室登记放行车辆"""
<|body_1|>
def test_cendutyCarInRecord(self, ce... | stack_v2_sparse_classes_36k_train_008442 | 3,464 | no_license | [
{
"docstring": "模拟车辆进场",
"name": "test_mockCarIn",
"signature": "def test_mockCarIn(self, centerMonitorLogin, send_data, expect)"
},
{
"docstring": "值班室登记放行车辆",
"name": "test_dutyRoomCheckCarIn",
"signature": "def test_dutyRoomCheckCarIn(self, centerMonitorLogin, send_data, expect)"
},... | 3 | stack_v2_sparse_classes_30k_train_021079 | Implement the Python class `TestDutyRoomHandleCarInOut` described below.
Class description:
Implement the TestDutyRoomHandleCarInOut class.
Method signatures and docstrings:
- def test_mockCarIn(self, centerMonitorLogin, send_data, expect): 模拟车辆进场
- def test_dutyRoomCheckCarIn(self, centerMonitorLogin, send_data, exp... | Implement the Python class `TestDutyRoomHandleCarInOut` described below.
Class description:
Implement the TestDutyRoomHandleCarInOut class.
Method signatures and docstrings:
- def test_mockCarIn(self, centerMonitorLogin, send_data, expect): 模拟车辆进场
- def test_dutyRoomCheckCarIn(self, centerMonitorLogin, send_data, exp... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestDutyRoomHandleCarInOut:
def test_mockCarIn(self, centerMonitorLogin, send_data, expect):
"""模拟车辆进场"""
<|body_0|>
def test_dutyRoomCheckCarIn(self, centerMonitorLogin, send_data, expect):
"""值班室登记放行车辆"""
<|body_1|>
def test_cendutyCarInRecord(self, ce... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDutyRoomHandleCarInOut:
def test_mockCarIn(self, centerMonitorLogin, send_data, expect):
"""模拟车辆进场"""
re = cloudparking_service(centerMonitorLogin).mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarI... | the_stack_v2_python_sparse | test_suite/centerMonitorRoom/carInOutHandle/test_dutyRoomHandleCarInOut.py | oyebino/pomp_api | train | 1 | |
03d5b85c85e361b482ae940c56802bd38977f09e | [
"if send_notifications:\n send_notifications_string = 'SendToAllAndSaveCopy'\nelse:\n send_notifications_string = 'SendToNone'\nroot = M.DeleteItem(M.ItemIds(item_id.to_xml()), DeleteType='HardDelete', SendMeetingCancellations=send_notifications_string, AffectedTaskOccurrences='AllOccurrences')\nsuper(DeleteC... | <|body_start_0|>
if send_notifications:
send_notifications_string = 'SendToAllAndSaveCopy'
else:
send_notifications_string = 'SendToNone'
root = M.DeleteItem(M.ItemIds(item_id.to_xml()), DeleteType='HardDelete', SendMeetingCancellations=send_notifications_string, Affected... | Encapsulates a request to delete an existing calendar item. | DeleteCalendarItemRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteCalendarItemRequest:
"""Encapsulates a request to delete an existing calendar item."""
def __init__(self, principal, item_id, send_notifications=True):
"""Initialize the request. :param principal: Principal email to impersonate :param item_id: Item ID object :type item_id: resp... | stack_v2_sparse_classes_36k_train_008443 | 8,656 | permissive | [
{
"docstring": "Initialize the request. :param principal: Principal email to impersonate :param item_id: Item ID object :type item_id: respa_exchange.objs.ItemID",
"name": "__init__",
"signature": "def __init__(self, principal, item_id, send_notifications=True)"
},
{
"docstring": "Send the delet... | 2 | stack_v2_sparse_classes_30k_train_013771 | Implement the Python class `DeleteCalendarItemRequest` described below.
Class description:
Encapsulates a request to delete an existing calendar item.
Method signatures and docstrings:
- def __init__(self, principal, item_id, send_notifications=True): Initialize the request. :param principal: Principal email to imper... | Implement the Python class `DeleteCalendarItemRequest` described below.
Class description:
Encapsulates a request to delete an existing calendar item.
Method signatures and docstrings:
- def __init__(self, principal, item_id, send_notifications=True): Initialize the request. :param principal: Principal email to imper... | e6ae93087dde0eb62f859da732ee19d0b6c5fccf | <|skeleton|>
class DeleteCalendarItemRequest:
"""Encapsulates a request to delete an existing calendar item."""
def __init__(self, principal, item_id, send_notifications=True):
"""Initialize the request. :param principal: Principal email to impersonate :param item_id: Item ID object :type item_id: resp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteCalendarItemRequest:
"""Encapsulates a request to delete an existing calendar item."""
def __init__(self, principal, item_id, send_notifications=True):
"""Initialize the request. :param principal: Principal email to impersonate :param item_id: Item ID object :type item_id: respa_exchange.ob... | the_stack_v2_python_sparse | respa_exchange/ews/calendar.py | City-of-Helsinki/respa | train | 69 |
9d234b5b7344118b6e7e0df451e54a327ccd50cf | [
"if not matrix:\n return []\nres = []\nSHIFT = ((0, 1), (1, 0), (0, -1), (-1, 0))\nm, n = (len(matrix), len(matrix[0]))\nx = y = direction = 0\nfor i in range(m * n):\n res.append(matrix[x][y])\n matrix[x][y] = 0\n next_x, next_y = (x + SHIFT[direction][0], y + SHIFT[direction][1])\n if not 0 <= next... | <|body_start_0|>
if not matrix:
return []
res = []
SHIFT = ((0, 1), (1, 0), (0, -1), (-1, 0))
m, n = (len(matrix), len(matrix[0]))
x = y = direction = 0
for i in range(m * n):
res.append(matrix[x][y])
matrix[x][y] = 0
next_x... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def spiralOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int] if mod ele is allowed"""
<|body_0|>
def spiralOrder2(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int] mod ele not allowed"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_008444 | 1,920 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: List[int] if mod ele is allowed",
"name": "spiralOrder",
"signature": "def spiralOrder(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: List[int] mod ele not allowed",
"name": "spiralOrder2",
"signature": "def s... | 2 | stack_v2_sparse_classes_30k_train_015816 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def spiralOrder(self, matrix): :type matrix: List[List[int]] :rtype: List[int] if mod ele is allowed
- def spiralOrder2(self, matrix): :type matrix: List[List[int]] :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def spiralOrder(self, matrix): :type matrix: List[List[int]] :rtype: List[int] if mod ele is allowed
- def spiralOrder2(self, matrix): :type matrix: List[List[int]] :rtype: List[... | 4d2b4e322f92de71c7d13c9a2289a422242da38f | <|skeleton|>
class Solution:
def spiralOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int] if mod ele is allowed"""
<|body_0|>
def spiralOrder2(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int] mod ele not allowed"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def spiralOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int] if mod ele is allowed"""
if not matrix:
return []
res = []
SHIFT = ((0, 1), (1, 0), (0, -1), (-1, 0))
m, n = (len(matrix), len(matrix[0]))
x = y = direction =... | the_stack_v2_python_sparse | leetcode/arrays/54_spiral_matrix.py | Lance117/Etudes | train | 0 | |
a7ab68e5629125ccc3c538ffffaf49176b5d4469 | [
"self._position_indices = position_indices\nself._max_distance = max_distance\nself._num_players = len(position_indices)\nsuper(ProductStateProximityCost, self).__init__(name)",
"total_cost = torch.zeros(1, 1, requires_grad=True).double()\nfor ii in range(self._num_players):\n xi_idx, yi_idx = self._position_i... | <|body_start_0|>
self._position_indices = position_indices
self._max_distance = max_distance
self._num_players = len(position_indices)
super(ProductStateProximityCost, self).__init__(name)
<|end_body_0|>
<|body_start_1|>
total_cost = torch.zeros(1, 1, requires_grad=True).double(... | ProductStateProximityCost | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductStateProximityCost:
def __init__(self, position_indices, max_distance, name=''):
"""Initialize with dimension to add cost to and threshold BELOW which to impose quadratic cost. :param position_indices: list of index tuples corresponding to (x, y) :type position_indices: [(uint, ui... | stack_v2_sparse_classes_36k_train_008445 | 3,730 | permissive | [
{
"docstring": "Initialize with dimension to add cost to and threshold BELOW which to impose quadratic cost. :param position_indices: list of index tuples corresponding to (x, y) :type position_indices: [(uint, uint)] :param max_distance: maximum value of distance to penalize :type max_distance: float",
"na... | 2 | stack_v2_sparse_classes_30k_train_015978 | Implement the Python class `ProductStateProximityCost` described below.
Class description:
Implement the ProductStateProximityCost class.
Method signatures and docstrings:
- def __init__(self, position_indices, max_distance, name=''): Initialize with dimension to add cost to and threshold BELOW which to impose quadra... | Implement the Python class `ProductStateProximityCost` described below.
Class description:
Implement the ProductStateProximityCost class.
Method signatures and docstrings:
- def __init__(self, position_indices, max_distance, name=''): Initialize with dimension to add cost to and threshold BELOW which to impose quadra... | fbe9501a51e33498e0b916e2a870dada7c61df57 | <|skeleton|>
class ProductStateProximityCost:
def __init__(self, position_indices, max_distance, name=''):
"""Initialize with dimension to add cost to and threshold BELOW which to impose quadratic cost. :param position_indices: list of index tuples corresponding to (x, y) :type position_indices: [(uint, ui... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductStateProximityCost:
def __init__(self, position_indices, max_distance, name=''):
"""Initialize with dimension to add cost to and threshold BELOW which to impose quadratic cost. :param position_indices: list of index tuples corresponding to (x, y) :type position_indices: [(uint, uint)] :param ma... | the_stack_v2_python_sparse | python/product_state_proximity_cost.py | HJReachability/ilqgames | train | 89 | |
a8513f183b32cbb6b7a70b33d8c7bb59c118c000 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | A set of methods for managing API Gateway WebSocket connections. | ConnectionServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectionServiceServicer:
"""A set of methods for managing API Gateway WebSocket connections."""
def Get(self, request, context):
"""Returns the specified connection info."""
<|body_0|>
def Send(self, request, context):
"""Sends data to the specified connection.... | stack_v2_sparse_classes_36k_train_008446 | 7,571 | permissive | [
{
"docstring": "Returns the specified connection info.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Sends data to the specified connection.",
"name": "Send",
"signature": "def Send(self, request, context)"
},
{
"docstring": "Disconnects the s... | 3 | null | Implement the Python class `ConnectionServiceServicer` described below.
Class description:
A set of methods for managing API Gateway WebSocket connections.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified connection info.
- def Send(self, request, context): Sends data to the ... | Implement the Python class `ConnectionServiceServicer` described below.
Class description:
A set of methods for managing API Gateway WebSocket connections.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified connection info.
- def Send(self, request, context): Sends data to the ... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class ConnectionServiceServicer:
"""A set of methods for managing API Gateway WebSocket connections."""
def Get(self, request, context):
"""Returns the specified connection info."""
<|body_0|>
def Send(self, request, context):
"""Sends data to the specified connection.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConnectionServiceServicer:
"""A set of methods for managing API Gateway WebSocket connections."""
def Get(self, request, context):
"""Returns the specified connection info."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
ra... | the_stack_v2_python_sparse | yandex/cloud/serverless/apigateway/websocket/v1/connection_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
5289c1ebabb587d92dabaa3c9533809713c66c0f | [
"rights = gci_access.GCIChecker(params)\nrights['create'] = ['checkIsDeveloper']\nrights['edit'] = [('checkIsMyActiveRole', gci_mentor_logic.logic)]\nrights['delete'] = ['checkIsDeveloper']\nrights['invite'] = [('checkHasRoleForScope', gci_org_admin_logic.logic)]\nrights['accept_invite'] = [('checkIsMyRequestWithSt... | <|body_start_0|>
rights = gci_access.GCIChecker(params)
rights['create'] = ['checkIsDeveloper']
rights['edit'] = [('checkIsMyActiveRole', gci_mentor_logic.logic)]
rights['delete'] = ['checkIsDeveloper']
rights['invite'] = [('checkHasRoleForScope', gci_org_admin_logic.logic)]
... | View methods for the GCI Mentor model. | View | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
"""View methods for the GCI Mentor model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the mentor View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
<... | stack_v2_sparse_classes_36k_train_008447 | 7,352 | permissive | [
{
"docstring": "Defines the fields and methods required for the mentor View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View",
"name": "__init__",
"signature": "def __init__(self, params=None)"
},
{
"docstring": "Returns... | 3 | null | Implement the Python class `View` described below.
Class description:
View methods for the GCI Mentor model.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the mentor View class to provide the user with list, public, create, edit and delete views. Para... | Implement the Python class `View` described below.
Class description:
View methods for the GCI Mentor model.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the mentor View class to provide the user with list, public, create, edit and delete views. Para... | 9bd45c168f8ddb5c0e6c04eacdcaeafd61908be7 | <|skeleton|>
class View:
"""View methods for the GCI Mentor model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the mentor View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class View:
"""View methods for the GCI Mentor model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the mentor View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
rights = gci_a... | the_stack_v2_python_sparse | app/soc/modules/gci/views/models/mentor.py | pombredanne/Melange-1 | train | 0 |
03d8270ae92af661e0134810706b980e8746ba4b | [
"l = logging.getLogger(__name__)\nself.handler = QtHandler()\nself.handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))\nl.addHandler(self.handler)\nl.setLevel(logging.DEBUG)\nself.outHandlerGui = QTextBrowser()\nyield l",
"self.handler.messageWritten.connect(self.outHandlerGui.insertPlainText)\n... | <|body_start_0|>
l = logging.getLogger(__name__)
self.handler = QtHandler()
self.handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
l.addHandler(self.handler)
l.setLevel(logging.DEBUG)
self.outHandlerGui = QTextBrowser()
yield l
<|end_body_0|>
... | SasviewLoggerTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SasviewLoggerTest:
def logger(self, qapp):
"""Create/Destroy the logger"""
<|body_0|>
def testQtHandler(self, logger):
"""Test redirection of all levels of logging"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = logging.getLogger(__name__)
... | stack_v2_sparse_classes_36k_train_008448 | 1,285 | permissive | [
{
"docstring": "Create/Destroy the logger",
"name": "logger",
"signature": "def logger(self, qapp)"
},
{
"docstring": "Test redirection of all levels of logging",
"name": "testQtHandler",
"signature": "def testQtHandler(self, logger)"
}
] | 2 | null | Implement the Python class `SasviewLoggerTest` described below.
Class description:
Implement the SasviewLoggerTest class.
Method signatures and docstrings:
- def logger(self, qapp): Create/Destroy the logger
- def testQtHandler(self, logger): Test redirection of all levels of logging | Implement the Python class `SasviewLoggerTest` described below.
Class description:
Implement the SasviewLoggerTest class.
Method signatures and docstrings:
- def logger(self, qapp): Create/Destroy the logger
- def testQtHandler(self, logger): Test redirection of all levels of logging
<|skeleton|>
class SasviewLogger... | 55b1e9f6db58e33729f2a93b7dd1d8bf255b46f7 | <|skeleton|>
class SasviewLoggerTest:
def logger(self, qapp):
"""Create/Destroy the logger"""
<|body_0|>
def testQtHandler(self, logger):
"""Test redirection of all levels of logging"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SasviewLoggerTest:
def logger(self, qapp):
"""Create/Destroy the logger"""
l = logging.getLogger(__name__)
self.handler = QtHandler()
self.handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
l.addHandler(self.handler)
l.setLevel(logging.DEBUG)
... | the_stack_v2_python_sparse | src/sas/qtgui/Utilities/UnitTesting/SasviewLoggerTest.py | SasView/sasview | train | 48 | |
5da67df2885ce81c1d8ee28dc5d514490828e547 | [
"from apysc import EventType\nfrom apysc import MouseEvent\nfrom apysc.event.handler import append_handler_expression\nfrom apysc.event.handler import get_handler_name\nfrom apysc.type.variable_name_interface import VariableNameInterface\nself_instance: VariableNameInterface = self._validate_self_is_variable_name_i... | <|body_start_0|>
from apysc import EventType
from apysc import MouseEvent
from apysc.event.handler import append_handler_expression
from apysc.event.handler import get_handler_name
from apysc.type.variable_name_interface import VariableNameInterface
self_instance: Variabl... | ClickInterface | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClickInterface:
def click(self, handler: Handler, options: Optional[Dict[str, Any]]=None) -> str:
"""Add click event listener setting. Parameters ---------- handler : Handler Callable that called when this instance is clicked. options : dict or None, default None Optional arguments dicti... | stack_v2_sparse_classes_36k_train_008449 | 2,924 | permissive | [
{
"docstring": "Add click event listener setting. Parameters ---------- handler : Handler Callable that called when this instance is clicked. options : dict or None, default None Optional arguments dictionary to be passed to handler. Returns ------- name : str Handler's name.",
"name": "click",
"signatu... | 4 | null | Implement the Python class `ClickInterface` described below.
Class description:
Implement the ClickInterface class.
Method signatures and docstrings:
- def click(self, handler: Handler, options: Optional[Dict[str, Any]]=None) -> str: Add click event listener setting. Parameters ---------- handler : Handler Callable t... | Implement the Python class `ClickInterface` described below.
Class description:
Implement the ClickInterface class.
Method signatures and docstrings:
- def click(self, handler: Handler, options: Optional[Dict[str, Any]]=None) -> str: Add click event listener setting. Parameters ---------- handler : Handler Callable t... | 5c6a4674e2e9684cb2cb1325dc9b070879d4d355 | <|skeleton|>
class ClickInterface:
def click(self, handler: Handler, options: Optional[Dict[str, Any]]=None) -> str:
"""Add click event listener setting. Parameters ---------- handler : Handler Callable that called when this instance is clicked. options : dict or None, default None Optional arguments dicti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClickInterface:
def click(self, handler: Handler, options: Optional[Dict[str, Any]]=None) -> str:
"""Add click event listener setting. Parameters ---------- handler : Handler Callable that called when this instance is clicked. options : dict or None, default None Optional arguments dictionary to be pa... | the_stack_v2_python_sparse | apysc/event/click_interface.py | TrendingTechnology/apysc | train | 0 | |
ce49af528a5ce92e32f7814b34783ac3e845c0b0 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AudioRoutingGroup()",
"from .entity import Entity\nfrom .routing_mode import RoutingMode\nfrom .entity import Entity\nfrom .routing_mode import RoutingMode\nfields: Dict[str, Callable[[Any], None]] = {'receivers': lambda n: setattr(sel... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AudioRoutingGroup()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .routing_mode import RoutingMode
from .entity import Entity
from .routing_mode import ... | AudioRoutingGroup | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AudioRoutingGroup:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object... | stack_v2_sparse_classes_36k_train_008450 | 2,660 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: AudioRoutingGroup",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_v... | 3 | stack_v2_sparse_classes_30k_train_014665 | Implement the Python class `AudioRoutingGroup` described below.
Class description:
Implement the AudioRoutingGroup class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup: Creates a new instance of the appropriate class based on discrim... | Implement the Python class `AudioRoutingGroup` described below.
Class description:
Implement the AudioRoutingGroup class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup: Creates a new instance of the appropriate class based on discrim... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AudioRoutingGroup:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AudioRoutingGroup:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Audi... | the_stack_v2_python_sparse | msgraph/generated/models/audio_routing_group.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
24b1311596112a082624596d5ec6f9a3c5f8a5e0 | [
"super().__init__()\nraise Exception('The Affine spatial transformer is untested, and the code outdated')\nself.identity = Identity()\nself.grid_sampler = GridSampler(mode=mode)\nself.ndims = settings.get_ndims()",
"coordinates = self.identity(src)\ncoordinates = torch.cat((coordinates, torch.ones(coordinates.sha... | <|body_start_0|>
super().__init__()
raise Exception('The Affine spatial transformer is untested, and the code outdated')
self.identity = Identity()
self.grid_sampler = GridSampler(mode=mode)
self.ndims = settings.get_ndims()
<|end_body_0|>
<|body_start_1|>
coordinates = ... | N-D Spatial Transformer for affine input | AffineSpatialTransformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AffineSpatialTransformer:
"""N-D Spatial Transformer for affine input"""
def __init__(self, mode='bilinear'):
"""Instantiates the spatial transformer. A spatial transformer transforms a src image with a flow of displacement vectors. Parameters: mode: interpolation mode"""
<|b... | stack_v2_sparse_classes_36k_train_008451 | 8,565 | no_license | [
{
"docstring": "Instantiates the spatial transformer. A spatial transformer transforms a src image with a flow of displacement vectors. Parameters: mode: interpolation mode",
"name": "__init__",
"signature": "def __init__(self, mode='bilinear')"
},
{
"docstring": "Transforms the src with the flo... | 2 | null | Implement the Python class `AffineSpatialTransformer` described below.
Class description:
N-D Spatial Transformer for affine input
Method signatures and docstrings:
- def __init__(self, mode='bilinear'): Instantiates the spatial transformer. A spatial transformer transforms a src image with a flow of displacement vec... | Implement the Python class `AffineSpatialTransformer` described below.
Class description:
N-D Spatial Transformer for affine input
Method signatures and docstrings:
- def __init__(self, mode='bilinear'): Instantiates the spatial transformer. A spatial transformer transforms a src image with a flow of displacement vec... | c295ab990c8394a4da8fedee01d1e5a3f63d8f04 | <|skeleton|>
class AffineSpatialTransformer:
"""N-D Spatial Transformer for affine input"""
def __init__(self, mode='bilinear'):
"""Instantiates the spatial transformer. A spatial transformer transforms a src image with a flow of displacement vectors. Parameters: mode: interpolation mode"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AffineSpatialTransformer:
"""N-D Spatial Transformer for affine input"""
def __init__(self, mode='bilinear'):
"""Instantiates the spatial transformer. A spatial transformer transforms a src image with a flow of displacement vectors. Parameters: mode: interpolation mode"""
super().__init__... | the_stack_v2_python_sparse | torchreg/nn/layers.py | SteffenCzolbe/TopologicalChangeDetection | train | 3 |
8a6e20db19a023b4c3e5697f6d101fafbecd1373 | [
"instance_id = self.get_current_instance_id()\nvm = self.get_current_machine()\nfor lb in self.lbs:\n match = self.match_load_balancer_and_vm(lb, vm)\n if not match:\n self.record(lb.name, instance_id, RegistrationAction.REGISTER, [RegistrationActionReason.NOT_YET_REGISTERED])\n if not self.add_... | <|body_start_0|>
instance_id = self.get_current_instance_id()
vm = self.get_current_machine()
for lb in self.lbs:
match = self.match_load_balancer_and_vm(lb, vm)
if not match:
self.record(lb.name, instance_id, RegistrationAction.REGISTER, [RegistrationActi... | Registerer that adds and removes current machine from configured ELBs. | AzureLbSelfRegisterer | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AzureLbSelfRegisterer:
"""Registerer that adds and removes current machine from configured ELBs."""
def add(self):
"""Add the current instance to all configured LBs. Assumes that this code is running on an Azure instance."""
<|body_0|>
def remove(self):
"""Remove... | stack_v2_sparse_classes_36k_train_008452 | 16,722 | permissive | [
{
"docstring": "Add the current instance to all configured LBs. Assumes that this code is running on an Azure instance.",
"name": "add",
"signature": "def add(self)"
},
{
"docstring": "Remove the current instance from all configured LBs. Assumes that this code is running on an Azure instance.",
... | 2 | stack_v2_sparse_classes_30k_train_005992 | Implement the Python class `AzureLbSelfRegisterer` described below.
Class description:
Registerer that adds and removes current machine from configured ELBs.
Method signatures and docstrings:
- def add(self): Add the current instance to all configured LBs. Assumes that this code is running on an Azure instance.
- def... | Implement the Python class `AzureLbSelfRegisterer` described below.
Class description:
Registerer that adds and removes current machine from configured ELBs.
Method signatures and docstrings:
- def add(self): Add the current instance to all configured LBs. Assumes that this code is running on an Azure instance.
- def... | 73a1e7086cc4dd171456f50724246a9261febaf8 | <|skeleton|>
class AzureLbSelfRegisterer:
"""Registerer that adds and removes current machine from configured ELBs."""
def add(self):
"""Add the current instance to all configured LBs. Assumes that this code is running on an Azure instance."""
<|body_0|>
def remove(self):
"""Remove... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AzureLbSelfRegisterer:
"""Registerer that adds and removes current machine from configured ELBs."""
def add(self):
"""Add the current instance to all configured LBs. Assumes that this code is running on an Azure instance."""
instance_id = self.get_current_instance_id()
vm = self.g... | the_stack_v2_python_sparse | tellapart/aurproxy/register/azurelb.py | aurora-scheduler/aurproxy | train | 1 |
1a60f9b0a2e952e1e1d45df6f2b80025d74a534b | [
"if 'style' in kwargs:\n style = kwargs['style']\nelse:\n style = wx.FRAME_TOOL_WINDOW | wx.FRAME_FLOAT_ON_PARENT | wx.FRAME_NO_TASKBAR | wx.CLIP_CHILDREN\nif fwidgets.inSSHSession():\n style &= ~wx.FRAME_TOOL_WINDOW\nkwargs['style'] = style\nsuper().__init__(*args, **kwargs)",
"super().SetPaneWindow(pan... | <|body_start_0|>
if 'style' in kwargs:
style = kwargs['style']
else:
style = wx.FRAME_TOOL_WINDOW | wx.FRAME_FLOAT_ON_PARENT | wx.FRAME_NO_TASKBAR | wx.CLIP_CHILDREN
if fwidgets.inSSHSession():
style &= ~wx.FRAME_TOOL_WINDOW
kwargs['style'] = style
... | Here I am monkey patching the ``wx.agw.aui.framemanager.AuiFloatingFrame.__init__`` method. I am doing this because I have observed some strange behaviour when running a remote instance of this application over an SSH/X11 session, with the X11 server (i.e. the local machine) running in OS X. When a combobox is embedded... | MyAuiFloatingFrame | [
"Apache-2.0",
"CC-BY-3.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyAuiFloatingFrame:
"""Here I am monkey patching the ``wx.agw.aui.framemanager.AuiFloatingFrame.__init__`` method. I am doing this because I have observed some strange behaviour when running a remote instance of this application over an SSH/X11 session, with the X11 server (i.e. the local machine... | stack_v2_sparse_classes_36k_train_008453 | 3,585 | permissive | [
{
"docstring": "My new constructor, which makes sure that the ``FRAME_TOOL_WINDOW`` style is not passed through to the ``AuiFloatingFrame`` constructor",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Make sure that floated toolbars are sized correctly.... | 2 | stack_v2_sparse_classes_30k_train_006429 | Implement the Python class `MyAuiFloatingFrame` described below.
Class description:
Here I am monkey patching the ``wx.agw.aui.framemanager.AuiFloatingFrame.__init__`` method. I am doing this because I have observed some strange behaviour when running a remote instance of this application over an SSH/X11 session, with... | Implement the Python class `MyAuiFloatingFrame` described below.
Class description:
Here I am monkey patching the ``wx.agw.aui.framemanager.AuiFloatingFrame.__init__`` method. I am doing this because I have observed some strange behaviour when running a remote instance of this application over an SSH/X11 session, with... | 37b45d034d60660b6de3e4bdf5dd6349ed6d853b | <|skeleton|>
class MyAuiFloatingFrame:
"""Here I am monkey patching the ``wx.agw.aui.framemanager.AuiFloatingFrame.__init__`` method. I am doing this because I have observed some strange behaviour when running a remote instance of this application over an SSH/X11 session, with the X11 server (i.e. the local machine... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyAuiFloatingFrame:
"""Here I am monkey patching the ``wx.agw.aui.framemanager.AuiFloatingFrame.__init__`` method. I am doing this because I have observed some strange behaviour when running a remote instance of this application over an SSH/X11 session, with the X11 server (i.e. the local machine) running in ... | the_stack_v2_python_sparse | fsleyes/patches/wx_lib_agw_aui_framemanager.py | CGSchwarzMayo/fsleyes | train | 0 |
4effbd606ee086e0ee261c3a35aa4bc649e42e0b | [
"assert embedding_type in ['skipgram', 'cbow']\nself.embedding_type = embedding_type\nself.model_name = model_name\nself.model_path = os.path.join(MODELS_DIR, '{}_{}'.format(self.embedding_type, model_name))\nself.model = None",
"input_path = os.path.join(DATA_DIR, file_input)\nif self.embedding_type == 'skipgram... | <|body_start_0|>
assert embedding_type in ['skipgram', 'cbow']
self.embedding_type = embedding_type
self.model_name = model_name
self.model_path = os.path.join(MODELS_DIR, '{}_{}'.format(self.embedding_type, model_name))
self.model = None
<|end_body_0|>
<|body_start_1|>
... | FastTextEmbedding | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastTextEmbedding:
def __init__(self, embedding_type='skipgram', model_name='model'):
""":param embedding_type: :param model_name:"""
<|body_0|>
def train_model(self, file_input='train_text.txt'):
""":param file_input: :return:"""
<|body_1|>
def load_mod... | stack_v2_sparse_classes_36k_train_008454 | 4,860 | permissive | [
{
"docstring": ":param embedding_type: :param model_name:",
"name": "__init__",
"signature": "def __init__(self, embedding_type='skipgram', model_name='model')"
},
{
"docstring": ":param file_input: :return:",
"name": "train_model",
"signature": "def train_model(self, file_input='train_t... | 4 | stack_v2_sparse_classes_30k_train_004444 | Implement the Python class `FastTextEmbedding` described below.
Class description:
Implement the FastTextEmbedding class.
Method signatures and docstrings:
- def __init__(self, embedding_type='skipgram', model_name='model'): :param embedding_type: :param model_name:
- def train_model(self, file_input='train_text.txt'... | Implement the Python class `FastTextEmbedding` described below.
Class description:
Implement the FastTextEmbedding class.
Method signatures and docstrings:
- def __init__(self, embedding_type='skipgram', model_name='model'): :param embedding_type: :param model_name:
- def train_model(self, file_input='train_text.txt'... | 281a63732a0994f986529580716f25e4ab67ad20 | <|skeleton|>
class FastTextEmbedding:
def __init__(self, embedding_type='skipgram', model_name='model'):
""":param embedding_type: :param model_name:"""
<|body_0|>
def train_model(self, file_input='train_text.txt'):
""":param file_input: :return:"""
<|body_1|>
def load_mod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FastTextEmbedding:
def __init__(self, embedding_type='skipgram', model_name='model'):
""":param embedding_type: :param model_name:"""
assert embedding_type in ['skipgram', 'cbow']
self.embedding_type = embedding_type
self.model_name = model_name
self.model_path = os.pat... | the_stack_v2_python_sparse | rpcc/word_embedding.py | gperakis/research-paper-category-classifier | train | 1 | |
8eabd4e708ce7cbd5f206d1e084283d4ee98c391 | [
"self.node_1 = BinaryTree(1)\nself.node_2 = BinaryTree(2)\nself.node_3 = BinaryTree(3)\nself.node_4 = BinaryTree(4)\nself.node_5 = BinaryTree(5)\nself.node_6 = BinaryTree(6)\nself.node_7 = BinaryTree(7)\nself.node_8 = BinaryTree(8)\nself.node_1.left = self.node_2\nself.node_1.right = self.node_3\nself.node_2.left =... | <|body_start_0|>
self.node_1 = BinaryTree(1)
self.node_2 = BinaryTree(2)
self.node_3 = BinaryTree(3)
self.node_4 = BinaryTree(4)
self.node_5 = BinaryTree(5)
self.node_6 = BinaryTree(6)
self.node_7 = BinaryTree(7)
self.node_8 = BinaryTree(8)
self.no... | Class with unittests for FindNodesDistanceK.py | test_FindNodesDistanceK | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_FindNodesDistanceK:
"""Class with unittests for FindNodesDistanceK.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_user_input(self):
"""Checks if method works properly."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.no... | stack_v2_sparse_classes_36k_train_008455 | 1,497 | no_license | [
{
"docstring": "Sets up input.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if method works properly.",
"name": "test_user_input",
"signature": "def test_user_input(self)"
}
] | 2 | null | Implement the Python class `test_FindNodesDistanceK` described below.
Class description:
Class with unittests for FindNodesDistanceK.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_user_input(self): Checks if method works properly. | Implement the Python class `test_FindNodesDistanceK` described below.
Class description:
Class with unittests for FindNodesDistanceK.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_user_input(self): Checks if method works properly.
<|skeleton|>
class test_FindNodesDistanceK:
"""... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_FindNodesDistanceK:
"""Class with unittests for FindNodesDistanceK.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_user_input(self):
"""Checks if method works properly."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_FindNodesDistanceK:
"""Class with unittests for FindNodesDistanceK.py"""
def setUp(self):
"""Sets up input."""
self.node_1 = BinaryTree(1)
self.node_2 = BinaryTree(2)
self.node_3 = BinaryTree(3)
self.node_4 = BinaryTree(4)
self.node_5 = BinaryTree(5)
... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Hard/FindNodesDistanceK/test_FindNodesDIstanceK.py | JakubKazimierski/PythonPortfolio | train | 9 |
727b2ceaed4d461d6f589bf46d782654d59fa9d4 | [
"try:\n import IPython\nexcept ImportError:\n if willful:\n req_missing(['IPython'], 'use the IPython console')\n raise\nelse:\n site = self.context['site']\n nikola_site = self.context['nikola_site']\n conf = self.context['conf']\n commands = self.context['commands']\n IPython.embed(... | <|body_start_0|>
try:
import IPython
except ImportError:
if willful:
req_missing(['IPython'], 'use the IPython console')
raise
else:
site = self.context['site']
nikola_site = self.context['nikola_site']
conf ... | Start debugging console. | CommandConsole | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandConsole:
"""Start debugging console."""
def ipython(self, willful=True):
"""Run an IPython shell."""
<|body_0|>
def bpython(self, willful=True):
"""Run a bpython shell."""
<|body_1|>
def plain(self, willful=True):
"""Run a plain Python... | stack_v2_sparse_classes_36k_train_008456 | 5,906 | permissive | [
{
"docstring": "Run an IPython shell.",
"name": "ipython",
"signature": "def ipython(self, willful=True)"
},
{
"docstring": "Run a bpython shell.",
"name": "bpython",
"signature": "def bpython(self, willful=True)"
},
{
"docstring": "Run a plain Python shell.",
"name": "plain"... | 4 | null | Implement the Python class `CommandConsole` described below.
Class description:
Start debugging console.
Method signatures and docstrings:
- def ipython(self, willful=True): Run an IPython shell.
- def bpython(self, willful=True): Run a bpython shell.
- def plain(self, willful=True): Run a plain Python shell.
- def _... | Implement the Python class `CommandConsole` described below.
Class description:
Start debugging console.
Method signatures and docstrings:
- def ipython(self, willful=True): Run an IPython shell.
- def bpython(self, willful=True): Run a bpython shell.
- def plain(self, willful=True): Run a plain Python shell.
- def _... | 2b10e9952bac5a1119e6845c7a2c28273aca9775 | <|skeleton|>
class CommandConsole:
"""Start debugging console."""
def ipython(self, willful=True):
"""Run an IPython shell."""
<|body_0|>
def bpython(self, willful=True):
"""Run a bpython shell."""
<|body_1|>
def plain(self, willful=True):
"""Run a plain Python... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommandConsole:
"""Start debugging console."""
def ipython(self, willful=True):
"""Run an IPython shell."""
try:
import IPython
except ImportError:
if willful:
req_missing(['IPython'], 'use the IPython console')
raise
els... | the_stack_v2_python_sparse | nikola/plugins/command/console.py | getnikola/nikola | train | 2,142 |
8bc48e38b4d6a2bed4730d64e8552f6a8041451c | [
"self.output_raw = output_raw\nif isinstance(filter_spec, dict):\n self.output_raw = filter_spec.get('output-raw', output_raw)\n filter_spec = filter_spec.get('script', '.')\nif isinstance(filter_spec, list):\n filter_spec = '\\n'.join([str(line) for line in filter_spec])\nif not isinstance(filter_spec, st... | <|body_start_0|>
self.output_raw = output_raw
if isinstance(filter_spec, dict):
self.output_raw = filter_spec.get('output-raw', output_raw)
filter_spec = filter_spec.get('script', '.')
if isinstance(filter_spec, list):
filter_spec = '\n'.join([str(line) for li... | JQ JSON filter | JQFilter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JQFilter:
"""JQ JSON filter"""
def __init__(self, filter_spec='.', args={}, output_raw=False, groom=False):
"""Construct a filter. Arguments: filter_spec - The JQ script to be used for this filter. This may be any subclass of basestring, a list or a dict. Strings are interpreted dire... | stack_v2_sparse_classes_36k_train_008457 | 4,966 | permissive | [
{
"docstring": "Construct a filter. Arguments: filter_spec - The JQ script to be used for this filter. This may be any subclass of basestring, a list or a dict. Strings are interpreted directly, lists are stringified and joined with newlines (to make multi-line scripts readable in JSON) and dicts give their \"s... | 2 | stack_v2_sparse_classes_30k_train_011418 | Implement the Python class `JQFilter` described below.
Class description:
JQ JSON filter
Method signatures and docstrings:
- def __init__(self, filter_spec='.', args={}, output_raw=False, groom=False): Construct a filter. Arguments: filter_spec - The JQ script to be used for this filter. This may be any subclass of b... | Implement the Python class `JQFilter` described below.
Class description:
JQ JSON filter
Method signatures and docstrings:
- def __init__(self, filter_spec='.', args={}, output_raw=False, groom=False): Construct a filter. Arguments: filter_spec - The JQ script to be used for this filter. This may be any subclass of b... | f6d04c0455e5be4d490df16ec1acb377f9025d9f | <|skeleton|>
class JQFilter:
"""JQ JSON filter"""
def __init__(self, filter_spec='.', args={}, output_raw=False, groom=False):
"""Construct a filter. Arguments: filter_spec - The JQ script to be used for this filter. This may be any subclass of basestring, a list or a dict. Strings are interpreted dire... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JQFilter:
"""JQ JSON filter"""
def __init__(self, filter_spec='.', args={}, output_raw=False, groom=False):
"""Construct a filter. Arguments: filter_spec - The JQ script to be used for this filter. This may be any subclass of basestring, a list or a dict. Strings are interpreted directly, lists a... | the_stack_v2_python_sparse | python-pscheduler/pscheduler/pscheduler/jqfilter.py | perfsonar/pscheduler | train | 53 |
dbb03e317204bceffa8a455524e54557644695e4 | [
"super(CurrentResourceValue, self).__init__()\nself.device_id = device_id\nself.resource_path = resource_path\nself.async_id = utils.new_async_id()\nLOG.debug('new async id: %s', self.async_id)\nself._route_keys = expand_dict_as_keys(dict(id=self.async_id, channel=ChannelIdentifiers.async_responses))\nself._optiona... | <|body_start_0|>
super(CurrentResourceValue, self).__init__()
self.device_id = device_id
self.resource_path = resource_path
self.async_id = utils.new_async_id()
LOG.debug('new async id: %s', self.async_id)
self._route_keys = expand_dict_as_keys(dict(id=self.async_id, chan... | Triggers on response to a request for a current resource value | CurrentResourceValue | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurrentResourceValue:
"""Triggers on response to a request for a current resource value"""
def __init__(self, device_id, resource_path, **extra_filters):
"""Triggers on response to a request for a current resource value .. warning:: This functionality is considered experimental; the ... | stack_v2_sparse_classes_36k_train_008458 | 3,067 | permissive | [
{
"docstring": "Triggers on response to a request for a current resource value .. warning:: This functionality is considered experimental; the interface may change in future releases :param device_id: a device identifier :param resource_path: a resource path :param extra_filters:",
"name": "__init__",
"... | 3 | null | Implement the Python class `CurrentResourceValue` described below.
Class description:
Triggers on response to a request for a current resource value
Method signatures and docstrings:
- def __init__(self, device_id, resource_path, **extra_filters): Triggers on response to a request for a current resource value .. warn... | Implement the Python class `CurrentResourceValue` described below.
Class description:
Triggers on response to a request for a current resource value
Method signatures and docstrings:
- def __init__(self, device_id, resource_path, **extra_filters): Triggers on response to a request for a current resource value .. warn... | 76ef009903415f37f69dcc5778be8f5fb14c08fe | <|skeleton|>
class CurrentResourceValue:
"""Triggers on response to a request for a current resource value"""
def __init__(self, device_id, resource_path, **extra_filters):
"""Triggers on response to a request for a current resource value .. warning:: This functionality is considered experimental; the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CurrentResourceValue:
"""Triggers on response to a request for a current resource value"""
def __init__(self, device_id, resource_path, **extra_filters):
"""Triggers on response to a request for a current resource value .. warning:: This functionality is considered experimental; the interface may... | the_stack_v2_python_sparse | src/mbed_cloud/subscribe/channels/current_resource_value.py | GQMai/mbed-cloud-sdk-python | train | 0 |
65bca06eda577b457a460d13822a338ab6cbfb62 | [
"QProgressBar.__init__(self)\nself.setMinimum(0)\nself.parent = parent\nself.remaining_time_label = remaining_time_label",
"self.current_thread = QThread.currentThread()\nself.setEnabled(True)\nif new_set_value != 0:\n self.setValue(new_set_value)\nif increment_value != 0:\n self.setValue(self.value() + inc... | <|body_start_0|>
QProgressBar.__init__(self)
self.setMinimum(0)
self.parent = parent
self.remaining_time_label = remaining_time_label
<|end_body_0|>
<|body_start_1|>
self.current_thread = QThread.currentThread()
self.setEnabled(True)
if new_set_value != 0:
... | Class containing the progress bar of the current analysis | ProgressBar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgressBar:
"""Class containing the progress bar of the current analysis"""
def __init__(self, remaining_time_label, parent=None):
"""Args: remaining_time_label: Associated analysis remaining time"""
<|body_0|>
def update_progress_bar(self, time_started, increment_value... | stack_v2_sparse_classes_36k_train_008459 | 49,308 | no_license | [
{
"docstring": "Args: remaining_time_label: Associated analysis remaining time",
"name": "__init__",
"signature": "def __init__(self, remaining_time_label, parent=None)"
},
{
"docstring": "Update the progress bar in the analysis widget and the corresponding remaining time Args: time_started (flo... | 3 | stack_v2_sparse_classes_30k_train_019910 | Implement the Python class `ProgressBar` described below.
Class description:
Class containing the progress bar of the current analysis
Method signatures and docstrings:
- def __init__(self, remaining_time_label, parent=None): Args: remaining_time_label: Associated analysis remaining time
- def update_progress_bar(sel... | Implement the Python class `ProgressBar` described below.
Class description:
Class containing the progress bar of the current analysis
Method signatures and docstrings:
- def __init__(self, remaining_time_label, parent=None): Args: remaining_time_label: Associated analysis remaining time
- def update_progress_bar(sel... | 75449d4f0f7ea92e4daf329b5d40820832b62de2 | <|skeleton|>
class ProgressBar:
"""Class containing the progress bar of the current analysis"""
def __init__(self, remaining_time_label, parent=None):
"""Args: remaining_time_label: Associated analysis remaining time"""
<|body_0|>
def update_progress_bar(self, time_started, increment_value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProgressBar:
"""Class containing the progress bar of the current analysis"""
def __init__(self, remaining_time_label, parent=None):
"""Args: remaining_time_label: Associated analysis remaining time"""
QProgressBar.__init__(self)
self.setMinimum(0)
self.parent = parent
... | the_stack_v2_python_sparse | src/cicada/gui/cicada_analysis_parameters_gui.py | PaulUteza/cicada | train | 0 |
8e6b72fe29c60fcdfeda10afef90ae65f44c170d | [
"if num_splits is None:\n num_splits = len(self.list_of_blocks)\nif other_axis_partition is not None:\n if not isinstance(other_axis_partition, list):\n other_axis_partition = [other_axis_partition]\n other_shape = np.cumsum([0] + [len(o.list_of_blocks) for o in other_axis_partition])\n return se... | <|body_start_0|>
if num_splits is None:
num_splits = len(self.list_of_blocks)
if other_axis_partition is not None:
if not isinstance(other_axis_partition, list):
other_axis_partition = [other_axis_partition]
other_shape = np.cumsum([0] + [len(o.list_of... | An abstract class is created to simplify and consolidate the code for axis partition that run pandas. Because much of the code is similar, this allows us to reuse this code. | PandasFrameAxisPartition | [
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PandasFrameAxisPartition:
"""An abstract class is created to simplify and consolidate the code for axis partition that run pandas. Because much of the code is similar, this allows us to reuse this code."""
def apply(self, func, num_splits=None, other_axis_partition=None, maintain_partitionin... | stack_v2_sparse_classes_36k_train_008460 | 13,560 | permissive | [
{
"docstring": "Apply a function to this axis partition along full axis. Parameters ---------- func : callable The function to apply. num_splits : int, default: None The number of times to split the result object. other_axis_partition : PandasFrameAxisPartition, default: None Another `PandasFrameAxisPartition` ... | 4 | stack_v2_sparse_classes_30k_train_005674 | Implement the Python class `PandasFrameAxisPartition` described below.
Class description:
An abstract class is created to simplify and consolidate the code for axis partition that run pandas. Because much of the code is similar, this allows us to reuse this code.
Method signatures and docstrings:
- def apply(self, fu... | Implement the Python class `PandasFrameAxisPartition` described below.
Class description:
An abstract class is created to simplify and consolidate the code for axis partition that run pandas. Because much of the code is similar, this allows us to reuse this code.
Method signatures and docstrings:
- def apply(self, fu... | b58663bd8f2c8802bb45d7bafa2cc65ae988f959 | <|skeleton|>
class PandasFrameAxisPartition:
"""An abstract class is created to simplify and consolidate the code for axis partition that run pandas. Because much of the code is similar, this allows us to reuse this code."""
def apply(self, func, num_splits=None, other_axis_partition=None, maintain_partitionin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PandasFrameAxisPartition:
"""An abstract class is created to simplify and consolidate the code for axis partition that run pandas. Because much of the code is similar, this allows us to reuse this code."""
def apply(self, func, num_splits=None, other_axis_partition=None, maintain_partitioning=True, **kwa... | the_stack_v2_python_sparse | modin/engines/base/frame/axis_partition.py | wroldwiedbwe/modin | train | 0 |
c9dcffee548828ecef986e3c103f22c10e3288e3 | [
"try:\n profile = Profile.objects.get(user=request.user)\nexcept Profile.DoesNotExist:\n if request.user.is_superuser:\n return Files.objects.all()\nif profile.access == 'teacher':\n return Files.objects.filter(subject__teacher__profile__user=request.user)",
"if db_field.name == 'subject' and requ... | <|body_start_0|>
try:
profile = Profile.objects.get(user=request.user)
except Profile.DoesNotExist:
if request.user.is_superuser:
return Files.objects.all()
if profile.access == 'teacher':
return Files.objects.filter(subject__teacher__profile__... | FilesAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilesAdmin:
def get_queryset(self, request):
"""Get all marks for current profile"""
<|body_0|>
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""Set default teacher"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_36k_train_008461 | 2,518 | no_license | [
{
"docstring": "Get all marks for current profile",
"name": "get_queryset",
"signature": "def get_queryset(self, request)"
},
{
"docstring": "Set default teacher",
"name": "formfield_for_foreignkey",
"signature": "def formfield_for_foreignkey(self, db_field, request, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005641 | Implement the Python class `FilesAdmin` described below.
Class description:
Implement the FilesAdmin class.
Method signatures and docstrings:
- def get_queryset(self, request): Get all marks for current profile
- def formfield_for_foreignkey(self, db_field, request, **kwargs): Set default teacher | Implement the Python class `FilesAdmin` described below.
Class description:
Implement the FilesAdmin class.
Method signatures and docstrings:
- def get_queryset(self, request): Get all marks for current profile
- def formfield_for_foreignkey(self, db_field, request, **kwargs): Set default teacher
<|skeleton|>
class ... | 76c0df6f07f41f4baf7346acdbbf316b4dd13ee5 | <|skeleton|>
class FilesAdmin:
def get_queryset(self, request):
"""Get all marks for current profile"""
<|body_0|>
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""Set default teacher"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilesAdmin:
def get_queryset(self, request):
"""Get all marks for current profile"""
try:
profile = Profile.objects.get(user=request.user)
except Profile.DoesNotExist:
if request.user.is_superuser:
return Files.objects.all()
if profile.ac... | the_stack_v2_python_sparse | office/admin.py | HallrizonX/api_chpk | train | 3 | |
6117b6be55b0572460a81b2633823993623b1741 | [
"super(LevelThree, self).__init__(screen)\nself.villain_one = None\nself.villain_two = None\nself.villain_three = None\nself._set_villain()",
"self.villain_one = donkey.Donkey(100, constants.THREE_Y, 0, 500)\nself.active_sprite_list.add(self.villain_one)\nself.villain_two = donkey.Donkey(900, constants.TWO_Y, 700... | <|body_start_0|>
super(LevelThree, self).__init__(screen)
self.villain_one = None
self.villain_two = None
self.villain_three = None
self._set_villain()
<|end_body_0|>
<|body_start_1|>
self.villain_one = donkey.Donkey(100, constants.THREE_Y, 0, 500)
self.active_sp... | Class which defines the third level of the game | LevelThree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LevelThree:
"""Class which defines the third level of the game"""
def __init__(self, screen):
"""Constructor for the third level of the game"""
<|body_0|>
def _set_villain(self):
"""Sets the number of donkeys and their positions for the third level of the game"""... | stack_v2_sparse_classes_36k_train_008462 | 1,964 | no_license | [
{
"docstring": "Constructor for the third level of the game",
"name": "__init__",
"signature": "def __init__(self, screen)"
},
{
"docstring": "Sets the number of donkeys and their positions for the third level of the game",
"name": "_set_villain",
"signature": "def _set_villain(self)"
... | 2 | stack_v2_sparse_classes_30k_train_013037 | Implement the Python class `LevelThree` described below.
Class description:
Class which defines the third level of the game
Method signatures and docstrings:
- def __init__(self, screen): Constructor for the third level of the game
- def _set_villain(self): Sets the number of donkeys and their positions for the third... | Implement the Python class `LevelThree` described below.
Class description:
Class which defines the third level of the game
Method signatures and docstrings:
- def __init__(self, screen): Constructor for the third level of the game
- def _set_villain(self): Sets the number of donkeys and their positions for the third... | 26d629f8348f0110fa84b02009e787a238aff441 | <|skeleton|>
class LevelThree:
"""Class which defines the third level of the game"""
def __init__(self, screen):
"""Constructor for the third level of the game"""
<|body_0|>
def _set_villain(self):
"""Sets the number of donkeys and their positions for the third level of the game"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LevelThree:
"""Class which defines the third level of the game"""
def __init__(self, screen):
"""Constructor for the third level of the game"""
super(LevelThree, self).__init__(screen)
self.villain_one = None
self.villain_two = None
self.villain_three = None
... | the_stack_v2_python_sparse | IIITSERC-ssad_2015_a3_group1-88a823ccd2d0/Akshat Tandon/201503001/levels.py | anirudhdahiya9/Open-data-projecy | train | 1 |
8df120006538e72e8e7e248f5befec826cb4d276 | [
"self.application_parameters = application_parameters\nself.excluded_disks = excluded_disks\nself.vm_credentials = vm_credentials",
"if dictionary is None:\n return None\napplication_parameters = cohesity_management_sdk.models.application_parameters.ApplicationParameters.from_dictionary(dictionary.get('applica... | <|body_start_0|>
self.application_parameters = application_parameters
self.excluded_disks = excluded_disks
self.vm_credentials = vm_credentials
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
application_parameters = cohesity_management_sdk.models.... | Implementation of the 'VmwareSpecialParameters' model. Specifies additional special settings applicable for a Protection Source of 'kVMware' type in a Protection Job. Attributes: application_parameters (ApplicationParameters): Specifies parameters that are related to applications running on the Protection Source. exclu... | VmwareSpecialParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VmwareSpecialParameters:
"""Implementation of the 'VmwareSpecialParameters' model. Specifies additional special settings applicable for a Protection Source of 'kVMware' type in a Protection Job. Attributes: application_parameters (ApplicationParameters): Specifies parameters that are related to a... | stack_v2_sparse_classes_36k_train_008463 | 3,395 | permissive | [
{
"docstring": "Constructor for the VmwareSpecialParameters class",
"name": "__init__",
"signature": "def __init__(self, application_parameters=None, excluded_disks=None, vm_credentials=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A... | 2 | stack_v2_sparse_classes_30k_train_008337 | Implement the Python class `VmwareSpecialParameters` described below.
Class description:
Implementation of the 'VmwareSpecialParameters' model. Specifies additional special settings applicable for a Protection Source of 'kVMware' type in a Protection Job. Attributes: application_parameters (ApplicationParameters): Spe... | Implement the Python class `VmwareSpecialParameters` described below.
Class description:
Implementation of the 'VmwareSpecialParameters' model. Specifies additional special settings applicable for a Protection Source of 'kVMware' type in a Protection Job. Attributes: application_parameters (ApplicationParameters): Spe... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VmwareSpecialParameters:
"""Implementation of the 'VmwareSpecialParameters' model. Specifies additional special settings applicable for a Protection Source of 'kVMware' type in a Protection Job. Attributes: application_parameters (ApplicationParameters): Specifies parameters that are related to a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VmwareSpecialParameters:
"""Implementation of the 'VmwareSpecialParameters' model. Specifies additional special settings applicable for a Protection Source of 'kVMware' type in a Protection Job. Attributes: application_parameters (ApplicationParameters): Specifies parameters that are related to applications r... | the_stack_v2_python_sparse | cohesity_management_sdk/models/vmware_special_parameters.py | cohesity/management-sdk-python | train | 24 |
09044019ba370ade295f50c0ae833a08be63a174 | [
"self.queue_url = queue_url\nself.profile_name = profile_name\nself.region_name = region_name\nself.filters = list(filters) if filters else []\nself.session = None\nself.client = None\nif connect:\n self.connect()",
"pname = self.profile_name if profile_name is None else profile_name\nrname = self.region_name ... | <|body_start_0|>
self.queue_url = queue_url
self.profile_name = profile_name
self.region_name = region_name
self.filters = list(filters) if filters else []
self.session = None
self.client = None
if connect:
self.connect()
<|end_body_0|>
<|body_start_1... | AWS SQS queue message receiver and handler selector. | SQSSifter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQSSifter:
"""AWS SQS queue message receiver and handler selector."""
def __init__(self, queue_url, profile_name=None, region_name='us-east-1', connect=True, filters=None):
"""Initialize an SQS Sifter instance. Arguments: queue_url (str) The URL of the AWS Queue to sift. profile_name... | stack_v2_sparse_classes_36k_train_008464 | 8,134 | permissive | [
{
"docstring": "Initialize an SQS Sifter instance. Arguments: queue_url (str) The URL of the AWS Queue to sift. profile_name (str) Session parameter for the AWS connection. region_name (str, default='us-east-1') Session parameter for the AWS connection. connect (bool, default=True) If ``True``, a session will b... | 5 | stack_v2_sparse_classes_30k_train_013028 | Implement the Python class `SQSSifter` described below.
Class description:
AWS SQS queue message receiver and handler selector.
Method signatures and docstrings:
- def __init__(self, queue_url, profile_name=None, region_name='us-east-1', connect=True, filters=None): Initialize an SQS Sifter instance. Arguments: queue... | Implement the Python class `SQSSifter` described below.
Class description:
AWS SQS queue message receiver and handler selector.
Method signatures and docstrings:
- def __init__(self, queue_url, profile_name=None, region_name='us-east-1', connect=True, filters=None): Initialize an SQS Sifter instance. Arguments: queue... | b78fc02b93f2ed1320ba253b01f28f5e2f45afa0 | <|skeleton|>
class SQSSifter:
"""AWS SQS queue message receiver and handler selector."""
def __init__(self, queue_url, profile_name=None, region_name='us-east-1', connect=True, filters=None):
"""Initialize an SQS Sifter instance. Arguments: queue_url (str) The URL of the AWS Queue to sift. profile_name... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SQSSifter:
"""AWS SQS queue message receiver and handler selector."""
def __init__(self, queue_url, profile_name=None, region_name='us-east-1', connect=True, filters=None):
"""Initialize an SQS Sifter instance. Arguments: queue_url (str) The URL of the AWS Queue to sift. profile_name (str) Sessio... | the_stack_v2_python_sparse | boogio/sqs_sifter.py | osgirl/boogio | train | 0 |
ce3749ee1424c6adce799fe1e348471b79ae42af | [
"super(BowElmoEmbedder, self).__init__()\nself.emb_dim = emb_dim\nself.dropout_value = dropout_value\nself.layer_aggregation_type = layer_aggregation\nself.allowed_layer_aggregation_types = ['sum', 'average', 'last', 'first']\nself.cuda_device_id = cuda_device_id\nself.device = torch.device('cpu') if cuda_device_id... | <|body_start_0|>
super(BowElmoEmbedder, self).__init__()
self.emb_dim = emb_dim
self.dropout_value = dropout_value
self.layer_aggregation_type = layer_aggregation
self.allowed_layer_aggregation_types = ['sum', 'average', 'last', 'first']
self.cuda_device_id = cuda_device_... | BowElmoEmbedder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BowElmoEmbedder:
def __init__(self, emb_dim: int=1024, dropout_value: float=0.0, layer_aggregation: str='sum', cuda_device_id: int=-1):
"""Bag of words Elmo Embedder which aggregates elmo embedding for every token Parameters ---------- emb_dim : int Embedding dimension dropout_value : fl... | stack_v2_sparse_classes_36k_train_008465 | 4,125 | permissive | [
{
"docstring": "Bag of words Elmo Embedder which aggregates elmo embedding for every token Parameters ---------- emb_dim : int Embedding dimension dropout_value : float Any input dropout to be applied to the embeddings layer_aggregation : str You can chose one of ``[sum, average, last, first]`` which decides ho... | 2 | stack_v2_sparse_classes_30k_train_001202 | Implement the Python class `BowElmoEmbedder` described below.
Class description:
Implement the BowElmoEmbedder class.
Method signatures and docstrings:
- def __init__(self, emb_dim: int=1024, dropout_value: float=0.0, layer_aggregation: str='sum', cuda_device_id: int=-1): Bag of words Elmo Embedder which aggregates e... | Implement the Python class `BowElmoEmbedder` described below.
Class description:
Implement the BowElmoEmbedder class.
Method signatures and docstrings:
- def __init__(self, emb_dim: int=1024, dropout_value: float=0.0, layer_aggregation: str='sum', cuda_device_id: int=-1): Bag of words Elmo Embedder which aggregates e... | cb4c1413ddc3c749835e1cb80db31c0060e7a1eb | <|skeleton|>
class BowElmoEmbedder:
def __init__(self, emb_dim: int=1024, dropout_value: float=0.0, layer_aggregation: str='sum', cuda_device_id: int=-1):
"""Bag of words Elmo Embedder which aggregates elmo embedding for every token Parameters ---------- emb_dim : int Embedding dimension dropout_value : fl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BowElmoEmbedder:
def __init__(self, emb_dim: int=1024, dropout_value: float=0.0, layer_aggregation: str='sum', cuda_device_id: int=-1):
"""Bag of words Elmo Embedder which aggregates elmo embedding for every token Parameters ---------- emb_dim : int Embedding dimension dropout_value : float Any input ... | the_stack_v2_python_sparse | sciwing/modules/embedders/bow_elmo_embedder.py | yaxche-io/sciwing | train | 0 | |
cd6d799e12791c497bece0c4e7e69aa65c69bafa | [
"import colander as c\nd = {}\nif isinstance(key_provider, str):\n key_provider = uncommafy(key_provider)\nelif not issubclass(key_provider, list):\n key_provider = [n.name for n in key_provider.__all_schema_nodes__]\nfor k in key_provider:\n val = getattr(model, k, undefined)\n if val is undefined:\n ... | <|body_start_0|>
import colander as c
d = {}
if isinstance(key_provider, str):
key_provider = uncommafy(key_provider)
elif not issubclass(key_provider, list):
key_provider = [n.name for n in key_provider.__all_schema_nodes__]
for k in key_provider:
... | BaseViewForDeform | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseViewForDeform:
def model_to_dict(self, model, key_provider):
"""Return an appstruct dict with values taken from the ``model``. *key_provider* can be: * a comma-delimited string of key names, * a list of strings representing key names, * a colander.Schema (or subclass)."""
<|b... | stack_v2_sparse_classes_36k_train_008466 | 2,631 | permissive | [
{
"docstring": "Return an appstruct dict with values taken from the ``model``. *key_provider* can be: * a comma-delimited string of key names, * a list of strings representing key names, * a colander.Schema (or subclass).",
"name": "model_to_dict",
"signature": "def model_to_dict(self, model, key_provid... | 2 | stack_v2_sparse_classes_30k_train_016200 | Implement the Python class `BaseViewForDeform` described below.
Class description:
Implement the BaseViewForDeform class.
Method signatures and docstrings:
- def model_to_dict(self, model, key_provider): Return an appstruct dict with values taken from the ``model``. *key_provider* can be: * a comma-delimited string o... | Implement the Python class `BaseViewForDeform` described below.
Class description:
Implement the BaseViewForDeform class.
Method signatures and docstrings:
- def model_to_dict(self, model, key_provider): Return an appstruct dict with values taken from the ``model``. *key_provider* can be: * a comma-delimited string o... | 63f6fbd3e768bf55d79ac96964aa3bf7702f3f9a | <|skeleton|>
class BaseViewForDeform:
def model_to_dict(self, model, key_provider):
"""Return an appstruct dict with values taken from the ``model``. *key_provider* can be: * a comma-delimited string of key names, * a list of strings representing key names, * a colander.Schema (or subclass)."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseViewForDeform:
def model_to_dict(self, model, key_provider):
"""Return an appstruct dict with values taken from the ``model``. *key_provider* can be: * a comma-delimited string of key names, * a list of strings representing key names, * a colander.Schema (or subclass)."""
import colander a... | the_stack_v2_python_sparse | bag/web/pyramid/apps/views.py | nandoflorestan/bag | train | 24 | |
4d426cae266924625a3592304de415e6dcea4e9e | [
"super(Directory, self).__init__(name, repo_details, create_new, overwrite)\ndir_path = pathlib.Path(name)\nif dir_path.exists():\n self._full_path = dir_path.absolute()\nelif create_new is True:\n dir_path = dir_path.absolute()\n self._full_path = dir_path.mkdir(parents=True)\nelse:\n raise Exception('... | <|body_start_0|>
super(Directory, self).__init__(name, repo_details, create_new, overwrite)
dir_path = pathlib.Path(name)
if dir_path.exists():
self._full_path = dir_path.absolute()
elif create_new is True:
dir_path = dir_path.absolute()
self._full_pat... | Same as :class:`File` but works on dirs instead | DirectoryDriver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectoryDriver:
"""Same as :class:`File` but works on dirs instead"""
def __init__(self, name: str, repo_details: Type[Dict]=None, create_new: bool=False, overwrite: bool=False):
"""Default constructor for an directory"""
<|body_0|>
def copy(self, destination: str, forc... | stack_v2_sparse_classes_36k_train_008467 | 10,502 | no_license | [
{
"docstring": "Default constructor for an directory",
"name": "__init__",
"signature": "def __init__(self, name: str, repo_details: Type[Dict]=None, create_new: bool=False, overwrite: bool=False)"
},
{
"docstring": "Copy file to new location passed as param. If file already exists and force par... | 6 | stack_v2_sparse_classes_30k_train_021010 | Implement the Python class `DirectoryDriver` described below.
Class description:
Same as :class:`File` but works on dirs instead
Method signatures and docstrings:
- def __init__(self, name: str, repo_details: Type[Dict]=None, create_new: bool=False, overwrite: bool=False): Default constructor for an directory
- def c... | Implement the Python class `DirectoryDriver` described below.
Class description:
Same as :class:`File` but works on dirs instead
Method signatures and docstrings:
- def __init__(self, name: str, repo_details: Type[Dict]=None, create_new: bool=False, overwrite: bool=False): Default constructor for an directory
- def c... | 99f61a0ce0f2d5c587002ddf8d2843e83d9538d3 | <|skeleton|>
class DirectoryDriver:
"""Same as :class:`File` but works on dirs instead"""
def __init__(self, name: str, repo_details: Type[Dict]=None, create_new: bool=False, overwrite: bool=False):
"""Default constructor for an directory"""
<|body_0|>
def copy(self, destination: str, forc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DirectoryDriver:
"""Same as :class:`File` but works on dirs instead"""
def __init__(self, name: str, repo_details: Type[Dict]=None, create_new: bool=False, overwrite: bool=False):
"""Default constructor for an directory"""
super(Directory, self).__init__(name, repo_details, create_new, ov... | the_stack_v2_python_sparse | plugins/io/default/armin_ext/drivers/file/system.py | singajeet/armin | train | 0 |
5d83fa327126e72251f3282bb58e220c2896e5ff | [
"if root is None:\n return []\nstack = [root]\nyy = []\nwhile stack:\n print(stack)\n y = []\n l = len(stack)\n for i in range(l):\n cur = stack.pop(0)\n y.append(cur.val)\n if cur.left:\n stack.append(cur.left)\n if cur.right:\n stack.append(cur.righ... | <|body_start_0|>
if root is None:
return []
stack = [root]
yy = []
while stack:
print(stack)
y = []
l = len(stack)
for i in range(l):
cur = stack.pop(0)
y.append(cur.val)
if cur.le... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":param root: TreeNode :return:list[list[int]"""
<|body_0|>
def levelOrder_2(self, root):
""":param root: TreeNode :return:list[list[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
... | stack_v2_sparse_classes_36k_train_008468 | 1,830 | no_license | [
{
"docstring": ":param root: TreeNode :return:list[list[int]",
"name": "levelOrder",
"signature": "def levelOrder(self, root)"
},
{
"docstring": ":param root: TreeNode :return:list[list[int]",
"name": "levelOrder_2",
"signature": "def levelOrder_2(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :param root: TreeNode :return:list[list[int]
- def levelOrder_2(self, root): :param root: TreeNode :return:list[list[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :param root: TreeNode :return:list[list[int]
- def levelOrder_2(self, root): :param root: TreeNode :return:list[list[int]
<|skeleton|>
class Solution... | 4f2802d4773eddd2a2e06e61c51463056886b730 | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":param root: TreeNode :return:list[list[int]"""
<|body_0|>
def levelOrder_2(self, root):
""":param root: TreeNode :return:list[list[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def levelOrder(self, root):
""":param root: TreeNode :return:list[list[int]"""
if root is None:
return []
stack = [root]
yy = []
while stack:
print(stack)
y = []
l = len(stack)
for i in range(l):
... | the_stack_v2_python_sparse | leetcode/30_levelOrder.py | Yara7L/python_algorithm | train | 0 | |
acb305d75598a41d1c46e4307bd4014847bacbd5 | [
"if not identifier and (not location) or not parent:\n raise ValueError('Missing identifier and location, or parent value.')\nsuper(HFSPathSpec, self).__init__(parent=parent, **kwargs)\nself.data_stream = data_stream\nself.identifier = identifier\nself.location = location",
"string_parts = []\nif self.data_str... | <|body_start_0|>
if not identifier and (not location) or not parent:
raise ValueError('Missing identifier and location, or parent value.')
super(HFSPathSpec, self).__init__(parent=parent, **kwargs)
self.data_stream = data_stream
self.identifier = identifier
self.locat... | HFS path specification implementation. Attributes: data_stream (str): data stream name, where None indicates the default data stream. identifier (int): catalog node identifier (CNID). location (str): location. | HFSPathSpec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HFSPathSpec:
"""HFS path specification implementation. Attributes: data_stream (str): data stream name, where None indicates the default data stream. identifier (int): catalog node identifier (CNID). location (str): location."""
def __init__(self, data_stream=None, identifier=None, location=... | stack_v2_sparse_classes_36k_train_008469 | 1,932 | permissive | [
{
"docstring": "Initializes a path specification. Note that an HFS path specification must have a parent. Args: data_stream (Optional[str]): data stream name, where None indicates the default data stream. identifier (Optional[int]): catalog node identifier (CNID). location (Optional[str]): location. parent (Opt... | 2 | stack_v2_sparse_classes_30k_train_006283 | Implement the Python class `HFSPathSpec` described below.
Class description:
HFS path specification implementation. Attributes: data_stream (str): data stream name, where None indicates the default data stream. identifier (int): catalog node identifier (CNID). location (str): location.
Method signatures and docstring... | Implement the Python class `HFSPathSpec` described below.
Class description:
HFS path specification implementation. Attributes: data_stream (str): data stream name, where None indicates the default data stream. identifier (int): catalog node identifier (CNID). location (str): location.
Method signatures and docstring... | 28756d910e951a22c5f0b2bcf5184f055a19d544 | <|skeleton|>
class HFSPathSpec:
"""HFS path specification implementation. Attributes: data_stream (str): data stream name, where None indicates the default data stream. identifier (int): catalog node identifier (CNID). location (str): location."""
def __init__(self, data_stream=None, identifier=None, location=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HFSPathSpec:
"""HFS path specification implementation. Attributes: data_stream (str): data stream name, where None indicates the default data stream. identifier (int): catalog node identifier (CNID). location (str): location."""
def __init__(self, data_stream=None, identifier=None, location=None, parent=... | the_stack_v2_python_sparse | dfvfs/path/hfs_path_spec.py | log2timeline/dfvfs | train | 197 |
dfc331360babeadf9a1325e7e924e833784a3252 | [
"pairs.sort(key=lambda x: x[1])\nn = len(pairs)\nret = 0\ncur_end = -float('inf')\nfor i in range(n):\n if pairs[i][0] <= cur_end:\n continue\n cur_end = pairs[i][1]\n ret += 1\nreturn ret",
"pairs.sort(key=lambda x: x[1])\nn = len(pairs)\nret = 0\ni = 0\nwhile i < n:\n ret += 1\n cur_end = ... | <|body_start_0|>
pairs.sort(key=lambda x: x[1])
n = len(pairs)
ret = 0
cur_end = -float('inf')
for i in range(n):
if pairs[i][0] <= cur_end:
continue
cur_end = pairs[i][1]
ret += 1
return ret
<|end_body_0|>
<|body_start... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
"""Greedy sort by the interval end similar to 435 Non-overlaping interval O(nlg n) + O(n)"""
<|body_0|>
def findLongestChain2(self, pairs: List[List[int]]) -> int:
"""Greedy sort by the interval end... | stack_v2_sparse_classes_36k_train_008470 | 2,168 | no_license | [
{
"docstring": "Greedy sort by the interval end similar to 435 Non-overlaping interval O(nlg n) + O(n)",
"name": "findLongestChain",
"signature": "def findLongestChain(self, pairs: List[List[int]]) -> int"
},
{
"docstring": "Greedy sort by the interval end similar to 435 Non-overlaping interval"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLongestChain(self, pairs: List[List[int]]) -> int: Greedy sort by the interval end similar to 435 Non-overlaping interval O(nlg n) + O(n)
- def findLongestChain2(self, pa... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLongestChain(self, pairs: List[List[int]]) -> int: Greedy sort by the interval end similar to 435 Non-overlaping interval O(nlg n) + O(n)
- def findLongestChain2(self, pa... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
"""Greedy sort by the interval end similar to 435 Non-overlaping interval O(nlg n) + O(n)"""
<|body_0|>
def findLongestChain2(self, pairs: List[List[int]]) -> int:
"""Greedy sort by the interval end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
"""Greedy sort by the interval end similar to 435 Non-overlaping interval O(nlg n) + O(n)"""
pairs.sort(key=lambda x: x[1])
n = len(pairs)
ret = 0
cur_end = -float('inf')
for i in range(n):
... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/646 Maximum Length of Pair Chain.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
2e7f6dac0b79271ba1d8184474af53820bae0490 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TenantAppManagementPolicy()",
"from .app_management_configuration import AppManagementConfiguration\nfrom .policy_base import PolicyBase\nfrom .app_management_configuration import AppManagementConfiguration\nfrom .policy_base import Po... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TenantAppManagementPolicy()
<|end_body_0|>
<|body_start_1|>
from .app_management_configuration import AppManagementConfiguration
from .policy_base import PolicyBase
from .app_man... | TenantAppManagementPolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenantAppManagementPolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TenantAppManagementPolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and c... | stack_v2_sparse_classes_36k_train_008471 | 3,160 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TenantAppManagementPolicy",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrim... | 3 | stack_v2_sparse_classes_30k_train_004390 | Implement the Python class `TenantAppManagementPolicy` described below.
Class description:
Implement the TenantAppManagementPolicy class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TenantAppManagementPolicy: Creates a new instance of the appropriat... | Implement the Python class `TenantAppManagementPolicy` described below.
Class description:
Implement the TenantAppManagementPolicy class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TenantAppManagementPolicy: Creates a new instance of the appropriat... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TenantAppManagementPolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TenantAppManagementPolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TenantAppManagementPolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TenantAppManagementPolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | the_stack_v2_python_sparse | msgraph/generated/models/tenant_app_management_policy.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
4ceb25d102a01d160b316ff965f95e2cbca8c3f5 | [
"self.app = app\nif 'name' not in queue_info:\n raise InvalidQueueConfiguration('Queue requires a name: {}'.format(queue_info))\nself.name = queue_info['name']\nself.task_retry_limit = self.DEFAULT_RETRY_LIMIT\nif 'retry_parameters' in queue_info:\n retry_params = queue_info['retry_parameters']\n if 'task_... | <|body_start_0|>
self.app = app
if 'name' not in queue_info:
raise InvalidQueueConfiguration('Queue requires a name: {}'.format(queue_info))
self.name = queue_info['name']
self.task_retry_limit = self.DEFAULT_RETRY_LIMIT
if 'retry_parameters' in queue_info:
... | Represents a queue created by an App Engine application. | Queue | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Queue:
"""Represents a queue created by an App Engine application."""
def __init__(self, queue_info, app):
"""Create a Queue object. Args: queue_info: A dictionary containing queue info. app: A string containing the application ID."""
<|body_0|>
def validate_config(self)... | stack_v2_sparse_classes_36k_train_008472 | 29,716 | permissive | [
{
"docstring": "Create a Queue object. Args: queue_info: A dictionary containing queue info. app: A string containing the application ID.",
"name": "__init__",
"signature": "def __init__(self, queue_info, app)"
},
{
"docstring": "Ensures all of the Queue's attributes are valid. Raises: InvalidQu... | 3 | stack_v2_sparse_classes_30k_train_001285 | Implement the Python class `Queue` described below.
Class description:
Represents a queue created by an App Engine application.
Method signatures and docstrings:
- def __init__(self, queue_info, app): Create a Queue object. Args: queue_info: A dictionary containing queue info. app: A string containing the application... | Implement the Python class `Queue` described below.
Class description:
Represents a queue created by an App Engine application.
Method signatures and docstrings:
- def __init__(self, queue_info, app): Create a Queue object. Args: queue_info: A dictionary containing queue info. app: A string containing the application... | c24ddfd987c8eed8ed8864cc839cc0556a8af3c7 | <|skeleton|>
class Queue:
"""Represents a queue created by an App Engine application."""
def __init__(self, queue_info, app):
"""Create a Queue object. Args: queue_info: A dictionary containing queue info. app: A string containing the application ID."""
<|body_0|>
def validate_config(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Queue:
"""Represents a queue created by an App Engine application."""
def __init__(self, queue_info, app):
"""Create a Queue object. Args: queue_info: A dictionary containing queue info. app: A string containing the application ID."""
self.app = app
if 'name' not in queue_info:
... | the_stack_v2_python_sparse | AppTaskQueue/appscale/taskqueue/queue.py | christianbaun/appscale | train | 2 |
5be74370162047a66687c6ecd158a982349bc734 | [
"Inventory.__init__(self, inventory_info)\nself.material = material\nself.size = size",
"output_dict = Inventory.return_as_dictionary(self)\noutput_dict['material'] = self.material\noutput_dict['size'] = self.size\nreturn output_dict"
] | <|body_start_0|>
Inventory.__init__(self, inventory_info)
self.material = material
self.size = size
<|end_body_0|>
<|body_start_1|>
output_dict = Inventory.return_as_dictionary(self)
output_dict['material'] = self.material
output_dict['size'] = self.size
return o... | Creates a class that handles data on furniture | Furniture | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Furniture:
"""Creates a class that handles data on furniture"""
def __init__(self, inventory_info, material, size):
"""Initializes the class info"""
<|body_0|>
def return_as_dictionary(self):
"""Returns a dictionary of the furniture information"""
<|body_... | stack_v2_sparse_classes_36k_train_008473 | 695 | no_license | [
{
"docstring": "Initializes the class info",
"name": "__init__",
"signature": "def __init__(self, inventory_info, material, size)"
},
{
"docstring": "Returns a dictionary of the furniture information",
"name": "return_as_dictionary",
"signature": "def return_as_dictionary(self)"
}
] | 2 | null | Implement the Python class `Furniture` described below.
Class description:
Creates a class that handles data on furniture
Method signatures and docstrings:
- def __init__(self, inventory_info, material, size): Initializes the class info
- def return_as_dictionary(self): Returns a dictionary of the furniture informati... | Implement the Python class `Furniture` described below.
Class description:
Creates a class that handles data on furniture
Method signatures and docstrings:
- def __init__(self, inventory_info, material, size): Initializes the class info
- def return_as_dictionary(self): Returns a dictionary of the furniture informati... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class Furniture:
"""Creates a class that handles data on furniture"""
def __init__(self, inventory_info, material, size):
"""Initializes the class info"""
<|body_0|>
def return_as_dictionary(self):
"""Returns a dictionary of the furniture information"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Furniture:
"""Creates a class that handles data on furniture"""
def __init__(self, inventory_info, material, size):
"""Initializes the class info"""
Inventory.__init__(self, inventory_info)
self.material = material
self.size = size
def return_as_dictionary(self):
... | the_stack_v2_python_sparse | students/dfspray/Lesson01/inventory_management/furniture_class.py | JavaRod/SP_Python220B_2019 | train | 1 |
b0dfb261cd8e38c1bdaab216c55b49593deca1d5 | [
"if n < 4:\n return n\ncounts = list(range(n + 1))\nfor i in range(n):\n j = 1\n while True:\n temp = i + j * j\n if temp > n:\n break\n if counts[temp] > counts[i] + 1:\n counts[temp] = counts[i] + 1\n j += 1\nreturn counts[n]",
"if n < 4:\n return n\... | <|body_start_0|>
if n < 4:
return n
counts = list(range(n + 1))
for i in range(n):
j = 1
while True:
temp = i + j * j
if temp > n:
break
if counts[temp] > counts[i] + 1:
co... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares_DP(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def numSquares_Math(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n < 4:
return n
counts = list(range(n + ... | stack_v2_sparse_classes_36k_train_008474 | 2,068 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "numSquares_DP",
"signature": "def numSquares_DP(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "numSquares_Math",
"signature": "def numSquares_Math(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000606 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares_DP(self, n): :type n: int :rtype: int
- def numSquares_Math(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares_DP(self, n): :type n: int :rtype: int
- def numSquares_Math(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def numSquares_DP(self, n):
... | e07b85a4121f2665393f1176befbdbe06f1e1ad0 | <|skeleton|>
class Solution:
def numSquares_DP(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def numSquares_Math(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSquares_DP(self, n):
""":type n: int :rtype: int"""
if n < 4:
return n
counts = list(range(n + 1))
for i in range(n):
j = 1
while True:
temp = i + j * j
if temp > n:
break
... | the_stack_v2_python_sparse | Algorithms/perfect-squares.py | feilniu/LeetCode | train | 0 | |
060676526d8244fb554f4e095b8a715eedaf623f | [
"import collections as cc\nidx_time = cc.defaultdict(list)\npstack = []\nfor lg in logs:\n idx, entry, ts = lg.split(':')\n idx, ts = (int(idx), int(ts))\n if entry == 'end':\n parent_func = pstack.pop()\n func_sum = ts - parent_func[1] + 1\n idx_time[parent_func[0]].append(func_sum - ... | <|body_start_0|>
import collections as cc
idx_time = cc.defaultdict(list)
pstack = []
for lg in logs:
idx, entry, ts = lg.split(':')
idx, ts = (int(idx), int(ts))
if entry == 'end':
parent_func = pstack.pop()
func_sum = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def exclusiveTime(self, n, logs):
""":type n: int 有多少functions :type logs: List[str] :rtype: List[int]"""
<|body_0|>
def rewrite(self, n, logs):
""":type n: int 有多少functions :type logs: List[str] :rtype: List[int] 最佳解 call function本來就是stack rewind"""
... | stack_v2_sparse_classes_36k_train_008475 | 4,227 | no_license | [
{
"docstring": ":type n: int 有多少functions :type logs: List[str] :rtype: List[int]",
"name": "exclusiveTime",
"signature": "def exclusiveTime(self, n, logs)"
},
{
"docstring": ":type n: int 有多少functions :type logs: List[str] :rtype: List[int] 最佳解 call function本來就是stack rewind",
"name": "rewri... | 2 | stack_v2_sparse_classes_30k_train_003914 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def exclusiveTime(self, n, logs): :type n: int 有多少functions :type logs: List[str] :rtype: List[int]
- def rewrite(self, n, logs): :type n: int 有多少functions :type logs: List[str] ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def exclusiveTime(self, n, logs): :type n: int 有多少functions :type logs: List[str] :rtype: List[int]
- def rewrite(self, n, logs): :type n: int 有多少functions :type logs: List[str] ... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def exclusiveTime(self, n, logs):
""":type n: int 有多少functions :type logs: List[str] :rtype: List[int]"""
<|body_0|>
def rewrite(self, n, logs):
""":type n: int 有多少functions :type logs: List[str] :rtype: List[int] 最佳解 call function本來就是stack rewind"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def exclusiveTime(self, n, logs):
""":type n: int 有多少functions :type logs: List[str] :rtype: List[int]"""
import collections as cc
idx_time = cc.defaultdict(list)
pstack = []
for lg in logs:
idx, entry, ts = lg.split(':')
idx, ts = (int... | the_stack_v2_python_sparse | stack/636_Exclusive_Time_of_Functions.py | vsdrun/lc_public | train | 6 | |
7fafa8dda581cdd720b0570be600d28f49346d95 | [
"Frame.__init__(self, master)\nself.pack()\nself.createWidgets()",
"top_frame = Frame(self)\nself.text_in = Entry(top_frame)\nself.label = Label(top_frame, text='Output label')\nself.text_in.pack()\nself.label.pack()\nself.r = IntVar()\nRadiobutton(top_frame, text='Upper case', variable=self.r, value=1).pack(side... | <|body_start_0|>
Frame.__init__(self, master)
self.pack()
self.createWidgets()
<|end_body_0|>
<|body_start_1|>
top_frame = Frame(self)
self.text_in = Entry(top_frame)
self.label = Label(top_frame, text='Output label')
self.text_in.pack()
self.label.pack()... | Application main window class. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):
... | stack_v2_sparse_classes_36k_train_008476 | 2,403 | no_license | [
{
"docstring": "Main frame initialization (mostly delegated)",
"name": "__init__",
"signature": "def __init__(self, master=None)"
},
{
"docstring": "Add all the widgets to the main frame.",
"name": "createWidgets",
"signature": "def createWidgets(self)"
},
{
"docstring": "Handle ... | 3 | stack_v2_sparse_classes_30k_train_007918 | Implement the Python class `Application` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createWidgets(self): Add all the widgets to the main frame.
- def handle(self): Handle a c... | Implement the Python class `Application` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createWidgets(self): Add all the widgets to the main frame.
- def handle(self): Handle a c... | 06c45545ed064d0e9c4fd15cc81cf454cb079c9d | <|skeleton|>
class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
"""Add all the widgets to the main fram... | the_stack_v2_python_sparse | Lesson 7 - Intro GUI/texthandler.py | jmwoloso/Python_2 | train | 0 |
ee225ac9bf012a3d7824915fa9e698ad0e1aca64 | [
"assert isinstance(gf, callflow.GraphFrame)\nassert 'component_path' in gf.df.columns\npaths = self.callsite_paths(callsites)\nmodule_name_group_df = gf.df.groupby(['module', 'name'])\nfor path in paths:\n component_edges = self.create_source_targets(path['component_path'])\n for idx, edge in enumerate(compon... | <|body_start_0|>
assert isinstance(gf, callflow.GraphFrame)
assert 'component_path' in gf.df.columns
paths = self.callsite_paths(callsites)
module_name_group_df = gf.df.groupby(['module', 'name'])
for path in paths:
component_edges = self.create_source_targets(path['c... | Split a callee if it is a module. | SplitCallee | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SplitCallee:
"""Split a callee if it is a module."""
def __init__(self, gf, callsites):
""":param gf: :param callsites:"""
<|body_0|>
def create_source_targets(self, component_path):
""":param component_path: :return:"""
<|body_1|>
def callsite_paths... | stack_v2_sparse_classes_36k_train_008477 | 4,324 | permissive | [
{
"docstring": ":param gf: :param callsites:",
"name": "__init__",
"signature": "def __init__(self, gf, callsites)"
},
{
"docstring": ":param component_path: :return:",
"name": "create_source_targets",
"signature": "def create_source_targets(self, component_path)"
},
{
"docstring... | 3 | stack_v2_sparse_classes_30k_train_018812 | Implement the Python class `SplitCallee` described below.
Class description:
Split a callee if it is a module.
Method signatures and docstrings:
- def __init__(self, gf, callsites): :param gf: :param callsites:
- def create_source_targets(self, component_path): :param component_path: :return:
- def callsite_paths(sel... | Implement the Python class `SplitCallee` described below.
Class description:
Split a callee if it is a module.
Method signatures and docstrings:
- def __init__(self, gf, callsites): :param gf: :param callsites:
- def create_source_targets(self, component_path): :param component_path: :return:
- def callsite_paths(sel... | 6bbdabe4b71be369e616e3136d7f0120531c9fc8 | <|skeleton|>
class SplitCallee:
"""Split a callee if it is a module."""
def __init__(self, gf, callsites):
""":param gf: :param callsites:"""
<|body_0|>
def create_source_targets(self, component_path):
""":param component_path: :return:"""
<|body_1|>
def callsite_paths... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SplitCallee:
"""Split a callee if it is a module."""
def __init__(self, gf, callsites):
""":param gf: :param callsites:"""
assert isinstance(gf, callflow.GraphFrame)
assert 'component_path' in gf.df.columns
paths = self.callsite_paths(callsites)
module_name_group_d... | the_stack_v2_python_sparse | callflow/operations/split_callee.py | LLNL/CallFlow | train | 32 |
490abdc21c224c19a9f1bd64486999d9e93698bf | [
"if self.attrs is None:\n self.attrs = set()\nself.attrs.add(paramsCss['attr'])\nsuper(CssStyle, self).append(paramsCss)",
"if self.attrs is None:\n for attr, val in params.items():\n self.append({'attr': attr, 'value': val})\nelse:\n for attr, val in params.items():\n if attr in self.attrs... | <|body_start_0|>
if self.attrs is None:
self.attrs = set()
self.attrs.add(paramsCss['attr'])
super(CssStyle, self).append(paramsCss)
<|end_body_0|>
<|body_start_1|>
if self.attrs is None:
for attr, val in params.items():
self.append({'attr': attr,... | :category: CSS :rubric: PY :type: constructor :dsc: This is proxy class to a list dedicated to monitor the CSS classes The use of this class will help to manage the different possible attributes but also to be able going forward to add more flexibility | CssStyle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CssStyle:
""":category: CSS :rubric: PY :type: constructor :dsc: This is proxy class to a list dedicated to monitor the CSS classes The use of this class will help to manage the different possible attributes but also to be able going forward to add more flexibility"""
def append(self, params... | stack_v2_sparse_classes_36k_train_008478 | 29,788 | permissive | [
{
"docstring": ":category: CSS Style Builder :rubric: PY :type: style :example: >>> cssObj.append( {'attr': 'color'} ) :dsc: Add parameters to the CSS Style generated from Python :link CSS Class Documentation: https://www.w3schools.com/html/html_classes.asp",
"name": "append",
"signature": "def append(s... | 2 | null | Implement the Python class `CssStyle` described below.
Class description:
:category: CSS :rubric: PY :type: constructor :dsc: This is proxy class to a list dedicated to monitor the CSS classes The use of this class will help to manage the different possible attributes but also to be able going forward to add more flex... | Implement the Python class `CssStyle` described below.
Class description:
:category: CSS :rubric: PY :type: constructor :dsc: This is proxy class to a list dedicated to monitor the CSS classes The use of this class will help to manage the different possible attributes but also to be able going forward to add more flex... | 3cf5068f874b3f6fe898968b2a7efa86fadca99d | <|skeleton|>
class CssStyle:
""":category: CSS :rubric: PY :type: constructor :dsc: This is proxy class to a list dedicated to monitor the CSS classes The use of this class will help to manage the different possible attributes but also to be able going forward to add more flexibility"""
def append(self, params... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CssStyle:
""":category: CSS :rubric: PY :type: constructor :dsc: This is proxy class to a list dedicated to monitor the CSS classes The use of this class will help to manage the different possible attributes but also to be able going forward to add more flexibility"""
def append(self, paramsCss):
... | the_stack_v2_python_sparse | Lib/css/CssBase.py | jeamick/ares-visual | train | 0 |
1c82d096d7c6bdea7d863c8d1db7ea065e8f127a | [
"raise ApiError(500, 1, 'vlan status is null')\nobj = {'vlan_arr': []}\nargs = Verify.dict(self.req_args, {'limit?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid limit')), 'index?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid index'))})\narr = vcmd.get_arr_simple('cdbctl read/cdb/... | <|body_start_0|>
raise ApiError(500, 1, 'vlan status is null')
obj = {'vlan_arr': []}
args = Verify.dict(self.req_args, {'limit?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid limit')), 'index?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid index'))})
ar... | VlanApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VlanApi:
def get(self):
"""get vlan array"""
<|body_0|>
def post(self):
"""add vlan"""
<|body_1|>
def put(self):
"""modify vlan name"""
<|body_2|>
def delete(self):
"""delete vlans"""
<|body_3|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_008479 | 3,263 | no_license | [
{
"docstring": "get vlan array",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "add vlan",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "modify vlan name",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "delete vla... | 4 | stack_v2_sparse_classes_30k_train_000558 | Implement the Python class `VlanApi` described below.
Class description:
Implement the VlanApi class.
Method signatures and docstrings:
- def get(self): get vlan array
- def post(self): add vlan
- def put(self): modify vlan name
- def delete(self): delete vlans | Implement the Python class `VlanApi` described below.
Class description:
Implement the VlanApi class.
Method signatures and docstrings:
- def get(self): get vlan array
- def post(self): add vlan
- def put(self): modify vlan name
- def delete(self): delete vlans
<|skeleton|>
class VlanApi:
def get(self):
... | 2fee6115caec25fd040188dda0cb922bfca1a55f | <|skeleton|>
class VlanApi:
def get(self):
"""get vlan array"""
<|body_0|>
def post(self):
"""add vlan"""
<|body_1|>
def put(self):
"""modify vlan name"""
<|body_2|>
def delete(self):
"""delete vlans"""
<|body_3|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VlanApi:
def get(self):
"""get vlan array"""
raise ApiError(500, 1, 'vlan status is null')
obj = {'vlan_arr': []}
args = Verify.dict(self.req_args, {'limit?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid limit')), 'index?': (lambda x: x.type('int') and x > 0, A... | the_stack_v2_python_sparse | osp_sai_2.1.8/system/apps/web/api_class/vlan.py | bonald/vim_cfg | train | 0 | |
36f1f1176ca5b91d8e496019f7b037101f623504 | [
"alphabet_size = len(self.alphabet)\nif background is None:\n background = ones(alphabet_size, float32) / alphabet_size\ntotals = numpy.sum(self.values, 1)[:, newaxis]\nvalues = log2(maximum(self.values, correction)) - log2(totals) - log2(maximum(background, correction))\nreturn ScoringMatrix.create_from_other(s... | <|body_start_0|>
alphabet_size = len(self.alphabet)
if background is None:
background = ones(alphabet_size, float32) / alphabet_size
totals = numpy.sum(self.values, 1)[:, newaxis]
values = log2(maximum(self.values, correction)) - log2(totals) - log2(maximum(background, correc... | A position specific count/frequency matrix. | FrequencyMatrix | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrequencyMatrix:
"""A position specific count/frequency matrix."""
def to_logodds_scoring_matrix(self, background=None, correction=DEFAULT_CORRECTION):
"""Create a standard logodds scoring matrix."""
<|body_0|>
def to_stormo_scoring_matrix(self, background=None):
... | stack_v2_sparse_classes_36k_train_008480 | 5,401 | permissive | [
{
"docstring": "Create a standard logodds scoring matrix.",
"name": "to_logodds_scoring_matrix",
"signature": "def to_logodds_scoring_matrix(self, background=None, correction=DEFAULT_CORRECTION)"
},
{
"docstring": "Create a scoring matrix from this count matrix using the method from: Hertz, G.Z.... | 2 | null | Implement the Python class `FrequencyMatrix` described below.
Class description:
A position specific count/frequency matrix.
Method signatures and docstrings:
- def to_logodds_scoring_matrix(self, background=None, correction=DEFAULT_CORRECTION): Create a standard logodds scoring matrix.
- def to_stormo_scoring_matrix... | Implement the Python class `FrequencyMatrix` described below.
Class description:
A position specific count/frequency matrix.
Method signatures and docstrings:
- def to_logodds_scoring_matrix(self, background=None, correction=DEFAULT_CORRECTION): Create a standard logodds scoring matrix.
- def to_stormo_scoring_matrix... | 7758bc4492626ffdbaa90c8fc5dd7620b1e2f3f8 | <|skeleton|>
class FrequencyMatrix:
"""A position specific count/frequency matrix."""
def to_logodds_scoring_matrix(self, background=None, correction=DEFAULT_CORRECTION):
"""Create a standard logodds scoring matrix."""
<|body_0|>
def to_stormo_scoring_matrix(self, background=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FrequencyMatrix:
"""A position specific count/frequency matrix."""
def to_logodds_scoring_matrix(self, background=None, correction=DEFAULT_CORRECTION):
"""Create a standard logodds scoring matrix."""
alphabet_size = len(self.alphabet)
if background is None:
background ... | the_stack_v2_python_sparse | lib/bx/motif/pwm.py | bxlab/bx-python | train | 141 |
4408d3351401dc52435f2ab39e1f26ace725432a | [
"super().__init__(hub, entry)\nif slave_count:\n self._count = self._count * (slave_count + 1)\nself._coordinator: DataUpdateCoordinator[list[int] | None] | None = None\nself._attr_native_unit_of_measurement = entry.get(CONF_UNIT_OF_MEASUREMENT)\nself._attr_state_class = entry.get(CONF_STATE_CLASS)\nself._attr_d... | <|body_start_0|>
super().__init__(hub, entry)
if slave_count:
self._count = self._count * (slave_count + 1)
self._coordinator: DataUpdateCoordinator[list[int] | None] | None = None
self._attr_native_unit_of_measurement = entry.get(CONF_UNIT_OF_MEASUREMENT)
self._attr_... | Modbus register sensor. | ModbusRegisterSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModbusRegisterSensor:
"""Modbus register sensor."""
def __init__(self, hub: ModbusHub, entry: dict[str, Any], slave_count: int) -> None:
"""Initialize the modbus register sensor."""
<|body_0|>
async def async_setup_slaves(self, hass: HomeAssistant, slave_count: int, entr... | stack_v2_sparse_classes_36k_train_008481 | 6,226 | permissive | [
{
"docstring": "Initialize the modbus register sensor.",
"name": "__init__",
"signature": "def __init__(self, hub: ModbusHub, entry: dict[str, Any], slave_count: int) -> None"
},
{
"docstring": "Add slaves as needed (1 read for multiple sensors).",
"name": "async_setup_slaves",
"signatur... | 4 | stack_v2_sparse_classes_30k_test_000463 | Implement the Python class `ModbusRegisterSensor` described below.
Class description:
Modbus register sensor.
Method signatures and docstrings:
- def __init__(self, hub: ModbusHub, entry: dict[str, Any], slave_count: int) -> None: Initialize the modbus register sensor.
- async def async_setup_slaves(self, hass: HomeA... | Implement the Python class `ModbusRegisterSensor` described below.
Class description:
Modbus register sensor.
Method signatures and docstrings:
- def __init__(self, hub: ModbusHub, entry: dict[str, Any], slave_count: int) -> None: Initialize the modbus register sensor.
- async def async_setup_slaves(self, hass: HomeA... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ModbusRegisterSensor:
"""Modbus register sensor."""
def __init__(self, hub: ModbusHub, entry: dict[str, Any], slave_count: int) -> None:
"""Initialize the modbus register sensor."""
<|body_0|>
async def async_setup_slaves(self, hass: HomeAssistant, slave_count: int, entr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModbusRegisterSensor:
"""Modbus register sensor."""
def __init__(self, hub: ModbusHub, entry: dict[str, Any], slave_count: int) -> None:
"""Initialize the modbus register sensor."""
super().__init__(hub, entry)
if slave_count:
self._count = self._count * (slave_count +... | the_stack_v2_python_sparse | homeassistant/components/modbus/sensor.py | home-assistant/core | train | 35,501 |
2f2dfb0b8031d58b5d6d87465367928fd01a259d | [
"try:\n value = get_user_preference(request.user, preference_key, username=username)\n if value is None:\n return Response(status=status.HTTP_404_NOT_FOUND)\nexcept UserNotAuthorized:\n return Response(status=status.HTTP_403_FORBIDDEN)\nexcept UserNotFound:\n return Response(status=status.HTTP_40... | <|body_start_0|>
try:
value = get_user_preference(request.user, preference_key, username=username)
if value is None:
return Response(status=status.HTTP_404_NOT_FOUND)
except UserNotAuthorized:
return Response(status=status.HTTP_403_FORBIDDEN)
e... | **Use Cases** Get, create, update, or delete a specific user preference. **Example Requests** GET /api/user/v1/preferences/{username}/{preference_key} PUT /api/user/v1/preferences/{username}/{preference_key} DELETE /api/user/v1/preferences/{username}/{preference_key} **Response Values for GET** If the specified usernam... | PreferencesDetailView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreferencesDetailView:
"""**Use Cases** Get, create, update, or delete a specific user preference. **Example Requests** GET /api/user/v1/preferences/{username}/{preference_key} PUT /api/user/v1/preferences/{username}/{preference_key} DELETE /api/user/v1/preferences/{username}/{preference_key} **R... | stack_v2_sparse_classes_36k_train_008482 | 11,020 | permissive | [
{
"docstring": "GET /api/user/v1/preferences/{username}/{preference_key}",
"name": "get",
"signature": "def get(self, request, username, preference_key)"
},
{
"docstring": "PUT /api/user/v1/preferences/{username}/{preference_key}",
"name": "put",
"signature": "def put(self, request, user... | 3 | stack_v2_sparse_classes_30k_train_001248 | Implement the Python class `PreferencesDetailView` described below.
Class description:
**Use Cases** Get, create, update, or delete a specific user preference. **Example Requests** GET /api/user/v1/preferences/{username}/{preference_key} PUT /api/user/v1/preferences/{username}/{preference_key} DELETE /api/user/v1/pref... | Implement the Python class `PreferencesDetailView` described below.
Class description:
**Use Cases** Get, create, update, or delete a specific user preference. **Example Requests** GET /api/user/v1/preferences/{username}/{preference_key} PUT /api/user/v1/preferences/{username}/{preference_key} DELETE /api/user/v1/pref... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class PreferencesDetailView:
"""**Use Cases** Get, create, update, or delete a specific user preference. **Example Requests** GET /api/user/v1/preferences/{username}/{preference_key} PUT /api/user/v1/preferences/{username}/{preference_key} DELETE /api/user/v1/preferences/{username}/{preference_key} **R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PreferencesDetailView:
"""**Use Cases** Get, create, update, or delete a specific user preference. **Example Requests** GET /api/user/v1/preferences/{username}/{preference_key} PUT /api/user/v1/preferences/{username}/{preference_key} DELETE /api/user/v1/preferences/{username}/{preference_key} **Response Value... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/user_api/preferences/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
17f28dec79bd7e85c81a30a9f3c740a50eb9355c | [
"if not email:\n raise ValueError('Users must have an email')\nif not username:\n raise ValueError('Users must have an username')\nuser = self.model(username=username, email=email, password=password, last_name=last_name, first_name=first_name)\nuser.is_active = True\nuser.set_password(password)\nuser.save(usi... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email')
if not username:
raise ValueError('Users must have an username')
user = self.model(username=username, email=email, password=password, last_name=last_name, first_name=first_name)
user.is_ac... | AuthUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthUserManager:
def create_user(self, username, email, password, last_name, first_name):
"""ユーザ作成 :param username: ユーザID :param email: メールアドレス :param password: パスワード :param last_name: 苗字 :param first_name: 名前 :return: AuthUserオブジェクト"""
<|body_0|>
def create_superuser(self, ... | stack_v2_sparse_classes_36k_train_008483 | 31,843 | no_license | [
{
"docstring": "ユーザ作成 :param username: ユーザID :param email: メールアドレス :param password: パスワード :param last_name: 苗字 :param first_name: 名前 :return: AuthUserオブジェクト",
"name": "create_user",
"signature": "def create_user(self, username, email, password, last_name, first_name)"
},
{
"docstring": "スーパーユーザ作... | 2 | stack_v2_sparse_classes_30k_train_015841 | Implement the Python class `AuthUserManager` described below.
Class description:
Implement the AuthUserManager class.
Method signatures and docstrings:
- def create_user(self, username, email, password, last_name, first_name): ユーザ作成 :param username: ユーザID :param email: メールアドレス :param password: パスワード :param last_name:... | Implement the Python class `AuthUserManager` described below.
Class description:
Implement the AuthUserManager class.
Method signatures and docstrings:
- def create_user(self, username, email, password, last_name, first_name): ユーザ作成 :param username: ユーザID :param email: メールアドレス :param password: パスワード :param last_name:... | ee51f79e8d5c68b40c2fbd96272bbe2cc657a849 | <|skeleton|>
class AuthUserManager:
def create_user(self, username, email, password, last_name, first_name):
"""ユーザ作成 :param username: ユーザID :param email: メールアドレス :param password: パスワード :param last_name: 苗字 :param first_name: 名前 :return: AuthUserオブジェクト"""
<|body_0|>
def create_superuser(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthUserManager:
def create_user(self, username, email, password, last_name, first_name):
"""ユーザ作成 :param username: ユーザID :param email: メールアドレス :param password: パスワード :param last_name: 苗字 :param first_name: 名前 :return: AuthUserオブジェクト"""
if not email:
raise ValueError('Users must ha... | the_stack_v2_python_sparse | account/models.py | adusu-masaomi/adusu-python-account | train | 0 | |
3eefb62e82fd3443214f95d959ce2141f3de2bdb | [
"self.func = func\nself.task_loader = task_loader\nsuper(Function, self).__init__(**kwargs)",
"if isinstance(self.func, ThisObject):\n self.func = getattr(self.flow_class.instance, self.func.name)\nif isinstance(self.task_loader, ThisObject):\n self.task_loader = getattr(self.flow_class.instance, self.task_... | <|body_start_0|>
self.func = func
self.task_loader = task_loader
super(Function, self).__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
if isinstance(self.func, ThisObject):
self.func = getattr(self.flow_class.instance, self.func.name)
if isinstance(self.task_loade... | Function task to be executed outside of the flow. Example:: class MyFlow(Flow): ... shipment_received_handler = ( flow.Function( this.on_shipment_receive, task_loader=this.get_shipment_handler_task) .Next(this.end) ) .... @method_decorator(flow.flow_func) def on_shipment_receive(self, activation, shipment): activation.... | Function | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Function:
"""Function task to be executed outside of the flow. Example:: class MyFlow(Flow): ... shipment_received_handler = ( flow.Function( this.on_shipment_receive, task_loader=this.get_shipment_handler_task) .Next(this.end) ) .... @method_decorator(flow.flow_func) def on_shipment_receive(self... | stack_v2_sparse_classes_36k_train_008484 | 4,920 | permissive | [
{
"docstring": "Instantiate a Function task. :param func: Callable[activation, **kwargs] :param task_loader: Callable[**kwargs] -> Task `task_loader` could be a `this` reference to the class instance method. You can skip a `task_loader` if the function going to be called with Task instance, ex:: class MyFlow(Fl... | 3 | stack_v2_sparse_classes_30k_train_019872 | Implement the Python class `Function` described below.
Class description:
Function task to be executed outside of the flow. Example:: class MyFlow(Flow): ... shipment_received_handler = ( flow.Function( this.on_shipment_receive, task_loader=this.get_shipment_handler_task) .Next(this.end) ) .... @method_decorator(flow.... | Implement the Python class `Function` described below.
Class description:
Function task to be executed outside of the flow. Example:: class MyFlow(Flow): ... shipment_received_handler = ( flow.Function( this.on_shipment_receive, task_loader=this.get_shipment_handler_task) .Next(this.end) ) .... @method_decorator(flow.... | 0267168bb90e8e9c85aecdd715972b9622b82384 | <|skeleton|>
class Function:
"""Function task to be executed outside of the flow. Example:: class MyFlow(Flow): ... shipment_received_handler = ( flow.Function( this.on_shipment_receive, task_loader=this.get_shipment_handler_task) .Next(this.end) ) .... @method_decorator(flow.flow_func) def on_shipment_receive(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Function:
"""Function task to be executed outside of the flow. Example:: class MyFlow(Flow): ... shipment_received_handler = ( flow.Function( this.on_shipment_receive, task_loader=this.get_shipment_handler_task) .Next(this.end) ) .... @method_decorator(flow.flow_func) def on_shipment_receive(self, activation,... | the_stack_v2_python_sparse | Scripts/ict/viewflow/nodes/func.py | mspgeek/Client_Portal | train | 6 |
cb9979bb0a9f9cff964903c9ed136f817e24b100 | [
"startTime = datetime.datetime.now()\nif trial:\n endTime = datetime.datetime.now()\n return {'start': startTime, 'end': endTime}\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate(TEAM_NAME, TEAM_NAME)\nquestionsIds = list(repo[BALLOT_QUESTIONS_NAME].find({}, {'_id': 1}))\nquestionRes... | <|body_start_0|>
startTime = datetime.datetime.now()
if trial:
endTime = datetime.datetime.now()
return {'start': startTime, 'end': endTime}
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate(TEAM_NAME, TEAM_NAME)
questionsIds ... | ballotQuestionsResults | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ballotQuestionsResults:
def execute(trial=False):
"""Retrieve ballot question results data from electionstats and insert into collection ex) { "Locality" : "Bourne", "Ward" : "-", "Pct" : "7", "Yes" : 375, "No" : 914, "Blanks" : 26, "Total Votes Cast" : 1315, "Question ID" : "7303" }"""
... | stack_v2_sparse_classes_36k_train_008485 | 6,357 | no_license | [
{
"docstring": "Retrieve ballot question results data from electionstats and insert into collection ex) { \"Locality\" : \"Bourne\", \"Ward\" : \"-\", \"Pct\" : \"7\", \"Yes\" : 375, \"No\" : 914, \"Blanks\" : 26, \"Total Votes Cast\" : 1315, \"Question ID\" : \"7303\" }",
"name": "execute",
"signature"... | 3 | null | Implement the Python class `ballotQuestionsResults` described below.
Class description:
Implement the ballotQuestionsResults class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve ballot question results data from electionstats and insert into collection ex) { "Locality" : "Bourne", "Ward" : "-... | Implement the Python class `ballotQuestionsResults` described below.
Class description:
Implement the ballotQuestionsResults class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve ballot question results data from electionstats and insert into collection ex) { "Locality" : "Bourne", "Ward" : "-... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class ballotQuestionsResults:
def execute(trial=False):
"""Retrieve ballot question results data from electionstats and insert into collection ex) { "Locality" : "Bourne", "Ward" : "-", "Pct" : "7", "Yes" : 375, "No" : 914, "Blanks" : 26, "Total Votes Cast" : 1315, "Question ID" : "7303" }"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ballotQuestionsResults:
def execute(trial=False):
"""Retrieve ballot question results data from electionstats and insert into collection ex) { "Locality" : "Bourne", "Ward" : "-", "Pct" : "7", "Yes" : 375, "No" : 914, "Blanks" : 26, "Total Votes Cast" : 1315, "Question ID" : "7303" }"""
startT... | the_stack_v2_python_sparse | ldisalvo_skeesara_vidyaap/ballotQuestionsResults.py | maximega/course-2019-spr-proj | train | 2 | |
587fcc5493081aa26787413f58e6f8e5d8782256 | [
"adm = ProjektAdministration()\nmodule = adm.get_alle_module()\nreturn module",
"id = request.args.get('id')\nadm = ProjektAdministration()\nadm.delete_modul(id)",
"adm = ProjektAdministration()\nmodul = Modul.from_dict(api.payload)\nif modul is not None:\n ' Wir verwenden modul des Proposals für\\n ... | <|body_start_0|>
adm = ProjektAdministration()
module = adm.get_alle_module()
return module
<|end_body_0|>
<|body_start_1|>
id = request.args.get('id')
adm = ProjektAdministration()
adm.delete_modul(id)
<|end_body_1|>
<|body_start_2|>
adm = ProjektAdministration... | ModulOperationen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModulOperationen:
def get(self):
"""Auslesen aller Module-Objekte. Sollten keine Module-Objekte verfügbar sein, so wird eine leere Sequenz zurückgegeben."""
<|body_0|>
def delete(self):
"""Löschen von Module-Objekten."""
<|body_1|>
def put(self):
... | stack_v2_sparse_classes_36k_train_008486 | 29,521 | no_license | [
{
"docstring": "Auslesen aller Module-Objekte. Sollten keine Module-Objekte verfügbar sein, so wird eine leere Sequenz zurückgegeben.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Löschen von Module-Objekten.",
"name": "delete",
"signature": "def delete(self)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_000084 | Implement the Python class `ModulOperationen` described below.
Class description:
Implement the ModulOperationen class.
Method signatures and docstrings:
- def get(self): Auslesen aller Module-Objekte. Sollten keine Module-Objekte verfügbar sein, so wird eine leere Sequenz zurückgegeben.
- def delete(self): Löschen v... | Implement the Python class `ModulOperationen` described below.
Class description:
Implement the ModulOperationen class.
Method signatures and docstrings:
- def get(self): Auslesen aller Module-Objekte. Sollten keine Module-Objekte verfügbar sein, so wird eine leere Sequenz zurückgegeben.
- def delete(self): Löschen v... | 9014f16fed08956bd28216e1373b60139e5caea1 | <|skeleton|>
class ModulOperationen:
def get(self):
"""Auslesen aller Module-Objekte. Sollten keine Module-Objekte verfügbar sein, so wird eine leere Sequenz zurückgegeben."""
<|body_0|>
def delete(self):
"""Löschen von Module-Objekten."""
<|body_1|>
def put(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModulOperationen:
def get(self):
"""Auslesen aller Module-Objekte. Sollten keine Module-Objekte verfügbar sein, so wird eine leere Sequenz zurückgegeben."""
adm = ProjektAdministration()
module = adm.get_alle_module()
return module
def delete(self):
"""Löschen von ... | the_stack_v2_python_sparse | src/main.py | leanderpeter/university_project_selector | train | 3 | |
514627b3b78dbf4a626cea05caaa58a984ea2601 | [
"super().__init__(coordinates)\nself.animationFrames = self.spriteSheet.getStripImages(680, 0, 255, 564)\nself.demoNumber = demoNumber\nself.image = self.animationFrames[0]\nif demoNumber == 2:\n self.image = self.animationFrames[1]\nself.rect = self.image.get_rect()",
"self.frameCount += 1\nif self.demoNumber... | <|body_start_0|>
super().__init__(coordinates)
self.animationFrames = self.spriteSheet.getStripImages(680, 0, 255, 564)
self.demoNumber = demoNumber
self.image = self.animationFrames[0]
if demoNumber == 2:
self.image = self.animationFrames[1]
self.rect = self.... | Create an instance of a the level's boundary wall sprite for the demo. Attributes: demoNumber: An integer determining whether this sprite belongs to the first, second, third, or fourth demo animation. coordinates: A tuple location to blit the sprite on the screen. | DemoWallSprite | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DemoWallSprite:
"""Create an instance of a the level's boundary wall sprite for the demo. Attributes: demoNumber: An integer determining whether this sprite belongs to the first, second, third, or fourth demo animation. coordinates: A tuple location to blit the sprite on the screen."""
def _... | stack_v2_sparse_classes_36k_train_008487 | 38,283 | permissive | [
{
"docstring": "Init DemoWallSprite using the integer demoNumber and the tuple coordinates. Instance variables: animationFrames: A list of 11 Surface objects from the SpriteSheet object. animated: A boolean indicating whether or not the sprite is currently going through an animation. image: The current image to... | 2 | stack_v2_sparse_classes_30k_train_014772 | Implement the Python class `DemoWallSprite` described below.
Class description:
Create an instance of a the level's boundary wall sprite for the demo. Attributes: demoNumber: An integer determining whether this sprite belongs to the first, second, third, or fourth demo animation. coordinates: A tuple location to blit ... | Implement the Python class `DemoWallSprite` described below.
Class description:
Create an instance of a the level's boundary wall sprite for the demo. Attributes: demoNumber: An integer determining whether this sprite belongs to the first, second, third, or fourth demo animation. coordinates: A tuple location to blit ... | 090f3749e102c5331136298356d543c8b4e8a9a5 | <|skeleton|>
class DemoWallSprite:
"""Create an instance of a the level's boundary wall sprite for the demo. Attributes: demoNumber: An integer determining whether this sprite belongs to the first, second, third, or fourth demo animation. coordinates: A tuple location to blit the sprite on the screen."""
def _... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DemoWallSprite:
"""Create an instance of a the level's boundary wall sprite for the demo. Attributes: demoNumber: An integer determining whether this sprite belongs to the first, second, third, or fourth demo animation. coordinates: A tuple location to blit the sprite on the screen."""
def __init__(self,... | the_stack_v2_python_sparse | game/demo/demo_sprites.py | leoua7/clu-clu-game | train | 0 |
273688249d65e0fda0d79cd1e4ae8498e429899e | [
"context = super().get_context_data(**kwargs)\ncontext['url_stap_2'] = reverse('Account:otp-koppelen-stap2')\ncontext['url_controleer'] = reverse('Account:otp-koppelen-stap3')\ncontext['site_name'] = settings.OTP_ISSUER_NAME\ncontext['form'] = OTPControleForm()\ncontext['now'] = timezone.now()\nmenu_dynamics(self.r... | <|body_start_0|>
context = super().get_context_data(**kwargs)
context['url_stap_2'] = reverse('Account:otp-koppelen-stap2')
context['url_controleer'] = reverse('Account:otp-koppelen-stap3')
context['site_name'] = settings.OTP_ISSUER_NAME
context['form'] = OTPControleForm()
... | OTPKoppelenStap3View | [
"BSD-3-Clause-Clear"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OTPKoppelenStap3View:
def get_context_data(self, **kwargs):
"""called by the template system to get the context data for the template"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""deze functie wordt aangeroepen als een POST request ontvangen is. dit is g... | stack_v2_sparse_classes_36k_train_008488 | 5,630 | permissive | [
{
"docstring": "called by the template system to get the context data for the template",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "deze functie wordt aangeroepen als een POST request ontvangen is. dit is gekoppeld aan het drukken op de Con... | 2 | stack_v2_sparse_classes_30k_train_014946 | Implement the Python class `OTPKoppelenStap3View` described below.
Class description:
Implement the OTPKoppelenStap3View class.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): called by the template system to get the context data for the template
- def post(self, request, *args, **kwargs): d... | Implement the Python class `OTPKoppelenStap3View` described below.
Class description:
Implement the OTPKoppelenStap3View class.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): called by the template system to get the context data for the template
- def post(self, request, *args, **kwargs): d... | 5ed38165a231f0caa56f67e8faf2dd074916e500 | <|skeleton|>
class OTPKoppelenStap3View:
def get_context_data(self, **kwargs):
"""called by the template system to get the context data for the template"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""deze functie wordt aangeroepen als een POST request ontvangen is. dit is g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OTPKoppelenStap3View:
def get_context_data(self, **kwargs):
"""called by the template system to get the context data for the template"""
context = super().get_context_data(**kwargs)
context['url_stap_2'] = reverse('Account:otp-koppelen-stap2')
context['url_controleer'] = revers... | the_stack_v2_python_sparse | Account/view_otp_koppelen.py | RamonvdW/nhb-apps | train | 2 | |
1a18caa46e137f754141f36cbc07b101c2bdce82 | [
"if options['expiry_minutes']:\n self.expire_stack_ownership(options['expiry_minutes'], 'minutes')\nif options['expiry_days']:\n self.expire_stack_ownership(options['expiry_days'], 'days')\nif options['expiry_hours']:\n self.expire_stack_ownership(options['expiry_hours'], 'hours')",
"try:\n ownership_... | <|body_start_0|>
if options['expiry_minutes']:
self.expire_stack_ownership(options['expiry_minutes'], 'minutes')
if options['expiry_days']:
self.expire_stack_ownership(options['expiry_days'], 'days')
if options['expiry_hours']:
self.expire_stack_ownership(opti... | Extend Base class and define options with values. | Command | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Extend Base class and define options with values."""
def handle(self, *args, **options):
"""Handle options and supplied arguments."""
<|body_0|>
def expire_stack_ownership(self, expirytime, timetype):
"""Expire stack ownership in the specified time in... | stack_v2_sparse_classes_36k_train_008489 | 3,050 | permissive | [
{
"docstring": "Handle options and supplied arguments.",
"name": "handle",
"signature": "def handle(self, *args, **options)"
},
{
"docstring": "Expire stack ownership in the specified time in days, hours or minutes.",
"name": "expire_stack_ownership",
"signature": "def expire_stack_owner... | 2 | stack_v2_sparse_classes_30k_train_020642 | Implement the Python class `Command` described below.
Class description:
Extend Base class and define options with values.
Method signatures and docstrings:
- def handle(self, *args, **options): Handle options and supplied arguments.
- def expire_stack_ownership(self, expirytime, timetype): Expire stack ownership in ... | Implement the Python class `Command` described below.
Class description:
Extend Base class and define options with values.
Method signatures and docstrings:
- def handle(self, *args, **options): Handle options and supplied arguments.
- def expire_stack_ownership(self, expirytime, timetype): Expire stack ownership in ... | d205924dc3938ef49f156148ac1dda20220f7575 | <|skeleton|>
class Command:
"""Extend Base class and define options with values."""
def handle(self, *args, **options):
"""Handle options and supplied arguments."""
<|body_0|>
def expire_stack_ownership(self, expirytime, timetype):
"""Expire stack ownership in the specified time in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
"""Extend Base class and define options with values."""
def handle(self, *args, **options):
"""Handle options and supplied arguments."""
if options['expiry_minutes']:
self.expire_stack_ownership(options['expiry_minutes'], 'minutes')
if options['expiry_days']:
... | the_stack_v2_python_sparse | appv1/management/commands/expireownership.py | CBitLabs/atlas | train | 0 |
8776a9446a8a462749edef1bf6a99285c3096a2b | [
"for label, item in cls.labels.items():\n if item == cls:\n return label\nraise NotImplementedError(f'Class {cls} is not implemented.')",
"def decorator(obj):\n if label in cls.labels:\n print(f\"registering duplicate label '{label}' for {cls.__name__}.\")\n cls.labels[label] = obj\n ret... | <|body_start_0|>
for label, item in cls.labels.items():
if item == cls:
return label
raise NotImplementedError(f'Class {cls} is not implemented.')
<|end_body_0|>
<|body_start_1|>
def decorator(obj):
if label in cls.labels:
print(f"register... | CustomABC | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomABC:
def get_label(cls):
"""Returns the string label of a class object."""
<|body_0|>
def register(cls, label):
"""Decorator to register new classes."""
<|body_1|>
def __class_getitem__(cls, item):
"""Returns the child."""
<|body_2|... | stack_v2_sparse_classes_36k_train_008490 | 912 | permissive | [
{
"docstring": "Returns the string label of a class object.",
"name": "get_label",
"signature": "def get_label(cls)"
},
{
"docstring": "Decorator to register new classes.",
"name": "register",
"signature": "def register(cls, label)"
},
{
"docstring": "Returns the child.",
"na... | 3 | stack_v2_sparse_classes_30k_train_002108 | Implement the Python class `CustomABC` described below.
Class description:
Implement the CustomABC class.
Method signatures and docstrings:
- def get_label(cls): Returns the string label of a class object.
- def register(cls, label): Decorator to register new classes.
- def __class_getitem__(cls, item): Returns the c... | Implement the Python class `CustomABC` described below.
Class description:
Implement the CustomABC class.
Method signatures and docstrings:
- def get_label(cls): Returns the string label of a class object.
- def register(cls, label): Decorator to register new classes.
- def __class_getitem__(cls, item): Returns the c... | 29f37740bacc9a77b94daf6fbae769c003ee9349 | <|skeleton|>
class CustomABC:
def get_label(cls):
"""Returns the string label of a class object."""
<|body_0|>
def register(cls, label):
"""Decorator to register new classes."""
<|body_1|>
def __class_getitem__(cls, item):
"""Returns the child."""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomABC:
def get_label(cls):
"""Returns the string label of a class object."""
for label, item in cls.labels.items():
if item == cls:
return label
raise NotImplementedError(f'Class {cls} is not implemented.')
def register(cls, label):
"""Decor... | the_stack_v2_python_sparse | profit/util/base_class.py | redmod-team/profit | train | 19 | |
8579086ae92cad02417ed5a410c04fac0dfa62b4 | [
"MuscleTestInfoView.validate_muscle_test_info_request(id_patient, id_treatment_cycle, id_treatment, id_muscle_test)\nmuscle_test_info = MuscleTestService.muscle_test_info(id_muscle_test)\nreturn JsonResponse(muscle_test_info)",
"Utils.validate_uuid(id_patient)\nUtils.validate_uuid(id_treatment_cycle)\nUtils.valid... | <|body_start_0|>
MuscleTestInfoView.validate_muscle_test_info_request(id_patient, id_treatment_cycle, id_treatment, id_muscle_test)
muscle_test_info = MuscleTestService.muscle_test_info(id_muscle_test)
return JsonResponse(muscle_test_info)
<|end_body_0|>
<|body_start_1|>
Utils.validate_... | All endpoints related to muscle test info actions | MuscleTestInfoView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MuscleTestInfoView:
"""All endpoints related to muscle test info actions"""
def get(request, id_patient, id_treatment_cycle, id_treatment, id_muscle_test):
"""Action when calling the endpoint with GET"""
<|body_0|>
def validate_muscle_test_info_request(id_patient, id_tre... | stack_v2_sparse_classes_36k_train_008491 | 3,700 | no_license | [
{
"docstring": "Action when calling the endpoint with GET",
"name": "get",
"signature": "def get(request, id_patient, id_treatment_cycle, id_treatment, id_muscle_test)"
},
{
"docstring": "Validates the treatment information received in the request body :param id_patient: Id of the patient receiv... | 2 | null | Implement the Python class `MuscleTestInfoView` described below.
Class description:
All endpoints related to muscle test info actions
Method signatures and docstrings:
- def get(request, id_patient, id_treatment_cycle, id_treatment, id_muscle_test): Action when calling the endpoint with GET
- def validate_muscle_test... | Implement the Python class `MuscleTestInfoView` described below.
Class description:
All endpoints related to muscle test info actions
Method signatures and docstrings:
- def get(request, id_patient, id_treatment_cycle, id_treatment, id_muscle_test): Action when calling the endpoint with GET
- def validate_muscle_test... | 941e8b2870f8724db3d5103dda5157fd597cfcc7 | <|skeleton|>
class MuscleTestInfoView:
"""All endpoints related to muscle test info actions"""
def get(request, id_patient, id_treatment_cycle, id_treatment, id_muscle_test):
"""Action when calling the endpoint with GET"""
<|body_0|>
def validate_muscle_test_info_request(id_patient, id_tre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MuscleTestInfoView:
"""All endpoints related to muscle test info actions"""
def get(request, id_patient, id_treatment_cycle, id_treatment, id_muscle_test):
"""Action when calling the endpoint with GET"""
MuscleTestInfoView.validate_muscle_test_info_request(id_patient, id_treatment_cycle, ... | the_stack_v2_python_sparse | backend/martin_helder/views/muscle_test_info_view.py | JoaoAlvaroFerreira/FEUP-LGP | train | 1 |
5cdad122a09bbee668c5cdb59b18113607caf063 | [
"exp = ' A -> B\\n A.radius < B.radius\\n '\ndm = dotmotif.Motif(exp)\nself.assertEqual(len(dm.list_dynamic_node_constraints()), 1)",
"exp = ' macro(A, B) {\\n A.radius > B.radius\\n }\\n macro(A, B)\\n A -> B\\n '\ndm = dotmotif.Motif(exp)\nself.... | <|body_start_0|>
exp = ' A -> B\n A.radius < B.radius\n '
dm = dotmotif.Motif(exp)
self.assertEqual(len(dm.list_dynamic_node_constraints()), 1)
<|end_body_0|>
<|body_start_1|>
exp = ' macro(A, B) {\n A.radius > B.radius\n }\n macro(A,... | TestDynamicNodeConstraints | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDynamicNodeConstraints:
def test_dynamic_constraints(self):
"""Test that comparisons may be made between variables, e.g.: A.type != B.type"""
<|body_0|>
def test_dynamic_constraints_in_macro(self):
"""Test that comparisons may be made between variables in a macro... | stack_v2_sparse_classes_36k_train_008492 | 11,613 | permissive | [
{
"docstring": "Test that comparisons may be made between variables, e.g.: A.type != B.type",
"name": "test_dynamic_constraints",
"signature": "def test_dynamic_constraints(self)"
},
{
"docstring": "Test that comparisons may be made between variables in a macro, e.g.: A.type != B.type",
"nam... | 2 | stack_v2_sparse_classes_30k_train_015447 | Implement the Python class `TestDynamicNodeConstraints` described below.
Class description:
Implement the TestDynamicNodeConstraints class.
Method signatures and docstrings:
- def test_dynamic_constraints(self): Test that comparisons may be made between variables, e.g.: A.type != B.type
- def test_dynamic_constraints... | Implement the Python class `TestDynamicNodeConstraints` described below.
Class description:
Implement the TestDynamicNodeConstraints class.
Method signatures and docstrings:
- def test_dynamic_constraints(self): Test that comparisons may be made between variables, e.g.: A.type != B.type
- def test_dynamic_constraints... | db093ddad7308756e9cf7ee01199f0dca1369872 | <|skeleton|>
class TestDynamicNodeConstraints:
def test_dynamic_constraints(self):
"""Test that comparisons may be made between variables, e.g.: A.type != B.type"""
<|body_0|>
def test_dynamic_constraints_in_macro(self):
"""Test that comparisons may be made between variables in a macro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDynamicNodeConstraints:
def test_dynamic_constraints(self):
"""Test that comparisons may be made between variables, e.g.: A.type != B.type"""
exp = ' A -> B\n A.radius < B.radius\n '
dm = dotmotif.Motif(exp)
self.assertEqual(len(dm.list_dynamic_node_con... | the_stack_v2_python_sparse | dotmotif/parsers/v2/test_v2_parser.py | JuttaPig/dotmotif | train | 0 | |
8d429ae268f5979724de54ebe0075e38f857c830 | [
"nvars = 3\nsuper().__init__(init=(nvars, None, np.dtype('float64')))\nself._makeAttributeAndRegister('nvars', localVars=locals(), readOnly=True)\nself._makeAttributeAndRegister('sigma', 'rho', 'beta', 'newton_tol', 'newton_maxiter', localVars=locals(), readOnly=False)\nself.work_counters['newton'] = WorkCounter()\... | <|body_start_0|>
nvars = 3
super().__init__(init=(nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister('nvars', localVars=locals(), readOnly=True)
self._makeAttributeAndRegister('sigma', 'rho', 'beta', 'newton_tol', 'newton_maxiter', localVars=locals(), readOnly=False)
... | Simple script to run a Lorenz attractor problem. The Lorenz attractor is a system of three ordinary differential equations (ODEs) that exhibits some chaotic behaviour. It is well known for the "Butterfly Effect", because the solution looks like a butterfly (solve to :math:`T_{end} = 100` or so to see this with these in... | LorenzAttractor | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LorenzAttractor:
"""Simple script to run a Lorenz attractor problem. The Lorenz attractor is a system of three ordinary differential equations (ODEs) that exhibits some chaotic behaviour. It is well known for the "Butterfly Effect", because the solution looks like a butterfly (solve to :math:`T_{... | stack_v2_sparse_classes_36k_train_008493 | 7,847 | permissive | [
{
"docstring": "Initialization routine",
"name": "__init__",
"signature": "def __init__(self, sigma=10.0, rho=28.0, beta=8.0 / 3.0, newton_tol=1e-09, newton_maxiter=99)"
},
{
"docstring": "Routine to evaluate the right-hand side of the problem. Parameters ---------- u : dtype_u Current values of... | 4 | stack_v2_sparse_classes_30k_train_015582 | Implement the Python class `LorenzAttractor` described below.
Class description:
Simple script to run a Lorenz attractor problem. The Lorenz attractor is a system of three ordinary differential equations (ODEs) that exhibits some chaotic behaviour. It is well known for the "Butterfly Effect", because the solution look... | Implement the Python class `LorenzAttractor` described below.
Class description:
Simple script to run a Lorenz attractor problem. The Lorenz attractor is a system of three ordinary differential equations (ODEs) that exhibits some chaotic behaviour. It is well known for the "Butterfly Effect", because the solution look... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class LorenzAttractor:
"""Simple script to run a Lorenz attractor problem. The Lorenz attractor is a system of three ordinary differential equations (ODEs) that exhibits some chaotic behaviour. It is well known for the "Butterfly Effect", because the solution looks like a butterfly (solve to :math:`T_{... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LorenzAttractor:
"""Simple script to run a Lorenz attractor problem. The Lorenz attractor is a system of three ordinary differential equations (ODEs) that exhibits some chaotic behaviour. It is well known for the "Butterfly Effect", because the solution looks like a butterfly (solve to :math:`T_{end} = 100` o... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/Lorenz.py | Parallel-in-Time/pySDC | train | 30 |
9ee264bb2e7ebc00a76231cf671a7d1ac5df8c3f | [
"label = \"Heroes' Day\"\nif year == 2017:\n day = date(year, 2, 27)\nelse:\n day = date(year, 3, 1)\nreturn (day, label)",
"label = 'Founding of Asunción'\nif year == 2017:\n day = date(year, 8, 14)\nelse:\n day = date(year, 8, 15)\nreturn (day, label)",
"label = 'Boqueron Battle Victory Day'\nif y... | <|body_start_0|>
label = "Heroes' Day"
if year == 2017:
day = date(year, 2, 27)
else:
day = date(year, 3, 1)
return (day, label)
<|end_body_0|>
<|body_start_1|>
label = 'Founding of Asunción'
if year == 2017:
day = date(year, 8, 14)
... | Paraguay | Paraguay | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Paraguay:
"""Paraguay"""
def get_heroes_day(self, year):
"""Heroes Day is a fixed holidays. In 2017, it has been moved to February 27th ; otherwise, it happens on March 1st. ref: https://en.wikipedia.org/wiki/Public_holidays_in_Paraguay"""
<|body_0|>
def get_founding_of_... | stack_v2_sparse_classes_36k_train_008494 | 2,194 | permissive | [
{
"docstring": "Heroes Day is a fixed holidays. In 2017, it has been moved to February 27th ; otherwise, it happens on March 1st. ref: https://en.wikipedia.org/wiki/Public_holidays_in_Paraguay",
"name": "get_heroes_day",
"signature": "def get_heroes_day(self, year)"
},
{
"docstring": "Return the... | 4 | null | Implement the Python class `Paraguay` described below.
Class description:
Paraguay
Method signatures and docstrings:
- def get_heroes_day(self, year): Heroes Day is a fixed holidays. In 2017, it has been moved to February 27th ; otherwise, it happens on March 1st. ref: https://en.wikipedia.org/wiki/Public_holidays_in... | Implement the Python class `Paraguay` described below.
Class description:
Paraguay
Method signatures and docstrings:
- def get_heroes_day(self, year): Heroes Day is a fixed holidays. In 2017, it has been moved to February 27th ; otherwise, it happens on March 1st. ref: https://en.wikipedia.org/wiki/Public_holidays_in... | 0a3b05706fcd0b8a2c4c761694b91b5fc12d1383 | <|skeleton|>
class Paraguay:
"""Paraguay"""
def get_heroes_day(self, year):
"""Heroes Day is a fixed holidays. In 2017, it has been moved to February 27th ; otherwise, it happens on March 1st. ref: https://en.wikipedia.org/wiki/Public_holidays_in_Paraguay"""
<|body_0|>
def get_founding_of_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Paraguay:
"""Paraguay"""
def get_heroes_day(self, year):
"""Heroes Day is a fixed holidays. In 2017, it has been moved to February 27th ; otherwise, it happens on March 1st. ref: https://en.wikipedia.org/wiki/Public_holidays_in_Paraguay"""
label = "Heroes' Day"
if year == 2017:
... | the_stack_v2_python_sparse | calendra/america/paraguay.py | jaraco/calendra | train | 5 |
5c4ff38e214af7583e8f31e460d1d19bfa9fd382 | [
"if len(rating) < 3:\n return 0\nres = 0\nfor i in range(len(rating) - 2):\n for j in range(i + 1, len(rating) - 1):\n for k in range(j + 1, len(rating)):\n if rating[i] < rating[j] and rating[j] < rating[k] or (rating[i] > rating[j] and rating[j] > rating[k]):\n res += 1\nret... | <|body_start_0|>
if len(rating) < 3:
return 0
res = 0
for i in range(len(rating) - 2):
for j in range(i + 1, len(rating) - 1):
for k in range(j + 1, len(rating)):
if rating[i] < rating[j] and rating[j] < rating[k] or (rating[i] > rating... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numTeams(self, rating):
""":type rating: List[int] :rtype: int"""
<|body_0|>
def numTeams(self, rating):
""":type rating: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(rating) < 3:
return 0
... | stack_v2_sparse_classes_36k_train_008495 | 1,057 | no_license | [
{
"docstring": ":type rating: List[int] :rtype: int",
"name": "numTeams",
"signature": "def numTeams(self, rating)"
},
{
"docstring": ":type rating: List[int] :rtype: int",
"name": "numTeams",
"signature": "def numTeams(self, rating)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019120 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numTeams(self, rating): :type rating: List[int] :rtype: int
- def numTeams(self, rating): :type rating: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numTeams(self, rating): :type rating: List[int] :rtype: int
- def numTeams(self, rating): :type rating: List[int] :rtype: int
<|skeleton|>
class Solution:
def numTeams(... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def numTeams(self, rating):
""":type rating: List[int] :rtype: int"""
<|body_0|>
def numTeams(self, rating):
""":type rating: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numTeams(self, rating):
""":type rating: List[int] :rtype: int"""
if len(rating) < 3:
return 0
res = 0
for i in range(len(rating) - 2):
for j in range(i + 1, len(rating) - 1):
for k in range(j + 1, len(rating)):
... | the_stack_v2_python_sparse | 1395_Count_Number_of_Teams.py | bingli8802/leetcode | train | 0 | |
bf6f28549df628e48491abe0e634fc59acc3dda4 | [
"self.__cell_matrix = []\ncells = []\nfor col in self.columns:\n cells.append(self._MakeCell(col.name, alignment=col.alignment))\nself.__cell_matrix.append(tuple(cells))\nfor row in self.rows:\n cells = []\n for cell, col in zip(row, self.columns):\n cell = self._MakeCell(cell, alignment=col.alignme... | <|body_start_0|>
self.__cell_matrix = []
cells = []
for col in self.columns:
cells.append(self._MakeCell(col.name, alignment=col.alignment))
self.__cell_matrix.append(tuple(cells))
for row in self.rows:
cells = []
for cell, col in zip(row, self... | A class that can be used for displaying tabular data. This class can produce tables like the following: +------+-------------+--------------+------------+------+ | Rank | Country | Capital City | Population | Year | +------+-------------+--------------+------------+------+ | 1 | Japan | Tokyo | 13,189,000 | 2011 | +---... | Table | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Table:
"""A class that can be used for displaying tabular data. This class can produce tables like the following: +------+-------------+--------------+------------+------+ | Rank | Country | Capital City | Population | Year | +------+-------------+--------------+------------+------+ | 1 | Japan |... | stack_v2_sparse_classes_36k_train_008496 | 32,076 | permissive | [
{
"docstring": "Creates a matrix containing the column headers and rows as _Cells. The result is placed in the property __cell_matrix.",
"name": "_MakeCellMatrix",
"signature": "def _MakeCellMatrix(self)"
},
{
"docstring": "Writes the table to out. Assumes SetColumns() has been called. Args: out... | 2 | null | Implement the Python class `Table` described below.
Class description:
A class that can be used for displaying tabular data. This class can produce tables like the following: +------+-------------+--------------+------------+------+ | Rank | Country | Capital City | Population | Year | +------+-------------+----------... | Implement the Python class `Table` described below.
Class description:
A class that can be used for displaying tabular data. This class can produce tables like the following: +------+-------------+--------------+------------+------+ | Rank | Country | Capital City | Population | Year | +------+-------------+----------... | d379afa2db3582d5c3be652165f0e9e2e0c154c6 | <|skeleton|>
class Table:
"""A class that can be used for displaying tabular data. This class can produce tables like the following: +------+-------------+--------------+------------+------+ | Rank | Country | Capital City | Population | Year | +------+-------------+--------------+------------+------+ | 1 | Japan |... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Table:
"""A class that can be used for displaying tabular data. This class can produce tables like the following: +------+-------------+--------------+------------+------+ | Rank | Country | Capital City | Population | Year | +------+-------------+--------------+------------+------+ | 1 | Japan | Tokyo | 13,1... | the_stack_v2_python_sparse | y/google-cloud-sdk/.install/.backup/platform/gcutil/lib/google_compute_engine/gcutil_lib/table/table.py | ychen820/microblog | train | 0 |
b3e39a1bb1553be909a04195dc2df49472001850 | [
"from components.slots.slots import CategoricalSlot\nif not reuse:\n slot = CategoricalSlot(name=name, questioner=questioner, silent_value=silent_value, categories_synsets=categories_domain_specification).save()\nelse:\n slot, created = CategoricalSlot.get_or_create(name=name, questioner=questioner, silent_va... | <|body_start_0|>
from components.slots.slots import CategoricalSlot
if not reuse:
slot = CategoricalSlot(name=name, questioner=questioner, silent_value=silent_value, categories_synsets=categories_domain_specification).save()
else:
slot, created = CategoricalSlot.get_or_cr... | Bunch of factory methods to create a Slot instances retrievable by Interactions from UserDialog TODO: should factory make registration of object? | SlotsFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlotsFactory:
"""Bunch of factory methods to create a Slot instances retrievable by Interactions from UserDialog TODO: should factory make registration of object?"""
def produce_categorical_slot(cls, name, questioner, categories_domain_specification, requestioning_strategy='ResumeOnIdle', re... | stack_v2_sparse_classes_36k_train_008497 | 6,892 | no_license | [
{
"docstring": "factory method for production of unregistered slots with categorical values Args: name: name of slot questioner: categories_domain_specification: TODO specify format requestioning_strategy:",
"name": "produce_categorical_slot",
"signature": "def produce_categorical_slot(cls, name, questi... | 5 | stack_v2_sparse_classes_30k_test_000521 | Implement the Python class `SlotsFactory` described below.
Class description:
Bunch of factory methods to create a Slot instances retrievable by Interactions from UserDialog TODO: should factory make registration of object?
Method signatures and docstrings:
- def produce_categorical_slot(cls, name, questioner, catego... | Implement the Python class `SlotsFactory` described below.
Class description:
Bunch of factory methods to create a Slot instances retrievable by Interactions from UserDialog TODO: should factory make registration of object?
Method signatures and docstrings:
- def produce_categorical_slot(cls, name, questioner, catego... | 7a0bc78ca03ee8ca1202e8ad2a6860444f0ce75d | <|skeleton|>
class SlotsFactory:
"""Bunch of factory methods to create a Slot instances retrievable by Interactions from UserDialog TODO: should factory make registration of object?"""
def produce_categorical_slot(cls, name, questioner, categories_domain_specification, requestioning_strategy='ResumeOnIdle', re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SlotsFactory:
"""Bunch of factory methods to create a Slot instances retrievable by Interactions from UserDialog TODO: should factory make registration of object?"""
def produce_categorical_slot(cls, name, questioner, categories_domain_specification, requestioning_strategy='ResumeOnIdle', reuse=True, sil... | the_stack_v2_python_sparse | ruler_bot/components/slots/slots_factory.py | acriptis/dj_bot | train | 3 |
bc3c52942c457e839d532815cb63621a4d84f30b | [
"if not root:\n return '#'\nstack = [root]\nres = []\nwhile stack:\n node = stack.pop()\n if node:\n res.append(str(node.val))\n stack.append(node.right)\n stack.append(node.left)\n else:\n res.append('#')\nreturn ' '.join(res)",
"def rdeserialize(l):\n \"\"\" a recursiv... | <|body_start_0|>
if not root:
return '#'
stack = [root]
res = []
while stack:
node = stack.pop()
if node:
res.append(str(node.val))
stack.append(node.right)
stack.append(node.left)
else:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_008498 | 2,194 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_018780 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | feab001b9291f6e57c44eeb0b625fdaa145d19b4 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '#'
stack = [root]
res = []
while stack:
node = stack.pop()
if node:
res.append(str(node.v... | the_stack_v2_python_sparse | 297_Serialize_and_Deserialize_Binary_Tree.py | luchang59/leetcode | train | 0 | |
7b3943700dd932d3aeb67973c6b8cc31641f5ffb | [
"struct = mojom.Struct('test')\nindex = 1\nfor kind in kinds:\n struct.AddField('%d' % index, kind)\n index += 1\nps = pack.PackedStruct(struct)\nnum_fields = len(ps.packed_fields)\nself.assertEquals(len(kinds), num_fields)\nfor i in xrange(num_fields):\n self.assertEquals('%d' % fields[i], ps.packed_field... | <|body_start_0|>
struct = mojom.Struct('test')
index = 1
for kind in kinds:
struct.AddField('%d' % index, kind)
index += 1
ps = pack.PackedStruct(struct)
num_fields = len(ps.packed_fields)
self.assertEquals(len(kinds), num_fields)
for i in ... | PackTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackTest:
def _CheckPackSequence(self, kinds, fields, offsets):
"""Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fields that are to be created. fields: The expected order of the resulting fields, with the integer "... | stack_v2_sparse_classes_36k_train_008499 | 4,828 | permissive | [
{
"docstring": "Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fields that are to be created. fields: The expected order of the resulting fields, with the integer \"1\" first. offsets: The expected order of offsets, with the integer \"0\" ... | 6 | stack_v2_sparse_classes_30k_val_001185 | Implement the Python class `PackTest` described below.
Class description:
Implement the PackTest class.
Method signatures and docstrings:
- def _CheckPackSequence(self, kinds, fields, offsets): Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fiel... | Implement the Python class `PackTest` described below.
Class description:
Implement the PackTest class.
Method signatures and docstrings:
- def _CheckPackSequence(self, kinds, fields, offsets): Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fiel... | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | <|skeleton|>
class PackTest:
def _CheckPackSequence(self, kinds, fields, offsets):
"""Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fields that are to be created. fields: The expected order of the resulting fields, with the integer "... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PackTest:
def _CheckPackSequence(self, kinds, fields, offsets):
"""Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fields that are to be created. fields: The expected order of the resulting fields, with the integer "1" first. offs... | the_stack_v2_python_sparse | mojo/public/tools/bindings/pylib/mojom_tests/generate/pack_unittest.py | Samsung/Castanets | train | 58 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.