blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ae74ec510096893c1629c9555f3503c75aaf1f05 | [
"if isinstance(instance, RegisteredShutdown):\n container = GracefulShutdown.ServiceContainer(instance, nice)\n GracefulShutdown._register.append(container)\nelse:\n raise TypeError('Registered objects for graceful shutdown MUST be of type `RegisteredShutdown`.')",
"logging.info('Shutting down services:'... | <|body_start_0|>
if isinstance(instance, RegisteredShutdown):
container = GracefulShutdown.ServiceContainer(instance, nice)
GracefulShutdown._register.append(container)
else:
raise TypeError('Registered objects for graceful shutdown MUST be of type `RegisteredShutdown... | GracefulShutdown | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GracefulShutdown:
def register(instance, nice=0):
"""Arguments: `instance` argument should be an Object of type `RegisteredShutdown`. `nice` parameter permits a natural ascending priority-basis for shutdown execution order. Default is 0 (int), no range limitations. Usage: - subprocess.Po... | stack_v2_sparse_classes_10k_train_004100 | 2,914 | permissive | [
{
"docstring": "Arguments: `instance` argument should be an Object of type `RegisteredShutdown`. `nice` parameter permits a natural ascending priority-basis for shutdown execution order. Default is 0 (int), no range limitations. Usage: - subprocess.Popen() object containers, should - extend RegisteredShutdown a... | 2 | stack_v2_sparse_classes_30k_train_003560 | Implement the Python class `GracefulShutdown` described below.
Class description:
Implement the GracefulShutdown class.
Method signatures and docstrings:
- def register(instance, nice=0): Arguments: `instance` argument should be an Object of type `RegisteredShutdown`. `nice` parameter permits a natural ascending prio... | Implement the Python class `GracefulShutdown` described below.
Class description:
Implement the GracefulShutdown class.
Method signatures and docstrings:
- def register(instance, nice=0): Arguments: `instance` argument should be an Object of type `RegisteredShutdown`. `nice` parameter permits a natural ascending prio... | 92f21b1b8a9f701cac3976a8db7034ecfefc58c7 | <|skeleton|>
class GracefulShutdown:
def register(instance, nice=0):
"""Arguments: `instance` argument should be an Object of type `RegisteredShutdown`. `nice` parameter permits a natural ascending priority-basis for shutdown execution order. Default is 0 (int), no range limitations. Usage: - subprocess.Po... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GracefulShutdown:
def register(instance, nice=0):
"""Arguments: `instance` argument should be an Object of type `RegisteredShutdown`. `nice` parameter permits a natural ascending priority-basis for shutdown execution order. Default is 0 (int), no range limitations. Usage: - subprocess.Popen() object c... | the_stack_v2_python_sparse | src/service/registered_shutdown.py | yeauxji/LightStage-Repo | train | 0 | |
6b8e9afda6c673b9aeedca8afce715a58fff43d0 | [
"data = {}\nwith open(fpath) as f:\n data = toml.load(f)\nnetwork = data.get(network_name, {})\nself.baseline = network.get('all', {}).get('default', {})\nspecific_general_data = network.get('all', {}).get(metadata.variant, {})\naddendum = network.get(framework, {})\naddendum_default = addendum.get('default', {}... | <|body_start_0|>
data = {}
with open(fpath) as f:
data = toml.load(f)
network = data.get(network_name, {})
self.baseline = network.get('all', {}).get('default', {})
specific_general_data = network.get('all', {}).get(metadata.variant, {})
addendum = network.get... | Loads a toml checkpoint file for comparing labels and inputs. | NNTomlCheckpoint | [
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"ISC",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NNTomlCheckpoint:
"""Loads a toml checkpoint file for comparing labels and inputs."""
def __init__(self, fpath: str, framework: str, network_name: str, metadata: NetworkMetadata):
"""Loads the toml file for processing."""
<|body_0|>
def _iterate_data(self, slice: List[st... | stack_v2_sparse_classes_10k_train_004101 | 4,090 | permissive | [
{
"docstring": "Loads the toml file for processing.",
"name": "__init__",
"signature": "def __init__(self, fpath: str, framework: str, network_name: str, metadata: NetworkMetadata)"
},
{
"docstring": "Helper for child classes to iterate through a slice of data. Return: (Union[Dict[str, str], Lis... | 2 | stack_v2_sparse_classes_30k_train_001716 | Implement the Python class `NNTomlCheckpoint` described below.
Class description:
Loads a toml checkpoint file for comparing labels and inputs.
Method signatures and docstrings:
- def __init__(self, fpath: str, framework: str, network_name: str, metadata: NetworkMetadata): Loads the toml file for processing.
- def _i... | Implement the Python class `NNTomlCheckpoint` described below.
Class description:
Loads a toml checkpoint file for comparing labels and inputs.
Method signatures and docstrings:
- def __init__(self, fpath: str, framework: str, network_name: str, metadata: NetworkMetadata): Loads the toml file for processing.
- def _i... | 81438d602344c977ef3cab71bd04995c1834e51c | <|skeleton|>
class NNTomlCheckpoint:
"""Loads a toml checkpoint file for comparing labels and inputs."""
def __init__(self, fpath: str, framework: str, network_name: str, metadata: NetworkMetadata):
"""Loads the toml file for processing."""
<|body_0|>
def _iterate_data(self, slice: List[st... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NNTomlCheckpoint:
"""Loads a toml checkpoint file for comparing labels and inputs."""
def __init__(self, fpath: str, framework: str, network_name: str, metadata: NetworkMetadata):
"""Loads the toml file for processing."""
data = {}
with open(fpath) as f:
data = toml.lo... | the_stack_v2_python_sparse | tensorrt-basic-1.10-3rd-plugin/TensorRT-main/demo/HuggingFace/NNDF/checkpoints.py | jinmin527/learning-cuda-trt | train | 36 |
971b033fc41126b850d323387751a1624d6e78e1 | [
"if value is not None:\n obj: Optional[str] = serializer.dumps(value)\nelse:\n obj = value\nreturn obj",
"if value is not None:\n value = serializer.loads(value)\nreturn value"
] | <|body_start_0|>
if value is not None:
obj: Optional[str] = serializer.dumps(value)
else:
obj = value
return obj
<|end_body_0|>
<|body_start_1|>
if value is not None:
value = serializer.loads(value)
return value
<|end_body_1|>
| A SQLite-friendly JSON data type. | SQLiteJSON | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLiteJSON:
"""A SQLite-friendly JSON data type."""
def process_bind_param(self, value: Optional[dict], dialect: str) -> Optional[str]:
"""Serialize a dict to JSON."""
<|body_0|>
def process_result_value(self, value: str, dialect: str) -> Optional[Union[str, dict]]:
... | stack_v2_sparse_classes_10k_train_004102 | 3,561 | permissive | [
{
"docstring": "Serialize a dict to JSON.",
"name": "process_bind_param",
"signature": "def process_bind_param(self, value: Optional[dict], dialect: str) -> Optional[str]"
},
{
"docstring": "Deserialize JSON content to a dict.",
"name": "process_result_value",
"signature": "def process_r... | 2 | stack_v2_sparse_classes_30k_train_006413 | Implement the Python class `SQLiteJSON` described below.
Class description:
A SQLite-friendly JSON data type.
Method signatures and docstrings:
- def process_bind_param(self, value: Optional[dict], dialect: str) -> Optional[str]: Serialize a dict to JSON.
- def process_result_value(self, value: str, dialect: str) -> ... | Implement the Python class `SQLiteJSON` described below.
Class description:
A SQLite-friendly JSON data type.
Method signatures and docstrings:
- def process_bind_param(self, value: Optional[dict], dialect: str) -> Optional[str]: Serialize a dict to JSON.
- def process_result_value(self, value: str, dialect: str) -> ... | 6077ce4e0685d67ce7010800083a898857158112 | <|skeleton|>
class SQLiteJSON:
"""A SQLite-friendly JSON data type."""
def process_bind_param(self, value: Optional[dict], dialect: str) -> Optional[str]:
"""Serialize a dict to JSON."""
<|body_0|>
def process_result_value(self, value: str, dialect: str) -> Optional[Union[str, dict]]:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SQLiteJSON:
"""A SQLite-friendly JSON data type."""
def process_bind_param(self, value: Optional[dict], dialect: str) -> Optional[str]:
"""Serialize a dict to JSON."""
if value is not None:
obj: Optional[str] = serializer.dumps(value)
else:
obj = value
... | the_stack_v2_python_sparse | core/arxiv/submission/services/classic/util.py | arXiv/arxiv-submission-core | train | 14 |
0c47102e76757fba95a716bc39b718cb80ebf56b | [
"if not phone:\n raise ValueError('The given phone must be set')\nuser = self.model(phone=phone, **extra_fields)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"extra_fields.setdefault('is_staff', False)\nextra_fields.setdefault('is_superuser', False)\nreturn self._create_user(phone, pa... | <|body_start_0|>
if not phone:
raise ValueError('The given phone must be set')
user = self.model(phone=phone, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
extra_fields.setdefault('is_staff',... | CustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
def _create_user(self, phone, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create_user(self, phone, password=None, **extra_fields):
"""Create and save a regular User with the given email ... | stack_v2_sparse_classes_10k_train_004103 | 3,142 | no_license | [
{
"docstring": "Create and save a User with the given email and password.",
"name": "_create_user",
"signature": "def _create_user(self, phone, password, **extra_fields)"
},
{
"docstring": "Create and save a regular User with the given email and password.",
"name": "create_user",
"signat... | 3 | stack_v2_sparse_classes_30k_train_002983 | Implement the Python class `CustomUserManager` described below.
Class description:
Implement the CustomUserManager class.
Method signatures and docstrings:
- def _create_user(self, phone, password, **extra_fields): Create and save a User with the given email and password.
- def create_user(self, phone, password=None,... | Implement the Python class `CustomUserManager` described below.
Class description:
Implement the CustomUserManager class.
Method signatures and docstrings:
- def _create_user(self, phone, password, **extra_fields): Create and save a User with the given email and password.
- def create_user(self, phone, password=None,... | abe910229da2d5be9a18c1e46fcf86f51f732c65 | <|skeleton|>
class CustomUserManager:
def _create_user(self, phone, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create_user(self, phone, password=None, **extra_fields):
"""Create and save a regular User with the given email ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomUserManager:
def _create_user(self, phone, password, **extra_fields):
"""Create and save a User with the given email and password."""
if not phone:
raise ValueError('The given phone must be set')
user = self.model(phone=phone, **extra_fields)
user.set_password... | the_stack_v2_python_sparse | accounts/models.py | shams0910/uharvest-backend | train | 0 | |
c85cf8903c0fea89158f771f1fad49626b078a21 | [
"self.num = 0\nself.num_list = []\nself.sort_num_list = None\nself.k = k\nself.m = m",
"if len(self.num_list) < self.m:\n self.num_list.append(num)\nelse:\n self.num_list.pop(0)\n self.num_list.append(num)\nif len(self.num_list) == self.m:\n self.sort_num_list = copy.deepcopy(self.num_list)\n self.... | <|body_start_0|>
self.num = 0
self.num_list = []
self.sort_num_list = None
self.k = k
self.m = m
<|end_body_0|>
<|body_start_1|>
if len(self.num_list) < self.m:
self.num_list.append(num)
else:
self.num_list.pop(0)
self.num_list... | MKAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MKAverage:
def __init__(self, m, k):
""":type m: int :type k: int"""
<|body_0|>
def addElement(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def calculateMKAverage(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_10k_train_004104 | 881 | no_license | [
{
"docstring": ":type m: int :type k: int",
"name": "__init__",
"signature": "def __init__(self, m, k)"
},
{
"docstring": ":type num: int :rtype: None",
"name": "addElement",
"signature": "def addElement(self, num)"
},
{
"docstring": ":rtype: int",
"name": "calculateMKAverage... | 3 | stack_v2_sparse_classes_30k_train_007313 | Implement the Python class `MKAverage` described below.
Class description:
Implement the MKAverage class.
Method signatures and docstrings:
- def __init__(self, m, k): :type m: int :type k: int
- def addElement(self, num): :type num: int :rtype: None
- def calculateMKAverage(self): :rtype: int | Implement the Python class `MKAverage` described below.
Class description:
Implement the MKAverage class.
Method signatures and docstrings:
- def __init__(self, m, k): :type m: int :type k: int
- def addElement(self, num): :type num: int :rtype: None
- def calculateMKAverage(self): :rtype: int
<|skeleton|>
class MKA... | d34d4b592d05e9e0e724d8834eaf9587a64c5034 | <|skeleton|>
class MKAverage:
def __init__(self, m, k):
""":type m: int :type k: int"""
<|body_0|>
def addElement(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def calculateMKAverage(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MKAverage:
def __init__(self, m, k):
""":type m: int :type k: int"""
self.num = 0
self.num_list = []
self.sort_num_list = None
self.k = k
self.m = m
def addElement(self, num):
""":type num: int :rtype: None"""
if len(self.num_list) < self.m:... | the_stack_v2_python_sparse | LeetCode算法题/1825_求出MK平均值/求出MK平均值.py | exueyuanAlgorithm/AlgorithmDemo | train | 0 | |
a7c902c8a499105dab33b1cc70f58badb44835de | [
"p = self.make('Prescription')\nday_state = p.day_state\nself.assertFalse(day_state.pre_actions)\nday_state.pre_actions = True\nwith self.assertRaises(ValidationError) as cm:\n day_state.full_clean()\n self.assertEqual(cm.exception.messages_dict, {'pre_actions': ['Pre-burn actions cannot be marked as complete... | <|body_start_0|>
p = self.make('Prescription')
day_state = p.day_state
self.assertFalse(day_state.pre_actions)
day_state.pre_actions = True
with self.assertRaises(ValidationError) as cm:
day_state.full_clean()
self.assertEqual(cm.exception.messages_dict, {... | BurnImplementationStateTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BurnImplementationStateTests:
def test_pre_burn_actions(self):
"""Test that marking pre-burn actions as complete works as expected."""
<|body_0|>
def test_day_of_burn_actions(self):
"""Test that marking day of burn actions as complete works as expected."""
<|... | stack_v2_sparse_classes_10k_train_004105 | 5,840 | permissive | [
{
"docstring": "Test that marking pre-burn actions as complete works as expected.",
"name": "test_pre_burn_actions",
"signature": "def test_pre_burn_actions(self)"
},
{
"docstring": "Test that marking day of burn actions as complete works as expected.",
"name": "test_day_of_burn_actions",
... | 2 | stack_v2_sparse_classes_30k_train_006218 | Implement the Python class `BurnImplementationStateTests` described below.
Class description:
Implement the BurnImplementationStateTests class.
Method signatures and docstrings:
- def test_pre_burn_actions(self): Test that marking pre-burn actions as complete works as expected.
- def test_day_of_burn_actions(self): T... | Implement the Python class `BurnImplementationStateTests` described below.
Class description:
Implement the BurnImplementationStateTests class.
Method signatures and docstrings:
- def test_pre_burn_actions(self): Test that marking pre-burn actions as complete works as expected.
- def test_day_of_burn_actions(self): T... | 37113bfd3a18824f3cd3368e68672607b7a89cb3 | <|skeleton|>
class BurnImplementationStateTests:
def test_pre_burn_actions(self):
"""Test that marking pre-burn actions as complete works as expected."""
<|body_0|>
def test_day_of_burn_actions(self):
"""Test that marking day of burn actions as complete works as expected."""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BurnImplementationStateTests:
def test_pre_burn_actions(self):
"""Test that marking pre-burn actions as complete works as expected."""
p = self.make('Prescription')
day_state = p.day_state
self.assertFalse(day_state.pre_actions)
day_state.pre_actions = True
with... | the_stack_v2_python_sparse | pbs/report/tests.py | patrickmaslen/pbs | train | 0 | |
ba8e876a89132c06552098984ae7b9385fc2ba82 | [
"if not board:\n return\nrow = len(board)\ncol = len(board[0])\ndummy = row * col\nunion = UnionFind()\nfor i in range(row):\n for j in range(col):\n if board[i][j] == 'O':\n if i == 0 or i == row - 1 or j == 0 or (j == col - 1):\n union.add(i * col + j)\n union... | <|body_start_0|>
if not board:
return
row = len(board)
col = len(board[0])
dummy = row * col
union = UnionFind()
for i in range(row):
for j in range(col):
if board[i][j] == 'O':
if i == 0 or i == row - 1 or j == ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_0|>
def solve1(self, board: List[List[str]]) -> None:
"""dfs方式 :param self: :param board: :return:"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_004106 | 4,283 | no_license | [
{
"docstring": "Do not return anything, modify board in-place instead.",
"name": "solve",
"signature": "def solve(self, board: List[List[str]]) -> None"
},
{
"docstring": "dfs方式 :param self: :param board: :return:",
"name": "solve1",
"signature": "def solve1(self, board: List[List[str]])... | 2 | stack_v2_sparse_classes_30k_train_001308 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, board: List[List[str]]) -> None: Do not return anything, modify board in-place instead.
- def solve1(self, board: List[List[str]]) -> None: dfs方式 :param self: :pa... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, board: List[List[str]]) -> None: Do not return anything, modify board in-place instead.
- def solve1(self, board: List[List[str]]) -> None: dfs方式 :param self: :pa... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_0|>
def solve1(self, board: List[List[str]]) -> None:
"""dfs方式 :param self: :param board: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def solve(self, board: List[List[str]]) -> None:
"""Do not return anything, modify board in-place instead."""
if not board:
return
row = len(board)
col = len(board[0])
dummy = row * col
union = UnionFind()
for i in range(row):
... | the_stack_v2_python_sparse | datastructure/union_find/Solve.py | yinhuax/leet_code | train | 0 | |
669ba5d3ddcb833f1e01465ccec198b7daee4b80 | [
"super(Reader_Downstream, self).__init__()\nself.add = P.Add()\nself.para_bias = Parameter(Tensor(np.random.uniform(0, 1, (1,)).astype(np.float32)), name=None)\nself.para_output_layer = SupportingOutputLayer(linear_1_weight_shape=(4096, 8192), linear_1_bias_shape=(8192,), bert_layer_norm_weight_shape=(8192,), bert_... | <|body_start_0|>
super(Reader_Downstream, self).__init__()
self.add = P.Add()
self.para_bias = Parameter(Tensor(np.random.uniform(0, 1, (1,)).astype(np.float32)), name=None)
self.para_output_layer = SupportingOutputLayer(linear_1_weight_shape=(4096, 8192), linear_1_bias_shape=(8192,), be... | Downstream model for reader | Reader_Downstream | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reader_Downstream:
"""Downstream model for reader"""
def __init__(self):
"""init function"""
<|body_0|>
def construct(self, para_state, sent_state, state, context_mask):
"""construct function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super... | stack_v2_sparse_classes_10k_train_004107 | 9,011 | permissive | [
{
"docstring": "init function",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "construct function",
"name": "construct",
"signature": "def construct(self, para_state, sent_state, state, context_mask)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001444 | Implement the Python class `Reader_Downstream` described below.
Class description:
Downstream model for reader
Method signatures and docstrings:
- def __init__(self): init function
- def construct(self, para_state, sent_state, state, context_mask): construct function | Implement the Python class `Reader_Downstream` described below.
Class description:
Downstream model for reader
Method signatures and docstrings:
- def __init__(self): init function
- def construct(self, para_state, sent_state, state, context_mask): construct function
<|skeleton|>
class Reader_Downstream:
"""Down... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class Reader_Downstream:
"""Downstream model for reader"""
def __init__(self):
"""init function"""
<|body_0|>
def construct(self, para_state, sent_state, state, context_mask):
"""construct function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Reader_Downstream:
"""Downstream model for reader"""
def __init__(self):
"""init function"""
super(Reader_Downstream, self).__init__()
self.add = P.Add()
self.para_bias = Parameter(Tensor(np.random.uniform(0, 1, (1,)).astype(np.float32)), name=None)
self.para_outpu... | the_stack_v2_python_sparse | research/nlp/tprr/src/reader_downstream.py | mindspore-ai/models | train | 301 |
5a399fa9930d6c0b345fb6009e6259493cff6e35 | [
"if not gas or not cost or sum(cost) > sum(gas):\n return -1\nn = len(gas)\nfor i in range(n):\n position = i\n balance = 0\n for _ in range(n):\n balance += gas[position % n] - cost[position % n]\n if balance < 0:\n break\n position += 1\n else:\n return i\nret... | <|body_start_0|>
if not gas or not cost or sum(cost) > sum(gas):
return -1
n = len(gas)
for i in range(n):
position = i
balance = 0
for _ in range(n):
balance += gas[position % n] - cost[position % n]
if balance < 0:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
"""Complexity n^2"""
<|body_0|>
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
"""greedy algorithm"""
<|body_1|>
def canCompleteCircuit(self, gas: List... | stack_v2_sparse_classes_10k_train_004108 | 1,486 | no_license | [
{
"docstring": "Complexity n^2",
"name": "canCompleteCircuit",
"signature": "def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int"
},
{
"docstring": "greedy algorithm",
"name": "canCompleteCircuit",
"signature": "def canCompleteCircuit(self, gas: List[int], cost: List[int... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: Complexity n^2
- def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: greedy algorithm
- de... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: Complexity n^2
- def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: greedy algorithm
- de... | e50dc0642f087f37ab3234390be3d8a0ed48fe62 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
"""Complexity n^2"""
<|body_0|>
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
"""greedy algorithm"""
<|body_1|>
def canCompleteCircuit(self, gas: List... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
"""Complexity n^2"""
if not gas or not cost or sum(cost) > sum(gas):
return -1
n = len(gas)
for i in range(n):
position = i
balance = 0
for _ in range... | the_stack_v2_python_sparse | Leetcode/134. Gas Station.py | brlala/Educative-Grokking-Coding-Exercise | train | 3 | |
0760607db001d6263f43dfdb167b2b48d408668a | [
"super(MultiLoss, self).__init__(*losses)\nself.loss_fn = []\nfor loss in losses:\n self.loss_fn.append(loss)",
"outputs = None\nfor model in self.loss_fn:\n if outputs is None:\n outputs = model(output, target)\n else:\n outputs = outputs + model(output, target)\nreturn outputs"
] | <|body_start_0|>
super(MultiLoss, self).__init__(*losses)
self.loss_fn = []
for loss in losses:
self.loss_fn.append(loss)
<|end_body_0|>
<|body_start_1|>
outputs = None
for model in self.loss_fn:
if outputs is None:
outputs = model(output,... | Define Multi loss creator for base. | MultiLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiLoss:
"""Define Multi loss creator for base."""
def __init__(self, *losses):
"""Initialize loss."""
<|body_0|>
def call(self, output, target):
"""Sum all loss of predict and groundtruth."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super... | stack_v2_sparse_classes_10k_train_004109 | 1,238 | permissive | [
{
"docstring": "Initialize loss.",
"name": "__init__",
"signature": "def __init__(self, *losses)"
},
{
"docstring": "Sum all loss of predict and groundtruth.",
"name": "call",
"signature": "def call(self, output, target)"
}
] | 2 | null | Implement the Python class `MultiLoss` described below.
Class description:
Define Multi loss creator for base.
Method signatures and docstrings:
- def __init__(self, *losses): Initialize loss.
- def call(self, output, target): Sum all loss of predict and groundtruth. | Implement the Python class `MultiLoss` described below.
Class description:
Define Multi loss creator for base.
Method signatures and docstrings:
- def __init__(self, *losses): Initialize loss.
- def call(self, output, target): Sum all loss of predict and groundtruth.
<|skeleton|>
class MultiLoss:
"""Define Multi... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class MultiLoss:
"""Define Multi loss creator for base."""
def __init__(self, *losses):
"""Initialize loss."""
<|body_0|>
def call(self, output, target):
"""Sum all loss of predict and groundtruth."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiLoss:
"""Define Multi loss creator for base."""
def __init__(self, *losses):
"""Initialize loss."""
super(MultiLoss, self).__init__(*losses)
self.loss_fn = []
for loss in losses:
self.loss_fn.append(loss)
def call(self, output, target):
"""Sum... | the_stack_v2_python_sparse | zeus/modules/loss/multiloss.py | huawei-noah/xingtian | train | 308 |
5e3b369e1b7b75f80c19ae61fe3afe7c303eca34 | [
"opt = WassersteinCycleGANTestOptions if use_wasserstein else CycleGANTestOptions\nopt.checkpoints_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), opt.checkpoints_dir)\ntf_properties = {'load_size': opt.load_size, 'crop_size': opt.crop_size, 'preprocess': opt.preprocess, 'mask': os.path.join(os.path.di... | <|body_start_0|>
opt = WassersteinCycleGANTestOptions if use_wasserstein else CycleGANTestOptions
opt.checkpoints_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), opt.checkpoints_dir)
tf_properties = {'load_size': opt.load_size, 'crop_size': opt.crop_size, 'preprocess': opt.preproces... | Implementation of a simple ROS interface to translate simulated to "real" images. | ImageTranslator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageTranslator:
"""Implementation of a simple ROS interface to translate simulated to "real" images."""
def __init__(self, use_wasserstein=True):
"""Initialize the ImageTranslator class. Use default test options but could be via command-line. Load and setup the model"""
<|bo... | stack_v2_sparse_classes_10k_train_004110 | 5,855 | permissive | [
{
"docstring": "Initialize the ImageTranslator class. Use default test options but could be via command-line. Load and setup the model",
"name": "__init__",
"signature": "def __init__(self, use_wasserstein=True)"
},
{
"docstring": "Translate an image to a \"fake real\" image by using the loaded ... | 2 | stack_v2_sparse_classes_30k_train_006469 | Implement the Python class `ImageTranslator` described below.
Class description:
Implementation of a simple ROS interface to translate simulated to "real" images.
Method signatures and docstrings:
- def __init__(self, use_wasserstein=True): Initialize the ImageTranslator class. Use default test options but could be v... | Implement the Python class `ImageTranslator` described below.
Class description:
Implementation of a simple ROS interface to translate simulated to "real" images.
Method signatures and docstrings:
- def __init__(self, use_wasserstein=True): Initialize the ImageTranslator class. Use default test options but could be v... | 8a9438b5a24c288721ae0302889fe55e26046310 | <|skeleton|>
class ImageTranslator:
"""Implementation of a simple ROS interface to translate simulated to "real" images."""
def __init__(self, use_wasserstein=True):
"""Initialize the ImageTranslator class. Use default test options but could be via command-line. Load and setup the model"""
<|bo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImageTranslator:
"""Implementation of a simple ROS interface to translate simulated to "real" images."""
def __init__(self, use_wasserstein=True):
"""Initialize the ImageTranslator class. Use default test options but could be via command-line. Load and setup the model"""
opt = Wasserstein... | the_stack_v2_python_sparse | simulation/utils/machine_learning/cycle_gan/image_translator.py | KITcar-Team/kitcar-gazebo-simulation | train | 19 |
6c62533f884b57095d1924b36cba24805dac91fe | [
"uri = self.base_path\nresp = session.post(uri, headers={'Content-Type': 'application/json'}, endpoint_filter=self.service, json={'image_id': image_id, 'tenant_id_dst': tenant_id_dst})\nself._translate_response(resp, has_body=True)\nreturn self",
"uri = self.base_path + '/' + str(job_id)\nresp = session.delete(ur... | <|body_start_0|>
uri = self.base_path
resp = session.post(uri, headers={'Content-Type': 'application/json'}, endpoint_filter=self.service, json={'image_id': image_id, 'tenant_id_dst': tenant_id_dst})
self._translate_response(resp, has_body=True)
return self
<|end_body_0|>
<|body_start_1... | ImageCopy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageCopy:
def copy_image(self, session, image_id, tenant_id_dst):
"""Copy image to a specified region."""
<|body_0|>
def cancel_copy_image(self, session, job_id):
"""Cancel a specified image copy job."""
<|body_1|>
def list_image_copy_jobs(self, session... | stack_v2_sparse_classes_10k_train_004111 | 2,977 | permissive | [
{
"docstring": "Copy image to a specified region.",
"name": "copy_image",
"signature": "def copy_image(self, session, image_id, tenant_id_dst)"
},
{
"docstring": "Cancel a specified image copy job.",
"name": "cancel_copy_image",
"signature": "def cancel_copy_image(self, session, job_id)"... | 4 | stack_v2_sparse_classes_30k_train_000923 | Implement the Python class `ImageCopy` described below.
Class description:
Implement the ImageCopy class.
Method signatures and docstrings:
- def copy_image(self, session, image_id, tenant_id_dst): Copy image to a specified region.
- def cancel_copy_image(self, session, job_id): Cancel a specified image copy job.
- d... | Implement the Python class `ImageCopy` described below.
Class description:
Implement the ImageCopy class.
Method signatures and docstrings:
- def copy_image(self, session, image_id, tenant_id_dst): Copy image to a specified region.
- def cancel_copy_image(self, session, job_id): Cancel a specified image copy job.
- d... | c2dafba850c4e6fb55b5e10de79257bbc9a01af3 | <|skeleton|>
class ImageCopy:
def copy_image(self, session, image_id, tenant_id_dst):
"""Copy image to a specified region."""
<|body_0|>
def cancel_copy_image(self, session, job_id):
"""Cancel a specified image copy job."""
<|body_1|>
def list_image_copy_jobs(self, session... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImageCopy:
def copy_image(self, session, image_id, tenant_id_dst):
"""Copy image to a specified region."""
uri = self.base_path
resp = session.post(uri, headers={'Content-Type': 'application/json'}, endpoint_filter=self.service, json={'image_id': image_id, 'tenant_id_dst': tenant_id_ds... | the_stack_v2_python_sparse | ecl/image/v2/image_copy.py | nttcom/eclsdk | train | 5 | |
14935c8951193de3b8718182b8456168e31f57b4 | [
"self.smaller, self.bigger = ([], [])\nheapify(self.smaller)\nheapify(self.bigger)",
"heappush(self.bigger, num)\nheappush(self.smaller, -heappop(self.bigger))\nwhile len(self.smaller) > len(self.bigger):\n heappush(self.bigger, -heappop(self.smaller))",
"if len(self.smaller) == len(self.bigger):\n return... | <|body_start_0|>
self.smaller, self.bigger = ([], [])
heapify(self.smaller)
heapify(self.bigger)
<|end_body_0|>
<|body_start_1|>
heappush(self.bigger, num)
heappush(self.smaller, -heappop(self.bigger))
while len(self.smaller) > len(self.bigger):
heappush(self... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_10k_train_004112 | 1,169 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type num: int :rtype: None",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": ":rtype: float",
"name": "findMedian",
"s... | 3 | null | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: None
- def findMedian(self): :rtype: float | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: None
- def findMedian(self): :rtype: float
<|skeleton|>
class Me... | 76d767ec001649b2df07aac211ac4b43b415ebdd | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
self.smaller, self.bigger = ([], [])
heapify(self.smaller)
heapify(self.bigger)
def addNum(self, num):
""":type num: int :rtype: None"""
heappush(self.bigger, num)
heappush... | the_stack_v2_python_sparse | leetcode295 Find Median from Data Stream.py | whglamrock/leetcode_series | train | 2 | |
3b729d42e3ec9b7c9ef4d5dae046314139869071 | [
"if self.request.user.is_authenticated:\n return self.request.user.is_manager\nelse:\n False",
"manger_form = form.save(commit=False)\nmanger_form.manager = self.request.user\nmanger_form.save()\nreturn super(InteractionCreateView, self).form_valid(form)"
] | <|body_start_0|>
if self.request.user.is_authenticated:
return self.request.user.is_manager
else:
False
<|end_body_0|>
<|body_start_1|>
manger_form = form.save(commit=False)
manger_form.manager = self.request.user
manger_form.save()
return super(I... | Класс для создания взаимодействия | InteractionCreateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InteractionCreateView:
"""Класс для создания взаимодействия"""
def test_func(self):
"""Отклоняет реквест с 403 ошибкой,если метод возвращает False"""
<|body_0|>
def form_valid(self, form):
"""Вызывается, если форма валидна и добавляет к взаимодействию менеджера,к... | stack_v2_sparse_classes_10k_train_004113 | 17,093 | no_license | [
{
"docstring": "Отклоняет реквест с 403 ошибкой,если метод возвращает False",
"name": "test_func",
"signature": "def test_func(self)"
},
{
"docstring": "Вызывается, если форма валидна и добавляет к взаимодействию менеджера,которым оно было создано",
"name": "form_valid",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_005116 | Implement the Python class `InteractionCreateView` described below.
Class description:
Класс для создания взаимодействия
Method signatures and docstrings:
- def test_func(self): Отклоняет реквест с 403 ошибкой,если метод возвращает False
- def form_valid(self, form): Вызывается, если форма валидна и добавляет к взаим... | Implement the Python class `InteractionCreateView` described below.
Class description:
Класс для создания взаимодействия
Method signatures and docstrings:
- def test_func(self): Отклоняет реквест с 403 ошибкой,если метод возвращает False
- def form_valid(self, form): Вызывается, если форма валидна и добавляет к взаим... | e987577ebf0fe153029ec4c0312d2132f43e2180 | <|skeleton|>
class InteractionCreateView:
"""Класс для создания взаимодействия"""
def test_func(self):
"""Отклоняет реквест с 403 ошибкой,если метод возвращает False"""
<|body_0|>
def form_valid(self, form):
"""Вызывается, если форма валидна и добавляет к взаимодействию менеджера,к... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InteractionCreateView:
"""Класс для создания взаимодействия"""
def test_func(self):
"""Отклоняет реквест с 403 ошибкой,если метод возвращает False"""
if self.request.user.is_authenticated:
return self.request.user.is_manager
else:
False
def form_valid(... | the_stack_v2_python_sparse | crmapp/crm/views.py | vova55151/2342343243 | train | 0 |
a745098dad93ebee4282f503a489fe10d56f64a3 | [
"for item in content.items():\n if item not in serializer.data.items():\n key, val = item\n print('CONTENT %s' % key.upper(), val)\n print('SERIALIZER %s' % key.upper(), serializer.data[key])",
"diff = (item for item in list_a if item not in list_b)\nfor d in diff:\n print(d)"
] | <|body_start_0|>
for item in content.items():
if item not in serializer.data.items():
key, val = item
print('CONTENT %s' % key.upper(), val)
print('SERIALIZER %s' % key.upper(), serializer.data[key])
<|end_body_0|>
<|body_start_1|>
diff = (ite... | Some method to help the test | TestMixinUtils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMixinUtils:
"""Some method to help the test"""
def all_serializer_items_diff_assertion(self, serializer, content):
"""Find out the different items and print them out"""
<|body_0|>
def diff_between_lists(self, list_a, list_b):
"""Find the different items betwe... | stack_v2_sparse_classes_10k_train_004114 | 7,639 | no_license | [
{
"docstring": "Find out the different items and print them out",
"name": "all_serializer_items_diff_assertion",
"signature": "def all_serializer_items_diff_assertion(self, serializer, content)"
},
{
"docstring": "Find the different items between two lists :type list_a: list :type list_b: list",... | 2 | null | Implement the Python class `TestMixinUtils` described below.
Class description:
Some method to help the test
Method signatures and docstrings:
- def all_serializer_items_diff_assertion(self, serializer, content): Find out the different items and print them out
- def diff_between_lists(self, list_a, list_b): Find the ... | Implement the Python class `TestMixinUtils` described below.
Class description:
Some method to help the test
Method signatures and docstrings:
- def all_serializer_items_diff_assertion(self, serializer, content): Find out the different items and print them out
- def diff_between_lists(self, list_a, list_b): Find the ... | 33d6e35ef3483da311c06502f9b6ce996bc0d06e | <|skeleton|>
class TestMixinUtils:
"""Some method to help the test"""
def all_serializer_items_diff_assertion(self, serializer, content):
"""Find out the different items and print them out"""
<|body_0|>
def diff_between_lists(self, list_a, list_b):
"""Find the different items betwe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestMixinUtils:
"""Some method to help the test"""
def all_serializer_items_diff_assertion(self, serializer, content):
"""Find out the different items and print them out"""
for item in content.items():
if item not in serializer.data.items():
key, val = item
... | the_stack_v2_python_sparse | utils/tests.py | levivm/backend | train | 1 |
4316dd648a836b67fd26c58b4a557df4bfffc03e | [
"self.continue_on_error = continue_on_error\nself.is_active = is_active\nself.script_params = script_params\nself.script_path = script_path\nself.timeout_secs = timeout_secs",
"if dictionary is None:\n return None\ncontinue_on_error = dictionary.get('continueOnError')\nis_active = dictionary.get('isActive')\ns... | <|body_start_0|>
self.continue_on_error = continue_on_error
self.is_active = is_active
self.script_params = script_params
self.script_path = script_path
self.timeout_secs = timeout_secs
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
... | Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to true, then backup job will start even if the pre backup script fails. is_active (bool):... | ScriptPathAndParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScriptPathAndParams:
"""Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to true, then backup job will start even if... | stack_v2_sparse_classes_10k_train_004115 | 3,226 | permissive | [
{
"docstring": "Constructor for the ScriptPathAndParams class",
"name": "__init__",
"signature": "def __init__(self, continue_on_error=None, is_active=None, script_params=None, script_path=None, timeout_secs=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dict... | 2 | stack_v2_sparse_classes_30k_train_001704 | Implement the Python class `ScriptPathAndParams` described below.
Class description:
Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to t... | Implement the Python class `ScriptPathAndParams` described below.
Class description:
Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to t... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ScriptPathAndParams:
"""Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to true, then backup job will start even if... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ScriptPathAndParams:
"""Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to true, then backup job will start even if the pre back... | the_stack_v2_python_sparse | cohesity_management_sdk/models/script_path_and_params.py | cohesity/management-sdk-python | train | 24 |
2662eab3094ce1b4b0db9369edac940ffe9ada52 | [
"self.controller = controller\nself.deserializer = deserializer or RequestDeserializer()\nself.serializer = serializer or ResponseSerializer()\nself._fault_body_function = fault_body_function",
"LOG.info('%(method)s %(url)s', {'method': request.method, 'url': request.url})\ntry:\n action, args, accept = self.d... | <|body_start_0|>
self.controller = controller
self.deserializer = deserializer or RequestDeserializer()
self.serializer = serializer or ResponseSerializer()
self._fault_body_function = fault_body_function
<|end_body_0|>
<|body_start_1|>
LOG.info('%(method)s %(url)s', {'method': ... | WSGI app that handles (de)serialization and controller dispatch. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a 'req' argument, which is the incoming wsgi.Request. If the operation is a PUT or PO... | Resource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resource:
"""WSGI app that handles (de)serialization and controller dispatch. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a 'req' argument, which is the incoming wsgi.Requ... | stack_v2_sparse_classes_10k_train_004116 | 29,625 | permissive | [
{
"docstring": "Object initialization. :param controller: object that implement methods created by routes lib :param deserializer: object that can serialize the output of a controller into a webob response :param serializer: object that can deserialize a webob request into necessary pieces :param fault_body_fun... | 3 | null | Implement the Python class `Resource` described below.
Class description:
WSGI app that handles (de)serialization and controller dispatch. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a 'req' ar... | Implement the Python class `Resource` described below.
Class description:
WSGI app that handles (de)serialization and controller dispatch. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a 'req' ar... | dde31aae392b80341f6440eb38db1583563d7d1f | <|skeleton|>
class Resource:
"""WSGI app that handles (de)serialization and controller dispatch. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a 'req' argument, which is the incoming wsgi.Requ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Resource:
"""WSGI app that handles (de)serialization and controller dispatch. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a 'req' argument, which is the incoming wsgi.Request. If the o... | the_stack_v2_python_sparse | neutron/wsgi.py | openstack/neutron | train | 1,174 |
753f5b230f4f020a079d35e99f32e32673ac2c21 | [
"entity = cls.__name__\nif not isinstance(properties, dict):\n raise TypeError(f'{str(entity)} properties {properties} are of type {type(properties)}, they should be a `dict`.')\nfor key, value in properties.items():\n if not isinstance(key, str):\n raise TypeError(f\"{str(entity)} property {key} : {va... | <|body_start_0|>
entity = cls.__name__
if not isinstance(properties, dict):
raise TypeError(f'{str(entity)} properties {properties} are of type {type(properties)}, they should be a `dict`.')
for key, value in properties.items():
if not isinstance(key, str):
... | The mixin for Container and Well entities used to mutate the entity instance ctx_properties and properties | EntityPropertiesMixin | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntityPropertiesMixin:
"""The mixin for Container and Well entities used to mutate the entity instance ctx_properties and properties"""
def validate_properties(cls, properties):
"""Validates that properties are valid"""
<|body_0|>
def fromDict(self, dict_: Dict):
... | stack_v2_sparse_classes_10k_train_004117 | 41,841 | permissive | [
{
"docstring": "Validates that properties are valid",
"name": "validate_properties",
"signature": "def validate_properties(cls, properties)"
},
{
"docstring": "Generates the EntityProperties mapping from a dictionary Parameters ---------- dict_ : dict Dictionary of properties to associate to a e... | 6 | null | Implement the Python class `EntityPropertiesMixin` described below.
Class description:
The mixin for Container and Well entities used to mutate the entity instance ctx_properties and properties
Method signatures and docstrings:
- def validate_properties(cls, properties): Validates that properties are valid
- def from... | Implement the Python class `EntityPropertiesMixin` described below.
Class description:
The mixin for Container and Well entities used to mutate the entity instance ctx_properties and properties
Method signatures and docstrings:
- def validate_properties(cls, properties): Validates that properties are valid
- def from... | 84f6d3fced521849657d21ae4cb9681f5897b957 | <|skeleton|>
class EntityPropertiesMixin:
"""The mixin for Container and Well entities used to mutate the entity instance ctx_properties and properties"""
def validate_properties(cls, properties):
"""Validates that properties are valid"""
<|body_0|>
def fromDict(self, dict_: Dict):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EntityPropertiesMixin:
"""The mixin for Container and Well entities used to mutate the entity instance ctx_properties and properties"""
def validate_properties(cls, properties):
"""Validates that properties are valid"""
entity = cls.__name__
if not isinstance(properties, dict):
... | the_stack_v2_python_sparse | venv/lib/python3.9/site-packages/autoprotocol/container.py | ClassWizard/PodLockParser | train | 2 |
1b5caaf8edd93e3f28dbdee27db9e5d5714030ca | [
"super().__init__()\nlayers: list[Module] = [nn.modules.Sequential(nn.modules.Conv2d(in_channels, inner_channels, 3, 1, 1), nn.modules.BatchNorm2d(inner_channels), nn.modules.ReLU(True))]\nlayers += [nn.modules.Sequential(nn.modules.Conv2d(inner_channels, inner_channels, 3, 1, 1), nn.modules.BatchNorm2d(inner_chann... | <|body_start_0|>
super().__init__()
layers: list[Module] = [nn.modules.Sequential(nn.modules.Conv2d(in_channels, inner_channels, 3, 1, 1), nn.modules.BatchNorm2d(inner_channels), nn.modules.ReLU(True))]
layers += [nn.modules.Sequential(nn.modules.Conv2d(inner_channels, inner_channels, 3, 1, 1), ... | This module enables any segmentation model to detect binary change. The common usage is to attach this module on a segmentation model without the classification head. If you use this model in your research, please cite the following paper: * https://arxiv.org/abs/2108.07002 | ChangeMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeMixin:
"""This module enables any segmentation model to detect binary change. The common usage is to attach this module on a segmentation model without the classification head. If you use this model in your research, please cite the following paper: * https://arxiv.org/abs/2108.07002"""
... | stack_v2_sparse_classes_10k_train_004118 | 7,715 | permissive | [
{
"docstring": "Initializes a new ChangeMixin module. Args: in_channels: sum of channels of bitemporal feature maps inner_channels: number of channels of inner feature maps num_convs: number of convolution blocks scale_factor: number of upsampling factor",
"name": "__init__",
"signature": "def __init__(... | 2 | stack_v2_sparse_classes_30k_train_002964 | Implement the Python class `ChangeMixin` described below.
Class description:
This module enables any segmentation model to detect binary change. The common usage is to attach this module on a segmentation model without the classification head. If you use this model in your research, please cite the following paper: * ... | Implement the Python class `ChangeMixin` described below.
Class description:
This module enables any segmentation model to detect binary change. The common usage is to attach this module on a segmentation model without the classification head. If you use this model in your research, please cite the following paper: * ... | 29985861614b3b93f9ef5389469ebb98570de7dd | <|skeleton|>
class ChangeMixin:
"""This module enables any segmentation model to detect binary change. The common usage is to attach this module on a segmentation model without the classification head. If you use this model in your research, please cite the following paper: * https://arxiv.org/abs/2108.07002"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ChangeMixin:
"""This module enables any segmentation model to detect binary change. The common usage is to attach this module on a segmentation model without the classification head. If you use this model in your research, please cite the following paper: * https://arxiv.org/abs/2108.07002"""
def __init_... | the_stack_v2_python_sparse | torchgeo/models/changestar.py | microsoft/torchgeo | train | 1,724 |
378c845527ed1579e91c7197270a543a223c26a0 | [
"data = np.ones((16, 16), dtype=np.float32)\nself.cube = set_up_variable_cube(data, 'precipitation_amount', 'kg m^-2', grid_spacing=1, domain_corner=(49, -8))\nself.cube_360 = set_up_variable_cube(data, 'precipitation_amount', 'kg m^-2', grid_spacing=1, domain_corner=(49, 345))\nself.spot_cube = create_spot_cube(xr... | <|body_start_0|>
data = np.ones((16, 16), dtype=np.float32)
self.cube = set_up_variable_cube(data, 'precipitation_amount', 'kg m^-2', grid_spacing=1, domain_corner=(49, -8))
self.cube_360 = set_up_variable_cube(data, 'precipitation_amount', 'kg m^-2', grid_spacing=1, domain_corner=(49, 345))
... | Test string representation | Test__daynight_lat_lon_cube | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__daynight_lat_lon_cube:
"""Test string representation"""
def setUp(self):
"""Set up the cube for testing."""
<|body_0|>
def test_basic_lat_lon_cube_gridded(self):
"""Test this create a blank gridded mask cube"""
<|body_1|>
def test_basic_lat_lon... | stack_v2_sparse_classes_10k_train_004119 | 18,065 | permissive | [
{
"docstring": "Set up the cube for testing.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test this create a blank gridded mask cube",
"name": "test_basic_lat_lon_cube_gridded",
"signature": "def test_basic_lat_lon_cube_gridded(self)"
},
{
"docstring": "Te... | 4 | null | Implement the Python class `Test__daynight_lat_lon_cube` described below.
Class description:
Test string representation
Method signatures and docstrings:
- def setUp(self): Set up the cube for testing.
- def test_basic_lat_lon_cube_gridded(self): Test this create a blank gridded mask cube
- def test_basic_lat_lon_cub... | Implement the Python class `Test__daynight_lat_lon_cube` described below.
Class description:
Test string representation
Method signatures and docstrings:
- def setUp(self): Set up the cube for testing.
- def test_basic_lat_lon_cube_gridded(self): Test this create a blank gridded mask cube
- def test_basic_lat_lon_cub... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__daynight_lat_lon_cube:
"""Test string representation"""
def setUp(self):
"""Set up the cube for testing."""
<|body_0|>
def test_basic_lat_lon_cube_gridded(self):
"""Test this create a blank gridded mask cube"""
<|body_1|>
def test_basic_lat_lon... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test__daynight_lat_lon_cube:
"""Test string representation"""
def setUp(self):
"""Set up the cube for testing."""
data = np.ones((16, 16), dtype=np.float32)
self.cube = set_up_variable_cube(data, 'precipitation_amount', 'kg m^-2', grid_spacing=1, domain_corner=(49, -8))
se... | the_stack_v2_python_sparse | improver_tests/utilities/solar/test_DayNightMask.py | metoppv/improver | train | 101 |
1d95b2c16f355fcf690685b4112ff05e08d1c2db | [
"self.contents = HashMap()\nfor gdl in description:\n if not self.contents.containsKey(key):\n self.contents.put(key, ArrayList())\n self.contents.get(key).add(rule)",
"key = sentence.__name__\nif self.contents.containsKey(key):\n return self.contents.get(key)\nelse:\n return ArrayList()"
] | <|body_start_0|>
self.contents = HashMap()
for gdl in description:
if not self.contents.containsKey(key):
self.contents.put(key, ArrayList())
self.contents.get(key).add(rule)
<|end_body_0|>
<|body_start_1|>
key = sentence.__name__
if self.contents... | generated source for class KnowledgeBase | KnowledgeBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KnowledgeBase:
"""generated source for class KnowledgeBase"""
def __init__(self, description):
"""generated source for method __init__"""
<|body_0|>
def fetch(self, sentence):
"""generated source for method fetch"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_10k_train_004120 | 1,425 | permissive | [
{
"docstring": "generated source for method __init__",
"name": "__init__",
"signature": "def __init__(self, description)"
},
{
"docstring": "generated source for method fetch",
"name": "fetch",
"signature": "def fetch(self, sentence)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006147 | Implement the Python class `KnowledgeBase` described below.
Class description:
generated source for class KnowledgeBase
Method signatures and docstrings:
- def __init__(self, description): generated source for method __init__
- def fetch(self, sentence): generated source for method fetch | Implement the Python class `KnowledgeBase` described below.
Class description:
generated source for class KnowledgeBase
Method signatures and docstrings:
- def __init__(self, description): generated source for method __init__
- def fetch(self, sentence): generated source for method fetch
<|skeleton|>
class Knowledge... | 4e6e6e876c3a4294cd711647051da2d9c1836b60 | <|skeleton|>
class KnowledgeBase:
"""generated source for class KnowledgeBase"""
def __init__(self, description):
"""generated source for method __init__"""
<|body_0|>
def fetch(self, sentence):
"""generated source for method fetch"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KnowledgeBase:
"""generated source for class KnowledgeBase"""
def __init__(self, description):
"""generated source for method __init__"""
self.contents = HashMap()
for gdl in description:
if not self.contents.containsKey(key):
self.contents.put(key, Arr... | the_stack_v2_python_sparse | ggpy/cruft/autocode/KnowledgeBase.py | hobson/ggpy | train | 1 |
e063df01da31a836e52be8c53f7d3ed55daa12a0 | [
"self.eval_model = eval_model.to(device)\nself.submission = pd.read_csv(submission_template)\nself.test_dataset = test_dataset\nself.device = device",
"for image, image_name, image_leaderboard in tqdm(self.test_dataset):\n image = image.to(self.device).unsqueeze(0)\n predicted_class, predicted_kev = self.ev... | <|body_start_0|>
self.eval_model = eval_model.to(device)
self.submission = pd.read_csv(submission_template)
self.test_dataset = test_dataset
self.device = device
<|end_body_0|>
<|body_start_1|>
for image, image_name, image_leaderboard in tqdm(self.test_dataset):
imag... | SubmissionMaker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubmissionMaker:
def __init__(self, eval_model: nn.Module, submission_template: str, test_dataset: IdaoInferenceDataset, device: str='cuda:0'):
"""[Use trained model to make prediction and generate a submission file] Args: eval_model (nn.Module): [Eval model after loading weight to archi... | stack_v2_sparse_classes_10k_train_004121 | 3,102 | no_license | [
{
"docstring": "[Use trained model to make prediction and generate a submission file] Args: eval_model (nn.Module): [Eval model after loading weight to architecture] submission_template (str): [Submission template file] test_dataset (IdaoInferenceDataset): [Pytorch dataset for private and public test] device (s... | 2 | stack_v2_sparse_classes_30k_train_001572 | Implement the Python class `SubmissionMaker` described below.
Class description:
Implement the SubmissionMaker class.
Method signatures and docstrings:
- def __init__(self, eval_model: nn.Module, submission_template: str, test_dataset: IdaoInferenceDataset, device: str='cuda:0'): [Use trained model to make prediction... | Implement the Python class `SubmissionMaker` described below.
Class description:
Implement the SubmissionMaker class.
Method signatures and docstrings:
- def __init__(self, eval_model: nn.Module, submission_template: str, test_dataset: IdaoInferenceDataset, device: str='cuda:0'): [Use trained model to make prediction... | 56fe9005ebc915acd962a4b17fb057c86ef0ebd8 | <|skeleton|>
class SubmissionMaker:
def __init__(self, eval_model: nn.Module, submission_template: str, test_dataset: IdaoInferenceDataset, device: str='cuda:0'):
"""[Use trained model to make prediction and generate a submission file] Args: eval_model (nn.Module): [Eval model after loading weight to archi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SubmissionMaker:
def __init__(self, eval_model: nn.Module, submission_template: str, test_dataset: IdaoInferenceDataset, device: str='cuda:0'):
"""[Use trained model to make prediction and generate a submission file] Args: eval_model (nn.Module): [Eval model after loading weight to architecture] submi... | the_stack_v2_python_sparse | src/submission_maker.py | 3outeille/IDAO-2021-Qualifier | train | 0 | |
27fe09b7cb917c800936f92418e336a711280fa4 | [
"if not is_all(eids):\n gidx = gidx.edge_subgraph([eids], True).graph\nif norm_by == 'src':\n gidx = gidx.reverse()\nu_len = gidx.number_of_ntypes()\ne_len = gidx.number_of_etypes()\nlhs = [None] * u_len\nfeats = tuple(lhs + list(score))\nscore_max = _gspmm_hetero(gidx, 'copy_rhs', 'max', u_len, feats)[0]\nou... | <|body_start_0|>
if not is_all(eids):
gidx = gidx.edge_subgraph([eids], True).graph
if norm_by == 'src':
gidx = gidx.reverse()
u_len = gidx.number_of_ntypes()
e_len = gidx.number_of_etypes()
lhs = [None] * u_len
feats = tuple(lhs + list(score))
... | EdgeSoftmax_hetero | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdgeSoftmax_hetero:
def forward(ctx, gidx, eids, norm_by, *score):
"""Forward function. Pseudo-code: .. code:: python score = dgl.EData(g, score) score_max = score.dst_max() # of type dgl.NData score = score - score_max # edge_sub_dst, ret dgl.EData score_sum = score.dst_sum() # of type ... | stack_v2_sparse_classes_10k_train_004122 | 40,333 | permissive | [
{
"docstring": "Forward function. Pseudo-code: .. code:: python score = dgl.EData(g, score) score_max = score.dst_max() # of type dgl.NData score = score - score_max # edge_sub_dst, ret dgl.EData score_sum = score.dst_sum() # of type dgl.NData out = score / score_sum # edge_div_dst, ret dgl.EData return out.dat... | 2 | null | Implement the Python class `EdgeSoftmax_hetero` described below.
Class description:
Implement the EdgeSoftmax_hetero class.
Method signatures and docstrings:
- def forward(ctx, gidx, eids, norm_by, *score): Forward function. Pseudo-code: .. code:: python score = dgl.EData(g, score) score_max = score.dst_max() # of ty... | Implement the Python class `EdgeSoftmax_hetero` described below.
Class description:
Implement the EdgeSoftmax_hetero class.
Method signatures and docstrings:
- def forward(ctx, gidx, eids, norm_by, *score): Forward function. Pseudo-code: .. code:: python score = dgl.EData(g, score) score_max = score.dst_max() # of ty... | bbc8ff6261f2e0d2b5982e992b6fbe545e2a4aa1 | <|skeleton|>
class EdgeSoftmax_hetero:
def forward(ctx, gidx, eids, norm_by, *score):
"""Forward function. Pseudo-code: .. code:: python score = dgl.EData(g, score) score_max = score.dst_max() # of type dgl.NData score = score - score_max # edge_sub_dst, ret dgl.EData score_sum = score.dst_sum() # of type ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EdgeSoftmax_hetero:
def forward(ctx, gidx, eids, norm_by, *score):
"""Forward function. Pseudo-code: .. code:: python score = dgl.EData(g, score) score_max = score.dst_max() # of type dgl.NData score = score - score_max # edge_sub_dst, ret dgl.EData score_sum = score.dst_sum() # of type dgl.NData out ... | the_stack_v2_python_sparse | python/dgl/backend/pytorch/sparse.py | dmlc/dgl | train | 12,631 | |
011fd74f7ee1e5058d89451fb37547bc94af2209 | [
"logger.debug('Parsing request object to XML')\ntry:\n xml = xmltodict.unparse(request.normalize_xml())\nexcept Exception as e:\n error_msg = 'Error parsing request to XML'\n logger.error('{}: {}'.format(error_msg, e))\n raise SdkError(error_msg, e)\nreturn xml",
"logger.debug('Parsing XML response to... | <|body_start_0|>
logger.debug('Parsing request object to XML')
try:
xml = xmltodict.unparse(request.normalize_xml())
except Exception as e:
error_msg = 'Error parsing request to XML'
logger.error('{}: {}'.format(error_msg, e))
raise SdkError(error_... | Utils to serialize and deserialize objects to XML | XmlUtils | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XmlUtils:
"""Utils to serialize and deserialize objects to XML"""
def to_xml(request):
"""This method parse request to XML object :return: string"""
<|body_0|>
def from_xml_api_response(xml):
"""Method parse XML to dict. :param xml: string :return: dict"""
... | stack_v2_sparse_classes_10k_train_004123 | 1,447 | permissive | [
{
"docstring": "This method parse request to XML object :return: string",
"name": "to_xml",
"signature": "def to_xml(request)"
},
{
"docstring": "Method parse XML to dict. :param xml: string :return: dict",
"name": "from_xml_api_response",
"signature": "def from_xml_api_response(xml)"
... | 2 | stack_v2_sparse_classes_30k_train_000037 | Implement the Python class `XmlUtils` described below.
Class description:
Utils to serialize and deserialize objects to XML
Method signatures and docstrings:
- def to_xml(request): This method parse request to XML object :return: string
- def from_xml_api_response(xml): Method parse XML to dict. :param xml: string :r... | Implement the Python class `XmlUtils` described below.
Class description:
Utils to serialize and deserialize objects to XML
Method signatures and docstrings:
- def to_xml(request): This method parse request to XML object :return: string
- def from_xml_api_response(xml): Method parse XML to dict. :param xml: string :r... | 8fcf2a0e9d6d99d18e313f04b9721ccc4769a83f | <|skeleton|>
class XmlUtils:
"""Utils to serialize and deserialize objects to XML"""
def to_xml(request):
"""This method parse request to XML object :return: string"""
<|body_0|>
def from_xml_api_response(xml):
"""Method parse XML to dict. :param xml: string :return: dict"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class XmlUtils:
"""Utils to serialize and deserialize objects to XML"""
def to_xml(request):
"""This method parse request to XML object :return: string"""
logger.debug('Parsing request object to XML')
try:
xml = xmltodict.unparse(request.normalize_xml())
except Excep... | the_stack_v2_python_sparse | addonpayments/api/utils.py | ComerciaGP/addonpayments-Python-SDK | train | 3 |
ec67429fb2fb8fed002590ecf6fe34a524f7f753 | [
"logger.info('Training the model.')\nconfig = self.get_config()\nif seed:\n logger.info(f'Setting seed to {seed}')\n seed_everything(seed, workers=True)\nconfig.trainer.deterministic = 'warn' if deterministic else deterministic\nlogger.info(\"Training Configs '%s'\", config)\ndatamodule = OTXAnomalyDataModule... | <|body_start_0|>
logger.info('Training the model.')
config = self.get_config()
if seed:
logger.info(f'Setting seed to {seed}')
seed_everything(seed, workers=True)
config.trainer.deterministic = 'warn' if deterministic else deterministic
logger.info("Traini... | Base Anomaly Task. | TrainingTask | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainingTask:
"""Base Anomaly Task."""
def train(self, dataset: DatasetEntity, output_model: ModelEntity, train_parameters: TrainParameters, seed: Optional[int]=None, deterministic: bool=False) -> None:
"""Train the anomaly classification model. Args: dataset (DatasetEntity): Input d... | stack_v2_sparse_classes_10k_train_004124 | 5,264 | permissive | [
{
"docstring": "Train the anomaly classification model. Args: dataset (DatasetEntity): Input dataset. output_model (ModelEntity): Output model to save the model weights. train_parameters (TrainParameters): Training parameters seed (Optional[int]): Setting seed to a value other than 0 deterministic (bool): Setti... | 2 | stack_v2_sparse_classes_30k_train_003430 | Implement the Python class `TrainingTask` described below.
Class description:
Base Anomaly Task.
Method signatures and docstrings:
- def train(self, dataset: DatasetEntity, output_model: ModelEntity, train_parameters: TrainParameters, seed: Optional[int]=None, deterministic: bool=False) -> None: Train the anomaly cla... | Implement the Python class `TrainingTask` described below.
Class description:
Base Anomaly Task.
Method signatures and docstrings:
- def train(self, dataset: DatasetEntity, output_model: ModelEntity, train_parameters: TrainParameters, seed: Optional[int]=None, deterministic: bool=False) -> None: Train the anomaly cla... | 80454808b38727e358e8b880043eeac0f18152fb | <|skeleton|>
class TrainingTask:
"""Base Anomaly Task."""
def train(self, dataset: DatasetEntity, output_model: ModelEntity, train_parameters: TrainParameters, seed: Optional[int]=None, deterministic: bool=False) -> None:
"""Train the anomaly classification model. Args: dataset (DatasetEntity): Input d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TrainingTask:
"""Base Anomaly Task."""
def train(self, dataset: DatasetEntity, output_model: ModelEntity, train_parameters: TrainParameters, seed: Optional[int]=None, deterministic: bool=False) -> None:
"""Train the anomaly classification model. Args: dataset (DatasetEntity): Input dataset. outpu... | the_stack_v2_python_sparse | src/otx/algorithms/anomaly/tasks/train.py | openvinotoolkit/training_extensions | train | 397 |
cb82c6fd958fd9f2a6dc5b2d445a99f30cbc4a12 | [
"if Arm64e.check_valid_pointer_format(pointer_format):\n raise NotImplementedError('Arm64e is not implemented yet')\nelif Generic64.check_valid_pointer_format(pointer_format):\n if self.generic64.bind.bind:\n return (self.generic64.bind.ordinal, self.generic64.bind.addend)\n else:\n return No... | <|body_start_0|>
if Arm64e.check_valid_pointer_format(pointer_format):
raise NotImplementedError('Arm64e is not implemented yet')
elif Generic64.check_valid_pointer_format(pointer_format):
if self.generic64.bind.bind:
return (self.generic64.bind.ordinal, self.gene... | the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141 | ChainedFixupPointerOnDisk | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChainedFixupPointerOnDisk:
"""the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141"""
def isBind(self, pointer_format: DyldChainedPtrFormats) -> Optional[Tuple[int, int]]:
"""Port of ChainedFixupP... | stack_v2_sparse_classes_10k_train_004125 | 13,909 | permissive | [
{
"docstring": "Port of ChainedFixupPointerOnDisk::isBind(uint16_t pointerFormat, uint32_t& bindOrdinal, int64_t& addend) https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.cpp#L1098-L1147 Returns None if not a bind (so `if struct.isBind()` works), :return:",
"name": "isBind",
"signat... | 2 | stack_v2_sparse_classes_30k_train_002849 | Implement the Python class `ChainedFixupPointerOnDisk` described below.
Class description:
the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141
Method signatures and docstrings:
- def isBind(self, pointer_format: DyldChainedPtrFor... | Implement the Python class `ChainedFixupPointerOnDisk` described below.
Class description:
the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141
Method signatures and docstrings:
- def isBind(self, pointer_format: DyldChainedPtrFor... | 23edc1e95b0b1bace308ca80b5a8189bf8cbf8f3 | <|skeleton|>
class ChainedFixupPointerOnDisk:
"""the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141"""
def isBind(self, pointer_format: DyldChainedPtrFormats) -> Optional[Tuple[int, int]]:
"""Port of ChainedFixupP... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ChainedFixupPointerOnDisk:
"""the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141"""
def isBind(self, pointer_format: DyldChainedPtrFormats) -> Optional[Tuple[int, int]]:
"""Port of ChainedFixupPointerOnDisk:... | the_stack_v2_python_sparse | cle/backends/macho/structs.py | angr/cle | train | 389 |
d39e17a393aa6fdc344046ef8159f4dd631d9f2d | [
"if status == 'CANCELLED' and (not cancel_reason):\n raise ILLError('You have to provide a cancel reason when cancelling a request')\nif cancel_reason and (not status == 'CANCELLED'):\n raise ILLError('If you select a cancel reason you need to select \"Cancelled\" in the state')",
"Document = current_app_il... | <|body_start_0|>
if status == 'CANCELLED' and (not cancel_reason):
raise ILLError('You have to provide a cancel reason when cancelling a request')
if cancel_reason and (not status == 'CANCELLED'):
raise ILLError('If you select a cancel reason you need to select "Cancelled" in the... | Ill record validator. | IllValidator | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IllValidator:
"""Ill record validator."""
def validate_cancel(self, status, cancel_reason):
"""Validate decline is correct."""
<|body_0|>
def ensure_document_exists(self, document_pid):
"""Ensure document exists or raise."""
<|body_1|>
def ensure_pat... | stack_v2_sparse_classes_10k_train_004126 | 13,301 | permissive | [
{
"docstring": "Validate decline is correct.",
"name": "validate_cancel",
"signature": "def validate_cancel(self, status, cancel_reason)"
},
{
"docstring": "Ensure document exists or raise.",
"name": "ensure_document_exists",
"signature": "def ensure_document_exists(self, document_pid)"
... | 5 | stack_v2_sparse_classes_30k_train_006644 | Implement the Python class `IllValidator` described below.
Class description:
Ill record validator.
Method signatures and docstrings:
- def validate_cancel(self, status, cancel_reason): Validate decline is correct.
- def ensure_document_exists(self, document_pid): Ensure document exists or raise.
- def ensure_patron_... | Implement the Python class `IllValidator` described below.
Class description:
Ill record validator.
Method signatures and docstrings:
- def validate_cancel(self, status, cancel_reason): Validate decline is correct.
- def ensure_document_exists(self, document_pid): Ensure document exists or raise.
- def ensure_patron_... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class IllValidator:
"""Ill record validator."""
def validate_cancel(self, status, cancel_reason):
"""Validate decline is correct."""
<|body_0|>
def ensure_document_exists(self, document_pid):
"""Ensure document exists or raise."""
<|body_1|>
def ensure_pat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IllValidator:
"""Ill record validator."""
def validate_cancel(self, status, cancel_reason):
"""Validate decline is correct."""
if status == 'CANCELLED' and (not cancel_reason):
raise ILLError('You have to provide a cancel reason when cancelling a request')
if cancel_re... | the_stack_v2_python_sparse | invenio_app_ils/ill/api.py | inveniosoftware/invenio-app-ils | train | 64 |
c1e30ed339ffdc2b8b089ffd3d15881610c31a28 | [
"self.m_Cap = capacity\nself.m_Cnt = 0\nself.m_Info = OrderedDict()",
"if key in self.m_Info:\n val = self.m_Info[key]\n del self.m_Info[key]\n self.m_Info[key] = val\n return val\nreturn -1",
"if key in self.m_Info:\n del self.m_Info[key]\n self.m_Info[key] = value\n return\nself.m_Cnt += ... | <|body_start_0|>
self.m_Cap = capacity
self.m_Cnt = 0
self.m_Info = OrderedDict()
<|end_body_0|>
<|body_start_1|>
if key in self.m_Info:
val = self.m_Info[key]
del self.m_Info[key]
self.m_Info[key] = val
return val
return -1
<|end_... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k_train_004127 | 1,172 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_005097 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 818833ca87e8dbf964c0743d8381408964d37c71 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.m_Cap = capacity
self.m_Cnt = 0
self.m_Info = OrderedDict()
def get(self, key):
""":type key: int :rtype: int"""
if key in self.m_Info:
val = self.m_Info[key]
del... | the_stack_v2_python_sparse | 100-199/146-lru-cache.py | lamborghini1993/LeetCode | train | 0 | |
1b8966dab0538a1e9b8ed464c26ff46fe285eed0 | [
"if not intervals:\n return 0\nintervals.sort()\nroom_num = 1\nrooms = [[] for _ in intervals]\nrooms[0].append(intervals[0])\nfor i in range(1, len(intervals)):\n for j in range(len(rooms)):\n if rooms[j] != []:\n last_int = rooms[j][-1]\n if intervals[i][0] >= last_int[1]:\n ... | <|body_start_0|>
if not intervals:
return 0
intervals.sort()
room_num = 1
rooms = [[] for _ in intervals]
rooms[0].append(intervals[0])
for i in range(1, len(intervals)):
for j in range(len(rooms)):
if rooms[j] != []:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minMeetingRooms(self, intervals):
"""Algorithm: go through all the intervals, and see if current interval can be added to a existing room, if not, create a new room for current interval return the final number of rooms created"""
<|body_0|>
def minMeetingRoomsH... | stack_v2_sparse_classes_10k_train_004128 | 2,318 | no_license | [
{
"docstring": "Algorithm: go through all the intervals, and see if current interval can be added to a existing room, if not, create a new room for current interval return the final number of rooms created",
"name": "minMeetingRooms",
"signature": "def minMeetingRooms(self, intervals)"
},
{
"doc... | 2 | stack_v2_sparse_classes_30k_train_006603 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMeetingRooms(self, intervals): Algorithm: go through all the intervals, and see if current interval can be added to a existing room, if not, create a new room for current ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMeetingRooms(self, intervals): Algorithm: go through all the intervals, and see if current interval can be added to a existing room, if not, create a new room for current ... | 7eddbc93a237d1d5cabcdc67806b01ff55ea8562 | <|skeleton|>
class Solution:
def minMeetingRooms(self, intervals):
"""Algorithm: go through all the intervals, and see if current interval can be added to a existing room, if not, create a new room for current interval return the final number of rooms created"""
<|body_0|>
def minMeetingRoomsH... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minMeetingRooms(self, intervals):
"""Algorithm: go through all the intervals, and see if current interval can be added to a existing room, if not, create a new room for current interval return the final number of rooms created"""
if not intervals:
return 0
int... | the_stack_v2_python_sparse | LeetCode Problems/Array/Meeting Rooms II.py | GZHOUW/Algorithm | train | 0 | |
e3cdd6449c6652fe070a5e258973c4cf68ef85e5 | [
"testcases: List[TestCase] = TestCase.query.all()\nres = [{'id': testcase.id, 'name': testcase.name, 'description': testcase.description, 'steps': json.loads(testcase.steps)} for testcase in testcases]\nreturn {'body': res}",
"testcase = TestCase(name=request.json.get('name'), description=request.json.get('descri... | <|body_start_0|>
testcases: List[TestCase] = TestCase.query.all()
res = [{'id': testcase.id, 'name': testcase.name, 'description': testcase.description, 'steps': json.loads(testcase.steps)} for testcase in testcases]
return {'body': res}
<|end_body_0|>
<|body_start_1|>
testcase = TestCa... | TestCaseService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCaseService:
def get(self):
"""测试用例的浏览获取 /testcase.json /testcase.json?id=1"""
<|body_0|>
def post(self):
"""上传用例, 更新用例 /testcase.json {'name': 'xx', 'description': 'xxx', 'steps': []}"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
testcases: L... | stack_v2_sparse_classes_10k_train_004129 | 4,613 | no_license | [
{
"docstring": "测试用例的浏览获取 /testcase.json /testcase.json?id=1",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "上传用例, 更新用例 /testcase.json {'name': 'xx', 'description': 'xxx', 'steps': []}",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006204 | Implement the Python class `TestCaseService` described below.
Class description:
Implement the TestCaseService class.
Method signatures and docstrings:
- def get(self): 测试用例的浏览获取 /testcase.json /testcase.json?id=1
- def post(self): 上传用例, 更新用例 /testcase.json {'name': 'xx', 'description': 'xxx', 'steps': []} | Implement the Python class `TestCaseService` described below.
Class description:
Implement the TestCaseService class.
Method signatures and docstrings:
- def get(self): 测试用例的浏览获取 /testcase.json /testcase.json?id=1
- def post(self): 上传用例, 更新用例 /testcase.json {'name': 'xx', 'description': 'xxx', 'steps': []}
<|skeleto... | bd8bce8160c458bf49970dbf94dadb3c822fdd53 | <|skeleton|>
class TestCaseService:
def get(self):
"""测试用例的浏览获取 /testcase.json /testcase.json?id=1"""
<|body_0|>
def post(self):
"""上传用例, 更新用例 /testcase.json {'name': 'xx', 'description': 'xxx', 'steps': []}"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestCaseService:
def get(self):
"""测试用例的浏览获取 /testcase.json /testcase.json?id=1"""
testcases: List[TestCase] = TestCase.query.all()
res = [{'id': testcase.id, 'name': testcase.name, 'description': testcase.description, 'steps': json.loads(testcase.steps)} for testcase in testcases]
... | the_stack_v2_python_sparse | platform/src/backend.py | baihongliang/HogwartsLG4 | train | 0 | |
0c08651b9bcdffc0b9f45fe8a5f7fd02376d69aa | [
"self._verbose = verbose\nself._print_prefix = print_prefix\nself._lock = lock\nreturn",
"if self._verbose:\n if args or kwargs:\n with self._lock:\n print(self._print_prefix, *args, flush=flush, **kwargs)\nreturn"
] | <|body_start_0|>
self._verbose = verbose
self._print_prefix = print_prefix
self._lock = lock
return
<|end_body_0|>
<|body_start_1|>
if self._verbose:
if args or kwargs:
with self._lock:
print(self._print_prefix, *args, flush=flush,... | LockPrinter | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LockPrinter:
def __init__(self, verbose: bool, print_prefix: str, lock: ParallelPool.LockType) -> None:
"""Construct a `LockPrinter` Parameters ---------- verbose : whether to print at all print_prefix : the prefix string to prepend to all print output lock : the lock to acquire before p... | stack_v2_sparse_classes_10k_train_004130 | 6,591 | permissive | [
{
"docstring": "Construct a `LockPrinter` Parameters ---------- verbose : whether to print at all print_prefix : the prefix string to prepend to all print output lock : the lock to acquire before printing",
"name": "__init__",
"signature": "def __init__(self, verbose: bool, print_prefix: str, lock: Para... | 2 | stack_v2_sparse_classes_30k_train_000308 | Implement the Python class `LockPrinter` described below.
Class description:
Implement the LockPrinter class.
Method signatures and docstrings:
- def __init__(self, verbose: bool, print_prefix: str, lock: ParallelPool.LockType) -> None: Construct a `LockPrinter` Parameters ---------- verbose : whether to print at all... | Implement the Python class `LockPrinter` described below.
Class description:
Implement the LockPrinter class.
Method signatures and docstrings:
- def __init__(self, verbose: bool, print_prefix: str, lock: ParallelPool.LockType) -> None: Construct a `LockPrinter` Parameters ---------- verbose : whether to print at all... | 9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9 | <|skeleton|>
class LockPrinter:
def __init__(self, verbose: bool, print_prefix: str, lock: ParallelPool.LockType) -> None:
"""Construct a `LockPrinter` Parameters ---------- verbose : whether to print at all print_prefix : the prefix string to prepend to all print output lock : the lock to acquire before p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LockPrinter:
def __init__(self, verbose: bool, print_prefix: str, lock: ParallelPool.LockType) -> None:
"""Construct a `LockPrinter` Parameters ---------- verbose : whether to print at all print_prefix : the prefix string to prepend to all print output lock : the lock to acquire before printing"""
... | the_stack_v2_python_sparse | lib/petsc/bin/maint/petsclinter/petsclinter/queue_main.py | petsc/petsc | train | 341 | |
b698ac2e1cdb958c5f3ad6fe55f31909450611e5 | [
"http_method = str(request_raw['method']).lower()\ntemp_url = str(request_raw['url']).strip()\ntemp_headers = header_to_lowercase(json.loads(request_raw['headers']))\nif http_method == HttpMethod.GET:\n parameters = self.get_parser_class(request_raw).get_parameter(url=temp_url, data=None, http_method=HttpMethod.... | <|body_start_0|>
http_method = str(request_raw['method']).lower()
temp_url = str(request_raw['url']).strip()
temp_headers = header_to_lowercase(json.loads(request_raw['headers']))
if http_method == HttpMethod.GET:
parameters = self.get_parser_class(request_raw).get_parameter(... | Checker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Checker:
def check_logic(self, request_raw):
"""检测逻辑,jsonp 水坑攻击只会存在于GET请求中,检测方式,看能否自定义设置CALLBACK :param request_raw: :return:"""
<|body_0|>
def init_plugin_info(self):
"""初插件始化信息 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
http_method =... | stack_v2_sparse_classes_10k_train_004131 | 3,308 | permissive | [
{
"docstring": "检测逻辑,jsonp 水坑攻击只会存在于GET请求中,检测方式,看能否自定义设置CALLBACK :param request_raw: :return:",
"name": "check_logic",
"signature": "def check_logic(self, request_raw)"
},
{
"docstring": "初插件始化信息 :return:",
"name": "init_plugin_info",
"signature": "def init_plugin_info(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007171 | Implement the Python class `Checker` described below.
Class description:
Implement the Checker class.
Method signatures and docstrings:
- def check_logic(self, request_raw): 检测逻辑,jsonp 水坑攻击只会存在于GET请求中,检测方式,看能否自定义设置CALLBACK :param request_raw: :return:
- def init_plugin_info(self): 初插件始化信息 :return: | Implement the Python class `Checker` described below.
Class description:
Implement the Checker class.
Method signatures and docstrings:
- def check_logic(self, request_raw): 检测逻辑,jsonp 水坑攻击只会存在于GET请求中,检测方式,看能否自定义设置CALLBACK :param request_raw: :return:
- def init_plugin_info(self): 初插件始化信息 :return:
<|skeleton|>
class... | 4ee5cca8dc5fc5d7e631e935517bd0f493c30a37 | <|skeleton|>
class Checker:
def check_logic(self, request_raw):
"""检测逻辑,jsonp 水坑攻击只会存在于GET请求中,检测方式,看能否自定义设置CALLBACK :param request_raw: :return:"""
<|body_0|>
def init_plugin_info(self):
"""初插件始化信息 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Checker:
def check_logic(self, request_raw):
"""检测逻辑,jsonp 水坑攻击只会存在于GET请求中,检测方式,看能否自定义设置CALLBACK :param request_raw: :return:"""
http_method = str(request_raw['method']).lower()
temp_url = str(request_raw['url']).strip()
temp_headers = header_to_lowercase(json.loads(request_raw... | the_stack_v2_python_sparse | HunterAdminApi/plugins/owasp/jsonp_hijacking.py | a1kaid/hunter | train | 0 | |
3a161dd6dbe23017b76349bbd49f1f46af02cbac | [
"r = 0\nhight = 100\nfor i in range(num):\n r += hight\n hight /= 2\n r += hight\nreturn (hight, r)",
"for per in s_father:\n if per == s_child:\n return True\nreturn False",
"s_len = len(s_child)\nfor index_ in range(len(s_father) - s_len + 1):\n per = s_father[index_:index_ + s_len]\n ... | <|body_start_0|>
r = 0
hight = 100
for i in range(num):
r += hight
hight /= 2
r += hight
return (hight, r)
<|end_body_0|>
<|body_start_1|>
for per in s_father:
if per == s_child:
return True
return False
<|e... | Pratice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pratice:
def func_01(self, num, is_count=None):
"""第一题: 给一个下落次数, 1.求出此时小球离地面的距离 2.小球总共走的路径 :param num: :param is_count: :return:"""
<|body_0|>
def func_02(self, s_father, s_child):
"""第二题: 判断一个单个字符是否在一个字符串里面 s_father = 'hello world' s_child = 'd' 注:不能用in"""
<... | stack_v2_sparse_classes_10k_train_004132 | 3,368 | no_license | [
{
"docstring": "第一题: 给一个下落次数, 1.求出此时小球离地面的距离 2.小球总共走的路径 :param num: :param is_count: :return:",
"name": "func_01",
"signature": "def func_01(self, num, is_count=None)"
},
{
"docstring": "第二题: 判断一个单个字符是否在一个字符串里面 s_father = 'hello world' s_child = 'd' 注:不能用in",
"name": "func_02",
"signatur... | 3 | null | Implement the Python class `Pratice` described below.
Class description:
Implement the Pratice class.
Method signatures and docstrings:
- def func_01(self, num, is_count=None): 第一题: 给一个下落次数, 1.求出此时小球离地面的距离 2.小球总共走的路径 :param num: :param is_count: :return:
- def func_02(self, s_father, s_child): 第二题: 判断一个单个字符是否在一个字符串里面... | Implement the Python class `Pratice` described below.
Class description:
Implement the Pratice class.
Method signatures and docstrings:
- def func_01(self, num, is_count=None): 第一题: 给一个下落次数, 1.求出此时小球离地面的距离 2.小球总共走的路径 :param num: :param is_count: :return:
- def func_02(self, s_father, s_child): 第二题: 判断一个单个字符是否在一个字符串里面... | 167c86be6241c6c148eb586b5dd19275246372a7 | <|skeleton|>
class Pratice:
def func_01(self, num, is_count=None):
"""第一题: 给一个下落次数, 1.求出此时小球离地面的距离 2.小球总共走的路径 :param num: :param is_count: :return:"""
<|body_0|>
def func_02(self, s_father, s_child):
"""第二题: 判断一个单个字符是否在一个字符串里面 s_father = 'hello world' s_child = 'd' 注:不能用in"""
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Pratice:
def func_01(self, num, is_count=None):
"""第一题: 给一个下落次数, 1.求出此时小球离地面的距离 2.小球总共走的路径 :param num: :param is_count: :return:"""
r = 0
hight = 100
for i in range(num):
r += hight
hight /= 2
r += hight
return (hight, r)
def fun... | the_stack_v2_python_sparse | py3-study/面向对象课上代码/1901/9-10/练习题02_答案.py | liuluyang/mk | train | 0 | |
7a53427c2b19e39e219c77b79603212d8ac9029f | [
"self.R = R\nself.B = B\nself.N_leaves = N_leaves\nself.alignment = alignment",
"X = [math.exp(x) for x in X_logs]\nB_subs = {}\nfor v_parent, v_child in self.R:\n edge = frozenset([v_parent, v_child])\n r = X[v_child]\n t = self.B[edge]\n B_subs[edge] = r * t\nnewick_string = FtreeIO.RBN_to_newick(se... | <|body_start_0|>
self.R = R
self.B = B
self.N_leaves = N_leaves
self.alignment = alignment
<|end_body_0|>
<|body_start_1|>
X = [math.exp(x) for x in X_logs]
B_subs = {}
for v_parent, v_child in self.R:
edge = frozenset([v_parent, v_child])
... | This is for maximum likelihood search of lineage rates. | Opt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Opt:
"""This is for maximum likelihood search of lineage rates."""
def __init__(self, R, B, N_leaves, alignment):
"""The vertices should be consecutive integers starting at zero. The largest vertex should be the root."""
<|body_0|>
def __call__(self, X_logs):
"""... | stack_v2_sparse_classes_10k_train_004133 | 18,637 | no_license | [
{
"docstring": "The vertices should be consecutive integers starting at zero. The largest vertex should be the root.",
"name": "__init__",
"signature": "def __init__(self, R, B, N_leaves, alignment)"
},
{
"docstring": "The vth entry of X corresponds to the log rate of the branch above v. Return ... | 2 | stack_v2_sparse_classes_30k_test_000357 | Implement the Python class `Opt` described below.
Class description:
This is for maximum likelihood search of lineage rates.
Method signatures and docstrings:
- def __init__(self, R, B, N_leaves, alignment): The vertices should be consecutive integers starting at zero. The largest vertex should be the root.
- def __c... | Implement the Python class `Opt` described below.
Class description:
This is for maximum likelihood search of lineage rates.
Method signatures and docstrings:
- def __init__(self, R, B, N_leaves, alignment): The vertices should be consecutive integers starting at zero. The largest vertex should be the root.
- def __c... | 91c6f8331f18c914eb3dfc51bc166915998c5081 | <|skeleton|>
class Opt:
"""This is for maximum likelihood search of lineage rates."""
def __init__(self, R, B, N_leaves, alignment):
"""The vertices should be consecutive integers starting at zero. The largest vertex should be the root."""
<|body_0|>
def __call__(self, X_logs):
"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Opt:
"""This is for maximum likelihood search of lineage rates."""
def __init__(self, R, B, N_leaves, alignment):
"""The vertices should be consecutive integers starting at zero. The largest vertex should be the root."""
self.R = R
self.B = B
self.N_leaves = N_leaves
... | the_stack_v2_python_sparse | 20120403a.py | argriffing/xgcode | train | 1 |
5ed40b0c2124d4659b163f7515f7ac00128620dc | [
"self.broadcast_threshold = broadcast_threshold\nself.multicast_threshold = multicast_threshold\nself.unknown_unicast_threshold = unknown_unicast_threshold",
"if dictionary is None:\n return None\nbroadcast_threshold = dictionary.get('broadcastThreshold')\nmulticast_threshold = dictionary.get('multicastThresho... | <|body_start_0|>
self.broadcast_threshold = broadcast_threshold
self.multicast_threshold = multicast_threshold
self.unknown_unicast_threshold = unknown_unicast_threshold
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
broadcast_threshold = dictiona... | Implementation of the 'updateNetworkSwitchSettingsStormControl' model. TODO: type model description here. Attributes: broadcast_threshold (int): Percentage (1 to 99) of total available port bandwidth for broadcast traffic type. Default value 100 percent rate is to clear the configuration. multicast_threshold (int): Per... | UpdateNetworkSwitchSettingsStormControlModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateNetworkSwitchSettingsStormControlModel:
"""Implementation of the 'updateNetworkSwitchSettingsStormControl' model. TODO: type model description here. Attributes: broadcast_threshold (int): Percentage (1 to 99) of total available port bandwidth for broadcast traffic type. Default value 100 pe... | stack_v2_sparse_classes_10k_train_004134 | 2,778 | permissive | [
{
"docstring": "Constructor for the UpdateNetworkSwitchSettingsStormControlModel class",
"name": "__init__",
"signature": "def __init__(self, broadcast_threshold=None, multicast_threshold=None, unknown_unicast_threshold=None)"
},
{
"docstring": "Creates an instance of this model from a dictionar... | 2 | stack_v2_sparse_classes_30k_train_003689 | Implement the Python class `UpdateNetworkSwitchSettingsStormControlModel` described below.
Class description:
Implementation of the 'updateNetworkSwitchSettingsStormControl' model. TODO: type model description here. Attributes: broadcast_threshold (int): Percentage (1 to 99) of total available port bandwidth for broad... | Implement the Python class `UpdateNetworkSwitchSettingsStormControlModel` described below.
Class description:
Implementation of the 'updateNetworkSwitchSettingsStormControl' model. TODO: type model description here. Attributes: broadcast_threshold (int): Percentage (1 to 99) of total available port bandwidth for broad... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class UpdateNetworkSwitchSettingsStormControlModel:
"""Implementation of the 'updateNetworkSwitchSettingsStormControl' model. TODO: type model description here. Attributes: broadcast_threshold (int): Percentage (1 to 99) of total available port bandwidth for broadcast traffic type. Default value 100 pe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UpdateNetworkSwitchSettingsStormControlModel:
"""Implementation of the 'updateNetworkSwitchSettingsStormControl' model. TODO: type model description here. Attributes: broadcast_threshold (int): Percentage (1 to 99) of total available port bandwidth for broadcast traffic type. Default value 100 percent rate is... | the_stack_v2_python_sparse | meraki/models/update_network_switch_settings_storm_control_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
b625beed16b51ac3534311b236bf985db6b7aa7f | [
"if data and data.content_type not in settings.IMAGE_ALLOWED_MIME_TYPES:\n raise forms.ValidationError(self.error_messages['invalid_image'])\nif hasattr(data, 'name') and mimetypes.guess_type(data.name)[0] not in settings.IMAGE_ALLOWED_MIME_TYPES:\n raise forms.ValidationError(self.error_messages['invalid_ima... | <|body_start_0|>
if data and data.content_type not in settings.IMAGE_ALLOWED_MIME_TYPES:
raise forms.ValidationError(self.error_messages['invalid_image'])
if hasattr(data, 'name') and mimetypes.guess_type(data.name)[0] not in settings.IMAGE_ALLOWED_MIME_TYPES:
raise forms.Validat... | Actual FormField that does the validation of the mime-types. | RestrictedImageFormField | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestrictedImageFormField:
"""Actual FormField that does the validation of the mime-types."""
def to_python(self, data):
"""Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the engine supports). If the item cannot be converted t... | stack_v2_sparse_classes_10k_train_004135 | 9,634 | permissive | [
{
"docstring": "Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the engine supports). If the item cannot be converted to an image, check if the file is and svg",
"name": "to_python",
"signature": "def to_python(self, data)"
},
{
"docstrin... | 2 | null | Implement the Python class `RestrictedImageFormField` described below.
Class description:
Actual FormField that does the validation of the mime-types.
Method signatures and docstrings:
- def to_python(self, data): Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whateve... | Implement the Python class `RestrictedImageFormField` described below.
Class description:
Actual FormField that does the validation of the mime-types.
Method signatures and docstrings:
- def to_python(self, data): Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whateve... | 2b5f3562584137c8c9f5392265db1ab8ee8acf75 | <|skeleton|>
class RestrictedImageFormField:
"""Actual FormField that does the validation of the mime-types."""
def to_python(self, data):
"""Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the engine supports). If the item cannot be converted t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RestrictedImageFormField:
"""Actual FormField that does the validation of the mime-types."""
def to_python(self, data):
"""Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the engine supports). If the item cannot be converted to an image, c... | the_stack_v2_python_sparse | bluebottle/utils/fields.py | onepercentclub/bluebottle | train | 15 |
5ff9cfe8ed6bb7b83e4e7679ec6a84428f3ccd64 | [
"self.assertEqual(source.add(10, 5), 15)\nself.assertEqual(source.add(-1, 1), 0)\nself.assertEqual(source.add(-1, -1), -2)",
"self.assertEqual(source.sub(10, 5), 5)\nself.assertEqual(source.sub(-1, 1), -2)\nself.assertEqual(source.sub(-1, -1), 0)",
"self.assertEqual(source.mul(10, 5), 50)\nself.assertEqual(sour... | <|body_start_0|>
self.assertEqual(source.add(10, 5), 15)
self.assertEqual(source.add(-1, 1), 0)
self.assertEqual(source.add(-1, -1), -2)
<|end_body_0|>
<|body_start_1|>
self.assertEqual(source.sub(10, 5), 5)
self.assertEqual(source.sub(-1, 1), -2)
self.assertEqual(source... | Test class to make the methods for testing the original methods All the test methods inside test class should start form the name 'test_' or else the method will be skipped from unit testing. This is by convention. | TestSource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSource:
"""Test class to make the methods for testing the original methods All the test methods inside test class should start form the name 'test_' or else the method will be skipped from unit testing. This is by convention."""
def test_add(self):
"""test method for testing add ... | stack_v2_sparse_classes_10k_train_004136 | 1,693 | no_license | [
{
"docstring": "test method for testing add function",
"name": "test_add",
"signature": "def test_add(self)"
},
{
"docstring": "test method for testing sub function",
"name": "test_sub",
"signature": "def test_sub(self)"
},
{
"docstring": "test method for testing mul function",
... | 4 | stack_v2_sparse_classes_30k_train_001172 | Implement the Python class `TestSource` described below.
Class description:
Test class to make the methods for testing the original methods All the test methods inside test class should start form the name 'test_' or else the method will be skipped from unit testing. This is by convention.
Method signatures and docst... | Implement the Python class `TestSource` described below.
Class description:
Test class to make the methods for testing the original methods All the test methods inside test class should start form the name 'test_' or else the method will be skipped from unit testing. This is by convention.
Method signatures and docst... | 52249822e2239113506a65f51a20caff37d8fb14 | <|skeleton|>
class TestSource:
"""Test class to make the methods for testing the original methods All the test methods inside test class should start form the name 'test_' or else the method will be skipped from unit testing. This is by convention."""
def test_add(self):
"""test method for testing add ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestSource:
"""Test class to make the methods for testing the original methods All the test methods inside test class should start form the name 'test_' or else the method will be skipped from unit testing. This is by convention."""
def test_add(self):
"""test method for testing add function"""
... | the_stack_v2_python_sparse | Concepts/18_unit_testing/Test1/test_source.py | Silver-Taurus/Python_at_FLT | train | 1 |
dc0f266dabf1b03b53175019a50a547c21b45be5 | [
"if current_user in self.event.participants:\n return jsonify({'status': 200, 'message': 'You are registered as a participant'})\nelif current_user in self.event.guests:\n return jsonify({'status': 200, 'message': 'You are registered as a guest'})\nelse:\n return jsonify({'status': 200, 'message': 'You are... | <|body_start_0|>
if current_user in self.event.participants:
return jsonify({'status': 200, 'message': 'You are registered as a participant'})
elif current_user in self.event.guests:
return jsonify({'status': 200, 'message': 'You are registered as a guest'})
else:
... | Resource for registering and unregistering as a participant fo event | UserAsParticipant | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAsParticipant:
"""Resource for registering and unregistering as a participant fo event"""
def get(self, event_id: int) -> Response:
"""Method for checking registration as a participant Parameters ---------- event_id : int Event id Returns ------- Response Response message with st... | stack_v2_sparse_classes_10k_train_004137 | 7,636 | no_license | [
{
"docstring": "Method for checking registration as a participant Parameters ---------- event_id : int Event id Returns ------- Response Response message with status code",
"name": "get",
"signature": "def get(self, event_id: int) -> Response"
},
{
"docstring": "Method for registering as a parti... | 3 | stack_v2_sparse_classes_30k_train_001688 | Implement the Python class `UserAsParticipant` described below.
Class description:
Resource for registering and unregistering as a participant fo event
Method signatures and docstrings:
- def get(self, event_id: int) -> Response: Method for checking registration as a participant Parameters ---------- event_id : int E... | Implement the Python class `UserAsParticipant` described below.
Class description:
Resource for registering and unregistering as a participant fo event
Method signatures and docstrings:
- def get(self, event_id: int) -> Response: Method for checking registration as a participant Parameters ---------- event_id : int E... | 51e4d69f88c120cfc587fd007f21528a7bd661a0 | <|skeleton|>
class UserAsParticipant:
"""Resource for registering and unregistering as a participant fo event"""
def get(self, event_id: int) -> Response:
"""Method for checking registration as a participant Parameters ---------- event_id : int Event id Returns ------- Response Response message with st... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserAsParticipant:
"""Resource for registering and unregistering as a participant fo event"""
def get(self, event_id: int) -> Response:
"""Method for checking registration as a participant Parameters ---------- event_id : int Event id Returns ------- Response Response message with status code"""
... | the_stack_v2_python_sparse | flask_app/resources/participant.py | Kyrylo-Kotelevets/Flask_Events | train | 0 |
3341f212189aefb222f15433ae144571fa6b52c7 | [
"if not root:\n return None\nhead, tail = self.get_linked_list(root)\nhead.left = tail\ntail.right = head\nreturn head",
"if not node.left and (not node.right):\n return (node, node)\nlhead, ltail = self.get_linked_list(node.left) if node.left else (node, None)\nrhead, rtail = self.get_linked_list(node.righ... | <|body_start_0|>
if not root:
return None
head, tail = self.get_linked_list(root)
head.left = tail
tail.right = head
return head
<|end_body_0|>
<|body_start_1|>
if not node.left and (not node.right):
return (node, node)
lhead, ltail = self... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node"""
<|body_0|>
def get_linked_list(self, node):
"""Helper function to turn subtree starting at node into linked list. Returns (head, tail) of the linked list."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_10k_train_004138 | 2,611 | no_license | [
{
"docstring": ":type root: Node :rtype: Node",
"name": "treeToDoublyList",
"signature": "def treeToDoublyList(self, root)"
},
{
"docstring": "Helper function to turn subtree starting at node into linked list. Returns (head, tail) of the linked list.",
"name": "get_linked_list",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_001039 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def treeToDoublyList(self, root): :type root: Node :rtype: Node
- def get_linked_list(self, node): Helper function to turn subtree starting at node into linked list. Returns (hea... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def treeToDoublyList(self, root): :type root: Node :rtype: Node
- def get_linked_list(self, node): Helper function to turn subtree starting at node into linked list. Returns (hea... | eb3fc22450b362703c3322d9e975d191eb324ffc | <|skeleton|>
class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node"""
<|body_0|>
def get_linked_list(self, node):
"""Helper function to turn subtree starting at node into linked list. Returns (head, tail) of the linked list."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node"""
if not root:
return None
head, tail = self.get_linked_list(root)
head.left = tail
tail.right = head
return head
def get_linked_list(self, node):
"""Helper fu... | the_stack_v2_python_sparse | 2-14/426-Convert-Binary-Search-Tree-to-Sorted-DLL.py | whalejasmine/leetcode_python_summary | train | 0 | |
460b7d194c1924327e0a5f561a064d43189c23dc | [
"with conn.cursor() as cur:\n cur.execute(\"\\nselect count(*) as ct\\n from pg_class\\n where relnamespace = 'acct10001'::regnamespace\\n and relname = 'presto_delete_wrapper_log';\\n\")\n self.assertTrue(bool(cur.fetchone()[0]))\n cur.execute(\"\\nselect count(*) as ct\\n from pg_trigger\\n where tgn... | <|body_start_0|>
with conn.cursor() as cur:
cur.execute("\nselect count(*) as ct\n from pg_class\n where relnamespace = 'acct10001'::regnamespace\n and relname = 'presto_delete_wrapper_log';\n")
self.assertTrue(bool(cur.fetchone()[0]))
cur.execute("\nselect count(*) as ct\... | TestPrestoDeleteLogTrigger | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPrestoDeleteLogTrigger:
def test_presto_delete_log_table_exists(self):
"""Ensure that the table and trigger exists"""
<|body_0|>
def test_presto_delete_log_func_exists(self):
"""Ensure that the presto delete wrapper trigger function exists"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_004139 | 2,799 | permissive | [
{
"docstring": "Ensure that the table and trigger exists",
"name": "test_presto_delete_log_table_exists",
"signature": "def test_presto_delete_log_table_exists(self)"
},
{
"docstring": "Ensure that the presto delete wrapper trigger function exists",
"name": "test_presto_delete_log_func_exist... | 3 | null | Implement the Python class `TestPrestoDeleteLogTrigger` described below.
Class description:
Implement the TestPrestoDeleteLogTrigger class.
Method signatures and docstrings:
- def test_presto_delete_log_table_exists(self): Ensure that the table and trigger exists
- def test_presto_delete_log_func_exists(self): Ensure... | Implement the Python class `TestPrestoDeleteLogTrigger` described below.
Class description:
Implement the TestPrestoDeleteLogTrigger class.
Method signatures and docstrings:
- def test_presto_delete_log_table_exists(self): Ensure that the table and trigger exists
- def test_presto_delete_log_func_exists(self): Ensure... | 2979f03fbdd1c20c3abc365a963a1282b426f321 | <|skeleton|>
class TestPrestoDeleteLogTrigger:
def test_presto_delete_log_table_exists(self):
"""Ensure that the table and trigger exists"""
<|body_0|>
def test_presto_delete_log_func_exists(self):
"""Ensure that the presto delete wrapper trigger function exists"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestPrestoDeleteLogTrigger:
def test_presto_delete_log_table_exists(self):
"""Ensure that the table and trigger exists"""
with conn.cursor() as cur:
cur.execute("\nselect count(*) as ct\n from pg_class\n where relnamespace = 'acct10001'::regnamespace\n and relname = 'presto_dele... | the_stack_v2_python_sparse | koku/koku/test_presto_delete_wrapper_trigger.py | luisfdez/koku | train | 0 | |
f3f5c3430f5c84f13b6654527d1004225d139f50 | [
"self.Wz = np.random.normal(size=(h + i, h))\nself.Wr = np.random.normal(size=(h + i, h))\nself.Wh = np.random.normal(size=(h + i, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bz = np.zeros((1, h))\nself.br = np.zeros((1, h))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"x_max = np.max(x, axis=... | <|body_start_0|>
self.Wz = np.random.normal(size=(h + i, h))
self.Wr = np.random.normal(size=(h + i, h))
self.Wh = np.random.normal(size=(h + i, h))
self.Wy = np.random.normal(size=(h, o))
self.bz = np.zeros((1, h))
self.br = np.zeros((1, h))
self.bh = np.zeros((1... | Class GRUCell that represents a gated recurrent unit | GRUCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRUCell:
"""Class GRUCell that represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dimensionality of the outputs Public instance attributes Wz,... | stack_v2_sparse_classes_10k_train_004140 | 2,573 | no_license | [
{
"docstring": "class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dimensionality of the outputs Public instance attributes Wz, Wr, Wh, Wy, bz, br, bh, by that represent the weights and biases of the cell - Wzand bz are for the update gate... | 3 | stack_v2_sparse_classes_30k_train_003409 | Implement the Python class `GRUCell` described below.
Class description:
Class GRUCell that represents a gated recurrent unit
Method signatures and docstrings:
- def __init__(self, i, h, o): class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dim... | Implement the Python class `GRUCell` described below.
Class description:
Class GRUCell that represents a gated recurrent unit
Method signatures and docstrings:
- def __init__(self, i, h, o): class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dim... | fc2cec306961f7ca2448965ddd3a2f656bbe10c7 | <|skeleton|>
class GRUCell:
"""Class GRUCell that represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dimensionality of the outputs Public instance attributes Wz,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GRUCell:
"""Class GRUCell that represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dimensionality of the outputs Public instance attributes Wz, Wr, Wh, Wy, ... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/2-gru_cell.py | dalexach/holbertonschool-machine_learning | train | 2 |
0ee0f5b294282010a67a53b83da14dc4523cee25 | [
"self.x2Num = collections.defaultdict(int)\nself.numList = collections.defaultdict(list)\nself.max = 0",
"self.x2Num[x] += 1\nkey = self.x2Num[x]\nself.numList[key].append(x)\nself.max = max(self.max, key)",
"a = self.numList[self.max].pop()\nself.x2Num[a] -= 1\nif len(self.numList[self.max]) <= 0:\n self.ma... | <|body_start_0|>
self.x2Num = collections.defaultdict(int)
self.numList = collections.defaultdict(list)
self.max = 0
<|end_body_0|>
<|body_start_1|>
self.x2Num[x] += 1
key = self.x2Num[x]
self.numList[key].append(x)
self.max = max(self.max, key)
<|end_body_1|>
<... | FreqStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FreqStack:
def __init__(self):
"""292 ms"""
<|body_0|>
def push(self, x):
""":type x: int :rtype: void"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.x2Num = collections.defaultd... | stack_v2_sparse_classes_10k_train_004141 | 2,719 | no_license | [
{
"docstring": "292 ms",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type x: int :rtype: void",
"name": "push",
"signature": "def push(self, x)"
},
{
"docstring": ":rtype: int",
"name": "pop",
"signature": "def pop(self)"
}
] | 3 | null | Implement the Python class `FreqStack` described below.
Class description:
Implement the FreqStack class.
Method signatures and docstrings:
- def __init__(self): 292 ms
- def push(self, x): :type x: int :rtype: void
- def pop(self): :rtype: int | Implement the Python class `FreqStack` described below.
Class description:
Implement the FreqStack class.
Method signatures and docstrings:
- def __init__(self): 292 ms
- def push(self, x): :type x: int :rtype: void
- def pop(self): :rtype: int
<|skeleton|>
class FreqStack:
def __init__(self):
"""292 ms... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class FreqStack:
def __init__(self):
"""292 ms"""
<|body_0|>
def push(self, x):
""":type x: int :rtype: void"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FreqStack:
def __init__(self):
"""292 ms"""
self.x2Num = collections.defaultdict(int)
self.numList = collections.defaultdict(list)
self.max = 0
def push(self, x):
""":type x: int :rtype: void"""
self.x2Num[x] += 1
key = self.x2Num[x]
self.nu... | the_stack_v2_python_sparse | MaximumFrequencyStack_HARD_895.py | 953250587/leetcode-python | train | 2 | |
f0f250cce5905d08e194e5dbb07c49a4b3b0a561 | [
"email_parser = BytesParser(policy=policy.default)\nparsed_email = email_parser.parsebytes(response.body)\ncontent = ''\nfor part in parsed_email.iter_parts():\n if part.get_content_maintype() == 'multipart':\n for sub_part in part.get_payload():\n if sub_part.get_content_maintype() == 'text':\... | <|body_start_0|>
email_parser = BytesParser(policy=policy.default)
parsed_email = email_parser.parsebytes(response.body)
content = ''
for part in parsed_email.iter_parts():
if part.get_content_maintype() == 'multipart':
for sub_part in part.get_payload():
... | AkrAirportAuthoritySpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AkrAirportAuthoritySpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_start(self, date_str, year_str):
"""Parse start datetime ... | stack_v2_sparse_classes_10k_train_004142 | 2,357 | permissive | [
{
"docstring": "`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Parse start datetime as a naive datetime object.",
"name": "_parse_st... | 2 | stack_v2_sparse_classes_30k_train_000730 | Implement the Python class `AkrAirportAuthoritySpider` described below.
Class description:
Implement the AkrAirportAuthoritySpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scrap... | Implement the Python class `AkrAirportAuthoritySpider` described below.
Class description:
Implement the AkrAirportAuthoritySpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scrap... | 33f16492aea888a29d6a5570fd91ea1817b70bb3 | <|skeleton|>
class AkrAirportAuthoritySpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_start(self, date_str, year_str):
"""Parse start datetime ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AkrAirportAuthoritySpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
email_parser = BytesParser(policy=policy.default)
parsed_email = email_parser.parsebytes(response.... | the_stack_v2_python_sparse | city_scrapers/spiders/akr_airport_authority.py | City-Bureau/city-scrapers-akr | train | 0 | |
e2f04afe564524ab8906255f7cd3ff943862de48 | [
"if not root:\n return root\nleftmost = root\nwhile leftmost.left:\n head = leftmost\n while head:\n head.left.next = head.right\n if head.next:\n head.right.next = head.next.left\n head = head.next\n leftmost = leftmost.left\nif not root:\n return root\nqueue = collec... | <|body_start_0|>
if not root:
return root
leftmost = root
while leftmost.left:
head = leftmost
while head:
head.left.next = head.right
if head.next:
head.right.next = head.next.left
head = hea... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def connect(self, root: 'Node') -> 'Node':
"""117. 填充每个节点的下一个右侧节点指针 给定一个(完美)二叉树 struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。 如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 初始状态下,所有 next 指针都被设置为 NULL。"""
<|body_0|>
def lowestCommon... | stack_v2_sparse_classes_10k_train_004143 | 4,318 | no_license | [
{
"docstring": "117. 填充每个节点的下一个右侧节点指针 给定一个(完美)二叉树 struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。 如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 初始状态下,所有 next 指针都被设置为 NULL。",
"name": "connect",
"signature": "def connect(self, root: 'Node') -> 'Node'"
},
{
"docstri... | 5 | stack_v2_sparse_classes_30k_train_001469 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root: 'Node') -> 'Node': 117. 填充每个节点的下一个右侧节点指针 给定一个(完美)二叉树 struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。 如果找不到下一... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root: 'Node') -> 'Node': 117. 填充每个节点的下一个右侧节点指针 给定一个(完美)二叉树 struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。 如果找不到下一... | 330330ef6bc42eeb17f4dea53c30d230506b4e8f | <|skeleton|>
class Solution:
def connect(self, root: 'Node') -> 'Node':
"""117. 填充每个节点的下一个右侧节点指针 给定一个(完美)二叉树 struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。 如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 初始状态下,所有 next 指针都被设置为 NULL。"""
<|body_0|>
def lowestCommon... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def connect(self, root: 'Node') -> 'Node':
"""117. 填充每个节点的下一个右侧节点指针 给定一个(完美)二叉树 struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。 如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 初始状态下,所有 next 指针都被设置为 NULL。"""
if not root:
return root
l... | the_stack_v2_python_sparse | Code/leetcode_everyday/0305.py | NiceToMeeetU/ToGetReady | train | 0 | |
a7a1744a7049662192e1f54b0a073f663430e802 | [
"offer = self.offer or self.price or self.cost\nprice = self.price or self.cost\nif not offer or not price:\n return None\nreturn '%1.2f%%' % float((offer - price) * Decimal(-100.0) / price)",
"cls.objects.all().delete()\n\ndef int_(v):\n try:\n return int(v)\n except Exception:\n return No... | <|body_start_0|>
offer = self.offer or self.price or self.cost
price = self.price or self.cost
if not offer or not price:
return None
return '%1.2f%%' % float((offer - price) * Decimal(-100.0) / price)
<|end_body_0|>
<|body_start_1|>
cls.objects.all().delete()
... | Un repuesto y su informacion asociada. Por ahora solamente ponemos los datos, sin indexar ni nada. | Replacement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Replacement:
"""Un repuesto y su informacion asociada. Por ahora solamente ponemos los datos, sin indexar ni nada."""
def discount(self):
"""Estima cual es el descuento (entre 0 y 99.99... - si es negativo es un "sobrecuento" :p)"""
<|body_0|>
def load_xls(cls, xls_file)... | stack_v2_sparse_classes_10k_train_004144 | 4,826 | no_license | [
{
"docstring": "Estima cual es el descuento (entre 0 y 99.99... - si es negativo es un \"sobrecuento\" :p)",
"name": "discount",
"signature": "def discount(self)"
},
{
"docstring": "Limpia y carga todo desde un xml.",
"name": "load_xls",
"signature": "def load_xls(cls, xls_file)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005613 | Implement the Python class `Replacement` described below.
Class description:
Un repuesto y su informacion asociada. Por ahora solamente ponemos los datos, sin indexar ni nada.
Method signatures and docstrings:
- def discount(self): Estima cual es el descuento (entre 0 y 99.99... - si es negativo es un "sobrecuento" :... | Implement the Python class `Replacement` described below.
Class description:
Un repuesto y su informacion asociada. Por ahora solamente ponemos los datos, sin indexar ni nada.
Method signatures and docstrings:
- def discount(self): Estima cual es el descuento (entre 0 y 99.99... - si es negativo es un "sobrecuento" :... | 1c38605197f41770df1e7b53efe14ff56bb0d5f2 | <|skeleton|>
class Replacement:
"""Un repuesto y su informacion asociada. Por ahora solamente ponemos los datos, sin indexar ni nada."""
def discount(self):
"""Estima cual es el descuento (entre 0 y 99.99... - si es negativo es un "sobrecuento" :p)"""
<|body_0|>
def load_xls(cls, xls_file)... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Replacement:
"""Un repuesto y su informacion asociada. Por ahora solamente ponemos los datos, sin indexar ni nada."""
def discount(self):
"""Estima cual es el descuento (entre 0 y 99.99... - si es negativo es un "sobrecuento" :p)"""
offer = self.offer or self.price or self.cost
pr... | the_stack_v2_python_sparse | stock/models.py | luismasuelli/repuestazo | train | 0 |
22421d3003c3fc1ed5bfa4d216d290d17e15fb48 | [
"index_array = []\nrc_arr = []\nfor ind in range(0, len(A)):\n index_array.append(ind)\n rc_arr.append(0)\nself.sort(A, index_array, 0, len(index_array) - 1, rc_arr)\nreturn rc_arr",
"left = ind[p:q + 1]\nright = ind[q + 1:r + 1]\ni = 0\nj = 0\nic = 0\nk = p\nwhile i < len(left) and j < len(right):\n if ... | <|body_start_0|>
index_array = []
rc_arr = []
for ind in range(0, len(A)):
index_array.append(ind)
rc_arr.append(0)
self.sort(A, index_array, 0, len(index_array) - 1, rc_arr)
return rc_arr
<|end_body_0|>
<|body_start_1|>
left = ind[p:q + 1]
... | InversionCount | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InversionCount:
def count(self, A: [int]) -> [int]:
"""Count and return the array containing the count of each element"""
<|body_0|>
def merge(self, A, ind, p, q, r, rc_array):
"""This method does the same work as mergeSort but we will be checking for the inversion a... | stack_v2_sparse_classes_10k_train_004145 | 1,753 | permissive | [
{
"docstring": "Count and return the array containing the count of each element",
"name": "count",
"signature": "def count(self, A: [int]) -> [int]"
},
{
"docstring": "This method does the same work as mergeSort but we will be checking for the inversion and increase the count",
"name": "merg... | 3 | stack_v2_sparse_classes_30k_train_000052 | Implement the Python class `InversionCount` described below.
Class description:
Implement the InversionCount class.
Method signatures and docstrings:
- def count(self, A: [int]) -> [int]: Count and return the array containing the count of each element
- def merge(self, A, ind, p, q, r, rc_array): This method does the... | Implement the Python class `InversionCount` described below.
Class description:
Implement the InversionCount class.
Method signatures and docstrings:
- def count(self, A: [int]) -> [int]: Count and return the array containing the count of each element
- def merge(self, A, ind, p, q, r, rc_array): This method does the... | a30008a7fa8ba15ee241bd7fc5df94cd68c80003 | <|skeleton|>
class InversionCount:
def count(self, A: [int]) -> [int]:
"""Count and return the array containing the count of each element"""
<|body_0|>
def merge(self, A, ind, p, q, r, rc_array):
"""This method does the same work as mergeSort but we will be checking for the inversion a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InversionCount:
def count(self, A: [int]) -> [int]:
"""Count and return the array containing the count of each element"""
index_array = []
rc_arr = []
for ind in range(0, len(A)):
index_array.append(ind)
rc_arr.append(0)
self.sort(A, index_array,... | the_stack_v2_python_sparse | InversionCount.py | vinayakasg18/algorithms | train | 0 | |
b5d10f44ebf814558b526e382590331b3171a39c | [
"camera = RaspberryPiCamera(self.mudpi, config)\nif camera:\n self.add_component(camera)\nreturn True",
"if not isinstance(config, list):\n config = [config]\nfor conf in config:\n if not conf.get('path'):\n raise ConfigError('Camera needs a `path` to save files to.')\nreturn config"
] | <|body_start_0|>
camera = RaspberryPiCamera(self.mudpi, config)
if camera:
self.add_component(camera)
return True
<|end_body_0|>
<|body_start_1|>
if not isinstance(config, list):
config = [config]
for conf in config:
if not conf.get('path'):
... | Interface | [
"BSD-4-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interface:
def load(self, config):
"""Load pi camera component from configs"""
<|body_0|>
def validate(self, config):
"""Validate the camera config"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
camera = RaspberryPiCamera(self.mudpi, config)
... | stack_v2_sparse_classes_10k_train_004146 | 3,236 | permissive | [
{
"docstring": "Load pi camera component from configs",
"name": "load",
"signature": "def load(self, config)"
},
{
"docstring": "Validate the camera config",
"name": "validate",
"signature": "def validate(self, config)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000661 | Implement the Python class `Interface` described below.
Class description:
Implement the Interface class.
Method signatures and docstrings:
- def load(self, config): Load pi camera component from configs
- def validate(self, config): Validate the camera config | Implement the Python class `Interface` described below.
Class description:
Implement the Interface class.
Method signatures and docstrings:
- def load(self, config): Load pi camera component from configs
- def validate(self, config): Validate the camera config
<|skeleton|>
class Interface:
def load(self, config... | fb206b1136f529c7197f1e6b29629ed05630d377 | <|skeleton|>
class Interface:
def load(self, config):
"""Load pi camera component from configs"""
<|body_0|>
def validate(self, config):
"""Validate the camera config"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Interface:
def load(self, config):
"""Load pi camera component from configs"""
camera = RaspberryPiCamera(self.mudpi, config)
if camera:
self.add_component(camera)
return True
def validate(self, config):
"""Validate the camera config"""
if not i... | the_stack_v2_python_sparse | mudpi/extensions/picamera/camera.py | mistasp0ck/mudpi-core | train | 0 | |
9eb69b1ee067fc4ce8ffc7fda39146693790ccde | [
"if t not in cls.EMBED_MAPPER:\n raise DependencyEmbedderError('Type %s is not mapped! Types mapped: %s' % (t, cls.EMBED_MAPPER.keys()))\nembed_list = []\nfor ef, ev in cls.EMBED_MAPPER[t].items():\n if not ev:\n embed_list.append('.'.join([base_path, ef]))\n else:\n embed_list.extend(['.'.jo... | <|body_start_0|>
if t not in cls.EMBED_MAPPER:
raise DependencyEmbedderError('Type %s is not mapped! Types mapped: %s' % (t, cls.EMBED_MAPPER.keys()))
embed_list = []
for ef, ev in cls.EMBED_MAPPER[t].items():
if not ev:
embed_list.append('.'.join([base_pa... | Utility class intended to be used to produce the embedded list necessary for a general default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are specified in EMBED_MAPPER and that top level properties have None value while linked em... | DependencyEmbedder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DependencyEmbedder:
"""Utility class intended to be used to produce the embedded list necessary for a general default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are specified in EMBED_MAPPER and that top le... | stack_v2_sparse_classes_10k_train_004147 | 5,519 | permissive | [
{
"docstring": "Embeds the fields necessary for a default embed of the given type and base_path :param base_path: path to linkTo :param t: item type this embed is for :return: list of embeds",
"name": "embed_defaults_for_type",
"signature": "def embed_defaults_for_type(cls, *, base_path, t)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_007345 | Implement the Python class `DependencyEmbedder` described below.
Class description:
Utility class intended to be used to produce the embedded list necessary for a general default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are sp... | Implement the Python class `DependencyEmbedder` described below.
Class description:
Utility class intended to be used to produce the embedded list necessary for a general default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are sp... | e6542da84eb40e190653fd868e9b89015dfb829e | <|skeleton|>
class DependencyEmbedder:
"""Utility class intended to be used to produce the embedded list necessary for a general default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are specified in EMBED_MAPPER and that top le... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DependencyEmbedder:
"""Utility class intended to be used to produce the embedded list necessary for a general default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are specified in EMBED_MAPPER and that top level propertie... | the_stack_v2_python_sparse | src/encoded/types/dependencies.py | 4dn-dcic/fourfront | train | 13 |
3610fa11406aab74feba6b034e76e404bb00c387 | [
"self._params = Parameters()\nfor path, param in network.get_variables().items():\n self._params.add(path + '_velocity', numpy.zeros_like(param.get_value()))\nif 'momentum' not in optimization_options:\n raise ValueError('Momentum is not given in optimization options.')\nself._momentum = optimization_options[... | <|body_start_0|>
self._params = Parameters()
for path, param in network.get_variables().items():
self._params.add(path + '_velocity', numpy.zeros_like(param.get_value()))
if 'momentum' not in optimization_options:
raise ValueError('Momentum is not given in optimization op... | Nesterov Momentum Optimization Method Normally Nesterov momentum is implemented by first taking a step towards the previous update direction, calculating gradient at that position, using the gradient to obtain the new update direction, and finally updating the parameters. We use an alternative formulation that requires... | NesterovOptimizer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NesterovOptimizer:
"""Nesterov Momentum Optimization Method Normally Nesterov momentum is implemented by first taking a step towards the previous update direction, calculating gradient at that position, using the gradient to obtain the new update direction, and finally updating the parameters. We... | stack_v2_sparse_classes_10k_train_004148 | 2,905 | permissive | [
{
"docstring": "Creates a Nesterov momentum optimizer. Nesterov momentum optimizer does not use additional parameters. :type optimization_options: dict :param optimization_options: a dictionary of optimization options :type network: Network :param network: the neural network object",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_004862 | Implement the Python class `NesterovOptimizer` described below.
Class description:
Nesterov Momentum Optimization Method Normally Nesterov momentum is implemented by first taking a step towards the previous update direction, calculating gradient at that position, using the gradient to obtain the new update direction, ... | Implement the Python class `NesterovOptimizer` described below.
Class description:
Nesterov Momentum Optimization Method Normally Nesterov momentum is implemented by first taking a step towards the previous update direction, calculating gradient at that position, using the gradient to obtain the new update direction, ... | 9904faec19ad5718470f21927229aad2656e5686 | <|skeleton|>
class NesterovOptimizer:
"""Nesterov Momentum Optimization Method Normally Nesterov momentum is implemented by first taking a step towards the previous update direction, calculating gradient at that position, using the gradient to obtain the new update direction, and finally updating the parameters. We... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NesterovOptimizer:
"""Nesterov Momentum Optimization Method Normally Nesterov momentum is implemented by first taking a step towards the previous update direction, calculating gradient at that position, using the gradient to obtain the new update direction, and finally updating the parameters. We use an alter... | the_stack_v2_python_sparse | theanolm/training/nesterovoptimizer.py | senarvi/theanolm | train | 95 |
8cf3d606094100af657b459573438099bb80cfd9 | [
"super().__init__('synthetic_facial_image_generation_node')\nself.image_publisher = self.create_publisher(ROS_Image, output_rgb_image_topic, 10)\nself.create_subscription(ROS_Image, input_rgb_image_topic, self.callback, 1)\nself._cv_bridge = CvBridge()\nself.ID = 0\nself.args = args\nself.path_in = args.path_in\nse... | <|body_start_0|>
super().__init__('synthetic_facial_image_generation_node')
self.image_publisher = self.create_publisher(ROS_Image, output_rgb_image_topic, 10)
self.create_subscription(ROS_Image, input_rgb_image_topic, self.callback, 1)
self._cv_bridge = CvBridge()
self.ID = 0
... | SyntheticDataGeneratorNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyntheticDataGeneratorNode:
def __init__(self, args, input_rgb_image_topic='/image_raw', output_rgb_image_topic='/opendr/synthetic_facial_images'):
"""Creates a ROS Node for SyntheticDataGeneration :param input_rgb_image_topic: Topic from which we are reading the input image :type input_... | stack_v2_sparse_classes_10k_train_004149 | 9,414 | permissive | [
{
"docstring": "Creates a ROS Node for SyntheticDataGeneration :param input_rgb_image_topic: Topic from which we are reading the input image :type input_rgb_image_topic: str :param output_rgb_image_topic: Topic to which we are publishing the synthetic facial image (if None, no image is published) :type output_r... | 2 | null | Implement the Python class `SyntheticDataGeneratorNode` described below.
Class description:
Implement the SyntheticDataGeneratorNode class.
Method signatures and docstrings:
- def __init__(self, args, input_rgb_image_topic='/image_raw', output_rgb_image_topic='/opendr/synthetic_facial_images'): Creates a ROS Node for... | Implement the Python class `SyntheticDataGeneratorNode` described below.
Class description:
Implement the SyntheticDataGeneratorNode class.
Method signatures and docstrings:
- def __init__(self, args, input_rgb_image_topic='/image_raw', output_rgb_image_topic='/opendr/synthetic_facial_images'): Creates a ROS Node for... | b3d6ce670cdf63469fc5766630eb295d67b3d788 | <|skeleton|>
class SyntheticDataGeneratorNode:
def __init__(self, args, input_rgb_image_topic='/image_raw', output_rgb_image_topic='/opendr/synthetic_facial_images'):
"""Creates a ROS Node for SyntheticDataGeneration :param input_rgb_image_topic: Topic from which we are reading the input image :type input_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SyntheticDataGeneratorNode:
def __init__(self, args, input_rgb_image_topic='/image_raw', output_rgb_image_topic='/opendr/synthetic_facial_images'):
"""Creates a ROS Node for SyntheticDataGeneration :param input_rgb_image_topic: Topic from which we are reading the input image :type input_rgb_image_topi... | the_stack_v2_python_sparse | projects/opendr_ws_2/src/opendr_data_generation/opendr_data_generation/synthetic_facial_generation_node.py | opendr-eu/opendr | train | 535 | |
52d2439979024932501afd97dcac96c9281b62d9 | [
"LOG.debug(f'Inserting {len(cytobands)} cytoband intervals into database')\nresult = self.cytoband_collection.insert_many(cytobands)\nLOG.debug(f'Number of inserted documents:{len(result.inserted_ids)}')",
"if '38' in str(build):\n build = '38'\nelse:\n build = '37'\nmatch = {'$match': {'build': build}}\ngr... | <|body_start_0|>
LOG.debug(f'Inserting {len(cytobands)} cytoband intervals into database')
result = self.cytoband_collection.insert_many(cytobands)
LOG.debug(f'Number of inserted documents:{len(result.inserted_ids)}')
<|end_body_0|>
<|body_start_1|>
if '38' in str(build):
bu... | Class to handle cytoband-related entries | CytobandHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CytobandHandler:
"""Class to handle cytoband-related entries"""
def add_cytobands(self, cytobands):
"""Adds a list of cytoband objects to database Args: cytobands(list): a list of cytobands objects"""
<|body_0|>
def cytoband_by_chrom(self, build='37'):
"""Returns... | stack_v2_sparse_classes_10k_train_004150 | 2,082 | permissive | [
{
"docstring": "Adds a list of cytoband objects to database Args: cytobands(list): a list of cytobands objects",
"name": "add_cytobands",
"signature": "def add_cytobands(self, cytobands)"
},
{
"docstring": "Returns a dictionary of cytobands with chromosomes as keys Args: build(str): \"37\" or \"... | 2 | stack_v2_sparse_classes_30k_train_003081 | Implement the Python class `CytobandHandler` described below.
Class description:
Class to handle cytoband-related entries
Method signatures and docstrings:
- def add_cytobands(self, cytobands): Adds a list of cytoband objects to database Args: cytobands(list): a list of cytobands objects
- def cytoband_by_chrom(self,... | Implement the Python class `CytobandHandler` described below.
Class description:
Class to handle cytoband-related entries
Method signatures and docstrings:
- def add_cytobands(self, cytobands): Adds a list of cytoband objects to database Args: cytobands(list): a list of cytobands objects
- def cytoband_by_chrom(self,... | 1e6a633ba0a83495047ee7b66db1ebf690ee465f | <|skeleton|>
class CytobandHandler:
"""Class to handle cytoband-related entries"""
def add_cytobands(self, cytobands):
"""Adds a list of cytoband objects to database Args: cytobands(list): a list of cytobands objects"""
<|body_0|>
def cytoband_by_chrom(self, build='37'):
"""Returns... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CytobandHandler:
"""Class to handle cytoband-related entries"""
def add_cytobands(self, cytobands):
"""Adds a list of cytoband objects to database Args: cytobands(list): a list of cytobands objects"""
LOG.debug(f'Inserting {len(cytobands)} cytoband intervals into database')
result... | the_stack_v2_python_sparse | scout/adapter/mongo/cytoband.py | Clinical-Genomics/scout | train | 143 |
fbb6b021cfe2644005744a3e4d97f1ffa4cd8fa4 | [
"self.file_name = file_name\ndtype = np.dtype = [('lih', '<i4'), ('liu', '<i4'), ('liv', '<i4'), ('h', '<f4'), ('u', '<f4'), ('v', '<f4'), ('au', '<f4'), ('lit', '<i4'), ('t', '<f4'), ('at', '<f4'), ('bt', '<f4'), ('n', '<i4'), ('line', '<i4')]\nif file_name != '':\n core = [tuple(line.strip().split()[0:13]) for... | <|body_start_0|>
self.file_name = file_name
dtype = np.dtype = [('lih', '<i4'), ('liu', '<i4'), ('liv', '<i4'), ('h', '<f4'), ('u', '<f4'), ('v', '<f4'), ('au', '<f4'), ('lit', '<i4'), ('t', '<f4'), ('at', '<f4'), ('bt', '<f4'), ('n', '<i4'), ('line', '<i4')]
if file_name != '':
core... | Boundary conditions class | Conlim | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conlim:
"""Boundary conditions class"""
def __init__(self, file_name):
"""@brief Initializes the Conlim object @param file_name (string): name of the boundary conditions file @return None"""
<|body_0|>
def set_numliq(self, closed_contours):
"""@brief Sets the num... | stack_v2_sparse_classes_10k_train_004151 | 6,142 | no_license | [
{
"docstring": "@brief Initializes the Conlim object @param file_name (string): name of the boundary conditions file @return None",
"name": "__init__",
"signature": "def __init__(self, file_name)"
},
{
"docstring": "@brief Sets the number of liquid boundaries @param closed_contours (list): list ... | 3 | stack_v2_sparse_classes_30k_train_005805 | Implement the Python class `Conlim` described below.
Class description:
Boundary conditions class
Method signatures and docstrings:
- def __init__(self, file_name): @brief Initializes the Conlim object @param file_name (string): name of the boundary conditions file @return None
- def set_numliq(self, closed_contours)... | Implement the Python class `Conlim` described below.
Class description:
Boundary conditions class
Method signatures and docstrings:
- def __init__(self, file_name): @brief Initializes the Conlim object @param file_name (string): name of the boundary conditions file @return None
- def set_numliq(self, closed_contours)... | 738e8e491e10bbbc3c21afe01221ed4661ce8a87 | <|skeleton|>
class Conlim:
"""Boundary conditions class"""
def __init__(self, file_name):
"""@brief Initializes the Conlim object @param file_name (string): name of the boundary conditions file @return None"""
<|body_0|>
def set_numliq(self, closed_contours):
"""@brief Sets the num... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Conlim:
"""Boundary conditions class"""
def __init__(self, file_name):
"""@brief Initializes the Conlim object @param file_name (string): name of the boundary conditions file @return None"""
self.file_name = file_name
dtype = np.dtype = [('lih', '<i4'), ('liu', '<i4'), ('liv', '<i... | the_stack_v2_python_sparse | scripts/python3/data_manip/formats/conlim.py | msecher/scripts_python_3_opentelemac_r14499 | train | 0 |
067eaeb44191cd205b879e540524ca606d7c3b04 | [
"self.encoder = encoder\nself.dataset = dataset\nself.path = path\nself.batch_size = batch_size\nself.topo = topo",
"if self.batch_size is None:\n if self.topo:\n data = self.dataset.get_topological_view()\n else:\n data = self.dataset.get_design_matrix()\n output = self.encoder.perform(dat... | <|body_start_0|>
self.encoder = encoder
self.dataset = dataset
self.path = path
self.batch_size = batch_size
self.topo = topo
<|end_body_0|>
<|body_start_1|>
if self.batch_size is None:
if self.topo:
data = self.dataset.get_topological_view()
... | .. todo:: WRITEME Parameters ---------- encoder : WRITEME dataset : WRITEME path : WRITEME batch_size : WRITEME topo : WRITEME | FeatureDump | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureDump:
""".. todo:: WRITEME Parameters ---------- encoder : WRITEME dataset : WRITEME path : WRITEME batch_size : WRITEME topo : WRITEME"""
def __init__(self, encoder, dataset, path, batch_size=None, topo=False):
""".. todo:: WRITEME"""
<|body_0|>
def main_loop(sel... | stack_v2_sparse_classes_10k_train_004152 | 8,573 | permissive | [
{
"docstring": ".. todo:: WRITEME",
"name": "__init__",
"signature": "def __init__(self, encoder, dataset, path, batch_size=None, topo=False)"
},
{
"docstring": ".. todo:: WRITEME Parameters ---------- **kwargs : dict, optional WRITEME",
"name": "main_loop",
"signature": "def main_loop(s... | 2 | null | Implement the Python class `FeatureDump` described below.
Class description:
.. todo:: WRITEME Parameters ---------- encoder : WRITEME dataset : WRITEME path : WRITEME batch_size : WRITEME topo : WRITEME
Method signatures and docstrings:
- def __init__(self, encoder, dataset, path, batch_size=None, topo=False): .. to... | Implement the Python class `FeatureDump` described below.
Class description:
.. todo:: WRITEME Parameters ---------- encoder : WRITEME dataset : WRITEME path : WRITEME batch_size : WRITEME topo : WRITEME
Method signatures and docstrings:
- def __init__(self, encoder, dataset, path, batch_size=None, topo=False): .. to... | 96edb376ced1b828962c749240059903686da549 | <|skeleton|>
class FeatureDump:
""".. todo:: WRITEME Parameters ---------- encoder : WRITEME dataset : WRITEME path : WRITEME batch_size : WRITEME topo : WRITEME"""
def __init__(self, encoder, dataset, path, batch_size=None, topo=False):
""".. todo:: WRITEME"""
<|body_0|>
def main_loop(sel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FeatureDump:
""".. todo:: WRITEME Parameters ---------- encoder : WRITEME dataset : WRITEME path : WRITEME batch_size : WRITEME topo : WRITEME"""
def __init__(self, encoder, dataset, path, batch_size=None, topo=False):
""".. todo:: WRITEME"""
self.encoder = encoder
self.dataset = ... | the_stack_v2_python_sparse | pylearn2/scripts/train.py | Coderx7/pylearn2 | train | 1 |
bdf1d1dd1115bdf04fd513be501d8103764d2717 | [
"if destination.is_dirty():\n raise OSError(f'Repo `{destination.working_tree_dir}` is dirty')\nself.source = source\nself.destination = destination\nself.commits_in_order = GetCommitsInOrder(source, head_ref=head_ref)\nself.files_of_interest = files_of_interest\nif not self.commits_in_order:\n raise OSError(... | <|body_start_0|>
if destination.is_dirty():
raise OSError(f'Repo `{destination.working_tree_dir}` is dirty')
self.source = source
self.destination = destination
self.commits_in_order = GetCommitsInOrder(source, head_ref=head_ref)
self.files_of_interest = files_of_inte... | A progressable thread for exporting a subset of a repo's commits. | SubtreeExporter | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubtreeExporter:
"""A progressable thread for exporting a subset of a repo's commits."""
def __init__(self, source: git.Repo, destination: git.Repo, files_of_interest: Set[str], head_ref: str='HEAD'):
"""Constructor. Args: source: The source repository to export from. destination: Th... | stack_v2_sparse_classes_10k_train_004153 | 6,824 | permissive | [
{
"docstring": "Constructor. Args: source: The source repository to export from. destination: The destination repository to export to. files_of_interest: The relpaths of the files to export. head_ref: The commit to export up to.",
"name": "__init__",
"signature": "def __init__(self, source: git.Repo, de... | 2 | stack_v2_sparse_classes_30k_train_005357 | Implement the Python class `SubtreeExporter` described below.
Class description:
A progressable thread for exporting a subset of a repo's commits.
Method signatures and docstrings:
- def __init__(self, source: git.Repo, destination: git.Repo, files_of_interest: Set[str], head_ref: str='HEAD'): Constructor. Args: sour... | Implement the Python class `SubtreeExporter` described below.
Class description:
A progressable thread for exporting a subset of a repo's commits.
Method signatures and docstrings:
- def __init__(self, source: git.Repo, destination: git.Repo, files_of_interest: Set[str], head_ref: str='HEAD'): Constructor. Args: sour... | 913d67f4f454cedc61220a210113bbf0460bb4d5 | <|skeleton|>
class SubtreeExporter:
"""A progressable thread for exporting a subset of a repo's commits."""
def __init__(self, source: git.Repo, destination: git.Repo, files_of_interest: Set[str], head_ref: str='HEAD'):
"""Constructor. Args: source: The source repository to export from. destination: Th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SubtreeExporter:
"""A progressable thread for exporting a subset of a repo's commits."""
def __init__(self, source: git.Repo, destination: git.Repo, files_of_interest: Set[str], head_ref: str='HEAD'):
"""Constructor. Args: source: The source repository to export from. destination: The destination... | the_stack_v2_python_sparse | tools/git/export_subtree.py | ChrisCummins/labm8 | train | 3 |
9a13a641f8ec42e9ed6e1dc4fca9529199bc50fe | [
"res = 0\nn = len(prices)\nif n <= 1:\n return 0\nminpre = prices[0]\nfor i in range(1, n):\n res = max(prices[i] - minpre, res)\n minpre = min(prices[i], minpre)\nreturn res",
"res = 0\nn = len(prices)\nif n <= 1:\n return 0\ndp = [[0 for i in range(2)] for j in range(n)]\ndp[0][0] = 0\ndp[0][1] = -p... | <|body_start_0|>
res = 0
n = len(prices)
if n <= 1:
return 0
minpre = prices[0]
for i in range(1, n):
res = max(prices[i] - minpre, res)
minpre = min(prices[i], minpre)
return res
<|end_body_0|>
<|body_start_1|>
res = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""只交易一次"""
<|body_0|>
def maxProfit(self, prices: List[int]) -> int:
"""给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_004154 | 1,188 | no_license | [
{
"docstring": "只交易一次",
"name": "maxProfit",
"signature": "def maxProfit(self, prices: List[int]) -> int"
},
{
"docstring": "给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。",
"name": "maxProfit",
"signature": "def maxProfi... | 2 | stack_v2_sparse_classes_30k_train_001995 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 只交易一次
- def maxProfit(self, prices: List[int]) -> int: 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 只交易一次
- def maxProfit(self, prices: List[int]) -> int: 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票... | cb3587242195bb3f2626231af2da13b90945a4d5 | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""只交易一次"""
<|body_0|>
def maxProfit(self, prices: List[int]) -> int:
"""给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""只交易一次"""
res = 0
n = len(prices)
if n <= 1:
return 0
minpre = prices[0]
for i in range(1, n):
res = max(prices[i] - minpre, res)
minpre = min(prices[i], minpre)
... | the_stack_v2_python_sparse | MianShi/zijie/买卖股票的最佳时机N121.py | lionheartStark/sword_towards_offer | train | 0 | |
8da0d16bb56fef384382aae050836db6a277536e | [
"super().__init__(*args, **kargs)\nif self.instance.action_type == models.Action.PERSONALIZED_TEXT or self.instance.action_type == models.Action.RUBRIC_TEXT or self.instance.action_type == models.Action.EMAIL_REPORT:\n self.fields['text_content'].widget = TinyMCE(attrs={'cols': 80, 'rows': 30})\nif self.instance... | <|body_start_0|>
super().__init__(*args, **kargs)
if self.instance.action_type == models.Action.PERSONALIZED_TEXT or self.instance.action_type == models.Action.RUBRIC_TEXT or self.instance.action_type == models.Action.EMAIL_REPORT:
self.fields['text_content'].widget = TinyMCE(attrs={'cols': ... | Main class to edit an action out. | EditActionOutForm | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditActionOutForm:
"""Main class to edit an action out."""
def __init__(self, *args, **kargs):
"""Adjust field parameters for content and target_URL."""
<|body_0|>
def clean(self) -> Dict:
"""Verify that the template text renders correctly."""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_004155 | 5,848 | permissive | [
{
"docstring": "Adjust field parameters for content and target_URL.",
"name": "__init__",
"signature": "def __init__(self, *args, **kargs)"
},
{
"docstring": "Verify that the template text renders correctly.",
"name": "clean",
"signature": "def clean(self) -> Dict"
}
] | 2 | null | Implement the Python class `EditActionOutForm` described below.
Class description:
Main class to edit an action out.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Adjust field parameters for content and target_URL.
- def clean(self) -> Dict: Verify that the template text renders correctly. | Implement the Python class `EditActionOutForm` described below.
Class description:
Main class to edit an action out.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Adjust field parameters for content and target_URL.
- def clean(self) -> Dict: Verify that the template text renders correctly.
... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class EditActionOutForm:
"""Main class to edit an action out."""
def __init__(self, *args, **kargs):
"""Adjust field parameters for content and target_URL."""
<|body_0|>
def clean(self) -> Dict:
"""Verify that the template text renders correctly."""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EditActionOutForm:
"""Main class to edit an action out."""
def __init__(self, *args, **kargs):
"""Adjust field parameters for content and target_URL."""
super().__init__(*args, **kargs)
if self.instance.action_type == models.Action.PERSONALIZED_TEXT or self.instance.action_type ==... | the_stack_v2_python_sparse | ontask/action/forms/edit.py | abelardopardo/ontask_b | train | 43 |
5b85be2512696f7634a2fb349bbeaaa342cf6875 | [
"crypto_meta_json = self._response_header_value(header_name)\nif crypto_meta_json is None:\n return None\ncrypto_meta = load_crypto_meta(crypto_meta_json)\nif check:\n self.crypto.check_crypto_meta(crypto_meta)\nreturn crypto_meta",
"try:\n return self.crypto.unwrap_key(wrapping_key, crypto_meta['body_ke... | <|body_start_0|>
crypto_meta_json = self._response_header_value(header_name)
if crypto_meta_json is None:
return None
crypto_meta = load_crypto_meta(crypto_meta_json)
if check:
self.crypto.check_crypto_meta(crypto_meta)
return crypto_meta
<|end_body_0|>
<... | BaseDecrypterContext | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseDecrypterContext:
def get_crypto_meta(self, header_name, check=True):
"""Extract a crypto_meta dict from a header. :param header_name: name of header that may have crypto_meta :param check: if True validate the crypto meta :return: A dict containing crypto_meta items :raises Encrypti... | stack_v2_sparse_classes_10k_train_004156 | 20,452 | permissive | [
{
"docstring": "Extract a crypto_meta dict from a header. :param header_name: name of header that may have crypto_meta :param check: if True validate the crypto meta :return: A dict containing crypto_meta items :raises EncryptionException: if an error occurs while parsing the crypto meta",
"name": "get_cryp... | 5 | stack_v2_sparse_classes_30k_test_000049 | Implement the Python class `BaseDecrypterContext` described below.
Class description:
Implement the BaseDecrypterContext class.
Method signatures and docstrings:
- def get_crypto_meta(self, header_name, check=True): Extract a crypto_meta dict from a header. :param header_name: name of header that may have crypto_meta... | Implement the Python class `BaseDecrypterContext` described below.
Class description:
Implement the BaseDecrypterContext class.
Method signatures and docstrings:
- def get_crypto_meta(self, header_name, check=True): Extract a crypto_meta dict from a header. :param header_name: name of header that may have crypto_meta... | f06e5369579599648cc78e4b556887bc6d978c2b | <|skeleton|>
class BaseDecrypterContext:
def get_crypto_meta(self, header_name, check=True):
"""Extract a crypto_meta dict from a header. :param header_name: name of header that may have crypto_meta :param check: if True validate the crypto meta :return: A dict containing crypto_meta items :raises Encrypti... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaseDecrypterContext:
def get_crypto_meta(self, header_name, check=True):
"""Extract a crypto_meta dict from a header. :param header_name: name of header that may have crypto_meta :param check: if True validate the crypto meta :return: A dict containing crypto_meta items :raises EncryptionException: i... | the_stack_v2_python_sparse | swift/common/middleware/crypto/decrypter.py | openstack/swift | train | 2,370 | |
e821956fe365552bf5e725daea7a87b27b5d45de | [
"positive_ctx = row['positive_ctx']\npositive_ctx_tokens = self.tokenizer.tokenize(positive_ctx)\npositive_ctx_token_ids, positive_ctx_segment_labels, positive_ctx_seq_len, positive_ctx_positions = self.tensorizer_script_impl.numberize([positive_ctx_tokens])\nnegative_ctxs = row['negative_ctxs']\nif negative_ctxs:\... | <|body_start_0|>
positive_ctx = row['positive_ctx']
positive_ctx_tokens = self.tokenizer.tokenize(positive_ctx)
positive_ctx_token_ids, positive_ctx_segment_labels, positive_ctx_seq_len, positive_ctx_positions = self.tensorizer_script_impl.numberize([positive_ctx_tokens])
negative_ctxs =... | Methods numberize() and tensorize() implement https://fburl.com/an4fv7m1. | BERTContextTensorizerForDenseRetrieval | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BERTContextTensorizerForDenseRetrieval:
"""Methods numberize() and tensorize() implement https://fburl.com/an4fv7m1."""
def numberize(self, row: Dict) -> Tuple[Any, ...]:
"""This function contains logic for converting tokens into ids based on the specified vocab. It also outputs, for... | stack_v2_sparse_classes_10k_train_004157 | 5,499 | permissive | [
{
"docstring": "This function contains logic for converting tokens into ids based on the specified vocab. It also outputs, for each instance, the vectors needed to run the actual model. It works off of one sample.",
"name": "numberize",
"signature": "def numberize(self, row: Dict) -> Tuple[Any, ...]"
... | 2 | stack_v2_sparse_classes_30k_train_003030 | Implement the Python class `BERTContextTensorizerForDenseRetrieval` described below.
Class description:
Methods numberize() and tensorize() implement https://fburl.com/an4fv7m1.
Method signatures and docstrings:
- def numberize(self, row: Dict) -> Tuple[Any, ...]: This function contains logic for converting tokens in... | Implement the Python class `BERTContextTensorizerForDenseRetrieval` described below.
Class description:
Methods numberize() and tensorize() implement https://fburl.com/an4fv7m1.
Method signatures and docstrings:
- def numberize(self, row: Dict) -> Tuple[Any, ...]: This function contains logic for converting tokens in... | 3bba58a048c87d7c93a41830fa7853896c4b3e66 | <|skeleton|>
class BERTContextTensorizerForDenseRetrieval:
"""Methods numberize() and tensorize() implement https://fburl.com/an4fv7m1."""
def numberize(self, row: Dict) -> Tuple[Any, ...]:
"""This function contains logic for converting tokens into ids based on the specified vocab. It also outputs, for... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BERTContextTensorizerForDenseRetrieval:
"""Methods numberize() and tensorize() implement https://fburl.com/an4fv7m1."""
def numberize(self, row: Dict) -> Tuple[Any, ...]:
"""This function contains logic for converting tokens into ids based on the specified vocab. It also outputs, for each instanc... | the_stack_v2_python_sparse | pytext/data/dense_retrieval_tensorizer.py | mruberry/pytext | train | 2 |
5de40c7d8d371ca4df46c8fd1a9c061eb997c4d6 | [
"rtn = []\n\ndef dfs(node):\n if node:\n rtn.append(str(node.val))\n for c in node.children:\n dfs(c)\n rtn.append('#')\n else:\n rtn.append('#')\ndfs(root)\nreturn ' '.join(rtn)",
"def dfs():\n val = next(vals)\n if val == '#':\n return None\n else:\n ... | <|body_start_0|>
rtn = []
def dfs(node):
if node:
rtn.append(str(node.val))
for c in node.children:
dfs(c)
rtn.append('#')
else:
rtn.append('#')
dfs(root)
return ' '.join(rtn)
<|e... | Codec | [
"Apache-2.0"
] | 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_10k_train_004158 | 1,325 | permissive | [
{
"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 | null | 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... | a00a57e1b36433648d1cace331e15ff276cef189 | <|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_10k | 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"""
rtn = []
def dfs(node):
if node:
rtn.append(str(node.val))
for c in node.children:
dfs(c)
... | the_stack_v2_python_sparse | leet/trees/encodenary.py | stacykutyepov/python-cp-cheatsheet | train | 2 | |
ed567eeee35fa9260888599dd67d1019f28d03d4 | [
"self._grid = grid\nself.runoff_rate = runoff_rate / 3600000.0\nself.vel_coef = 1.0 / roughness\nself.changing_topo = changing_topo\nself.depth_exp = depth_exp\nself.weight = weight\ntry:\n self.elev = grid.at_node['topographic__elevation']\nexcept:\n raise\nif 'surface_water__depth' in grid.at_node:\n sel... | <|body_start_0|>
self._grid = grid
self.runoff_rate = runoff_rate / 3600000.0
self.vel_coef = 1.0 / roughness
self.changing_topo = changing_topo
self.depth_exp = depth_exp
self.weight = weight
try:
self.elev = grid.at_node['topographic__elevation']
... | Calculate shallow water flow over topography. Landlab component that implements a two-dimensional kinematic wave model. This is a form of the 2D shallow-water equations in which energy slope is assumed to equal bed slope. The solution method is locally implicit, and works as follows. At each time step, we iterate from ... | KinwaveImplicitOverlandFlow | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KinwaveImplicitOverlandFlow:
"""Calculate shallow water flow over topography. Landlab component that implements a two-dimensional kinematic wave model. This is a form of the 2D shallow-water equations in which energy slope is assumed to equal bed slope. The solution method is locally implicit, an... | stack_v2_sparse_classes_10k_train_004159 | 14,450 | permissive | [
{
"docstring": "Initialize the KinwaveOverlandFlowModel. Parameters ---------- grid : ModelGrid Landlab ModelGrid object runoff_rate : float, optional (defaults to 1 mm/hr) Precipitation rate, mm/hr roughnes : float, defaults to 0.01 Manning roughness coefficient, s/m^1/3 changing_topo : boolean, optional (defa... | 2 | stack_v2_sparse_classes_30k_train_003400 | Implement the Python class `KinwaveImplicitOverlandFlow` described below.
Class description:
Calculate shallow water flow over topography. Landlab component that implements a two-dimensional kinematic wave model. This is a form of the 2D shallow-water equations in which energy slope is assumed to equal bed slope. The ... | Implement the Python class `KinwaveImplicitOverlandFlow` described below.
Class description:
Calculate shallow water flow over topography. Landlab component that implements a two-dimensional kinematic wave model. This is a form of the 2D shallow-water equations in which energy slope is assumed to equal bed slope. The ... | 8c8613f8b8653906c1497f6557dd2a0bc555a79a | <|skeleton|>
class KinwaveImplicitOverlandFlow:
"""Calculate shallow water flow over topography. Landlab component that implements a two-dimensional kinematic wave model. This is a form of the 2D shallow-water equations in which energy slope is assumed to equal bed slope. The solution method is locally implicit, an... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KinwaveImplicitOverlandFlow:
"""Calculate shallow water flow over topography. Landlab component that implements a two-dimensional kinematic wave model. This is a form of the 2D shallow-water equations in which energy slope is assumed to equal bed slope. The solution method is locally implicit, and works as fo... | the_stack_v2_python_sparse | landlab/components/overland_flow/generate_overland_flow_implicit_kinwave.py | RondaStrauch/landlab | train | 2 |
02873659d7bdabbbbad78f84c585c91fc56abfd0 | [
"self.title = title\nself.description = jsondata.get('description', '')\n_verbose(\" Pod '{}': {}\".format(self.title, self.description))\nself.servers = [Server(data) for data in jsondata.get('servers', [])]\nfor ctr, server in enumerate(self.servers):\n _verbose(' Server: {}'.format(server.sockname))\n ... | <|body_start_0|>
self.title = title
self.description = jsondata.get('description', '')
_verbose(" Pod '{}': {}".format(self.title, self.description))
self.servers = [Server(data) for data in jsondata.get('servers', [])]
for ctr, server in enumerate(self.servers):
_ve... | Model object that represents an L{Pod}. | Pod | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pod:
"""Model object that represents an L{Pod}."""
def __init__(self, title, jsondata):
"""Parse the pod details from the JSON data and create the list of L{Server}'s."""
<|body_0|>
def sendSock(self):
"""Update the data for each L{Server} in this L{Pod}."""
... | stack_v2_sparse_classes_10k_train_004160 | 14,800 | permissive | [
{
"docstring": "Parse the pod details from the JSON data and create the list of L{Server}'s.",
"name": "__init__",
"signature": "def __init__(self, title, jsondata)"
},
{
"docstring": "Update the data for each L{Server} in this L{Pod}.",
"name": "sendSock",
"signature": "def sendSock(sel... | 3 | null | Implement the Python class `Pod` described below.
Class description:
Model object that represents an L{Pod}.
Method signatures and docstrings:
- def __init__(self, title, jsondata): Parse the pod details from the JSON data and create the list of L{Server}'s.
- def sendSock(self): Update the data for each L{Server} in... | Implement the Python class `Pod` described below.
Class description:
Model object that represents an L{Pod}.
Method signatures and docstrings:
- def __init__(self, title, jsondata): Parse the pod details from the JSON data and create the list of L{Server}'s.
- def sendSock(self): Update the data for each L{Server} in... | cb2962f1f1927f1e52ea405094fa3e7e180f23cb | <|skeleton|>
class Pod:
"""Model object that represents an L{Pod}."""
def __init__(self, title, jsondata):
"""Parse the pod details from the JSON data and create the list of L{Server}'s."""
<|body_0|>
def sendSock(self):
"""Update the data for each L{Server} in this L{Pod}."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Pod:
"""Model object that represents an L{Pod}."""
def __init__(self, title, jsondata):
"""Parse the pod details from the JSON data and create the list of L{Server}'s."""
self.title = title
self.description = jsondata.get('description', '')
_verbose(" Pod '{}': {}".format... | the_stack_v2_python_sparse | calendarserver/tools/dashcollect.py | ass-a2s/ccs-calendarserver | train | 2 |
2be866b765d97b151da286ee113080d9177bf2c5 | [
"self.keyToFreq = {}\nself.freqToKeyValue = defaultdict(OrderedDict)\nself.capacity = capacity\nself.minFreq = 1",
"if key not in self.keyToFreq:\n return -1\nif len(self.freqToKeyValue[self.keyToFreq[key]]) == 1 and self.keyToFreq[key] == self.minFreq:\n self.minFreq = self.keyToFreq[key] + 1\nfreq = self.... | <|body_start_0|>
self.keyToFreq = {}
self.freqToKeyValue = defaultdict(OrderedDict)
self.capacity = capacity
self.minFreq = 1
<|end_body_0|>
<|body_start_1|>
if key not in self.keyToFreq:
return -1
if len(self.freqToKeyValue[self.keyToFreq[key]]) == 1 and sel... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k_train_004161 | 3,574 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_002243 | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | ea3e6aa7efd570e6a2a32b269198027ccf1d6a3b | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.keyToFreq = {}
self.freqToKeyValue = defaultdict(OrderedDict)
self.capacity = capacity
self.minFreq = 1
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.ke... | the_stack_v2_python_sparse | Python/HashTablePlusList/LfuCache.py | DreamOfTheRedChamber/leetcode | train | 51 | |
f0349ce7de8159d47191604fab68f67922246401 | [
"for prop in self.__dict__.values():\n if issubclass(prop.__class__, JobPropertyContainer) and 'signatures' in prop.__dict__.keys():\n prop.setL2()",
"for prop in self.__dict__.values():\n if issubclass(prop.__class__, JobPropertyContainer) and 'signatures' in prop.__dict__.keys():\n prop.setE... | <|body_start_0|>
for prop in self.__dict__.values():
if issubclass(prop.__class__, JobPropertyContainer) and 'signatures' in prop.__dict__.keys():
prop.setL2()
<|end_body_0|>
<|body_start_1|>
for prop in self.__dict__.values():
if issubclass(prop.__class__, JobPr... | Trigger top flags | Trigger | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trigger:
"""Trigger top flags"""
def Slices_LVL2_setOn(self):
"""Runs setL2 flags in all slices. Effectivelly enable LVL2."""
<|body_0|>
def Slices_EF_setOn(self):
"""Runs setEF flags in all slices. Effectivelly enable EF."""
<|body_1|>
def Slices_al... | stack_v2_sparse_classes_10k_train_004162 | 43,775 | permissive | [
{
"docstring": "Runs setL2 flags in all slices. Effectivelly enable LVL2.",
"name": "Slices_LVL2_setOn",
"signature": "def Slices_LVL2_setOn(self)"
},
{
"docstring": "Runs setEF flags in all slices. Effectivelly enable EF.",
"name": "Slices_EF_setOn",
"signature": "def Slices_EF_setOn(se... | 6 | stack_v2_sparse_classes_30k_train_004170 | Implement the Python class `Trigger` described below.
Class description:
Trigger top flags
Method signatures and docstrings:
- def Slices_LVL2_setOn(self): Runs setL2 flags in all slices. Effectivelly enable LVL2.
- def Slices_EF_setOn(self): Runs setEF flags in all slices. Effectivelly enable EF.
- def Slices_all_se... | Implement the Python class `Trigger` described below.
Class description:
Trigger top flags
Method signatures and docstrings:
- def Slices_LVL2_setOn(self): Runs setL2 flags in all slices. Effectivelly enable LVL2.
- def Slices_EF_setOn(self): Runs setEF flags in all slices. Effectivelly enable EF.
- def Slices_all_se... | 354f92551294f7be678aebcd7b9d67d2c4448176 | <|skeleton|>
class Trigger:
"""Trigger top flags"""
def Slices_LVL2_setOn(self):
"""Runs setL2 flags in all slices. Effectivelly enable LVL2."""
<|body_0|>
def Slices_EF_setOn(self):
"""Runs setEF flags in all slices. Effectivelly enable EF."""
<|body_1|>
def Slices_al... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Trigger:
"""Trigger top flags"""
def Slices_LVL2_setOn(self):
"""Runs setL2 flags in all slices. Effectivelly enable LVL2."""
for prop in self.__dict__.values():
if issubclass(prop.__class__, JobPropertyContainer) and 'signatures' in prop.__dict__.keys():
prop.... | the_stack_v2_python_sparse | Trigger/TriggerCommon/TriggerJobOpts/python/TriggerFlags.py | strigazi/athena | train | 0 |
757d5ea0f100e99e02551a4e15d25a4f2e89afa9 | [
"tensor, mask = self.forward_embedding(input, positions, segments)\nif self.variant == 'xlm' or self.variant == 'bart':\n tensor = self.norm_embeddings(tensor)\ntensor = self.dropout(tensor)\ntensor *= mask.unsqueeze(-1).type_as(tensor)\ntensor = self.forward_layers(tensor, mask, **kwargs)\ntensor, weights = ten... | <|body_start_0|>
tensor, mask = self.forward_embedding(input, positions, segments)
if self.variant == 'xlm' or self.variant == 'bart':
tensor = self.norm_embeddings(tensor)
tensor = self.dropout(tensor)
tensor *= mask.unsqueeze(-1).type_as(tensor)
tensor = self.forwar... | Override TransformerEncoder to return the self-attn weights. | TransformerReturnWeightsEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerReturnWeightsEncoder:
"""Override TransformerEncoder to return the self-attn weights."""
def forward(self, input: torch.LongTensor, positions: Optional[torch.LongTensor]=None, segments: Optional[torch.LongTensor]=None, **kwargs) -> Union[Tuple[torch.Tensor, Optional[torch.Tensor]]... | stack_v2_sparse_classes_10k_train_004163 | 12,281 | permissive | [
{
"docstring": "Forward pass. Propagate kwargs",
"name": "forward",
"signature": "def forward(self, input: torch.LongTensor, positions: Optional[torch.LongTensor]=None, segments: Optional[torch.LongTensor]=None, **kwargs) -> Union[Tuple[torch.Tensor, Optional[torch.Tensor]], Tuple[torch.Tensor, torch.Bo... | 3 | null | Implement the Python class `TransformerReturnWeightsEncoder` described below.
Class description:
Override TransformerEncoder to return the self-attn weights.
Method signatures and docstrings:
- def forward(self, input: torch.LongTensor, positions: Optional[torch.LongTensor]=None, segments: Optional[torch.LongTensor]=... | Implement the Python class `TransformerReturnWeightsEncoder` described below.
Class description:
Override TransformerEncoder to return the self-attn weights.
Method signatures and docstrings:
- def forward(self, input: torch.LongTensor, positions: Optional[torch.LongTensor]=None, segments: Optional[torch.LongTensor]=... | e1d899edfb92471552bae153f59ad30aa7fca468 | <|skeleton|>
class TransformerReturnWeightsEncoder:
"""Override TransformerEncoder to return the self-attn weights."""
def forward(self, input: torch.LongTensor, positions: Optional[torch.LongTensor]=None, segments: Optional[torch.LongTensor]=None, **kwargs) -> Union[Tuple[torch.Tensor, Optional[torch.Tensor]]... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TransformerReturnWeightsEncoder:
"""Override TransformerEncoder to return the self-attn weights."""
def forward(self, input: torch.LongTensor, positions: Optional[torch.LongTensor]=None, segments: Optional[torch.LongTensor]=None, **kwargs) -> Union[Tuple[torch.Tensor, Optional[torch.Tensor]], Tuple[torch... | the_stack_v2_python_sparse | projects/light_whoami/agents/poly_return_weights.py | facebookresearch/ParlAI | train | 10,943 |
a69c132bd1b1fa468a8abb189844ac73080c36be | [
"if len(nums) <= 1:\n return False\nfor i in range(len(nums)):\n for j in range(len(nums)):\n if i is not j and nums[i] + nums[j] == target:\n return [i, j]",
"if len(nums) <= 1:\n return False\nbuf_dict = {}\nfor i in range(len(nums)):\n if nums[i] in buf_dict:\n return [buf_... | <|body_start_0|>
if len(nums) <= 1:
return False
for i in range(len(nums)):
for j in range(len(nums)):
if i is not j and nums[i] + nums[j] == target:
return [i, j]
<|end_body_0|>
<|body_start_1|>
if len(nums) <= 1:
return F... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twosum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twosum_hash(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twosum_enumerate(self... | stack_v2_sparse_classes_10k_train_004164 | 1,310 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twosum",
"signature": "def twosum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twosum_hash",
"signature": "def twosum_hash(self, nums, targ... | 3 | stack_v2_sparse_classes_30k_train_002748 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twosum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twosum_hash(self, nums, target): :type nums: List[int] :type target: int :rtype: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twosum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twosum_hash(self, nums, target): :type nums: List[int] :type target: int :rtype: L... | 326d2656b2f852f64c43ab4932ebd0819ae6d5b9 | <|skeleton|>
class Solution:
def twosum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twosum_hash(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twosum_enumerate(self... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def twosum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
if len(nums) <= 1:
return False
for i in range(len(nums)):
for j in range(len(nums)):
if i is not j and nums[i] + nums[j] == target:
... | the_stack_v2_python_sparse | LeetCode/LeetCode_1.py | No1CharlesWu/Python | train | 0 | |
a86b02581f06d22d5907fefdb2ff7bb64f911b59 | [
"self.x = np.array(x)\nself.xmin = self.x.min()\nself.xmax = self.x.max()\nself.y = np.array(y)\nself.ymin = self.y.min()\nself.ymax = self.y.max()\npol, cov = np.polyfit(self.x, self.y, deg, cov=True)\nPolynomial.__init__(self, pol, cov)",
"if restrict:\n x = np.array(x)\n for i in range(len(x)):\n ... | <|body_start_0|>
self.x = np.array(x)
self.xmin = self.x.min()
self.xmax = self.x.max()
self.y = np.array(y)
self.ymin = self.y.min()
self.ymax = self.y.max()
pol, cov = np.polyfit(self.x, self.y, deg, cov=True)
Polynomial.__init__(self, pol, cov)
<|end_bo... | Perform least squares polynomial fit and evaluate fit. (see numpy.polyfit) | PolyFit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PolyFit:
"""Perform least squares polynomial fit and evaluate fit. (see numpy.polyfit)"""
def __init__(self, x, y, deg=1):
"""Perform fit. Parameters ---------- x : (*,) float array-like x-coordinates of sample points. y : (*,) float array-like y-coordinates of sample points. deg : i... | stack_v2_sparse_classes_10k_train_004165 | 35,535 | permissive | [
{
"docstring": "Perform fit. Parameters ---------- x : (*,) float array-like x-coordinates of sample points. y : (*,) float array-like y-coordinates of sample points. deg : int Degree of the fitting polynomial. (default: 1)",
"name": "__init__",
"signature": "def __init__(self, x, y, deg=1)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_004513 | Implement the Python class `PolyFit` described below.
Class description:
Perform least squares polynomial fit and evaluate fit. (see numpy.polyfit)
Method signatures and docstrings:
- def __init__(self, x, y, deg=1): Perform fit. Parameters ---------- x : (*,) float array-like x-coordinates of sample points. y : (*,)... | Implement the Python class `PolyFit` described below.
Class description:
Perform least squares polynomial fit and evaluate fit. (see numpy.polyfit)
Method signatures and docstrings:
- def __init__(self, x, y, deg=1): Perform fit. Parameters ---------- x : (*,) float array-like x-coordinates of sample points. y : (*,)... | 99107a0d4935296b673f67469c1e2bd258954b9b | <|skeleton|>
class PolyFit:
"""Perform least squares polynomial fit and evaluate fit. (see numpy.polyfit)"""
def __init__(self, x, y, deg=1):
"""Perform fit. Parameters ---------- x : (*,) float array-like x-coordinates of sample points. y : (*,) float array-like y-coordinates of sample points. deg : i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PolyFit:
"""Perform least squares polynomial fit and evaluate fit. (see numpy.polyfit)"""
def __init__(self, x, y, deg=1):
"""Perform fit. Parameters ---------- x : (*,) float array-like x-coordinates of sample points. y : (*,) float array-like y-coordinates of sample points. deg : int Degree of ... | the_stack_v2_python_sparse | maths.py | yketa/active_work | train | 1 |
4768a2cbac14372206f1b2a4917f8aea5979bd00 | [
"m = defaultdict(list)\nfor i, score in items:\n if len(m[i]) < 5:\n heapq.heappush(m[i], score)\n else:\n heapq.heappushpop(m[i], score)\nres = []\nfor i in sorted(m.keys()):\n print(m[i])\n res.append(sum(m[i]) // 5)\nreturn res",
"m = defaultdict(list)\nfor r in results:\n if len(m... | <|body_start_0|>
m = defaultdict(list)
for i, score in items:
if len(m[i]) < 5:
heapq.heappush(m[i], score)
else:
heapq.heappushpop(m[i], score)
res = []
for i in sorted(m.keys()):
print(m[i])
res.append(sum(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def highFive(self, items):
""":type items: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def highFiveLint(self, results):
""":type items: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = d... | stack_v2_sparse_classes_10k_train_004166 | 2,399 | no_license | [
{
"docstring": ":type items: List[List[int]] :rtype: List[List[int]]",
"name": "highFive",
"signature": "def highFive(self, items)"
},
{
"docstring": ":type items: List[List[int]] :rtype: List[List[int]]",
"name": "highFiveLint",
"signature": "def highFiveLint(self, results)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000373 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def highFive(self, items): :type items: List[List[int]] :rtype: List[List[int]]
- def highFiveLint(self, results): :type items: List[List[int]] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def highFive(self, items): :type items: List[List[int]] :rtype: List[List[int]]
- def highFiveLint(self, results): :type items: List[List[int]] :rtype: List[List[int]]
<|skeleto... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def highFive(self, items):
""":type items: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def highFiveLint(self, results):
""":type items: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def highFive(self, items):
""":type items: List[List[int]] :rtype: List[List[int]]"""
m = defaultdict(list)
for i, score in items:
if len(m[i]) < 5:
heapq.heappush(m[i], score)
else:
heapq.heappushpop(m[i], score)
... | the_stack_v2_python_sparse | H/HighFive.py | bssrdf/pyleet | train | 2 | |
44ede86acf9a53b15995d2ab334bdd3ac589bf30 | [
"if not root:\n return ''\nqueue = deque([root])\nres = []\nwhile queue:\n node = queue.popleft()\n if node != SEPERATOR:\n res.append(str(node.val))\n for child in node.children:\n queue.append(child)\n queue.append(SEPERATOR)\n else:\n res.append(SEPERATOR)\nretu... | <|body_start_0|>
if not root:
return ''
queue = deque([root])
res = []
while queue:
node = queue.popleft()
if node != SEPERATOR:
res.append(str(node.val))
for child in node.children:
queue.append(chil... | 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_10k_train_004167 | 1,652 | 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_006556 | 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... | fdb6bcb4c721e03e853890dd89122f2c4196a1ea | <|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_10k | 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 ''
queue = deque([root])
res = []
while queue:
node = queue.popleft()
if node != SEPERATOR:
... | the_stack_v2_python_sparse | python/tree/SerializeAndDeserializeNaryTree.py | XifeiNi/LeetCode-Traversal | train | 2 | |
70e4adff849c53d2efc692d5a0b0b7be6a6948f3 | [
"m = {}\nfor index, num in enumerate(nums):\n if m.get(num, None):\n m[num][1].append(index)\n m[num][0] += 1\n else:\n m[num] = [1, [index]]\nfrequency_record = -1\nlength_record = -1\nfor num, info in m.items():\n length = info[1][-1] - info[1][0] + 1\n frequency = info[0]\n if... | <|body_start_0|>
m = {}
for index, num in enumerate(nums):
if m.get(num, None):
m[num][1].append(index)
m[num][0] += 1
else:
m[num] = [1, [index]]
frequency_record = -1
length_record = -1
for num, info in m.i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findShortestSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findShortestSubArray1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = {}
for index, ... | stack_v2_sparse_classes_10k_train_004168 | 1,968 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findShortestSubArray",
"signature": "def findShortestSubArray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findShortestSubArray1",
"signature": "def findShortestSubArray1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000323 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findShortestSubArray(self, nums): :type nums: List[int] :rtype: int
- def findShortestSubArray1(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 findShortestSubArray(self, nums): :type nums: List[int] :rtype: int
- def findShortestSubArray1(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def findShortestSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findShortestSubArray1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findShortestSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
m = {}
for index, num in enumerate(nums):
if m.get(num, None):
m[num][1].append(index)
m[num][0] += 1
else:
m[num] = [1, [inde... | the_stack_v2_python_sparse | python/leetcode_bak/697_Degree_of_an_Array.py | bobcaoge/my-code | train | 0 | |
2e275413053787a633f19bf3ead54ea946b1275c | [
"self.parent_view: Union[Subview, View] = parent_view\nself.base_view: View = self._get_base_view(parent_view)\nself.data: np.ndarray = parent_view.data[data_slice]\nself.array = kokkos.unmanaged_array(self.data, parent_view.dtype.value, parent_view.space.value)\nself.shape: List[int] = list(self.data.shape)\nself.... | <|body_start_0|>
self.parent_view: Union[Subview, View] = parent_view
self.base_view: View = self._get_base_view(parent_view)
self.data: np.ndarray = parent_view.data[data_slice]
self.array = kokkos.unmanaged_array(self.data, parent_view.dtype.value, parent_view.space.value)
self... | A Subview wraps the "data" member of a View (or Subview) and references a slice of that data. Subviews are passed to C++ as unmanaged views. This class contains the Python implementation of a subview. The user is not meant to call the constructor directly, instead they should slice the original View object. | Subview | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subview:
"""A Subview wraps the "data" member of a View (or Subview) and references a slice of that data. Subviews are passed to C++ as unmanaged views. This class contains the Python implementation of a subview. The user is not meant to call the constructor directly, instead they should slice th... | stack_v2_sparse_classes_10k_train_004169 | 12,649 | no_license | [
{
"docstring": "Subview constructor. :param parent_view: the View or Subview that is meant to be sliced :param data_slice: the slice of the parent_view",
"name": "__init__",
"signature": "def __init__(self, parent_view: Union[Subview, View], data_slice: Union[slice, Tuple])"
},
{
"docstring": "T... | 3 | stack_v2_sparse_classes_30k_train_007309 | Implement the Python class `Subview` described below.
Class description:
A Subview wraps the "data" member of a View (or Subview) and references a slice of that data. Subviews are passed to C++ as unmanaged views. This class contains the Python implementation of a subview. The user is not meant to call the constructor... | Implement the Python class `Subview` described below.
Class description:
A Subview wraps the "data" member of a View (or Subview) and references a slice of that data. Subviews are passed to C++ as unmanaged views. This class contains the Python implementation of a subview. The user is not meant to call the constructor... | f4c96b66d25d03a5c12bb2aef993273647a6f463 | <|skeleton|>
class Subview:
"""A Subview wraps the "data" member of a View (or Subview) and references a slice of that data. Subviews are passed to C++ as unmanaged views. This class contains the Python implementation of a subview. The user is not meant to call the constructor directly, instead they should slice th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Subview:
"""A Subview wraps the "data" member of a View (or Subview) and references a slice of that data. Subviews are passed to C++ as unmanaged views. This class contains the Python implementation of a subview. The user is not meant to call the constructor directly, instead they should slice the original Vi... | the_stack_v2_python_sparse | pykokkos/interface/views.py | yiorgb/pykokkos | train | 0 |
87549ddd9cc78c3d6f348873ffdd32e287d3a6c8 | [
"with self.assertRaises(wx.PyNoAppError):\n frame = wx.Frame(None)\n frame.Close()",
"app = wx.App()\nframe = wx.Frame(None)\nframe.Show()\nframe.Close()\napp.MainLoop()"
] | <|body_start_0|>
with self.assertRaises(wx.PyNoAppError):
frame = wx.Frame(None)
frame.Close()
<|end_body_0|>
<|body_start_1|>
app = wx.App()
frame = wx.Frame(None)
frame.Show()
frame.Close()
app.MainLoop()
<|end_body_1|>
| TestMustHaveApp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMustHaveApp:
def test_mustHaveApp0(self):
"""Test that an exception is raised if there is no app"""
<|body_0|>
def test_mustHaveApp1(self):
"""Create App and then create a frame"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
with self.assertRai... | stack_v2_sparse_classes_10k_train_004170 | 690 | no_license | [
{
"docstring": "Test that an exception is raised if there is no app",
"name": "test_mustHaveApp0",
"signature": "def test_mustHaveApp0(self)"
},
{
"docstring": "Create App and then create a frame",
"name": "test_mustHaveApp1",
"signature": "def test_mustHaveApp1(self)"
}
] | 2 | null | Implement the Python class `TestMustHaveApp` described below.
Class description:
Implement the TestMustHaveApp class.
Method signatures and docstrings:
- def test_mustHaveApp0(self): Test that an exception is raised if there is no app
- def test_mustHaveApp1(self): Create App and then create a frame | Implement the Python class `TestMustHaveApp` described below.
Class description:
Implement the TestMustHaveApp class.
Method signatures and docstrings:
- def test_mustHaveApp0(self): Test that an exception is raised if there is no app
- def test_mustHaveApp1(self): Create App and then create a frame
<|skeleton|>
cla... | a1184286703cf24c4b88e5bc14cf2979c1b1ea00 | <|skeleton|>
class TestMustHaveApp:
def test_mustHaveApp0(self):
"""Test that an exception is raised if there is no app"""
<|body_0|>
def test_mustHaveApp1(self):
"""Create App and then create a frame"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestMustHaveApp:
def test_mustHaveApp0(self):
"""Test that an exception is raised if there is no app"""
with self.assertRaises(wx.PyNoAppError):
frame = wx.Frame(None)
frame.Close()
def test_mustHaveApp1(self):
"""Create App and then create a frame"""
... | the_stack_v2_python_sparse | unittests/test_mustHaveApp.py | wxWidgets/Phoenix | train | 2,268 | |
884007d2bb2edf7b3683053dd508f9c70ebbe306 | [
"arguments.AddBackupResourceArg(parser, 'to list backups for')\nparser.display_info.AddFormat('\\n table(\\n name.basename():sort=1:label=NAME,\\n cluster():label=CLUSTER,\\n sourceTable.basename():label=TABLE,\\n expireTime:label=EXPIRE_TIME,\\n state... | <|body_start_0|>
arguments.AddBackupResourceArg(parser, 'to list backups for')
parser.display_info.AddFormat('\n table(\n name.basename():sort=1:label=NAME,\n cluster():label=CLUSTER,\n sourceTable.basename():label=TABLE,\n expireTime:label=EXPIRE_TIM... | List existing Bigtable backups. | ListBackups | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListBackups:
"""List existing Bigtable backups."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were... | stack_v2_sparse_classes_10k_train_004171 | 3,739 | permissive | [
{
"docstring": "Register flags for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Yields: Some value t... | 2 | stack_v2_sparse_classes_30k_train_002656 | Implement the Python class `ListBackups` described below.
Class description:
List existing Bigtable backups.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namespace. All th... | Implement the Python class `ListBackups` described below.
Class description:
List existing Bigtable backups.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namespace. All th... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class ListBackups:
"""List existing Bigtable backups."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ListBackups:
"""List existing Bigtable backups."""
def Args(parser):
"""Register flags for this command."""
arguments.AddBackupResourceArg(parser, 'to list backups for')
parser.display_info.AddFormat('\n table(\n name.basename():sort=1:label=NAME,\n ... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/bigtable/backups/list.py | bopopescu/socialliteapp | train | 0 |
4b11bbaaaa2c3d8554f629fa6da538eead1ae024 | [
"chr_location = models.ChromosomeLocation(species_id='taxonomy:9606', chr=location['chr'], interval=models.CytobandInterval(start=location['start'], end=location['end']))\nchr_location._id = ga4gh_identify(chr_location)\nreturn chr_location.as_dict()",
"if 'chr' in location and 'start' in location and ('end' in l... | <|body_start_0|>
chr_location = models.ChromosomeLocation(species_id='taxonomy:9606', chr=location['chr'], interval=models.CytobandInterval(start=location['start'], end=location['end']))
chr_location._id = ga4gh_identify(chr_location)
return chr_location.as_dict()
<|end_body_0|>
<|body_start_1|... | The class for GA4GH Chromosome Location. | ChromosomeLocation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChromosomeLocation:
"""The class for GA4GH Chromosome Location."""
def add_location(self, location):
"""Get a gene's Chromosome Location. :param dict location: A gene's location. :return: A dictionary of a GA4GH VRS ChromosomeLocation."""
<|body_0|>
def get_location(self... | stack_v2_sparse_classes_10k_train_004172 | 3,279 | permissive | [
{
"docstring": "Get a gene's Chromosome Location. :param dict location: A gene's location. :return: A dictionary of a GA4GH VRS ChromosomeLocation.",
"name": "add_location",
"signature": "def add_location(self, location)"
},
{
"docstring": "Transform a gene's location into a Chromosome Location.... | 3 | stack_v2_sparse_classes_30k_train_003293 | Implement the Python class `ChromosomeLocation` described below.
Class description:
The class for GA4GH Chromosome Location.
Method signatures and docstrings:
- def add_location(self, location): Get a gene's Chromosome Location. :param dict location: A gene's location. :return: A dictionary of a GA4GH VRS ChromosomeL... | Implement the Python class `ChromosomeLocation` described below.
Class description:
The class for GA4GH Chromosome Location.
Method signatures and docstrings:
- def add_location(self, location): Get a gene's Chromosome Location. :param dict location: A gene's location. :return: A dictionary of a GA4GH VRS ChromosomeL... | 6dd633c2590aa6a40247b1b48c2e3381225d89ab | <|skeleton|>
class ChromosomeLocation:
"""The class for GA4GH Chromosome Location."""
def add_location(self, location):
"""Get a gene's Chromosome Location. :param dict location: A gene's location. :return: A dictionary of a GA4GH VRS ChromosomeLocation."""
<|body_0|>
def get_location(self... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ChromosomeLocation:
"""The class for GA4GH Chromosome Location."""
def add_location(self, location):
"""Get a gene's Chromosome Location. :param dict location: A gene's location. :return: A dictionary of a GA4GH VRS ChromosomeLocation."""
chr_location = models.ChromosomeLocation(species_i... | the_stack_v2_python_sparse | gene/vrs_locations/chromosome_location.py | richardhj/gene-normalization | train | 0 |
abddb939990176bda53e17a35662b50bfea1ba86 | [
"errors = {}\nfor sub_resource in resource.get_sub_resources():\n try:\n cls.release_resource(sub_resource, username)\n except ServerError as ex:\n errors[sub_resource.name] = (ex.ERROR_CODE, str(ex))\nif resource.OWNABLE:\n if username is not None and resource.is_available(username):\n ... | <|body_start_0|>
errors = {}
for sub_resource in resource.get_sub_resources():
try:
cls.release_resource(sub_resource, username)
except ServerError as ex:
errors[sub_resource.name] = (ex.ERROR_CODE, str(ex))
if resource.OWNABLE:
... | Release the given resources one by one. For complex resource, marks also its sub-resources as free. Raises: ResourceReleaseError: if resource is a complex resource and fails. ResourcePermissionError: if resource is locked by other user. ResourceAlreadyAvailableError: if resource was already available. | ReleaseResources | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReleaseResources:
"""Release the given resources one by one. For complex resource, marks also its sub-resources as free. Raises: ResourceReleaseError: if resource is a complex resource and fails. ResourcePermissionError: if resource is locked by other user. ResourceAlreadyAvailableError: if resou... | stack_v2_sparse_classes_10k_train_004173 | 4,862 | permissive | [
{
"docstring": "Mark the resource as free. For complex resource, marks also its sub-resources as free. Args: resource (ResourceData): resource to release. username (str): name of the releasing user. Raises: ResourceReleaseError: if resource is a complex resource and fails. ResourcePermissionError: if resource i... | 2 | stack_v2_sparse_classes_30k_train_005732 | Implement the Python class `ReleaseResources` described below.
Class description:
Release the given resources one by one. For complex resource, marks also its sub-resources as free. Raises: ResourceReleaseError: if resource is a complex resource and fails. ResourcePermissionError: if resource is locked by other user. ... | Implement the Python class `ReleaseResources` described below.
Class description:
Release the given resources one by one. For complex resource, marks also its sub-resources as free. Raises: ResourceReleaseError: if resource is a complex resource and fails. ResourcePermissionError: if resource is locked by other user. ... | c443bc1b99e02f047adfcab9943966f0023f652c | <|skeleton|>
class ReleaseResources:
"""Release the given resources one by one. For complex resource, marks also its sub-resources as free. Raises: ResourceReleaseError: if resource is a complex resource and fails. ResourcePermissionError: if resource is locked by other user. ResourceAlreadyAvailableError: if resou... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReleaseResources:
"""Release the given resources one by one. For complex resource, marks also its sub-resources as free. Raises: ResourceReleaseError: if resource is a complex resource and fails. ResourcePermissionError: if resource is locked by other user. ResourceAlreadyAvailableError: if resource was alrea... | the_stack_v2_python_sparse | src/rotest/api/resource_control/release_resources.py | gregoil/rotest | train | 26 |
154a7b9d972ed9033495f161d622f4b10c38aa3a | [
"if args is None:\n args = []\nif context is None:\n context = {}\nif not context.get('closed', False):\n args.append(('state', '=', 'draft'))\nreturn super(account_period, self).name_search(cr, uid, name, args=args, operator='ilike', context=context, limit=limit)",
"if self.search(cr, uid, [('id', 'in',... | <|body_start_0|>
if args is None:
args = []
if context is None:
context = {}
if not context.get('closed', False):
args.append(('state', '=', 'draft'))
return super(account_period, self).name_search(cr, uid, name, args=args, operator='ilike', context=co... | account_period | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class account_period:
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
"""Inherit name_search method to display only open period unless order close period by sending closed=True in context @return: super name_search"""
<|body_0|>
def acti... | stack_v2_sparse_classes_10k_train_004174 | 16,800 | no_license | [
{
"docstring": "Inherit name_search method to display only open period unless order close period by sending closed=True in context @return: super name_search",
"name": "name_search",
"signature": "def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_train_003491 | Implement the Python class `account_period` described below.
Class description:
Implement the account_period class.
Method signatures and docstrings:
- def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100): Inherit name_search method to display only open period unless order close ... | Implement the Python class `account_period` described below.
Class description:
Implement the account_period class.
Method signatures and docstrings:
- def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100): Inherit name_search method to display only open period unless order close ... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class account_period:
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
"""Inherit name_search method to display only open period unless order close period by sending closed=True in context @return: super name_search"""
<|body_0|>
def acti... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class account_period:
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
"""Inherit name_search method to display only open period unless order close period by sending closed=True in context @return: super name_search"""
if args is None:
args = []... | the_stack_v2_python_sparse | v_7/Dongola/wafi/account_custom_wafi/account_custom(old).py | musabahmed/baba | train | 0 | |
570b83ef88f4cbe3562c4a7c7beb977671e8fec7 | [
"try:\n args = parser.parse_args()\n data = control.roles_users.role_user_list(args['user_name'], args['role_name'])\nexcept Exception as e:\n return (set_return_val(False, {}, str(e), 1234), 400)\nreturn set_return_val(True, data, '获取列表成功', 1234)",
"try:\n args = parser.parse_args()\n user_id = ar... | <|body_start_0|>
try:
args = parser.parse_args()
data = control.roles_users.role_user_list(args['user_name'], args['role_name'])
except Exception as e:
return (set_return_val(False, {}, str(e), 1234), 400)
return set_return_val(True, data, '获取列表成功', 1234)
<|en... | RolesUsersManage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RolesUsersManage:
def get(self):
"""获取用户角色列表 --- tags: - user_role parameters: - in: query type: string name: user_name description: 用户名 - in: query name: role_name type: string description: 角色名 responses: 200: description: 获取用户角色信息 schema: properties: ok: type: boolean default: 200 desc... | stack_v2_sparse_classes_10k_train_004175 | 8,276 | no_license | [
{
"docstring": "获取用户角色列表 --- tags: - user_role parameters: - in: query type: string name: user_name description: 用户名 - in: query name: role_name type: string description: 角色名 responses: 200: description: 获取用户角色信息 schema: properties: ok: type: boolean default: 200 description: 状态 code: type: string msg: type: st... | 4 | stack_v2_sparse_classes_30k_train_001660 | Implement the Python class `RolesUsersManage` described below.
Class description:
Implement the RolesUsersManage class.
Method signatures and docstrings:
- def get(self): 获取用户角色列表 --- tags: - user_role parameters: - in: query type: string name: user_name description: 用户名 - in: query name: role_name type: string descr... | Implement the Python class `RolesUsersManage` described below.
Class description:
Implement the RolesUsersManage class.
Method signatures and docstrings:
- def get(self): 获取用户角色列表 --- tags: - user_role parameters: - in: query type: string name: user_name description: 用户名 - in: query name: role_name type: string descr... | d25871dc66dfbd9f04e3d4d95843e39de286cfc8 | <|skeleton|>
class RolesUsersManage:
def get(self):
"""获取用户角色列表 --- tags: - user_role parameters: - in: query type: string name: user_name description: 用户名 - in: query name: role_name type: string description: 角色名 responses: 200: description: 获取用户角色信息 schema: properties: ok: type: boolean default: 200 desc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RolesUsersManage:
def get(self):
"""获取用户角色列表 --- tags: - user_role parameters: - in: query type: string name: user_name description: 用户名 - in: query name: role_name type: string description: 角色名 responses: 200: description: 获取用户角色信息 schema: properties: ok: type: boolean default: 200 description: 状态 co... | the_stack_v2_python_sparse | app/main/base/apis/roles_users.py | zcl-organization/naguan | train | 0 | |
5f8cbd0085f8006aaff0a569b132791de2f3397b | [
"if not root:\n return []\nq = deque()\nq.appendleft(root)\nresult = []\nwhile q:\n node = q.pop()\n if node:\n result.append(str(node.val))\n q.appendleft(node.left)\n q.appendleft(node.right)\n else:\n result.append('null')\nreturn result",
"if not data:\n return\ninde... | <|body_start_0|>
if not root:
return []
q = deque()
q.appendleft(root)
result = []
while q:
node = q.pop()
if node:
result.append(str(node.val))
q.appendleft(node.left)
q.appendleft(node.right)
... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_004176 | 3,122 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 6a83cb798cc317d1e4357ac6b2b1fbf76fa034fb | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
q = deque()
q.appendleft(root)
result = []
while q:
node = q.pop()
if node:
res... | the_stack_v2_python_sparse | Month 03/Week 03/Day 02/d.py | KevinKnott/Coding-Review | train | 0 | |
5e41fd0e70cd2e73f65b5541c5d7186e6043af6a | [
"begin, end, res = (0, 0, [])\npStillNeed = collections.Counter(p)\ncounter = len(pStillNeed)\nwhile end < len(s):\n c = s[end]\n if c in pStillNeed:\n pStillNeed[c] -= 1\n if pStillNeed[c] == 0:\n counter -= 1\n end += 1\n while counter == 0:\n tempc = s[begin]\n ... | <|body_start_0|>
begin, end, res = (0, 0, [])
pStillNeed = collections.Counter(p)
counter = len(pStillNeed)
while end < len(s):
c = s[end]
if c in pStillNeed:
pStillNeed[c] -= 1
if pStillNeed[c] == 0:
counter -= ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_0|>
def findAnagramsSlidingWindow(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
begin, end... | stack_v2_sparse_classes_10k_train_004177 | 2,550 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagrams",
"signature": "def findAnagrams(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagramsSlidingWindow",
"signature": "def findAnagramsSlidingWindow(self, s, p)"... | 2 | stack_v2_sparse_classes_30k_train_001806 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagramsSlidingWindow(self, s, p): :type s: str :type p: str :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagramsSlidingWindow(self, s, p): :type s: str :type p: str :rtype: List[int]
<|skeleton|>
c... | 7fa160362ebb58e7286b490012542baa2d51e5c9 | <|skeleton|>
class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_0|>
def findAnagramsSlidingWindow(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
begin, end, res = (0, 0, [])
pStillNeed = collections.Counter(p)
counter = len(pStillNeed)
while end < len(s):
c = s[end]
if c in pStillNeed:
... | the_stack_v2_python_sparse | substring/find_all_anagrams_in_string.py | gerrycfchang/leetcode-python | train | 2 | |
18d77dd3863b9e011dbbbf4f0089361ed26993ba | [
"super(Blank, self).__init__()\nself.__keywords = sorted(kw.keys())\nfor k, v in kw.iteritems():\n setattr(self, k, v)\nself.__isfrozen = True",
"if self.__isfrozen and (not hasattr(self, name)):\n raise AttributeError(\"Trying to set invalid attribute '%s'. Valid attributes are: %s.\" % (name, ', '.join(se... | <|body_start_0|>
super(Blank, self).__init__()
self.__keywords = sorted(kw.keys())
for k, v in kw.iteritems():
setattr(self, k, v)
self.__isfrozen = True
<|end_body_0|>
<|body_start_1|>
if self.__isfrozen and (not hasattr(self, name)):
raise AttributeErro... | Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use of arbitrary descriptors similar to dictionaries, but with simpler access... | Blank | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Blank:
"""Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use of arbitrary descriptors similar to dict... | stack_v2_sparse_classes_10k_train_004178 | 4,466 | permissive | [
{
"docstring": "Initializes the attributes given in keyword arguments. No new attribute is allowed after this.",
"name": "__init__",
"signature": "def __init__(self, **kw)"
},
{
"docstring": "Sets an attribute. If the attribute name was given during initialization, it's set to value. Raises an e... | 4 | stack_v2_sparse_classes_30k_train_004072 | Implement the Python class `Blank` described below.
Class description:
Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use o... | Implement the Python class `Blank` described below.
Class description:
Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use o... | c1bcca66a5ef1ff0ebd6373e3820e72dee6b0b70 | <|skeleton|>
class Blank:
"""Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use of arbitrary descriptors similar to dict... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Blank:
"""Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use of arbitrary descriptors similar to dictionaries, but... | the_stack_v2_python_sparse | mir3/data/blank.py | pymir3/pymir3 | train | 13 |
946dc54231e6c560fde952e1fbd64907e1da3f72 | [
"Inventory.__init__(self, product_code, description, market_price, rental_price)\nself.brand = brand\nself.voltage = voltage",
"output_dict = {}\noutput_dict['product_code'] = self.product_code\noutput_dict['description'] = self.description\noutput_dict['market_price'] = self.market_price\noutput_dict['rental_pri... | <|body_start_0|>
Inventory.__init__(self, product_code, description, market_price, rental_price)
self.brand = brand
self.voltage = voltage
<|end_body_0|>
<|body_start_1|>
output_dict = {}
output_dict['product_code'] = self.product_code
output_dict['description'] = self.d... | ElectricAppliances class | ElectricAppliances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElectricAppliances:
"""ElectricAppliances class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
""":param product_code: :param description: :param market_price: :param rental_price: :param brand: :param voltage:"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_004179 | 1,089 | no_license | [
{
"docstring": ":param product_code: :param description: :param market_price: :param rental_price: :param brand: :param voltage:",
"name": "__init__",
"signature": "def __init__(self, product_code, description, market_price, rental_price, brand, voltage)"
},
{
"docstring": ":return:",
"name"... | 2 | stack_v2_sparse_classes_30k_train_004910 | Implement the Python class `ElectricAppliances` described below.
Class description:
ElectricAppliances class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): :param product_code: :param description: :param market_price: :param rental_price:... | Implement the Python class `ElectricAppliances` described below.
Class description:
ElectricAppliances class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): :param product_code: :param description: :param market_price: :param rental_price:... | 6ffd7b4ab8346076d3b6cc02ca1ebca3bf028697 | <|skeleton|>
class ElectricAppliances:
"""ElectricAppliances class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
""":param product_code: :param description: :param market_price: :param rental_price: :param brand: :param voltage:"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ElectricAppliances:
"""ElectricAppliances class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
""":param product_code: :param description: :param market_price: :param rental_price: :param brand: :param voltage:"""
Inventory.__init__(self, pro... | the_stack_v2_python_sparse | students/jsward/lesson01/assignment/inventory_management/electric_appliances.py | UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019 | train | 4 |
847c02a4e39af8f9bebd87081d62aceeede77984 | [
"name = None\nif 'name' in kwargs:\n name = kwargs.pop('name')\nsuper().__init__(*args, **kwargs)\nif name:\n self.fields['file'].label = _(f'{name.title()} File')\n self.fields['file'].help_text = _(f'Select {name} file to upload')",
"file = self.cleaned_data['file']\nFileManager.validate(file)\nreturn ... | <|body_start_0|>
name = None
if 'name' in kwargs:
name = kwargs.pop('name')
super().__init__(*args, **kwargs)
if name:
self.fields['file'].label = _(f'{name.title()} File')
self.fields['file'].help_text = _(f'Select {name} file to upload')
<|end_body_0... | Step 1 of FileManagementFormView. | UploadFileForm | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadFileForm:
"""Step 1 of FileManagementFormView."""
def __init__(self, *args, **kwargs):
"""Update label and help_text."""
<|body_0|>
def clean_file(self):
"""Run tabular file validation. If anything is wrong with the file, it will raise ValidationError"""
... | stack_v2_sparse_classes_10k_train_004180 | 6,816 | permissive | [
{
"docstring": "Update label and help_text.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Run tabular file validation. If anything is wrong with the file, it will raise ValidationError",
"name": "clean_file",
"signature": "def clean_file(self... | 2 | stack_v2_sparse_classes_30k_train_000871 | Implement the Python class `UploadFileForm` described below.
Class description:
Step 1 of FileManagementFormView.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Update label and help_text.
- def clean_file(self): Run tabular file validation. If anything is wrong with the file, it will raise ... | Implement the Python class `UploadFileForm` described below.
Class description:
Step 1 of FileManagementFormView.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Update label and help_text.
- def clean_file(self): Run tabular file validation. If anything is wrong with the file, it will raise ... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class UploadFileForm:
"""Step 1 of FileManagementFormView."""
def __init__(self, *args, **kwargs):
"""Update label and help_text."""
<|body_0|>
def clean_file(self):
"""Run tabular file validation. If anything is wrong with the file, it will raise ValidationError"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UploadFileForm:
"""Step 1 of FileManagementFormView."""
def __init__(self, *args, **kwargs):
"""Update label and help_text."""
name = None
if 'name' in kwargs:
name = kwargs.pop('name')
super().__init__(*args, **kwargs)
if name:
self.fields[... | the_stack_v2_python_sparse | InvenTree/common/forms.py | inventree/InvenTree | train | 3,077 |
712328b9342690f14a4a9983a8ae3fdc963e78ab | [
"for val in ['string', 1.5]:\n with self.subTest(x=1):\n self.assertRaises(TypeError, factorize, val)",
"for i in (-1, -10, -100):\n with self.subTest(x=2):\n self.assertRaises(ValueError, factorize, i)",
"for key, val in [(0, (0,)), (1, (1,))]:\n with self.subTest(x=3):\n self.ass... | <|body_start_0|>
for val in ['string', 1.5]:
with self.subTest(x=1):
self.assertRaises(TypeError, factorize, val)
<|end_body_0|>
<|body_start_1|>
for i in (-1, -10, -100):
with self.subTest(x=2):
self.assertRaises(ValueError, factorize, i)
<|end_b... | TestFactorize | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFactorize:
def test_wrong_types_raise_exception(self):
"""test_wrong_types_raise_exception - проверяет, что передаваемый в функцию аргумент типа float или str вызывает исключение TypeError. Тестовый набор входных данных: 'string', 1.5"""
<|body_0|>
def test_negative(self... | stack_v2_sparse_classes_10k_train_004181 | 3,111 | no_license | [
{
"docstring": "test_wrong_types_raise_exception - проверяет, что передаваемый в функцию аргумент типа float или str вызывает исключение TypeError. Тестовый набор входных данных: 'string', 1.5",
"name": "test_wrong_types_raise_exception",
"signature": "def test_wrong_types_raise_exception(self)"
},
... | 6 | stack_v2_sparse_classes_30k_train_000523 | Implement the Python class `TestFactorize` described below.
Class description:
Implement the TestFactorize class.
Method signatures and docstrings:
- def test_wrong_types_raise_exception(self): test_wrong_types_raise_exception - проверяет, что передаваемый в функцию аргумент типа float или str вызывает исключение Typ... | Implement the Python class `TestFactorize` described below.
Class description:
Implement the TestFactorize class.
Method signatures and docstrings:
- def test_wrong_types_raise_exception(self): test_wrong_types_raise_exception - проверяет, что передаваемый в функцию аргумент типа float или str вызывает исключение Typ... | c1ff0d6fd4371a86b5f10e5220353eaa7e63d6ca | <|skeleton|>
class TestFactorize:
def test_wrong_types_raise_exception(self):
"""test_wrong_types_raise_exception - проверяет, что передаваемый в функцию аргумент типа float или str вызывает исключение TypeError. Тестовый набор входных данных: 'string', 1.5"""
<|body_0|>
def test_negative(self... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestFactorize:
def test_wrong_types_raise_exception(self):
"""test_wrong_types_raise_exception - проверяет, что передаваемый в функцию аргумент типа float или str вызывает исключение TypeError. Тестовый набор входных данных: 'string', 1.5"""
for val in ['string', 1.5]:
with self.su... | the_stack_v2_python_sparse | course_2/week_01/06_factorize.py | flanker-d/coursera_python | train | 0 | |
eff6e0b49dee7e51b28edb61300870e80bc9f8e1 | [
"filename = TRUKeywords.download_tru()\nself.assertTrue(path.exists(filename))\nremove(filename)\nfilename = TRUKeywords.download_tru(file_name='tru.zip')\nself.assertTrue(path.exists('tru.zip'))\nremove(filename)\nret_file_path = TRUKeywords.download_tru(file_type='tarball')\nself.assertTrue(path.exists(ret_file_p... | <|body_start_0|>
filename = TRUKeywords.download_tru()
self.assertTrue(path.exists(filename))
remove(filename)
filename = TRUKeywords.download_tru(file_name='tru.zip')
self.assertTrue(path.exists('tru.zip'))
remove(filename)
ret_file_path = TRUKeywords.download_tr... | Unit tests for TRUKeywords | TruTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TruTests:
"""Unit tests for TRUKeywords"""
def test_download_latest(self):
"""Test latest versions"""
<|body_0|>
def test_download_specific(self):
"""Test specific versions"""
<|body_1|>
def test_run_tru(self):
"""Test full run and retrieval"... | stack_v2_sparse_classes_10k_train_004182 | 10,750 | no_license | [
{
"docstring": "Test latest versions",
"name": "test_download_latest",
"signature": "def test_download_latest(self)"
},
{
"docstring": "Test specific versions",
"name": "test_download_specific",
"signature": "def test_download_specific(self)"
},
{
"docstring": "Test full run and ... | 3 | null | Implement the Python class `TruTests` described below.
Class description:
Unit tests for TRUKeywords
Method signatures and docstrings:
- def test_download_latest(self): Test latest versions
- def test_download_specific(self): Test specific versions
- def test_run_tru(self): Test full run and retrieval | Implement the Python class `TruTests` described below.
Class description:
Unit tests for TRUKeywords
Method signatures and docstrings:
- def test_download_latest(self): Test latest versions
- def test_download_specific(self): Test specific versions
- def test_run_tru(self): Test full run and retrieval
<|skeleton|>
c... | 24a74926170cbdfafa47e972644e2fe5b627d8ff | <|skeleton|>
class TruTests:
"""Unit tests for TRUKeywords"""
def test_download_latest(self):
"""Test latest versions"""
<|body_0|>
def test_download_specific(self):
"""Test specific versions"""
<|body_1|>
def test_run_tru(self):
"""Test full run and retrieval"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TruTests:
"""Unit tests for TRUKeywords"""
def test_download_latest(self):
"""Test latest versions"""
filename = TRUKeywords.download_tru()
self.assertTrue(path.exists(filename))
remove(filename)
filename = TRUKeywords.download_tru(file_name='tru.zip')
self... | the_stack_v2_python_sparse | robo4.2/fusion/FusionLibrary/keywords/tru.py | richa92/Jenkin_Regression_Testing | train | 0 |
5cdce8d3b987cd4adfd5cd2f3a2ad6c73b80dfa6 | [
"super().__init__(*args, **kwargs)\ngroup_choices = Group.objects.all().values_list('pk', 'name').order_by('name')\nselected_group_ids = []\nif 'instance' in kwargs:\n preset = kwargs['instance']\n selected_group_ids = [group.pk for group in preset.groups_with_permission(Permission.VIEW)]\nself.fields['groups... | <|body_start_0|>
super().__init__(*args, **kwargs)
group_choices = Group.objects.all().values_list('pk', 'name').order_by('name')
selected_group_ids = []
if 'instance' in kwargs:
preset = kwargs['instance']
selected_group_ids = [group.pk for group in preset.groups... | Form for AnnotationPreset admin page. | AnnotationPresetForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnnotationPresetForm:
"""Form for AnnotationPreset admin page."""
def __init__(self, *args, **kwargs):
"""Set the groups choices and initial value."""
<|body_0|>
def save(self, commit):
"""Save changes made to the preset."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_004183 | 2,462 | permissive | [
{
"docstring": "Set the groups choices and initial value.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Save changes made to the preset.",
"name": "save",
"signature": "def save(self, commit)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006918 | Implement the Python class `AnnotationPresetForm` described below.
Class description:
Form for AnnotationPreset admin page.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Set the groups choices and initial value.
- def save(self, commit): Save changes made to the preset. | Implement the Python class `AnnotationPresetForm` described below.
Class description:
Form for AnnotationPreset admin page.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Set the groups choices and initial value.
- def save(self, commit): Save changes made to the preset.
<|skeleton|>
class ... | 25c0c45235ef37beb45c1af4c917fbbae6282016 | <|skeleton|>
class AnnotationPresetForm:
"""Form for AnnotationPreset admin page."""
def __init__(self, *args, **kwargs):
"""Set the groups choices and initial value."""
<|body_0|>
def save(self, commit):
"""Save changes made to the preset."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AnnotationPresetForm:
"""Form for AnnotationPreset admin page."""
def __init__(self, *args, **kwargs):
"""Set the groups choices and initial value."""
super().__init__(*args, **kwargs)
group_choices = Group.objects.all().values_list('pk', 'name').order_by('name')
selected_... | the_stack_v2_python_sparse | resolwe/flow/admin.py | genialis/resolwe | train | 35 |
25c42d4b23294fbd3df79e038134f53debdec550 | [
"name = clean_name(name)\ndistrict = clean_string(district).replace('&', 'and')\nrole = clean_string(role)\nif role == 'City Councillor':\n role = 'Councillor'\nfor k, v in kwargs.items():\n if isinstance(v, str):\n kwargs[k] = clean_string(v)\nif not district:\n raise Exception('No district')\nsupe... | <|body_start_0|>
name = clean_name(name)
district = clean_string(district).replace('&', 'and')
role = clean_string(role)
if role == 'City Councillor':
role = 'Councillor'
for k, v in kwargs.items():
if isinstance(v, str):
kwargs[k] = clean_... | CanadianPerson | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanadianPerson:
def __init__(self, *, name, district, role, **kwargs):
"""Cleans a person's name, district, role and any other attributes."""
<|body_0|>
def __setattr__(self, name, value):
"""Corrects gender values."""
<|body_1|>
def add_link(self, url, ... | stack_v2_sparse_classes_10k_train_004184 | 27,455 | permissive | [
{
"docstring": "Cleans a person's name, district, role and any other attributes.",
"name": "__init__",
"signature": "def __init__(self, *, name, district, role, **kwargs)"
},
{
"docstring": "Corrects gender values.",
"name": "__setattr__",
"signature": "def __setattr__(self, name, value)... | 6 | stack_v2_sparse_classes_30k_train_007255 | Implement the Python class `CanadianPerson` described below.
Class description:
Implement the CanadianPerson class.
Method signatures and docstrings:
- def __init__(self, *, name, district, role, **kwargs): Cleans a person's name, district, role and any other attributes.
- def __setattr__(self, name, value): Corrects... | Implement the Python class `CanadianPerson` described below.
Class description:
Implement the CanadianPerson class.
Method signatures and docstrings:
- def __init__(self, *, name, district, role, **kwargs): Cleans a person's name, district, role and any other attributes.
- def __setattr__(self, name, value): Corrects... | ef7bd9990e2a31c731d3bd1e7c2616fbfa7f2882 | <|skeleton|>
class CanadianPerson:
def __init__(self, *, name, district, role, **kwargs):
"""Cleans a person's name, district, role and any other attributes."""
<|body_0|>
def __setattr__(self, name, value):
"""Corrects gender values."""
<|body_1|>
def add_link(self, url, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CanadianPerson:
def __init__(self, *, name, district, role, **kwargs):
"""Cleans a person's name, district, role and any other attributes."""
name = clean_name(name)
district = clean_string(district).replace('&', 'and')
role = clean_string(role)
if role == 'City Council... | the_stack_v2_python_sparse | utils.py | opencivicdata/scrapers-ca | train | 21 | |
6c45bf8ab80c5c4a955e7bd9e9d7d4e6f8216ab5 | [
"self.num_in = num_in\nself.number_of_nodes = number_of_nodes\nself.weights = self.init_weights(activation)\nself.output = activation(T.dot(input, self.weights))\nself.params = [self.weights]",
"weights = np.asarray(np.random.uniform(low=-np.sqrt(6.0 / (self.num_in + self.number_of_nodes)), high=np.sqrt(6.0 / (se... | <|body_start_0|>
self.num_in = num_in
self.number_of_nodes = number_of_nodes
self.weights = self.init_weights(activation)
self.output = activation(T.dot(input, self.weights))
self.params = [self.weights]
<|end_body_0|>
<|body_start_1|>
weights = np.asarray(np.random.unif... | HiddenLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HiddenLayer:
def __init__(self, input, num_in, number_of_nodes, activation):
"""A hidden layer in an artifical neural network is defined by the output of the activation function of the previous layer, the number of incoming neurons connected to the layer, the amount of neurons in the lay... | stack_v2_sparse_classes_10k_train_004185 | 2,621 | permissive | [
{
"docstring": "A hidden layer in an artifical neural network is defined by the output of the activation function of the previous layer, the number of incoming neurons connected to the layer, the amount of neurons in the layer and an activation function. :param input: the output of the activation function in th... | 2 | stack_v2_sparse_classes_30k_train_002517 | Implement the Python class `HiddenLayer` described below.
Class description:
Implement the HiddenLayer class.
Method signatures and docstrings:
- def __init__(self, input, num_in, number_of_nodes, activation): A hidden layer in an artifical neural network is defined by the output of the activation function of the pre... | Implement the Python class `HiddenLayer` described below.
Class description:
Implement the HiddenLayer class.
Method signatures and docstrings:
- def __init__(self, input, num_in, number_of_nodes, activation): A hidden layer in an artifical neural network is defined by the output of the activation function of the pre... | 79f3b4a5f624d473b461548b263bcf7ecc0846dc | <|skeleton|>
class HiddenLayer:
def __init__(self, input, num_in, number_of_nodes, activation):
"""A hidden layer in an artifical neural network is defined by the output of the activation function of the previous layer, the number of incoming neurons connected to the layer, the amount of neurons in the lay... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HiddenLayer:
def __init__(self, input, num_in, number_of_nodes, activation):
"""A hidden layer in an artifical neural network is defined by the output of the activation function of the previous layer, the number of incoming neurons connected to the layer, the amount of neurons in the layer and an acti... | the_stack_v2_python_sparse | project3/module5/deeplearning/layer.py | pmitche/it3105-aiprogramming | train | 3 | |
33b6c6f27bcc2cea48c3537844e64223486a258d | [
"opens = '([{'\ncloses = ')]}'\nparstack = Stack()\nbalance = True\nfor each in s:\n if each in '([{':\n parstack.push(each)\n elif parstack.isEmpty():\n balance = False\n else:\n top = parstack.pop()\n if opens.index(top) != closes.index(each):\n balance = False\nif ... | <|body_start_0|>
opens = '([{'
closes = ')]}'
parstack = Stack()
balance = True
for each in s:
if each in '([{':
parstack.push(each)
elif parstack.isEmpty():
balance = False
else:
top = parstack.p... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValid_stack(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isValid(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
def isValid_similar(self, s):
"""time O(n) space O(n) :param s: :return:"""
<|body_2|>
<|en... | stack_v2_sparse_classes_10k_train_004186 | 1,928 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "isValid_stack",
"signature": "def isValid_stack(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "isValid",
"signature": "def isValid(self, s)"
},
{
"docstring": "time O(n) space O(n) :param s: :return:",
"n... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid_stack(self, s): :type s: str :rtype: bool
- def isValid(self, s): :type s: str :rtype: bool
- def isValid_similar(self, s): time O(n) space O(n) :param s: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid_stack(self, s): :type s: str :rtype: bool
- def isValid(self, s): :type s: str :rtype: bool
- def isValid_similar(self, s): time O(n) space O(n) :param s: :return:
<... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def isValid_stack(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isValid(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
def isValid_similar(self, s):
"""time O(n) space O(n) :param s: :return:"""
<|body_2|>
<|en... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isValid_stack(self, s):
""":type s: str :rtype: bool"""
opens = '([{'
closes = ')]}'
parstack = Stack()
balance = True
for each in s:
if each in '([{':
parstack.push(each)
elif parstack.isEmpty():
... | the_stack_v2_python_sparse | LeetCode/Stack/20_Stack_valid_parentheses.py | XyK0907/for_work | train | 0 | |
773f0d381695cf9ab75154a5b6097d25f537d590 | [
"self = super().__new__(cls)\nif not isinstance(func, T.Callable):\n out_dtype = in_dtype\n in_dtype = func\n func = None\nif func is not None:\n self.__init__(in_dtype, out_dtype)\n return self(func)\nreturn self",
"super().__init__()\nself._in_dtype = in_dtype\nself._out_dtype = out_dtype\nreturn... | <|body_start_0|>
self = super().__new__(cls)
if not isinstance(func, T.Callable):
out_dtype = in_dtype
in_dtype = func
func = None
if func is not None:
self.__init__(in_dtype, out_dtype)
return self(func)
return self
<|end_body_... | Ensure arguments are type *dtype*. Parameters ---------- func : function, optional function to decorate inargs : list [(index, dtype), ...] outargs : list [(index, dtype), ...] these arguments, except func, should be specified by key word if inargs is forgotten and func is not a function, then func is assumed to be ina... | dtypeDecorator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dtypeDecorator:
"""Ensure arguments are type *dtype*. Parameters ---------- func : function, optional function to decorate inargs : list [(index, dtype), ...] outargs : list [(index, dtype), ...] these arguments, except func, should be specified by key word if inargs is forgotten and func is not ... | stack_v2_sparse_classes_10k_train_004187 | 19,204 | permissive | [
{
"docstring": "New dtypeDecorator.",
"name": "__new__",
"signature": "def __new__(cls, func: T.Optional[T.Callable]=None, in_dtype: T.Any=None, out_dtype: T.Any=None)"
},
{
"docstring": "Initialize dtypeDecorator.",
"name": "__init__",
"signature": "def __init__(self, in_dtype: T.Any=No... | 3 | stack_v2_sparse_classes_30k_train_001411 | Implement the Python class `dtypeDecorator` described below.
Class description:
Ensure arguments are type *dtype*. Parameters ---------- func : function, optional function to decorate inargs : list [(index, dtype), ...] outargs : list [(index, dtype), ...] these arguments, except func, should be specified by key word ... | Implement the Python class `dtypeDecorator` described below.
Class description:
Ensure arguments are type *dtype*. Parameters ---------- func : function, optional function to decorate inargs : list [(index, dtype), ...] outargs : list [(index, dtype), ...] these arguments, except func, should be specified by key word ... | 17984942145d31126724df23500bafba18fb7516 | <|skeleton|>
class dtypeDecorator:
"""Ensure arguments are type *dtype*. Parameters ---------- func : function, optional function to decorate inargs : list [(index, dtype), ...] outargs : list [(index, dtype), ...] these arguments, except func, should be specified by key word if inargs is forgotten and func is not ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class dtypeDecorator:
"""Ensure arguments are type *dtype*. Parameters ---------- func : function, optional function to decorate inargs : list [(index, dtype), ...] outargs : list [(index, dtype), ...] these arguments, except func, should be specified by key word if inargs is forgotten and func is not a function, t... | the_stack_v2_python_sparse | utilipy/decorators/func_io.py | nstarman/utilipy | train | 2 |
ea323a40e1a18d08974ed9dc7e44ef8a46fd45e6 | [
"super().__init__()\nself.momentum = momentum\nself.inv_momentum = 1.0 - momentum\nself.crops_for_assign = crops_for_assign\nself.is_distributed = False\nself.momentum_eval_mode_iter_start = momentum_eval_mode_iter_start",
"logging.info('Building momentum encoder - rank %s %s', *get_machine_local_and_dist_rank())... | <|body_start_0|>
super().__init__()
self.momentum = momentum
self.inv_momentum = 1.0 - momentum
self.crops_for_assign = crops_for_assign
self.is_distributed = False
self.momentum_eval_mode_iter_start = momentum_eval_mode_iter_start
<|end_body_0|>
<|body_start_1|>
... | This hook is for the extension of the SwAV loss proposed in paper https://arxiv.org/abs/2006.09882 by Caron et al. The loss combines the benefits of using the SwAV approach with the momentum encoder as used in MoCo. | SwAVMomentumHook | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwAVMomentumHook:
"""This hook is for the extension of the SwAV loss proposed in paper https://arxiv.org/abs/2006.09882 by Caron et al. The loss combines the benefits of using the SwAV approach with the momentum encoder as used in MoCo."""
def __init__(self, momentum: float, momentum_eval_mo... | stack_v2_sparse_classes_10k_train_004188 | 7,963 | permissive | [
{
"docstring": "Args: momentum (float): for the momentum encoder momentum_eval_mode_iter_start (int): from what iteration should the momentum encoder network be in eval mode crops_for_assign (List[int]): what crops to use for assignment",
"name": "__init__",
"signature": "def __init__(self, momentum: fl... | 4 | null | Implement the Python class `SwAVMomentumHook` described below.
Class description:
This hook is for the extension of the SwAV loss proposed in paper https://arxiv.org/abs/2006.09882 by Caron et al. The loss combines the benefits of using the SwAV approach with the momentum encoder as used in MoCo.
Method signatures an... | Implement the Python class `SwAVMomentumHook` described below.
Class description:
This hook is for the extension of the SwAV loss proposed in paper https://arxiv.org/abs/2006.09882 by Caron et al. The loss combines the benefits of using the SwAV approach with the momentum encoder as used in MoCo.
Method signatures an... | b647c256447af7ea66655811849be1f642377db8 | <|skeleton|>
class SwAVMomentumHook:
"""This hook is for the extension of the SwAV loss proposed in paper https://arxiv.org/abs/2006.09882 by Caron et al. The loss combines the benefits of using the SwAV approach with the momentum encoder as used in MoCo."""
def __init__(self, momentum: float, momentum_eval_mo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SwAVMomentumHook:
"""This hook is for the extension of the SwAV loss proposed in paper https://arxiv.org/abs/2006.09882 by Caron et al. The loss combines the benefits of using the SwAV approach with the momentum encoder as used in MoCo."""
def __init__(self, momentum: float, momentum_eval_mode_iter_start... | the_stack_v2_python_sparse | vissl/hooks/swav_momentum_hooks.py | pzharrington/vissl | train | 1 |
6a8cd2950f6b94c5d9344334fede04012c162db9 | [
"alpha = np.where(x < x_break, alpha_1, alpha_2)\nxx = x / x_break\nreturn amplitude * xx ** (-alpha)",
"alpha = np.where(x < x_break, alpha_1, alpha_2)\nxx = x / x_break\nd_amplitude = xx ** (-alpha)\nd_x_break = amplitude * alpha * d_amplitude / x_break\nd_alpha = -amplitude * d_amplitude * np.log(xx)\nd_alpha_... | <|body_start_0|>
alpha = np.where(x < x_break, alpha_1, alpha_2)
xx = x / x_break
return amplitude * xx ** (-alpha)
<|end_body_0|>
<|body_start_1|>
alpha = np.where(x < x_break, alpha_1, alpha_2)
xx = x / x_break
d_amplitude = xx ** (-alpha)
d_x_break = amplitude... | One dimensional power law model with a break. Parameters ---------- amplitude : float Model amplitude at the break point x_break : float Break point alpha_1 : float Power law index for x < x_break alpha_2 : float Power law index for x > x_break See Also -------- PowerLaw1D, ExponentialCutoffPowerLaw1D, LogParabola1D No... | BrokenPowerLaw1D | [
"Python-2.0",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrokenPowerLaw1D:
"""One dimensional power law model with a break. Parameters ---------- amplitude : float Model amplitude at the break point x_break : float Break point alpha_1 : float Power law index for x < x_break alpha_2 : float Power law index for x > x_break See Also -------- PowerLaw1D, E... | stack_v2_sparse_classes_10k_train_004189 | 6,539 | permissive | [
{
"docstring": "One dimensional broken power law model function",
"name": "evaluate",
"signature": "def evaluate(x, amplitude, x_break, alpha_1, alpha_2)"
},
{
"docstring": "One dimensional broken power law derivative with respect to parameters",
"name": "fit_deriv",
"signature": "def fi... | 2 | stack_v2_sparse_classes_30k_train_001069 | Implement the Python class `BrokenPowerLaw1D` described below.
Class description:
One dimensional power law model with a break. Parameters ---------- amplitude : float Model amplitude at the break point x_break : float Break point alpha_1 : float Power law index for x < x_break alpha_2 : float Power law index for x > ... | Implement the Python class `BrokenPowerLaw1D` described below.
Class description:
One dimensional power law model with a break. Parameters ---------- amplitude : float Model amplitude at the break point x_break : float Break point alpha_1 : float Power law index for x < x_break alpha_2 : float Power law index for x > ... | 2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6 | <|skeleton|>
class BrokenPowerLaw1D:
"""One dimensional power law model with a break. Parameters ---------- amplitude : float Model amplitude at the break point x_break : float Break point alpha_1 : float Power law index for x < x_break alpha_2 : float Power law index for x > x_break See Also -------- PowerLaw1D, E... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BrokenPowerLaw1D:
"""One dimensional power law model with a break. Parameters ---------- amplitude : float Model amplitude at the break point x_break : float Break point alpha_1 : float Power law index for x < x_break alpha_2 : float Power law index for x > x_break See Also -------- PowerLaw1D, ExponentialCut... | the_stack_v2_python_sparse | lib/python2.7/site-packages/astropy/modeling/powerlaws.py | wangyum/Anaconda | train | 11 |
c0198bd760324f7637a1012c4d35c3abdb8b40a5 | [
"if old in old2new:\n return old2new[old]\nnew = UndirectedGraphNode(old.label)\nnew.neighbors = [None] * len(old.neighbors)\nold2new[old] = new\nfor i, old_neighbor in enumerate(old.neighbors):\n new_neighbor = self._clone(old_neighbor, old2new)\n new.neighbors[i] = new_neighbor\nreturn new",
"if not no... | <|body_start_0|>
if old in old2new:
return old2new[old]
new = UndirectedGraphNode(old.label)
new.neighbors = [None] * len(old.neighbors)
old2new[old] = new
for i, old_neighbor in enumerate(old.neighbors):
new_neighbor = self._clone(old_neighbor, old2new)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _clone(self, old, old2new):
"""d maps old node to new neighbors"""
<|body_0|>
def cloneGraph(self, node):
""":type node: UndirectedGraphNode :rtype: UndirectedGraphNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if old in old2new:... | stack_v2_sparse_classes_10k_train_004190 | 938 | no_license | [
{
"docstring": "d maps old node to new neighbors",
"name": "_clone",
"signature": "def _clone(self, old, old2new)"
},
{
"docstring": ":type node: UndirectedGraphNode :rtype: UndirectedGraphNode",
"name": "cloneGraph",
"signature": "def cloneGraph(self, node)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _clone(self, old, old2new): d maps old node to new neighbors
- def cloneGraph(self, node): :type node: UndirectedGraphNode :rtype: UndirectedGraphNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _clone(self, old, old2new): d maps old node to new neighbors
- def cloneGraph(self, node): :type node: UndirectedGraphNode :rtype: UndirectedGraphNode
<|skeleton|>
class Sol... | 20580185c6f72f3c09a725168af48893156161f5 | <|skeleton|>
class Solution:
def _clone(self, old, old2new):
"""d maps old node to new neighbors"""
<|body_0|>
def cloneGraph(self, node):
""":type node: UndirectedGraphNode :rtype: UndirectedGraphNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def _clone(self, old, old2new):
"""d maps old node to new neighbors"""
if old in old2new:
return old2new[old]
new = UndirectedGraphNode(old.label)
new.neighbors = [None] * len(old.neighbors)
old2new[old] = new
for i, old_neighbor in enumera... | the_stack_v2_python_sparse | coding/00133-clone-graph/solution.py | misaka-10032/leetcode | train | 3 | |
af3322ad957a08f4130ddcb02cf4667c40221731 | [
"def dp(lo, hi, memo):\n if lo >= hi:\n return 0\n if (lo, hi) not in memo:\n ans = float('inf')\n for x in range(lo, hi + 1):\n ans = min(ans, x + max(dp(lo, x - 1, memo), dp(x + 1, hi, memo)))\n memo[lo, hi] = ans\n return memo[lo, hi]\nreturn dp(1, n, {})",
"dp =... | <|body_start_0|>
def dp(lo, hi, memo):
if lo >= hi:
return 0
if (lo, hi) not in memo:
ans = float('inf')
for x in range(lo, hi + 1):
ans = min(ans, x + max(dp(lo, x - 1, memo), dp(x + 1, hi, memo)))
memo[... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getMoneyAmount(self, n: int) -> int:
"""intuition: we want to find out the minimum cost to gurantee a win. Initially we only know that the secret number is within 1 to n; as we progress in the game, the lower and higher bound of the secrete number is getting smaller and sma... | stack_v2_sparse_classes_10k_train_004191 | 3,662 | no_license | [
{
"docstring": "intuition: we want to find out the minimum cost to gurantee a win. Initially we only know that the secret number is within 1 to n; as we progress in the game, the lower and higher bound of the secrete number is getting smaller and smaller. Without lose generality, let's assume we want to find th... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getMoneyAmount(self, n: int) -> int: intuition: we want to find out the minimum cost to gurantee a win. Initially we only know that the secret number is within 1 to n; as we ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getMoneyAmount(self, n: int) -> int: intuition: we want to find out the minimum cost to gurantee a win. Initially we only know that the secret number is within 1 to n; as we ... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def getMoneyAmount(self, n: int) -> int:
"""intuition: we want to find out the minimum cost to gurantee a win. Initially we only know that the secret number is within 1 to n; as we progress in the game, the lower and higher bound of the secrete number is getting smaller and sma... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def getMoneyAmount(self, n: int) -> int:
"""intuition: we want to find out the minimum cost to gurantee a win. Initially we only know that the secret number is within 1 to n; as we progress in the game, the lower and higher bound of the secrete number is getting smaller and smaller. Without ... | the_stack_v2_python_sparse | Leetcode 0375. Guess Number Higher or Lower II.py | Chaoran-sjsu/leetcode | train | 0 | |
b68e305e86d1ada8e7f0a3a0c2aa3d634b2f24fb | [
"folder = os.path.dirname(input_path)\noutput_path = folder + '/nifti/'\nif not os.path.exists(output_path):\n os.mkdir(output_path)\noutput_path += os.path.basename(os.path.dirname(input_path)) + '.nii'\nopen(output_path, 'a').close()\ndicom_array = DICOMImporter.open_dicom_from_folder(input_path)\ndicom_array_... | <|body_start_0|>
folder = os.path.dirname(input_path)
output_path = folder + '/nifti/'
if not os.path.exists(output_path):
os.mkdir(output_path)
output_path += os.path.basename(os.path.dirname(input_path)) + '.nii'
open(output_path, 'a').close()
dicom_array = ... | DICOM_2_NIFTI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DICOM_2_NIFTI:
def convert_dicom_series(input_path):
"""Converts a raw DICOM file series into a Nifti file. Saves a Nifti file to the file system based on path of DICOM file. Input: input_path: - a directory path to a valid series of DICOM images (more than 1) - sample directory layout /... | stack_v2_sparse_classes_10k_train_004192 | 4,993 | no_license | [
{
"docstring": "Converts a raw DICOM file series into a Nifti file. Saves a Nifti file to the file system based on path of DICOM file. Input: input_path: - a directory path to a valid series of DICOM images (more than 1) - sample directory layout /patient/date/dicom_raw/*.dcm will result in nifti file located a... | 2 | stack_v2_sparse_classes_30k_train_003860 | Implement the Python class `DICOM_2_NIFTI` described below.
Class description:
Implement the DICOM_2_NIFTI class.
Method signatures and docstrings:
- def convert_dicom_series(input_path): Converts a raw DICOM file series into a Nifti file. Saves a Nifti file to the file system based on path of DICOM file. Input: inpu... | Implement the Python class `DICOM_2_NIFTI` described below.
Class description:
Implement the DICOM_2_NIFTI class.
Method signatures and docstrings:
- def convert_dicom_series(input_path): Converts a raw DICOM file series into a Nifti file. Saves a Nifti file to the file system based on path of DICOM file. Input: inpu... | d665ca405bdf35fdb57f8149a10b90be82d8de22 | <|skeleton|>
class DICOM_2_NIFTI:
def convert_dicom_series(input_path):
"""Converts a raw DICOM file series into a Nifti file. Saves a Nifti file to the file system based on path of DICOM file. Input: input_path: - a directory path to a valid series of DICOM images (more than 1) - sample directory layout /... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DICOM_2_NIFTI:
def convert_dicom_series(input_path):
"""Converts a raw DICOM file series into a Nifti file. Saves a Nifti file to the file system based on path of DICOM file. Input: input_path: - a directory path to a valid series of DICOM images (more than 1) - sample directory layout /patient/date/d... | the_stack_v2_python_sparse | BSSCSFramework/CTConverter/DICOM_operations.py | wezleysherman/TBI-NN-421 | train | 3 | |
2f2dfb0b8031d58b5d6d87465367928fd01a259d | [
"try:\n user_preferences = get_user_preferences(request.user, username=username)\nexcept UserNotAuthorized:\n return Response(status=status.HTTP_403_FORBIDDEN)\nexcept UserNotFound:\n return Response(status=status.HTTP_404_NOT_FOUND)\nreturn Response(user_preferences)",
"if not request.data or not getatt... | <|body_start_0|>
try:
user_preferences = get_user_preferences(request.user, username=username)
except UserNotAuthorized:
return Response(status=status.HTTP_403_FORBIDDEN)
except UserNotFound:
return Response(status=status.HTTP_404_NOT_FOUND)
return Res... | **Use Cases** Get or update the user's preference information. Updates are only supported through merge patch. Preference values of null in a patch request are treated as requests to remove the preference. **Example Requests** GET /api/user/v1/preferences/{username}/ PATCH /api/user/v1/preferences/{username}/ with cont... | PreferencesView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreferencesView:
"""**Use Cases** Get or update the user's preference information. Updates are only supported through merge patch. Preference values of null in a patch request are treated as requests to remove the preference. **Example Requests** GET /api/user/v1/preferences/{username}/ PATCH /ap... | stack_v2_sparse_classes_10k_train_004193 | 11,020 | permissive | [
{
"docstring": "GET /api/user/v1/preferences/{username}/",
"name": "get",
"signature": "def get(self, request, username)"
},
{
"docstring": "PATCH /api/user/v1/preferences/{username}/",
"name": "patch",
"signature": "def patch(self, request, username)"
}
] | 2 | null | Implement the Python class `PreferencesView` described below.
Class description:
**Use Cases** Get or update the user's preference information. Updates are only supported through merge patch. Preference values of null in a patch request are treated as requests to remove the preference. **Example Requests** GET /api/us... | Implement the Python class `PreferencesView` described below.
Class description:
**Use Cases** Get or update the user's preference information. Updates are only supported through merge patch. Preference values of null in a patch request are treated as requests to remove the preference. **Example Requests** GET /api/us... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class PreferencesView:
"""**Use Cases** Get or update the user's preference information. Updates are only supported through merge patch. Preference values of null in a patch request are treated as requests to remove the preference. **Example Requests** GET /api/user/v1/preferences/{username}/ PATCH /ap... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PreferencesView:
"""**Use Cases** Get or update the user's preference information. Updates are only supported through merge patch. Preference values of null in a patch request are treated as requests to remove the preference. **Example Requests** GET /api/user/v1/preferences/{username}/ PATCH /api/user/v1/pre... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/user_api/preferences/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
81c6013775667f080ebc67d00df95d6b39eeeecd | [
"print(' Starting job: %s\\nExecuting command: %s\\n' % (jobnum, command))\nrv = os.system(command)\nif rv:\n print('Problem running job...\\nFile: %s\\n Job: %d\\nLine: %d\\n...dieing!' % (batchfile, jobnum, linenum))\n sys.exit(rv)",
"if not os.path.isfile(batchfile):\n print('Cannot find batch fil... | <|body_start_0|>
print(' Starting job: %s\nExecuting command: %s\n' % (jobnum, command))
rv = os.system(command)
if rv:
print('Problem running job...\nFile: %s\n Job: %d\nLine: %d\n...dieing!' % (batchfile, jobnum, linenum))
sys.exit(rv)
<|end_body_0|>
<|body_start_1... | This is the main class Instantiate it then call run() | SimpleBatchFile | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleBatchFile:
"""This is the main class Instantiate it then call run()"""
def _exec(self, command, jobnum, linenum, batchfile):
"""Execute a command in a subshell, die on errors"""
<|body_0|>
def __init__(self, batchfile):
"""Start the fun"""
<|body_1|... | stack_v2_sparse_classes_10k_train_004194 | 4,414 | permissive | [
{
"docstring": "Execute a command in a subshell, die on errors",
"name": "_exec",
"signature": "def _exec(self, command, jobnum, linenum, batchfile)"
},
{
"docstring": "Start the fun",
"name": "__init__",
"signature": "def __init__(self, batchfile)"
},
{
"docstring": "List jobs a... | 4 | null | Implement the Python class `SimpleBatchFile` described below.
Class description:
This is the main class Instantiate it then call run()
Method signatures and docstrings:
- def _exec(self, command, jobnum, linenum, batchfile): Execute a command in a subshell, die on errors
- def __init__(self, batchfile): Start the fun... | Implement the Python class `SimpleBatchFile` described below.
Class description:
This is the main class Instantiate it then call run()
Method signatures and docstrings:
- def _exec(self, command, jobnum, linenum, batchfile): Execute a command in a subshell, die on errors
- def __init__(self, batchfile): Start the fun... | d097ca0ad6a6aee2180d32dce6a3322621f655fd | <|skeleton|>
class SimpleBatchFile:
"""This is the main class Instantiate it then call run()"""
def _exec(self, command, jobnum, linenum, batchfile):
"""Execute a command in a subshell, die on errors"""
<|body_0|>
def __init__(self, batchfile):
"""Start the fun"""
<|body_1|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SimpleBatchFile:
"""This is the main class Instantiate it then call run()"""
def _exec(self, command, jobnum, linenum, batchfile):
"""Execute a command in a subshell, die on errors"""
print(' Starting job: %s\nExecuting command: %s\n' % (jobnum, command))
rv = os.system(comman... | the_stack_v2_python_sparse | recipes/Python/496897_Running_Batch_Commands/recipe-496897.py | betty29/code-1 | train | 0 |
a5c69f31fa31fde42e5b30a4cc761e4a312f1d30 | [
"a = len(nums)\nif a < 1:\n return None\nreturn self.createBST(nums, 0, a - 1)",
"if end < start:\n return None\nmid = int((start + end) / 2)\nroot = TreeNode(nums[mid])\nroot.left = self.createBST(nums, start, mid - 1)\nroot.right = self.createBST(nums, mid + 1, end)\nreturn root"
] | <|body_start_0|>
a = len(nums)
if a < 1:
return None
return self.createBST(nums, 0, a - 1)
<|end_body_0|>
<|body_start_1|>
if end < start:
return None
mid = int((start + end) / 2)
root = TreeNode(nums[mid])
root.left = self.createBST(nums,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortedArrayToBST(self, nums):
"""Method calls a recursive function that builds a BST with lowest height :type nums: List[int] :rtype: TreeNode"""
<|body_0|>
def createBST(self, nums, start, end):
"""Keep dividing nums in two parts :param start: :param e... | stack_v2_sparse_classes_10k_train_004195 | 1,084 | no_license | [
{
"docstring": "Method calls a recursive function that builds a BST with lowest height :type nums: List[int] :rtype: TreeNode",
"name": "sortedArrayToBST",
"signature": "def sortedArrayToBST(self, nums)"
},
{
"docstring": "Keep dividing nums in two parts :param start: :param end: :return: root o... | 2 | stack_v2_sparse_classes_30k_train_005445 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedArrayToBST(self, nums): Method calls a recursive function that builds a BST with lowest height :type nums: List[int] :rtype: TreeNode
- def createBST(self, nums, start,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedArrayToBST(self, nums): Method calls a recursive function that builds a BST with lowest height :type nums: List[int] :rtype: TreeNode
- def createBST(self, nums, start,... | 6c32a295f5e2b8c1959f73fad006273204734481 | <|skeleton|>
class Solution:
def sortedArrayToBST(self, nums):
"""Method calls a recursive function that builds a BST with lowest height :type nums: List[int] :rtype: TreeNode"""
<|body_0|>
def createBST(self, nums, start, end):
"""Keep dividing nums in two parts :param start: :param e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def sortedArrayToBST(self, nums):
"""Method calls a recursive function that builds a BST with lowest height :type nums: List[int] :rtype: TreeNode"""
a = len(nums)
if a < 1:
return None
return self.createBST(nums, 0, a - 1)
def createBST(self, nums, s... | the_stack_v2_python_sparse | BTreeToBST.py | shahamish150294/LeetCode | train | 0 | |
edc9e3552f6aee4e98b0600bd02afdb8cccc26e1 | [
"l = longUrl.split('/')\nl.append(1)\nreturn l",
"l = shortUrl\ntmp = l[-1]\ndel l[-1]\ns = l[0] + '//'\ni = 2\nwhile i < len(l):\n s += l[i] + '/'\n i += 1\nreturn s[:-1]"
] | <|body_start_0|>
l = longUrl.split('/')
l.append(1)
return l
<|end_body_0|>
<|body_start_1|>
l = shortUrl
tmp = l[-1]
del l[-1]
s = l[0] + '//'
i = 2
while i < len(l):
s += l[i] + '/'
i += 1
return s[:-1]
<|end_body... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
<|body_0|>
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = longUrl.spli... | stack_v2_sparse_classes_10k_train_004196 | 639 | no_license | [
{
"docstring": "Encodes a URL to a shortened URL.",
"name": "encode",
"signature": "def encode(self, longUrl: str) -> str"
},
{
"docstring": "Decodes a shortened URL to its original URL.",
"name": "decode",
"signature": "def decode(self, shortUrl: str) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_000302 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl: str) -> str: Encodes a URL to a shortened URL.
- def decode(self, shortUrl: str) -> str: Decodes a shortened URL to its original URL. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl: str) -> str: Encodes a URL to a shortened URL.
- def decode(self, shortUrl: str) -> str: Decodes a shortened URL to its original URL.
<|skeleton|>
class Code... | 7aabed082826f8df555bf6e97046ee077becf759 | <|skeleton|>
class Codec:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
<|body_0|>
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
l = longUrl.split('/')
l.append(1)
return l
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
l = shortUrl
tmp = l[-1]
... | the_stack_v2_python_sparse | Python 3/LeetCode/lc535.py | nsmith0310/Programming-Challenges | train | 0 | |
edd85c517a28e0d07098960a989d08a439a70eaf | [
"def preorder(node: TreeNode) -> str:\n if not node:\n return ''\n return ','.join([str(node.val), preorder(node.left), preorder(node.right)])\nreturn preorder(root)",
"arr = data.split(',')\narr.reverse()\n\ndef build(arr) -> TreeNode:\n val = arr.pop()\n if val == '':\n return None\n ... | <|body_start_0|>
def preorder(node: TreeNode) -> str:
if not node:
return ''
return ','.join([str(node.val), preorder(node.left), preorder(node.right)])
return preorder(root)
<|end_body_0|>
<|body_start_1|>
arr = data.split(',')
arr.reverse()
... | 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|>
def preorder(n... | stack_v2_sparse_classes_10k_train_004197 | 1,297 | 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 | stack_v2_sparse_classes_30k_train_006545 | 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... | 64fd7baf3543a7a32ebcbaadb39c11fcc152bf4c | <|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_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def preorder(node: TreeNode) -> str:
if not node:
return ''
return ','.join([str(node.val), preorder(node.left), preorder(node.right)])
return preorder(ro... | the_stack_v2_python_sparse | daily/20201009-serialize-bst.py | kapppa-joe/leetcode-practice | train | 0 | |
fb6b85b6bba11054c5ec916cb67322b82dec70b6 | [
"resp, body = self.get('/')\nbody = json.loads(body)\nself.expected_success(200, resp.status)\nreturn rest_client.ResponseBody(resp, body)",
"resp, body = self.get(version + '/')\nbody = json.loads(body)\nself.expected_success(200, resp.status)\nreturn rest_client.ResponseBody(resp, body)"
] | <|body_start_0|>
resp, body = self.get('/')
body = json.loads(body)
self.expected_success(200, resp.status)
return rest_client.ResponseBody(resp, body)
<|end_body_0|>
<|body_start_1|>
resp, body = self.get(version + '/')
body = json.loads(body)
self.expected_succ... | NetworkVersionsClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkVersionsClient:
def list_versions(self):
"""Do a GET / to fetch available API version information. For more information, please refer to the official API reference: https://docs.openstack.org/api-ref/network/v2/index.html#list-api-versions"""
<|body_0|>
def show_versi... | stack_v2_sparse_classes_10k_train_004198 | 1,823 | permissive | [
{
"docstring": "Do a GET / to fetch available API version information. For more information, please refer to the official API reference: https://docs.openstack.org/api-ref/network/v2/index.html#list-api-versions",
"name": "list_versions",
"signature": "def list_versions(self)"
},
{
"docstring": ... | 2 | null | Implement the Python class `NetworkVersionsClient` described below.
Class description:
Implement the NetworkVersionsClient class.
Method signatures and docstrings:
- def list_versions(self): Do a GET / to fetch available API version information. For more information, please refer to the official API reference: https:... | Implement the Python class `NetworkVersionsClient` described below.
Class description:
Implement the NetworkVersionsClient class.
Method signatures and docstrings:
- def list_versions(self): Do a GET / to fetch available API version information. For more information, please refer to the official API reference: https:... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class NetworkVersionsClient:
def list_versions(self):
"""Do a GET / to fetch available API version information. For more information, please refer to the official API reference: https://docs.openstack.org/api-ref/network/v2/index.html#list-api-versions"""
<|body_0|>
def show_versi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NetworkVersionsClient:
def list_versions(self):
"""Do a GET / to fetch available API version information. For more information, please refer to the official API reference: https://docs.openstack.org/api-ref/network/v2/index.html#list-api-versions"""
resp, body = self.get('/')
body = js... | the_stack_v2_python_sparse | tempest/lib/services/network/versions_client.py | openstack/tempest | train | 270 | |
d2cc412e30fb8ab6432776ebfa83e70e630a5bec | [
"super().__init__(cv)\nself.cid = cv.create_polygon(x - 12, 530, x + 12, 530, x, 500, fill='red')\nself.x = x\nself.pps = pps\nself.colors = colors\nself._tospawn = 0",
"super().update(dt)\nself._tospawn += self.pps * dt\ncolor = self.colors[int(self.age / 3) % len(self.colors)]\nfor i in range(int(self._tospawn)... | <|body_start_0|>
super().__init__(cv)
self.cid = cv.create_polygon(x - 12, 530, x + 12, 530, x, 500, fill='red')
self.x = x
self.pps = pps
self.colors = colors
self._tospawn = 0
<|end_body_0|>
<|body_start_1|>
super().update(dt)
self._tospawn += self.pps ... | A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn. | Volcano | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Volcano:
"""A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn."""
def __init__(self, cv, x, pps, colors):
"""... | stack_v2_sparse_classes_10k_train_004199 | 16,427 | permissive | [
{
"docstring": "Init Volcano objects. Args: cv (Tk.canvas): the canvas in which the particle is drawn. x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn.",
"name": "__init__",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_001220 | Implement the Python class `Volcano` described below.
Class description:
A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn.
Method signatures a... | Implement the Python class `Volcano` described below.
Class description:
A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn.
Method signatures a... | c6b6d80e9d59f5d115ca8b8fc020fcd6cb030af8 | <|skeleton|>
class Volcano:
"""A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn."""
def __init__(self, cv, x, pps, colors):
"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Volcano:
"""A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn."""
def __init__(self, cv, x, pps, colors):
"""Init Volcano ... | the_stack_v2_python_sparse | scripts/sheet9/9.2.py | LennartElbe/PythOnline | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.