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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2af56df1745ea9445618617f301e80ec16deaf87 | [
"user = request.user\nif not hasattr(user, 'user_profile'):\n return RESPONSE_400_OBJECT_NOT_FOUND\nprofile = user.user_profile\nreturn JsonResponse(profile.to_dict(), status=200)",
"user = request.user\nif not hasattr(user, 'user_profile'):\n return RESPONSE_400_OBJECT_NOT_FOUND\nprofile = user.user_profil... | <|body_start_0|>
user = request.user
if not hasattr(user, 'user_profile'):
return RESPONSE_400_OBJECT_NOT_FOUND
profile = user.user_profile
return JsonResponse(profile.to_dict(), status=200)
<|end_body_0|>
<|body_start_1|>
user = request.user
if not hasattr(u... | Class that handles HTTP requests for user_profile model. | UserProfileView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileView:
"""Class that handles HTTP requests for user_profile model."""
def get(self, request):
"""Handle the request to retrieve a user_profile object."""
<|body_0|>
def put(self, request):
"""Handle the request to update an existing user_profile object ... | stack_v2_sparse_classes_36k_train_032300 | 3,252 | no_license | [
{
"docstring": "Handle the request to retrieve a user_profile object.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Handle the request to update an existing user_profile object with appropriate id.",
"name": "put",
"signature": "def put(self, request)"
}
] | 2 | null | Implement the Python class `UserProfileView` described below.
Class description:
Class that handles HTTP requests for user_profile model.
Method signatures and docstrings:
- def get(self, request): Handle the request to retrieve a user_profile object.
- def put(self, request): Handle the request to update an existing... | Implement the Python class `UserProfileView` described below.
Class description:
Class that handles HTTP requests for user_profile model.
Method signatures and docstrings:
- def get(self, request): Handle the request to retrieve a user_profile object.
- def put(self, request): Handle the request to update an existing... | c5f533bd049f6939037b14045e2aa2550aaac36a | <|skeleton|>
class UserProfileView:
"""Class that handles HTTP requests for user_profile model."""
def get(self, request):
"""Handle the request to retrieve a user_profile object."""
<|body_0|>
def put(self, request):
"""Handle the request to update an existing user_profile object ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileView:
"""Class that handles HTTP requests for user_profile model."""
def get(self, request):
"""Handle the request to retrieve a user_profile object."""
user = request.user
if not hasattr(user, 'user_profile'):
return RESPONSE_400_OBJECT_NOT_FOUND
pr... | the_stack_v2_python_sparse | way_to_home/user_profile/views.py | Lv-365python/wayToHome | train | 1 |
45a2b73b5b66b0059ee6dcbfeac393737c946a39 | [
"super().__init__(pos_enc_class)\nself.out = nn.Sequential(Linear(idim, odim), LayerNorm(odim, epsilon=1e-12), nn.Dropout(dropout_rate), nn.ReLU())\nself.right_context = 0\nself.subsampling_rate = 1",
"x = self.out(x)\nx, pos_emb = self.pos_enc(x, offset)\nreturn (x, pos_emb, x_mask)"
] | <|body_start_0|>
super().__init__(pos_enc_class)
self.out = nn.Sequential(Linear(idim, odim), LayerNorm(odim, epsilon=1e-12), nn.Dropout(dropout_rate), nn.ReLU())
self.right_context = 0
self.subsampling_rate = 1
<|end_body_0|>
<|body_start_1|>
x = self.out(x)
x, pos_emb ... | Linear transform the input without subsampling. | LinearNoSubsampling | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearNoSubsampling:
"""Linear transform the input without subsampling."""
def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class: nn.Layer=PositionalEncoding):
"""Construct an linear object. Args: idim (int): Input dimension. odim (int): Output dimension. dropou... | stack_v2_sparse_classes_36k_train_032301 | 11,942 | permissive | [
{
"docstring": "Construct an linear object. Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc_class (PositionalEncoding): position encoding class",
"name": "__init__",
"signature": "def __init__(self, idim: int, odim: int, dropout_rate: float, p... | 2 | stack_v2_sparse_classes_30k_train_006208 | Implement the Python class `LinearNoSubsampling` described below.
Class description:
Linear transform the input without subsampling.
Method signatures and docstrings:
- def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class: nn.Layer=PositionalEncoding): Construct an linear object. Args: idim (in... | Implement the Python class `LinearNoSubsampling` described below.
Class description:
Linear transform the input without subsampling.
Method signatures and docstrings:
- def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class: nn.Layer=PositionalEncoding): Construct an linear object. Args: idim (in... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class LinearNoSubsampling:
"""Linear transform the input without subsampling."""
def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class: nn.Layer=PositionalEncoding):
"""Construct an linear object. Args: idim (int): Input dimension. odim (int): Output dimension. dropou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearNoSubsampling:
"""Linear transform the input without subsampling."""
def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class: nn.Layer=PositionalEncoding):
"""Construct an linear object. Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float... | the_stack_v2_python_sparse | paddlespeech/s2t/modules/subsampling.py | anniyanvr/DeepSpeech-1 | train | 0 |
16f9f1e8880f2224d95e06113601ceb529e55b72 | [
"xyz = _handle_input(x, y, z, dtype, device, 'Translate')\nsuper().__init__(device=xyz.device, dtype=dtype)\nN = xyz.shape[0]\nmat = torch.eye(4, dtype=dtype, device=self.device)\nmat = mat.view(1, 4, 4).repeat(N, 1, 1)\nmat[:, 3, :3] = xyz\nself._matrix = mat",
"inv_mask = self._matrix.new_ones([1, 4, 4])\ninv_m... | <|body_start_0|>
xyz = _handle_input(x, y, z, dtype, device, 'Translate')
super().__init__(device=xyz.device, dtype=dtype)
N = xyz.shape[0]
mat = torch.eye(4, dtype=dtype, device=self.device)
mat = mat.view(1, 4, 4).repeat(N, 1, 1)
mat[:, 3, :3] = xyz
self._matrix... | Translate | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Translate:
def __init__(self, x, y=None, z=None, dtype: torch.dtype=torch.float32, device: Optional[Device]=None) -> None:
"""Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, device='cpu') xyz should be a tensor of shape (N, 3) Option I... | stack_v2_sparse_classes_36k_train_032302 | 30,693 | permissive | [
{
"docstring": "Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, device='cpu') xyz should be a tensor of shape (N, 3) Option II: Translate(x, y, z, dtype=torch.float32, device='cpu') Here x, y, and z will be broadcast against each other and concatenated to for... | 2 | stack_v2_sparse_classes_30k_train_012626 | Implement the Python class `Translate` described below.
Class description:
Implement the Translate class.
Method signatures and docstrings:
- def __init__(self, x, y=None, z=None, dtype: torch.dtype=torch.float32, device: Optional[Device]=None) -> None: Create a new Transform3d representing 3D translations. Option I:... | Implement the Python class `Translate` described below.
Class description:
Implement the Translate class.
Method signatures and docstrings:
- def __init__(self, x, y=None, z=None, dtype: torch.dtype=torch.float32, device: Optional[Device]=None) -> None: Create a new Transform3d representing 3D translations. Option I:... | a3d99cab6bf5eb69be8d5eb48895da6edd859565 | <|skeleton|>
class Translate:
def __init__(self, x, y=None, z=None, dtype: torch.dtype=torch.float32, device: Optional[Device]=None) -> None:
"""Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, device='cpu') xyz should be a tensor of shape (N, 3) Option I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Translate:
def __init__(self, x, y=None, z=None, dtype: torch.dtype=torch.float32, device: Optional[Device]=None) -> None:
"""Create a new Transform3d representing 3D translations. Option I: Translate(xyz, dtype=torch.float32, device='cpu') xyz should be a tensor of shape (N, 3) Option II: Translate(x... | the_stack_v2_python_sparse | pytorch3d/transforms/transform3d.py | facebookresearch/pytorch3d | train | 7,964 | |
56ba4a33a842cfedb21b752c31b4dfaeeca1e292 | [
"super(OperatorLookupError, self).__init__(operator)\nself.operator = operator\nself.filename = filename\nself.lineno = lineno\nself.block = block",
"op = self.operator\ntext = '%s\\n\\n' % op\ntext += _format_source_error(self.filename, self.lineno, self.block)\noptext = \"'%s'\" % op\nif op in self.op_map:\n ... | <|body_start_0|>
super(OperatorLookupError, self).__init__(operator)
self.operator = operator
self.filename = filename
self.lineno = lineno
self.block = block
<|end_body_0|>
<|body_start_1|>
op = self.operator
text = '%s\n\n' % op
text += _format_source_e... | A LookupError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed operator lookups when building the object tree. | OperatorLookupError | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OperatorLookupError:
"""A LookupError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed operator lookups when building the object tree."""
def __init__(self, operator, filename, lineno, block):
"... | stack_v2_sparse_classes_36k_train_032303 | 4,784 | permissive | [
{
"docstring": "Initialize an OperatorLookupError. Parameters ---------- operator : str The name of the operator which was not found. filename : str The filename where the lookup failed. lineno : int The line number of the error. block : str The name of the lexical block in which the lookup failed.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_017421 | Implement the Python class `OperatorLookupError` described below.
Class description:
A LookupError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed operator lookups when building the object tree.
Method signatures and docstrings... | Implement the Python class `OperatorLookupError` described below.
Class description:
A LookupError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed operator lookups when building the object tree.
Method signatures and docstrings... | 424bba29219de58fe9e47196de6763de8b2009f2 | <|skeleton|>
class OperatorLookupError:
"""A LookupError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed operator lookups when building the object tree."""
def __init__(self, operator, filename, lineno, block):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OperatorLookupError:
"""A LookupError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed operator lookups when building the object tree."""
def __init__(self, operator, filename, lineno, block):
"""Initialize ... | the_stack_v2_python_sparse | enaml/core/exceptions.py | enthought/enaml | train | 17 |
f1197a3a4c3543f883bdd8d6cc19902e061b9515 | [
"assert isinstance(input_integer, int), 'Invalid input type -- int expected'\nsuper().__init__(self.PROBLEM_NAME)\nself.input_integer = int(input_integer)",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nif self.input_integer < 0:\n return False\ninput_integer = self.input_integer\ndivisor = 1\nwh... | <|body_start_0|>
assert isinstance(input_integer, int), 'Invalid input type -- int expected'
super().__init__(self.PROBLEM_NAME)
self.input_integer = int(input_integer)
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
if self.input_intege... | PalindromeNumber | PalindromeNumber | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PalindromeNumber:
"""PalindromeNumber"""
def __init__(self, input_integer):
"""Palindrome Number Args: input_integer: to be checked if it's a palindrome Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solve the problem Note: O(n) solution works by co... | stack_v2_sparse_classes_36k_train_032304 | 2,020 | no_license | [
{
"docstring": "Palindrome Number Args: input_integer: to be checked if it's a palindrome Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, input_integer)"
},
{
"docstring": "Solve the problem Note: O(n) solution works by comparing left and right most digits until... | 2 | null | Implement the Python class `PalindromeNumber` described below.
Class description:
PalindromeNumber
Method signatures and docstrings:
- def __init__(self, input_integer): Palindrome Number Args: input_integer: to be checked if it's a palindrome Returns: None Raises: None
- def solve(self): Solve the problem Note: O(n)... | Implement the Python class `PalindromeNumber` described below.
Class description:
PalindromeNumber
Method signatures and docstrings:
- def __init__(self, input_integer): Palindrome Number Args: input_integer: to be checked if it's a palindrome Returns: None Raises: None
- def solve(self): Solve the problem Note: O(n)... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class PalindromeNumber:
"""PalindromeNumber"""
def __init__(self, input_integer):
"""Palindrome Number Args: input_integer: to be checked if it's a palindrome Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solve the problem Note: O(n) solution works by co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PalindromeNumber:
"""PalindromeNumber"""
def __init__(self, input_integer):
"""Palindrome Number Args: input_integer: to be checked if it's a palindrome Returns: None Raises: None"""
assert isinstance(input_integer, int), 'Invalid input type -- int expected'
super().__init__(self.... | the_stack_v2_python_sparse | python/problems/math/palindrome_number.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
efefecd09ad8506b7a9421370f064661fa5e39ee | [
"_1 = ListNode(1)\n_2 = ListNode(2)\n_3 = ListNode(3)\n_4 = ListNode(4)\n_1.next = _2\n_2.next = _3\n_3.next = _4\ns = Solution()\nnode = s.swapPairs(_1)\nself.assertIsNotNone(node)\nfor i in [2, 1, 4, 3]:\n self.assertEqual(i, node.val)\n node = node.next",
"_1 = ListNode(1)\n_2 = ListNode(2)\n_3 = ListNod... | <|body_start_0|>
_1 = ListNode(1)
_2 = ListNode(2)
_3 = ListNode(3)
_4 = ListNode(4)
_1.next = _2
_2.next = _3
_3.next = _4
s = Solution()
node = s.swapPairs(_1)
self.assertIsNotNone(node)
for i in [2, 1, 4, 3]:
self.ass... | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def test1(self):
"""给定 1->2->3->4, 你应该返回 2->1->4->3."""
<|body_0|>
def test2(self):
"""给定 1->2->3, 你应该返回 2->1->3."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
_1 = ListNode(1)
_2 = ListNode(2)
_3 = ListNode(3)
_4 = L... | stack_v2_sparse_classes_36k_train_032305 | 1,673 | no_license | [
{
"docstring": "给定 1->2->3->4, 你应该返回 2->1->4->3.",
"name": "test1",
"signature": "def test1(self)"
},
{
"docstring": "给定 1->2->3, 你应该返回 2->1->3.",
"name": "test2",
"signature": "def test2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000868 | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test1(self): 给定 1->2->3->4, 你应该返回 2->1->4->3.
- def test2(self): 给定 1->2->3, 你应该返回 2->1->3. | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test1(self): 给定 1->2->3->4, 你应该返回 2->1->4->3.
- def test2(self): 给定 1->2->3, 你应该返回 2->1->3.
<|skeleton|>
class Test:
def test1(self):
"""给定 1->2->3->4, 你应该返回 2->1->4->3... | 248b620791611001ebb471dcf8284437264b2f20 | <|skeleton|>
class Test:
def test1(self):
"""给定 1->2->3->4, 你应该返回 2->1->4->3."""
<|body_0|>
def test2(self):
"""给定 1->2->3, 你应该返回 2->1->3."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
def test1(self):
"""给定 1->2->3->4, 你应该返回 2->1->4->3."""
_1 = ListNode(1)
_2 = ListNode(2)
_3 = ListNode(3)
_4 = ListNode(4)
_1.next = _2
_2.next = _3
_3.next = _4
s = Solution()
node = s.swapPairs(_1)
self.assertIsNo... | the_stack_v2_python_sparse | 24_swap_nodes_in_pairs/_1.py | chxj1992/leetcode-exercise | train | 0 | |
46d222cf259394e54407ac66f616638741e92174 | [
"super().__init__(lr, weight_decay, team_emb_dim=team_emb_dim, player_emb_dim=player_emb_dim, **kwargs)\nnum_group = 9\noffdef_dim = self.n_player_emb * 2\ntp_dim = self.n_team_emb + offdef_dim\nself.off = nn.Linear(self.n_player_emb * 2, self.n_player_emb * 2)\nself.deff = nn.Linear(self.n_player_emb * 2, self.n_p... | <|body_start_0|>
super().__init__(lr, weight_decay, team_emb_dim=team_emb_dim, player_emb_dim=player_emb_dim, **kwargs)
num_group = 9
offdef_dim = self.n_player_emb * 2
tp_dim = self.n_team_emb + offdef_dim
self.off = nn.Linear(self.n_player_emb * 2, self.n_player_emb * 2)
... | mixed logistic regression | NBAMixedLogit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NBAMixedLogit:
"""mixed logistic regression"""
def __init__(self, lr=0.01, weight_decay=[0.0], team_emb_dim=2, player_emb_dim=2, **kwargs):
"""init method"""
<|body_0|>
def forward(self, x, return_embedding=True):
"""representations"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_032306 | 15,813 | no_license | [
{
"docstring": "init method",
"name": "__init__",
"signature": "def __init__(self, lr=0.01, weight_decay=[0.0], team_emb_dim=2, player_emb_dim=2, **kwargs)"
},
{
"docstring": "representations",
"name": "forward",
"signature": "def forward(self, x, return_embedding=True)"
}
] | 2 | null | Implement the Python class `NBAMixedLogit` described below.
Class description:
mixed logistic regression
Method signatures and docstrings:
- def __init__(self, lr=0.01, weight_decay=[0.0], team_emb_dim=2, player_emb_dim=2, **kwargs): init method
- def forward(self, x, return_embedding=True): representations | Implement the Python class `NBAMixedLogit` described below.
Class description:
mixed logistic regression
Method signatures and docstrings:
- def __init__(self, lr=0.01, weight_decay=[0.0], team_emb_dim=2, player_emb_dim=2, **kwargs): init method
- def forward(self, x, return_embedding=True): representations
<|skelet... | 2fd0fe7cff486bb13af2432f81e90a7df8e9e3d1 | <|skeleton|>
class NBAMixedLogit:
"""mixed logistic regression"""
def __init__(self, lr=0.01, weight_decay=[0.0], team_emb_dim=2, player_emb_dim=2, **kwargs):
"""init method"""
<|body_0|>
def forward(self, x, return_embedding=True):
"""representations"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NBAMixedLogit:
"""mixed logistic regression"""
def __init__(self, lr=0.01, weight_decay=[0.0], team_emb_dim=2, player_emb_dim=2, **kwargs):
"""init method"""
super().__init__(lr, weight_decay, team_emb_dim=team_emb_dim, player_emb_dim=player_emb_dim, **kwargs)
num_group = 9
... | the_stack_v2_python_sparse | player-rl/models/mlr.py | jensqin/exercise | train | 1 |
f5ed6dd93b755b0389868391f22c184c9a552a79 | [
"val_s = Stack()\ncur_node = headnode\nwhile cur_node:\n val_s.push(cur_node.val)\n cur_node = cur_node.next\nwhile not val_s.empty():\n print(val_s.pop())",
"curnode = headnode\nif curnode:\n self.solve2(curnode.next)\n print(curnode.val)"
] | <|body_start_0|>
val_s = Stack()
cur_node = headnode
while cur_node:
val_s.push(cur_node.val)
cur_node = cur_node.next
while not val_s.empty():
print(val_s.pop())
<|end_body_0|>
<|body_start_1|>
curnode = headnode
if curnode:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solve(self, headnode):
"""思路:用一个栈保存所有节点,之后一个一个 pop"""
<|body_0|>
def solve2(self, headnode):
"""能用栈就可以使用递归。这一点需要能联想到"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
val_s = Stack()
cur_node = headnode
while cur_node:
... | stack_v2_sparse_classes_36k_train_032307 | 1,362 | permissive | [
{
"docstring": "思路:用一个栈保存所有节点,之后一个一个 pop",
"name": "solve",
"signature": "def solve(self, headnode)"
},
{
"docstring": "能用栈就可以使用递归。这一点需要能联想到",
"name": "solve2",
"signature": "def solve2(self, headnode)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003182 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, headnode): 思路:用一个栈保存所有节点,之后一个一个 pop
- def solve2(self, headnode): 能用栈就可以使用递归。这一点需要能联想到 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, headnode): 思路:用一个栈保存所有节点,之后一个一个 pop
- def solve2(self, headnode): 能用栈就可以使用递归。这一点需要能联想到
<|skeleton|>
class Solution:
def solve(self, headnode):
"""思路... | 3469a79c34b6c08ae52797c3974b49fbfa8cca51 | <|skeleton|>
class Solution:
def solve(self, headnode):
"""思路:用一个栈保存所有节点,之后一个一个 pop"""
<|body_0|>
def solve2(self, headnode):
"""能用栈就可以使用递归。这一点需要能联想到"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def solve(self, headnode):
"""思路:用一个栈保存所有节点,之后一个一个 pop"""
val_s = Stack()
cur_node = headnode
while cur_node:
val_s.push(cur_node.val)
cur_node = cur_node.next
while not val_s.empty():
print(val_s.pop())
def solve2(self... | the_stack_v2_python_sparse | 剑指offer/05_PrintListInReversedOrder(从尾到头打印链表).py | Mark24Code/python_data_structures_and_algorithms | train | 1 | |
2720ce840d72c3cb36058d83c951627d6195ff7f | [
"super().__init__(name, **kwargs)\nself.website_id = 'the_mobile_indian'\nself.website_type = 'news'\nself.post_list_xpath = '//*[@id=\"middle\"]/div/ul/li[1]/section/ul/li'\nself.post_url_xpath = './h3/a/@href'\nself.post_list_url_xpath = '//*[@id=\"middle\"]/div/ul/li[1]/section/div[3]/ul/li//*[text()=\"»\"]/@hre... | <|body_start_0|>
super().__init__(name, **kwargs)
self.website_id = 'the_mobile_indian'
self.website_type = 'news'
self.post_list_xpath = '//*[@id="middle"]/div/ul/li[1]/section/ul/li'
self.post_url_xpath = './h3/a/@href'
self.post_list_url_xpath = '//*[@id="middle"]/div/... | 解析数据和爬虫逻辑类 | MySpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySpider:
"""解析数据和爬虫逻辑类"""
def __init__(self, name=None, **kwargs):
"""完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None"""
<|body_0|>
def parse(self, response):
"""解析列表页数据... | stack_v2_sparse_classes_36k_train_032308 | 2,524 | no_license | [
{
"docstring": "完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None",
"name": "__init__",
"signature": "def __init__(self, name=None, **kwargs)"
},
{
"docstring": "解析列表页数据以及构造帖子页和下一列表页请求",
"name": "parse... | 3 | stack_v2_sparse_classes_30k_train_017022 | Implement the Python class `MySpider` described below.
Class description:
解析数据和爬虫逻辑类
Method signatures and docstrings:
- def __init__(self, name=None, **kwargs): 完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None
- def parse(sel... | Implement the Python class `MySpider` described below.
Class description:
解析数据和爬虫逻辑类
Method signatures and docstrings:
- def __init__(self, name=None, **kwargs): 完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None
- def parse(sel... | 1b42878b694fabc65a02228662ffdf819e5dcc71 | <|skeleton|>
class MySpider:
"""解析数据和爬虫逻辑类"""
def __init__(self, name=None, **kwargs):
"""完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None"""
<|body_0|>
def parse(self, response):
"""解析列表页数据... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MySpider:
"""解析数据和爬虫逻辑类"""
def __init__(self, name=None, **kwargs):
"""完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None"""
super().__init__(name, **kwargs)
self.website_id = 'the_mobile_ind... | the_stack_v2_python_sparse | wujian/the_mobile_indian/the_mobile_indian/spiders/the_mobile_indian.py | wangsanshi123/spiders | train | 0 |
a1b86f8846cd2986fc8a7582a8fbcc094697d84a | [
"if not datas:\n datas = {}\nif not context:\n context = {}\nif 'updated' not in datas:\n datas['updated'] = False\nreturn super(osv.osv, self).write(cr, uid, ids, datas, context)",
"if not default:\n default = {}\nif not context:\n context = {}\ndefault = default.copy()\ndefault.update({'prestasho... | <|body_start_0|>
if not datas:
datas = {}
if not context:
context = {}
if 'updated' not in datas:
datas['updated'] = False
return super(osv.osv, self).write(cr, uid, ids, datas, context)
<|end_body_0|>
<|body_start_1|>
if not default:
... | Product Category inherited class for prestashop | product_category | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class product_category:
"""Product Category inherited class for prestashop"""
def write(self, cr, uid, ids, datas=None, context=None):
"""Base method overridden for custom approach"""
<|body_0|>
def copy(self, cr, uid, id, default=None, context=None):
"""Copy method ov... | stack_v2_sparse_classes_36k_train_032309 | 14,342 | no_license | [
{
"docstring": "Base method overridden for custom approach",
"name": "write",
"signature": "def write(self, cr, uid, ids, datas=None, context=None)"
},
{
"docstring": "Copy method overidden",
"name": "copy",
"signature": "def copy(self, cr, uid, id, default=None, context=None)"
},
{
... | 4 | null | Implement the Python class `product_category` described below.
Class description:
Product Category inherited class for prestashop
Method signatures and docstrings:
- def write(self, cr, uid, ids, datas=None, context=None): Base method overridden for custom approach
- def copy(self, cr, uid, id, default=None, context=... | Implement the Python class `product_category` described below.
Class description:
Product Category inherited class for prestashop
Method signatures and docstrings:
- def write(self, cr, uid, ids, datas=None, context=None): Base method overridden for custom approach
- def copy(self, cr, uid, id, default=None, context=... | 1081f3a5ff8864a31b2dcd89406fac076a908e78 | <|skeleton|>
class product_category:
"""Product Category inherited class for prestashop"""
def write(self, cr, uid, ids, datas=None, context=None):
"""Base method overridden for custom approach"""
<|body_0|>
def copy(self, cr, uid, id, default=None, context=None):
"""Copy method ov... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class product_category:
"""Product Category inherited class for prestashop"""
def write(self, cr, uid, ids, datas=None, context=None):
"""Base method overridden for custom approach"""
if not datas:
datas = {}
if not context:
context = {}
if 'updated' not ... | the_stack_v2_python_sparse | extra-addons/prestashop/product.py | sgeerish/sirr_production | train | 0 |
26790fe126a31a8310887306caaa4a3a8a218b1b | [
"self.lang = 'ar'\nself.cache = {}\nself.tokenizer = lambda sent: sent.split()",
"if profession not in self.cache:\n self.cache[profession] = self._get_gender(profession)\nreturn self.cache[profession]",
"if not profession.strip():\n return GENDER.unknown\ntoks = self.tokenizer(profession)\nif any(['ة' in... | <|body_start_0|>
self.lang = 'ar'
self.cache = {}
self.tokenizer = lambda sent: sent.split()
<|end_body_0|>
<|body_start_1|>
if profession not in self.cache:
self.cache[profession] = self._get_gender(profession)
return self.cache[profession]
<|end_body_1|>
<|body_st... | Arabic morphology heurstics. | ArabicPredictor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArabicPredictor:
"""Arabic morphology heurstics."""
def __init__(self):
"""Init tokenizer for Arabic."""
<|body_0|>
def get_gender(self, profession: str, translated_sent=None, entity_index=None, ds_entry=None) -> GENDER:
"""Predict gender of an input profession."... | stack_v2_sparse_classes_36k_train_032310 | 3,035 | permissive | [
{
"docstring": "Init tokenizer for Arabic.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Predict gender of an input profession.",
"name": "get_gender",
"signature": "def get_gender(self, profession: str, translated_sent=None, entity_index=None, ds_entry=None)... | 3 | stack_v2_sparse_classes_30k_train_007074 | Implement the Python class `ArabicPredictor` described below.
Class description:
Arabic morphology heurstics.
Method signatures and docstrings:
- def __init__(self): Init tokenizer for Arabic.
- def get_gender(self, profession: str, translated_sent=None, entity_index=None, ds_entry=None) -> GENDER: Predict gender of ... | Implement the Python class `ArabicPredictor` described below.
Class description:
Arabic morphology heurstics.
Method signatures and docstrings:
- def __init__(self): Init tokenizer for Arabic.
- def get_gender(self, profession: str, translated_sent=None, entity_index=None, ds_entry=None) -> GENDER: Predict gender of ... | 586292861cf2efdda2dec03c69c3408995a8b293 | <|skeleton|>
class ArabicPredictor:
"""Arabic morphology heurstics."""
def __init__(self):
"""Init tokenizer for Arabic."""
<|body_0|>
def get_gender(self, profession: str, translated_sent=None, entity_index=None, ds_entry=None) -> GENDER:
"""Predict gender of an input profession."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArabicPredictor:
"""Arabic morphology heurstics."""
def __init__(self):
"""Init tokenizer for Arabic."""
self.lang = 'ar'
self.cache = {}
self.tokenizer = lambda sent: sent.split()
def get_gender(self, profession: str, translated_sent=None, entity_index=None, ds_entry... | the_stack_v2_python_sparse | src/languages/semitic_languages.py | gabrielStanovsky/mt_gender | train | 42 |
cb86dabe0044903a17d6b9d94f9589eb7d9a1ace | [
"self.queue = deque()\nfor v in [v1, v2]:\n if v:\n self.queue.append((deque(v), 0))",
"self.hasNext()\ncurrentV, posistion = self.queue.popleft()\nif posistion < len(currentV):\n returnVal = currentV[posistion]\n self.queue.append((currentV, posistion + 1))\n return returnVal",
"currentQueue... | <|body_start_0|>
self.queue = deque()
for v in [v1, v2]:
if v:
self.queue.append((deque(v), 0))
<|end_body_0|>
<|body_start_1|>
self.hasNext()
currentV, posistion = self.queue.popleft()
if posistion < len(currentV):
returnVal = currentV[po... | ZigzagIterator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_36k_train_032311 | 2,357 | permissive | [
{
"docstring": "Initialize your data structure here. :type v1: List[int] :type v2: List[int]",
"name": "__init__",
"signature": "def __init__(self, v1, v2)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name"... | 3 | null | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | 20ae1a048eddbc9a32c819cf61258e2b57572f05 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
self.queue = deque()
for v in [v1, v2]:
if v:
self.queue.append((deque(v), 0))
def next(self):
""":rtype: int"""
... | the_stack_v2_python_sparse | leetcode.com/python/281_Zigzag_Iterator.py | partho-maple/coding-interview-gym | train | 862 | |
a0715197af010acc0836477f967ff32827eab9ab | [
"if other not in self.document:\n return True\nif value < self.document[other]:\n self._error(field, 'Value is lesser than %s.' % other)",
"if self.document['field_type'] == 'multiplechoice' or self.document['field_type'] == 'selectboxes':\n if isinstance(value, list):\n for v in value:\n ... | <|body_start_0|>
if other not in self.document:
return True
if value < self.document[other]:
self._error(field, 'Value is lesser than %s.' % other)
<|end_body_0|>
<|body_start_1|>
if self.document['field_type'] == 'multiplechoice' or self.document['field_type'] == 'selec... | FormsValidator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormsValidator:
def _validate_greater_than_equal(self, other, field, value):
"""{'type': 'string'}"""
<|body_0|>
def _validate_bounds(self, other, field, value):
"""{'type': 'string'}"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if other not in s... | stack_v2_sparse_classes_36k_train_032312 | 749 | no_license | [
{
"docstring": "{'type': 'string'}",
"name": "_validate_greater_than_equal",
"signature": "def _validate_greater_than_equal(self, other, field, value)"
},
{
"docstring": "{'type': 'string'}",
"name": "_validate_bounds",
"signature": "def _validate_bounds(self, other, field, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002553 | Implement the Python class `FormsValidator` described below.
Class description:
Implement the FormsValidator class.
Method signatures and docstrings:
- def _validate_greater_than_equal(self, other, field, value): {'type': 'string'}
- def _validate_bounds(self, other, field, value): {'type': 'string'} | Implement the Python class `FormsValidator` described below.
Class description:
Implement the FormsValidator class.
Method signatures and docstrings:
- def _validate_greater_than_equal(self, other, field, value): {'type': 'string'}
- def _validate_bounds(self, other, field, value): {'type': 'string'}
<|skeleton|>
cl... | 02c250a57d5e0544cff6e7722ee3398d68f32379 | <|skeleton|>
class FormsValidator:
def _validate_greater_than_equal(self, other, field, value):
"""{'type': 'string'}"""
<|body_0|>
def _validate_bounds(self, other, field, value):
"""{'type': 'string'}"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FormsValidator:
def _validate_greater_than_equal(self, other, field, value):
"""{'type': 'string'}"""
if other not in self.document:
return True
if value < self.document[other]:
self._error(field, 'Value is lesser than %s.' % other)
def _validate_bounds(sel... | the_stack_v2_python_sparse | backend/forms/schema/FormsValidator.py | iolser/lesforms | train | 0 | |
2af2f859778c06eef15c2fdb5b8629ef51800984 | [
"with plt.style.context(config.STYLE_SHEET):\n title = f'Confusion Matrix - {self._estimator_name}'\n y_pred = _classify(self._data.test_x, self._estimator, threshold=threshold)\n return plot_confusion_matrix(self._data.test_y, y_pred, normalized, title, **kwargs)",
"if not hasattr(self._estimator, 'pred... | <|body_start_0|>
with plt.style.context(config.STYLE_SHEET):
title = f'Confusion Matrix - {self._estimator_name}'
y_pred = _classify(self._data.test_x, self._estimator, threshold=threshold)
return plot_confusion_matrix(self._data.test_y, y_pred, normalized, title, **kwargs)
<... | Visualization class for Classification models | ClassificationVisualize | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassificationVisualize:
"""Visualization class for Classification models"""
def confusion_matrix(self, normalized: bool=True, threshold: Optional[float]=None, **kwargs) -> plt.Axes:
"""Visualize a confusion matrix for a classification estimator Any kwargs are passed onto matplotlib ... | stack_v2_sparse_classes_36k_train_032313 | 4,086 | permissive | [
{
"docstring": "Visualize a confusion matrix for a classification estimator Any kwargs are passed onto matplotlib Parameters ---------- normalized: bool Whether or not to normalize annotated class counts threshold: float Threshold to use for classification - defaults to 0.5 Returns ------- plt.Axes Returns a Co... | 4 | stack_v2_sparse_classes_30k_train_009958 | Implement the Python class `ClassificationVisualize` described below.
Class description:
Visualization class for Classification models
Method signatures and docstrings:
- def confusion_matrix(self, normalized: bool=True, threshold: Optional[float]=None, **kwargs) -> plt.Axes: Visualize a confusion matrix for a classi... | Implement the Python class `ClassificationVisualize` described below.
Class description:
Visualization class for Classification models
Method signatures and docstrings:
- def confusion_matrix(self, normalized: bool=True, threshold: Optional[float]=None, **kwargs) -> plt.Axes: Visualize a confusion matrix for a classi... | a7a627873a8957a742c125917149a92de4b10e3c | <|skeleton|>
class ClassificationVisualize:
"""Visualization class for Classification models"""
def confusion_matrix(self, normalized: bool=True, threshold: Optional[float]=None, **kwargs) -> plt.Axes:
"""Visualize a confusion matrix for a classification estimator Any kwargs are passed onto matplotlib ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassificationVisualize:
"""Visualization class for Classification models"""
def confusion_matrix(self, normalized: bool=True, threshold: Optional[float]=None, **kwargs) -> plt.Axes:
"""Visualize a confusion matrix for a classification estimator Any kwargs are passed onto matplotlib Parameters --... | the_stack_v2_python_sparse | src/ml_tooling/plots/viz/classification_viz.py | andersbogsnes/ml_tooling | train | 7 |
86aa5f56bc3cfbd1c8f80561f5fb510dea006877 | [
"self.headquarters_address = headquarters_address\nself.legal_address = legal_address\nself.legal_jurisdiction = legal_jurisdiction\nself.legal_name = legal_name\nself.entity_status = entity_status\nself.entity_category = entity_category\nself.legal_form = legal_form\nself.registration_authority = registration_auth... | <|body_start_0|>
self.headquarters_address = headquarters_address
self.legal_address = legal_address
self.legal_jurisdiction = legal_jurisdiction
self.legal_name = legal_name
self.entity_status = entity_status
self.entity_category = entity_category
self.legal_form... | Implementation of the 'LeiEntity' model. TODO: type model description here. Attributes: headquarters_address (LeiEntityAddress): TODO: type description here. legal_address (LeiEntityAddress): TODO: type description here. legal_jurisdiction (string): TODO: type description here. legal_name (string): TODO: type descripti... | LeiEntity | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LeiEntity:
"""Implementation of the 'LeiEntity' model. TODO: type model description here. Attributes: headquarters_address (LeiEntityAddress): TODO: type description here. legal_address (LeiEntityAddress): TODO: type description here. legal_jurisdiction (string): TODO: type description here. lega... | stack_v2_sparse_classes_36k_train_032314 | 4,641 | permissive | [
{
"docstring": "Constructor for the LeiEntity class",
"name": "__init__",
"signature": "def __init__(self, headquarters_address=None, legal_address=None, legal_jurisdiction=None, legal_name=None, entity_status=None, entity_category=None, legal_form=None, registration_authority=None, additional_propertie... | 2 | null | Implement the Python class `LeiEntity` described below.
Class description:
Implementation of the 'LeiEntity' model. TODO: type model description here. Attributes: headquarters_address (LeiEntityAddress): TODO: type description here. legal_address (LeiEntityAddress): TODO: type description here. legal_jurisdiction (str... | Implement the Python class `LeiEntity` described below.
Class description:
Implementation of the 'LeiEntity' model. TODO: type model description here. Attributes: headquarters_address (LeiEntityAddress): TODO: type description here. legal_address (LeiEntityAddress): TODO: type description here. legal_jurisdiction (str... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class LeiEntity:
"""Implementation of the 'LeiEntity' model. TODO: type model description here. Attributes: headquarters_address (LeiEntityAddress): TODO: type description here. legal_address (LeiEntityAddress): TODO: type description here. legal_jurisdiction (string): TODO: type description here. lega... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LeiEntity:
"""Implementation of the 'LeiEntity' model. TODO: type model description here. Attributes: headquarters_address (LeiEntityAddress): TODO: type description here. legal_address (LeiEntityAddress): TODO: type description here. legal_jurisdiction (string): TODO: type description here. legal_name (strin... | the_stack_v2_python_sparse | idfy_rest_client/models/lei_entity.py | dealflowteam/Idfy | train | 0 |
f14b844b5bcf5cd333c3325c16c84b5fca2a9b41 | [
"assert type(screen_name) == str\nfollowers_users_screen_name = tweepy_getter.get_followers_by_screen_name(screen_name, num_followers)\nuser_followers_setter.store_followers_by_screen_name(screen_name, followers_users_screen_name)",
"assert type(id) == int\nfollowers_users_ID = tweepy_getter.get_followers_by_id(i... | <|body_start_0|>
assert type(screen_name) == str
followers_users_screen_name = tweepy_getter.get_followers_by_screen_name(screen_name, num_followers)
user_followers_setter.store_followers_by_screen_name(screen_name, followers_users_screen_name)
<|end_body_0|>
<|body_start_1|>
assert typ... | Download Twitter Followers for use in future algorithms. | TwitterFollowersDownloader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwitterFollowersDownloader:
"""Download Twitter Followers for use in future algorithms."""
def gen_followers_by_screen_name(self, screen_name: str, tweepy_getter, user_followers_setter, num_followers=None) -> List[str]:
"""Gets a list of followers of a user by screen name @param scre... | stack_v2_sparse_classes_36k_train_032315 | 7,540 | no_license | [
{
"docstring": "Gets a list of followers of a user by screen name @param screen_name the screen name of the user to search for @param tweepy_getter the dao to access twitter with @param user_followers_setter the dao to store the users followers in @param num_followers the maximum number of followers to retrieve... | 2 | stack_v2_sparse_classes_30k_train_002306 | Implement the Python class `TwitterFollowersDownloader` described below.
Class description:
Download Twitter Followers for use in future algorithms.
Method signatures and docstrings:
- def gen_followers_by_screen_name(self, screen_name: str, tweepy_getter, user_followers_setter, num_followers=None) -> List[str]: Gets... | Implement the Python class `TwitterFollowersDownloader` described below.
Class description:
Download Twitter Followers for use in future algorithms.
Method signatures and docstrings:
- def gen_followers_by_screen_name(self, screen_name: str, tweepy_getter, user_followers_setter, num_followers=None) -> List[str]: Gets... | 33a3fa38ad4dcdd54ff583da15dcd67c99ad9701 | <|skeleton|>
class TwitterFollowersDownloader:
"""Download Twitter Followers for use in future algorithms."""
def gen_followers_by_screen_name(self, screen_name: str, tweepy_getter, user_followers_setter, num_followers=None) -> List[str]:
"""Gets a list of followers of a user by screen name @param scre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwitterFollowersDownloader:
"""Download Twitter Followers for use in future algorithms."""
def gen_followers_by_screen_name(self, screen_name: str, tweepy_getter, user_followers_setter, num_followers=None) -> List[str]:
"""Gets a list of followers of a user by screen name @param screen_name the s... | the_stack_v2_python_sparse | src/process/download/twitter_downloader.py | ReinaKousaka/core | train | 0 |
e4bcf1b7116e7b057e4d06d63ed0d168936d294c | [
"self.name = name\nself.hparams = hparams\nself.optimizer_n = optimizer\nself.training_freq = hparams.training_freq\nself.training_epochs = hparams.training_epochs\nself.t = 0\nself.q = hparams.q\nself.p = hparams.p\nself.datasets = [ContextualDataset(hparams.context_dim, hparams.num_actions, hparams.buffer_s) for ... | <|body_start_0|>
self.name = name
self.hparams = hparams
self.optimizer_n = optimizer
self.training_freq = hparams.training_freq
self.training_epochs = hparams.training_epochs
self.t = 0
self.q = hparams.q
self.p = hparams.p
self.datasets = [Contex... | Thompson Sampling algorithm based on training several neural networks. | BootstrappedBNNSampling | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BootstrappedBNNSampling:
"""Thompson Sampling algorithm based on training several neural networks."""
def __init__(self, name, hparams, optimizer='RMS'):
"""Creates a BootstrappedSGDSampling object based on a specific optimizer. hparams.q: Number of models that are independently trai... | stack_v2_sparse_classes_36k_train_032316 | 3,522 | permissive | [
{
"docstring": "Creates a BootstrappedSGDSampling object based on a specific optimizer. hparams.q: Number of models that are independently trained. hparams.p: Prob of independently including each datapoint in each model. Args: name: Name given to the instance. hparams: Hyperparameters for each individual model.... | 3 | stack_v2_sparse_classes_30k_test_001167 | Implement the Python class `BootstrappedBNNSampling` described below.
Class description:
Thompson Sampling algorithm based on training several neural networks.
Method signatures and docstrings:
- def __init__(self, name, hparams, optimizer='RMS'): Creates a BootstrappedSGDSampling object based on a specific optimizer... | Implement the Python class `BootstrappedBNNSampling` described below.
Class description:
Thompson Sampling algorithm based on training several neural networks.
Method signatures and docstrings:
- def __init__(self, name, hparams, optimizer='RMS'): Creates a BootstrappedSGDSampling object based on a specific optimizer... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class BootstrappedBNNSampling:
"""Thompson Sampling algorithm based on training several neural networks."""
def __init__(self, name, hparams, optimizer='RMS'):
"""Creates a BootstrappedSGDSampling object based on a specific optimizer. hparams.q: Number of models that are independently trai... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BootstrappedBNNSampling:
"""Thompson Sampling algorithm based on training several neural networks."""
def __init__(self, name, hparams, optimizer='RMS'):
"""Creates a BootstrappedSGDSampling object based on a specific optimizer. hparams.q: Number of models that are independently trained. hparams.... | the_stack_v2_python_sparse | models/research/deep_contextual_bandits/bandits/algorithms/bootstrapped_bnn_sampling.py | finnickniu/tensorflow_object_detection_tflite | train | 60 |
9f2f7bdbe644fc84c68066666508221cd7e6e9bc | [
"super().__init__(**kwargs)\nself.conv1 = keras.layers.Conv2D(64, 2, padding='same', activation='relu')\nself.maxpool1 = keras.layers.MaxPool2D(pool_size=(2, 2), strides=2)\nself.dropout1 = keras.layers.Dropout(0.3)\nself.conv2 = keras.layers.Conv2D(32, 2, padding='same', activation='relu')\nself.maxpool2 = keras.l... | <|body_start_0|>
super().__init__(**kwargs)
self.conv1 = keras.layers.Conv2D(64, 2, padding='same', activation='relu')
self.maxpool1 = keras.layers.MaxPool2D(pool_size=(2, 2), strides=2)
self.dropout1 = keras.layers.Dropout(0.3)
self.conv2 = keras.layers.Conv2D(32, 2, padding='sa... | MNIST classifier used in the experiments for Counterfactual with Reinforcement Learning. The model consists of two convolutional layers having 64 and 32 channels and a kernel size of 2 with ReLU nonlinearities, followed by maxpooling of size 2 and dropout of 0.3. The convolutional block is followed by a fully connected... | MNISTClassifier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MNISTClassifier:
"""MNIST classifier used in the experiments for Counterfactual with Reinforcement Learning. The model consists of two convolutional layers having 64 and 32 channels and a kernel size of 2 with ReLU nonlinearities, followed by maxpooling of size 2 and dropout of 0.3. The convoluti... | stack_v2_sparse_classes_36k_train_032317 | 8,692 | permissive | [
{
"docstring": "Constructor. Parameters ---------- output_dim Output dimension",
"name": "__init__",
"signature": "def __init__(self, output_dim: int=10, **kwargs) -> None"
},
{
"docstring": "Forward pass. Parameters ---------- x Input tensor. training Training flag. **kwargs Other arguments. No... | 2 | null | Implement the Python class `MNISTClassifier` described below.
Class description:
MNIST classifier used in the experiments for Counterfactual with Reinforcement Learning. The model consists of two convolutional layers having 64 and 32 channels and a kernel size of 2 with ReLU nonlinearities, followed by maxpooling of s... | Implement the Python class `MNISTClassifier` described below.
Class description:
MNIST classifier used in the experiments for Counterfactual with Reinforcement Learning. The model consists of two convolutional layers having 64 and 32 channels and a kernel size of 2 with ReLU nonlinearities, followed by maxpooling of s... | 54d0c957fb01c7ebba4e2a0d28fcbde52d9c6718 | <|skeleton|>
class MNISTClassifier:
"""MNIST classifier used in the experiments for Counterfactual with Reinforcement Learning. The model consists of two convolutional layers having 64 and 32 channels and a kernel size of 2 with ReLU nonlinearities, followed by maxpooling of size 2 and dropout of 0.3. The convoluti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MNISTClassifier:
"""MNIST classifier used in the experiments for Counterfactual with Reinforcement Learning. The model consists of two convolutional layers having 64 and 32 channels and a kernel size of 2 with ReLU nonlinearities, followed by maxpooling of size 2 and dropout of 0.3. The convolutional block is... | the_stack_v2_python_sparse | alibi/models/tensorflow/cfrl_models.py | SeldonIO/alibi | train | 2,143 |
d2e679118f1a07ffac3c6dbbfa34b6915c1ef085 | [
"super(InceptionV3, self).__init__()\nself.resize_input = resize_input\nself.normalize_input = normalize_input\nself.output_blocks = sorted(output_blocks)\nself.last_needed_block = max(output_blocks)\nassert self.last_needed_block <= 3, 'Last possible output block index is 3'\nself.blocks = nn.ModuleList()\nincepti... | <|body_start_0|>
super(InceptionV3, self).__init__()
self.resize_input = resize_input
self.normalize_input = normalize_input
self.output_blocks = sorted(output_blocks)
self.last_needed_block = max(output_blocks)
assert self.last_needed_block <= 3, 'Last possible output bl... | Pretrained InceptionV3 network returning feature maps | InceptionV3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InceptionV3:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False):
"""Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices of... | stack_v2_sparse_classes_36k_train_032318 | 16,361 | no_license | [
{
"docstring": "Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices of blocks to return features of. Possible values are: - 0: corresponds to output of first max pooling - 1: corresponds to output of second max pooling - 2: corresponds to output which is fed to aux classifier ... | 2 | stack_v2_sparse_classes_30k_train_017334 | Implement the Python class `InceptionV3` described below.
Class description:
Pretrained InceptionV3 network returning feature maps
Method signatures and docstrings:
- def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False): Build pretrained InceptionV3 Par... | Implement the Python class `InceptionV3` described below.
Class description:
Pretrained InceptionV3 network returning feature maps
Method signatures and docstrings:
- def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False): Build pretrained InceptionV3 Par... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class InceptionV3:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False):
"""Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InceptionV3:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False):
"""Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices of blocks to re... | the_stack_v2_python_sparse | generated/test_crcrpar_pytorch_sngan_projection.py | jansel/pytorch-jit-paritybench | train | 35 |
e60b9b10d7443ed4c5cbb372a600ff99ee5fc767 | [
"session = async_get_clientsession(self.hass)\nweb_account = WebAccount(session, email, password)\nweb_account_info = await web_account.login()\nmobile_account = MobileAccount(session, email, password)\nawait mobile_account.login()\nreturn {CONF_ACCESS_TOKEN: mobile_account.access_token, CONF_EMAIL: web_account_inf... | <|body_start_0|>
session = async_get_clientsession(self.hass)
web_account = WebAccount(session, email, password)
web_account_info = await web_account.login()
mobile_account = MobileAccount(session, email, password)
await mobile_account.login()
return {CONF_ACCESS_TOKEN: m... | Handle a config flow for Aseko Pool Live. | ConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Aseko Pool Live."""
async def get_account_info(self, email: str, password: str) -> dict:
"""Get account info from the mobile API and the web API."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, Any] | None=None)... | stack_v2_sparse_classes_36k_train_032319 | 2,634 | permissive | [
{
"docstring": "Get account info from the mobile API and the web API.",
"name": "get_account_info",
"signature": "async def get_account_info(self, email: str, password: str) -> dict"
},
{
"docstring": "Handle the initial step.",
"name": "async_step_user",
"signature": "async def async_st... | 2 | stack_v2_sparse_classes_30k_train_008710 | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Aseko Pool Live.
Method signatures and docstrings:
- async def get_account_info(self, email: str, password: str) -> dict: Get account info from the mobile API and the web API.
- async def async_step_user(self, user_in... | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Aseko Pool Live.
Method signatures and docstrings:
- async def get_account_info(self, email: str, password: str) -> dict: Get account info from the mobile API and the web API.
- async def async_step_user(self, user_in... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Aseko Pool Live."""
async def get_account_info(self, email: str, password: str) -> dict:
"""Get account info from the mobile API and the web API."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, Any] | None=None)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigFlow:
"""Handle a config flow for Aseko Pool Live."""
async def get_account_info(self, email: str, password: str) -> dict:
"""Get account info from the mobile API and the web API."""
session = async_get_clientsession(self.hass)
web_account = WebAccount(session, email, passwo... | the_stack_v2_python_sparse | homeassistant/components/aseko_pool_live/config_flow.py | home-assistant/core | train | 35,501 |
d863594143c6371e3826797a732c5436e2f59e76 | [
"if not nums or k <= 0:\n return\nn = len(nums)\nk = k % n\nfor i in range(n // 2):\n nums[i], nums[n - 1 - i] = (nums[n - 1 - i], nums[i])\nfor i in range(k // 2):\n nums[i], nums[k - 1 - i] = (nums[k - 1 - i], nums[i])\nfor i in range((n - k) // 2):\n nums[k + i], nums[n - 1 - i] = (nums[n - 1 - i], n... | <|body_start_0|>
if not nums or k <= 0:
return
n = len(nums)
k = k % n
for i in range(n // 2):
nums[i], nums[n - 1 - i] = (nums[n - 1 - i], nums[i])
for i in range(k // 2):
nums[i], nums[k - 1 - i] = (nums[k - 1 - i], nums[i])
for i in ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify n... | stack_v2_sparse_classes_36k_train_032320 | 3,328 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.",
"name": "rotate",
"signature": "def rotate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place inste... | 3 | stack_v2_sparse_classes_30k_train_020215 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate2(self, nums, k): :type nums: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate2(self, nums, k): :type nums: List[in... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
if not nums or k <= 0:
return
n = len(nums)
k = k % n
for i in range(n // 2):
nums[i], nums[n - 1 - i... | the_stack_v2_python_sparse | code189RotateArray.py | cybelewang/leetcode-python | train | 0 | |
efc84b069aa2c3dc5c12432dc3d575cafca73bd4 | [
"object.__init__(self)\nself.driver_module = driver_module\nself.driver_class = driver_class\nself.device_addr = device_addr\nself.device_port = device_port\nself.command_port = command_port\nself.data_port = data_port\nself.port_agent_binary = port_agent_binary\nself.delim = delim\nself.work_dir = work_dir\nself._... | <|body_start_0|>
object.__init__(self)
self.driver_module = driver_module
self.driver_class = driver_class
self.device_addr = device_addr
self.device_port = device_port
self.command_port = command_port
self.data_port = data_port
self.port_agent_binary = po... | Common functionality helpful for driver integration testing. | DriverIntegrationTestSupport | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DriverIntegrationTestSupport:
"""Common functionality helpful for driver integration testing."""
def __init__(self, driver_module, driver_class, device_addr, device_port, data_port, command_port, port_agent_binary='port_agent', delim=None, work_dir='/tmp/'):
"""@param driver_module @... | stack_v2_sparse_classes_36k_train_032321 | 3,148 | no_license | [
{
"docstring": "@param driver_module @param driver_class @param device_addr @param device_port @param command_port @param port_agent_binary @param delim 2-element delimiter to indicate traffic from the driver in the logfile. See EthernetDeviceLogger.launch_process for default value. @param work_dir by default, ... | 3 | null | Implement the Python class `DriverIntegrationTestSupport` described below.
Class description:
Common functionality helpful for driver integration testing.
Method signatures and docstrings:
- def __init__(self, driver_module, driver_class, device_addr, device_port, data_port, command_port, port_agent_binary='port_agen... | Implement the Python class `DriverIntegrationTestSupport` described below.
Class description:
Common functionality helpful for driver integration testing.
Method signatures and docstrings:
- def __init__(self, driver_module, driver_class, device_addr, device_port, data_port, command_port, port_agent_binary='port_agen... | 1693081ddaacd4e72c75ab47c0289a04f08ca6c9 | <|skeleton|>
class DriverIntegrationTestSupport:
"""Common functionality helpful for driver integration testing."""
def __init__(self, driver_module, driver_class, device_addr, device_port, data_port, command_port, port_agent_binary='port_agent', delim=None, work_dir='/tmp/'):
"""@param driver_module @... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DriverIntegrationTestSupport:
"""Common functionality helpful for driver integration testing."""
def __init__(self, driver_module, driver_class, device_addr, device_port, data_port, command_port, port_agent_binary='port_agent', delim=None, work_dir='/tmp/'):
"""@param driver_module @param driver_... | the_stack_v2_python_sparse | ion/agents/instrument/driver_int_test_support.py | sfoley/coi-services | train | 1 |
ddb8dd6375c3eaeeeac76dd492e40aceb03b6acb | [
"splits = []\nsplit = []\nfor node in toposort(graph.return_):\n if self.is_cut(node):\n if len(split) != 0:\n splits.append(split)\n splits.append(node)\n split = []\n elif not (node.is_constant() or node.is_parameter()):\n split.append(node)\nreturn {'splits': splits}"... | <|body_start_0|>
splits = []
split = []
for node in toposort(graph.return_):
if self.is_cut(node):
if len(split) != 0:
splits.append(split)
splits.append(node)
split = []
elif not (node.is_constant() or n... | Pipeline step to cut the graph into linear portions and control flow. Inputs: graph: A graph Outputs: splits: list of graph portions | SplitGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SplitGraph:
"""Pipeline step to cut the graph into linear portions and control flow. Inputs: graph: A graph Outputs: splits: list of graph portions"""
def step(self, graph):
"""Split the graph into portions."""
<|body_0|>
def is_cut(self, node):
"""Returns whethe... | stack_v2_sparse_classes_36k_train_032322 | 12,200 | permissive | [
{
"docstring": "Split the graph into portions.",
"name": "step",
"signature": "def step(self, graph)"
},
{
"docstring": "Returns whether there should be a cut for this node. Cuts are done for all \"non-linear\" nodes: function calls, branches, ...",
"name": "is_cut",
"signature": "def is... | 2 | stack_v2_sparse_classes_30k_train_001910 | Implement the Python class `SplitGraph` described below.
Class description:
Pipeline step to cut the graph into linear portions and control flow. Inputs: graph: A graph Outputs: splits: list of graph portions
Method signatures and docstrings:
- def step(self, graph): Split the graph into portions.
- def is_cut(self, ... | Implement the Python class `SplitGraph` described below.
Class description:
Pipeline step to cut the graph into linear portions and control flow. Inputs: graph: A graph Outputs: splits: list of graph portions
Method signatures and docstrings:
- def step(self, graph): Split the graph into portions.
- def is_cut(self, ... | 3bfb8ac20468bfc7be34128a396f79f2e03b24a1 | <|skeleton|>
class SplitGraph:
"""Pipeline step to cut the graph into linear portions and control flow. Inputs: graph: A graph Outputs: splits: list of graph portions"""
def step(self, graph):
"""Split the graph into portions."""
<|body_0|>
def is_cut(self, node):
"""Returns whethe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SplitGraph:
"""Pipeline step to cut the graph into linear portions and control flow. Inputs: graph: A graph Outputs: splits: list of graph portions"""
def step(self, graph):
"""Split the graph into portions."""
splits = []
split = []
for node in toposort(graph.return_):
... | the_stack_v2_python_sparse | myia/compile/transform.py | kbrightfall/myia | train | 0 |
3df7c3b7c509cd08411da285530d355fc1dafb1c | [
"bus = PyCapture2.BusManager()\nnumCams = bus.getNumOfCameras()\nself.camera = PyCapture2.Camera()\nuid = bus.getCameraFromIndex(0)\nself.camera.connect(uid)\nself.camera.startCapture()",
"image = self.camera.retrieveBuffer()\nimdata = image.getData()\nrow_bytes = float(len(imdata)) / float(image.getRows())\ngray... | <|body_start_0|>
bus = PyCapture2.BusManager()
numCams = bus.getNumOfCameras()
self.camera = PyCapture2.Camera()
uid = bus.getCameraFromIndex(0)
self.camera.connect(uid)
self.camera.startCapture()
<|end_body_0|>
<|body_start_1|>
image = self.camera.retrieveBuffer... | this class does all the gritty image capture stuff you need to do to get data from the pointgrey cameras | FlyCamera | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlyCamera:
"""this class does all the gritty image capture stuff you need to do to get data from the pointgrey cameras"""
def __init__(self, camIndex=0):
"""this is all the stuff you need to do to initialize the camera. It should work for multiple cameras as long as you change the ca... | stack_v2_sparse_classes_36k_train_032323 | 1,398 | no_license | [
{
"docstring": "this is all the stuff you need to do to initialize the camera. It should work for multiple cameras as long as you change the camIndex",
"name": "__init__",
"signature": "def __init__(self, camIndex=0)"
},
{
"docstring": "the data from the camera comes in a weird format, and we ne... | 2 | stack_v2_sparse_classes_30k_test_000319 | Implement the Python class `FlyCamera` described below.
Class description:
this class does all the gritty image capture stuff you need to do to get data from the pointgrey cameras
Method signatures and docstrings:
- def __init__(self, camIndex=0): this is all the stuff you need to do to initialize the camera. It shou... | Implement the Python class `FlyCamera` described below.
Class description:
this class does all the gritty image capture stuff you need to do to get data from the pointgrey cameras
Method signatures and docstrings:
- def __init__(self, camIndex=0): this is all the stuff you need to do to initialize the camera. It shou... | 7e0cf10fe9706f2d389e7719b568419838471071 | <|skeleton|>
class FlyCamera:
"""this class does all the gritty image capture stuff you need to do to get data from the pointgrey cameras"""
def __init__(self, camIndex=0):
"""this is all the stuff you need to do to initialize the camera. It should work for multiple cameras as long as you change the ca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlyCamera:
"""this class does all the gritty image capture stuff you need to do to get data from the pointgrey cameras"""
def __init__(self, camIndex=0):
"""this is all the stuff you need to do to initialize the camera. It should work for multiple cameras as long as you change the camIndex"""
... | the_stack_v2_python_sparse | Lab3/image_publisher/nodes/cam_capture.py | jalderet/be107 | train | 0 |
928dc92e4a0cc1ce911e80f9112ef2cc9c4d4f14 | [
"if root is None:\n return ''\nreturn str(root.val) + '#' + self.serialize(root.left) + self.serialize(root.right)",
"def dfs(queue, lb, hb):\n if not queue:\n return None\n peek = int(queue[0])\n if peek < lb or peek > hb:\n return None\n val = int(queue.popleft())\n node = TreeNo... | <|body_start_0|>
if root is None:
return ''
return str(root.val) + '#' + self.serialize(root.left) + self.serialize(root.right)
<|end_body_0|>
<|body_start_1|>
def dfs(queue, lb, hb):
if not queue:
return None
peek = int(queue[0])
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is Non... | stack_v2_sparse_classes_36k_train_032324 | 2,123 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 67054f724c6c0e1699118248788522cec624b831 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
if root is None:
return ''
return str(root.val) + '#' + self.serialize(root.left) + self.serialize(root.right)
def deserialize(self, data: str) -> TreeNode:
"""Decodes y... | the_stack_v2_python_sparse | LeetCode449SerializeandDeserializeBST.py | lonely7yk/LeetCode_py | train | 0 | |
abaa1cbcfe89f6d1110f07a5c6a5934f4217b42a | [
"try:\n import dgl\nexcept:\n raise ImportError('This class requires dgl.')\ntry:\n import dgllife\nexcept:\n raise ImportError('This class requires dgllife.')\nif mode not in ['classification', 'regression']:\n raise ValueError(\"mode must be either 'classification' or 'regression'\")\nsuper(MPNN, s... | <|body_start_0|>
try:
import dgl
except:
raise ImportError('This class requires dgl.')
try:
import dgllife
except:
raise ImportError('This class requires dgllife.')
if mode not in ['classification', 'regression']:
raise ... | Model for Graph Property Prediction. This model proceeds as follows: * Combine latest node representations and edge features in updating node representations, which involves multiple rounds of message passing * For each graph, compute its representation by combining the representations of all nodes in it, which involve... | MPNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MPNN:
"""Model for Graph Property Prediction. This model proceeds as follows: * Combine latest node representations and edge features in updating node representations, which involves multiple rounds of message passing * For each graph, compute its representation by combining the representations o... | stack_v2_sparse_classes_36k_train_032325 | 12,074 | permissive | [
{
"docstring": "Parameters ---------- n_tasks: int Number of tasks. node_out_feats: int The length of the final node representation vectors. Default to 64. edge_hidden_feats: int The length of the hidden edge representation vectors. Default to 128. num_step_message_passing: int The number of rounds of message p... | 2 | stack_v2_sparse_classes_30k_train_012093 | Implement the Python class `MPNN` described below.
Class description:
Model for Graph Property Prediction. This model proceeds as follows: * Combine latest node representations and edge features in updating node representations, which involves multiple rounds of message passing * For each graph, compute its representa... | Implement the Python class `MPNN` described below.
Class description:
Model for Graph Property Prediction. This model proceeds as follows: * Combine latest node representations and edge features in updating node representations, which involves multiple rounds of message passing * For each graph, compute its representa... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class MPNN:
"""Model for Graph Property Prediction. This model proceeds as follows: * Combine latest node representations and edge features in updating node representations, which involves multiple rounds of message passing * For each graph, compute its representation by combining the representations o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MPNN:
"""Model for Graph Property Prediction. This model proceeds as follows: * Combine latest node representations and edge features in updating node representations, which involves multiple rounds of message passing * For each graph, compute its representation by combining the representations of all nodes i... | the_stack_v2_python_sparse | deepchem/models/torch_models/mpnn.py | deepchem/deepchem | train | 4,876 |
3486466935017cad555fe6e6ec7924eb5a4e0909 | [
"if request.method == 'GET':\n return WPS10DescribeProcessKVPDecoder(request.GET)\nelse:\n return WPS10DescribeProcessXMLDecoder(request.body)",
"decoder = self.get_decoder(request)\nidentifiers = set(decoder.identifiers)\nused_processes = []\nfor process in get_processes():\n process_identifier = getatt... | <|body_start_0|>
if request.method == 'GET':
return WPS10DescribeProcessKVPDecoder(request.GET)
else:
return WPS10DescribeProcessXMLDecoder(request.body)
<|end_body_0|>
<|body_start_1|>
decoder = self.get_decoder(request)
identifiers = set(decoder.identifiers)
... | WPS 1.0 DescribeProcess service handler. | WPS10DescribeProcessHandler | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WPS10DescribeProcessHandler:
"""WPS 1.0 DescribeProcess service handler."""
def get_decoder(request):
"""Get the WPS request decoder."""
<|body_0|>
def handle(self, request):
"""Handle HTTP request."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_032326 | 3,517 | permissive | [
{
"docstring": "Get the WPS request decoder.",
"name": "get_decoder",
"signature": "def get_decoder(request)"
},
{
"docstring": "Handle HTTP request.",
"name": "handle",
"signature": "def handle(self, request)"
}
] | 2 | null | Implement the Python class `WPS10DescribeProcessHandler` described below.
Class description:
WPS 1.0 DescribeProcess service handler.
Method signatures and docstrings:
- def get_decoder(request): Get the WPS request decoder.
- def handle(self, request): Handle HTTP request. | Implement the Python class `WPS10DescribeProcessHandler` described below.
Class description:
WPS 1.0 DescribeProcess service handler.
Method signatures and docstrings:
- def get_decoder(request): Get the WPS request decoder.
- def handle(self, request): Handle HTTP request.
<|skeleton|>
class WPS10DescribeProcessHan... | c7f709cbbcf9172b99fa327221b59b5119305c82 | <|skeleton|>
class WPS10DescribeProcessHandler:
"""WPS 1.0 DescribeProcess service handler."""
def get_decoder(request):
"""Get the WPS request decoder."""
<|body_0|>
def handle(self, request):
"""Handle HTTP request."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WPS10DescribeProcessHandler:
"""WPS 1.0 DescribeProcess service handler."""
def get_decoder(request):
"""Get the WPS request decoder."""
if request.method == 'GET':
return WPS10DescribeProcessKVPDecoder(request.GET)
else:
return WPS10DescribeProcessXMLDecod... | the_stack_v2_python_sparse | eoxserver/services/ows/wps/v10/describeprocess.py | EOxServer/eoxserver | train | 30 |
ada8786fe83991455096eeea52ced5ea56796943 | [
"super().__init__(*args, **kwargs)\nif self.instance.pk:\n self.fields['food_name'].initial = self.instance.food.name",
"ingredient = super().save(commit=False)\nfood_obj, created = Food.objects.get_or_create(name=self.cleaned_data['food_name'])\ningredient.food = food_obj\nif commit:\n ingredient.save()\nr... | <|body_start_0|>
super().__init__(*args, **kwargs)
if self.instance.pk:
self.fields['food_name'].initial = self.instance.food.name
<|end_body_0|>
<|body_start_1|>
ingredient = super().save(commit=False)
food_obj, created = Food.objects.get_or_create(name=self.cleaned_data['f... | IngredientForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IngredientForm:
def __init__(self, *args, **kwargs):
"""Fill in food_name field with name of the food of the ingredient when updating a recipe."""
<|body_0|>
def save(self, commit):
"""When creating a new ingredient: Check if a food with the given name is already sto... | stack_v2_sparse_classes_36k_train_032327 | 6,686 | no_license | [
{
"docstring": "Fill in food_name field with name of the food of the ingredient when updating a recipe.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "When creating a new ingredient: Check if a food with the given name is already stored in the databas... | 2 | stack_v2_sparse_classes_30k_train_013629 | Implement the Python class `IngredientForm` described below.
Class description:
Implement the IngredientForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Fill in food_name field with name of the food of the ingredient when updating a recipe.
- def save(self, commit): When creating a... | Implement the Python class `IngredientForm` described below.
Class description:
Implement the IngredientForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Fill in food_name field with name of the food of the ingredient when updating a recipe.
- def save(self, commit): When creating a... | 2de9abaa8fdfcee5d9e92bb93efa9ed207c19824 | <|skeleton|>
class IngredientForm:
def __init__(self, *args, **kwargs):
"""Fill in food_name field with name of the food of the ingredient when updating a recipe."""
<|body_0|>
def save(self, commit):
"""When creating a new ingredient: Check if a food with the given name is already sto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IngredientForm:
def __init__(self, *args, **kwargs):
"""Fill in food_name field with name of the food of the ingredient when updating a recipe."""
super().__init__(*args, **kwargs)
if self.instance.pk:
self.fields['food_name'].initial = self.instance.food.name
def save... | the_stack_v2_python_sparse | recipes/forms.py | tschuelia/cake_recipe_website | train | 0 | |
0582fe1d0c3100afd8d4baa29f0fbca1dbf47097 | [
"super(SimpleModel, self).__init__()\nself.blocks = [layers.Flatten(name='flatten')]\nself.blocks.append(build_linear_layers(hidden_dim, 1, name='fc0', **kwargs))\nfor i in range(num_residual_linear_blocks):\n self.blocks.append(ResLinearBlock(hidden_dim, num_layers_per_block, name='res_fcs' + str(i + 1), **kwar... | <|body_start_0|>
super(SimpleModel, self).__init__()
self.blocks = [layers.Flatten(name='flatten')]
self.blocks.append(build_linear_layers(hidden_dim, 1, name='fc0', **kwargs))
for i in range(num_residual_linear_blocks):
self.blocks.append(ResLinearBlock(hidden_dim, num_layer... | Simple model architecture with a point or Gaussian embedder. | SimpleModel | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleModel:
"""Simple model architecture with a point or Gaussian embedder."""
def __init__(self, output_shape, embedder=TYPE_EMBEDDER_POINT, hidden_dim=1024, num_residual_linear_blocks=2, num_layers_per_block=2, **kwargs):
"""Initializer. Args: output_shape: A tuple for the shape o... | stack_v2_sparse_classes_36k_train_032328 | 30,548 | permissive | [
{
"docstring": "Initializer. Args: output_shape: A tuple for the shape of the output. embedder: A string for the type of the embedder. hidden_dim: An integer for the dimension of linear layers. num_residual_linear_blocks: An integer for the number of residual linear blocks. num_layers_per_block: An integer for ... | 2 | null | Implement the Python class `SimpleModel` described below.
Class description:
Simple model architecture with a point or Gaussian embedder.
Method signatures and docstrings:
- def __init__(self, output_shape, embedder=TYPE_EMBEDDER_POINT, hidden_dim=1024, num_residual_linear_blocks=2, num_layers_per_block=2, **kwargs):... | Implement the Python class `SimpleModel` described below.
Class description:
Simple model architecture with a point or Gaussian embedder.
Method signatures and docstrings:
- def __init__(self, output_shape, embedder=TYPE_EMBEDDER_POINT, hidden_dim=1024, num_residual_linear_blocks=2, num_layers_per_block=2, **kwargs):... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class SimpleModel:
"""Simple model architecture with a point or Gaussian embedder."""
def __init__(self, output_shape, embedder=TYPE_EMBEDDER_POINT, hidden_dim=1024, num_residual_linear_blocks=2, num_layers_per_block=2, **kwargs):
"""Initializer. Args: output_shape: A tuple for the shape o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleModel:
"""Simple model architecture with a point or Gaussian embedder."""
def __init__(self, output_shape, embedder=TYPE_EMBEDDER_POINT, hidden_dim=1024, num_residual_linear_blocks=2, num_layers_per_block=2, **kwargs):
"""Initializer. Args: output_shape: A tuple for the shape of the output.... | the_stack_v2_python_sparse | poem/cv_mim/models.py | Jimmy-INL/google-research | train | 1 |
b28584b8bbd98555f50b21a94c76f7dbfe38ef70 | [
"super().__init__(hass, LOGGER, name=f'proxmox_coordinator_{host_name}_{node_name}', update_interval=timedelta(seconds=UPDATE_INTERVAL))\nself.hass = hass\nself.config_entry: ConfigEntry = self.config_entry\nself.proxmox = proxmox\nself.node_name = node_name",
"def poll_api() -> dict[str, Any] | None:\n \"\"\"... | <|body_start_0|>
super().__init__(hass, LOGGER, name=f'proxmox_coordinator_{host_name}_{node_name}', update_interval=timedelta(seconds=UPDATE_INTERVAL))
self.hass = hass
self.config_entry: ConfigEntry = self.config_entry
self.proxmox = proxmox
self.node_name = node_name
<|end_bod... | Proxmox VE Node data update coordinator. | ProxmoxNodeCoordinator | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProxmoxNodeCoordinator:
"""Proxmox VE Node data update coordinator."""
def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, node_name: str) -> None:
"""Initialize the Proxmox Node coordinator."""
<|body_0|>
async def _async_update_data(self) -> Pr... | stack_v2_sparse_classes_36k_train_032329 | 15,228 | permissive | [
{
"docstring": "Initialize the Proxmox Node coordinator.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, node_name: str) -> None"
},
{
"docstring": "Update data for Proxmox Node.",
"name": "_async_update_data",
"signature":... | 2 | null | Implement the Python class `ProxmoxNodeCoordinator` described below.
Class description:
Proxmox VE Node data update coordinator.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, node_name: str) -> None: Initialize the Proxmox Node coordinator.
- async de... | Implement the Python class `ProxmoxNodeCoordinator` described below.
Class description:
Proxmox VE Node data update coordinator.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, node_name: str) -> None: Initialize the Proxmox Node coordinator.
- async de... | 8548d9999ddd54f13d6a307e013abcb8c897a74e | <|skeleton|>
class ProxmoxNodeCoordinator:
"""Proxmox VE Node data update coordinator."""
def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, node_name: str) -> None:
"""Initialize the Proxmox Node coordinator."""
<|body_0|>
async def _async_update_data(self) -> Pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProxmoxNodeCoordinator:
"""Proxmox VE Node data update coordinator."""
def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, node_name: str) -> None:
"""Initialize the Proxmox Node coordinator."""
super().__init__(hass, LOGGER, name=f'proxmox_coordinator_{host_name}... | the_stack_v2_python_sparse | custom_components/proxmoxve/coordinator.py | bacco007/HomeAssistantConfig | train | 98 |
44fb874fc705da6c8900dd92f13ecda7e7798d31 | [
"assert isinstance(poly, Polygon)\nassert isinstance(splitter, LineString)\nunion = poly.boundary.union(splitter)\nreturn [pg for pg in polygonize(union) if poly.contains(pg.representative_point())]",
"if splitter.type in ('Polygon', 'MultiPolygon'):\n splitter = splitter.boundary\nassert isinstance(line, Line... | <|body_start_0|>
assert isinstance(poly, Polygon)
assert isinstance(splitter, LineString)
union = poly.boundary.union(splitter)
return [pg for pg in polygonize(union) if poly.contains(pg.representative_point())]
<|end_body_0|>
<|body_start_1|>
if splitter.type in ('Polygon', 'Mu... | SplitOp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SplitOp:
def _split_polygon_with_line(poly, splitter):
"""Split a Polygon with a LineString"""
<|body_0|>
def _split_line_with_line(line, splitter):
"""Split a LineString with another (Multi)LineString or (Multi)Polygon"""
<|body_1|>
def _split_line_with... | stack_v2_sparse_classes_36k_train_032330 | 17,864 | permissive | [
{
"docstring": "Split a Polygon with a LineString",
"name": "_split_polygon_with_line",
"signature": "def _split_polygon_with_line(poly, splitter)"
},
{
"docstring": "Split a LineString with another (Multi)LineString or (Multi)Polygon",
"name": "_split_line_with_line",
"signature": "def ... | 5 | null | Implement the Python class `SplitOp` described below.
Class description:
Implement the SplitOp class.
Method signatures and docstrings:
- def _split_polygon_with_line(poly, splitter): Split a Polygon with a LineString
- def _split_line_with_line(line, splitter): Split a LineString with another (Multi)LineString or (M... | Implement the Python class `SplitOp` described below.
Class description:
Implement the SplitOp class.
Method signatures and docstrings:
- def _split_polygon_with_line(poly, splitter): Split a Polygon with a LineString
- def _split_line_with_line(line, splitter): Split a LineString with another (Multi)LineString or (M... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class SplitOp:
def _split_polygon_with_line(poly, splitter):
"""Split a Polygon with a LineString"""
<|body_0|>
def _split_line_with_line(line, splitter):
"""Split a LineString with another (Multi)LineString or (Multi)Polygon"""
<|body_1|>
def _split_line_with... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SplitOp:
def _split_polygon_with_line(poly, splitter):
"""Split a Polygon with a LineString"""
assert isinstance(poly, Polygon)
assert isinstance(splitter, LineString)
union = poly.boundary.union(splitter)
return [pg for pg in polygonize(union) if poly.contains(pg.repre... | the_stack_v2_python_sparse | Shapely_numpy/source/shapely/ops.py | ryfeus/lambda-packs | train | 1,283 | |
8cd089e5fe8ac3149330de8c17073ee2b4a187c4 | [
"super(UnaryTransformation, self).__init__(operator, inner_expression)\nself.operator = operator\nself.inner_expression = inner_expression",
"_validate_operator_name(self.operator, UnaryTransformation.SUPPORTED_OPERATORS)\nif not isinstance(self.inner_expression, Expression):\n raise TypeError(u'Expected Expre... | <|body_start_0|>
super(UnaryTransformation, self).__init__(operator, inner_expression)
self.operator = operator
self.inner_expression = inner_expression
<|end_body_0|>
<|body_start_1|>
_validate_operator_name(self.operator, UnaryTransformation.SUPPORTED_OPERATORS)
if not isinsta... | An expression that modifies an underlying expression with a unary operator. | UnaryTransformation | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnaryTransformation:
"""An expression that modifies an underlying expression with a unary operator."""
def __init__(self, operator, inner_expression):
"""Construct a UnaryExpression that modifies the given inner expression."""
<|body_0|>
def validate(self):
"""Va... | stack_v2_sparse_classes_36k_train_032331 | 41,432 | permissive | [
{
"docstring": "Construct a UnaryExpression that modifies the given inner expression.",
"name": "__init__",
"signature": "def __init__(self, operator, inner_expression)"
},
{
"docstring": "Validate that the UnaryTransformation is correctly representable.",
"name": "validate",
"signature"... | 5 | stack_v2_sparse_classes_30k_train_018285 | Implement the Python class `UnaryTransformation` described below.
Class description:
An expression that modifies an underlying expression with a unary operator.
Method signatures and docstrings:
- def __init__(self, operator, inner_expression): Construct a UnaryExpression that modifies the given inner expression.
- d... | Implement the Python class `UnaryTransformation` described below.
Class description:
An expression that modifies an underlying expression with a unary operator.
Method signatures and docstrings:
- def __init__(self, operator, inner_expression): Construct a UnaryExpression that modifies the given inner expression.
- d... | 4511793281698bd55e63fd7a3f25f9cb094084d4 | <|skeleton|>
class UnaryTransformation:
"""An expression that modifies an underlying expression with a unary operator."""
def __init__(self, operator, inner_expression):
"""Construct a UnaryExpression that modifies the given inner expression."""
<|body_0|>
def validate(self):
"""Va... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnaryTransformation:
"""An expression that modifies an underlying expression with a unary operator."""
def __init__(self, operator, inner_expression):
"""Construct a UnaryExpression that modifies the given inner expression."""
super(UnaryTransformation, self).__init__(operator, inner_expr... | the_stack_v2_python_sparse | graphql_compiler/compiler/expressions.py | jb-kensho/graphql-compiler | train | 0 |
66c5f3cc8291e25adf38da6756c651172922bb08 | [
"Any.requireIsFileNonEmpty(filePath)\nself._filePath = filePath\nself._data = None\nself._loadFile()",
"Any.requireIsFileNonEmpty(sourceFile)\nfor item in self._data:\n itemAsDict = dict(item)\n if itemAsDict['file'] == sourceFile:\n return itemAsDict['command']\nraise ValueError('%s: No compile info... | <|body_start_0|>
Any.requireIsFileNonEmpty(filePath)
self._filePath = filePath
self._data = None
self._loadFile()
<|end_body_0|>
<|body_start_1|>
Any.requireIsFileNonEmpty(sourceFile)
for item in self._data:
itemAsDict = dict(item)
if itemAsDict['... | CMakeCompileCommands | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CMakeCompileCommands:
def __init__(self, filePath: str) -> None:
"""Creates an instance for accessing the specified CMake compile commands file, e.g. in case of BST.py found under 'build/<platformName>/compile_commands.json'."""
<|body_0|>
def getCompilerCommand(self, source... | stack_v2_sparse_classes_36k_train_032332 | 5,136 | permissive | [
{
"docstring": "Creates an instance for accessing the specified CMake compile commands file, e.g. in case of BST.py found under 'build/<platformName>/compile_commands.json'.",
"name": "__init__",
"signature": "def __init__(self, filePath: str) -> None"
},
{
"docstring": "Returns a long string wi... | 5 | null | Implement the Python class `CMakeCompileCommands` described below.
Class description:
Implement the CMakeCompileCommands class.
Method signatures and docstrings:
- def __init__(self, filePath: str) -> None: Creates an instance for accessing the specified CMake compile commands file, e.g. in case of BST.py found under... | Implement the Python class `CMakeCompileCommands` described below.
Class description:
Implement the CMakeCompileCommands class.
Method signatures and docstrings:
- def __init__(self, filePath: str) -> None: Creates an instance for accessing the specified CMake compile commands file, e.g. in case of BST.py found under... | cec3efde5a726de19dbe088281bc4beada5c1475 | <|skeleton|>
class CMakeCompileCommands:
def __init__(self, filePath: str) -> None:
"""Creates an instance for accessing the specified CMake compile commands file, e.g. in case of BST.py found under 'build/<platformName>/compile_commands.json'."""
<|body_0|>
def getCompilerCommand(self, source... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CMakeCompileCommands:
def __init__(self, filePath: str) -> None:
"""Creates an instance for accessing the specified CMake compile commands file, e.g. in case of BST.py found under 'build/<platformName>/compile_commands.json'."""
Any.requireIsFileNonEmpty(filePath)
self._filePath = file... | the_stack_v2_python_sparse | include/ToolBOSCore/Storage/CMakeCompileCommands.py | HRI-EU/ToolBOSCore | train | 7 | |
e76ea67c34129393b23335ae1ab31ba755bc250f | [
"try:\n run_permission_hooks('clone', obj)\nexcept PermissionDenied:\n return False\nelse:\n perm_codename = self.get_perm_codename('add')\n return self.user_has_specific_permission(user, perm_codename)",
"try:\n run_permission_hooks('update', obj)\nexcept PermissionDenied:\n return False\nelse:... | <|body_start_0|>
try:
run_permission_hooks('clone', obj)
except PermissionDenied:
return False
else:
perm_codename = self.get_perm_codename('add')
return self.user_has_specific_permission(user, perm_codename)
<|end_body_0|>
<|body_start_1|>
... | Custom permission helper class for Wagtail Omni forms | WagtailOmniFormPermissionHelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WagtailOmniFormPermissionHelper:
"""Custom permission helper class for Wagtail Omni forms"""
def user_can_clone_obj(self, user, obj):
"""Checks that the user has permission to clone a form in the system :param user: Logged in user instance :param obj: OmniForm model instance :return:... | stack_v2_sparse_classes_36k_train_032333 | 22,300 | permissive | [
{
"docstring": "Checks that the user has permission to clone a form in the system :param user: Logged in user instance :param obj: OmniForm model instance :return: bool - True if the user can create a form instance, otherwise false",
"name": "user_can_clone_obj",
"signature": "def user_can_clone_obj(sel... | 3 | stack_v2_sparse_classes_30k_train_001989 | Implement the Python class `WagtailOmniFormPermissionHelper` described below.
Class description:
Custom permission helper class for Wagtail Omni forms
Method signatures and docstrings:
- def user_can_clone_obj(self, user, obj): Checks that the user has permission to clone a form in the system :param user: Logged in u... | Implement the Python class `WagtailOmniFormPermissionHelper` described below.
Class description:
Custom permission helper class for Wagtail Omni forms
Method signatures and docstrings:
- def user_can_clone_obj(self, user, obj): Checks that the user has permission to clone a form in the system :param user: Logged in u... | 0c96162445f8b5ddf7f326f6b0a2e6ec239c4bd5 | <|skeleton|>
class WagtailOmniFormPermissionHelper:
"""Custom permission helper class for Wagtail Omni forms"""
def user_can_clone_obj(self, user, obj):
"""Checks that the user has permission to clone a form in the system :param user: Logged in user instance :param obj: OmniForm model instance :return:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WagtailOmniFormPermissionHelper:
"""Custom permission helper class for Wagtail Omni forms"""
def user_can_clone_obj(self, user, obj):
"""Checks that the user has permission to clone a form in the system :param user: Logged in user instance :param obj: OmniForm model instance :return: bool - True ... | the_stack_v2_python_sparse | omniforms/wagtail/wagtail_hooks.py | omni-digital/omni-forms | train | 6 |
2e75f3f70ab13799d3b163d4f2873035a0de5839 | [
"clickndrag.Plane.__init__(self, name, pygame.Rect((0, 0), (0, 0)))\nself.padding = padding\nself.background_color = BACKGROUND_COLOR\nif background_color is not None:\n self.background_color = background_color\nreturn",
"self.image = pygame.Surface(self.rect.size)\nself.image.fill(self.background_color)\ndraw... | <|body_start_0|>
clickndrag.Plane.__init__(self, name, pygame.Rect((0, 0), (0, 0)))
self.padding = padding
self.background_color = BACKGROUND_COLOR
if background_color is not None:
self.background_color = background_color
return
<|end_body_0|>
<|body_start_1|>
... | A Container for Planes. If a subplane is added via sub(), the container places it below any existing subplanes and resizes itself to fit the width and height of the subplanes. Additional attributes: Container.padding Space between subplanes and border, in pixels Container.background_color The original background color ... | Container | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Container:
"""A Container for Planes. If a subplane is added via sub(), the container places it below any existing subplanes and resizes itself to fit the width and height of the subplanes. Additional attributes: Container.padding Space between subplanes and border, in pixels Container.background... | stack_v2_sparse_classes_36k_train_032334 | 27,668 | permissive | [
{
"docstring": "Initialise. Container.image is initialised to a 0x0 px Surface.",
"name": "__init__",
"signature": "def __init__(self, name, padding=0, background_color=None)"
},
{
"docstring": "Redraw Container.image from the dimensions in Containter.rect. This also creates a new Container.rend... | 5 | stack_v2_sparse_classes_30k_train_020936 | Implement the Python class `Container` described below.
Class description:
A Container for Planes. If a subplane is added via sub(), the container places it below any existing subplanes and resizes itself to fit the width and height of the subplanes. Additional attributes: Container.padding Space between subplanes and... | Implement the Python class `Container` described below.
Class description:
A Container for Planes. If a subplane is added via sub(), the container places it below any existing subplanes and resizes itself to fit the width and height of the subplanes. Additional attributes: Container.padding Space between subplanes and... | c2fc3d4e9beedb8487cfa4bfa13bdf55ec36af97 | <|skeleton|>
class Container:
"""A Container for Planes. If a subplane is added via sub(), the container places it below any existing subplanes and resizes itself to fit the width and height of the subplanes. Additional attributes: Container.padding Space between subplanes and border, in pixels Container.background... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Container:
"""A Container for Planes. If a subplane is added via sub(), the container places it below any existing subplanes and resizes itself to fit the width and height of the subplanes. Additional attributes: Container.padding Space between subplanes and border, in pixels Container.background_color The or... | the_stack_v2_python_sparse | reference_scripts/clickndrag-0.4.1/clickndrag/gui.py | stivosaurus/rpi-snippets | train | 1 |
fc1a5c6b55e0f1a60e4afc8804e4b9252dacbade | [
"from htk.lib.iterable.utils import get_workflow_id\nsign_up_workflow_id = get_workflow_id('account.sign_up')\nif sign_up_workflow_id is not None:\n payload = {'dataFields': {'userId': user.id, 'date_joined': user.date_joined.strftime(ITERABLE_DATE_FORMAT)}}\n self.trigger_workflow(user.profile.confirmed_emai... | <|body_start_0|>
from htk.lib.iterable.utils import get_workflow_id
sign_up_workflow_id = get_workflow_id('account.sign_up')
if sign_up_workflow_id is not None:
payload = {'dataFields': {'userId': user.id, 'date_joined': user.date_joined.strftime(ITERABLE_DATE_FORMAT)}}
s... | HTK-flavored Iterable API client This extends IterableAPIClient, which is more vanilla | HtkIterableAPIClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtkIterableAPIClient:
"""HTK-flavored Iterable API client This extends IterableAPIClient, which is more vanilla"""
def notify_sign_up(self, user):
"""Notify Iterable of a `user` sign up event Based on HTK settings, either track an event, trigger a workflow, or both"""
<|body_... | stack_v2_sparse_classes_36k_train_032335 | 7,919 | permissive | [
{
"docstring": "Notify Iterable of a `user` sign up event Based on HTK settings, either track an event, trigger a workflow, or both",
"name": "notify_sign_up",
"signature": "def notify_sign_up(self, user)"
},
{
"docstring": "Notify Iterable of a `user` activation event",
"name": "notify_acco... | 3 | null | Implement the Python class `HtkIterableAPIClient` described below.
Class description:
HTK-flavored Iterable API client This extends IterableAPIClient, which is more vanilla
Method signatures and docstrings:
- def notify_sign_up(self, user): Notify Iterable of a `user` sign up event Based on HTK settings, either track... | Implement the Python class `HtkIterableAPIClient` described below.
Class description:
HTK-flavored Iterable API client This extends IterableAPIClient, which is more vanilla
Method signatures and docstrings:
- def notify_sign_up(self, user): Notify Iterable of a `user` sign up event Based on HTK settings, either track... | 935c4913e33d959f8c29583825f72b238f85b380 | <|skeleton|>
class HtkIterableAPIClient:
"""HTK-flavored Iterable API client This extends IterableAPIClient, which is more vanilla"""
def notify_sign_up(self, user):
"""Notify Iterable of a `user` sign up event Based on HTK settings, either track an event, trigger a workflow, or both"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HtkIterableAPIClient:
"""HTK-flavored Iterable API client This extends IterableAPIClient, which is more vanilla"""
def notify_sign_up(self, user):
"""Notify Iterable of a `user` sign up event Based on HTK settings, either track an event, trigger a workflow, or both"""
from htk.lib.iterabl... | the_stack_v2_python_sparse | lib/iterable/api.py | hacktoolkit/django-htk | train | 210 |
9c18d20ff33e810e02ef7b4deeb9239dc0e44ce7 | [
"if request.method in CONTENT_TYPE_METHODS:\n if 'CONTENT_TYPE' not in request.META:\n return HttpResponse('POST/PUT requests must include a Content-Type header.', status=415)\nif 'HTTP_ACCEPT' not in request.META:\n log.warning('Accept header is recommended in all requests.')",
"if isinstance(ex, Us... | <|body_start_0|>
if request.method in CONTENT_TYPE_METHODS:
if 'CONTENT_TYPE' not in request.META:
return HttpResponse('POST/PUT requests must include a Content-Type header.', status=415)
if 'HTTP_ACCEPT' not in request.META:
log.warning('Accept header is recommen... | RestAuthMiddleware | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestAuthMiddleware:
def process_request(self, request):
"""Middleware to ensure required headers are present."""
<|body_0|>
def process_exception(self, request, ex):
"""Handle RestAuth related exceptions."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_032336 | 2,594 | no_license | [
{
"docstring": "Middleware to ensure required headers are present.",
"name": "process_request",
"signature": "def process_request(self, request)"
},
{
"docstring": "Handle RestAuth related exceptions.",
"name": "process_exception",
"signature": "def process_exception(self, request, ex)"
... | 2 | stack_v2_sparse_classes_30k_train_015337 | Implement the Python class `RestAuthMiddleware` described below.
Class description:
Implement the RestAuthMiddleware class.
Method signatures and docstrings:
- def process_request(self, request): Middleware to ensure required headers are present.
- def process_exception(self, request, ex): Handle RestAuth related exc... | Implement the Python class `RestAuthMiddleware` described below.
Class description:
Implement the RestAuthMiddleware class.
Method signatures and docstrings:
- def process_request(self, request): Middleware to ensure required headers are present.
- def process_exception(self, request, ex): Handle RestAuth related exc... | 60769f6b4965836b2220878cfa2e1bc403d8f8a3 | <|skeleton|>
class RestAuthMiddleware:
def process_request(self, request):
"""Middleware to ensure required headers are present."""
<|body_0|>
def process_exception(self, request, ex):
"""Handle RestAuth related exceptions."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestAuthMiddleware:
def process_request(self, request):
"""Middleware to ensure required headers are present."""
if request.method in CONTENT_TYPE_METHODS:
if 'CONTENT_TYPE' not in request.META:
return HttpResponse('POST/PUT requests must include a Content-Type head... | the_stack_v2_python_sparse | env/lib/python3.6/site-packages/RestAuth/common/middleware.py | sachinlokesh05/login-registration-forgotpassword-and-resetpassword-using-django-rest-framework- | train | 3 | |
1155b519a9a3255c0864d4760cad13aafd5602c2 | [
"if '_xml_ns' in kwargs:\n self._xml_ns = kwargs['_xml_ns']\nif '_xml_ns_key' in kwargs:\n self._xml_ns_key = kwargs['_xml_ns_key']\nself.index = index\nsuper(XYVertexType, self).__init__(X=X, Y=Y, **kwargs)",
"if array is None:\n return None\nif isinstance(array, (numpy.ndarray, list, tuple)):\n if l... | <|body_start_0|>
if '_xml_ns' in kwargs:
self._xml_ns = kwargs['_xml_ns']
if '_xml_ns_key' in kwargs:
self._xml_ns_key = kwargs['_xml_ns_key']
self.index = index
super(XYVertexType, self).__init__(X=X, Y=Y, **kwargs)
<|end_body_0|>
<|body_start_1|>
if arr... | An array element of XYType. | XYVertexType | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XYVertexType:
"""An array element of XYType."""
def __init__(self, X=None, Y=None, index=None, **kwargs):
"""Parameters ---------- X : float Y : float index : int kwargs"""
<|body_0|>
def from_array(cls, array, index=1):
"""Create from an array type entry. Parame... | stack_v2_sparse_classes_36k_train_032337 | 10,131 | permissive | [
{
"docstring": "Parameters ---------- X : float Y : float index : int kwargs",
"name": "__init__",
"signature": "def __init__(self, X=None, Y=None, index=None, **kwargs)"
},
{
"docstring": "Create from an array type entry. Parameters ---------- array: numpy.ndarray|list|tuple assumed [X, Y] inde... | 2 | stack_v2_sparse_classes_30k_train_002620 | Implement the Python class `XYVertexType` described below.
Class description:
An array element of XYType.
Method signatures and docstrings:
- def __init__(self, X=None, Y=None, index=None, **kwargs): Parameters ---------- X : float Y : float index : int kwargs
- def from_array(cls, array, index=1): Create from an arr... | Implement the Python class `XYVertexType` described below.
Class description:
An array element of XYType.
Method signatures and docstrings:
- def __init__(self, X=None, Y=None, index=None, **kwargs): Parameters ---------- X : float Y : float index : int kwargs
- def from_array(cls, array, index=1): Create from an arr... | de1b1886f161a83b6c89aadc7a2c7cfc4892ef81 | <|skeleton|>
class XYVertexType:
"""An array element of XYType."""
def __init__(self, X=None, Y=None, index=None, **kwargs):
"""Parameters ---------- X : float Y : float index : int kwargs"""
<|body_0|>
def from_array(cls, array, index=1):
"""Create from an array type entry. Parame... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XYVertexType:
"""An array element of XYType."""
def __init__(self, X=None, Y=None, index=None, **kwargs):
"""Parameters ---------- X : float Y : float index : int kwargs"""
if '_xml_ns' in kwargs:
self._xml_ns = kwargs['_xml_ns']
if '_xml_ns_key' in kwargs:
... | the_stack_v2_python_sparse | sarpy/io/phase_history/cphd1_elements/blocks.py | ngageoint/sarpy | train | 192 |
2516b1514a316d456480ad995ee71297c6b7b313 | [
"self.head = head\nl = 0\ncurr = head\nwhile curr is not None:\n curr = curr.next\n l += 1\nself.len = l",
"r = randrange(self.len)\nif r == 0:\n return self.head.val\nk = 0\ncurr = self.head\nwhile k < r:\n curr = curr.next\n k += 1\nreturn curr.val"
] | <|body_start_0|>
self.head = head
l = 0
curr = head
while curr is not None:
curr = curr.next
l += 1
self.len = l
<|end_body_0|>
<|body_start_1|>
r = randrange(self.len)
if r == 0:
return self.head.val
k = 0
curr... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
<|body_0|>
def getRandom(self):
"""Returns a random node's value. :rtype: int"""
... | stack_v2_sparse_classes_36k_train_032338 | 1,024 | no_license | [
{
"docstring": "@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode",
"name": "__init__",
"signature": "def __init__(self, head)"
},
{
"docstring": "Returns a random node's value. :rtype: int",
"name": "g... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode
- def getRan... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode
- def getRan... | 2337b5031d4dfe033a471cea8ab4aa5ab66122d0 | <|skeleton|>
class Solution:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
<|body_0|>
def getRandom(self):
"""Returns a random node's value. :rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
self.head = head
l = 0
curr = head
while curr is not None:
curr = curr.next
... | the_stack_v2_python_sparse | 382.py | shants/LeetCodePy | train | 0 | |
74740fad7b96eeb46118e5d97bf81abef5df8f6e | [
"super().__init__(coordinator, device, 'power', 'Energy usage', f'phase_{phase}_current')\nself._attr_name = f'Phase {phase} current'\nself._phase = phase",
"phase_sensor = getattr(self.coordinator.data, f'phase{self._phase}', None)\nif phase_sensor is None:\n return None\nreturn phase_sensor.current"
] | <|body_start_0|>
super().__init__(coordinator, device, 'power', 'Energy usage', f'phase_{phase}_current')
self._attr_name = f'Phase {phase} current'
self._phase = phase
<|end_body_0|>
<|body_start_1|>
phase_sensor = getattr(self.coordinator.data, f'phase{self._phase}', None)
if ... | The current current of a single phase. | PhaseCurrentSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhaseCurrentSensor:
"""The current current of a single phase."""
def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, phase: int) -> None:
"""Initialize the current phase sensor."""
<|body_0|>
def get_sensor(self) -> YoulessSensor | None:
... | stack_v2_sparse_classes_36k_train_032339 | 11,812 | permissive | [
{
"docstring": "Initialize the current phase sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, phase: int) -> None"
},
{
"docstring": "Get the sensor value from the coordinator for phase current.",
"name": "get_sensor"... | 2 | null | Implement the Python class `PhaseCurrentSensor` described below.
Class description:
The current current of a single phase.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, phase: int) -> None: Initialize the current phase sensor.
- def get_sensor(self... | Implement the Python class `PhaseCurrentSensor` described below.
Class description:
The current current of a single phase.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, phase: int) -> None: Initialize the current phase sensor.
- def get_sensor(self... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class PhaseCurrentSensor:
"""The current current of a single phase."""
def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, phase: int) -> None:
"""Initialize the current phase sensor."""
<|body_0|>
def get_sensor(self) -> YoulessSensor | None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PhaseCurrentSensor:
"""The current current of a single phase."""
def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, phase: int) -> None:
"""Initialize the current phase sensor."""
super().__init__(coordinator, device, 'power', 'Energy usage', f'phase_{phase}_c... | the_stack_v2_python_sparse | homeassistant/components/youless/sensor.py | home-assistant/core | train | 35,501 |
821fec272697c24eff3eb5cc4075736c9d08db31 | [
"if obj is None:\n return self.add_fieldsets\nreturn super(ApplicationAdmin, self).get_fieldsets(request, obj=obj)",
"if obj is None:\n kwargs = kwargs.copy()\n kwargs['form'] = self.add_form\n kwargs['fields'] = flatten_fieldsets(self.add_fieldsets)\nreturn super(ApplicationAdmin, self).get_form(requ... | <|body_start_0|>
if obj is None:
return self.add_fieldsets
return super(ApplicationAdmin, self).get_fieldsets(request, obj=obj)
<|end_body_0|>
<|body_start_1|>
if obj is None:
kwargs = kwargs.copy()
kwargs['form'] = self.add_form
kwargs['fields'] ... | The model admin for the OAuth application model. The default model admin provided by django-oauth-toolkit does not provide help text for the majority of the fields, so this admin uses a custom form which does provide the help text. | ApplicationAdmin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplicationAdmin:
"""The model admin for the OAuth application model. The default model admin provided by django-oauth-toolkit does not provide help text for the majority of the fields, so this admin uses a custom form which does provide the help text."""
def get_fieldsets(self, request, obj... | stack_v2_sparse_classes_36k_train_032340 | 5,321 | permissive | [
{
"docstring": "Return the appropriate fieldset. Args: request (django.http.HttpRequest): The current HTTP request. obj (reviewboard.oauth.models.Application, optional): The application being edited, if it already exists. Returns: tuple: The fieldset for either changing an Application (i.e., when ``obj is not N... | 3 | null | Implement the Python class `ApplicationAdmin` described below.
Class description:
The model admin for the OAuth application model. The default model admin provided by django-oauth-toolkit does not provide help text for the majority of the fields, so this admin uses a custom form which does provide the help text.
Meth... | Implement the Python class `ApplicationAdmin` described below.
Class description:
The model admin for the OAuth application model. The default model admin provided by django-oauth-toolkit does not provide help text for the majority of the fields, so this admin uses a custom form which does provide the help text.
Meth... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class ApplicationAdmin:
"""The model admin for the OAuth application model. The default model admin provided by django-oauth-toolkit does not provide help text for the majority of the fields, so this admin uses a custom form which does provide the help text."""
def get_fieldsets(self, request, obj... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApplicationAdmin:
"""The model admin for the OAuth application model. The default model admin provided by django-oauth-toolkit does not provide help text for the majority of the fields, so this admin uses a custom form which does provide the help text."""
def get_fieldsets(self, request, obj=None):
... | the_stack_v2_python_sparse | reviewboard/oauth/admin.py | reviewboard/reviewboard | train | 1,141 |
5b158450fde38f3a7b4542d4803c934a4fb7076f | [
"use_ssl = url.scheme == 'https'\nport = url.port or (443 if use_ssl else 80)\nreturn {'host': url.hostname, 'port': port, 'path_prefix': url.path, 'scheme': url.scheme}",
"opts = super()._get_options_from_host_urls(urls)\nbasic_auth = (urls[0].username, urls[0].password)\nif any(((url.username, url.password) != ... | <|body_start_0|>
use_ssl = url.scheme == 'https'
port = url.port or (443 if use_ssl else 80)
return {'host': url.hostname, 'port': port, 'path_prefix': url.path, 'scheme': url.scheme}
<|end_body_0|>
<|body_start_1|>
opts = super()._get_options_from_host_urls(urls)
basic_auth = (... | Elasticsearch8SearchBackend | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Elasticsearch8SearchBackend:
def _get_host_config_from_url(self, url):
"""Given a parsed URL, return the host configuration to be added to self.hosts"""
<|body_0|>
def _get_options_from_host_urls(self, urls):
"""Given a list of parsed URLs, return a dict of additiona... | stack_v2_sparse_classes_36k_train_032341 | 2,690 | permissive | [
{
"docstring": "Given a parsed URL, return the host configuration to be added to self.hosts",
"name": "_get_host_config_from_url",
"signature": "def _get_host_config_from_url(self, url)"
},
{
"docstring": "Given a list of parsed URLs, return a dict of additional options to be passed into the Ela... | 2 | stack_v2_sparse_classes_30k_train_016102 | Implement the Python class `Elasticsearch8SearchBackend` described below.
Class description:
Implement the Elasticsearch8SearchBackend class.
Method signatures and docstrings:
- def _get_host_config_from_url(self, url): Given a parsed URL, return the host configuration to be added to self.hosts
- def _get_options_fro... | Implement the Python class `Elasticsearch8SearchBackend` described below.
Class description:
Implement the Elasticsearch8SearchBackend class.
Method signatures and docstrings:
- def _get_host_config_from_url(self, url): Given a parsed URL, return the host configuration to be added to self.hosts
- def _get_options_fro... | 06a7bc6124bf62675c09fbe0a4ed9bbac183e025 | <|skeleton|>
class Elasticsearch8SearchBackend:
def _get_host_config_from_url(self, url):
"""Given a parsed URL, return the host configuration to be added to self.hosts"""
<|body_0|>
def _get_options_from_host_urls(self, urls):
"""Given a list of parsed URLs, return a dict of additiona... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Elasticsearch8SearchBackend:
def _get_host_config_from_url(self, url):
"""Given a parsed URL, return the host configuration to be added to self.hosts"""
use_ssl = url.scheme == 'https'
port = url.port or (443 if use_ssl else 80)
return {'host': url.hostname, 'port': port, 'path... | the_stack_v2_python_sparse | wagtail/search/backends/elasticsearch8.py | wagtail/wagtail | train | 12,974 | |
83a8f86694ccd846525add38c9f8923c0d9d3637 | [
"app_config = root_path / APP_CONFIG_FILE_NAME\nmbed_os_ref = root_path / MBED_OS_REFERENCE_FILE_NAME\ncmakelists_file = root_path / CMAKELISTS_FILE_NAME\nmain_cpp = root_path / MAIN_CPP_FILE_NAME\ngitignore = root_path / '.gitignore'\ncmake_build_dir = root_path / BUILD_DIR\ncustom_targets_json = root_path / CUSTO... | <|body_start_0|>
app_config = root_path / APP_CONFIG_FILE_NAME
mbed_os_ref = root_path / MBED_OS_REFERENCE_FILE_NAME
cmakelists_file = root_path / CMAKELISTS_FILE_NAME
main_cpp = root_path / MAIN_CPP_FILE_NAME
gitignore = root_path / '.gitignore'
cmake_build_dir = root_pa... | Files defining an MbedProgram. This object holds paths to the various files which define an MbedProgram. MbedPrograms must contain an mbed-os.lib reference file, defining Mbed OS as a program dependency. A program can optionally include an mbed_app.json file which defines application level config. Attributes: app_confi... | MbedProgramFiles | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MbedProgramFiles:
"""Files defining an MbedProgram. This object holds paths to the various files which define an MbedProgram. MbedPrograms must contain an mbed-os.lib reference file, defining Mbed OS as a program dependency. A program can optionally include an mbed_app.json file which defines app... | stack_v2_sparse_classes_36k_train_032342 | 6,084 | permissive | [
{
"docstring": "Create MbedProgramFiles from a new directory. A \"new directory\" in this context means it doesn't already contain an Mbed program. Args: root_path: The directory in which to create the program data files. Raises: ValueError: A program .mbed or mbed-os.lib file already exists at this path.",
... | 2 | stack_v2_sparse_classes_30k_train_021487 | Implement the Python class `MbedProgramFiles` described below.
Class description:
Files defining an MbedProgram. This object holds paths to the various files which define an MbedProgram. MbedPrograms must contain an mbed-os.lib reference file, defining Mbed OS as a program dependency. A program can optionally include ... | Implement the Python class `MbedProgramFiles` described below.
Class description:
Files defining an MbedProgram. This object holds paths to the various files which define an MbedProgram. MbedPrograms must contain an mbed-os.lib reference file, defining Mbed OS as a program dependency. A program can optionally include ... | 7ff8ed4d57857805bbf9f2b79486fdc3440dee9f | <|skeleton|>
class MbedProgramFiles:
"""Files defining an MbedProgram. This object holds paths to the various files which define an MbedProgram. MbedPrograms must contain an mbed-os.lib reference file, defining Mbed OS as a program dependency. A program can optionally include an mbed_app.json file which defines app... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MbedProgramFiles:
"""Files defining an MbedProgram. This object holds paths to the various files which define an MbedProgram. MbedPrograms must contain an mbed-os.lib reference file, defining Mbed OS as a program dependency. A program can optionally include an mbed_app.json file which defines application leve... | the_stack_v2_python_sparse | src/mbed_tools/project/_internal/project_data.py | ARMmbed/mbed-tools | train | 48 |
d5c52e5229d54dd387ea596200db5b68b2f4a848 | [
"if isinstance(kernel_size, int) and isinstance(stride, int):\n kernel_size = np.array([kernel_size] * 3)\n stride = [stride] * 3\nelif isinstance(kernel_size, int):\n kernel_size = np.array([kernel_size] * len(stride))\nelif isinstance(stride, int):\n stride = [stride] * len(kernel_size)\nself.out_filt... | <|body_start_0|>
if isinstance(kernel_size, int) and isinstance(stride, int):
kernel_size = np.array([kernel_size] * 3)
stride = [stride] * 3
elif isinstance(kernel_size, int):
kernel_size = np.array([kernel_size] * len(stride))
elif isinstance(stride, int):
... | Vanilla pre-activation residual unit pre-activation residual unit as proposed by He, Kaiming, et al. "Identity mappings in deep residual networks." ECCV, 2016. - https://link.springer.com/chapter/10.1007/978-3-319-46493-0_38 | VanillaResidualUnit | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VanillaResidualUnit:
"""Vanilla pre-activation residual unit pre-activation residual unit as proposed by He, Kaiming, et al. "Identity mappings in deep residual networks." ECCV, 2016. - https://link.springer.com/chapter/10.1007/978-3-319-46493-0_38"""
def __init__(self, out_filters, kernel_s... | stack_v2_sparse_classes_36k_train_032343 | 4,131 | permissive | [
{
"docstring": "Builds a residual unit Parameters ---------- out_filters : int number of output filters kernel_size : int or tuple or list, optional size of the kernel for the convolutions stride : int or tuple or list, optional stride used for first convolution in unit relu_leakiness : float leakiness of relu ... | 2 | stack_v2_sparse_classes_30k_train_006839 | Implement the Python class `VanillaResidualUnit` described below.
Class description:
Vanilla pre-activation residual unit pre-activation residual unit as proposed by He, Kaiming, et al. "Identity mappings in deep residual networks." ECCV, 2016. - https://link.springer.com/chapter/10.1007/978-3-319-46493-0_38
Method s... | Implement the Python class `VanillaResidualUnit` described below.
Class description:
Vanilla pre-activation residual unit pre-activation residual unit as proposed by He, Kaiming, et al. "Identity mappings in deep residual networks." ECCV, 2016. - https://link.springer.com/chapter/10.1007/978-3-319-46493-0_38
Method s... | 80d1a04dc163590aa44b62688b06aece78fb7fd6 | <|skeleton|>
class VanillaResidualUnit:
"""Vanilla pre-activation residual unit pre-activation residual unit as proposed by He, Kaiming, et al. "Identity mappings in deep residual networks." ECCV, 2016. - https://link.springer.com/chapter/10.1007/978-3-319-46493-0_38"""
def __init__(self, out_filters, kernel_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VanillaResidualUnit:
"""Vanilla pre-activation residual unit pre-activation residual unit as proposed by He, Kaiming, et al. "Identity mappings in deep residual networks." ECCV, 2016. - https://link.springer.com/chapter/10.1007/978-3-319-46493-0_38"""
def __init__(self, out_filters, kernel_size=3, stride... | the_stack_v2_python_sparse | dltk/core/modules/residual_units.py | pawni/DLTK-1 | train | 1 |
b9d12081a454c04b079b353e5d6081e856abd85d | [
"self.t = [[float('-inf'), 0]]\nself.total = 0\nself.lock = Lock()",
"with self.lock:\n if self.t[-1][0] == timestamp:\n self.t[-1][1] += 1\n else:\n c = self.t[-1][1] + 1\n self.t.append([timestamp, c])",
"i = bisect(self.t, [timestamp - 300, float('inf')]) - 1\nj = bisect(self.t, [t... | <|body_start_0|>
self.t = [[float('-inf'), 0]]
self.total = 0
self.lock = Lock()
<|end_body_0|>
<|body_start_1|>
with self.lock:
if self.t[-1][0] == timestamp:
self.t[-1][1] += 1
else:
c = self.t[-1][1] + 1
self.t.a... | HitCounter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: in... | stack_v2_sparse_classes_36k_train_032344 | 1,540 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Record a hit. @param timestamp - The current timestamp (in seconds granularity).",
"name": "hit",
"signature": "def hit(self, timestamp: int) -> None"
},
{
... | 3 | null | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari... | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari... | 84b35ec9a4e4319b29eb5f0f226543c9f3f47630 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
self.t = [[float('-inf'), 0]]
self.total = 0
self.lock = Lock()
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
... | the_stack_v2_python_sparse | design-hit-counter.py | maomao905/algo | train | 0 | |
a7af196c40923c3f22ed2facd7df2162b85ffe15 | [
"super().__init__()\nself.bn = bn\nself.groups = 1\nself.conv1 = nn.Conv2D(features, features, kernel_size=3, stride=1, padding=1, bias_attr=not self.bn, groups=self.groups)\nself.conv2 = nn.Conv2D(features, features, kernel_size=3, stride=1, padding=1, bias_attr=not self.bn, groups=self.groups)\nif self.bn == True... | <|body_start_0|>
super().__init__()
self.bn = bn
self.groups = 1
self.conv1 = nn.Conv2D(features, features, kernel_size=3, stride=1, padding=1, bias_attr=not self.bn, groups=self.groups)
self.conv2 = nn.Conv2D(features, features, kernel_size=3, stride=1, padding=1, bias_attr=not ... | Residual convolution module. | ResidualConvUnit_custom | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidualConvUnit_custom:
"""Residual convolution module."""
def __init__(self, features, activation, bn):
"""Init. Args: features (int): number of features"""
<|body_0|>
def forward(self, x):
"""Forward pass. Args: x (tensor): input Returns: tensor: output"""
... | stack_v2_sparse_classes_36k_train_032345 | 7,931 | permissive | [
{
"docstring": "Init. Args: features (int): number of features",
"name": "__init__",
"signature": "def __init__(self, features, activation, bn)"
},
{
"docstring": "Forward pass. Args: x (tensor): input Returns: tensor: output",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | null | Implement the Python class `ResidualConvUnit_custom` described below.
Class description:
Residual convolution module.
Method signatures and docstrings:
- def __init__(self, features, activation, bn): Init. Args: features (int): number of features
- def forward(self, x): Forward pass. Args: x (tensor): input Returns: ... | Implement the Python class `ResidualConvUnit_custom` described below.
Class description:
Residual convolution module.
Method signatures and docstrings:
- def __init__(self, features, activation, bn): Init. Args: features (int): number of features
- def forward(self, x): Forward pass. Args: x (tensor): input Returns: ... | b402610a6f0b382a978e82473b541ea1fc6cf09a | <|skeleton|>
class ResidualConvUnit_custom:
"""Residual convolution module."""
def __init__(self, features, activation, bn):
"""Init. Args: features (int): number of features"""
<|body_0|>
def forward(self, x):
"""Forward pass. Args: x (tensor): input Returns: tensor: output"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResidualConvUnit_custom:
"""Residual convolution module."""
def __init__(self, features, activation, bn):
"""Init. Args: features (int): number of features"""
super().__init__()
self.bn = bn
self.groups = 1
self.conv1 = nn.Conv2D(features, features, kernel_size=3, ... | the_stack_v2_python_sparse | modules/image/semantic_segmentation/lseg/models/scratch.py | PaddlePaddle/PaddleHub | train | 12,914 |
46a7a213d276eacbdaa1c36ad2cbce3d7d0928d5 | [
"self.bol = True\nself.stateT = True\nself.stateL = True\nself.geschw = True\nself.geschws = 0\nself.geschwp = 0\nself.geschwl = True\nself.stop = True",
"if key == b'c':\n if self.bol is True:\n self.bol = False\n elif self.bol is False:\n self.bol = True\n self.stateC = True\nif key =... | <|body_start_0|>
self.bol = True
self.stateT = True
self.stateL = True
self.geschw = True
self.geschws = 0
self.geschwp = 0
self.geschwl = True
self.stop = True
<|end_body_0|>
<|body_start_1|>
if key == b'c':
if self.bol is True:
... | Interaction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interaction:
def __init__(self):
"""Konstruktor der Klasse Interaction"""
<|body_0|>
def keyPressed(self, key, x, y):
"""Methode für die Tastatureneingabe :param key: Taste :param x: :param y:"""
<|body_1|>
def mouse(self, button, state, x, y):
"... | stack_v2_sparse_classes_36k_train_032346 | 2,908 | no_license | [
{
"docstring": "Konstruktor der Klasse Interaction",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Methode für die Tastatureneingabe :param key: Taste :param x: :param y:",
"name": "keyPressed",
"signature": "def keyPressed(self, key, x, y)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_000428 | Implement the Python class `Interaction` described below.
Class description:
Implement the Interaction class.
Method signatures and docstrings:
- def __init__(self): Konstruktor der Klasse Interaction
- def keyPressed(self, key, x, y): Methode für die Tastatureneingabe :param key: Taste :param x: :param y:
- def mous... | Implement the Python class `Interaction` described below.
Class description:
Implement the Interaction class.
Method signatures and docstrings:
- def __init__(self): Konstruktor der Klasse Interaction
- def keyPressed(self, key, x, y): Methode für die Tastatureneingabe :param key: Taste :param x: :param y:
- def mous... | 02585b8cf3bbf382eeb313911979cb5b965e76ad | <|skeleton|>
class Interaction:
def __init__(self):
"""Konstruktor der Klasse Interaction"""
<|body_0|>
def keyPressed(self, key, x, y):
"""Methode für die Tastatureneingabe :param key: Taste :param x: :param y:"""
<|body_1|>
def mouse(self, button, state, x, y):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Interaction:
def __init__(self):
"""Konstruktor der Klasse Interaction"""
self.bol = True
self.stateT = True
self.stateL = True
self.geschw = True
self.geschws = 0
self.geschwp = 0
self.geschwl = True
self.stop = True
def keyPressed(... | the_stack_v2_python_sparse | interaction.py | cdolacek-tgm/Sonnensystem | train | 0 | |
997d7f586ede3e0354754218eab15385a35ea74d | [
"super().__init__()\nself._model = model\nself._dev_x = x\nself._dev_y = y\nself._valid_steps = once_every\nself._batch_size = batch_size\nself._model_save_path = model_save_path\nself._verbose = verbose",
"if (epoch + 1) % self._valid_steps == 0:\n val_logs = self._model.evaluate(self._dev_x, self._dev_y, sel... | <|body_start_0|>
super().__init__()
self._model = model
self._dev_x = x
self._dev_y = y
self._valid_steps = once_every
self._batch_size = batch_size
self._model_save_path = model_save_path
self._verbose = verbose
<|end_body_0|>
<|body_start_1|>
if... | Callback to evaluate all metrics. MatchZoo metrics can not be evaluated batch-wise since they require dataset-level information. As a result, MatchZoo metrics are not evaluated automatically when a Model `fit`. When this callback is used, all metrics, including MatchZoo metrics and Keras metrics, are evluated once ever... | EvaluateAllMetrics | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvaluateAllMetrics:
"""Callback to evaluate all metrics. MatchZoo metrics can not be evaluated batch-wise since they require dataset-level information. As a result, MatchZoo metrics are not evaluated automatically when a Model `fit`. When this callback is used, all metrics, including MatchZoo met... | stack_v2_sparse_classes_36k_train_032347 | 2,513 | permissive | [
{
"docstring": "Initializer.",
"name": "__init__",
"signature": "def __init__(self, model: 'BaseModel', x: typing.Union[np.ndarray, typing.List[np.ndarray]], y: np.ndarray, once_every: int=1, batch_size: int=128, model_save_path: str=None, verbose=1)"
},
{
"docstring": "Called at the end of en e... | 2 | stack_v2_sparse_classes_30k_train_002322 | Implement the Python class `EvaluateAllMetrics` described below.
Class description:
Callback to evaluate all metrics. MatchZoo metrics can not be evaluated batch-wise since they require dataset-level information. As a result, MatchZoo metrics are not evaluated automatically when a Model `fit`. When this callback is us... | Implement the Python class `EvaluateAllMetrics` described below.
Class description:
Callback to evaluate all metrics. MatchZoo metrics can not be evaluated batch-wise since they require dataset-level information. As a result, MatchZoo metrics are not evaluated automatically when a Model `fit`. When this callback is us... | db101beed691a0e399f9b0b19fb59c7dc8b16760 | <|skeleton|>
class EvaluateAllMetrics:
"""Callback to evaluate all metrics. MatchZoo metrics can not be evaluated batch-wise since they require dataset-level information. As a result, MatchZoo metrics are not evaluated automatically when a Model `fit`. When this callback is used, all metrics, including MatchZoo met... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EvaluateAllMetrics:
"""Callback to evaluate all metrics. MatchZoo metrics can not be evaluated batch-wise since they require dataset-level information. As a result, MatchZoo metrics are not evaluated automatically when a Model `fit`. When this callback is used, all metrics, including MatchZoo metrics and Kera... | the_stack_v2_python_sparse | matchzoo/engine/callbacks.py | nguyenvo09/LearningFromFactCheckers | train | 11 |
95a00bf540728437bb745b9e5ca5eb3cdfbb087e | [
"super(ResBlock, self).__init__()\nif channels_in is None or channels_in == num_filters:\n channels_in = num_filters\n self.projection = None\nelse:\n self.projection = IdentityMapping(num_filters, channels_in, stride)\nself.conv1 = nn.Conv2d(channels_in, num_filters, 3, stride, 1)\nself.bn1 = nn.BatchNorm... | <|body_start_0|>
super(ResBlock, self).__init__()
if channels_in is None or channels_in == num_filters:
channels_in = num_filters
self.projection = None
else:
self.projection = IdentityMapping(num_filters, channels_in, stride)
self.conv1 = nn.Conv2d(ch... | Class for residual blocks in ResNet. | ResBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResBlock:
"""Class for residual blocks in ResNet."""
def __init__(self, num_filters, channels_in=None, stride=1):
"""Class initializer."""
<|body_0|>
def forward(self, x):
"""Forward propagation."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s... | stack_v2_sparse_classes_36k_train_032348 | 4,467 | permissive | [
{
"docstring": "Class initializer.",
"name": "__init__",
"signature": "def __init__(self, num_filters, channels_in=None, stride=1)"
},
{
"docstring": "Forward propagation.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000628 | Implement the Python class `ResBlock` described below.
Class description:
Class for residual blocks in ResNet.
Method signatures and docstrings:
- def __init__(self, num_filters, channels_in=None, stride=1): Class initializer.
- def forward(self, x): Forward propagation. | Implement the Python class `ResBlock` described below.
Class description:
Class for residual blocks in ResNet.
Method signatures and docstrings:
- def __init__(self, num_filters, channels_in=None, stride=1): Class initializer.
- def forward(self, x): Forward propagation.
<|skeleton|>
class ResBlock:
"""Class for... | fe5d1eb5ab5453be70c4be473fd3da71afe4b06c | <|skeleton|>
class ResBlock:
"""Class for residual blocks in ResNet."""
def __init__(self, num_filters, channels_in=None, stride=1):
"""Class initializer."""
<|body_0|>
def forward(self, x):
"""Forward propagation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResBlock:
"""Class for residual blocks in ResNet."""
def __init__(self, num_filters, channels_in=None, stride=1):
"""Class initializer."""
super(ResBlock, self).__init__()
if channels_in is None or channels_in == num_filters:
channels_in = num_filters
self.... | the_stack_v2_python_sparse | src/kegnet/classifier/models/resnet.py | videoturingtest/KegNet | train | 0 |
56876e7da93f8db588642b8841c9c81928a7e19f | [
"self.method = env['REQUEST_METHOD']\nself.query_params = {}\nself.query_string = env['QUERY_STRING']\nself.path = env['PATH_INFO']\nself.post_params = {}\nself.env_raw = env\nfor param, value in parse_qs(env['QUERY_STRING']).items():\n self.query_params[param] = value[0]\nif self.method == 'POST' and env['CONTE... | <|body_start_0|>
self.method = env['REQUEST_METHOD']
self.query_params = {}
self.query_string = env['QUERY_STRING']
self.path = env['PATH_INFO']
self.post_params = {}
self.env_raw = env
for param, value in parse_qs(env['QUERY_STRING']).items():
self.qu... | Contains data of the current HTTP request. | Request | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Request:
"""Contains data of the current HTTP request."""
def __init__(self, env):
""":param env: Wsgi environment"""
<|body_0|>
def get_param(self, name, default=None):
"""Returns a param of a GET request identified by its name."""
<|body_1|>
def po... | stack_v2_sparse_classes_36k_train_032349 | 3,603 | permissive | [
{
"docstring": ":param env: Wsgi environment",
"name": "__init__",
"signature": "def __init__(self, env)"
},
{
"docstring": "Returns a param of a GET request identified by its name.",
"name": "get_param",
"signature": "def get_param(self, name, default=None)"
},
{
"docstring": "R... | 4 | stack_v2_sparse_classes_30k_train_019855 | Implement the Python class `Request` described below.
Class description:
Contains data of the current HTTP request.
Method signatures and docstrings:
- def __init__(self, env): :param env: Wsgi environment
- def get_param(self, name, default=None): Returns a param of a GET request identified by its name.
- def post_p... | Implement the Python class `Request` described below.
Class description:
Contains data of the current HTTP request.
Method signatures and docstrings:
- def __init__(self, env): :param env: Wsgi environment
- def get_param(self, name, default=None): Returns a param of a GET request identified by its name.
- def post_p... | d1f75e321bac049291925b9ee345bf4218f5b7a9 | <|skeleton|>
class Request:
"""Contains data of the current HTTP request."""
def __init__(self, env):
""":param env: Wsgi environment"""
<|body_0|>
def get_param(self, name, default=None):
"""Returns a param of a GET request identified by its name."""
<|body_1|>
def po... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Request:
"""Contains data of the current HTTP request."""
def __init__(self, env):
""":param env: Wsgi environment"""
self.method = env['REQUEST_METHOD']
self.query_params = {}
self.query_string = env['QUERY_STRING']
self.path = env['PATH_INFO']
self.post_p... | the_stack_v2_python_sparse | oauth2/web/wsgi.py | wndhydrnt/python-oauth2 | train | 121 |
26756b87a37ace9a85fffc0c35e07ff15f7b07b9 | [
"if not LOGGER_SETUP:\n setup_logging()\nself.logger = logging.getLogger('BaseDataLoader')\nself.logger.setLevel(logging.INFO)\nself.validation_split = validation_split\nself.shuffle = shuffle\nself.batch_idx = 0\nself.n_samples = len(dataset)\nself.sampler, self.valid_sampler = self._split_sampler(self.validati... | <|body_start_0|>
if not LOGGER_SETUP:
setup_logging()
self.logger = logging.getLogger('BaseDataLoader')
self.logger.setLevel(logging.INFO)
self.validation_split = validation_split
self.shuffle = shuffle
self.batch_idx = 0
self.n_samples = len(dataset)
... | Base class for all data loaders | BaseDataLoader | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseDataLoader:
"""Base class for all data loaders"""
def __init__(self, dataset, batch_size, shuffle, validation_split, num_workers, collate_fn=default_collate, drop_last=False):
"""Initiates the DataLoader with the given parameters and initiates the super class. :param dataset (Dat... | stack_v2_sparse_classes_36k_train_032350 | 4,643 | permissive | [
{
"docstring": "Initiates the DataLoader with the given parameters and initiates the super class. :param dataset (Dataset): dataset from which to load the data. :param batch_size (int): how many samples per batch to load. :param shuffle (bool): set to ``True`` to have the data reshuffled at every epoch. :param ... | 3 | stack_v2_sparse_classes_30k_train_007232 | Implement the Python class `BaseDataLoader` described below.
Class description:
Base class for all data loaders
Method signatures and docstrings:
- def __init__(self, dataset, batch_size, shuffle, validation_split, num_workers, collate_fn=default_collate, drop_last=False): Initiates the DataLoader with the given para... | Implement the Python class `BaseDataLoader` described below.
Class description:
Base class for all data loaders
Method signatures and docstrings:
- def __init__(self, dataset, batch_size, shuffle, validation_split, num_workers, collate_fn=default_collate, drop_last=False): Initiates the DataLoader with the given para... | 4d80bfadf2012275e84ce757730e62155e4a78c5 | <|skeleton|>
class BaseDataLoader:
"""Base class for all data loaders"""
def __init__(self, dataset, batch_size, shuffle, validation_split, num_workers, collate_fn=default_collate, drop_last=False):
"""Initiates the DataLoader with the given parameters and initiates the super class. :param dataset (Dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseDataLoader:
"""Base class for all data loaders"""
def __init__(self, dataset, batch_size, shuffle, validation_split, num_workers, collate_fn=default_collate, drop_last=False):
"""Initiates the DataLoader with the given parameters and initiates the super class. :param dataset (Dataset): datase... | the_stack_v2_python_sparse | data_loader/base_data_loader.py | galsuchetzky/PytorchTemplate | train | 2 |
99ee40f2bb8769328c9ee7f6026f46e1d68681dd | [
"product = ProductFactory(stock_amount=10)\nself.assertEqual(product.left_in_stock, 10)\nself.assertTrue(product.is_available())",
"product = ProductFactory(stock_amount=2)\nOrderProductRelationFactory(product=product, order__open=None)\nopr = OrderProductRelationFactory(product=product, order__open=None)\nself.a... | <|body_start_0|>
product = ProductFactory(stock_amount=10)
self.assertEqual(product.left_in_stock, 10)
self.assertTrue(product.is_available())
<|end_body_0|>
<|body_start_1|>
product = ProductFactory(stock_amount=2)
OrderProductRelationFactory(product=product, order__open=None)
... | Test logic about availability of products. | ProductAvailabilityTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductAvailabilityTest:
"""Test logic about availability of products."""
def test_product_available_by_stock(self):
"""If no orders have been made, the product is still available."""
<|body_0|>
def test_product_not_available_by_stock(self):
"""If max orders have... | stack_v2_sparse_classes_36k_train_032351 | 26,437 | permissive | [
{
"docstring": "If no orders have been made, the product is still available.",
"name": "test_product_available_by_stock",
"signature": "def test_product_available_by_stock(self)"
},
{
"docstring": "If max orders have been made, the product is NOT available.",
"name": "test_product_not_availa... | 6 | stack_v2_sparse_classes_30k_train_012004 | Implement the Python class `ProductAvailabilityTest` described below.
Class description:
Test logic about availability of products.
Method signatures and docstrings:
- def test_product_available_by_stock(self): If no orders have been made, the product is still available.
- def test_product_not_available_by_stock(self... | Implement the Python class `ProductAvailabilityTest` described below.
Class description:
Test logic about availability of products.
Method signatures and docstrings:
- def test_product_available_by_stock(self): If no orders have been made, the product is still available.
- def test_product_not_available_by_stock(self... | 767deb7f58429e9162e0c2ef79be9f0f38f37ce1 | <|skeleton|>
class ProductAvailabilityTest:
"""Test logic about availability of products."""
def test_product_available_by_stock(self):
"""If no orders have been made, the product is still available."""
<|body_0|>
def test_product_not_available_by_stock(self):
"""If max orders have... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductAvailabilityTest:
"""Test logic about availability of products."""
def test_product_available_by_stock(self):
"""If no orders have been made, the product is still available."""
product = ProductFactory(stock_amount=10)
self.assertEqual(product.left_in_stock, 10)
sel... | the_stack_v2_python_sparse | src/shop/tests.py | bornhack/bornhack-website | train | 9 |
909f5bec612ec47064be4f0287042d18ba85f00d | [
"super(Criterion, self).__init__()\nself.par = opt\nself.n_classes = opt.n_classes\nself.n_centroids = opt.loss_softtriplet_n_centroids\nself.margin_delta = opt.loss_softtriplet_margin_delta\nself.gamma = opt.loss_softtriplet_gamma\nself.lam = opt.loss_softtriplet_lambda\nself.reg_weight = opt.loss_softtriplet_reg_... | <|body_start_0|>
super(Criterion, self).__init__()
self.par = opt
self.n_classes = opt.n_classes
self.n_centroids = opt.loss_softtriplet_n_centroids
self.margin_delta = opt.loss_softtriplet_margin_delta
self.gamma = opt.loss_softtriplet_gamma
self.lam = opt.loss_s... | Criterion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin."""
<|body_0|>
def forward(self, batch, labels, **kwargs):
"""Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels: nparray/list: For each element of the batch assigns a class [... | stack_v2_sparse_classes_36k_train_032352 | 2,944 | permissive | [
{
"docstring": "Args: margin: Triplet Margin.",
"name": "__init__",
"signature": "def __init__(self, opt)"
},
{
"docstring": "Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels: nparray/list: For each element of the batch assigns a class [0,...,C-1], shape: (BS x 1)",
... | 2 | stack_v2_sparse_classes_30k_train_001608 | Implement the Python class `Criterion` described below.
Class description:
Implement the Criterion class.
Method signatures and docstrings:
- def __init__(self, opt): Args: margin: Triplet Margin.
- def forward(self, batch, labels, **kwargs): Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels:... | Implement the Python class `Criterion` described below.
Class description:
Implement the Criterion class.
Method signatures and docstrings:
- def __init__(self, opt): Args: margin: Triplet Margin.
- def forward(self, batch, labels, **kwargs): Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels:... | 01a7220bac7ebb1e70416ef663f3ba7cee9e8bf5 | <|skeleton|>
class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin."""
<|body_0|>
def forward(self, batch, labels, **kwargs):
"""Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels: nparray/list: For each element of the batch assigns a class [... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin."""
super(Criterion, self).__init__()
self.par = opt
self.n_classes = opt.n_classes
self.n_centroids = opt.loss_softtriplet_n_centroids
self.margin_delta = opt.loss_softtriplet_margin_delta
... | the_stack_v2_python_sparse | criteria/softtriplet.py | chenyanlinzhugoushou/DCML | train | 0 | |
4f949d20d79e29074f35b084d9b4298331cd0dc0 | [
"result = collections.defaultdict(list)\nfor e in strs:\n result[tuple(sorted(e))].append(e)\nreturn result.values()",
"result = collections.defaultdict(list)\nfor s in strs:\n count = [0] * 26\n for c in s:\n count[ord(c) - ord('a')] += 1\n result[tuple(count)].append(s)\nreturn result.values(... | <|body_start_0|>
result = collections.defaultdict(list)
for e in strs:
result[tuple(sorted(e))].append(e)
return result.values()
<|end_body_0|>
<|body_start_1|>
result = collections.defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams1(self, strs: List[str]) -> List[List[str]]:
"""Time Complexity: O(NK \\log K)O(NKlogK), where NN is the length of strs, and KK is the maximum length of a string in strs. The outer loop has complexity O(N)O(N) as we iterate through each string. Then, we sort ea... | stack_v2_sparse_classes_36k_train_032353 | 2,474 | no_license | [
{
"docstring": "Time Complexity: O(NK \\\\log K)O(NKlogK), where NN is the length of strs, and KK is the maximum length of a string in strs. The outer loop has complexity O(N)O(N) as we iterate through each string. Then, we sort each string in O(K \\\\log K)O(KlogK) time. Space Complexity: O(NK)O(NK), the total... | 2 | stack_v2_sparse_classes_30k_train_008386 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams1(self, strs: List[str]) -> List[List[str]]: Time Complexity: O(NK \\log K)O(NKlogK), where NN is the length of strs, and KK is the maximum length of a string in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams1(self, strs: List[str]) -> List[List[str]]: Time Complexity: O(NK \\log K)O(NKlogK), where NN is the length of strs, and KK is the maximum length of a string in... | 2091a45cf825e3d1f8c318ed4e7d00f7fe97d017 | <|skeleton|>
class Solution:
def groupAnagrams1(self, strs: List[str]) -> List[List[str]]:
"""Time Complexity: O(NK \\log K)O(NKlogK), where NN is the length of strs, and KK is the maximum length of a string in strs. The outer loop has complexity O(N)O(N) as we iterate through each string. Then, we sort ea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def groupAnagrams1(self, strs: List[str]) -> List[List[str]]:
"""Time Complexity: O(NK \\log K)O(NKlogK), where NN is the length of strs, and KK is the maximum length of a string in strs. The outer loop has complexity O(N)O(N) as we iterate through each string. Then, we sort each string in O... | the_stack_v2_python_sparse | groupAnagrams.py | zunzunwang/python-leetcode | train | 0 | |
2cbf1f9bdc66673efbca4eb7b1e221cc078481f6 | [
"OperationHandlerBase.__init__(self, operation, csPath)\ngMonitor.registerActivity('RegisterAtt', 'Attempted file registrations', 'RequestExecutingAgent', 'Files/min', gMonitor.OP_SUM)\ngMonitor.registerActivity('RegisterOK', 'Successful file registrations', 'RequestExecutingAgent', 'Files/min', gMonitor.OP_SUM)\ng... | <|body_start_0|>
OperationHandlerBase.__init__(self, operation, csPath)
gMonitor.registerActivity('RegisterAtt', 'Attempted file registrations', 'RequestExecutingAgent', 'Files/min', gMonitor.OP_SUM)
gMonitor.registerActivity('RegisterOK', 'Successful file registrations', 'RequestExecutingAgent'... | .. class:: RegisterOperation RegisterFile operation handler | RegisterFile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterFile:
""".. class:: RegisterOperation RegisterFile operation handler"""
def __init__(self, operation=None, csPath=None):
"""c'tor :param self: self reference :param Operation operation: Operation instance :param str csPath: CS path for this handler"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_032354 | 3,822 | no_license | [
{
"docstring": "c'tor :param self: self reference :param Operation operation: Operation instance :param str csPath: CS path for this handler",
"name": "__init__",
"signature": "def __init__(self, operation=None, csPath=None)"
},
{
"docstring": "call me maybe",
"name": "__call__",
"signat... | 2 | null | Implement the Python class `RegisterFile` described below.
Class description:
.. class:: RegisterOperation RegisterFile operation handler
Method signatures and docstrings:
- def __init__(self, operation=None, csPath=None): c'tor :param self: self reference :param Operation operation: Operation instance :param str csP... | Implement the Python class `RegisterFile` described below.
Class description:
.. class:: RegisterOperation RegisterFile operation handler
Method signatures and docstrings:
- def __init__(self, operation=None, csPath=None): c'tor :param self: self reference :param Operation operation: Operation instance :param str csP... | 00607d8f47e1a14b2d9e82ece924f42f10e541e3 | <|skeleton|>
class RegisterFile:
""".. class:: RegisterOperation RegisterFile operation handler"""
def __init__(self, operation=None, csPath=None):
"""c'tor :param self: self reference :param Operation operation: Operation instance :param str csPath: CS path for this handler"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegisterFile:
""".. class:: RegisterOperation RegisterFile operation handler"""
def __init__(self, operation=None, csPath=None):
"""c'tor :param self: self reference :param Operation operation: Operation instance :param str csPath: CS path for this handler"""
OperationHandlerBase.__init__... | the_stack_v2_python_sparse | DataManagementSystem/Agent/RequestOperations/RegisterFile.py | Teddy22/DIRAC | train | 0 |
58223a5755289cb41d090f31f16a1f492c9f3b46 | [
"sampleAtom = atoms[-1]\nself.atoms = []\nself.name = sampleAtom.resName\nself.chainID = sampleAtom.chainID\nself.resSeq = sampleAtom.resSeq\nself.iCode = sampleAtom.iCode\nself.fixed = 0\nself.ffname = 'WAT'\nself.map = {}\nself.reference = ref\nfor a in atoms:\n if a.name in ref.altnames:\n a.name = ref... | <|body_start_0|>
sampleAtom = atoms[-1]
self.atoms = []
self.name = sampleAtom.resName
self.chainID = sampleAtom.chainID
self.resSeq = sampleAtom.resSeq
self.iCode = sampleAtom.iCode
self.fixed = 0
self.ffname = 'WAT'
self.map = {}
self.ref... | Water class This class gives data about the Water object, and inherits off the base residue class. | WAT | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WAT:
"""Water class This class gives data about the Water object, and inherits off the base residue class."""
def __init__(self, atoms, ref):
"""Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)"""
<|body_0|>
def createAtom(s... | stack_v2_sparse_classes_36k_train_032355 | 22,508 | permissive | [
{
"docstring": "Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)",
"name": "__init__",
"signature": "def __init__(self, atoms, ref)"
},
{
"docstring": "Create a water atom. Note the HETATM field. Parameters atomname: The name of the atom (string) ne... | 3 | stack_v2_sparse_classes_30k_test_000086 | Implement the Python class `WAT` described below.
Class description:
Water class This class gives data about the Water object, and inherits off the base residue class.
Method signatures and docstrings:
- def __init__(self, atoms, ref): Initialize the class Parameters atoms: A list of Atom objects to be stored in this... | Implement the Python class `WAT` described below.
Class description:
Water class This class gives data about the Water object, and inherits off the base residue class.
Method signatures and docstrings:
- def __init__(self, atoms, ref): Initialize the class Parameters atoms: A list of Atom objects to be stored in this... | a50f0b2f7104007c730baa51b4ec65c891008c47 | <|skeleton|>
class WAT:
"""Water class This class gives data about the Water object, and inherits off the base residue class."""
def __init__(self, atoms, ref):
"""Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)"""
<|body_0|>
def createAtom(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WAT:
"""Water class This class gives data about the Water object, and inherits off the base residue class."""
def __init__(self, atoms, ref):
"""Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)"""
sampleAtom = atoms[-1]
self.atoms = [... | the_stack_v2_python_sparse | mscreen/autodocktools_prepare_py3k/MolKit/pdb2pqr/src/aa.py | e-mayo/mscreen | train | 10 |
bdb86ce15529df916ceeb80ca00b34f2d6deb028 | [
"password1 = self.cleaned_data.get('password1')\npassword2 = self.cleaned_data.get('password2')\nif password1 and password2 and (password1 != password2):\n raise forms.ValidationError(\"Passwords don't match\")\nreturn password2",
"user = super(UserCreationForm, self).save(commit=False)\nuser.set_password(self... | <|body_start_0|>
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and (password1 != password2):
raise forms.ValidationError("Passwords don't match")
return password2
<|end_body_0|>
<|body_start_1|>
... | A form for creating new users. Includes all the required fields, plus a repeated password. | UserCreationForm | [
"CC-BY-SA-4.0",
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCreationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_password2(self):
"""Check that the two password entries match"""
<|body_0|>
def save(self, commit=True):
"""Save the provided password in ... | stack_v2_sparse_classes_36k_train_032356 | 2,893 | permissive | [
{
"docstring": "Check that the two password entries match",
"name": "clean_password2",
"signature": "def clean_password2(self)"
},
{
"docstring": "Save the provided password in hashed format",
"name": "save",
"signature": "def save(self, commit=True)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020446 | Implement the Python class `UserCreationForm` described below.
Class description:
A form for creating new users. Includes all the required fields, plus a repeated password.
Method signatures and docstrings:
- def clean_password2(self): Check that the two password entries match
- def save(self, commit=True): Save the ... | Implement the Python class `UserCreationForm` described below.
Class description:
A form for creating new users. Includes all the required fields, plus a repeated password.
Method signatures and docstrings:
- def clean_password2(self): Check that the two password entries match
- def save(self, commit=True): Save the ... | a60dbb43141210cc0950cc2e7490af1fd98b2ec0 | <|skeleton|>
class UserCreationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_password2(self):
"""Check that the two password entries match"""
<|body_0|>
def save(self, commit=True):
"""Save the provided password in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserCreationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_password2(self):
"""Check that the two password entries match"""
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2... | the_stack_v2_python_sparse | sitePjt/accounts/forms.py | returnturn/200OK | train | 0 |
c81679de5cc003b92c404006a988f2623b6537f6 | [
"def bisearch_l() -> int:\n i = -1\n l, r = (0, len(nums) - 1)\n while l <= r:\n m = (l + r) // 2\n if nums[m] >= target:\n r = m - 1\n else:\n l = m + 1\n if nums[m] == target:\n i = m\n return i\n\ndef bisearch_r() -> int:\n i = -1\n l... | <|body_start_0|>
def bisearch_l() -> int:
i = -1
l, r = (0, len(nums) - 1)
while l <= r:
m = (l + r) // 2
if nums[m] >= target:
r = m - 1
else:
l = m + 1
if nums[m] == targ... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchRange4(self, nums: List[int], target: int) -> List[int]:
"""bisect.bisect_left() and bisect.bisect_right(), O(log n) Runtime: 68ms"""
<|body_0|>
def searchRange1(self, nums: List[int], target: int) -> List[int]:
"""Binary search: O(log n), the wor... | stack_v2_sparse_classes_36k_train_032357 | 4,074 | permissive | [
{
"docstring": "bisect.bisect_left() and bisect.bisect_right(), O(log n) Runtime: 68ms",
"name": "searchRange4",
"signature": "def searchRange4(self, nums: List[int], target: int) -> List[int]"
},
{
"docstring": "Binary search: O(log n), the worst case n + log n Runtime: 72ms",
"name": "sear... | 4 | stack_v2_sparse_classes_30k_train_017230 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchRange4(self, nums: List[int], target: int) -> List[int]: bisect.bisect_left() and bisect.bisect_right(), O(log n) Runtime: 68ms
- def searchRange1(self, nums: List[int]... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchRange4(self, nums: List[int], target: int) -> List[int]: bisect.bisect_left() and bisect.bisect_right(), O(log n) Runtime: 68ms
- def searchRange1(self, nums: List[int]... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def searchRange4(self, nums: List[int], target: int) -> List[int]:
"""bisect.bisect_left() and bisect.bisect_right(), O(log n) Runtime: 68ms"""
<|body_0|>
def searchRange1(self, nums: List[int], target: int) -> List[int]:
"""Binary search: O(log n), the wor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchRange4(self, nums: List[int], target: int) -> List[int]:
"""bisect.bisect_left() and bisect.bisect_right(), O(log n) Runtime: 68ms"""
def bisearch_l() -> int:
i = -1
l, r = (0, len(nums) - 1)
while l <= r:
m = (l + r) // 2... | the_stack_v2_python_sparse | leetcode/0034_find_first_and_last_position_of_element_in_sorted_array.py | chaosWsF/Python-Practice | train | 1 | |
8c1a25133e7a71db2f2c70e12b3d033c11d48eaa | [
"Log.log(level=log_level, msg='Save current host screen at {0}'.format(path))\nif Settings.HOST_OS is OSType.LINUX:\n os.system('import -window root {0}'.format(path))\nelse:\n try:\n from PIL import ImageGrab\n image = ImageGrab.grab()\n image.save(path)\n except IOError:\n Log... | <|body_start_0|>
Log.log(level=log_level, msg='Save current host screen at {0}'.format(path))
if Settings.HOST_OS is OSType.LINUX:
os.system('import -window root {0}'.format(path))
else:
try:
from PIL import ImageGrab
image = ImageGrab.grab... | Screen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Screen:
def save_screen(path, log_level=logging.DEBUG):
"""Save screen of host machine. :param path: Path where screen will be saved. :param log_level: Log level of the command."""
<|body_0|>
def get_screen_text():
"""Get text of current screen of host machine. :retu... | stack_v2_sparse_classes_36k_train_032358 | 2,503 | no_license | [
{
"docstring": "Save screen of host machine. :param path: Path where screen will be saved. :param log_level: Log level of the command.",
"name": "save_screen",
"signature": "def save_screen(path, log_level=logging.DEBUG)"
},
{
"docstring": "Get text of current screen of host machine. :return: Al... | 3 | stack_v2_sparse_classes_30k_train_016053 | Implement the Python class `Screen` described below.
Class description:
Implement the Screen class.
Method signatures and docstrings:
- def save_screen(path, log_level=logging.DEBUG): Save screen of host machine. :param path: Path where screen will be saved. :param log_level: Log level of the command.
- def get_scree... | Implement the Python class `Screen` described below.
Class description:
Implement the Screen class.
Method signatures and docstrings:
- def save_screen(path, log_level=logging.DEBUG): Save screen of host machine. :param path: Path where screen will be saved. :param log_level: Log level of the command.
- def get_scree... | 85e9662ab85c68a472b407e890656bcb73a87e70 | <|skeleton|>
class Screen:
def save_screen(path, log_level=logging.DEBUG):
"""Save screen of host machine. :param path: Path where screen will be saved. :param log_level: Log level of the command."""
<|body_0|>
def get_screen_text():
"""Get text of current screen of host machine. :retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Screen:
def save_screen(path, log_level=logging.DEBUG):
"""Save screen of host machine. :param path: Path where screen will be saved. :param log_level: Log level of the command."""
Log.log(level=log_level, msg='Save current host screen at {0}'.format(path))
if Settings.HOST_OS is OSTyp... | the_stack_v2_python_sparse | core/utils/screen.py | NativeScript/nativescript-tooling-qa | train | 5 | |
963e60b4c66e747f7ea34603e053f5c736b50f82 | [
"if self.weight is None:\n return 0\nreturn weight if self.weight.unit else weight / 2",
"if self.power is None:\n return 0\nreturn weight if self.power.unit else weight / 2",
"tally = 0\nfor a in ('depth', 'height', 'length', 'width'):\n if getattr(self, a) is not None:\n tally += 1\n if... | <|body_start_0|>
if self.weight is None:
return 0
return weight if self.weight.unit else weight / 2
<|end_body_0|>
<|body_start_1|>
if self.power is None:
return 0
return weight if self.power.unit else weight / 2
<|end_body_1|>
<|body_start_2|>
tally = 0... | Store product dimensions in a dataclass for easier access | WdcProductDimensions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WdcProductDimensions:
"""Store product dimensions in a dataclass for easier access"""
def __weight_accuracy(self, weight: float) -> float:
"""Calculate weight accuracy dependent on whether or not there's a unit associated :param weight: weight from source to be applied to dimension c... | stack_v2_sparse_classes_36k_train_032359 | 3,615 | permissive | [
{
"docstring": "Calculate weight accuracy dependent on whether or not there's a unit associated :param weight: weight from source to be applied to dimension confidence :return: confidence of dimension result",
"name": "__weight_accuracy",
"signature": "def __weight_accuracy(self, weight: float) -> float... | 4 | stack_v2_sparse_classes_30k_train_021558 | Implement the Python class `WdcProductDimensions` described below.
Class description:
Store product dimensions in a dataclass for easier access
Method signatures and docstrings:
- def __weight_accuracy(self, weight: float) -> float: Calculate weight accuracy dependent on whether or not there's a unit associated :para... | Implement the Python class `WdcProductDimensions` described below.
Class description:
Store product dimensions in a dataclass for easier access
Method signatures and docstrings:
- def __weight_accuracy(self, weight: float) -> float: Calculate weight accuracy dependent on whether or not there's a unit associated :para... | 28c19eba41e03e053ae4addff56a313d926e18d7 | <|skeleton|>
class WdcProductDimensions:
"""Store product dimensions in a dataclass for easier access"""
def __weight_accuracy(self, weight: float) -> float:
"""Calculate weight accuracy dependent on whether or not there's a unit associated :param weight: weight from source to be applied to dimension c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WdcProductDimensions:
"""Store product dimensions in a dataclass for easier access"""
def __weight_accuracy(self, weight: float) -> float:
"""Calculate weight accuracy dependent on whether or not there's a unit associated :param weight: weight from source to be applied to dimension confidence :re... | the_stack_v2_python_sparse | mowgli_etl/pipeline/wdc/wdc_product_dimensions.py | tetherless-world/mowgli-etl | train | 6 |
352125e282bcb9f4eb4705bccf6be3dc9c9f40d0 | [
"answer = []\nfor i in reversed(range(len(A))):\n largest_idx = self.find_largest_element_idx(A, i)\n left_portion = A[:largest_idx + 1]\n answer.append(largest_idx + 1)\n left_portion.reverse()\n right_portion = A[largest_idx + 1:]\n A = left_portion + right_portion\n left_portion = A[:i + 1]\... | <|body_start_0|>
answer = []
for i in reversed(range(len(A))):
largest_idx = self.find_largest_element_idx(A, i)
left_portion = A[:largest_idx + 1]
answer.append(largest_idx + 1)
left_portion.reverse()
right_portion = A[largest_idx + 1:]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pancakeSort(self, A: List[int]) -> List[int]:
"""Pancake Sorts a list :param A: the list to be sorted :return: the indices of the elements that were reversed at"""
<|body_0|>
def find_largest_element_idx(self, nums, end):
"""find the index of the larges... | stack_v2_sparse_classes_36k_train_032360 | 1,793 | no_license | [
{
"docstring": "Pancake Sorts a list :param A: the list to be sorted :return: the indices of the elements that were reversed at",
"name": "pancakeSort",
"signature": "def pancakeSort(self, A: List[int]) -> List[int]"
},
{
"docstring": "find the index of the largest element in the num list :param... | 2 | stack_v2_sparse_classes_30k_train_012733 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pancakeSort(self, A: List[int]) -> List[int]: Pancake Sorts a list :param A: the list to be sorted :return: the indices of the elements that were reversed at
- def find_large... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pancakeSort(self, A: List[int]) -> List[int]: Pancake Sorts a list :param A: the list to be sorted :return: the indices of the elements that were reversed at
- def find_large... | 36c95c760f3db5add3650d341608f12f10e77320 | <|skeleton|>
class Solution:
def pancakeSort(self, A: List[int]) -> List[int]:
"""Pancake Sorts a list :param A: the list to be sorted :return: the indices of the elements that were reversed at"""
<|body_0|>
def find_largest_element_idx(self, nums, end):
"""find the index of the larges... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pancakeSort(self, A: List[int]) -> List[int]:
"""Pancake Sorts a list :param A: the list to be sorted :return: the indices of the elements that were reversed at"""
answer = []
for i in reversed(range(len(A))):
largest_idx = self.find_largest_element_idx(A, i)
... | the_stack_v2_python_sparse | 969_PancakeSorting/Solution.py | ejwessel/LeetCodeProblems | train | 0 | |
7df9ddfcfd485096e53a37bf21c443ffff5740ae | [
"log.debug('Composing bundle %s', subgraph_id)\nlinks_file = self.links[subgraph_id]\nmanifest = []\nmetadata = {'links.json': links_file.content}\nentity_ids_by_type = self._entity_ids_by_type(subgraph_id)\nfor entity_type, entity_ids in entity_ids_by_type.items():\n for i, entity_id in enumerate(sorted(entity_... | <|body_start_0|>
log.debug('Composing bundle %s', subgraph_id)
links_file = self.links[subgraph_id]
manifest = []
metadata = {'links.json': links_file.content}
entity_ids_by_type = self._entity_ids_by_type(subgraph_id)
for entity_type, entity_ids in entity_ids_by_type.ite... | StagingArea | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StagingArea:
def get_bundle(self, subgraph_id: str) -> Tuple[str, List[JSON], JSON]:
"""Return a tuple consisting of the version of the downloaded bundle, a list of the manifest entries for all metadata files in the bundle, and a dictionary mapping the file name of each metadata file in ... | stack_v2_sparse_classes_36k_train_032361 | 13,088 | permissive | [
{
"docstring": "Return a tuple consisting of the version of the downloaded bundle, a list of the manifest entries for all metadata files in the bundle, and a dictionary mapping the file name of each metadata file in the bundle to the JSON contents of that file.",
"name": "get_bundle",
"signature": "def ... | 2 | null | Implement the Python class `StagingArea` described below.
Class description:
Implement the StagingArea class.
Method signatures and docstrings:
- def get_bundle(self, subgraph_id: str) -> Tuple[str, List[JSON], JSON]: Return a tuple consisting of the version of the downloaded bundle, a list of the manifest entries fo... | Implement the Python class `StagingArea` described below.
Class description:
Implement the StagingArea class.
Method signatures and docstrings:
- def get_bundle(self, subgraph_id: str) -> Tuple[str, List[JSON], JSON]: Return a tuple consisting of the version of the downloaded bundle, a list of the manifest entries fo... | 3722323d4eed3089d25f6d6c9cbfb1672b7de939 | <|skeleton|>
class StagingArea:
def get_bundle(self, subgraph_id: str) -> Tuple[str, List[JSON], JSON]:
"""Return a tuple consisting of the version of the downloaded bundle, a list of the manifest entries for all metadata files in the bundle, and a dictionary mapping the file name of each metadata file in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StagingArea:
def get_bundle(self, subgraph_id: str) -> Tuple[str, List[JSON], JSON]:
"""Return a tuple consisting of the version of the downloaded bundle, a list of the manifest entries for all metadata files in the bundle, and a dictionary mapping the file name of each metadata file in the bundle to ... | the_stack_v2_python_sparse | src/humancellatlas/data/metadata/helpers/staging_area.py | DataBiosphere/azul | train | 23 | |
83c1262221c71841a2ff0e00132cf5ddbdce2e70 | [
"if not nums:\n return 0\nsize = len(nums)\nif size == 1:\n return nums[0]\nreturn max(self.Myrob(nums[1:]), self.Myrob(nums[:size - 1]))",
"if not nums:\n return 0\nsize = len(nums)\nif size == 1:\n return nums[0]\ndp = [0 for _ in range(len(nums))]\ndp[0] = nums[0]\ndp[1] = max(nums[0], nums[1])\nfo... | <|body_start_0|>
if not nums:
return 0
size = len(nums)
if size == 1:
return nums[0]
return max(self.Myrob(nums[1:]), self.Myrob(nums[:size - 1]))
<|end_body_0|>
<|body_start_1|>
if not nums:
return 0
size = len(nums)
if size =... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def Myrob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
size = len(nums)
... | stack_v2_sparse_classes_36k_train_032362 | 701 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "Myrob",
"signature": "def Myrob(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def Myrob(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def Myrob(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
... | d2b8a1dfe986d71d02d2568b55bad6e5b1c81492 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def Myrob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 0
size = len(nums)
if size == 1:
return nums[0]
return max(self.Myrob(nums[1:]), self.Myrob(nums[:size - 1]))
def Myrob(self, nums):
""":type ... | the_stack_v2_python_sparse | Middle/Que213打家劫舍II.py | HuangZengPei/LeetCode | train | 2 | |
ef0b2001a6fcc9e6832332aa952d345c674c2056 | [
"super(Attention, self).__init__()\nself.key_layer = nn.Linear(hidden_size, hidden_size, bias=False)\nself.query_layer = nn.Linear(hidden_size, hidden_size, bias=False)\nself.energy_layer = nn.Linear(hidden_size, 1, bias=False)",
"batch_size, hidden_size = query.shape\nproj_key = self.key_layer(key.contiguous().v... | <|body_start_0|>
super(Attention, self).__init__()
self.key_layer = nn.Linear(hidden_size, hidden_size, bias=False)
self.query_layer = nn.Linear(hidden_size, hidden_size, bias=False)
self.energy_layer = nn.Linear(hidden_size, 1, bias=False)
<|end_body_0|>
<|body_start_1|>
batch_... | Implements Bahdanau (MLP) attention | Attention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
"""Implements Bahdanau (MLP) attention"""
def __init__(self, hidden_size):
"""Args: hidden_size: size of the hidden layer"""
<|body_0|>
def forward(self, query, key, feats):
"""Args: query: hidden state of the encoder (B x H) key: keys (B x N x H) feat... | stack_v2_sparse_classes_36k_train_032363 | 5,316 | no_license | [
{
"docstring": "Args: hidden_size: size of the hidden layer",
"name": "__init__",
"signature": "def __init__(self, hidden_size)"
},
{
"docstring": "Args: query: hidden state of the encoder (B x H) key: keys (B x N x H) feats: spatial features (B x N x V) Output: context: attention combined spati... | 2 | stack_v2_sparse_classes_30k_train_018710 | Implement the Python class `Attention` described below.
Class description:
Implements Bahdanau (MLP) attention
Method signatures and docstrings:
- def __init__(self, hidden_size): Args: hidden_size: size of the hidden layer
- def forward(self, query, key, feats): Args: query: hidden state of the encoder (B x H) key: ... | Implement the Python class `Attention` described below.
Class description:
Implements Bahdanau (MLP) attention
Method signatures and docstrings:
- def __init__(self, hidden_size): Args: hidden_size: size of the hidden layer
- def forward(self, query, key, feats): Args: query: hidden state of the encoder (B x H) key: ... | 5f347de39f5583cd043c6f572178da08f7c0de94 | <|skeleton|>
class Attention:
"""Implements Bahdanau (MLP) attention"""
def __init__(self, hidden_size):
"""Args: hidden_size: size of the hidden layer"""
<|body_0|>
def forward(self, query, key, feats):
"""Args: query: hidden state of the encoder (B x H) key: keys (B x N x H) feat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Attention:
"""Implements Bahdanau (MLP) attention"""
def __init__(self, hidden_size):
"""Args: hidden_size: size of the hidden layer"""
super(Attention, self).__init__()
self.key_layer = nn.Linear(hidden_size, hidden_size, bias=False)
self.query_layer = nn.Linear(hidden_si... | the_stack_v2_python_sparse | model/SpatialNet.py | AmmieQi/pytorch-video-caption-rationale | train | 0 |
cdc19af05f58fcb427e17f867790974aecb5254a | [
"if remote.ssh:\n return Connection(remote.ssh)\nelif remote.http:\n hostName = urlparse(remote.http).hostname\n username = None\n password = None\n if hostName in httpCredentials:\n username = httpCredentials[hostName].username\n password = httpCredentials[hostName].password\n retur... | <|body_start_0|>
if remote.ssh:
return Connection(remote.ssh)
elif remote.http:
hostName = urlparse(remote.http).hostname
username = None
password = None
if hostName in httpCredentials:
username = httpCredentials[hostName].usern... | Collection of drepo utility functions | Utils | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Utils:
"""Collection of drepo utility functions"""
def createQueryConnection(remote, httpCredentials):
"""Create a query connection (HTTP or SSH) based on what's available in the given remote @param remote Remote @param httpCredentials A map of HTTP credentials"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_032364 | 3,013 | permissive | [
{
"docstring": "Create a query connection (HTTP or SSH) based on what's available in the given remote @param remote Remote @param httpCredentials A map of HTTP credentials",
"name": "createQueryConnection",
"signature": "def createQueryConnection(remote, httpCredentials)"
},
{
"docstring": "Inje... | 2 | stack_v2_sparse_classes_30k_train_001042 | Implement the Python class `Utils` described below.
Class description:
Collection of drepo utility functions
Method signatures and docstrings:
- def createQueryConnection(remote, httpCredentials): Create a query connection (HTTP or SSH) based on what's available in the given remote @param remote Remote @param httpCre... | Implement the Python class `Utils` described below.
Class description:
Collection of drepo utility functions
Method signatures and docstrings:
- def createQueryConnection(remote, httpCredentials): Create a query connection (HTTP or SSH) based on what's available in the given remote @param remote Remote @param httpCre... | 58a035a08a7c58035c25f992c1b8aa33cc997cd2 | <|skeleton|>
class Utils:
"""Collection of drepo utility functions"""
def createQueryConnection(remote, httpCredentials):
"""Create a query connection (HTTP or SSH) based on what's available in the given remote @param remote Remote @param httpCredentials A map of HTTP credentials"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Utils:
"""Collection of drepo utility functions"""
def createQueryConnection(remote, httpCredentials):
"""Create a query connection (HTTP or SSH) based on what's available in the given remote @param remote Remote @param httpCredentials A map of HTTP credentials"""
if remote.ssh:
... | the_stack_v2_python_sparse | du/drepo/Utils.py | spiricn/DevUtils | train | 1 |
1e66cd3ea73f9ececd888f48b045a028d5899388 | [
"if not root:\n return ''\ns = []\nunique_id = 0\nd = {}\n\ndef trav(cur):\n nonlocal unique_id\n if not cur:\n return\n unique_id += 1\n copy_uid = unique_id\n d[str(unique_id)] = str(cur.val)\n for nxt in cur.children:\n nxt_uid = trav(nxt)\n s.append(f'{(copy_uid, nxt_ui... | <|body_start_0|>
if not root:
return ''
s = []
unique_id = 0
d = {}
def trav(cur):
nonlocal unique_id
if not cur:
return
unique_id += 1
copy_uid = unique_id
d[str(unique_id)] = str(cur.val)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_032365 | 2,190 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | stack_v2_sparse_classes_30k_train_003235 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | 96e086d4ee6169c0f83fff3819f38f32b8f17c98 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
if not root:
return ''
s = []
unique_id = 0
d = {}
def trav(cur):
nonlocal unique_id
if not cur:
... | the_stack_v2_python_sparse | leetcode/428. Serialize and Deserialize N-ary Tree.py | DeshErBojhaa/sports_programming | train | 1 | |
4aa971659c2a1e41a019c6a96b4c7ce4af10ec42 | [
"obj = context.active_object\nif obj is None:\n return False\nreturn obj is not None and obj.type == 'MESH' and (obj.mode == 'EDIT')",
"pg = context.scene.pdt_pg\npg.command = f'intall'\nreturn {'FINISHED'}"
] | <|body_start_0|>
obj = context.active_object
if obj is None:
return False
return obj is not None and obj.type == 'MESH' and (obj.mode == 'EDIT')
<|end_body_0|>
<|body_start_1|>
pg = context.scene.pdt_pg
pg.command = f'intall'
return {'FINISHED'}
<|end_body_1|... | Cut Selected Edges at All Intersections | PDT_OT_IntersectAllEdges | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PDT_OT_IntersectAllEdges:
"""Cut Selected Edges at All Intersections"""
def poll(cls, context):
"""Check to see object is in correct condition. Args: context: Blender bpy.context instance. Returns: Boolean"""
<|body_0|>
def execute(self, context):
"""Computes All... | stack_v2_sparse_classes_36k_train_032366 | 7,448 | permissive | [
{
"docstring": "Check to see object is in correct condition. Args: context: Blender bpy.context instance. Returns: Boolean",
"name": "poll",
"signature": "def poll(cls, context)"
},
{
"docstring": "Computes All intersections with Crossing Geometry. Note: Deletes original edges and replaces with ... | 2 | stack_v2_sparse_classes_30k_train_006278 | Implement the Python class `PDT_OT_IntersectAllEdges` described below.
Class description:
Cut Selected Edges at All Intersections
Method signatures and docstrings:
- def poll(cls, context): Check to see object is in correct condition. Args: context: Blender bpy.context instance. Returns: Boolean
- def execute(self, c... | Implement the Python class `PDT_OT_IntersectAllEdges` described below.
Class description:
Cut Selected Edges at All Intersections
Method signatures and docstrings:
- def poll(cls, context): Check to see object is in correct condition. Args: context: Blender bpy.context instance. Returns: Boolean
- def execute(self, c... | 4d5c304878c1e0018d97c1b07bcaa3981632265a | <|skeleton|>
class PDT_OT_IntersectAllEdges:
"""Cut Selected Edges at All Intersections"""
def poll(cls, context):
"""Check to see object is in correct condition. Args: context: Blender bpy.context instance. Returns: Boolean"""
<|body_0|>
def execute(self, context):
"""Computes All... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PDT_OT_IntersectAllEdges:
"""Cut Selected Edges at All Intersections"""
def poll(cls, context):
"""Check to see object is in correct condition. Args: context: Blender bpy.context instance. Returns: Boolean"""
obj = context.active_object
if obj is None:
return False
... | the_stack_v2_python_sparse | src/bpy/3.6/scripts/addons/precision_drawing_tools/pdt_xall.py | RnoB/3DVisualSwarm | train | 0 |
8a2945974629483c959c2473f5a2fcee81de1895 | [
"lst = list(self.list_display)\nif SETTINGS.get('admin_show_publisher'):\n lst.append('original_publisher')\nreturn lst",
"if obj.generally_controlled and obj.pr_society:\n return obj.get_publisher_dict().get('publisher_name')\nreturn ''",
"super().save_model(request, obj, form, *args, **kwargs)\nif form.... | <|body_start_0|>
lst = list(self.list_display)
if SETTINGS.get('admin_show_publisher'):
lst.append('original_publisher')
return lst
<|end_body_0|>
<|body_start_1|>
if obj.generally_controlled and obj.pr_society:
return obj.get_publisher_dict().get('publisher_name... | Interface for :class:`.models.Writer`. | WriterAdmin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WriterAdmin:
"""Interface for :class:`.models.Writer`."""
def get_list_display(self, *args, **kwargs):
"""Return the list of fields based on settings. Original Publisher is important for the US."""
<|body_0|>
def original_publisher(self, obj):
"""Return the origi... | stack_v2_sparse_classes_36k_train_032367 | 33,789 | permissive | [
{
"docstring": "Return the list of fields based on settings. Original Publisher is important for the US.",
"name": "get_list_display",
"signature": "def get_list_display(self, *args, **kwargs)"
},
{
"docstring": "Return the original publisher. This makes sense only in the US context.",
"name... | 3 | stack_v2_sparse_classes_30k_train_015904 | Implement the Python class `WriterAdmin` described below.
Class description:
Interface for :class:`.models.Writer`.
Method signatures and docstrings:
- def get_list_display(self, *args, **kwargs): Return the list of fields based on settings. Original Publisher is important for the US.
- def original_publisher(self, o... | Implement the Python class `WriterAdmin` described below.
Class description:
Interface for :class:`.models.Writer`.
Method signatures and docstrings:
- def get_list_display(self, *args, **kwargs): Return the list of fields based on settings. Original Publisher is important for the US.
- def original_publisher(self, o... | 298fe497670c02951d617aa6b6a6e03995fa6562 | <|skeleton|>
class WriterAdmin:
"""Interface for :class:`.models.Writer`."""
def get_list_display(self, *args, **kwargs):
"""Return the list of fields based on settings. Original Publisher is important for the US."""
<|body_0|>
def original_publisher(self, obj):
"""Return the origi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WriterAdmin:
"""Interface for :class:`.models.Writer`."""
def get_list_display(self, *args, **kwargs):
"""Return the list of fields based on settings. Original Publisher is important for the US."""
lst = list(self.list_display)
if SETTINGS.get('admin_show_publisher'):
... | the_stack_v2_python_sparse | music_publisher/admin.py | Huanghibo/django-music-publisher | train | 1 |
d823ae640fcd9ffdb5be2fe41bd52600a4e1d557 | [
"move_pool = self.pool.get('account.move')\nmove_line_pool = self.pool.get('account.move.line')\nwf_service = netsvc.LocalService('workflow')\nfor line in self.browse(cr, uid, ids, context=context):\n journal = line.distinta_id.config.acceptance_journal_id\n total_credit = 0.0\n move_id = move_pool.create(... | <|body_start_0|>
move_pool = self.pool.get('account.move')
move_line_pool = self.pool.get('account.move.line')
wf_service = netsvc.LocalService('workflow')
for line in self.browse(cr, uid, ids, context=context):
journal = line.distinta_id.config.acceptance_journal_id
... | riba_distinta_line | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class riba_distinta_line:
def confirm(self, cr, uid, ids, context=None):
"""The new confirm method handles amount residual"""
<|body_0|>
def onchange_riba_amount(self, cr, uid, ids, amount, context=None):
"""Change amount distinta line (in draft state)"""
<|body_1|... | stack_v2_sparse_classes_36k_train_032368 | 11,195 | no_license | [
{
"docstring": "The new confirm method handles amount residual",
"name": "confirm",
"signature": "def confirm(self, cr, uid, ids, context=None)"
},
{
"docstring": "Change amount distinta line (in draft state)",
"name": "onchange_riba_amount",
"signature": "def onchange_riba_amount(self, ... | 2 | stack_v2_sparse_classes_30k_train_003507 | Implement the Python class `riba_distinta_line` described below.
Class description:
Implement the riba_distinta_line class.
Method signatures and docstrings:
- def confirm(self, cr, uid, ids, context=None): The new confirm method handles amount residual
- def onchange_riba_amount(self, cr, uid, ids, amount, context=N... | Implement the Python class `riba_distinta_line` described below.
Class description:
Implement the riba_distinta_line class.
Method signatures and docstrings:
- def confirm(self, cr, uid, ids, context=None): The new confirm method handles amount residual
- def onchange_riba_amount(self, cr, uid, ids, amount, context=N... | 78fc164679b690bcf84866987266838de134bc2f | <|skeleton|>
class riba_distinta_line:
def confirm(self, cr, uid, ids, context=None):
"""The new confirm method handles amount residual"""
<|body_0|>
def onchange_riba_amount(self, cr, uid, ids, amount, context=None):
"""Change amount distinta line (in draft state)"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class riba_distinta_line:
def confirm(self, cr, uid, ids, context=None):
"""The new confirm method handles amount residual"""
move_pool = self.pool.get('account.move')
move_line_pool = self.pool.get('account.move.line')
wf_service = netsvc.LocalService('workflow')
for line in... | the_stack_v2_python_sparse | openforce_riba_extended/riba.py | alessandrocamilli/7-openforce-addons | train | 1 | |
ec6c2326762d753e3b2b903ec46089302904aee2 | [
"if self._short_id is None:\n self._short_id = self.id\n underscore_pos = self._short_id.find('_subseries')\n if underscore_pos != -1:\n self._short_id = self._short_id[underscore_pos + 1:]\nreturn self._short_id",
"if self._title is None:\n if hasattr(self, 'did') and hasattr(self.did, 'unitti... | <|body_start_0|>
if self._short_id is None:
self._short_id = self.id
underscore_pos = self._short_id.find('_subseries')
if underscore_pos != -1:
self._short_id = self._short_id[underscore_pos + 1:]
return self._short_id
<|end_body_0|>
<|body_start_1|>... | Extended for other subseries and the last level of the hierchy (currently, c03). Customized version of :class:`eulcore.xmlmap.eadmap.Component` | SubSeries_Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubSeries_Base:
"""Extended for other subseries and the last level of the hierchy (currently, c03). Customized version of :class:`eulcore.xmlmap.eadmap.Component`"""
def short_id(self):
"""Short-form id (without eadid prefix) for use in external urls."""
<|body_0|>
def t... | stack_v2_sparse_classes_36k_train_032369 | 4,050 | no_license | [
{
"docstring": "Short-form id (without eadid prefix) for use in external urls.",
"name": "short_id",
"signature": "def short_id(self)"
},
{
"docstring": "Title of subseries without the date.",
"name": "title",
"signature": "def title(self)"
}
] | 2 | null | Implement the Python class `SubSeries_Base` described below.
Class description:
Extended for other subseries and the last level of the hierchy (currently, c03). Customized version of :class:`eulcore.xmlmap.eadmap.Component`
Method signatures and docstrings:
- def short_id(self): Short-form id (without eadid prefix) f... | Implement the Python class `SubSeries_Base` described below.
Class description:
Extended for other subseries and the last level of the hierchy (currently, c03). Customized version of :class:`eulcore.xmlmap.eadmap.Component`
Method signatures and docstrings:
- def short_id(self): Short-form id (without eadid prefix) f... | 579d926794fc5662312e3f009c4b1a0d589867c9 | <|skeleton|>
class SubSeries_Base:
"""Extended for other subseries and the last level of the hierchy (currently, c03). Customized version of :class:`eulcore.xmlmap.eadmap.Component`"""
def short_id(self):
"""Short-form id (without eadid prefix) for use in external urls."""
<|body_0|>
def t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubSeries_Base:
"""Extended for other subseries and the last level of the hierchy (currently, c03). Customized version of :class:`eulcore.xmlmap.eadmap.Component`"""
def short_id(self):
"""Short-form id (without eadid prefix) for use in external urls."""
if self._short_id is None:
... | the_stack_v2_python_sparse | keep/common/eadmap.py | emory-libraries/TheKeep | train | 0 |
ad5481e9b26a8ea9f9d56a19ed369ce6fad3ce59 | [
"user = request.user\ncheck_user_status(user)\nvalidate(instance=request.data, schema=schemas.restaurant_insert_draft_schema)\nbody = request.data\nPendingRestaurant.field_validate_draft(body)\nrestaurant = PendingRestaurant.insert(body)\nreturn JsonResponse(model_to_json(restaurant))",
"user = request.user\nchec... | <|body_start_0|>
user = request.user
check_user_status(user)
validate(instance=request.data, schema=schemas.restaurant_insert_draft_schema)
body = request.data
PendingRestaurant.field_validate_draft(body)
restaurant = PendingRestaurant.insert(body)
return JsonResp... | insert restaurant draft view | RestaurantDraftView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestaurantDraftView:
"""insert restaurant draft view"""
def post(self, request):
"""Insert new restaurant as a draft into database"""
<|body_0|>
def put(self, request):
"""Edit a restaurant profile and save it as a draft in the database"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_032370 | 19,356 | no_license | [
{
"docstring": "Insert new restaurant as a draft into database",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Edit a restaurant profile and save it as a draft in the database",
"name": "put",
"signature": "def put(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001024 | Implement the Python class `RestaurantDraftView` described below.
Class description:
insert restaurant draft view
Method signatures and docstrings:
- def post(self, request): Insert new restaurant as a draft into database
- def put(self, request): Edit a restaurant profile and save it as a draft in the database | Implement the Python class `RestaurantDraftView` described below.
Class description:
insert restaurant draft view
Method signatures and docstrings:
- def post(self, request): Insert new restaurant as a draft into database
- def put(self, request): Edit a restaurant profile and save it as a draft in the database
<|sk... | 2707062c9a9a8bb4baca955e8a60ba08cc9f8953 | <|skeleton|>
class RestaurantDraftView:
"""insert restaurant draft view"""
def post(self, request):
"""Insert new restaurant as a draft into database"""
<|body_0|>
def put(self, request):
"""Edit a restaurant profile and save it as a draft in the database"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestaurantDraftView:
"""insert restaurant draft view"""
def post(self, request):
"""Insert new restaurant as a draft into database"""
user = request.user
check_user_status(user)
validate(instance=request.data, schema=schemas.restaurant_insert_draft_schema)
body = r... | the_stack_v2_python_sparse | backend/restaurant/views.py | MochiTarts/Find-Dining-The-Bridge | train | 1 |
190403b3228f212bebaa9f8613aec6c2b6900f63 | [
"super().__init__(hyperparams, protocol_handler, data_handler, fl_model, **kwargs)\nself.name = 'Gradient-Avg-SGD'\nself.lr = self.params_global.get('lr') or 0.1\nif hyperparams.get('initial_weights') is not None:\n if not self.current_model_weights:\n logger.info('Initializing the model using initial wei... | <|body_start_0|>
super().__init__(hyperparams, protocol_handler, data_handler, fl_model, **kwargs)
self.name = 'Gradient-Avg-SGD'
self.lr = self.params_global.get('lr') or 0.1
if hyperparams.get('initial_weights') is not None:
if not self.current_model_weights:
... | Class for gradient based aggregation and aggregated gradient descent | GradientFusionHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradientFusionHandler:
"""Class for gradient based aggregation and aggregated gradient descent"""
def __init__(self, hyperparams, protocol_handler, data_handler=None, fl_model=None, **kwargs):
"""Initializes an GradientFusionHandler object with provided information, such as protocol ... | stack_v2_sparse_classes_36k_train_032371 | 3,563 | permissive | [
{
"docstring": "Initializes an GradientFusionHandler object with provided information, such as protocol handler, fl_model, data_handler and hyperparams. :param hyperparams: Hyperparameters used for training. :type hyperparams: `dict` :param protocol_handler: Protocol handler used for handling learning algorithm... | 2 | null | Implement the Python class `GradientFusionHandler` described below.
Class description:
Class for gradient based aggregation and aggregated gradient descent
Method signatures and docstrings:
- def __init__(self, hyperparams, protocol_handler, data_handler=None, fl_model=None, **kwargs): Initializes an GradientFusionHa... | Implement the Python class `GradientFusionHandler` described below.
Class description:
Class for gradient based aggregation and aggregated gradient descent
Method signatures and docstrings:
- def __init__(self, hyperparams, protocol_handler, data_handler=None, fl_model=None, **kwargs): Initializes an GradientFusionHa... | 64ffa2ee2e906b1bd6b3dd6aabcf6fc3de862608 | <|skeleton|>
class GradientFusionHandler:
"""Class for gradient based aggregation and aggregated gradient descent"""
def __init__(self, hyperparams, protocol_handler, data_handler=None, fl_model=None, **kwargs):
"""Initializes an GradientFusionHandler object with provided information, such as protocol ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GradientFusionHandler:
"""Class for gradient based aggregation and aggregated gradient descent"""
def __init__(self, hyperparams, protocol_handler, data_handler=None, fl_model=None, **kwargs):
"""Initializes an GradientFusionHandler object with provided information, such as protocol handler, fl_m... | the_stack_v2_python_sparse | debugging-constructs/ibmfl/aggregator/fusion/gradient_fusion_handler.py | SEED-VT/FedDebug | train | 8 |
3cdf5ddd7311079b2f7727992b7d3d16e6b3c8ef | [
"square1 = PolybiusSquare(alphabet, key[0])\nsquare2 = PolybiusSquare(alphabet, key[1])\nsquare3 = PolybiusSquare(alphabet, key[2])\nres = []\nit = iter(text)\nrows = square1.get_rows()\ncols = square2.get_columns()\nwhile True:\n try:\n t = next(it)\n except StopIteration:\n break\n row1, co... | <|body_start_0|>
square1 = PolybiusSquare(alphabet, key[0])
square2 = PolybiusSquare(alphabet, key[1])
square3 = PolybiusSquare(alphabet, key[2])
res = []
it = iter(text)
rows = square1.get_rows()
cols = square2.get_columns()
while True:
try:
... | The Three Square Cipher | ThreeSquare | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreeSquare:
"""The Three Square Cipher"""
def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ):
"""Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, if there is no a value, English is used :type text: strin... | stack_v2_sparse_classes_36k_train_032372 | 2,590 | permissive | [
{
"docstring": "Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, if there is no a value, English is used :type text: string :type key: tuple of 3 strings :type alphabet: string :return: text :rtype: string",
"name": "encrypt",
"signa... | 2 | stack_v2_sparse_classes_30k_train_005853 | Implement the Python class `ThreeSquare` described below.
Class description:
The Three Square Cipher
Method signatures and docstrings:
- def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ): Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, ... | Implement the Python class `ThreeSquare` described below.
Class description:
The Three Square Cipher
Method signatures and docstrings:
- def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ): Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, ... | e464f998e5540f52e269fe360ec9d3a08e976b2e | <|skeleton|>
class ThreeSquare:
"""The Three Square Cipher"""
def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ):
"""Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, if there is no a value, English is used :type text: strin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreeSquare:
"""The Three Square Cipher"""
def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ):
"""Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, if there is no a value, English is used :type text: string :type key: ... | the_stack_v2_python_sparse | secretpy/ciphers/three_square.py | tigertv/secretpy | train | 65 |
be96b9bf484a3a706e5cb39905bd52c347828982 | [
"perm = CanEditIfOwner()\nfor method in ('GET', 'HEAD', 'OPTIONS'):\n request = Mock(method=method)\n with mute_signals(post_save):\n profile = ProfileFactory.create()\n assert perm.has_object_permission(request, None, profile)",
"perm = CanEditIfOwner()\nfor method in ('POST', 'PATCH', 'PUT'):\n ... | <|body_start_0|>
perm = CanEditIfOwner()
for method in ('GET', 'HEAD', 'OPTIONS'):
request = Mock(method=method)
with mute_signals(post_save):
profile = ProfileFactory.create()
assert perm.has_object_permission(request, None, profile)
<|end_body_0|>
<... | Tests for CanEditIfOwner permissions | CanEditIfOwnerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanEditIfOwnerTests:
"""Tests for CanEditIfOwner permissions"""
def test_allow_nonedit(self):
"""Users are allowed to use safe methods without owning the profile."""
<|body_0|>
def test_edit_if_owner(self):
"""Users are allowed to edit their own profile"""
... | stack_v2_sparse_classes_36k_train_032373 | 7,670 | permissive | [
{
"docstring": "Users are allowed to use safe methods without owning the profile.",
"name": "test_allow_nonedit",
"signature": "def test_allow_nonedit(self)"
},
{
"docstring": "Users are allowed to edit their own profile",
"name": "test_edit_if_owner",
"signature": "def test_edit_if_owne... | 3 | stack_v2_sparse_classes_30k_train_004252 | Implement the Python class `CanEditIfOwnerTests` described below.
Class description:
Tests for CanEditIfOwner permissions
Method signatures and docstrings:
- def test_allow_nonedit(self): Users are allowed to use safe methods without owning the profile.
- def test_edit_if_owner(self): Users are allowed to edit their ... | Implement the Python class `CanEditIfOwnerTests` described below.
Class description:
Tests for CanEditIfOwner permissions
Method signatures and docstrings:
- def test_allow_nonedit(self): Users are allowed to use safe methods without owning the profile.
- def test_edit_if_owner(self): Users are allowed to edit their ... | d6564caca0b7bbfd31e67a751564107fd17d6eb0 | <|skeleton|>
class CanEditIfOwnerTests:
"""Tests for CanEditIfOwner permissions"""
def test_allow_nonedit(self):
"""Users are allowed to use safe methods without owning the profile."""
<|body_0|>
def test_edit_if_owner(self):
"""Users are allowed to edit their own profile"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CanEditIfOwnerTests:
"""Tests for CanEditIfOwner permissions"""
def test_allow_nonedit(self):
"""Users are allowed to use safe methods without owning the profile."""
perm = CanEditIfOwner()
for method in ('GET', 'HEAD', 'OPTIONS'):
request = Mock(method=method)
... | the_stack_v2_python_sparse | profiles/permissions_test.py | mitodl/micromasters | train | 35 |
9443f683ab8ef3925744eb73d332518f9ef85c2a | [
"n = str(len(strs))\nprefix = [str(n), '#']\nfor s in strs:\n prefix.append(str(len(s)))\n prefix.append('#')\nreturn ''.join(prefix + strs)",
"i = 0\nn, i = extract_int(s, i)\ni += 1\nsizes = []\nfor _ in range(n):\n size, i = extract_int(s, i)\n sizes.append(size)\n i += 1\nres = []\nfor size in ... | <|body_start_0|>
n = str(len(strs))
prefix = [str(n), '#']
for s in strs:
prefix.append(str(len(s)))
prefix.append('#')
return ''.join(prefix + strs)
<|end_body_0|>
<|body_start_1|>
i = 0
n, i = extract_int(s, i)
i += 1
sizes = []
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_032374 | 1,127 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | f4da5a5dbda640b9bcbe14cb60a72c422b5d6240 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
n = str(len(strs))
prefix = [str(n), '#']
for s in strs:
prefix.append(str(len(s)))
prefix.append('#')
return ''.join(prefix + st... | the_stack_v2_python_sparse | leetcode/271.encode-and-decode-strings.py | phlalx/algorithms | train | 0 | |
7431e70c6294239576058da074c42a116f071f27 | [
"game = crowd_modelling.MFGCrowdModellingGame()\nfp = fictitious_play.FictitiousPlay(game)\nfor _ in range(10):\n fp.iteration()\nfp_policy = fp.get_policy()\nnash_conv_fp = nash_conv.NashConv(game, fp_policy)\nself.assertAlmostEqual(nash_conv_fp.nash_conv(), 0.9908032626911343)",
"game = crowd_modelling.MFGCr... | <|body_start_0|>
game = crowd_modelling.MFGCrowdModellingGame()
fp = fictitious_play.FictitiousPlay(game)
for _ in range(10):
fp.iteration()
fp_policy = fp.get_policy()
nash_conv_fp = nash_conv.NashConv(game, fp_policy)
self.assertAlmostEqual(nash_conv_fp.nash... | FictitiousPlayTest | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FictitiousPlayTest:
def test_fp_python_game(self):
"""Checks if fictitious play works."""
<|body_0|>
def test_dqn_fp_python_game(self):
"""Checks if fictitious play with DQN-based value function works."""
<|body_1|>
def test_average(self):
"""Tes... | stack_v2_sparse_classes_36k_train_032375 | 5,445 | permissive | [
{
"docstring": "Checks if fictitious play works.",
"name": "test_fp_python_game",
"signature": "def test_fp_python_game(self)"
},
{
"docstring": "Checks if fictitious play with DQN-based value function works.",
"name": "test_dqn_fp_python_game",
"signature": "def test_dqn_fp_python_game(... | 5 | null | Implement the Python class `FictitiousPlayTest` described below.
Class description:
Implement the FictitiousPlayTest class.
Method signatures and docstrings:
- def test_fp_python_game(self): Checks if fictitious play works.
- def test_dqn_fp_python_game(self): Checks if fictitious play with DQN-based value function w... | Implement the Python class `FictitiousPlayTest` described below.
Class description:
Implement the FictitiousPlayTest class.
Method signatures and docstrings:
- def test_fp_python_game(self): Checks if fictitious play works.
- def test_dqn_fp_python_game(self): Checks if fictitious play with DQN-based value function w... | 6f3551fd990053cf2287b380fb9ad0b2a2607c18 | <|skeleton|>
class FictitiousPlayTest:
def test_fp_python_game(self):
"""Checks if fictitious play works."""
<|body_0|>
def test_dqn_fp_python_game(self):
"""Checks if fictitious play with DQN-based value function works."""
<|body_1|>
def test_average(self):
"""Tes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FictitiousPlayTest:
def test_fp_python_game(self):
"""Checks if fictitious play works."""
game = crowd_modelling.MFGCrowdModellingGame()
fp = fictitious_play.FictitiousPlay(game)
for _ in range(10):
fp.iteration()
fp_policy = fp.get_policy()
nash_con... | the_stack_v2_python_sparse | open_spiel/python/mfg/algorithms/fictitious_play_test.py | sarahperrin/open_spiel | train | 3 | |
e883bfdb1f4a15131c819b93e74b2c85909a434f | [
"if not matrix:\n return 0\nn = len(matrix)\nm = len(matrix[0])\ndp = [[0 for _ in xrange(m)] for _ in xrange(n)]\nmax_length = 0\nfor i in xrange(n):\n for j in xrange(m):\n if i == 0 or j == 0:\n dp[i][j] = int(matrix[i][j])\n elif matrix[i][j] == '1':\n dp[i][j] = min(dp... | <|body_start_0|>
if not matrix:
return 0
n = len(matrix)
m = len(matrix[0])
dp = [[0 for _ in xrange(m)] for _ in xrange(n)]
max_length = 0
for i in xrange(n):
for j in xrange(m):
if i == 0 or j == 0:
dp[i][j] = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalSquare(self, matrix):
"""DP solution."""
<|body_0|>
def maximalSquareNCubic(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not matrix:
return 0
... | stack_v2_sparse_classes_36k_train_032376 | 2,983 | no_license | [
{
"docstring": "DP solution.",
"name": "maximalSquare",
"signature": "def maximalSquare(self, matrix)"
},
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquareNCubic",
"signature": "def maximalSquareNCubic(self, matrix)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001434 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, matrix): DP solution.
- def maximalSquareNCubic(self, matrix): :type matrix: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, matrix): DP solution.
- def maximalSquareNCubic(self, matrix): :type matrix: List[List[str]] :rtype: int
<|skeleton|>
class Solution:
def maximalSqu... | 33c623f226981942780751554f0593f2c71cf458 | <|skeleton|>
class Solution:
def maximalSquare(self, matrix):
"""DP solution."""
<|body_0|>
def maximalSquareNCubic(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maximalSquare(self, matrix):
"""DP solution."""
if not matrix:
return 0
n = len(matrix)
m = len(matrix[0])
dp = [[0 for _ in xrange(m)] for _ in xrange(n)]
max_length = 0
for i in xrange(n):
for j in xrange(m):
... | the_stack_v2_python_sparse | dynamic_programming/leetcode_Maximum_Square.py | monkeylyf/interviewjam | train | 59 | |
8f7e0dec1976d6cb361cd35f86a6a7b12fd5184f | [
"super(AgentStabilityML5, self).__init__(candidate_data=candidate_data, seed_data=seed_data, n_query=n_query, hull_distance=hull_distance, parallel=parallel)\nself.model = model or LinearRegression()\nself.exploit_fraction = exploit_fraction",
"X_cand, X_seed, y_seed = self.update_data(candidate_data, seed_data)\... | <|body_start_0|>
super(AgentStabilityML5, self).__init__(candidate_data=candidate_data, seed_data=seed_data, n_query=n_query, hull_distance=hull_distance, parallel=parallel)
self.model = model or LinearRegression()
self.exploit_fraction = exploit_fraction
<|end_body_0|>
<|body_start_1|>
... | An agent that does a certain fraction of full exploration and exploitation in each iteration. It will exploit a fraction of N_query options (frac), and explore the rest of its budget. | AgentStabilityML5 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgentStabilityML5:
"""An agent that does a certain fraction of full exploration and exploitation in each iteration. It will exploit a fraction of N_query options (frac), and explore the rest of its budget."""
def __init__(self, candidate_data=None, seed_data=None, n_query=1, hull_distance=0.... | stack_v2_sparse_classes_36k_train_032377 | 38,060 | permissive | [
{
"docstring": "Args: candidate_data (DataFrame): data about the candidates seed_data (DataFrame): data which to fit the Agent to n_query (int): number of hypotheses to generate hull_distance (float): hull distance as a criteria for which to deem a given material as \"stable\" parallel (bool): whether to use mu... | 2 | stack_v2_sparse_classes_30k_train_002184 | Implement the Python class `AgentStabilityML5` described below.
Class description:
An agent that does a certain fraction of full exploration and exploitation in each iteration. It will exploit a fraction of N_query options (frac), and explore the rest of its budget.
Method signatures and docstrings:
- def __init__(se... | Implement the Python class `AgentStabilityML5` described below.
Class description:
An agent that does a certain fraction of full exploration and exploitation in each iteration. It will exploit a fraction of N_query options (frac), and explore the rest of its budget.
Method signatures and docstrings:
- def __init__(se... | 905f5d577513d1ca5a54fac3d381525e0fe3576a | <|skeleton|>
class AgentStabilityML5:
"""An agent that does a certain fraction of full exploration and exploitation in each iteration. It will exploit a fraction of N_query options (frac), and explore the rest of its budget."""
def __init__(self, candidate_data=None, seed_data=None, n_query=1, hull_distance=0.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AgentStabilityML5:
"""An agent that does a certain fraction of full exploration and exploitation in each iteration. It will exploit a fraction of N_query options (frac), and explore the rest of its budget."""
def __init__(self, candidate_data=None, seed_data=None, n_query=1, hull_distance=0.0, parallel=c... | the_stack_v2_python_sparse | camd/agent/stability.py | apalizha/CAMD | train | 0 |
79a79a52a7e610447fec27dad59384e673f05400 | [
"super().__init__()\nself.Q = Q\nself.workF = workFunc\nself.period = 1.0 / updateHz\nself.stopToken = stopToken\nself.killed = False\nself.count = 0\nself._DEBUG = 1",
"self.Q.put(time())\nwhile 1:\n item = self.Q.get()\n if item == self.stopToken:\n break\n else:\n t_dif = item - time()\n... | <|body_start_0|>
super().__init__()
self.Q = Q
self.workF = workFunc
self.period = 1.0 / updateHz
self.stopToken = stopToken
self.killed = False
self.count = 0
self._DEBUG = 1
<|end_body_0|>
<|body_start_1|>
self.Q.put(time())
while 1:
... | Continue to do work until the thread is killed | TimerThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimerThread:
"""Continue to do work until the thread is killed"""
def __init__(self, Q, workFunc, updateHz, stopToken=None):
"""Set up worker and queue management"""
<|body_0|>
def run(self):
"""Execute the work function repeatedly until asked to stop"""
... | stack_v2_sparse_classes_36k_train_032378 | 3,564 | no_license | [
{
"docstring": "Set up worker and queue management",
"name": "__init__",
"signature": "def __init__(self, Q, workFunc, updateHz, stopToken=None)"
},
{
"docstring": "Execute the work function repeatedly until asked to stop",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021590 | Implement the Python class `TimerThread` described below.
Class description:
Continue to do work until the thread is killed
Method signatures and docstrings:
- def __init__(self, Q, workFunc, updateHz, stopToken=None): Set up worker and queue management
- def run(self): Execute the work function repeatedly until aske... | Implement the Python class `TimerThread` described below.
Class description:
Continue to do work until the thread is killed
Method signatures and docstrings:
- def __init__(self, Q, workFunc, updateHz, stopToken=None): Set up worker and queue management
- def run(self): Execute the work function repeatedly until aske... | 297f9f5733fe256e5c96f2da82f49d82c2a4ba9d | <|skeleton|>
class TimerThread:
"""Continue to do work until the thread is killed"""
def __init__(self, Q, workFunc, updateHz, stopToken=None):
"""Set up worker and queue management"""
<|body_0|>
def run(self):
"""Execute the work function repeatedly until asked to stop"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimerThread:
"""Continue to do work until the thread is killed"""
def __init__(self, Q, workFunc, updateHz, stopToken=None):
"""Set up worker and queue management"""
super().__init__()
self.Q = Q
self.workF = workFunc
self.period = 1.0 / updateHz
self.stopT... | the_stack_v2_python_sparse | Learning/threading_examples.py | jwatson-CO-edu/py_info | train | 0 |
a1985af3fd7ab6331761630e066f5825900bbe66 | [
"for line, record_type, key, value in LineTests.records:\n line = lncore.Line(line)\n assert line.record_type == record_type\n assert line.key == key\n assert line.value == value",
"for line, line_type in LineTests.lines:\n line = lncore.Line(line)\n assert line.line_type == line_type"
] | <|body_start_0|>
for line, record_type, key, value in LineTests.records:
line = lncore.Line(line)
assert line.record_type == record_type
assert line.key == key
assert line.value == value
<|end_body_0|>
<|body_start_1|>
for line, line_type in LineTests.lin... | Test line recognition. DOC testRecordInterpretation -- test record details testLineInterpretation -- test line types | LineTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LineTests:
"""Test line recognition. DOC testRecordInterpretation -- test record details testLineInterpretation -- test line types"""
def testRecordInterpretation(self):
"""Test details of record line interpretation."""
<|body_0|>
def testLineInterpretation(self):
... | stack_v2_sparse_classes_36k_train_032379 | 34,773 | no_license | [
{
"docstring": "Test details of record line interpretation.",
"name": "testRecordInterpretation",
"signature": "def testRecordInterpretation(self)"
},
{
"docstring": "Test that line types are proprely recognized.",
"name": "testLineInterpretation",
"signature": "def testLineInterpretatio... | 2 | stack_v2_sparse_classes_30k_train_017144 | Implement the Python class `LineTests` described below.
Class description:
Test line recognition. DOC testRecordInterpretation -- test record details testLineInterpretation -- test line types
Method signatures and docstrings:
- def testRecordInterpretation(self): Test details of record line interpretation.
- def test... | Implement the Python class `LineTests` described below.
Class description:
Test line recognition. DOC testRecordInterpretation -- test record details testLineInterpretation -- test line types
Method signatures and docstrings:
- def testRecordInterpretation(self): Test details of record line interpretation.
- def test... | da65d948b346d3f455e79168a8753b2b16d8fc5f | <|skeleton|>
class LineTests:
"""Test line recognition. DOC testRecordInterpretation -- test record details testLineInterpretation -- test line types"""
def testRecordInterpretation(self):
"""Test details of record line interpretation."""
<|body_0|>
def testLineInterpretation(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LineTests:
"""Test line recognition. DOC testRecordInterpretation -- test record details testLineInterpretation -- test line types"""
def testRecordInterpretation(self):
"""Test details of record line interpretation."""
for line, record_type, key, value in LineTests.records:
l... | the_stack_v2_python_sparse | pre2007/lncore/test.py | BackupTheBerlios/onebigsoup-svn | train | 0 |
2c1ce9b33fc0b7ac96c0e683692982322e64f2ae | [
"try:\n q = quantity.Flux(1.0, 'm^-2*s^-1')\n self.fail('Allowed invalid unit type \"m^-2*s^-1\".')\nexcept quantity.QuantityError:\n pass",
"q = quantity.Flux(1.0, 'mol/(m^2*s)')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)\nself.assertEqual(q.units, 'mo... | <|body_start_0|>
try:
q = quantity.Flux(1.0, 'm^-2*s^-1')
self.fail('Allowed invalid unit type "m^-2*s^-1".')
except quantity.QuantityError:
pass
<|end_body_0|>
<|body_start_1|>
q = quantity.Flux(1.0, 'mol/(m^2*s)')
self.assertAlmostEqual(q.value, 1.0... | Contains unit tests of the Flux unit type object. | TestFlux | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFlux:
"""Contains unit tests of the Flux unit type object."""
def test_perm2pers(self):
"""Test the creation of a flux quantity with units of m^-2*s^-1."""
<|body_0|>
def test_molperm3(self):
"""Test the creation of a flux quantity with units of mol/(m^2*s)."... | stack_v2_sparse_classes_36k_train_032380 | 33,010 | permissive | [
{
"docstring": "Test the creation of a flux quantity with units of m^-2*s^-1.",
"name": "test_perm2pers",
"signature": "def test_perm2pers(self)"
},
{
"docstring": "Test the creation of a flux quantity with units of mol/(m^2*s).",
"name": "test_molperm3",
"signature": "def test_molperm3(... | 3 | stack_v2_sparse_classes_30k_train_003154 | Implement the Python class `TestFlux` described below.
Class description:
Contains unit tests of the Flux unit type object.
Method signatures and docstrings:
- def test_perm2pers(self): Test the creation of a flux quantity with units of m^-2*s^-1.
- def test_molperm3(self): Test the creation of a flux quantity with u... | Implement the Python class `TestFlux` described below.
Class description:
Contains unit tests of the Flux unit type object.
Method signatures and docstrings:
- def test_perm2pers(self): Test the creation of a flux quantity with units of m^-2*s^-1.
- def test_molperm3(self): Test the creation of a flux quantity with u... | 0937b2e0a955dcf21b79674a4e89f43941c0dd85 | <|skeleton|>
class TestFlux:
"""Contains unit tests of the Flux unit type object."""
def test_perm2pers(self):
"""Test the creation of a flux quantity with units of m^-2*s^-1."""
<|body_0|>
def test_molperm3(self):
"""Test the creation of a flux quantity with units of mol/(m^2*s)."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestFlux:
"""Contains unit tests of the Flux unit type object."""
def test_perm2pers(self):
"""Test the creation of a flux quantity with units of m^-2*s^-1."""
try:
q = quantity.Flux(1.0, 'm^-2*s^-1')
self.fail('Allowed invalid unit type "m^-2*s^-1".')
exce... | the_stack_v2_python_sparse | rmgpy/quantityTest.py | vrlambert/RMG-Py | train | 1 |
bf3740564425b6217ae49aba2f0663fb126d8fe9 | [
"data = super().to_representation(instance)\nif 'request' in self.context and self.context['request'].method != 'POST' and (self.context['request'].user.username not in getattr(settings, 'UNMASKED_ATHLETE_USERS', [])):\n for field in ['date_of_birth', 'gender']:\n data.pop(field, None)\nreturn data",
"u... | <|body_start_0|>
data = super().to_representation(instance)
if 'request' in self.context and self.context['request'].method != 'POST' and (self.context['request'].user.username not in getattr(settings, 'UNMASKED_ATHLETE_USERS', [])):
for field in ['date_of_birth', 'gender']:
... | Serializer for athletes. | AthleteSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AthleteSerializer:
"""Serializer for athletes."""
def to_representation(self, instance):
"""Hide gender and date_of_birth unless POST or user is in UNMASKED_ATHLETE_USERS settings list."""
<|body_0|>
def validate(self, data):
"""Check permissions to create an ath... | stack_v2_sparse_classes_36k_train_032381 | 4,097 | permissive | [
{
"docstring": "Hide gender and date_of_birth unless POST or user is in UNMASKED_ATHLETE_USERS settings list.",
"name": "to_representation",
"signature": "def to_representation(self, instance)"
},
{
"docstring": "Check permissions to create an athlete. External organization athletes may be creat... | 2 | stack_v2_sparse_classes_30k_train_003619 | Implement the Python class `AthleteSerializer` described below.
Class description:
Serializer for athletes.
Method signatures and docstrings:
- def to_representation(self, instance): Hide gender and date_of_birth unless POST or user is in UNMASKED_ATHLETE_USERS settings list.
- def validate(self, data): Check permiss... | Implement the Python class `AthleteSerializer` described below.
Class description:
Serializer for athletes.
Method signatures and docstrings:
- def to_representation(self, instance): Hide gender and date_of_birth unless POST or user is in UNMASKED_ATHLETE_USERS settings list.
- def validate(self, data): Check permiss... | bd7d9d3c9c3f1ac58884bbd316f57b9064df00cf | <|skeleton|>
class AthleteSerializer:
"""Serializer for athletes."""
def to_representation(self, instance):
"""Hide gender and date_of_birth unless POST or user is in UNMASKED_ATHLETE_USERS settings list."""
<|body_0|>
def validate(self, data):
"""Check permissions to create an ath... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AthleteSerializer:
"""Serializer for athletes."""
def to_representation(self, instance):
"""Hide gender and date_of_birth unless POST or user is in UNMASKED_ATHLETE_USERS settings list."""
data = super().to_representation(instance)
if 'request' in self.context and self.context['re... | the_stack_v2_python_sparse | results/serializers/athletes.py | sal-kiti/sal-kiti | train | 2 |
bd5df34a6a786af4e589e6c505a5de8b1a91a0e8 | [
"self.graphemes = 'None'\nself.soft_triggers = 'None'\nself.soft_map = 'None'\nself.hard_triggers = 'None'\nself.hard_map = 'None'\nself.spirant_triggers = 'None'\nself.spirant_map = 'None'\nself.mixed_triggers = 'None'\nself.mixed_map = 'None'\nself.nasal_triggers = 'None'\nself.nasal_map = 'None'\nself.lenition_t... | <|body_start_0|>
self.graphemes = 'None'
self.soft_triggers = 'None'
self.soft_map = 'None'
self.hard_triggers = 'None'
self.hard_map = 'None'
self.spirant_triggers = 'None'
self.spirant_map = 'None'
self.mixed_triggers = 'None'
self.mixed_map = 'N... | A class containing language-specific info for Celtic consonant mutation. Attributes: graphemes: A union of strings of the graphemes of the language. soft_triggers: A union of strings of soft mutation triggers. soft_map: A string_map or union of transducers for the soft mutation. hard_triggers: A union of strings of har... | CelticMutationHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CelticMutationHandler:
"""A class containing language-specific info for Celtic consonant mutation. Attributes: graphemes: A union of strings of the graphemes of the language. soft_triggers: A union of strings of soft mutation triggers. soft_map: A string_map or union of transducers for the soft m... | stack_v2_sparse_classes_36k_train_032382 | 6,059 | permissive | [
{
"docstring": "Initialize attributes to none, other methods will set as needed.",
"name": "__init__",
"signature": "def __init__(self: str) -> None"
},
{
"docstring": "Handler for Breton-specific information.",
"name": "breton_handler",
"signature": "def breton_handler(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_010552 | Implement the Python class `CelticMutationHandler` described below.
Class description:
A class containing language-specific info for Celtic consonant mutation. Attributes: graphemes: A union of strings of the graphemes of the language. soft_triggers: A union of strings of soft mutation triggers. soft_map: A string_map... | Implement the Python class `CelticMutationHandler` described below.
Class description:
A class containing language-specific info for Celtic consonant mutation. Attributes: graphemes: A union of strings of the graphemes of the language. soft_triggers: A union of strings of soft mutation triggers. soft_map: A string_map... | 500c08f863539fc3aa6d000307c91b25848e1adc | <|skeleton|>
class CelticMutationHandler:
"""A class containing language-specific info for Celtic consonant mutation. Attributes: graphemes: A union of strings of the graphemes of the language. soft_triggers: A union of strings of soft mutation triggers. soft_map: A string_map or union of transducers for the soft m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CelticMutationHandler:
"""A class containing language-specific info for Celtic consonant mutation. Attributes: graphemes: A union of strings of the graphemes of the language. soft_triggers: A union of strings of soft mutation triggers. soft_map: A string_map or union of transducers for the soft mutation. hard... | the_stack_v2_python_sparse | starter_project/mutation_handler.py | googleinterns/text-norm-for-low-resource-languages | train | 2 |
50d7f65b7684c32ed5e2f7612c2eb73b9dd046fa | [
"if surveyname == 'DES':\n filename = 'DESround13.txt'\nelse:\n raise ValueError('survey %s you requested is not in the list' % surveyname)\nfilename = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'PackageData', filename))\nreturn filename",
"f2 = open(filename, 'r')\nlines = f2.readl... | <|body_start_0|>
if surveyname == 'DES':
filename = 'DESround13.txt'
else:
raise ValueError('survey %s you requested is not in the list' % surveyname)
filename = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'PackageData', filename))
return f... | contains checks for a certain coordinate and survey name | CheckFootprint | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckFootprint:
"""contains checks for a certain coordinate and survey name"""
def select_survey(self, surveyname):
"""selects survey data to be read in"""
<|body_0|>
def get_survey_data(self, filename):
"""returns raFoot and decFoot from the specified .txt file"... | stack_v2_sparse_classes_36k_train_032383 | 4,247 | permissive | [
{
"docstring": "selects survey data to be read in",
"name": "select_survey",
"signature": "def select_survey(self, surveyname)"
},
{
"docstring": "returns raFoot and decFoot from the specified .txt file",
"name": "get_survey_data",
"signature": "def get_survey_data(self, filename)"
},
... | 3 | stack_v2_sparse_classes_30k_train_021001 | Implement the Python class `CheckFootprint` described below.
Class description:
contains checks for a certain coordinate and survey name
Method signatures and docstrings:
- def select_survey(self, surveyname): selects survey data to be read in
- def get_survey_data(self, filename): returns raFoot and decFoot from the... | Implement the Python class `CheckFootprint` described below.
Class description:
contains checks for a certain coordinate and survey name
Method signatures and docstrings:
- def select_survey(self, surveyname): selects survey data to be read in
- def get_survey_data(self, filename): returns raFoot and decFoot from the... | d2223705bc44d07575a5e93291375ab8e69ebfa8 | <|skeleton|>
class CheckFootprint:
"""contains checks for a certain coordinate and survey name"""
def select_survey(self, surveyname):
"""selects survey data to be read in"""
<|body_0|>
def get_survey_data(self, filename):
"""returns raFoot and decFoot from the specified .txt file"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckFootprint:
"""contains checks for a certain coordinate and survey name"""
def select_survey(self, surveyname):
"""selects survey data to be read in"""
if surveyname == 'DES':
filename = 'DESround13.txt'
else:
raise ValueError('survey %s you requested i... | the_stack_v2_python_sparse | astrofunc/Footprint/footprint.py | sibirrer/astrofunc | train | 0 |
1f3eba17243a90d30720a9954fb985d5094c8ff6 | [
"username = self.cleaned_data['username']\nif User.objects.filter(username=username) or RegisterUser.objects.filter(username=username):\n raise forms.ValidationError('El usuario ya existe en usuarios o registro temporal.')\nreturn username",
"email = self.cleaned_data['email']\nif User.objects.filter(email=ema... | <|body_start_0|>
username = self.cleaned_data['username']
if User.objects.filter(username=username) or RegisterUser.objects.filter(username=username):
raise forms.ValidationError('El usuario ya existe en usuarios o registro temporal.')
return username
<|end_body_0|>
<|body_start_1|>... | Form crear usuario en admin. | UserCreationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCreationForm:
"""Form crear usuario en admin."""
def clean_username(self):
"""Comprueba que username no este registrado. También lo prueba en la tabla RegisterUser."""
<|body_0|>
def clean_email(self):
"""Email no puede ser repetido. También lo prueba en la t... | stack_v2_sparse_classes_36k_train_032384 | 3,955 | no_license | [
{
"docstring": "Comprueba que username no este registrado. También lo prueba en la tabla RegisterUser.",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "Email no puede ser repetido. También lo prueba en la tabla RegisterUser",
"name": "clean_email",
"... | 2 | stack_v2_sparse_classes_30k_train_013428 | Implement the Python class `UserCreationForm` described below.
Class description:
Form crear usuario en admin.
Method signatures and docstrings:
- def clean_username(self): Comprueba que username no este registrado. También lo prueba en la tabla RegisterUser.
- def clean_email(self): Email no puede ser repetido. Tamb... | Implement the Python class `UserCreationForm` described below.
Class description:
Form crear usuario en admin.
Method signatures and docstrings:
- def clean_username(self): Comprueba que username no este registrado. También lo prueba en la tabla RegisterUser.
- def clean_email(self): Email no puede ser repetido. Tamb... | 44b8d2934105ccbf02ff6c20896aa8c2b1746eaa | <|skeleton|>
class UserCreationForm:
"""Form crear usuario en admin."""
def clean_username(self):
"""Comprueba que username no este registrado. También lo prueba en la tabla RegisterUser."""
<|body_0|>
def clean_email(self):
"""Email no puede ser repetido. También lo prueba en la t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserCreationForm:
"""Form crear usuario en admin."""
def clean_username(self):
"""Comprueba que username no este registrado. También lo prueba en la tabla RegisterUser."""
username = self.cleaned_data['username']
if User.objects.filter(username=username) or RegisterUser.objects.fi... | the_stack_v2_python_sparse | src/apps/accounts/forms.py | snicoper/ofervivienda | train | 1 |
0029ba94a7095e342fb1396a706f416ecaa25518 | [
"self.name = name\nsuper().__init__(data=data, arguments=self.name)\nself.change_thickness(element='header', thickness=header_thickness)\nself.change_thickness(element='footer', thickness=footer_thickness)\nself.append(Head())\nself.append(Foot())",
"if element == 'header':\n self.data.append(Command('renewcom... | <|body_start_0|>
self.name = name
super().__init__(data=data, arguments=self.name)
self.change_thickness(element='header', thickness=header_thickness)
self.change_thickness(element='footer', thickness=footer_thickness)
self.append(Head())
self.append(Foot())
<|end_body_0|... | Allows the creation of new page styles. | PageStyle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PageStyle:
"""Allows the creation of new page styles."""
def __init__(self, name, *, header_thickness=0, footer_thickness=0, data=None):
"""Args ---- name: str The name of the page style header_thickness: float Value to set for the line under the header footer_thickness: float Value ... | stack_v2_sparse_classes_36k_train_032385 | 2,957 | permissive | [
{
"docstring": "Args ---- name: str The name of the page style header_thickness: float Value to set for the line under the header footer_thickness: float Value to set for the line over the footer data: str or `~.LatexObject` The data to place inside the PageStyle",
"name": "__init__",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_010570 | Implement the Python class `PageStyle` described below.
Class description:
Allows the creation of new page styles.
Method signatures and docstrings:
- def __init__(self, name, *, header_thickness=0, footer_thickness=0, data=None): Args ---- name: str The name of the page style header_thickness: float Value to set for... | Implement the Python class `PageStyle` described below.
Class description:
Allows the creation of new page styles.
Method signatures and docstrings:
- def __init__(self, name, *, header_thickness=0, footer_thickness=0, data=None): Args ---- name: str The name of the page style header_thickness: float Value to set for... | 2050b14d8d7ed4fe788c769afec6816e2b703355 | <|skeleton|>
class PageStyle:
"""Allows the creation of new page styles."""
def __init__(self, name, *, header_thickness=0, footer_thickness=0, data=None):
"""Args ---- name: str The name of the page style header_thickness: float Value to set for the line under the header footer_thickness: float Value ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PageStyle:
"""Allows the creation of new page styles."""
def __init__(self, name, *, header_thickness=0, footer_thickness=0, data=None):
"""Args ---- name: str The name of the page style header_thickness: float Value to set for the line under the header footer_thickness: float Value to set for th... | the_stack_v2_python_sparse | pylatex/headfoot.py | JelteF/PyLaTeX | train | 2,104 |
d8f2da941f0f28ce849d05c5b387b053fcb42a6d | [
"if not self.auth_based():\n self.set_secure_cookie('username', 'none')\n self.redirect('/')\n return\nif self.get_current_user():\n self.redirect('/')\n return\nself.render('login.html', error=self.get_argument('error', ''))",
"username = self.get_argument('username', '')\npassword = self.get_argu... | <|body_start_0|>
if not self.auth_based():
self.set_secure_cookie('username', 'none')
self.redirect('/')
return
if self.get_current_user():
self.redirect('/')
return
self.render('login.html', error=self.get_argument('error', ''))
<|end_... | Login page handler. | AuthLoginHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthLoginHandler:
"""Login page handler."""
def get(self):
"""Render login page."""
<|body_0|>
def post(self):
"""Process login credentials."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not self.auth_based():
self.set_secure_co... | stack_v2_sparse_classes_36k_train_032386 | 16,584 | permissive | [
{
"docstring": "Render login page.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Process login credentials.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009277 | Implement the Python class `AuthLoginHandler` described below.
Class description:
Login page handler.
Method signatures and docstrings:
- def get(self): Render login page.
- def post(self): Process login credentials. | Implement the Python class `AuthLoginHandler` described below.
Class description:
Login page handler.
Method signatures and docstrings:
- def get(self): Render login page.
- def post(self): Process login credentials.
<|skeleton|>
class AuthLoginHandler:
"""Login page handler."""
def get(self):
"""Re... | 38eac8eebf57da4bec07518383ab65a5544445fe | <|skeleton|>
class AuthLoginHandler:
"""Login page handler."""
def get(self):
"""Render login page."""
<|body_0|>
def post(self):
"""Process login credentials."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthLoginHandler:
"""Login page handler."""
def get(self):
"""Render login page."""
if not self.auth_based():
self.set_secure_cookie('username', 'none')
self.redirect('/')
return
if self.get_current_user():
self.redirect('/')
... | the_stack_v2_python_sparse | empower_core/apimanager/apimanager.py | 5g-empower/empower-core | train | 3 |
df877ef7ffec3c4c83cb1b9de02fec9408723b76 | [
"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... | 慢钱宝app订单/投资服务 | IOrderServiceServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IOrderServiceServicer:
"""慢钱宝app订单/投资服务"""
def GetMyOrderPaging(self, request, context):
"""获取我的订单列表数据"""
<|body_0|>
def GetMyOrderDetail(self, request, context):
"""获取我的订单详情"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
context.set_code(grpc.... | stack_v2_sparse_classes_36k_train_032387 | 2,299 | no_license | [
{
"docstring": "获取我的订单列表数据",
"name": "GetMyOrderPaging",
"signature": "def GetMyOrderPaging(self, request, context)"
},
{
"docstring": "获取我的订单详情",
"name": "GetMyOrderDetail",
"signature": "def GetMyOrderDetail(self, request, context)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020088 | Implement the Python class `IOrderServiceServicer` described below.
Class description:
慢钱宝app订单/投资服务
Method signatures and docstrings:
- def GetMyOrderPaging(self, request, context): 获取我的订单列表数据
- def GetMyOrderDetail(self, request, context): 获取我的订单详情 | Implement the Python class `IOrderServiceServicer` described below.
Class description:
慢钱宝app订单/投资服务
Method signatures and docstrings:
- def GetMyOrderPaging(self, request, context): 获取我的订单列表数据
- def GetMyOrderDetail(self, request, context): 获取我的订单详情
<|skeleton|>
class IOrderServiceServicer:
"""慢钱宝app订单/投资服务"""
... | 08e9ca1f3e3c091756f8774f1b58055dd80d1e90 | <|skeleton|>
class IOrderServiceServicer:
"""慢钱宝app订单/投资服务"""
def GetMyOrderPaging(self, request, context):
"""获取我的订单列表数据"""
<|body_0|>
def GetMyOrderDetail(self, request, context):
"""获取我的订单详情"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IOrderServiceServicer:
"""慢钱宝app订单/投资服务"""
def GetMyOrderPaging(self, request, context):
"""获取我的订单列表数据"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def GetMyOrder... | the_stack_v2_python_sparse | IOrderService_pb2_grpc.py | qianbingbing/apitest | train | 0 |
59c13283a5d7d15ce95180e44e0dabbb0e3bb36b | [
"p = Participant.query.get(kf_id)\nif p is None:\n abort(404, 'could not find {} `{}`'.format('participant', kf_id))\nreturn ParticipantSchema().jsonify(p)",
"p = Participant.query.get(kf_id)\nif p is None:\n abort(404, 'could not find {} `{}`'.format('participant', kf_id))\nbody = request.get_json(force=Tr... | <|body_start_0|>
p = Participant.query.get(kf_id)
if p is None:
abort(404, 'could not find {} `{}`'.format('participant', kf_id))
return ParticipantSchema().jsonify(p)
<|end_body_0|>
<|body_start_1|>
p = Participant.query.get(kf_id)
if p is None:
abort(40... | Participant API | ParticipantAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParticipantAPI:
"""Participant API"""
def get(self, kf_id):
"""Get a participant by id --- template: path: get_by_id.yml properties: resource: Participant"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing participant. Allows partial update --- template:... | stack_v2_sparse_classes_36k_train_032388 | 4,062 | permissive | [
{
"docstring": "Get a participant by id --- template: path: get_by_id.yml properties: resource: Participant",
"name": "get",
"signature": "def get(self, kf_id)"
},
{
"docstring": "Update an existing participant. Allows partial update --- template: path: update_by_id.yml properties: resource: Par... | 3 | null | Implement the Python class `ParticipantAPI` described below.
Class description:
Participant API
Method signatures and docstrings:
- def get(self, kf_id): Get a participant by id --- template: path: get_by_id.yml properties: resource: Participant
- def patch(self, kf_id): Update an existing participant. Allows partial... | Implement the Python class `ParticipantAPI` described below.
Class description:
Participant API
Method signatures and docstrings:
- def get(self, kf_id): Get a participant by id --- template: path: get_by_id.yml properties: resource: Participant
- def patch(self, kf_id): Update an existing participant. Allows partial... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class ParticipantAPI:
"""Participant API"""
def get(self, kf_id):
"""Get a participant by id --- template: path: get_by_id.yml properties: resource: Participant"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing participant. Allows partial update --- template:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParticipantAPI:
"""Participant API"""
def get(self, kf_id):
"""Get a participant by id --- template: path: get_by_id.yml properties: resource: Participant"""
p = Participant.query.get(kf_id)
if p is None:
abort(404, 'could not find {} `{}`'.format('participant', kf_id)... | the_stack_v2_python_sparse | dataservice/api/participant/resources.py | kids-first/kf-api-dataservice | train | 9 |
71084f518a6db5a1f9ddf701d8f7e33933ab2cc0 | [
"super(BaseController, self).__init__(**kwargs)\nself.backend = backend\nif controller:\n self.controller = controller\n self.opts = controller.opts",
"super_getattr = super(BaseController, self).__getattribute__\nopts = super_getattr('opts')\nif not opts:\n raise ImproperlyConfigured('Controller should ... | <|body_start_0|>
super(BaseController, self).__init__(**kwargs)
self.backend = backend
if controller:
self.controller = controller
self.opts = controller.opts
<|end_body_0|>
<|body_start_1|>
super_getattr = super(BaseController, self).__getattribute__
opt... | Functionality common to all Controllers: - Access to the Models as pass-though queries via QueryMixin. - Resolution of URLs based on naming conventions via Resolver. At the core of our Controller is the ability to resolve a URL pattern to a namespaced name given a set of kwargs. This single component is safe for univer... | BaseController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseController:
"""Functionality common to all Controllers: - Access to the Models as pass-though queries via QueryMixin. - Resolution of URLs based on naming conventions via Resolver. At the core of our Controller is the ability to resolve a URL pattern to a namespaced name given a set of kwargs... | stack_v2_sparse_classes_36k_train_032389 | 4,395 | permissive | [
{
"docstring": "One thing all Controller share is the concept of a \"registered\" Controller. For all but ViewController-instantiated InlineControllers, all Controller are guaranteed to have a registered counterpart. For \"registered\" Controller, the counterpart is self. For all others, is is resolvable in the... | 2 | stack_v2_sparse_classes_30k_train_018070 | Implement the Python class `BaseController` described below.
Class description:
Functionality common to all Controllers: - Access to the Models as pass-though queries via QueryMixin. - Resolution of URLs based on naming conventions via Resolver. At the core of our Controller is the ability to resolve a URL pattern to ... | Implement the Python class `BaseController` described below.
Class description:
Functionality common to all Controllers: - Access to the Models as pass-though queries via QueryMixin. - Resolution of URLs based on naming conventions via Resolver. At the core of our Controller is the ability to resolve a URL pattern to ... | 6aee69bf46c14e301002d0465a8a2b7e74e02953 | <|skeleton|>
class BaseController:
"""Functionality common to all Controllers: - Access to the Models as pass-though queries via QueryMixin. - Resolution of URLs based on naming conventions via Resolver. At the core of our Controller is the ability to resolve a URL pattern to a namespaced name given a set of kwargs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseController:
"""Functionality common to all Controllers: - Access to the Models as pass-though queries via QueryMixin. - Resolution of URLs based on naming conventions via Resolver. At the core of our Controller is the ability to resolve a URL pattern to a namespaced name given a set of kwargs. This single... | the_stack_v2_python_sparse | venv/lib/python3.7/site-packages/foundation/views/controllers/base.py | Ljuka/iwen | train | 1 |
9972ddcbaca746e4081a64a0d5ca102ffce5d3bc | [
"memo = {}\nif s in memo:\n return memo[s]\nif len(s) == 0:\n return 1\nif int(s[0]) == 0:\n return 0\nn = self.numDecodings(s[1:])\nif 10 <= int(s[:2]) <= 26:\n n += self.numDecodings(s[2:])\nmemo[s] = n\nreturn n",
"if not s:\n return 0\nif not '1' <= s[0] <= '9':\n return 0\nif len(s) == 1:\n... | <|body_start_0|>
memo = {}
if s in memo:
return memo[s]
if len(s) == 0:
return 1
if int(s[0]) == 0:
return 0
n = self.numDecodings(s[1:])
if 10 <= int(s[:2]) <= 26:
n += self.numDecodings(s[2:])
memo[s] = n
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numDecodings(self, s):
"""05/05/2018 01:30"""
<|body_0|>
def numDecodings(self, s: str) -> int:
"""08/24/2021 10:37 Time complexity: O(n) Space complexity: O(1)"""
<|body_1|>
def numDecodings(self, s: str) -> int:
"""10/16/2022 16:4... | stack_v2_sparse_classes_36k_train_032390 | 3,184 | no_license | [
{
"docstring": "05/05/2018 01:30",
"name": "numDecodings",
"signature": "def numDecodings(self, s)"
},
{
"docstring": "08/24/2021 10:37 Time complexity: O(n) Space complexity: O(1)",
"name": "numDecodings",
"signature": "def numDecodings(self, s: str) -> int"
},
{
"docstring": "1... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDecodings(self, s): 05/05/2018 01:30
- def numDecodings(self, s: str) -> int: 08/24/2021 10:37 Time complexity: O(n) Space complexity: O(1)
- def numDecodings(self, s: str... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDecodings(self, s): 05/05/2018 01:30
- def numDecodings(self, s: str) -> int: 08/24/2021 10:37 Time complexity: O(n) Space complexity: O(1)
- def numDecodings(self, s: str... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def numDecodings(self, s):
"""05/05/2018 01:30"""
<|body_0|>
def numDecodings(self, s: str) -> int:
"""08/24/2021 10:37 Time complexity: O(n) Space complexity: O(1)"""
<|body_1|>
def numDecodings(self, s: str) -> int:
"""10/16/2022 16:4... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numDecodings(self, s):
"""05/05/2018 01:30"""
memo = {}
if s in memo:
return memo[s]
if len(s) == 0:
return 1
if int(s[0]) == 0:
return 0
n = self.numDecodings(s[1:])
if 10 <= int(s[:2]) <= 26:
... | the_stack_v2_python_sparse | leetcode/solved/91_Decode_Ways/solution.py | sungminoh/algorithms | train | 0 | |
c37fd62061d8ed0467da9df97c482ee639ce0e4f | [
"params_copy = deepcopy(params)\nparams_copy[cls.json_topics] = list(params_copy[cls.json_topics])\nparams_copy[cls.avro_topics] = list(params_copy[cls.avro_topics])\nlogger = logging.getLogger(cls.logger_name)\nlogger.debug(json.dumps(params_copy))",
"logger = logging.getLogger(cls.logger_name)\nif ConnectionCon... | <|body_start_0|>
params_copy = deepcopy(params)
params_copy[cls.json_topics] = list(params_copy[cls.json_topics])
params_copy[cls.avro_topics] = list(params_copy[cls.avro_topics])
logger = logging.getLogger(cls.logger_name)
logger.debug(json.dumps(params_copy))
<|end_body_0|>
<|... | Implements logger, create directories and log file, and triggers logs | RequestLogger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestLogger:
"""Implements logger, create directories and log file, and triggers logs"""
def log_request(cls, params):
"""Log parsed incoming request :param params: dict()"""
<|body_0|>
def create_logger(cls):
"""Create logger, if enabled, at application boot t... | stack_v2_sparse_classes_36k_train_032391 | 4,071 | permissive | [
{
"docstring": "Log parsed incoming request :param params: dict()",
"name": "log_request",
"signature": "def log_request(cls, params)"
},
{
"docstring": "Create logger, if enabled, at application boot time",
"name": "create_logger",
"signature": "def create_logger(cls)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016303 | Implement the Python class `RequestLogger` described below.
Class description:
Implements logger, create directories and log file, and triggers logs
Method signatures and docstrings:
- def log_request(cls, params): Log parsed incoming request :param params: dict()
- def create_logger(cls): Create logger, if enabled, ... | Implement the Python class `RequestLogger` described below.
Class description:
Implements logger, create directories and log file, and triggers logs
Method signatures and docstrings:
- def log_request(cls, params): Log parsed incoming request :param params: dict()
- def create_logger(cls): Create logger, if enabled, ... | c9400b431ad83c0b67b569fe887123653866b81f | <|skeleton|>
class RequestLogger:
"""Implements logger, create directories and log file, and triggers logs"""
def log_request(cls, params):
"""Log parsed incoming request :param params: dict()"""
<|body_0|>
def create_logger(cls):
"""Create logger, if enabled, at application boot t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestLogger:
"""Implements logger, create directories and log file, and triggers logs"""
def log_request(cls, params):
"""Log parsed incoming request :param params: dict()"""
params_copy = deepcopy(params)
params_copy[cls.json_topics] = list(params_copy[cls.json_topics])
... | the_stack_v2_python_sparse | logger.py | michaelmernin/kafka-topics-message-browser | train | 1 |
18a0223bd9bb75b7737e7b052e28ba1f4a9117d5 | [
"if params.get('alert_type'):\n if params['alert_type'] not in ['error', 'warning', 'info', 'success']:\n raise ApiError('Parameter alert_type must be either error, warning, info or success')\nreturn super(Event, cls).create(attach_host_name=attach_host_name, **params)",
"def timestamp_to_integer(k, v):... | <|body_start_0|>
if params.get('alert_type'):
if params['alert_type'] not in ['error', 'warning', 'info', 'success']:
raise ApiError('Parameter alert_type must be either error, warning, info or success')
return super(Event, cls).create(attach_host_name=attach_host_name, **par... | A wrapper around Event HTTP API. | Event | [
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Event:
"""A wrapper around Event HTTP API."""
def create(cls, attach_host_name=True, **params):
"""Post an event. :param title: title for the new event :type title: string :param text: event message :type text: string :param aggregation_key: key by which to group events in event stre... | stack_v2_sparse_classes_36k_train_032392 | 3,376 | permissive | [
{
"docstring": "Post an event. :param title: title for the new event :type title: string :param text: event message :type text: string :param aggregation_key: key by which to group events in event stream :type aggregation_key: string :param alert_type: \"error\", \"warning\", \"info\" or \"success\". :type aler... | 2 | stack_v2_sparse_classes_30k_val_000698 | Implement the Python class `Event` described below.
Class description:
A wrapper around Event HTTP API.
Method signatures and docstrings:
- def create(cls, attach_host_name=True, **params): Post an event. :param title: title for the new event :type title: string :param text: event message :type text: string :param ag... | Implement the Python class `Event` described below.
Class description:
A wrapper around Event HTTP API.
Method signatures and docstrings:
- def create(cls, attach_host_name=True, **params): Post an event. :param title: title for the new event :type title: string :param text: event message :type text: string :param ag... | 11a38d0c8d6b156758e7500500d706b7159d18ed | <|skeleton|>
class Event:
"""A wrapper around Event HTTP API."""
def create(cls, attach_host_name=True, **params):
"""Post an event. :param title: title for the new event :type title: string :param text: event message :type text: string :param aggregation_key: key by which to group events in event stre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Event:
"""A wrapper around Event HTTP API."""
def create(cls, attach_host_name=True, **params):
"""Post an event. :param title: title for the new event :type title: string :param text: event message :type text: string :param aggregation_key: key by which to group events in event stream :type aggr... | the_stack_v2_python_sparse | datadog/api/events.py | DataDog/datadogpy | train | 602 |
8ce1e0375671a6c98a6ff07f93dae7c3a71db266 | [
"HelpedWidget.__init__(self, parent, label, help)\nself.active_label = QtGui.QLabel()\nself.addWidget(self.active_label)\nfont = self.active_label.font()\nfont.setWeight(QtGui.QFont.Bold)\nself.active_label.setFont(font)\nself.active_label.setText(default_string)",
"self_get_from_model = self.getFromModel()\nif s... | <|body_start_0|>
HelpedWidget.__init__(self, parent, label, help)
self.active_label = QtGui.QLabel()
self.addWidget(self.active_label)
font = self.active_label.font()
font.setWeight(QtGui.QFont.Bold)
self.active_label.setFont(font)
self.active_label.setText(defaul... | Label shows a string. The data structure expected from the getter is a string. | ActiveLabel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActiveLabel:
"""Label shows a string. The data structure expected from the getter is a string."""
def __init__(self, parent=None, label='', help='', default_string=''):
"""Construct a StringBox widget"""
<|body_0|>
def fetchContent(self):
"""Retrieves data from t... | stack_v2_sparse_classes_36k_train_032393 | 1,638 | no_license | [
{
"docstring": "Construct a StringBox widget",
"name": "__init__",
"signature": "def __init__(self, parent=None, label='', help='', default_string='')"
},
{
"docstring": "Retrieves data from the model and inserts it into the edit line",
"name": "fetchContent",
"signature": "def fetchCont... | 2 | stack_v2_sparse_classes_30k_train_017172 | Implement the Python class `ActiveLabel` described below.
Class description:
Label shows a string. The data structure expected from the getter is a string.
Method signatures and docstrings:
- def __init__(self, parent=None, label='', help='', default_string=''): Construct a StringBox widget
- def fetchContent(self): ... | Implement the Python class `ActiveLabel` described below.
Class description:
Label shows a string. The data structure expected from the getter is a string.
Method signatures and docstrings:
- def __init__(self, parent=None, label='', help='', default_string=''): Construct a StringBox widget
- def fetchContent(self): ... | 653602a5a958667c733520b34f9ab45052c71a02 | <|skeleton|>
class ActiveLabel:
"""Label shows a string. The data structure expected from the getter is a string."""
def __init__(self, parent=None, label='', help='', default_string=''):
"""Construct a StringBox widget"""
<|body_0|>
def fetchContent(self):
"""Retrieves data from t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActiveLabel:
"""Label shows a string. The data structure expected from the getter is a string."""
def __init__(self, parent=None, label='', help='', default_string=''):
"""Construct a StringBox widget"""
HelpedWidget.__init__(self, parent, label, help)
self.active_label = QtGui.QL... | the_stack_v2_python_sparse | devel/python/python/ert_gui/widgets/activelabel.py | myrseth/ert | train | 0 |
6407300850f5080adbd1515ad35b9574d189190e | [
"JudgmentVerification.__init__(self, config, basename)\nself.bi = center_name()\npass",
"functionName = inspect.stack()[0][3]\ntabs = t_c\nif tabs in case_value:\n self.ct = CustomTabs(self.driver, self.financial[tabs])\n self.ct.into_the_city(self.vac, case_value[tabs])\n pass\nelse:\n self.log.info(... | <|body_start_0|>
JudgmentVerification.__init__(self, config, basename)
self.bi = center_name()
pass
<|end_body_0|>
<|body_start_1|>
functionName = inspect.stack()[0][3]
tabs = t_c
if tabs in case_value:
self.ct = CustomTabs(self.driver, self.financial[tabs])
... | InviteOperateJude | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InviteOperateJude:
def __init__(self, config, basename, center_name):
"""定义模块数据信息 :param module: 元素模块 :param sheet: 用例标签名 :param basename: 执行程序的文件名"""
<|body_0|>
def switchover_tabs_city(self, case_value, t_c):
"""进入指定的tabs或者city :param t_c: :return:"""
<|bod... | stack_v2_sparse_classes_36k_train_032394 | 5,076 | no_license | [
{
"docstring": "定义模块数据信息 :param module: 元素模块 :param sheet: 用例标签名 :param basename: 执行程序的文件名",
"name": "__init__",
"signature": "def __init__(self, config, basename, center_name)"
},
{
"docstring": "进入指定的tabs或者city :param t_c: :return:",
"name": "switchover_tabs_city",
"signature": "def sw... | 4 | stack_v2_sparse_classes_30k_train_006221 | Implement the Python class `InviteOperateJude` described below.
Class description:
Implement the InviteOperateJude class.
Method signatures and docstrings:
- def __init__(self, config, basename, center_name): 定义模块数据信息 :param module: 元素模块 :param sheet: 用例标签名 :param basename: 执行程序的文件名
- def switchover_tabs_city(self, c... | Implement the Python class `InviteOperateJude` described below.
Class description:
Implement the InviteOperateJude class.
Method signatures and docstrings:
- def __init__(self, config, basename, center_name): 定义模块数据信息 :param module: 元素模块 :param sheet: 用例标签名 :param basename: 执行程序的文件名
- def switchover_tabs_city(self, c... | 4df8ce960721407a20d89de47faad0df0de063a1 | <|skeleton|>
class InviteOperateJude:
def __init__(self, config, basename, center_name):
"""定义模块数据信息 :param module: 元素模块 :param sheet: 用例标签名 :param basename: 执行程序的文件名"""
<|body_0|>
def switchover_tabs_city(self, case_value, t_c):
"""进入指定的tabs或者city :param t_c: :return:"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InviteOperateJude:
def __init__(self, config, basename, center_name):
"""定义模块数据信息 :param module: 元素模块 :param sheet: 用例标签名 :param basename: 执行程序的文件名"""
JudgmentVerification.__init__(self, config, basename)
self.bi = center_name()
pass
def switchover_tabs_city(self, case_val... | the_stack_v2_python_sparse | CenterBackground/GeneralizeAssist/Invite/inviteoperatejude.py | namexiaohuihui/operating | train | 0 | |
922da98e0e51957d2207a2a9067a1cc756e7fb26 | [
"if n < 10 and n > pow(2, 32) - 1:\n return -1\nns = list(str(n))\ni = len(ns) - 1\nwhile i > 0:\n if ns[i - 1] < ns[i]:\n j, p = (i, i)\n while j < len(ns) and ns[j] > ns[i - 1]:\n if ns[p] > ns[j]:\n p = j\n j += 1\n ns[i - 1], ns[p] = (ns[p], ns[i -... | <|body_start_0|>
if n < 10 and n > pow(2, 32) - 1:
return -1
ns = list(str(n))
i = len(ns) - 1
while i > 0:
if ns[i - 1] < ns[i]:
j, p = (i, i)
while j < len(ns) and ns[j] > ns[i - 1]:
if ns[p] > ns[j]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextGreaterElement1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def nextGreaterElement(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n < 10 and n > pow(2, 32) - 1:
return -... | stack_v2_sparse_classes_36k_train_032395 | 1,348 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "nextGreaterElement1",
"signature": "def nextGreaterElement1(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "nextGreaterElement",
"signature": "def nextGreaterElement(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012697 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement1(self, n): :type n: int :rtype: int
- def nextGreaterElement(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 nextGreaterElement1(self, n): :type n: int :rtype: int
- def nextGreaterElement(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def nextGreaterElement1(... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def nextGreaterElement1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def nextGreaterElement(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 nextGreaterElement1(self, n):
""":type n: int :rtype: int"""
if n < 10 and n > pow(2, 32) - 1:
return -1
ns = list(str(n))
i = len(ns) - 1
while i > 0:
if ns[i - 1] < ns[i]:
j, p = (i, i)
while j < le... | the_stack_v2_python_sparse | py/leetcode/556.py | wfeng1991/learnpy | train | 0 | |
8b71f537e548b2023443f7557cba0282fffdc5fc | [
"assert td_lambda in (0, 1), 'Currently GAE is not supported, so td_lambda has to be 0 or 1.'\nsuper().__init__(gamma=gamma, td_error_loss_fn=td_error_loss_fn, td_lambda=td_lambda, debug_summaries=debug_summaries, name=name)\nself._num_quantiles = num_quantiles\nself._cdf_midpoints = (torch.arange(num_quantiles, dt... | <|body_start_0|>
assert td_lambda in (0, 1), 'Currently GAE is not supported, so td_lambda has to be 0 or 1.'
super().__init__(gamma=gamma, td_error_loss_fn=td_error_loss_fn, td_lambda=td_lambda, debug_summaries=debug_summaries, name=name)
self._num_quantiles = num_quantiles
self._cdf_mi... | Temporal difference quantile regression loss. Compared to TDLoss, GAE support has not been implemented. | TDQRLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TDQRLoss:
"""Temporal difference quantile regression loss. Compared to TDLoss, GAE support has not been implemented."""
def __init__(self, num_quantiles: int=50, gamma: Union[float, List[float]]=0.99, td_error_loss_fn: Callable=losses.huber_function, td_lambda: float=1.0, sum_over_quantiles:... | stack_v2_sparse_classes_36k_train_032396 | 14,755 | permissive | [
{
"docstring": "Args: num_quantiles: the number of quantiles. gamma: A discount factor for future rewards. For multi-dim reward, this can also be a list of discounts, each discount applies to a reward dim. td_error_loss_fn: A function for computing the TD errors loss. This function takes as input the target and... | 2 | null | Implement the Python class `TDQRLoss` described below.
Class description:
Temporal difference quantile regression loss. Compared to TDLoss, GAE support has not been implemented.
Method signatures and docstrings:
- def __init__(self, num_quantiles: int=50, gamma: Union[float, List[float]]=0.99, td_error_loss_fn: Calla... | Implement the Python class `TDQRLoss` described below.
Class description:
Temporal difference quantile regression loss. Compared to TDLoss, GAE support has not been implemented.
Method signatures and docstrings:
- def __init__(self, num_quantiles: int=50, gamma: Union[float, List[float]]=0.99, td_error_loss_fn: Calla... | b00ff2fa5e660de31020338ba340263183fbeaa4 | <|skeleton|>
class TDQRLoss:
"""Temporal difference quantile regression loss. Compared to TDLoss, GAE support has not been implemented."""
def __init__(self, num_quantiles: int=50, gamma: Union[float, List[float]]=0.99, td_error_loss_fn: Callable=losses.huber_function, td_lambda: float=1.0, sum_over_quantiles:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TDQRLoss:
"""Temporal difference quantile regression loss. Compared to TDLoss, GAE support has not been implemented."""
def __init__(self, num_quantiles: int=50, gamma: Union[float, List[float]]=0.99, td_error_loss_fn: Callable=losses.huber_function, td_lambda: float=1.0, sum_over_quantiles: bool=False, ... | the_stack_v2_python_sparse | alf/algorithms/td_loss.py | HorizonRobotics/alf | train | 288 |
7166ecfdbeb363d923fc7f67bfe875ebf7bff458 | [
"self.numCorpus = numcorpus\nself.corpusLocation = corpuslocation\nself.classification = classification\nself.ratioFunny = 0.0\nself.ratioImpressive = 0.0\nself.ratioIntensity = 0.0\nself.ratioTerror = 0.0\nself.ratioTragic = 0.0",
"self.ratioFunny = round(float(numfunny) / GLOBAL_simioutputnum, 3)\nself.ratioImp... | <|body_start_0|>
self.numCorpus = numcorpus
self.corpusLocation = corpuslocation
self.classification = classification
self.ratioFunny = 0.0
self.ratioImpressive = 0.0
self.ratioIntensity = 0.0
self.ratioTerror = 0.0
self.ratioTragic = 0.0
<|end_body_0|>
<... | 用于描述corpus的分类(funny,impressive,...),相似列表中的分类百分比 数据源于 GLOBAL_simiresultsFolder *只在StatisticUtil中会用到,作统计分析* | Corpus | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Corpus:
"""用于描述corpus的分类(funny,impressive,...),相似列表中的分类百分比 数据源于 GLOBAL_simiresultsFolder *只在StatisticUtil中会用到,作统计分析*"""
def __init__(self, numcorpus, corpuslocation, classification):
"""初始化 corpus对象 :param numcorpus: corpus编号 :param corpuslocation: corpus位置 :param classification: cor... | stack_v2_sparse_classes_36k_train_032397 | 1,607 | no_license | [
{
"docstring": "初始化 corpus对象 :param numcorpus: corpus编号 :param corpuslocation: corpus位置 :param classification: corpus的归类 :return:",
"name": "__init__",
"signature": "def __init__(self, numcorpus, corpuslocation, classification)"
},
{
"docstring": "对四个ratio赋值,保留三位小数 :param numfunny: :param numimp... | 2 | stack_v2_sparse_classes_30k_train_017660 | Implement the Python class `Corpus` described below.
Class description:
用于描述corpus的分类(funny,impressive,...),相似列表中的分类百分比 数据源于 GLOBAL_simiresultsFolder *只在StatisticUtil中会用到,作统计分析*
Method signatures and docstrings:
- def __init__(self, numcorpus, corpuslocation, classification): 初始化 corpus对象 :param numcorpus: corpus编号 :... | Implement the Python class `Corpus` described below.
Class description:
用于描述corpus的分类(funny,impressive,...),相似列表中的分类百分比 数据源于 GLOBAL_simiresultsFolder *只在StatisticUtil中会用到,作统计分析*
Method signatures and docstrings:
- def __init__(self, numcorpus, corpuslocation, classification): 初始化 corpus对象 :param numcorpus: corpus编号 :... | adb9e34db832fef5bb0f629a6bd95f15a3e56f46 | <|skeleton|>
class Corpus:
"""用于描述corpus的分类(funny,impressive,...),相似列表中的分类百分比 数据源于 GLOBAL_simiresultsFolder *只在StatisticUtil中会用到,作统计分析*"""
def __init__(self, numcorpus, corpuslocation, classification):
"""初始化 corpus对象 :param numcorpus: corpus编号 :param corpuslocation: corpus位置 :param classification: cor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Corpus:
"""用于描述corpus的分类(funny,impressive,...),相似列表中的分类百分比 数据源于 GLOBAL_simiresultsFolder *只在StatisticUtil中会用到,作统计分析*"""
def __init__(self, numcorpus, corpuslocation, classification):
"""初始化 corpus对象 :param numcorpus: corpus编号 :param corpuslocation: corpus位置 :param classification: corpus的归类 :retur... | the_stack_v2_python_sparse | Entity/Corpus.py | autterman/GensimLDATool-TSCemotion | train | 0 |
4c231424109f9ebd43336ce8213490328a2f8caa | [
"super().__init__(env_spec, use_cuda)\nself.state_des = state_des\nself.limit_rad = 0.5236\nself.kp_servo = 14.0\nself.Kp, self.Kd = (None, None)\nself.init_param(kp, kd)",
"th_x, th_y, x, y, _, _, x_dot, y_dot = obs\nerr = to.tensor([self.state_des[0] - x, self.state_des[1] - y])\nerr_dot = to.tensor([0.0 - x_do... | <|body_start_0|>
super().__init__(env_spec, use_cuda)
self.state_des = state_des
self.limit_rad = 0.5236
self.kp_servo = 14.0
self.Kp, self.Kd = (None, None)
self.init_param(kp, kd)
<|end_body_0|>
<|body_start_1|>
th_x, th_y, x, y, _, _, x_dot, y_dot = obs
... | PD-controller for the Quanser Ball Balancer. The only but significant difference of this controller to the other PD controller is the clipping of the actions. .. note:: This class's desired state specification deviates from the Pyrado policies which interact with a `Task`. | QBallBalancerPDCtrl | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QBallBalancerPDCtrl:
"""PD-controller for the Quanser Ball Balancer. The only but significant difference of this controller to the other PD controller is the clipping of the actions. .. note:: This class's desired state specification deviates from the Pyrado policies which interact with a `Task`.... | stack_v2_sparse_classes_36k_train_032398 | 32,197 | permissive | [
{
"docstring": "Constructor :param env_spec: environment specification :param state_des: tensor of desired x and y ball position [m] :param kp: 2x2 tensor of constant controller feedback coefficients for error [V/m] :param kd: 2x2 tensor of constant controller feedback coefficients for error time derivative [Vs... | 4 | null | Implement the Python class `QBallBalancerPDCtrl` described below.
Class description:
PD-controller for the Quanser Ball Balancer. The only but significant difference of this controller to the other PD controller is the clipping of the actions. .. note:: This class's desired state specification deviates from the Pyrado... | Implement the Python class `QBallBalancerPDCtrl` described below.
Class description:
PD-controller for the Quanser Ball Balancer. The only but significant difference of this controller to the other PD controller is the clipping of the actions. .. note:: This class's desired state specification deviates from the Pyrado... | d7e9cd191ccb318d5f1e580babc2fc38b5b3675a | <|skeleton|>
class QBallBalancerPDCtrl:
"""PD-controller for the Quanser Ball Balancer. The only but significant difference of this controller to the other PD controller is the clipping of the actions. .. note:: This class's desired state specification deviates from the Pyrado policies which interact with a `Task`.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QBallBalancerPDCtrl:
"""PD-controller for the Quanser Ball Balancer. The only but significant difference of this controller to the other PD controller is the clipping of the actions. .. note:: This class's desired state specification deviates from the Pyrado policies which interact with a `Task`."""
def ... | the_stack_v2_python_sparse | Pyrado/pyrado/policies/special/environment_specific.py | 1abner1/SimuRLacra | train | 0 |
4729d47b89a5e28e7552820741e106e9a61cdcac | [
"news_liat = []\ntry:\n for new_num in new_numlist:\n self._params['new_num'] = new_num\n text = self.step(read_dir, 'get_the_news_read').text\n news_liat.append(text)\n print(f'獲取到的消息是:{text}')\n return news_liat\nexcept Exception as e:\n raise e",
"self._params['new_num'] = ... | <|body_start_0|>
news_liat = []
try:
for new_num in new_numlist:
self._params['new_num'] = new_num
text = self.step(read_dir, 'get_the_news_read').text
news_liat.append(text)
print(f'獲取到的消息是:{text}')
return news_liat... | Read | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Read:
def get_the_news_read(self, new_numlist):
"""根据传进来的nums去取第几条信息 获取第一行信息的text"""
<|body_0|>
def goto_overtime_for_news_read(self, new_num):
"""根據傳進來的序號獲取第N條消息並點擊進入改應用 驗證進入了加班應用,返回”加班詳情“text"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
news_li... | stack_v2_sparse_classes_36k_train_032399 | 1,051 | no_license | [
{
"docstring": "根据传进来的nums去取第几条信息 获取第一行信息的text",
"name": "get_the_news_read",
"signature": "def get_the_news_read(self, new_numlist)"
},
{
"docstring": "根據傳進來的序號獲取第N條消息並點擊進入改應用 驗證進入了加班應用,返回”加班詳情“text",
"name": "goto_overtime_for_news_read",
"signature": "def goto_overtime_for_news_read(s... | 2 | stack_v2_sparse_classes_30k_train_021570 | Implement the Python class `Read` described below.
Class description:
Implement the Read class.
Method signatures and docstrings:
- def get_the_news_read(self, new_numlist): 根据传进来的nums去取第几条信息 获取第一行信息的text
- def goto_overtime_for_news_read(self, new_num): 根據傳進來的序號獲取第N條消息並點擊進入改應用 驗證進入了加班應用,返回”加班詳情“text | Implement the Python class `Read` described below.
Class description:
Implement the Read class.
Method signatures and docstrings:
- def get_the_news_read(self, new_numlist): 根据传进来的nums去取第几条信息 获取第一行信息的text
- def goto_overtime_for_news_read(self, new_num): 根據傳進來的序號獲取第N條消息並點擊進入改應用 驗證進入了加班應用,返回”加班詳情“text
<|skeleton|>
cl... | 42545bad476dd3ab99bf421e702a3d6b4795aa01 | <|skeleton|>
class Read:
def get_the_news_read(self, new_numlist):
"""根据传进来的nums去取第几条信息 获取第一行信息的text"""
<|body_0|>
def goto_overtime_for_news_read(self, new_num):
"""根據傳進來的序號獲取第N條消息並點擊進入改應用 驗證進入了加班應用,返回”加班詳情“text"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Read:
def get_the_news_read(self, new_numlist):
"""根据传进来的nums去取第几条信息 获取第一行信息的text"""
news_liat = []
try:
for new_num in new_numlist:
self._params['new_num'] = new_num
text = self.step(read_dir, 'get_the_news_read').text
news_l... | the_stack_v2_python_sparse | page/news_list/read.py | xmaimiao/wmPC_oevertime | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.