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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3a56af78b21b83b75d8f573ed0f772507b219461 | [
"if not root:\n return '[]'\nqueue = collections.deque([root])\nans = []\nwhile queue:\n node = queue.popleft()\n if not node:\n ans.append('null')\n continue\n ans.append(str(node.val))\n queue.extend([node.left, node.right])\nreturn '[' + ','.join(ans) + ']'",
"vals = collections.de... | <|body_start_0|>
if not root:
return '[]'
queue = collections.deque([root])
ans = []
while queue:
node = queue.popleft()
if not node:
ans.append('null')
continue
ans.append(str(node.val))
queue.ex... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_006600 | 1,565 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_val_000039 | 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:... | 35cc05c763b4622aacd9d1166ded2fa320b7ceaf | <|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 '[]'
queue = collections.deque([root])
ans = []
while queue:
node = queue.popleft()
if not node:
... | the_stack_v2_python_sparse | 297.Serialize_and_Deserialize_Binary_Tree(BFS).py | simonzg/leetcode-solutions | train | 0 | |
c8b91741cfda4db64443c31db7ddb22d221e3d68 | [
"self.name = name\nself.code = code\nself.netValue = netValue\nself.netMarketCap = netValue\nself.positions = int(cash / netValue)\npass",
"self.netMarketCap = netValue\nnewNetValue = netValue\nnewPositions = int(cash / netValue)\nprint('买入价格:{0} 操作仓位:{1}'.format(round(newNetValue, 2), newPositions))\nself.netVal... | <|body_start_0|>
self.name = name
self.code = code
self.netValue = netValue
self.netMarketCap = netValue
self.positions = int(cash / netValue)
pass
<|end_body_0|>
<|body_start_1|>
self.netMarketCap = netValue
newNetValue = netValue
newPositions = ... | fund | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class fund:
def __init__(self, name, code, netValue, cash):
"""初始化一只基金"""
<|body_0|>
def buy(self, netValue, cash):
"""买入一定金额"""
<|body_1|>
def sell(self, netValue, cash):
"""卖出一定金额"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self... | stack_v2_sparse_classes_10k_train_006601 | 3,340 | no_license | [
{
"docstring": "初始化一只基金",
"name": "__init__",
"signature": "def __init__(self, name, code, netValue, cash)"
},
{
"docstring": "买入一定金额",
"name": "buy",
"signature": "def buy(self, netValue, cash)"
},
{
"docstring": "卖出一定金额",
"name": "sell",
"signature": "def sell(self, net... | 3 | stack_v2_sparse_classes_30k_train_003650 | Implement the Python class `fund` described below.
Class description:
Implement the fund class.
Method signatures and docstrings:
- def __init__(self, name, code, netValue, cash): 初始化一只基金
- def buy(self, netValue, cash): 买入一定金额
- def sell(self, netValue, cash): 卖出一定金额 | Implement the Python class `fund` described below.
Class description:
Implement the fund class.
Method signatures and docstrings:
- def __init__(self, name, code, netValue, cash): 初始化一只基金
- def buy(self, netValue, cash): 买入一定金额
- def sell(self, netValue, cash): 卖出一定金额
<|skeleton|>
class fund:
def __init__(self,... | 6837259cf3a0a174022e3052c00c4d289a7e2d19 | <|skeleton|>
class fund:
def __init__(self, name, code, netValue, cash):
"""初始化一只基金"""
<|body_0|>
def buy(self, netValue, cash):
"""买入一定金额"""
<|body_1|>
def sell(self, netValue, cash):
"""卖出一定金额"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class fund:
def __init__(self, name, code, netValue, cash):
"""初始化一只基金"""
self.name = name
self.code = code
self.netValue = netValue
self.netMarketCap = netValue
self.positions = int(cash / netValue)
pass
def buy(self, netValue, cash):
"""买入一定金额""... | the_stack_v2_python_sparse | MockTradeSystem/portfolio.py | klq26/finance-data | train | 5 | |
61f667fa3b1cc396f5ff6c82b26a229a28e7281f | [
"dq = collections.deque()\ndq.append(root)\nres = []\nwhile len(dq):\n size = len(dq)\n temp = []\n for _ in range(size):\n node = dq.popleft()\n if node:\n dq.append(node.left)\n dq.append(node.right)\n temp.append(node.val if node else None)\n res += temp\nre... | <|body_start_0|>
dq = collections.deque()
dq.append(root)
res = []
while len(dq):
size = len(dq)
temp = []
for _ in range(size):
node = dq.popleft()
if node:
dq.append(node.left)
d... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_006602 | 1,818 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_002834 | 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:... | df3a589ea858218f689fe315d134adc957c3debd | <|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"""
dq = collections.deque()
dq.append(root)
res = []
while len(dq):
size = len(dq)
temp = []
for _ in range(size):
... | the_stack_v2_python_sparse | 297.py | supperllx/LeetCode | train | 0 | |
eec269b1d989d34ae5f80122a3d62ee2dd7fe227 | [
"v0 = Vertex()\nself.assertIsNot(v0, None)\nself.assertIsInstance(v0, Vertex)",
"v1 = Vertex([1, 2, 3])\nself.assertIsNot(v1, None)\nself.assertIsInstance(v1, Vertex)",
"t = Triangle()\nv = Vertex(t)\nself.assertIsInstance(v, Vertex)\nv_parents = v.parents()\nself.assertTrue(t in v_parents)"
] | <|body_start_0|>
v0 = Vertex()
self.assertIsNot(v0, None)
self.assertIsInstance(v0, Vertex)
<|end_body_0|>
<|body_start_1|>
v1 = Vertex([1, 2, 3])
self.assertIsNot(v1, None)
self.assertIsInstance(v1, Vertex)
<|end_body_1|>
<|body_start_2|>
t = Triangle()
... | Test Vertex class calls | TestConstructor_Vertex | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestConstructor_Vertex:
"""Test Vertex class calls"""
def test_none(self):
"""Calling Vertex class with no key (key = None)"""
<|body_0|>
def test_iterable_simple(self):
"""Calling Vertex class with key containing simple types"""
<|body_1|>
def test_... | stack_v2_sparse_classes_10k_train_006603 | 11,224 | permissive | [
{
"docstring": "Calling Vertex class with no key (key = None)",
"name": "test_none",
"signature": "def test_none(self)"
},
{
"docstring": "Calling Vertex class with key containing simple types",
"name": "test_iterable_simple",
"signature": "def test_iterable_simple(self)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_train_005479 | Implement the Python class `TestConstructor_Vertex` described below.
Class description:
Test Vertex class calls
Method signatures and docstrings:
- def test_none(self): Calling Vertex class with no key (key = None)
- def test_iterable_simple(self): Calling Vertex class with key containing simple types
- def test_iter... | Implement the Python class `TestConstructor_Vertex` described below.
Class description:
Test Vertex class calls
Method signatures and docstrings:
- def test_none(self): Calling Vertex class with no key (key = None)
- def test_iterable_simple(self): Calling Vertex class with key containing simple types
- def test_iter... | f9b00a39bc16aea4abac60c0dd0aab2acac5adcf | <|skeleton|>
class TestConstructor_Vertex:
"""Test Vertex class calls"""
def test_none(self):
"""Calling Vertex class with no key (key = None)"""
<|body_0|>
def test_iterable_simple(self):
"""Calling Vertex class with key containing simple types"""
<|body_1|>
def test_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestConstructor_Vertex:
"""Test Vertex class calls"""
def test_none(self):
"""Calling Vertex class with no key (key = None)"""
v0 = Vertex()
self.assertIsNot(v0, None)
self.assertIsInstance(v0, Vertex)
def test_iterable_simple(self):
"""Calling Vertex class wi... | the_stack_v2_python_sparse | _BACKUPS_V4/v4_5/LightPicture_Test.py | nagame/LightPicture | train | 0 |
3d3319840b43424696654fb18535ad10811124cf | [
"self.lr = learning_rate\nself.momentum = momentum\nself.model_weight_specs = model_weight_specs\nself.noise_std = noise_std\nself.random_generator = tf.random.Generator.from_non_deterministic_state()",
"def noise_tensor(spec):\n noise = self.random_generator.normal(spec.shape, stddev=self.noise_std)\n nois... | <|body_start_0|>
self.lr = learning_rate
self.momentum = momentum
self.model_weight_specs = model_weight_specs
self.noise_std = noise_std
self.random_generator = tf.random.Generator.from_non_deterministic_state()
<|end_body_0|>
<|body_start_1|>
def noise_tensor(spec):
... | Momentum DPSGD Optimizer. | DPSGDMServerOptimizer | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DPSGDMServerOptimizer:
"""Momentum DPSGD Optimizer."""
def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]):
"""Initialize the momemtum DPSGD Optimizer."""
<|body_0|>
def _noise_fn(self):
"""Re... | stack_v2_sparse_classes_10k_train_006604 | 9,237 | permissive | [
{
"docstring": "Initialize the momemtum DPSGD Optimizer.",
"name": "__init__",
"signature": "def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec])"
},
{
"docstring": "Returns random noise to be added for differential privacy.",... | 4 | null | Implement the Python class `DPSGDMServerOptimizer` described below.
Class description:
Momentum DPSGD Optimizer.
Method signatures and docstrings:
- def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]): Initialize the momemtum DPSGD Optimizer.
- de... | Implement the Python class `DPSGDMServerOptimizer` described below.
Class description:
Momentum DPSGD Optimizer.
Method signatures and docstrings:
- def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]): Initialize the momemtum DPSGD Optimizer.
- de... | 329e60fa56b87f691303638ceb9dfa1fc5083953 | <|skeleton|>
class DPSGDMServerOptimizer:
"""Momentum DPSGD Optimizer."""
def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]):
"""Initialize the momemtum DPSGD Optimizer."""
<|body_0|>
def _noise_fn(self):
"""Re... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DPSGDMServerOptimizer:
"""Momentum DPSGD Optimizer."""
def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]):
"""Initialize the momemtum DPSGD Optimizer."""
self.lr = learning_rate
self.momentum = momentum
... | the_stack_v2_python_sparse | dp_ftrl/optimizer_utils.py | google-research/federated | train | 595 |
9d5ee497391326c719306c3c4c0c02b16c544220 | [
"try:\n login = True if 'login' in request.session else False\n return render(request, 'staff/sup_user_add.html', {'login': login})\nexcept Exception as e:\n logger.error(e, exc_info=True)\n return render(request, '404-error-page.html')",
"try:\n user = User.objects.filter(email__iexact=request.dat... | <|body_start_0|>
try:
login = True if 'login' in request.session else False
return render(request, 'staff/sup_user_add.html', {'login': login})
except Exception as e:
logger.error(e, exc_info=True)
return render(request, '404-error-page.html')
<|end_body_0... | SuperUserAddView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperUserAddView:
def get(self, request):
"""Gwt super user list view"""
<|body_0|>
def post(self, request):
"""Create super user"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
login = True if 'login' in request.session else False
... | stack_v2_sparse_classes_10k_train_006605 | 7,575 | no_license | [
{
"docstring": "Gwt super user list view",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Create super user",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000106 | Implement the Python class `SuperUserAddView` described below.
Class description:
Implement the SuperUserAddView class.
Method signatures and docstrings:
- def get(self, request): Gwt super user list view
- def post(self, request): Create super user | Implement the Python class `SuperUserAddView` described below.
Class description:
Implement the SuperUserAddView class.
Method signatures and docstrings:
- def get(self, request): Gwt super user list view
- def post(self, request): Create super user
<|skeleton|>
class SuperUserAddView:
def get(self, request):
... | 367cccca72f0eae6c3ccb70fabb371dc905f915e | <|skeleton|>
class SuperUserAddView:
def get(self, request):
"""Gwt super user list view"""
<|body_0|>
def post(self, request):
"""Create super user"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SuperUserAddView:
def get(self, request):
"""Gwt super user list view"""
try:
login = True if 'login' in request.session else False
return render(request, 'staff/sup_user_add.html', {'login': login})
except Exception as e:
logger.error(e, exc_info=Tr... | the_stack_v2_python_sparse | staff/views/sup_user_view.py | vshaladhav97/first_kick | train | 0 | |
04e10d8620976a6a415dda66ef606185f2343e9d | [
"self.ids = ids\nself.ida = ida\nself.gr = int(gr)",
"\"\"\"\n if self.ida=='0':\n return 'The Student: '+str(self.ids)+'\nAssignment '+'\nStatus: Not Given'\n elif self.gr==0:\n return 'The Student: '+str(self.ids)+'\nAssignment: '+str(self.ida)+'\nStatus: Given \nGrade: Ungra... | <|body_start_0|>
self.ids = ids
self.ida = ida
self.gr = int(gr)
<|end_body_0|>
<|body_start_1|>
"""
if self.ida=='0':
return 'The Student: '+str(self.ids)+'
Assignment '+'
Status: Not Given'
elif self.gr==0:
... | This class will define a grade. | grade | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class grade:
"""This class will define a grade."""
def __init__(self, ids, ida, gr):
"""Constructor"""
<|body_0|>
def __str__(self):
"""The grade wil be returned as for exemple : The Student: 1 Assignment: 2 Grade: Ungraded Grade is "Ungraded" if self.gr=0 and it means... | stack_v2_sparse_classes_10k_train_006606 | 1,331 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, ids, ida, gr)"
},
{
"docstring": "The grade wil be returned as for exemple : The Student: 1 Assignment: 2 Grade: Ungraded Grade is \"Ungraded\" if self.gr=0 and it means that assignment is not finished yet. The St... | 2 | stack_v2_sparse_classes_30k_train_005319 | Implement the Python class `grade` described below.
Class description:
This class will define a grade.
Method signatures and docstrings:
- def __init__(self, ids, ida, gr): Constructor
- def __str__(self): The grade wil be returned as for exemple : The Student: 1 Assignment: 2 Grade: Ungraded Grade is "Ungraded" if s... | Implement the Python class `grade` described below.
Class description:
This class will define a grade.
Method signatures and docstrings:
- def __init__(self, ids, ida, gr): Constructor
- def __str__(self): The grade wil be returned as for exemple : The Student: 1 Assignment: 2 Grade: Ungraded Grade is "Ungraded" if s... | e956d7399f0b2b47f6ce539ac1672492250ee013 | <|skeleton|>
class grade:
"""This class will define a grade."""
def __init__(self, ids, ida, gr):
"""Constructor"""
<|body_0|>
def __str__(self):
"""The grade wil be returned as for exemple : The Student: 1 Assignment: 2 Grade: Ungraded Grade is "Ungraded" if self.gr=0 and it means... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class grade:
"""This class will define a grade."""
def __init__(self, ids, ida, gr):
"""Constructor"""
self.ids = ids
self.ida = ida
self.gr = int(gr)
def __str__(self):
"""The grade wil be returned as for exemple : The Student: 1 Assignment: 2 Grade: Ungraded Grade... | the_stack_v2_python_sparse | StudentsCatalog/Student Lab Assignments/Assignment 5-7/domain_grade.py | FarcasiuRazvan/Python-Projects | train | 0 |
4a0521e733d7580ef3eba6519f3e26a369b68637 | [
"super().__init__(pooling_class, N, depth, laplacian_type, kernel_size, ratio)\nself.sequence_length = sequence_length\nself.encoder = EncoderTemporalConv(self.pooling_class.pooling, self.laps, self.sequence_length, self.kernel_size)\nself.decoder = Decoder(self.pooling_class.unpooling, self.laps, self.kernel_size)... | <|body_start_0|>
super().__init__(pooling_class, N, depth, laplacian_type, kernel_size, ratio)
self.sequence_length = sequence_length
self.encoder = EncoderTemporalConv(self.pooling_class.pooling, self.laps, self.sequence_length, self.kernel_size)
self.decoder = Decoder(self.pooling_clas... | Spherical GCNN Autoencoder with temporality by means of convolution over time. | SphericalUNetTemporalConv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphericalUNetTemporalConv:
"""Spherical GCNN Autoencoder with temporality by means of convolution over time."""
def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1):
"""Initialization. Args: pooling_class (obj): One of three classes of po... | stack_v2_sparse_classes_10k_train_006607 | 41,403 | no_license | [
{
"docstring": "Initialization. Args: pooling_class (obj): One of three classes of pooling methods N (int): Number of pixels in the input image depth (int): The depth of the UNet, which is bounded by the N and the type of pooling sequence_length (int): The number of images used per sample kernel_size (int): che... | 2 | null | Implement the Python class `SphericalUNetTemporalConv` described below.
Class description:
Spherical GCNN Autoencoder with temporality by means of convolution over time.
Method signatures and docstrings:
- def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1): Initializati... | Implement the Python class `SphericalUNetTemporalConv` described below.
Class description:
Spherical GCNN Autoencoder with temporality by means of convolution over time.
Method signatures and docstrings:
- def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1): Initializati... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SphericalUNetTemporalConv:
"""Spherical GCNN Autoencoder with temporality by means of convolution over time."""
def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1):
"""Initialization. Args: pooling_class (obj): One of three classes of po... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SphericalUNetTemporalConv:
"""Spherical GCNN Autoencoder with temporality by means of convolution over time."""
def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1):
"""Initialization. Args: pooling_class (obj): One of three classes of pooling methods... | the_stack_v2_python_sparse | generated/test_deepsphere_deepsphere_pytorch.py | jansel/pytorch-jit-paritybench | train | 35 |
01bd47e91421af891503f948b611260c8594cc53 | [
"root = TreeNode(preorder[0])\nif len(preorder) == 1:\n return root\nindex = inorder.index(root.value)\nleftlist, rightlist = ([], [])\nfor n in preorder:\n if n in inorder[:index]:\n leftlist.append(n)\n elif n in inorder[index + 1:]:\n rightlist.append(n)\nroot.lchild = self.buildTree(leftl... | <|body_start_0|>
root = TreeNode(preorder[0])
if len(preorder) == 1:
return root
index = inorder.index(root.value)
leftlist, rightlist = ([], [])
for n in preorder:
if n in inorder[:index]:
leftlist.append(n)
elif n in inorder[i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buildTree(self, preorder, inorder):
""":param preorder: list[int] :param inorder: list[int] :return: TreeNode"""
<|body_0|>
def buildTree2(self, preorder, inorder):
""":param preorder: list[int] :param inorder: list[int] :return: TreeNode"""
<|b... | stack_v2_sparse_classes_10k_train_006608 | 1,819 | no_license | [
{
"docstring": ":param preorder: list[int] :param inorder: list[int] :return: TreeNode",
"name": "buildTree",
"signature": "def buildTree(self, preorder, inorder)"
},
{
"docstring": ":param preorder: list[int] :param inorder: list[int] :return: TreeNode",
"name": "buildTree2",
"signature... | 2 | stack_v2_sparse_classes_30k_train_004598 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder, inorder): :param preorder: list[int] :param inorder: list[int] :return: TreeNode
- def buildTree2(self, preorder, inorder): :param preorder: list[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder, inorder): :param preorder: list[int] :param inorder: list[int] :return: TreeNode
- def buildTree2(self, preorder, inorder): :param preorder: list[in... | 4f2802d4773eddd2a2e06e61c51463056886b730 | <|skeleton|>
class Solution:
def buildTree(self, preorder, inorder):
""":param preorder: list[int] :param inorder: list[int] :return: TreeNode"""
<|body_0|>
def buildTree2(self, preorder, inorder):
""":param preorder: list[int] :param inorder: list[int] :return: TreeNode"""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def buildTree(self, preorder, inorder):
""":param preorder: list[int] :param inorder: list[int] :return: TreeNode"""
root = TreeNode(preorder[0])
if len(preorder) == 1:
return root
index = inorder.index(root.value)
leftlist, rightlist = ([], [])
... | the_stack_v2_python_sparse | leetcode2/62_buildTree.py | Yara7L/python_algorithm | train | 0 | |
2944d7b9804845f3cdc732a8449737134101d294 | [
"self.designate = designate\nself.parameter = parameter\nself.answers = [Path(answer) for answer in answers]\nself.default = Path(default)\nself.question = question\nself.logical_unit = next(self._logic_unit)\nself.value = self.default",
"question = tag.find('question').text\ndefault = tag.find('answer').text\nan... | <|body_start_0|>
self.designate = designate
self.parameter = parameter
self.answers = [Path(answer) for answer in answers]
self.default = Path(default)
self.question = question
self.logical_unit = next(self._logic_unit)
self.value = self.default
<|end_body_0|>
<|... | ExternalFile class. The External File Specification allows the user to associate a TRNSYS parameter ( typically a logical unit) with an external file through the use of the TRNSYS ASSIGN, FILES, or DESIGNATE statements. This feature allows the author to describe a question that will be asked in the assembly window. If ... | ExternalFile | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExternalFile:
"""ExternalFile class. The External File Specification allows the user to associate a TRNSYS parameter ( typically a logical unit) with an external file through the use of the TRNSYS ASSIGN, FILES, or DESIGNATE statements. This feature allows the author to describe a question that w... | stack_v2_sparse_classes_10k_train_006609 | 2,637 | permissive | [
{
"docstring": "Initialize object from arguments. Args: question (str): Question to ask. default (str): Default answer. answers (list of str): List of possible answers. parameter (str): The parameter associated with the external file. designate (bool): If True, the external files are assigned to logical unit nu... | 2 | stack_v2_sparse_classes_30k_train_003890 | Implement the Python class `ExternalFile` described below.
Class description:
ExternalFile class. The External File Specification allows the user to associate a TRNSYS parameter ( typically a logical unit) with an external file through the use of the TRNSYS ASSIGN, FILES, or DESIGNATE statements. This feature allows t... | Implement the Python class `ExternalFile` described below.
Class description:
ExternalFile class. The External File Specification allows the user to associate a TRNSYS parameter ( typically a logical unit) with an external file through the use of the TRNSYS ASSIGN, FILES, or DESIGNATE statements. This feature allows t... | f2deb5eb340a2814722eead5f8b6278a945c730d | <|skeleton|>
class ExternalFile:
"""ExternalFile class. The External File Specification allows the user to associate a TRNSYS parameter ( typically a logical unit) with an external file through the use of the TRNSYS ASSIGN, FILES, or DESIGNATE statements. This feature allows the author to describe a question that w... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExternalFile:
"""ExternalFile class. The External File Specification allows the user to associate a TRNSYS parameter ( typically a logical unit) with an external file through the use of the TRNSYS ASSIGN, FILES, or DESIGNATE statements. This feature allows the author to describe a question that will be asked ... | the_stack_v2_python_sparse | trnsystor/externalfile.py | sturmianseq/trnsystor | train | 0 |
a9e4992b2f4a0893666762e0259154d9befe541b | [
"self.private_key_path = None\nself.local_cert_path = None\nself.ca_certs_path = None",
"certs_dir = pathlib.Path(root_dir) / 'data' / 'certs'\ncerts_dir.mkdir(parents=True, exist_ok=True)\ncreated_certs = Certs()\nif private_key:\n private_key_file = certs_dir / 'client.key'\n private_key_file.write_text(p... | <|body_start_0|>
self.private_key_path = None
self.local_cert_path = None
self.ca_certs_path = None
<|end_body_0|>
<|body_start_1|>
certs_dir = pathlib.Path(root_dir) / 'data' / 'certs'
certs_dir.mkdir(parents=True, exist_ok=True)
created_certs = Certs()
if priva... | A collection of certificates and keys. Attributes: - private_key_path: A string containing the full path to client certificate private key. - local_cert_path: A string containing the full path to client certificate. - ca_certs_path: A string containing the full path to the CA certificates. | Certs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Certs:
"""A collection of certificates and keys. Attributes: - private_key_path: A string containing the full path to client certificate private key. - local_cert_path: A string containing the full path to client certificate. - ca_certs_path: A string containing the full path to the CA certificat... | stack_v2_sparse_classes_10k_train_006610 | 2,067 | permissive | [
{
"docstring": "Create an empty Certs object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create files that hold certificate data in a root_dir/data/certs folder (creating missing folders as appropriate). :param root_dir: root dir in which to create data/certs fold... | 2 | null | Implement the Python class `Certs` described below.
Class description:
A collection of certificates and keys. Attributes: - private_key_path: A string containing the full path to client certificate private key. - local_cert_path: A string containing the full path to client certificate. - ca_certs_path: A string contai... | Implement the Python class `Certs` described below.
Class description:
A collection of certificates and keys. Attributes: - private_key_path: A string containing the full path to client certificate private key. - local_cert_path: A string containing the full path to client certificate. - ca_certs_path: A string contai... | 8420d9d4b800223bff6a648015679684f5aba38c | <|skeleton|>
class Certs:
"""A collection of certificates and keys. Attributes: - private_key_path: A string containing the full path to client certificate private key. - local_cert_path: A string containing the full path to client certificate. - ca_certs_path: A string containing the full path to the CA certificat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Certs:
"""A collection of certificates and keys. Attributes: - private_key_path: A string containing the full path to client certificate private key. - local_cert_path: A string containing the full path to client certificate. - ca_certs_path: A string containing the full path to the CA certificates."""
d... | the_stack_v2_python_sparse | integration-tests/fake_spine/fake_spine/certs.py | nhsconnect/integration-adaptors | train | 15 |
d2358f34e298d0542adfe7debf59b270859f0e2c | [
"pos = 1\ncur = k\ncount = k\nwhile pos < n:\n if k % 2 == 0:\n cur = cur // 2\n else:\n cur = cur // 2 + 1\n count += cur\n pos += 1\nreturn count",
"l = 1\nr = m\nmid = l + (r - l) // 2\nwhile l <= r:\n v = self.compute(n, mid)\n if v == m:\n return mid\n elif v > m:\n ... | <|body_start_0|>
pos = 1
cur = k
count = k
while pos < n:
if k % 2 == 0:
cur = cur // 2
else:
cur = cur // 2 + 1
count += cur
pos += 1
return count
<|end_body_0|>
<|body_start_1|>
l = 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def compute(self, n, k):
"""第一天吃k块, 至少需要多少块. :param k: :return:"""
<|body_0|>
def twosplit(self, n, m):
""":param n: 天数 :param m: 巧克力数量 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pos = 1
cur = k
count = k
... | stack_v2_sparse_classes_10k_train_006611 | 914 | no_license | [
{
"docstring": "第一天吃k块, 至少需要多少块. :param k: :return:",
"name": "compute",
"signature": "def compute(self, n, k)"
},
{
"docstring": ":param n: 天数 :param m: 巧克力数量 :return:",
"name": "twosplit",
"signature": "def twosplit(self, n, m)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000125 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def compute(self, n, k): 第一天吃k块, 至少需要多少块. :param k: :return:
- def twosplit(self, n, m): :param n: 天数 :param m: 巧克力数量 :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def compute(self, n, k): 第一天吃k块, 至少需要多少块. :param k: :return:
- def twosplit(self, n, m): :param n: 天数 :param m: 巧克力数量 :return:
<|skeleton|>
class Solution:
def compute(self... | 4e03eee4558800e6e23504840401bb0544fac752 | <|skeleton|>
class Solution:
def compute(self, n, k):
"""第一天吃k块, 至少需要多少块. :param k: :return:"""
<|body_0|>
def twosplit(self, n, m):
""":param n: 天数 :param m: 巧克力数量 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def compute(self, n, k):
"""第一天吃k块, 至少需要多少块. :param k: :return:"""
pos = 1
cur = k
count = k
while pos < n:
if k % 2 == 0:
cur = cur // 2
else:
cur = cur // 2 + 1
count += cur
pos ... | the_stack_v2_python_sparse | leetcode_ex/ex贪吃的小q.py | LNZ001/Analysis-of-algorithm-exercises | train | 0 | |
87a10518b89829441f5fd2f371f775e973872853 | [
"super(RDropLoss, self).__init__()\nif reduction not in ['sum', 'mean', 'none', 'batchmean']:\n raise ValueError(\"'reduction' in 'RDropLoss' should be 'sum', 'mean' 'batchmean', or 'none', but received {}.\".format(reduction))\nself.reduction = reduction",
"p_loss = F.kl_div(F.log_softmax(p, axis=-1), F.softm... | <|body_start_0|>
super(RDropLoss, self).__init__()
if reduction not in ['sum', 'mean', 'none', 'batchmean']:
raise ValueError("'reduction' in 'RDropLoss' should be 'sum', 'mean' 'batchmean', or 'none', but received {}.".format(reduction))
self.reduction = reduction
<|end_body_0|>
<|... | R-Drop Loss implementation For more information about R-drop please refer to this paper: https://arxiv.org/abs/2106.14448 Original implementation please refer to this code: https://github.com/dropreg/R-Drop | RDropLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RDropLoss:
"""R-Drop Loss implementation For more information about R-drop please refer to this paper: https://arxiv.org/abs/2106.14448 Original implementation please refer to this code: https://github.com/dropreg/R-Drop"""
def __init__(self, reduction='none'):
"""reduction(obj:`str`... | stack_v2_sparse_classes_10k_train_006612 | 2,888 | no_license | [
{
"docstring": "reduction(obj:`str`, optional): Indicate how to average the loss, the candicates are ``'none'`` | ``'batchmean'`` | ``'mean'`` | ``'sum'``. If `reduction` is ``'mean'``, the reduced mean loss is returned; If `reduction` is ``'batchmean'``, the sum loss divided by batch size is returned; if `redu... | 2 | stack_v2_sparse_classes_30k_train_006165 | Implement the Python class `RDropLoss` described below.
Class description:
R-Drop Loss implementation For more information about R-drop please refer to this paper: https://arxiv.org/abs/2106.14448 Original implementation please refer to this code: https://github.com/dropreg/R-Drop
Method signatures and docstrings:
- ... | Implement the Python class `RDropLoss` described below.
Class description:
R-Drop Loss implementation For more information about R-drop please refer to this paper: https://arxiv.org/abs/2106.14448 Original implementation please refer to this code: https://github.com/dropreg/R-Drop
Method signatures and docstrings:
- ... | af8aa66703915aa5be3e820f2016bf02bea1fa2e | <|skeleton|>
class RDropLoss:
"""R-Drop Loss implementation For more information about R-drop please refer to this paper: https://arxiv.org/abs/2106.14448 Original implementation please refer to this code: https://github.com/dropreg/R-Drop"""
def __init__(self, reduction='none'):
"""reduction(obj:`str`... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RDropLoss:
"""R-Drop Loss implementation For more information about R-drop please refer to this paper: https://arxiv.org/abs/2106.14448 Original implementation please refer to this code: https://github.com/dropreg/R-Drop"""
def __init__(self, reduction='none'):
"""reduction(obj:`str`, optional): ... | the_stack_v2_python_sparse | paddlenlp/losses/rdrop.py | kevinng77/blenderbot_paddle | train | 12 |
812ed9daeee0b0f5667bed4975ecdabede2338ed | [
"from collections import deque as dq\norder = []\nlevel_nodes = dq()\nif root is None:\n return []\nqueue = dq([root, None])\nis_left = True\nwhile len(queue) > 0:\n curr_node = queue.popleft()\n if curr_node:\n if is_left:\n level_nodes.append(curr_node.val)\n else:\n l... | <|body_start_0|>
from collections import deque as dq
order = []
level_nodes = dq()
if root is None:
return []
queue = dq([root, None])
is_left = True
while len(queue) > 0:
curr_node = queue.popleft()
if curr_node:
... | ZigZag | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZigZag:
def level_order_travesal(self, root: TreeNode) -> List[List[int]]:
"""Approach: Breadth First Search Time Complexity: O(N) Space Complexity: O(N) :param root: :return:"""
<|body_0|>
def level_order_travesal(self, root: TreeNode) -> List[List[int]]:
"""Approac... | stack_v2_sparse_classes_10k_train_006613 | 2,270 | no_license | [
{
"docstring": "Approach: Breadth First Search Time Complexity: O(N) Space Complexity: O(N) :param root: :return:",
"name": "level_order_travesal",
"signature": "def level_order_travesal(self, root: TreeNode) -> List[List[int]]"
},
{
"docstring": "Approach: Depth First Search Time Complexity: O(... | 2 | null | Implement the Python class `ZigZag` described below.
Class description:
Implement the ZigZag class.
Method signatures and docstrings:
- def level_order_travesal(self, root: TreeNode) -> List[List[int]]: Approach: Breadth First Search Time Complexity: O(N) Space Complexity: O(N) :param root: :return:
- def level_order... | Implement the Python class `ZigZag` described below.
Class description:
Implement the ZigZag class.
Method signatures and docstrings:
- def level_order_travesal(self, root: TreeNode) -> List[List[int]]: Approach: Breadth First Search Time Complexity: O(N) Space Complexity: O(N) :param root: :return:
- def level_order... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class ZigZag:
def level_order_travesal(self, root: TreeNode) -> List[List[int]]:
"""Approach: Breadth First Search Time Complexity: O(N) Space Complexity: O(N) :param root: :return:"""
<|body_0|>
def level_order_travesal(self, root: TreeNode) -> List[List[int]]:
"""Approac... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ZigZag:
def level_order_travesal(self, root: TreeNode) -> List[List[int]]:
"""Approach: Breadth First Search Time Complexity: O(N) Space Complexity: O(N) :param root: :return:"""
from collections import deque as dq
order = []
level_nodes = dq()
if root is None:
... | the_stack_v2_python_sparse | data_structures/tree_node/zig_zag_order.py | Shiv2157k/leet_code | train | 1 | |
e751118729eed74d92ecbb67d8c0ce81e348b972 | [
"if graph.is_directed():\n raise ValueError('the graph is directed')\nself.graph = graph\nself.color = dict(((node, None) for node in self.graph.iternodes()))\nfor edge in self.graph.iteredges():\n if edge.source == edge.target:\n raise ValueError('a loop detected')\nself.saturation = dict(((node, set(... | <|body_start_0|>
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
self.color = dict(((node, None) for node in self.graph.iternodes()))
for edge in self.graph.iteredges():
if edge.source == edge.target:
raise Valu... | Find a saturated largest first (SLF) node coloring. Computational complexity is O(V^2). Attributes ---------- graph : input undirected graph or multigraph color : dict with nodes (values are colors) Notes ----- Colors are 0, 1, 2, ... | SLFNodeColoring | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SLFNodeColoring:
"""Find a saturated largest first (SLF) node coloring. Computational complexity is O(V^2). Attributes ---------- graph : input undirected graph or multigraph color : dict with nodes (values are colors) Notes ----- Colors are 0, 1, 2, ..."""
def __init__(self, graph):
... | stack_v2_sparse_classes_10k_train_006614 | 1,809 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Give node the smallest possible color.",
"name": "_greedy_co... | 3 | stack_v2_sparse_classes_30k_train_002404 | Implement the Python class `SLFNodeColoring` described below.
Class description:
Find a saturated largest first (SLF) node coloring. Computational complexity is O(V^2). Attributes ---------- graph : input undirected graph or multigraph color : dict with nodes (values are colors) Notes ----- Colors are 0, 1, 2, ...
Me... | Implement the Python class `SLFNodeColoring` described below.
Class description:
Find a saturated largest first (SLF) node coloring. Computational complexity is O(V^2). Attributes ---------- graph : input undirected graph or multigraph color : dict with nodes (values are colors) Notes ----- Colors are 0, 1, 2, ...
Me... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class SLFNodeColoring:
"""Find a saturated largest first (SLF) node coloring. Computational complexity is O(V^2). Attributes ---------- graph : input undirected graph or multigraph color : dict with nodes (values are colors) Notes ----- Colors are 0, 1, 2, ..."""
def __init__(self, graph):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SLFNodeColoring:
"""Find a saturated largest first (SLF) node coloring. Computational complexity is O(V^2). Attributes ---------- graph : input undirected graph or multigraph color : dict with nodes (values are colors) Notes ----- Colors are 0, 1, 2, ..."""
def __init__(self, graph):
"""The algor... | the_stack_v2_python_sparse | graphtheory/coloring/nodecolorslf.py | kgashok/graphs-dict | train | 0 |
a838a9a0e52cd87af618e4aa71c10bfd0a6fe197 | [
"def helper(nums1, nums2, k):\n if len(nums1) < len(nums2):\n nums1, nums2 = (nums2, nums1)\n if len(nums2) == 0:\n return nums1[k - 1]\n if k == 1:\n return min(nums1[0], nums2[0])\n t = min(k // 2, len(nums2))\n if nums1[t - 1] >= nums2[t - 1]:\n return helper(nums1, num... | <|body_start_0|>
def helper(nums1, nums2, k):
if len(nums1) < len(nums2):
nums1, nums2 = (nums2, nums1)
if len(nums2) == 0:
return nums1[k - 1]
if k == 1:
return min(nums1[0], nums2[0])
t = min(k // 2, len(nums2))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_1|>... | stack_v2_sparse_classes_10k_train_006615 | 2,401 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: float",
"name": "findMedianSortedArrays",
"signature": "def findMedianSortedArrays(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: float",
"name": "findMedianSortedArrays",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[in... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_1|>... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
def helper(nums1, nums2, k):
if len(nums1) < len(nums2):
nums1, nums2 = (nums2, nums1)
if len(nums2) == 0:
return ... | the_stack_v2_python_sparse | 0004_Median_of_Two_Sorted_Arrays.py | bingli8802/leetcode | train | 0 | |
7b99b6cb00cf487a9158678ad18c27ba7050b526 | [
"need = defaultdict(int)\nwindow = defaultdict(int)\nfor c in s1:\n need[c] += 1\nleft, right = (0, 0)\nvalid = 0\nwhile right < len(s2):\n c = s2[right]\n right += 1\n if c in need:\n window[c] += 1\n if window[c] == need[c]:\n valid += 1\n while right - left >= len(s1):\n ... | <|body_start_0|>
need = defaultdict(int)
window = defaultdict(int)
for c in s1:
need[c] += 1
left, right = (0, 0)
valid = 0
while right < len(s2):
c = s2[right]
right += 1
if c in need:
window[c] += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def checkInclusionFramework(self, s1, s2):
"""use the sliding window framework"""
<|body_0|>
def checkInclusion(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
need = defaultdict(i... | stack_v2_sparse_classes_10k_train_006616 | 3,498 | no_license | [
{
"docstring": "use the sliding window framework",
"name": "checkInclusionFramework",
"signature": "def checkInclusionFramework(self, s1, s2)"
},
{
"docstring": ":type s1: str :type s2: str :rtype: bool",
"name": "checkInclusion",
"signature": "def checkInclusion(self, s1, s2)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkInclusionFramework(self, s1, s2): use the sliding window framework
- def checkInclusion(self, s1, s2): :type s1: str :type s2: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkInclusionFramework(self, s1, s2): use the sliding window framework
- def checkInclusion(self, s1, s2): :type s1: str :type s2: str :rtype: bool
<|skeleton|>
class Solut... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def checkInclusionFramework(self, s1, s2):
"""use the sliding window framework"""
<|body_0|>
def checkInclusion(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def checkInclusionFramework(self, s1, s2):
"""use the sliding window framework"""
need = defaultdict(int)
window = defaultdict(int)
for c in s1:
need[c] += 1
left, right = (0, 0)
valid = 0
while right < len(s2):
c = s2[r... | the_stack_v2_python_sparse | P/PermutationInString.py | bssrdf/pyleet | train | 2 | |
688ac9db3a4be1bbba503d60a115aa6f8997ff8a | [
"import numpy as np\nself.income_data = merge_by_year(income, countries, year)\nself.year = year",
"fig = pl.figure(figsize=(15, 10))\nfor i, region in enumerate(self.income_data['Region'].unique()):\n ax = fig.add_subplot(2, 3, i + 1)\n self.income_data[self.income_data.Region == region].plot(kind='box', a... | <|body_start_0|>
import numpy as np
self.income_data = merge_by_year(income, countries, year)
self.year = year
<|end_body_0|>
<|body_start_1|>
fig = pl.figure(figsize=(15, 10))
for i, region in enumerate(self.income_data['Region'].unique()):
ax = fig.add_subplot(2, 3... | Class represents the income per capita for countries in the world in a given year | world_Income_per_capita | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class world_Income_per_capita:
"""Class represents the income per capita for countries in the world in a given year"""
def __init__(self, income, countries, year):
"""Constructor for world_Income_per_capita class inputs: num_trials: An integer between 1800 and 2012 representing the year of... | stack_v2_sparse_classes_10k_train_006617 | 2,801 | no_license | [
{
"docstring": "Constructor for world_Income_per_capita class inputs: num_trials: An integer between 1800 and 2012 representing the year of interest",
"name": "__init__",
"signature": "def __init__(self, income, countries, year)"
},
{
"docstring": "Plots a boxplot of the income distribution acro... | 3 | null | Implement the Python class `world_Income_per_capita` described below.
Class description:
Class represents the income per capita for countries in the world in a given year
Method signatures and docstrings:
- def __init__(self, income, countries, year): Constructor for world_Income_per_capita class inputs: num_trials: ... | Implement the Python class `world_Income_per_capita` described below.
Class description:
Class represents the income per capita for countries in the world in a given year
Method signatures and docstrings:
- def __init__(self, income, countries, year): Constructor for world_Income_per_capita class inputs: num_trials: ... | f5bb1e51de4f84ab3dd62d3073aee4f56534afa1 | <|skeleton|>
class world_Income_per_capita:
"""Class represents the income per capita for countries in the world in a given year"""
def __init__(self, income, countries, year):
"""Constructor for world_Income_per_capita class inputs: num_trials: An integer between 1800 and 2012 representing the year of... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class world_Income_per_capita:
"""Class represents the income per capita for countries in the world in a given year"""
def __init__(self, income, countries, year):
"""Constructor for world_Income_per_capita class inputs: num_trials: An integer between 1800 and 2012 representing the year of interest"""
... | the_stack_v2_python_sparse | jt2276/world_Income_per_capita.py | ds-ga-1007/assignment9 | train | 2 |
2f56b5d453a7277b18d9e7c191ffde76cb0e7d56 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ExternalConnection()",
"from ..entity import Entity\nfrom .activity_settings import ActivitySettings\nfrom .configuration import Configuration\nfrom .connection_operation import ConnectionOperation\nfrom .connection_state import Connec... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ExternalConnection()
<|end_body_0|>
<|body_start_1|>
from ..entity import Entity
from .activity_settings import ActivitySettings
from .configuration import Configuration
... | ExternalConnection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExternalConnection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalConnection:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | stack_v2_sparse_classes_10k_train_006618 | 5,859 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ExternalConnection",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | null | Implement the Python class `ExternalConnection` described below.
Class description:
Implement the ExternalConnection class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalConnection: Creates a new instance of the appropriate class based on disc... | Implement the Python class `ExternalConnection` described below.
Class description:
Implement the ExternalConnection class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalConnection: Creates a new instance of the appropriate class based on disc... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ExternalConnection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalConnection:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExternalConnection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalConnection:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Ex... | the_stack_v2_python_sparse | msgraph/generated/models/external_connectors/external_connection.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
0d88b97c9a45bf96b5c9ccd1af1f6f65453f6025 | [
"params = super().get_default_params(with_embedding=True, with_multi_layer_perceptron=True)\nparams['mlp_num_units'] = 256\nparams.get('mlp_num_units').hyper_space = hyper_spaces.quniform(16, 512)\nparams.get('mlp_num_layers').hyper_space = hyper_spaces.quniform(1, 5)\nreturn params",
"self.embeddinng = self._mak... | <|body_start_0|>
params = super().get_default_params(with_embedding=True, with_multi_layer_perceptron=True)
params['mlp_num_units'] = 256
params.get('mlp_num_units').hyper_space = hyper_spaces.quniform(16, 512)
params.get('mlp_num_layers').hyper_space = hyper_spaces.quniform(1, 5)
... | A simple densely connected baseline model. Examples: >>> model = DenseBaseline() >>> model.params['mlp_num_layers'] = 2 >>> model.params['mlp_num_units'] = 300 >>> model.params['mlp_num_fan_out'] = 128 >>> model.params['mlp_activation_func'] = 'relu' >>> model.guess_and_fill_missing_params(verbose=0) >>> model.build() | DenseBaseline | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DenseBaseline:
"""A simple densely connected baseline model. Examples: >>> model = DenseBaseline() >>> model.params['mlp_num_layers'] = 2 >>> model.params['mlp_num_units'] = 300 >>> model.params['mlp_num_fan_out'] = 128 >>> model.params['mlp_activation_func'] = 'relu' >>> model.guess_and_fill_mis... | stack_v2_sparse_classes_10k_train_006619 | 1,829 | permissive | [
{
"docstring": ":return: model default parameters.",
"name": "get_default_params",
"signature": "def get_default_params(cls) -> ParamTable"
},
{
"docstring": "Build.",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "Forward.",
"name": "forward",
"signat... | 3 | null | Implement the Python class `DenseBaseline` described below.
Class description:
A simple densely connected baseline model. Examples: >>> model = DenseBaseline() >>> model.params['mlp_num_layers'] = 2 >>> model.params['mlp_num_units'] = 300 >>> model.params['mlp_num_fan_out'] = 128 >>> model.params['mlp_activation_func'... | Implement the Python class `DenseBaseline` described below.
Class description:
A simple densely connected baseline model. Examples: >>> model = DenseBaseline() >>> model.params['mlp_num_layers'] = 2 >>> model.params['mlp_num_units'] = 300 >>> model.params['mlp_num_fan_out'] = 128 >>> model.params['mlp_activation_func'... | 4198ebce942f4afe7ddca6a96ab6f4464ade4518 | <|skeleton|>
class DenseBaseline:
"""A simple densely connected baseline model. Examples: >>> model = DenseBaseline() >>> model.params['mlp_num_layers'] = 2 >>> model.params['mlp_num_units'] = 300 >>> model.params['mlp_num_fan_out'] = 128 >>> model.params['mlp_activation_func'] = 'relu' >>> model.guess_and_fill_mis... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DenseBaseline:
"""A simple densely connected baseline model. Examples: >>> model = DenseBaseline() >>> model.params['mlp_num_layers'] = 2 >>> model.params['mlp_num_units'] = 300 >>> model.params['mlp_num_fan_out'] = 128 >>> model.params['mlp_activation_func'] = 'relu' >>> model.guess_and_fill_missing_params(v... | the_stack_v2_python_sparse | poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/models/dense_baseline.py | microsoft/ContextualSP | train | 332 |
898a7797e23923b5e2e23e22eb768bc8b01dc940 | [
"Component.__init__(self)\nself.name = 'Grid_default_name'\nself.input_max = 800000000\nself.bus_in = None\nself.set_parameters(params)\nself.commodity_costs = self.get_costs_and_art_costs()",
"sink = solph.Sink(label=self.name, inputs={busses[self.bus_in]: solph.Flow(variable_costs=self.commodity_costs, nominal_... | <|body_start_0|>
Component.__init__(self)
self.name = 'Grid_default_name'
self.input_max = 800000000
self.bus_in = None
self.set_parameters(params)
self.commodity_costs = self.get_costs_and_art_costs()
<|end_body_0|>
<|body_start_1|>
sink = solph.Sink(label=self.... | :param name: unique name given to the sink component :type name: str :param input_max: maximum input per timestep of commodity e.g. for excess electricity [Wh], heat [Wh], hydrogen [kg] :type input_max: numerical :param bus_in: input bus of the sink component e.g. the electricity bus :type bus_in: str :param set_parame... | Sink | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sink:
""":param name: unique name given to the sink component :type name: str :param input_max: maximum input per timestep of commodity e.g. for excess electricity [Wh], heat [Wh], hydrogen [kg] :type input_max: numerical :param bus_in: input bus of the sink component e.g. the electricity bus :ty... | stack_v2_sparse_classes_10k_train_006620 | 2,520 | permissive | [
{
"docstring": "Constructor method",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "Creates an oemof Sink component from the information given in the Sink class, to be used in the oemof model. :param busses: virtual buses used in the energy system :type busses: ... | 2 | stack_v2_sparse_classes_30k_train_001812 | Implement the Python class `Sink` described below.
Class description:
:param name: unique name given to the sink component :type name: str :param input_max: maximum input per timestep of commodity e.g. for excess electricity [Wh], heat [Wh], hydrogen [kg] :type input_max: numerical :param bus_in: input bus of the sink... | Implement the Python class `Sink` described below.
Class description:
:param name: unique name given to the sink component :type name: str :param input_max: maximum input per timestep of commodity e.g. for excess electricity [Wh], heat [Wh], hydrogen [kg] :type input_max: numerical :param bus_in: input bus of the sink... | 0d4d55d587c18d9e05258f85c1bb41c0b5fdaee7 | <|skeleton|>
class Sink:
""":param name: unique name given to the sink component :type name: str :param input_max: maximum input per timestep of commodity e.g. for excess electricity [Wh], heat [Wh], hydrogen [kg] :type input_max: numerical :param bus_in: input bus of the sink component e.g. the electricity bus :ty... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Sink:
""":param name: unique name given to the sink component :type name: str :param input_max: maximum input per timestep of commodity e.g. for excess electricity [Wh], heat [Wh], hydrogen [kg] :type input_max: numerical :param bus_in: input bus of the sink component e.g. the electricity bus :type bus_in: st... | the_stack_v2_python_sparse | smooth/components/component_sink.py | rl-institut/smooth | train | 7 |
4fd20b1408c0bab70cef4d26f58b1ca77e91bfe5 | [
"Inventory.__init__(self, product_code, description, market_price, rental_price)\nself.brand = brand\nself.voltage = voltage",
"item = Inventory.return_as_dictionary(self)\nitem['Brand'] = self.brand\nitem['Voltage'] = self.voltage\nreturn item"
] | <|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|>
item = Inventory.return_as_dictionary(self)
item['Brand'] = self.brand
item['Voltage'] = self.voltag... | The ElectricAppliances class | ElectricAppliances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElectricAppliances:
"""The ElectricAppliances class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Creates common instance variables from the parent class"""
<|body_0|>
def return_as_dictionary(self):
"""Function ... | stack_v2_sparse_classes_10k_train_006621 | 774 | no_license | [
{
"docstring": "Creates common instance variables from the parent class",
"name": "__init__",
"signature": "def __init__(self, product_code, description, market_price, rental_price, brand, voltage)"
},
{
"docstring": "Function to return appliance as a dictionary",
"name": "return_as_dictiona... | 2 | stack_v2_sparse_classes_30k_train_002862 | Implement the Python class `ElectricAppliances` described below.
Class description:
The ElectricAppliances class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): Creates common instance variables from the parent class
- def return_as_dictio... | Implement the Python class `ElectricAppliances` described below.
Class description:
The ElectricAppliances class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): Creates common instance variables from the parent class
- def return_as_dictio... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class ElectricAppliances:
"""The ElectricAppliances class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Creates common instance variables from the parent class"""
<|body_0|>
def return_as_dictionary(self):
"""Function ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ElectricAppliances:
"""The ElectricAppliances class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Creates common instance variables from the parent class"""
Inventory.__init__(self, product_code, description, market_price, rental_price)
... | the_stack_v2_python_sparse | students/JoeNunnelley/lesson01/assignment/inventory_management/electric_appliances.py | JavaRod/SP_Python220B_2019 | train | 1 |
4cee7a401b7bf864752d86b0923e2a281bd8afbd | [
"assert 1 <= height <= len(lowercase) and 1 <= width <= len(lowercase)\nself.game = game\nself.width = width\nself.height = height\nself.left = width * height\nself.cells = [[Cell(self, x, y) for x in range(width)] for y in range(height)]",
"for mine_cell in sample(range(self.width * self.height), num_mines):\n ... | <|body_start_0|>
assert 1 <= height <= len(lowercase) and 1 <= width <= len(lowercase)
self.game = game
self.width = width
self.height = height
self.left = width * height
self.cells = [[Cell(self, x, y) for x in range(width)] for y in range(height)]
<|end_body_0|>
<|body... | The board. | Board | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Board:
"""The board."""
def __init__(self, game, width, height):
"""Create the board. Set game, width, height, # cells left, and create the raw grid."""
<|body_0|>
def place_mines(self, num_mines):
"""PLace mines and update neighbors' mine counts."""
<|bo... | stack_v2_sparse_classes_10k_train_006622 | 5,366 | no_license | [
{
"docstring": "Create the board. Set game, width, height, # cells left, and create the raw grid.",
"name": "__init__",
"signature": "def __init__(self, game, width, height)"
},
{
"docstring": "PLace mines and update neighbors' mine counts.",
"name": "place_mines",
"signature": "def plac... | 3 | stack_v2_sparse_classes_30k_test_000398 | Implement the Python class `Board` described below.
Class description:
The board.
Method signatures and docstrings:
- def __init__(self, game, width, height): Create the board. Set game, width, height, # cells left, and create the raw grid.
- def place_mines(self, num_mines): PLace mines and update neighbors' mine co... | Implement the Python class `Board` described below.
Class description:
The board.
Method signatures and docstrings:
- def __init__(self, game, width, height): Create the board. Set game, width, height, # cells left, and create the raw grid.
- def place_mines(self, num_mines): PLace mines and update neighbors' mine co... | 2244d63607be13c70c531a6e3064f85074111ca7 | <|skeleton|>
class Board:
"""The board."""
def __init__(self, game, width, height):
"""Create the board. Set game, width, height, # cells left, and create the raw grid."""
<|body_0|>
def place_mines(self, num_mines):
"""PLace mines and update neighbors' mine counts."""
<|bo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Board:
"""The board."""
def __init__(self, game, width, height):
"""Create the board. Set game, width, height, # cells left, and create the raw grid."""
assert 1 <= height <= len(lowercase) and 1 <= width <= len(lowercase)
self.game = game
self.width = width
self.h... | the_stack_v2_python_sparse | HARD/minesweeper/minesweeper.py | jenihuang/hb_challenges | train | 2 |
43c22824a723ec4640cdfa82cb61ec9d795b9b0d | [
"self.logger = utils.get_logger()\nconstants = models.get_asset_dicts('preferences')\nfor key, value in constants.items():\n setattr(self, key, value)",
"for option, option_dict in self.OPTIONS.items():\n option_dict['handle'] = option\n for key, value in self.DEFAULTS.items():\n if option_dict.ge... | <|body_start_0|>
self.logger = utils.get_logger()
constants = models.get_asset_dicts('preferences')
for key, value in constants.items():
setattr(self, key, value)
<|end_body_0|>
<|body_start_1|>
for option, option_dict in self.OPTIONS.items():
option_dict['handle... | Preferences for the webapp are an object: this makes them easier to work with in routes.py, etc. since we can sweep more of the business logic under the rug of methods here, etc. Below, you'll see us setting some constants from assets/prefrence.py. In this version of the app, preferences are 'assets' similar to how we'... | Preferences | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Preferences:
"""Preferences for the webapp are an object: this makes them easier to work with in routes.py, etc. since we can sweep more of the business logic under the rug of methods here, etc. Below, you'll see us setting some constants from assets/prefrence.py. In this version of the app, pref... | stack_v2_sparse_classes_10k_train_006623 | 9,041 | permissive | [
{
"docstring": "Initialize a logger and set the constants, which are just the dictionaries from the assets/preferences.py module.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns a representation of the prefrences object. Returns as JSON by default; set 'return_... | 2 | stack_v2_sparse_classes_30k_train_006936 | Implement the Python class `Preferences` described below.
Class description:
Preferences for the webapp are an object: this makes them easier to work with in routes.py, etc. since we can sweep more of the business logic under the rug of methods here, etc. Below, you'll see us setting some constants from assets/prefren... | Implement the Python class `Preferences` described below.
Class description:
Preferences for the webapp are an object: this makes them easier to work with in routes.py, etc. since we can sweep more of the business logic under the rug of methods here, etc. Below, you'll see us setting some constants from assets/prefren... | 38fb75a830b365e6e640e64c816501f79e0da8b4 | <|skeleton|>
class Preferences:
"""Preferences for the webapp are an object: this makes them easier to work with in routes.py, etc. since we can sweep more of the business logic under the rug of methods here, etc. Below, you'll see us setting some constants from assets/prefrence.py. In this version of the app, pref... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Preferences:
"""Preferences for the webapp are an object: this makes them easier to work with in routes.py, etc. since we can sweep more of the business logic under the rug of methods here, etc. Below, you'll see us setting some constants from assets/prefrence.py. In this version of the app, preferences are '... | the_stack_v2_python_sparse | v4/app/models/users.py | toconnell/kdm-manager | train | 27 |
0a5bb1426c12ebd56c61368767c85c36a76f1b66 | [
"imageset = experiments[0].imageset\nfor expr in experiments:\n assert expr.imageset == imageset, 'All experiments must share and imageset'\nself.experiments = experiments\nself.reflections = reflections\nself.params = Parameters.from_phil(params.integration)\nself.profile_model_report = None\nself.integration_r... | <|body_start_0|>
imageset = experiments[0].imageset
for expr in experiments:
assert expr.imageset == imageset, 'All experiments must share and imageset'
self.experiments = experiments
self.reflections = reflections
self.params = Parameters.from_phil(params.integration... | A class that does integration directly on the image skipping the shoebox creation step. | ImageIntegrator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageIntegrator:
"""A class that does integration directly on the image skipping the shoebox creation step."""
def __init__(self, experiments, reflections, params):
"""Initialize the integrator :param experiments: The experiment list :param reflections: The reflections to process :pa... | stack_v2_sparse_classes_10k_train_006624 | 20,571 | permissive | [
{
"docstring": "Initialize the integrator :param experiments: The experiment list :param reflections: The reflections to process :param params: The parameters to use",
"name": "__init__",
"signature": "def __init__(self, experiments, reflections, params)"
},
{
"docstring": "Integrate the data",
... | 2 | null | Implement the Python class `ImageIntegrator` described below.
Class description:
A class that does integration directly on the image skipping the shoebox creation step.
Method signatures and docstrings:
- def __init__(self, experiments, reflections, params): Initialize the integrator :param experiments: The experimen... | Implement the Python class `ImageIntegrator` described below.
Class description:
A class that does integration directly on the image skipping the shoebox creation step.
Method signatures and docstrings:
- def __init__(self, experiments, reflections, params): Initialize the integrator :param experiments: The experimen... | 77d66c719b5746f37af51ad593e2941ed6fbba17 | <|skeleton|>
class ImageIntegrator:
"""A class that does integration directly on the image skipping the shoebox creation step."""
def __init__(self, experiments, reflections, params):
"""Initialize the integrator :param experiments: The experiment list :param reflections: The reflections to process :pa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImageIntegrator:
"""A class that does integration directly on the image skipping the shoebox creation step."""
def __init__(self, experiments, reflections, params):
"""Initialize the integrator :param experiments: The experiment list :param reflections: The reflections to process :param params: T... | the_stack_v2_python_sparse | modules/dials/algorithms/integration/image_integrator.py | jorgediazjr/dials-dev20191018 | train | 0 |
4b0a65bef9915f8dc51f3df7c6568a48896e096d | [
"res = 0\nself.grid = grid\nself.visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]\nfor i in range(len(grid)):\n for j in range(len(grid[0])):\n res = max(res, self.dfs(i, j))\nreturn res",
"if i < 0 or i >= len(self.grid) or j < 0 or (j >= len(self.grid[0])) or (not self.grid[i... | <|body_start_0|>
res = 0
self.grid = grid
self.visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]
for i in range(len(grid)):
for j in range(len(grid[0])):
res = max(res, self.dfs(i, j))
return res
<|end_body_0|>
<|body_start_1|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxAreaOfIsland(self, grid):
"""Args: grid: list[list[int]] Return: int"""
<|body_0|>
def dfs(self, i, j):
"""Args: i: int j: int Return: area: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = 0
self.grid = grid
... | stack_v2_sparse_classes_10k_train_006625 | 1,091 | no_license | [
{
"docstring": "Args: grid: list[list[int]] Return: int",
"name": "maxAreaOfIsland",
"signature": "def maxAreaOfIsland(self, grid)"
},
{
"docstring": "Args: i: int j: int Return: area: int",
"name": "dfs",
"signature": "def dfs(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004448 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaOfIsland(self, grid): Args: grid: list[list[int]] Return: int
- def dfs(self, i, j): Args: i: int j: int Return: area: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaOfIsland(self, grid): Args: grid: list[list[int]] Return: int
- def dfs(self, i, j): Args: i: int j: int Return: area: int
<|skeleton|>
class Solution:
def maxAr... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def maxAreaOfIsland(self, grid):
"""Args: grid: list[list[int]] Return: int"""
<|body_0|>
def dfs(self, i, j):
"""Args: i: int j: int Return: area: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxAreaOfIsland(self, grid):
"""Args: grid: list[list[int]] Return: int"""
res = 0
self.grid = grid
self.visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]
for i in range(len(grid)):
for j in range(len(grid[0])):
... | the_stack_v2_python_sparse | code/695. 岛屿的最大面积.py | AiZhanghan/Leetcode | train | 0 | |
50906f4b24f41bd4318d734b696012bbb0c5c0e2 | [
"super().__init__(track_interval=track_interval, track_offset=track_offset, verbose=verbose, track_schedule=track_schedule)\nself._epsilon = epsilon\nwarnings.warn('StoppingCriterion only applies to SGD without momentum.')",
"ext = []\nif self.is_active(global_step):\n ext.append(BatchGradTransforms_SumGradSqu... | <|body_start_0|>
super().__init__(track_interval=track_interval, track_offset=track_offset, verbose=verbose, track_schedule=track_schedule)
self._epsilon = epsilon
warnings.warn('StoppingCriterion only applies to SGD without momentum.')
<|end_body_0|>
<|body_start_1|>
ext = []
i... | Evidence-based (EB) early-stopping criterion. Note: Proposed in - Mahsereci, M., Balles, L., Lassner, C., & Hennig, P., Early stopping without a validation set (2017). | EarlyStopping | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EarlyStopping:
"""Evidence-based (EB) early-stopping criterion. Note: Proposed in - Mahsereci, M., Balles, L., Lassner, C., & Hennig, P., Early stopping without a validation set (2017)."""
def __init__(self, track_interval=1, track_offset=0, epsilon=1e-05, verbose=False, track_schedule=None)... | stack_v2_sparse_classes_10k_train_006626 | 3,188 | permissive | [
{
"docstring": "Initialize. Args: track_interval (int): Tracking rate. epsilon (float): Stabilization constant. Defaults to 0.0. verbose (bool): Turns on verbose mode. Defaults to ``False``.",
"name": "__init__",
"signature": "def __init__(self, track_interval=1, track_offset=0, epsilon=1e-05, verbose=F... | 4 | stack_v2_sparse_classes_30k_train_003407 | Implement the Python class `EarlyStopping` described below.
Class description:
Evidence-based (EB) early-stopping criterion. Note: Proposed in - Mahsereci, M., Balles, L., Lassner, C., & Hennig, P., Early stopping without a validation set (2017).
Method signatures and docstrings:
- def __init__(self, track_interval=1... | Implement the Python class `EarlyStopping` described below.
Class description:
Evidence-based (EB) early-stopping criterion. Note: Proposed in - Mahsereci, M., Balles, L., Lassner, C., & Hennig, P., Early stopping without a validation set (2017).
Method signatures and docstrings:
- def __init__(self, track_interval=1... | 5bd5ab3cda03eda0b0bf276f29d5c28b83d70b06 | <|skeleton|>
class EarlyStopping:
"""Evidence-based (EB) early-stopping criterion. Note: Proposed in - Mahsereci, M., Balles, L., Lassner, C., & Hennig, P., Early stopping without a validation set (2017)."""
def __init__(self, track_interval=1, track_offset=0, epsilon=1e-05, verbose=False, track_schedule=None)... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EarlyStopping:
"""Evidence-based (EB) early-stopping criterion. Note: Proposed in - Mahsereci, M., Balles, L., Lassner, C., & Hennig, P., Early stopping without a validation set (2017)."""
def __init__(self, track_interval=1, track_offset=0, epsilon=1e-05, verbose=False, track_schedule=None):
"""... | the_stack_v2_python_sparse | cockpit/quantities/early_stopping.py | MeNicefellow/cockpit | train | 0 |
4ea8d5f89063d53d94eae68df1e35943c20ac8f4 | [
"if np.isscalar(times):\n t = np.asarray([times])\nelse:\n t = np.asarray(times)\nif np.isscalar(data):\n d = data * np.ones((t.size,))\nelse:\n d = np.asarray(data)\nreturn (d, t)",
"if len(data.shape) != 1:\n raise EquationException('{}: Invalid number of dimensions in prescribed scalar data. Exp... | <|body_start_0|>
if np.isscalar(times):
t = np.asarray([times])
else:
t = np.asarray(times)
if np.isscalar(data):
d = data * np.ones((t.size,))
else:
d = np.asarray(data)
return (d, t)
<|end_body_0|>
<|body_start_1|>
if len... | PrescribedScalarParameter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrescribedScalarParameter:
def _setScalarData(self, data, times=0):
"""Set prescribed scalar data appropriately."""
<|body_0|>
def _verifySettingsPrescribedScalarData(self, name, data, times):
"""Verify the structure of the prescribed data."""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k_train_006627 | 1,257 | permissive | [
{
"docstring": "Set prescribed scalar data appropriately.",
"name": "_setScalarData",
"signature": "def _setScalarData(self, data, times=0)"
},
{
"docstring": "Verify the structure of the prescribed data.",
"name": "_verifySettingsPrescribedScalarData",
"signature": "def _verifySettingsP... | 2 | stack_v2_sparse_classes_30k_train_007040 | Implement the Python class `PrescribedScalarParameter` described below.
Class description:
Implement the PrescribedScalarParameter class.
Method signatures and docstrings:
- def _setScalarData(self, data, times=0): Set prescribed scalar data appropriately.
- def _verifySettingsPrescribedScalarData(self, name, data, t... | Implement the Python class `PrescribedScalarParameter` described below.
Class description:
Implement the PrescribedScalarParameter class.
Method signatures and docstrings:
- def _setScalarData(self, data, times=0): Set prescribed scalar data appropriately.
- def _verifySettingsPrescribedScalarData(self, name, data, t... | eba9fabddfa4ef439737807ef30978a52ab55afb | <|skeleton|>
class PrescribedScalarParameter:
def _setScalarData(self, data, times=0):
"""Set prescribed scalar data appropriately."""
<|body_0|>
def _verifySettingsPrescribedScalarData(self, name, data, times):
"""Verify the structure of the prescribed data."""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PrescribedScalarParameter:
def _setScalarData(self, data, times=0):
"""Set prescribed scalar data appropriately."""
if np.isscalar(times):
t = np.asarray([times])
else:
t = np.asarray(times)
if np.isscalar(data):
d = data * np.ones((t.size,))... | the_stack_v2_python_sparse | py/DREAM/Settings/Equations/PrescribedScalarParameter.py | anymodel/DREAM-1 | train | 0 | |
24afe08196974e94b7463e4bd76b024529fbe545 | [
"self.Wz = np.random.normal(size=(i + h, h))\nself.Wr = np.random.normal(size=(i + h, h))\nself.Wh = np.random.normal(size=(i + h, 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))",
"concat = np.concatenate... | <|body_start_0|>
self.Wz = np.random.normal(size=(i + h, h))
self.Wr = np.random.normal(size=(i + h, h))
self.Wh = np.random.normal(size=(i + h, 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... | Represents a gated recurrent unit | GRUCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRUCell:
"""Represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""Class constructor"""
<|body_0|>
def forward(self, h_prev, x_t):
"""Performs forward propagation for one time step. Returns: h_next, y"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_006628 | 1,724 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, i, h, o)"
},
{
"docstring": "Performs forward propagation for one time step. Returns: h_next, y",
"name": "forward",
"signature": "def forward(self, h_prev, x_t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004138 | Implement the Python class `GRUCell` described below.
Class description:
Represents a gated recurrent unit
Method signatures and docstrings:
- def __init__(self, i, h, o): Class constructor
- def forward(self, h_prev, x_t): Performs forward propagation for one time step. Returns: h_next, y | Implement the Python class `GRUCell` described below.
Class description:
Represents a gated recurrent unit
Method signatures and docstrings:
- def __init__(self, i, h, o): Class constructor
- def forward(self, h_prev, x_t): Performs forward propagation for one time step. Returns: h_next, y
<|skeleton|>
class GRUCell... | 161e33b23d398d7d01ad0d7740b78dda3f27e787 | <|skeleton|>
class GRUCell:
"""Represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""Class constructor"""
<|body_0|>
def forward(self, h_prev, x_t):
"""Performs forward propagation for one time step. Returns: h_next, y"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GRUCell:
"""Represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""Class constructor"""
self.Wz = np.random.normal(size=(i + h, h))
self.Wr = np.random.normal(size=(i + h, h))
self.Wh = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/2-gru_cell.py | felipeserna/holbertonschool-machine_learning | train | 0 |
dd505beeab289a88129187e103c67ad510c5a85f | [
"if path is None:\n outpath = os.path.dirname(os.path.abspath(configfile))\nelse:\n outpath = path\nself.config = Configuration(configfile, outpath=path)\nself.pixel = pixel\nself.nside = nside",
"if not self.config.galfile_pixelized:\n raise ValueError('Code only runs with pixelized galfile.')\nself.con... | <|body_start_0|>
if path is None:
outpath = os.path.dirname(os.path.abspath(configfile))
else:
outpath = path
self.config = Configuration(configfile, outpath=path)
self.pixel = pixel
self.nside = nside
<|end_body_0|>
<|body_start_1|>
if not self.c... | Class to run redmapper zmask randoms on a single healpix pixel, for distributed runs. | RunZmaskPixelTask | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunZmaskPixelTask:
"""Class to run redmapper zmask randoms on a single healpix pixel, for distributed runs."""
def __init__(self, configfile, pixel, nside, path=None):
"""Instantiate a RunZmaskPixelTask. Parameters ---------- configfile: `str` Configuration yaml filename. pixel: `int... | stack_v2_sparse_classes_10k_train_006629 | 10,033 | permissive | [
{
"docstring": "Instantiate a RunZmaskPixelTask. Parameters ---------- configfile: `str` Configuration yaml filename. pixel: `int` Healpix pixel to run on. nside: `int` Healpix nside associated with pixel. path: `str`, optional Output path. Default is None, use same absolute path as configfile.",
"name": "_... | 2 | stack_v2_sparse_classes_30k_train_006441 | Implement the Python class `RunZmaskPixelTask` described below.
Class description:
Class to run redmapper zmask randoms on a single healpix pixel, for distributed runs.
Method signatures and docstrings:
- def __init__(self, configfile, pixel, nside, path=None): Instantiate a RunZmaskPixelTask. Parameters ---------- c... | Implement the Python class `RunZmaskPixelTask` described below.
Class description:
Class to run redmapper zmask randoms on a single healpix pixel, for distributed runs.
Method signatures and docstrings:
- def __init__(self, configfile, pixel, nside, path=None): Instantiate a RunZmaskPixelTask. Parameters ---------- c... | d3a8b432c2f3a20aa518a7781c0f2aa315624855 | <|skeleton|>
class RunZmaskPixelTask:
"""Class to run redmapper zmask randoms on a single healpix pixel, for distributed runs."""
def __init__(self, configfile, pixel, nside, path=None):
"""Instantiate a RunZmaskPixelTask. Parameters ---------- configfile: `str` Configuration yaml filename. pixel: `int... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RunZmaskPixelTask:
"""Class to run redmapper zmask randoms on a single healpix pixel, for distributed runs."""
def __init__(self, configfile, pixel, nside, path=None):
"""Instantiate a RunZmaskPixelTask. Parameters ---------- configfile: `str` Configuration yaml filename. pixel: `int` Healpix pix... | the_stack_v2_python_sparse | redmapper/pipeline/redmappertask.py | erykoff/redmapper | train | 20 |
a9085eaf7a446c54f2a7226b5c8e7ae9a6661930 | [
"super(PositionalEncoding, self).__init__()\nself.d_model = d_model\nself.reverse = reverse\nself.xscale = math.sqrt(self.d_model)\nself.dropout = torch.nn.Dropout(p=dropout_rate)\nself.pe = None\nself.extend_pe(torch.tensor(0.0).expand(1, max_len))\nself._register_load_state_dict_pre_hook(_pre_hook)",
"if self.p... | <|body_start_0|>
super(PositionalEncoding, self).__init__()
self.d_model = d_model
self.reverse = reverse
self.xscale = math.sqrt(self.d_model)
self.dropout = torch.nn.Dropout(p=dropout_rate)
self.pe = None
self.extend_pe(torch.tensor(0.0).expand(1, max_len))
... | Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. Only for the class LegacyRelPositionalEncoding. We remove it in the current class RelPositionalEncoding. | PositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncoding:
"""Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. Only for the class LegacyRelPositionalEncoding. We remove it in the current class R... | stack_v2_sparse_classes_10k_train_006630 | 12,758 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, d_model, dropout_rate, max_len=5000, reverse=False)"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self, x)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_000558 | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. Only for the class LegacyRelPositionalEncodi... | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. Only for the class LegacyRelPositionalEncodi... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class PositionalEncoding:
"""Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. Only for the class LegacyRelPositionalEncoding. We remove it in the current class R... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PositionalEncoding:
"""Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. Only for the class LegacyRelPositionalEncoding. We remove it in the current class RelPositionalE... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transformer/embedding.py | espnet/espnet | train | 7,242 |
ddcb38246886062202b57eb45bb60e8a5de68486 | [
"hash_table = {}\nmax_len = 0\ncur = 0\nfor i, c in enumerate(s):\n if c in hash_table and cur <= hash_table[c]:\n cur = hash_table[c] + 1\n else:\n max_len = max(max_len, i - cur + 1)\n hash_table[c] = i\nreturn max_len",
"L, res, last = (-1, 0, {})\nfor R, char in enumerate(s):\n if ch... | <|body_start_0|>
hash_table = {}
max_len = 0
cur = 0
for i, c in enumerate(s):
if c in hash_table and cur <= hash_table[c]:
cur = hash_table[c] + 1
else:
max_len = max(max_len, i - cur + 1)
hash_table[c] = i
retu... | SolutionF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionF:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
hash_table = {}
max_len = 0
... | stack_v2_sparse_classes_10k_train_006631 | 2,850 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring2",
"signature": "def lengthOfLongestSubstring2(self, s)"
}
] | 2 | null | Implement the Python class `SolutionF` described below.
Class description:
Implement the SolutionF class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): :type s: str :rtype: int | Implement the Python class `SolutionF` described below.
Class description:
Implement the SolutionF class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): :type s: str :rtype: int
<|skeleton|>
class SolutionF:
def lengt... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class SolutionF:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SolutionF:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
hash_table = {}
max_len = 0
cur = 0
for i, c in enumerate(s):
if c in hash_table and cur <= hash_table[c]:
cur = hash_table[c] + 1
else:
... | the_stack_v2_python_sparse | SlidingWindow/q003_longest_substring_without_repeating_characters.py | sevenhe716/LeetCode | train | 0 | |
695c41c7f778557a88479bfc71625ef260bbb207 | [
"jsonconfig.JsonConfig.__init__(self)\nself.hostname = b'esp%05d' % Hostname.getNumber()\nself.activated = True\nself.fallback = True\nself.default = b''",
"result = '%s:\\n' % self.__class__.__name__\nresult += ' Activated :%s\\n' % useful.tostrings(self.activated)\nresult = ' Hostname :%s\\n' % useful.to... | <|body_start_0|>
jsonconfig.JsonConfig.__init__(self)
self.hostname = b'esp%05d' % Hostname.getNumber()
self.activated = True
self.fallback = True
self.default = b''
<|end_body_0|>
<|body_start_1|>
result = '%s:\n' % self.__class__.__name__
result += ' Activate... | Wifi station configuration class | StationConfig | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StationConfig:
"""Wifi station configuration class"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __repr__(self):
"""Display the content of wifi station"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
jsonconfig.JsonConfig.__init__(self... | stack_v2_sparse_classes_10k_train_006632 | 8,871 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Display the content of wifi station",
"name": "__repr__",
"signature": "def __repr__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001506 | Implement the Python class `StationConfig` described below.
Class description:
Wifi station configuration class
Method signatures and docstrings:
- def __init__(self): Constructor
- def __repr__(self): Display the content of wifi station | Implement the Python class `StationConfig` described below.
Class description:
Wifi station configuration class
Method signatures and docstrings:
- def __init__(self): Constructor
- def __repr__(self): Display the content of wifi station
<|skeleton|>
class StationConfig:
"""Wifi station configuration class"""
... | d86814625a7cd2f7e5fa01b8e1652efc811cef3a | <|skeleton|>
class StationConfig:
"""Wifi station configuration class"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __repr__(self):
"""Display the content of wifi station"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StationConfig:
"""Wifi station configuration class"""
def __init__(self):
"""Constructor"""
jsonconfig.JsonConfig.__init__(self)
self.hostname = b'esp%05d' % Hostname.getNumber()
self.activated = True
self.fallback = True
self.default = b''
def __repr_... | the_stack_v2_python_sparse | modules/lib/wifi/station.py | antiquefu/pycameresp | train | 0 |
eb91aaefae2b9f54370dbe8db4d03cea4a8158e0 | [
"if k == 1:\n return 1\nli = [1, 1]\nSUM = li[-1] + li[-2]\nwhile SUM < k:\n SUM = li[-1] + li[-2]\n if SUM <= k:\n li.append(SUM)\ncnt = 0\nrem = k\ni = len(li) - 1\nwhile rem != 0:\n rem -= li[i]\n if rem == 0:\n cnt += 1\n return cnt\n elif rem > 0:\n cnt += 1\n ... | <|body_start_0|>
if k == 1:
return 1
li = [1, 1]
SUM = li[-1] + li[-2]
while SUM < k:
SUM = li[-1] + li[-2]
if SUM <= k:
li.append(SUM)
cnt = 0
rem = k
i = len(li) - 1
while rem != 0:
rem -= l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMinFibonacciNumbers(self, k):
""":type k: int :rtype: int"""
<|body_0|>
def findMinFibonacciNumbers(self, k):
""":type k: int :rtype: int"""
<|body_1|>
def findMinFibonacciNumbers(self, k):
""":type k: int :rtype: int"""
... | stack_v2_sparse_classes_10k_train_006633 | 1,677 | no_license | [
{
"docstring": ":type k: int :rtype: int",
"name": "findMinFibonacciNumbers",
"signature": "def findMinFibonacciNumbers(self, k)"
},
{
"docstring": ":type k: int :rtype: int",
"name": "findMinFibonacciNumbers",
"signature": "def findMinFibonacciNumbers(self, k)"
},
{
"docstring":... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinFibonacciNumbers(self, k): :type k: int :rtype: int
- def findMinFibonacciNumbers(self, k): :type k: int :rtype: int
- def findMinFibonacciNumbers(self, k): :type k: i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinFibonacciNumbers(self, k): :type k: int :rtype: int
- def findMinFibonacciNumbers(self, k): :type k: int :rtype: int
- def findMinFibonacciNumbers(self, k): :type k: i... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def findMinFibonacciNumbers(self, k):
""":type k: int :rtype: int"""
<|body_0|>
def findMinFibonacciNumbers(self, k):
""":type k: int :rtype: int"""
<|body_1|>
def findMinFibonacciNumbers(self, k):
""":type k: int :rtype: int"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findMinFibonacciNumbers(self, k):
""":type k: int :rtype: int"""
if k == 1:
return 1
li = [1, 1]
SUM = li[-1] + li[-2]
while SUM < k:
SUM = li[-1] + li[-2]
if SUM <= k:
li.append(SUM)
cnt = 0
... | the_stack_v2_python_sparse | 1414_Find_the_Minimum_Number_of_Fibonacci_Numbers_Whose_Sum_Is_K.py | bingli8802/leetcode | train | 0 | |
4634506925d36b6e900e9db6887cda8232712270 | [
"self._api_url = url\nself._session = requests.Session()\nself._session.headers['x-api-key'] = api_key\nself._session.verify = verify\nif not url:\n raise ValueError('IronNet URL must be set')\nif not api_key:\n raise ValueError('IronNet API key must be set')",
"resp: Response = self._session.get(self._api_... | <|body_start_0|>
self._api_url = url
self._session = requests.Session()
self._session.headers['x-api-key'] = api_key
self._session.verify = verify
if not url:
raise ValueError('IronNet URL must be set')
if not api_key:
raise ValueError('IronNet API... | IronNet client | IronNetClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IronNetClient:
"""IronNet client"""
def __init__(self, url: str, api_key: str, verify: bool=True):
"""Constructor. :param url: IronNet url :param api_key: IronNet API key :param verify: Verify SSL connections"""
<|body_0|>
def query(self) -> Iterator[IronNetItem]:
... | stack_v2_sparse_classes_10k_train_006634 | 1,867 | permissive | [
{
"docstring": "Constructor. :param url: IronNet url :param api_key: IronNet API key :param verify: Verify SSL connections",
"name": "__init__",
"signature": "def __init__(self, url: str, api_key: str, verify: bool=True)"
},
{
"docstring": "Process the feed URL and return any indicators. :return... | 2 | null | Implement the Python class `IronNetClient` described below.
Class description:
IronNet client
Method signatures and docstrings:
- def __init__(self, url: str, api_key: str, verify: bool=True): Constructor. :param url: IronNet url :param api_key: IronNet API key :param verify: Verify SSL connections
- def query(self) ... | Implement the Python class `IronNetClient` described below.
Class description:
IronNet client
Method signatures and docstrings:
- def __init__(self, url: str, api_key: str, verify: bool=True): Constructor. :param url: IronNet url :param api_key: IronNet API key :param verify: Verify SSL connections
- def query(self) ... | d00a0243946ded25b5d06bdefd9b40015dea9b80 | <|skeleton|>
class IronNetClient:
"""IronNet client"""
def __init__(self, url: str, api_key: str, verify: bool=True):
"""Constructor. :param url: IronNet url :param api_key: IronNet API key :param verify: Verify SSL connections"""
<|body_0|>
def query(self) -> Iterator[IronNetItem]:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IronNetClient:
"""IronNet client"""
def __init__(self, url: str, api_key: str, verify: bool=True):
"""Constructor. :param url: IronNet url :param api_key: IronNet API key :param verify: Verify SSL connections"""
self._api_url = url
self._session = requests.Session()
self._... | the_stack_v2_python_sparse | external-import/ironnet/src/ironnet/client.py | OpenCTI-Platform/connectors | train | 254 |
f76873a736f00306e3a5983aabd788ebc298c3d4 | [
"self.context = zmq.Context()\nself.socket = self.context.socket(zmq.PAIR)\nself.socket.bind('tcp://*:%s' % port)",
"if data.status == const.DATA_STATUS_END:\n self.socket.send_json(dict(key='end', document='... end of transmission ...'))\n self.context.destroy()\nif data.status == const.DATA_STATUS_DIM:\n ... | <|body_start_0|>
self.context = zmq.Context()
self.socket = self.context.socket(zmq.PAIR)
self.socket.bind('tcp://*:%s' % port)
<|end_body_0|>
<|body_start_1|>
if data.status == const.DATA_STATUS_END:
self.socket.send_json(dict(key='end', document='... end of transmission ..... | This class represents ZeroMQ server. | zmq_sen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class zmq_sen:
"""This class represents ZeroMQ server."""
def __init__(self, port=None):
"""Constructor This constructor creates zmq Context and socket for the zmq.PAIR. It binds with the port and will accept one connection. Parameters ---------- port : str serving port"""
<|body_0... | stack_v2_sparse_classes_10k_train_006635 | 6,226 | no_license | [
{
"docstring": "Constructor This constructor creates zmq Context and socket for the zmq.PAIR. It binds with the port and will accept one connection. Parameters ---------- port : str serving port",
"name": "__init__",
"signature": "def __init__(self, port=None)"
},
{
"docstring": "This sends out ... | 2 | stack_v2_sparse_classes_30k_train_002603 | Implement the Python class `zmq_sen` described below.
Class description:
This class represents ZeroMQ server.
Method signatures and docstrings:
- def __init__(self, port=None): Constructor This constructor creates zmq Context and socket for the zmq.PAIR. It binds with the port and will accept one connection. Paramete... | Implement the Python class `zmq_sen` described below.
Class description:
This class represents ZeroMQ server.
Method signatures and docstrings:
- def __init__(self, port=None): Constructor This constructor creates zmq Context and socket for the zmq.PAIR. It binds with the port and will accept one connection. Paramete... | c8e9ef7c9cba497479faf60136f6810c41d8bd3c | <|skeleton|>
class zmq_sen:
"""This class represents ZeroMQ server."""
def __init__(self, port=None):
"""Constructor This constructor creates zmq Context and socket for the zmq.PAIR. It binds with the port and will accept one connection. Parameters ---------- port : str serving port"""
<|body_0... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class zmq_sen:
"""This class represents ZeroMQ server."""
def __init__(self, port=None):
"""Constructor This constructor creates zmq Context and socket for the zmq.PAIR. It binds with the port and will accept one connection. Parameters ---------- port : str serving port"""
self.context = zmq.Co... | the_stack_v2_python_sparse | dquality/clients/zmq_client.py | AdvancedPhotonSource/data-quality | train | 2 |
037d5658e5e85f09b18e9b0cab84902de5aed6fe | [
"super().__init__()\nassert len(fft_sizes) == len(hop_sizes) == len(win_lengths)\nself.stft_losses = nn.LayerList()\nfor fs, ss, wl in zip(fft_sizes, hop_sizes, win_lengths):\n self.stft_losses.append(STFTLoss(fs, ss, wl, window))",
"if len(x.shape) == 3:\n x = x.reshape([-1, x.shape[2]])\n y = y.reshape... | <|body_start_0|>
super().__init__()
assert len(fft_sizes) == len(hop_sizes) == len(win_lengths)
self.stft_losses = nn.LayerList()
for fs, ss, wl in zip(fft_sizes, hop_sizes, win_lengths):
self.stft_losses.append(STFTLoss(fs, ss, wl, window))
<|end_body_0|>
<|body_start_1|>
... | Multi resolution STFT loss module. | MultiResolutionSTFTLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiResolutionSTFTLoss:
"""Multi resolution STFT loss module."""
def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'):
"""Initialize Multi resolution STFT loss module. Args: fft_sizes (list): List of FFT sizes. hop_si... | stack_v2_sparse_classes_10k_train_006636 | 46,210 | permissive | [
{
"docstring": "Initialize Multi resolution STFT loss module. Args: fft_sizes (list): List of FFT sizes. hop_sizes (list): List of hop sizes. win_lengths (list): List of window lengths. window (str): Window function type.",
"name": "__init__",
"signature": "def __init__(self, fft_sizes=[1024, 2048, 512]... | 2 | stack_v2_sparse_classes_30k_train_005797 | Implement the Python class `MultiResolutionSTFTLoss` described below.
Class description:
Multi resolution STFT loss module.
Method signatures and docstrings:
- def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'): Initialize Multi resolution STFT loss ... | Implement the Python class `MultiResolutionSTFTLoss` described below.
Class description:
Multi resolution STFT loss module.
Method signatures and docstrings:
- def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'): Initialize Multi resolution STFT loss ... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class MultiResolutionSTFTLoss:
"""Multi resolution STFT loss module."""
def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'):
"""Initialize Multi resolution STFT loss module. Args: fft_sizes (list): List of FFT sizes. hop_si... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiResolutionSTFTLoss:
"""Multi resolution STFT loss module."""
def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'):
"""Initialize Multi resolution STFT loss module. Args: fft_sizes (list): List of FFT sizes. hop_sizes (list): L... | the_stack_v2_python_sparse | paddlespeech/t2s/modules/losses.py | anniyanvr/DeepSpeech-1 | train | 0 |
4b21f623501ef2b4eae6d072f9bf3119a3e067f1 | [
"res = []\nif not root:\n return []\nq = collections.deque([root])\nwhile q:\n for _ in range(len(q)):\n node = q.popleft()\n if node:\n res.append(node.val)\n q.append(node.left)\n q.append(node.right)\n else:\n res.append('null')\nreturn str(r... | <|body_start_0|>
res = []
if not root:
return []
q = collections.deque([root])
while q:
for _ in range(len(q)):
node = q.popleft()
if node:
res.append(node.val)
q.append(node.left)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_006637 | 3,153 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_006422 | 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:... | fc1b0bec0e28d31e9a6ff722b3a66eacb0278148 | <|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"""
res = []
if not root:
return []
q = collections.deque([root])
while q:
for _ in range(len(q)):
node = q.popleft()
... | the_stack_v2_python_sparse | 树/297二叉树的序列化与反序列化.py | LeopoldACC/Algorithm | train | 2 | |
a706247e5979fa7a63f8e16f7059b995cc979899 | [
"new_head = None\nwhile head:\n curr = ListNode(head.val)\n curr.next, new_head = (new_head, curr)\n head = head.next\nreturn new_head",
"if not head or not head.next:\n return head\nnew = Solution().reverseList2(head.next)\nhead.next.next = head\nhead.next = None\nreturn new"
] | <|body_start_0|>
new_head = None
while head:
curr = ListNode(head.val)
curr.next, new_head = (new_head, curr)
head = head.next
return new_head
<|end_body_0|>
<|body_start_1|>
if not head or not head.next:
return head
new = Solution... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
"""Iterative solution"""
<|body_0|>
def reverseList2(self, head):
"""Recursive solution"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
new_head = None
while head:
curr = ListNode(head.val)
... | stack_v2_sparse_classes_10k_train_006638 | 613 | no_license | [
{
"docstring": "Iterative solution",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": "Recursive solution",
"name": "reverseList2",
"signature": "def reverseList2(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000597 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): Iterative solution
- def reverseList2(self, head): Recursive solution | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): Iterative solution
- def reverseList2(self, head): Recursive solution
<|skeleton|>
class Solution:
def reverseList(self, head):
"""Iter... | f33d004d7629d46fbc5670f5b384f8a604d7f1e7 | <|skeleton|>
class Solution:
def reverseList(self, head):
"""Iterative solution"""
<|body_0|>
def reverseList2(self, head):
"""Recursive solution"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList(self, head):
"""Iterative solution"""
new_head = None
while head:
curr = ListNode(head.val)
curr.next, new_head = (new_head, curr)
head = head.next
return new_head
def reverseList2(self, head):
"""Recurs... | the_stack_v2_python_sparse | Reverse Linked List.py | aulee888/LeetCode | train | 0 | |
6117b6be55b0572460a81b2633823993623b1741 | [
"super(LevelThree, self).__init__(screen)\nself.villain_one = None\nself.villain_two = None\nself.villain_three = None\nself._set_villain()",
"self.villain_one = donkey.Donkey(100, constants.THREE_Y, 0, 500)\nself.active_sprite_list.add(self.villain_one)\nself.villain_two = donkey.Donkey(900, constants.TWO_Y, 700... | <|body_start_0|>
super(LevelThree, self).__init__(screen)
self.villain_one = None
self.villain_two = None
self.villain_three = None
self._set_villain()
<|end_body_0|>
<|body_start_1|>
self.villain_one = donkey.Donkey(100, constants.THREE_Y, 0, 500)
self.active_sp... | Class which defines the third level of the game | LevelThree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LevelThree:
"""Class which defines the third level of the game"""
def __init__(self, screen):
"""Constructor for the third level of the game"""
<|body_0|>
def _set_villain(self):
"""Sets the number of donkeys and their positions for the third level of the game"""... | stack_v2_sparse_classes_10k_train_006639 | 1,964 | no_license | [
{
"docstring": "Constructor for the third level of the game",
"name": "__init__",
"signature": "def __init__(self, screen)"
},
{
"docstring": "Sets the number of donkeys and their positions for the third level of the game",
"name": "_set_villain",
"signature": "def _set_villain(self)"
... | 2 | stack_v2_sparse_classes_30k_train_002933 | Implement the Python class `LevelThree` described below.
Class description:
Class which defines the third level of the game
Method signatures and docstrings:
- def __init__(self, screen): Constructor for the third level of the game
- def _set_villain(self): Sets the number of donkeys and their positions for the third... | Implement the Python class `LevelThree` described below.
Class description:
Class which defines the third level of the game
Method signatures and docstrings:
- def __init__(self, screen): Constructor for the third level of the game
- def _set_villain(self): Sets the number of donkeys and their positions for the third... | 26d629f8348f0110fa84b02009e787a238aff441 | <|skeleton|>
class LevelThree:
"""Class which defines the third level of the game"""
def __init__(self, screen):
"""Constructor for the third level of the game"""
<|body_0|>
def _set_villain(self):
"""Sets the number of donkeys and their positions for the third level of the game"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LevelThree:
"""Class which defines the third level of the game"""
def __init__(self, screen):
"""Constructor for the third level of the game"""
super(LevelThree, self).__init__(screen)
self.villain_one = None
self.villain_two = None
self.villain_three = None
... | the_stack_v2_python_sparse | IIITSERC-ssad_2015_a3_group1-88a823ccd2d0/Akshat Tandon/201503001/levels.py | anirudhdahiya9/Open-data-projecy | train | 1 |
ba762351e78afc6fa40fbc5fdf9079f1bc6cea97 | [
"dic = {}\nfor number in numbers:\n dic[number] = dic.get(number, 0) + 1\nfor number, frequency in dic.items():\n if frequency > len(numbers) // 2:\n return number\nreturn 0",
"count = 1\nnumber = numbers[0]\nfor i in numbers[1:]:\n if number == i:\n count += 1\n else:\n count -= ... | <|body_start_0|>
dic = {}
for number in numbers:
dic[number] = dic.get(number, 0) + 1
for number, frequency in dic.items():
if frequency > len(numbers) // 2:
return number
return 0
<|end_body_0|>
<|body_start_1|>
count = 1
number =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
"""time O(n) space O(n) :param numbers: :return:"""
<|body_0|>
def MoreThanHalfNum_Solution_best(self, numbers):
"""time O(n) space O(1) :param numbers: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_10k_train_006640 | 1,638 | no_license | [
{
"docstring": "time O(n) space O(n) :param numbers: :return:",
"name": "MoreThanHalfNum_Solution",
"signature": "def MoreThanHalfNum_Solution(self, numbers)"
},
{
"docstring": "time O(n) space O(1) :param numbers: :return:",
"name": "MoreThanHalfNum_Solution_best",
"signature": "def Mor... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def MoreThanHalfNum_Solution(self, numbers): time O(n) space O(n) :param numbers: :return:
- def MoreThanHalfNum_Solution_best(self, numbers): time O(n) space O(1) :param numbers... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def MoreThanHalfNum_Solution(self, numbers): time O(n) space O(n) :param numbers: :return:
- def MoreThanHalfNum_Solution_best(self, numbers): time O(n) space O(1) :param numbers... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
"""time O(n) space O(n) :param numbers: :return:"""
<|body_0|>
def MoreThanHalfNum_Solution_best(self, numbers):
"""time O(n) space O(1) :param numbers: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def MoreThanHalfNum_Solution(self, numbers):
"""time O(n) space O(n) :param numbers: :return:"""
dic = {}
for number in numbers:
dic[number] = dic.get(number, 0) + 1
for number, frequency in dic.items():
if frequency > len(numbers) // 2:
... | the_stack_v2_python_sparse | LeetCode/Offer/数组中出现次数超过一半的数字.py | XyK0907/for_work | train | 0 | |
46a57fd7deeb2e147dedeaba00120e4bbf971a25 | [
"self.args = args\nif any((not isinstance(x, Arg) for x in args)):\n raise TypeError('Arguments to Args object should all be Arg objects')\nself.args_by_name = {x.name: x for x in args}",
"attributes = {}\nerrors = []\nfor arg in self.args:\n if arg.name not in dargs and (not arg.IsOptional()):\n err... | <|body_start_0|>
self.args = args
if any((not isinstance(x, Arg) for x in args)):
raise TypeError('Arguments to Args object should all be Arg objects')
self.args_by_name = {x.name: x for x in args}
<|end_body_0|>
<|body_start_1|>
attributes = {}
errors = []
f... | A class to hold a list of argument specs for an argument parser. | Args | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Args:
"""A class to hold a list of argument specs for an argument parser."""
def __init__(self, *args):
"""Constructs an argument parser. Args: args: A list of Arg objects."""
<|body_0|>
def Parse(self, dargs, unresolvable_type=None):
"""Parses a dargs object fro... | stack_v2_sparse_classes_10k_train_006641 | 8,140 | permissive | [
{
"docstring": "Constructs an argument parser. Args: args: A list of Arg objects.",
"name": "__init__",
"signature": "def __init__(self, *args)"
},
{
"docstring": "Parses a dargs object from the test list. Args: dargs: A name/value map of arguments from the test list. unresolvable_type: A type i... | 2 | null | Implement the Python class `Args` described below.
Class description:
A class to hold a list of argument specs for an argument parser.
Method signatures and docstrings:
- def __init__(self, *args): Constructs an argument parser. Args: args: A list of Arg objects.
- def Parse(self, dargs, unresolvable_type=None): Pars... | Implement the Python class `Args` described below.
Class description:
A class to hold a list of argument specs for an argument parser.
Method signatures and docstrings:
- def __init__(self, *args): Constructs an argument parser. Args: args: A list of Arg objects.
- def Parse(self, dargs, unresolvable_type=None): Pars... | a1b0fccd68987d8cd9c89710adc3c04b868347ec | <|skeleton|>
class Args:
"""A class to hold a list of argument specs for an argument parser."""
def __init__(self, *args):
"""Constructs an argument parser. Args: args: A list of Arg objects."""
<|body_0|>
def Parse(self, dargs, unresolvable_type=None):
"""Parses a dargs object fro... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Args:
"""A class to hold a list of argument specs for an argument parser."""
def __init__(self, *args):
"""Constructs an argument parser. Args: args: A list of Arg objects."""
self.args = args
if any((not isinstance(x, Arg) for x in args)):
raise TypeError('Arguments t... | the_stack_v2_python_sparse | py/utils/arg_utils.py | bridder/factory | train | 0 |
b6e462fae276bc2cfbb8d86c9b3165dff01b1cdf | [
"it = iter(test_inputs.split('\\n')) if test_inputs else None\n\ndef uinput():\n return next(it) if it else sys.stdin.readline().rstrip()\nself.s = uinput()",
"chars = list(self.s)\nslen = len(chars)\nresult = set([])\nvis = set([])\nq = deque([(0, '')])\nwhile q:\n pos, prev = q.popleft()\n if pos in vi... | <|body_start_0|>
it = iter(test_inputs.split('\n')) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
self.s = uinput()
<|end_body_0|>
<|body_start_1|>
chars = list(self.s)
slen = len(chars)
result = set([])
... | Ling representation | Ling | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ling:
"""Ling representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
<|body_0|>
def calculate(self):
"""Main calcualtion function of the class"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
it = iter(test_inputs.split... | stack_v2_sparse_classes_10k_train_006642 | 3,411 | permissive | [
{
"docstring": "Default constructor",
"name": "__init__",
"signature": "def __init__(self, test_inputs=None)"
},
{
"docstring": "Main calcualtion function of the class",
"name": "calculate",
"signature": "def calculate(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006470 | Implement the Python class `Ling` described below.
Class description:
Ling representation
Method signatures and docstrings:
- def __init__(self, test_inputs=None): Default constructor
- def calculate(self): Main calcualtion function of the class | Implement the Python class `Ling` described below.
Class description:
Ling representation
Method signatures and docstrings:
- def __init__(self, test_inputs=None): Default constructor
- def calculate(self): Main calcualtion function of the class
<|skeleton|>
class Ling:
"""Ling representation"""
def __init_... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class Ling:
"""Ling representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
<|body_0|>
def calculate(self):
"""Main calcualtion function of the class"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Ling:
"""Ling representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
it = iter(test_inputs.split('\n')) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
self.s = uinput()
def calcul... | the_stack_v2_python_sparse | codeforces/667C_ling.py | snsokolov/contests | train | 1 |
1ff5cf19221fcaf3017c0cc3f48325da8afe2ce5 | [
"try:\n show = db.show_by_id(show_id, session=session)\nexcept NoResultFound:\n raise NotFoundError('Show with ID %s not found' % show_id)\nargs = series_list_parser.parse_args()\nbegin = args.get('begin')\nlatest = args.get('latest')\nreturn jsonify(series_details(show, begin, latest))",
"try:\n show = ... | <|body_start_0|>
try:
show = db.show_by_id(show_id, session=session)
except NoResultFound:
raise NotFoundError('Show with ID %s not found' % show_id)
args = series_list_parser.parse_args()
begin = args.get('begin')
latest = args.get('latest')
retur... | SeriesShowAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeriesShowAPI:
def get(self, show_id, session):
"""Get show details by ID"""
<|body_0|>
def delete(self, show_id, session):
"""Remove series from DB"""
<|body_1|>
def put(self, show_id, session):
"""Set the initial episode of an existing show"""
... | stack_v2_sparse_classes_10k_train_006643 | 47,001 | permissive | [
{
"docstring": "Get show details by ID",
"name": "get",
"signature": "def get(self, show_id, session)"
},
{
"docstring": "Remove series from DB",
"name": "delete",
"signature": "def delete(self, show_id, session)"
},
{
"docstring": "Set the initial episode of an existing show",
... | 3 | stack_v2_sparse_classes_30k_train_004018 | Implement the Python class `SeriesShowAPI` described below.
Class description:
Implement the SeriesShowAPI class.
Method signatures and docstrings:
- def get(self, show_id, session): Get show details by ID
- def delete(self, show_id, session): Remove series from DB
- def put(self, show_id, session): Set the initial e... | Implement the Python class `SeriesShowAPI` described below.
Class description:
Implement the SeriesShowAPI class.
Method signatures and docstrings:
- def get(self, show_id, session): Get show details by ID
- def delete(self, show_id, session): Remove series from DB
- def put(self, show_id, session): Set the initial e... | ea95ff60041beaea9aacbc2d93549e3a6b981dc5 | <|skeleton|>
class SeriesShowAPI:
def get(self, show_id, session):
"""Get show details by ID"""
<|body_0|>
def delete(self, show_id, session):
"""Remove series from DB"""
<|body_1|>
def put(self, show_id, session):
"""Set the initial episode of an existing show"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SeriesShowAPI:
def get(self, show_id, session):
"""Get show details by ID"""
try:
show = db.show_by_id(show_id, session=session)
except NoResultFound:
raise NotFoundError('Show with ID %s not found' % show_id)
args = series_list_parser.parse_args()
... | the_stack_v2_python_sparse | flexget/components/series/api.py | BrutuZ/Flexget | train | 1 | |
a0f4cd9f4e432148002ac1deed7828a87d509312 | [
"self.dt = 1.0 / 365\nself.S_0_1 = 100.0\nself.S_0_2 = 110.0\nself.gamma_0 = 0.0\nself.sigma_1 = 0.2\nself.sigma_2 = 0.15\nself.sigma_gamma = 0.2\nself.theta = 0.15\nself.rho = 0.8\nself.drift_1 = -0.5 * self.sigma_1 * self.sigma_1 * self.dt\nself.drift_2 = -0.5 * self.sigma_2 * self.sigma_2 * self.dt\nself.drift_g... | <|body_start_0|>
self.dt = 1.0 / 365
self.S_0_1 = 100.0
self.S_0_2 = 110.0
self.gamma_0 = 0.0
self.sigma_1 = 0.2
self.sigma_2 = 0.15
self.sigma_gamma = 0.2
self.theta = 0.15
self.rho = 0.8
self.drift_1 = -0.5 * self.sigma_1 * self.sigma_1 *... | Class that simulates the paths for two risky assets with a mean-reverting spread process. | CointegratedSeriesGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CointegratedSeriesGenerator:
"""Class that simulates the paths for two risky assets with a mean-reverting spread process."""
def __init__(self):
"""Constructor."""
<|body_0|>
def run(self, n_steps):
"""Simulate the model. Parameters ---------- n_steps: int Number... | stack_v2_sparse_classes_10k_train_006644 | 4,905 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Simulate the model. Parameters ---------- n_steps: int Number of steps to simulate",
"name": "run",
"signature": "def run(self, n_steps)"
},
{
"docstring": "Dumps data in .csv ... | 3 | stack_v2_sparse_classes_30k_train_002467 | Implement the Python class `CointegratedSeriesGenerator` described below.
Class description:
Class that simulates the paths for two risky assets with a mean-reverting spread process.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def run(self, n_steps): Simulate the model. Parameters ---------... | Implement the Python class `CointegratedSeriesGenerator` described below.
Class description:
Class that simulates the paths for two risky assets with a mean-reverting spread process.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def run(self, n_steps): Simulate the model. Parameters ---------... | 1a3ae97023acff1ee5e2d197a446734117a6fb99 | <|skeleton|>
class CointegratedSeriesGenerator:
"""Class that simulates the paths for two risky assets with a mean-reverting spread process."""
def __init__(self):
"""Constructor."""
<|body_0|>
def run(self, n_steps):
"""Simulate the model. Parameters ---------- n_steps: int Number... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CointegratedSeriesGenerator:
"""Class that simulates the paths for two risky assets with a mean-reverting spread process."""
def __init__(self):
"""Constructor."""
self.dt = 1.0 / 365
self.S_0_1 = 100.0
self.S_0_2 = 110.0
self.gamma_0 = 0.0
self.sigma_1 = 0... | the_stack_v2_python_sparse | Code/Preprocessing/generate_cointegrated_series.py | fdoperezi/Thesis | train | 0 |
3b79480f0f4856185b237652795ba4463b26c5e0 | [
"ret = self.addr\nself.addr = self.addr + size + self.align - 1\nself.addr &= self.mask ^ self.align - 1\nreturn ret",
"addr = self.next_addr(size)\njitter.vm.add_memory_page(addr, PAGE_READ | PAGE_WRITE, '\\x00' * size)\nreturn addr"
] | <|body_start_0|>
ret = self.addr
self.addr = self.addr + size + self.align - 1
self.addr &= self.mask ^ self.align - 1
return ret
<|end_body_0|>
<|body_start_1|>
addr = self.next_addr(size)
jitter.vm.add_memory_page(addr, PAGE_READ | PAGE_WRITE, '\x00' * size)
re... | Light heap simulation | heap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class heap:
"""Light heap simulation"""
def next_addr(self, size):
"""@size: the size to allocate return the future checnk address"""
<|body_0|>
def alloc(self, jitter, size):
"""@jitter: a jitter instance @size: the size to allocate"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_10k_train_006645 | 1,418 | no_license | [
{
"docstring": "@size: the size to allocate return the future checnk address",
"name": "next_addr",
"signature": "def next_addr(self, size)"
},
{
"docstring": "@jitter: a jitter instance @size: the size to allocate",
"name": "alloc",
"signature": "def alloc(self, jitter, size)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007186 | Implement the Python class `heap` described below.
Class description:
Light heap simulation
Method signatures and docstrings:
- def next_addr(self, size): @size: the size to allocate return the future checnk address
- def alloc(self, jitter, size): @jitter: a jitter instance @size: the size to allocate | Implement the Python class `heap` described below.
Class description:
Light heap simulation
Method signatures and docstrings:
- def next_addr(self, size): @size: the size to allocate return the future checnk address
- def alloc(self, jitter, size): @jitter: a jitter instance @size: the size to allocate
<|skeleton|>
... | 3af62274b68f13fc6eba680ef1524e5f215e5c8b | <|skeleton|>
class heap:
"""Light heap simulation"""
def next_addr(self, size):
"""@size: the size to allocate return the future checnk address"""
<|body_0|>
def alloc(self, jitter, size):
"""@jitter: a jitter instance @size: the size to allocate"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class heap:
"""Light heap simulation"""
def next_addr(self, size):
"""@size: the size to allocate return the future checnk address"""
ret = self.addr
self.addr = self.addr + size + self.align - 1
self.addr &= self.mask ^ self.align - 1
return ret
def alloc(self, jit... | the_stack_v2_python_sparse | miasm2/os_dep/common.py | laanwj/miasm | train | 1 |
b828ff4e4b1825a797c76b48622e3db528ac365c | [
"hashmap = {}\nfor index in range(len(nums)):\n if target - nums[index] in hashmap:\n return (index, hashmap.get(target - nums[index]))\n else:\n hashmap[nums[index]] = index",
"lookup = {}\nfor i, num in enumerate(nums):\n if target - num in lookup:\n return [lookup[target - num], i... | <|body_start_0|>
hashmap = {}
for index in range(len(nums)):
if target - nums[index] in hashmap:
return (index, hashmap.get(target - nums[index]))
else:
hashmap[nums[index]] = index
<|end_body_0|>
<|body_start_1|>
lookup = {}
for i... | 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 twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_10k_train_006646 | 831 | 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": "twoSum2",
"signature": "def twoSum2(self, nums, target)"
}... | 2 | stack_v2_sparse_classes_30k_train_005043 | 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 twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | 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 twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | b4fc2ba621f3484973c0520b02c60e5ed1930722 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | 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]"""
hashmap = {}
for index in range(len(nums)):
if target - nums[index] in hashmap:
return (index, hashmap.get(target - nums[index]))
else:
... | the_stack_v2_python_sparse | 001_TwoNumSum.py | Black-Mamba24/leetcode-python | train | 0 | |
89b9d7f0f9c993e133cad8229fb5cfe9cd8f04af | [
"context = self.env.context\nif type(context.get('default_location_id')) in (int, long):\n return context.get('default_location_id')\nif isinstance(context.get('default_location_id'), basestring):\n location_ids = self.env.get('stock.location').name_search(name=context['default_location_id'])\n if len(loca... | <|body_start_0|>
context = self.env.context
if type(context.get('default_location_id')) in (int, long):
return context.get('default_location_id')
if isinstance(context.get('default_location_id'), basestring):
location_ids = self.env.get('stock.location').name_search(name=... | simple_stock_in_line | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class simple_stock_in_line:
def _resolve_location_id_from_context(self):
"""Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a single Sales Team."""
<|body_0|>
def _get_default_location_id(self):
"""Gives default sec... | stack_v2_sparse_classes_10k_train_006647 | 11,827 | no_license | [
{
"docstring": "Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a single Sales Team.",
"name": "_resolve_location_id_from_context",
"signature": "def _resolve_location_id_from_context(self)"
},
{
"docstring": "Gives default section by che... | 2 | null | Implement the Python class `simple_stock_in_line` described below.
Class description:
Implement the simple_stock_in_line class.
Method signatures and docstrings:
- def _resolve_location_id_from_context(self): Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a s... | Implement the Python class `simple_stock_in_line` described below.
Class description:
Implement the simple_stock_in_line class.
Method signatures and docstrings:
- def _resolve_location_id_from_context(self): Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a s... | 46e15330b5d642053da61754247f3fbf9d02717e | <|skeleton|>
class simple_stock_in_line:
def _resolve_location_id_from_context(self):
"""Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a single Sales Team."""
<|body_0|>
def _get_default_location_id(self):
"""Gives default sec... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class simple_stock_in_line:
def _resolve_location_id_from_context(self):
"""Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a single Sales Team."""
context = self.env.context
if type(context.get('default_location_id')) in (int, long):... | the_stack_v2_python_sparse | core/simple_stock2/models/simple_stock_in.py | Muhammad-SF/Test | train | 0 | |
dbf4c6bb8984a5fb75df28f25a3c3cdad35c4ce1 | [
"super(ResUnit, self).__init__(name=name)\nself._depth = depth\nself._num_layers = 2\nself._kernel_shapes = [kernel_shape] * 2\nself._strides = [stride, 1]\nself._padding = snt.SAME\nself._activation = activation\nself._extra_params = extra_params\nself._downsample_input = False\nif stride != 1:\n self._downsamp... | <|body_start_0|>
super(ResUnit, self).__init__(name=name)
self._depth = depth
self._num_layers = 2
self._kernel_shapes = [kernel_shape] * 2
self._strides = [stride, 1]
self._padding = snt.SAME
self._activation = activation
self._extra_params = extra_params... | ResUnit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResUnit:
def __init__(self, depth, name='resUnit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, **extra_params):
"""Args: depth (int): the depth of the resUnit. name (str): module name. kernel_shape (int or [int,int]): the kernel size stride (int): the stride activation (tf func... | stack_v2_sparse_classes_10k_train_006648 | 48,282 | permissive | [
{
"docstring": "Args: depth (int): the depth of the resUnit. name (str): module name. kernel_shape (int or [int,int]): the kernel size stride (int): the stride activation (tf function): activation used for the internal layers. **extra_params: all the additional keyword arguments will be passed to snt.Conv2D lay... | 2 | null | Implement the Python class `ResUnit` described below.
Class description:
Implement the ResUnit class.
Method signatures and docstrings:
- def __init__(self, depth, name='resUnit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, **extra_params): Args: depth (int): the depth of the resUnit. name (str): module nam... | Implement the Python class `ResUnit` described below.
Class description:
Implement the ResUnit class.
Method signatures and docstrings:
- def __init__(self, depth, name='resUnit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, **extra_params): Args: depth (int): the depth of the resUnit. name (str): module nam... | a10c33346803239db8a64c104db7f22ec4e05bef | <|skeleton|>
class ResUnit:
def __init__(self, depth, name='resUnit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, **extra_params):
"""Args: depth (int): the depth of the resUnit. name (str): module name. kernel_shape (int or [int,int]): the kernel size stride (int): the stride activation (tf func... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResUnit:
def __init__(self, depth, name='resUnit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, **extra_params):
"""Args: depth (int): the depth of the resUnit. name (str): module name. kernel_shape (int or [int,int]): the kernel size stride (int): the stride activation (tf function): activat... | the_stack_v2_python_sparse | argo/core/utils/utils_modules.py | ricvo/argo | train | 0 | |
cce2681597a753edd19cb76d9017794a4fc8af10 | [
"if len(self) < 2:\n raise IndexError(f'Cannot obtain the penultimate set of coordinates, only had {len(self)}')\nreturn self[-2]",
"if len(self) < 1:\n raise IndexError('Cannot obtain the final set of coordinates from an empty history')\nreturn self[-1]",
"if len(self) == 0:\n raise IndexError('No min... | <|body_start_0|>
if len(self) < 2:
raise IndexError(f'Cannot obtain the penultimate set of coordinates, only had {len(self)}')
return self[-2]
<|end_body_0|>
<|body_start_1|>
if len(self) < 1:
raise IndexError('Cannot obtain the final set of coordinates from an empty his... | Sequential history of coordinates | OptimiserHistory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimiserHistory:
"""Sequential history of coordinates"""
def penultimate(self) -> OptCoordinates:
"""Last but one set of coordinates (the penultimate set) ----------------------------------------------------------------------- Returns: (OptCoordinates):"""
<|body_0|>
de... | stack_v2_sparse_classes_10k_train_006649 | 33,069 | permissive | [
{
"docstring": "Last but one set of coordinates (the penultimate set) ----------------------------------------------------------------------- Returns: (OptCoordinates):",
"name": "penultimate",
"signature": "def penultimate(self) -> OptCoordinates"
},
{
"docstring": "Last set of coordinates ----... | 5 | stack_v2_sparse_classes_30k_train_000416 | Implement the Python class `OptimiserHistory` described below.
Class description:
Sequential history of coordinates
Method signatures and docstrings:
- def penultimate(self) -> OptCoordinates: Last but one set of coordinates (the penultimate set) -----------------------------------------------------------------------... | Implement the Python class `OptimiserHistory` described below.
Class description:
Sequential history of coordinates
Method signatures and docstrings:
- def penultimate(self) -> OptCoordinates: Last but one set of coordinates (the penultimate set) -----------------------------------------------------------------------... | 4d6667592f083dfcf38de6b75c4222c0a0e7b60b | <|skeleton|>
class OptimiserHistory:
"""Sequential history of coordinates"""
def penultimate(self) -> OptCoordinates:
"""Last but one set of coordinates (the penultimate set) ----------------------------------------------------------------------- Returns: (OptCoordinates):"""
<|body_0|>
de... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OptimiserHistory:
"""Sequential history of coordinates"""
def penultimate(self) -> OptCoordinates:
"""Last but one set of coordinates (the penultimate set) ----------------------------------------------------------------------- Returns: (OptCoordinates):"""
if len(self) < 2:
r... | the_stack_v2_python_sparse | autode/opt/optimisers/base.py | duartegroup/autodE | train | 132 |
abd774ea44d0bf47c1b823520135c0b05c05672d | [
"def serialize_branch(root):\n if root is None:\n serialized.append('$')\n else:\n serialized.append(root.val)\n serialize_branch(root.left)\n serialize_branch(root.right)\nserialized = []\nserialize_branch(root)\nreturn '|'.join(('$' if x is None else str(x) for x in serialized))"... | <|body_start_0|>
def serialize_branch(root):
if root is None:
serialized.append('$')
else:
serialized.append(root.val)
serialize_branch(root.left)
serialize_branch(root.right)
serialized = []
serialize_branch... | 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_006650 | 1,454 | 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:... | ba84c192fb9995dd48ddc6d81c3153488dd3c698 | <|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"""
def serialize_branch(root):
if root is None:
serialized.append('$')
else:
serialized.append(root.val)
serialize_br... | the_stack_v2_python_sparse | Python/serialize-and-deserialize-binary-tree.py | phucle2411/LeetCode | train | 0 | |
5a1813cb35ad501e5e775fd3f6742d4995fcecf8 | [
"super(SkipGram, self).__init__()\nself.vocab_size = vocab_size\nself.emb_dimension = emb_dimension\nself.c_emb = nn.Embedding(vocab_size, emb_dimension, embedding_table=Uniform(0.5 / emb_dimension))\nself.n_emb = nn.Embedding(vocab_size, emb_dimension, embedding_table=Uniform(0))\nself.mul = ops.Mul()\nself.sum = ... | <|body_start_0|>
super(SkipGram, self).__init__()
self.vocab_size = vocab_size
self.emb_dimension = emb_dimension
self.c_emb = nn.Embedding(vocab_size, emb_dimension, embedding_table=Uniform(0.5 / emb_dimension))
self.n_emb = nn.Embedding(vocab_size, emb_dimension, embedding_tabl... | Skip gram model of word2vec. Attributes: vocab_size: Vocabulary size. emb_dimension: Embedding dimension. c_emb: Embedding for center word. n_emb: Embedding for neighbor word. | SkipGram | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkipGram:
"""Skip gram model of word2vec. Attributes: vocab_size: Vocabulary size. emb_dimension: Embedding dimension. c_emb: Embedding for center word. n_emb: Embedding for neighbor word."""
def __init__(self, vocab_size, emb_dimension):
"""Initialize model parameters. Apply for two... | stack_v2_sparse_classes_10k_train_006651 | 3,900 | permissive | [
{
"docstring": "Initialize model parameters. Apply for two embedding layers. Initialize layer weight. Args: vocab_size: Vocabulary size. emb_dimension: Embedding dimension. Returns: None",
"name": "__init__",
"signature": "def __init__(self, vocab_size, emb_dimension)"
},
{
"docstring": "Forward... | 3 | stack_v2_sparse_classes_30k_test_000198 | Implement the Python class `SkipGram` described below.
Class description:
Skip gram model of word2vec. Attributes: vocab_size: Vocabulary size. emb_dimension: Embedding dimension. c_emb: Embedding for center word. n_emb: Embedding for neighbor word.
Method signatures and docstrings:
- def __init__(self, vocab_size, e... | Implement the Python class `SkipGram` described below.
Class description:
Skip gram model of word2vec. Attributes: vocab_size: Vocabulary size. emb_dimension: Embedding dimension. c_emb: Embedding for center word. n_emb: Embedding for neighbor word.
Method signatures and docstrings:
- def __init__(self, vocab_size, e... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class SkipGram:
"""Skip gram model of word2vec. Attributes: vocab_size: Vocabulary size. emb_dimension: Embedding dimension. c_emb: Embedding for center word. n_emb: Embedding for neighbor word."""
def __init__(self, vocab_size, emb_dimension):
"""Initialize model parameters. Apply for two... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SkipGram:
"""Skip gram model of word2vec. Attributes: vocab_size: Vocabulary size. emb_dimension: Embedding dimension. c_emb: Embedding for center word. n_emb: Embedding for neighbor word."""
def __init__(self, vocab_size, emb_dimension):
"""Initialize model parameters. Apply for two embedding la... | the_stack_v2_python_sparse | research/nlp/skipgram/src/skipgram.py | mindspore-ai/models | train | 301 |
162d0fdc1f6466634341acc039c5baca02ec03f3 | [
"if isinstance(degrees, numbers.Number):\n if degrees < 0:\n raise ValueError('If degrees is a single number, it must be positive.')\n self.degrees = (-degrees, degrees)\nelse:\n if len(degrees) != 2:\n raise ValueError('If degrees is a sequence, it must be of len 2.')\n self.degrees = deg... | <|body_start_0|>
if isinstance(degrees, numbers.Number):
if degrees < 0:
raise ValueError('If degrees is a single number, it must be positive.')
self.degrees = (-degrees, degrees)
else:
if len(degrees) != 2:
raise ValueError('If degrees... | Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin is the upper left corner. Default is the ce... | RandomRotation4D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomRotation4D:
"""Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin... | stack_v2_sparse_classes_10k_train_006652 | 34,927 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, degrees, rotate_planes=[[0, 1], [0, 2], [1, 2]])"
},
{
"docstring": "Get parameters for ``rotate`` for a random rotation. Returns: sequence: params to be passed to ``rotate`` for random rotation.",
"name": "get_param... | 3 | null | Implement the Python class `RandomRotation4D` described below.
Class description:
Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optiona... | Implement the Python class `RandomRotation4D` described below.
Class description:
Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optiona... | 2c8c35a8949fef74599f5ec557d340a14415f20d | <|skeleton|>
class RandomRotation4D:
"""Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandomRotation4D:
"""Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin is the upper... | the_stack_v2_python_sparse | contrib/MedicalSeg/medicalseg/transforms/transform.py | PaddlePaddle/PaddleSeg | train | 8,531 |
72a3cadb24e6f2ece3e5abba15f83223eaf65c5e | [
"self.low = []\nheapq.heapify(self.low)\nself.high = []\nheapq.heapify(self.high)",
"heapq.heappush(self.high, num)\nif len(self.high) - len(self.low) > 1:\n temp = heapq.heappop(self.high)\n heapq.heappush(self.low, -1 * temp)",
"if len(self.high) == len(self.low):\n return float((self.high[0] - self.... | <|body_start_0|>
self.low = []
heapq.heapify(self.low)
self.high = []
heapq.heapify(self.high)
<|end_body_0|>
<|body_start_1|>
heapq.heappush(self.high, num)
if len(self.high) - len(self.low) > 1:
temp = heapq.heappop(self.high)
heapq.heappush(sel... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_10k_train_006653 | 958 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds a num into the data structure. :type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": "Returns the ... | 3 | stack_v2_sparse_classes_30k_train_000327 | 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): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | 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): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | b0f85616d10a568d7faef7fef9fff68f8063db7c | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
self.low = []
heapq.heapify(self.low)
self.high = []
heapq.heapify(self.high)
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
h... | the_stack_v2_python_sparse | FindMedicanFromDateStream.py | RengarAndKhz/QuoraInterview | train | 0 | |
7c0691e37058110fab8a976ded266ab51fb38443 | [
"sc.logger.info(u'创作页面初始状态检查测试开始')\ntime.sleep(2)\nel_home = sc.driver.find_element_by_id('com.quvideo.xiaoying:id/img_creation')\nel_home.click()\ntime.sleep(0.5)\nsc.capture_screen(inspect.stack()[0][3], sc.path_lists[0])\nassert el_home is not None",
"sc.logger.info(u'创作页面下拉刷新测试开始')\nstart_x = self.width // 2\... | <|body_start_0|>
sc.logger.info(u'创作页面初始状态检查测试开始')
time.sleep(2)
el_home = sc.driver.find_element_by_id('com.quvideo.xiaoying:id/img_creation')
el_home.click()
time.sleep(0.5)
sc.capture_screen(inspect.stack()[0][3], sc.path_lists[0])
assert el_home is not None
<|... | 创作页面的测试类,分步截图 | TestCreationUI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCreationUI:
"""创作页面的测试类,分步截图"""
def test_origin():
"""测试创作页面初始UI状态"""
<|body_0|>
def test_refresh(self):
"""测试下拉刷新"""
<|body_1|>
def test_swipe_vertical(self):
"""测试上下方向的滑动"""
<|body_2|>
def test_origin_home(self):
""... | stack_v2_sparse_classes_10k_train_006654 | 2,643 | no_license | [
{
"docstring": "测试创作页面初始UI状态",
"name": "test_origin",
"signature": "def test_origin()"
},
{
"docstring": "测试下拉刷新",
"name": "test_refresh",
"signature": "def test_refresh(self)"
},
{
"docstring": "测试上下方向的滑动",
"name": "test_swipe_vertical",
"signature": "def test_swipe_vert... | 4 | stack_v2_sparse_classes_30k_train_001268 | Implement the Python class `TestCreationUI` described below.
Class description:
创作页面的测试类,分步截图
Method signatures and docstrings:
- def test_origin(): 测试创作页面初始UI状态
- def test_refresh(self): 测试下拉刷新
- def test_swipe_vertical(self): 测试上下方向的滑动
- def test_origin_home(self): 测试创作页home tab的功能 | Implement the Python class `TestCreationUI` described below.
Class description:
创作页面的测试类,分步截图
Method signatures and docstrings:
- def test_origin(): 测试创作页面初始UI状态
- def test_refresh(self): 测试下拉刷新
- def test_swipe_vertical(self): 测试上下方向的滑动
- def test_origin_home(self): 测试创作页home tab的功能
<|skeleton|>
class TestCreationU... | b1190e3df62fa85562c14625c06a9794b8ce29a0 | <|skeleton|>
class TestCreationUI:
"""创作页面的测试类,分步截图"""
def test_origin():
"""测试创作页面初始UI状态"""
<|body_0|>
def test_refresh(self):
"""测试下拉刷新"""
<|body_1|>
def test_swipe_vertical(self):
"""测试上下方向的滑动"""
<|body_2|>
def test_origin_home(self):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestCreationUI:
"""创作页面的测试类,分步截图"""
def test_origin():
"""测试创作页面初始UI状态"""
sc.logger.info(u'创作页面初始状态检查测试开始')
time.sleep(2)
el_home = sc.driver.find_element_by_id('com.quvideo.xiaoying:id/img_creation')
el_home.click()
time.sleep(0.5)
sc.capture_scree... | the_stack_v2_python_sparse | Android/VivaVideo/test_creations/test_ui.py | hicheng/UItest | train | 0 |
b878a6872a2a33ef3c2c7d92a1e2981db7a79952 | [
"self._timer_start = perf_counter()\nself._timer_last = self._timer_start\nself.aoc_year = aoc_year\nuser_profile = Path(os.environ['USERPROFILE'])\nself._aoc_path = user_profile / 'aoc'\nbase_path = Path().cwd()\nwhile base_path.parts[-1].casefold() != 'AdventOfCode'.casefold():\n base_path = base_path.parent\n... | <|body_start_0|>
self._timer_start = perf_counter()
self._timer_last = self._timer_start
self.aoc_year = aoc_year
user_profile = Path(os.environ['USERPROFILE'])
self._aoc_path = user_profile / 'aoc'
base_path = Path().cwd()
while base_path.parts[-1].casefold() != ... | Advent of Code loader library. Attributes: aoc_year (int): The year of Advent of Code to work with. Methods: print_solution get_puzzle_input cache_data retrieve_data | LoaderLib | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoaderLib:
"""Advent of Code loader library. Attributes: aoc_year (int): The year of Advent of Code to work with. Methods: print_solution get_puzzle_input cache_data retrieve_data"""
def __init__(self, aoc_year):
"""Initialise helper library. Parameters: aoc_year (int): The year of A... | stack_v2_sparse_classes_10k_train_006655 | 4,883 | permissive | [
{
"docstring": "Initialise helper library. Parameters: aoc_year (int): The year of Advent of Code to work with.",
"name": "__init__",
"signature": "def __init__(self, aoc_year)"
},
{
"docstring": "Get puzzle input from the AOC website. Apply an optional transform function to it before returning.... | 5 | null | Implement the Python class `LoaderLib` described below.
Class description:
Advent of Code loader library. Attributes: aoc_year (int): The year of Advent of Code to work with. Methods: print_solution get_puzzle_input cache_data retrieve_data
Method signatures and docstrings:
- def __init__(self, aoc_year): Initialise ... | Implement the Python class `LoaderLib` described below.
Class description:
Advent of Code loader library. Attributes: aoc_year (int): The year of Advent of Code to work with. Methods: print_solution get_puzzle_input cache_data retrieve_data
Method signatures and docstrings:
- def __init__(self, aoc_year): Initialise ... | 567df9cb5645bc6cf4c22063a84a621039069311 | <|skeleton|>
class LoaderLib:
"""Advent of Code loader library. Attributes: aoc_year (int): The year of Advent of Code to work with. Methods: print_solution get_puzzle_input cache_data retrieve_data"""
def __init__(self, aoc_year):
"""Initialise helper library. Parameters: aoc_year (int): The year of A... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LoaderLib:
"""Advent of Code loader library. Attributes: aoc_year (int): The year of Advent of Code to work with. Methods: print_solution get_puzzle_input cache_data retrieve_data"""
def __init__(self, aoc_year):
"""Initialise helper library. Parameters: aoc_year (int): The year of Advent of Code... | the_stack_v2_python_sparse | aoc/loader.py | GeoffRiley/AdventOfCode | train | 3 |
9b203c29879fd6882603e4f666f807a2cc0c819e | [
"if not url_str:\n return err_resp('A url is required')\nif not isinstance(url_str, str):\n return err_resp('The \"url_str\" must be a string')\nreturn ok_resp(urlparse(url_str))",
"info = URLHelper.get_parsed_url(url_str)\nif not info.success:\n return info\nnetloc = info.result_obj.netloc\nif not netlo... | <|body_start_0|>
if not url_str:
return err_resp('A url is required')
if not isinstance(url_str, str):
return err_resp('The "url_str" must be a string')
return ok_resp(urlparse(url_str))
<|end_body_0|>
<|body_start_1|>
info = URLHelper.get_parsed_url(url_str)
... | Helper methods related to urls | URLHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class URLHelper:
"""Helper methods related to urls"""
def get_parsed_url(url_str):
"""Return a ParseResult object"""
<|body_0|>
def get_netloc_from_url(url_str):
"""Return the netloc from the url"""
<|body_1|>
def format_url_for_saving(url_str, remove_trai... | stack_v2_sparse_classes_10k_train_006656 | 5,027 | permissive | [
{
"docstring": "Return a ParseResult object",
"name": "get_parsed_url",
"signature": "def get_parsed_url(url_str)"
},
{
"docstring": "Return the netloc from the url",
"name": "get_netloc_from_url",
"signature": "def get_netloc_from_url(url_str)"
},
{
"docstring": "Make the url lo... | 6 | stack_v2_sparse_classes_30k_train_003820 | Implement the Python class `URLHelper` described below.
Class description:
Helper methods related to urls
Method signatures and docstrings:
- def get_parsed_url(url_str): Return a ParseResult object
- def get_netloc_from_url(url_str): Return the netloc from the url
- def format_url_for_saving(url_str, remove_trailing... | Implement the Python class `URLHelper` described below.
Class description:
Helper methods related to urls
Method signatures and docstrings:
- def get_parsed_url(url_str): Return a ParseResult object
- def get_netloc_from_url(url_str): Return the netloc from the url
- def format_url_for_saving(url_str, remove_trailing... | 9461522219f5ef0f4877f24c8f5923e462bd9557 | <|skeleton|>
class URLHelper:
"""Helper methods related to urls"""
def get_parsed_url(url_str):
"""Return a ParseResult object"""
<|body_0|>
def get_netloc_from_url(url_str):
"""Return the netloc from the url"""
<|body_1|>
def format_url_for_saving(url_str, remove_trai... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class URLHelper:
"""Helper methods related to urls"""
def get_parsed_url(url_str):
"""Return a ParseResult object"""
if not url_str:
return err_resp('A url is required')
if not isinstance(url_str, str):
return err_resp('The "url_str" must be a string')
re... | the_stack_v2_python_sparse | preprocess_web/code/ravens_metadata_apps/utils/url_helper.py | TwoRavens/raven-metadata-service | train | 0 |
23c84408a54a3675d5438be265381b7ca081466a | [
"if not fields:\n raise ValueError('At least one field must be provided')\nif not fields:\n raise ValueError('At least one field must be provided')\nselects = []\nfor field in fields:\n if isinstance(field, list):\n selects.append(','.join(field))\n else:\n selects.append(field)\nself._req... | <|body_start_0|>
if not fields:
raise ValueError('At least one field must be provided')
if not fields:
raise ValueError('At least one field must be provided')
selects = []
for field in fields:
if isinstance(field, list):
selects.append(... | Represent a search suggestion query again an Azure Search index. | SuggestQuery | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuggestQuery:
"""Represent a search suggestion query again an Azure Search index."""
def order_by(self, *fields: str) -> None:
"""Update the `orderby` property for the search results. :param fields: A list of fields for the query result to be ordered by. :type fields: str :raises: Va... | stack_v2_sparse_classes_10k_train_006657 | 4,488 | permissive | [
{
"docstring": "Update the `orderby` property for the search results. :param fields: A list of fields for the query result to be ordered by. :type fields: str :raises: ValueError",
"name": "order_by",
"signature": "def order_by(self, *fields: str) -> None"
},
{
"docstring": "Update the `select` ... | 2 | stack_v2_sparse_classes_30k_train_002707 | Implement the Python class `SuggestQuery` described below.
Class description:
Represent a search suggestion query again an Azure Search index.
Method signatures and docstrings:
- def order_by(self, *fields: str) -> None: Update the `orderby` property for the search results. :param fields: A list of fields for the que... | Implement the Python class `SuggestQuery` described below.
Class description:
Represent a search suggestion query again an Azure Search index.
Method signatures and docstrings:
- def order_by(self, *fields: str) -> None: Update the `orderby` property for the search results. :param fields: A list of fields for the que... | c2ca191e736bb06bfbbbc9493e8325763ba990bb | <|skeleton|>
class SuggestQuery:
"""Represent a search suggestion query again an Azure Search index."""
def order_by(self, *fields: str) -> None:
"""Update the `orderby` property for the search results. :param fields: A list of fields for the query result to be ordered by. :type fields: str :raises: Va... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SuggestQuery:
"""Represent a search suggestion query again an Azure Search index."""
def order_by(self, *fields: str) -> None:
"""Update the `orderby` property for the search results. :param fields: A list of fields for the query result to be ordered by. :type fields: str :raises: ValueError"""
... | the_stack_v2_python_sparse | sdk/search/azure-search-documents/azure/search/documents/_queries.py | Azure/azure-sdk-for-python | train | 4,046 |
81c3f329d93adc3b57df685c68b719f9a16e112d | [
"zk_client = KazooClient(hosts=','.join(zk_locations), connection_retry=ZK_PERSISTENT_RECONNECTS)\nzk_client.start()\nself.ioloop = io_loop\nself.target = target\nself.start_time = None\nself.status = 'Not started'\nself.finish_time = None\nself.solr_adapter = solr_adapter.SolrAdapter(zk_client)\nself.scheduled_ind... | <|body_start_0|>
zk_client = KazooClient(hosts=','.join(zk_locations), connection_retry=ZK_PERSISTENT_RECONNECTS)
zk_client.start()
self.ioloop = io_loop
self.target = target
self.start_time = None
self.status = 'Not started'
self.finish_time = None
self.s... | Exports data from Search Service 2 to target storage. | Exporter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exporter:
"""Exports data from Search Service 2 to target storage."""
def __init__(self, io_loop, zk_locations, target, max_concurrency):
"""Args: io_loop: an instance of tornado IOLoop. zk_locations: a list - Zookeeper locations. target: an instance of export Target (e.g.: S3Target)... | stack_v2_sparse_classes_10k_train_006658 | 10,087 | permissive | [
{
"docstring": "Args: io_loop: an instance of tornado IOLoop. zk_locations: a list - Zookeeper locations. target: an instance of export Target (e.g.: S3Target). max_concurrency: an int - maximum number of concurrent jobs.",
"name": "__init__",
"signature": "def __init__(self, io_loop, zk_locations, targ... | 4 | null | Implement the Python class `Exporter` described below.
Class description:
Exports data from Search Service 2 to target storage.
Method signatures and docstrings:
- def __init__(self, io_loop, zk_locations, target, max_concurrency): Args: io_loop: an instance of tornado IOLoop. zk_locations: a list - Zookeeper locatio... | Implement the Python class `Exporter` described below.
Class description:
Exports data from Search Service 2 to target storage.
Method signatures and docstrings:
- def __init__(self, io_loop, zk_locations, target, max_concurrency): Args: io_loop: an instance of tornado IOLoop. zk_locations: a list - Zookeeper locatio... | be17e5f658d7b42b5aa7eeb7a5ddd4962f3ea82f | <|skeleton|>
class Exporter:
"""Exports data from Search Service 2 to target storage."""
def __init__(self, io_loop, zk_locations, target, max_concurrency):
"""Args: io_loop: an instance of tornado IOLoop. zk_locations: a list - Zookeeper locations. target: an instance of export Target (e.g.: S3Target)... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Exporter:
"""Exports data from Search Service 2 to target storage."""
def __init__(self, io_loop, zk_locations, target, max_concurrency):
"""Args: io_loop: an instance of tornado IOLoop. zk_locations: a list - Zookeeper locations. target: an instance of export Target (e.g.: S3Target). max_concurr... | the_stack_v2_python_sparse | SearchService2/appscale/search/backup_restore/backup_from_v2.py | obino/appscale | train | 1 |
226826158e2f6b8d9717a4ca44c6bc8690282af4 | [
"try:\n self.request_control = request.RequestController(endopoint=accounting_endpoint)\nexcept Exception as e:\n raise exceptions.ConfigurationException('Accounting server configuration failed %s. ' % e.message)",
"path = '/set_accounting'\nparameters = {'admin_token': admin_token, 'accounting': accounting... | <|body_start_0|>
try:
self.request_control = request.RequestController(endopoint=accounting_endpoint)
except Exception as e:
raise exceptions.ConfigurationException('Accounting server configuration failed %s. ' % e.message)
<|end_body_0|>
<|body_start_1|>
path = '/set_ac... | Notification controller for batch systems. | BatchNotificationController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchNotificationController:
"""Notification controller for batch systems."""
def __init__(self, accounting_endpoint):
"""Initialize the controller It set attributes and creates a Request controller by using the endpoint related to the accounting server. :param accounting_endpoint: :... | stack_v2_sparse_classes_10k_train_006659 | 29,683 | permissive | [
{
"docstring": "Initialize the controller It set attributes and creates a Request controller by using the endpoint related to the accounting server. :param accounting_endpoint: :return:",
"name": "__init__",
"signature": "def __init__(self, accounting_endpoint)"
},
{
"docstring": "Execute a PUT ... | 2 | stack_v2_sparse_classes_30k_train_002089 | Implement the Python class `BatchNotificationController` described below.
Class description:
Notification controller for batch systems.
Method signatures and docstrings:
- def __init__(self, accounting_endpoint): Initialize the controller It set attributes and creates a Request controller by using the endpoint relate... | Implement the Python class `BatchNotificationController` described below.
Class description:
Notification controller for batch systems.
Method signatures and docstrings:
- def __init__(self, accounting_endpoint): Initialize the controller It set attributes and creates a Request controller by using the endpoint relate... | 346f5bdd7a1ff6c705c30172661a93540d9f0985 | <|skeleton|>
class BatchNotificationController:
"""Notification controller for batch systems."""
def __init__(self, accounting_endpoint):
"""Initialize the controller It set attributes and creates a Request controller by using the endpoint related to the accounting server. :param accounting_endpoint: :... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BatchNotificationController:
"""Notification controller for batch systems."""
def __init__(self, accounting_endpoint):
"""Initialize the controller It set attributes and creates a Request controller by using the endpoint related to the accounting server. :param accounting_endpoint: :return:"""
... | the_stack_v2_python_sparse | bdocker/modules/batch.py | indigo-dc/bdocker | train | 4 |
3170646c3dc3f1c06a465a3d427cab169e89de74 | [
"if mibs_location:\n self.src_directories = mibs_location\nif type(self.src_directories) != list:\n self.src_directories = [self.src_directories]\nfor d in self.src_directories:\n if not os.path.exists(str(d)):\n msg = 'No mibs directory {} found test_SnmpHelper.'.format(str(d))\n raise Excep... | <|body_start_0|>
if mibs_location:
self.src_directories = mibs_location
if type(self.src_directories) != list:
self.src_directories = [self.src_directories]
for d in self.src_directories:
if not os.path.exists(str(d)):
msg = 'No mibs directory ... | Unit test for the SnmpMibs class to be run as a standalone module DEBUG: BFT_DEBUG=y shows the compiled dictionary BFT_DEBUG=yy VERY verbose, shows the compiled dictionary and mibs/oid details | SnmpMibsUnitTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnmpMibsUnitTest:
"""Unit test for the SnmpMibs class to be run as a standalone module DEBUG: BFT_DEBUG=y shows the compiled dictionary BFT_DEBUG=yy VERY verbose, shows the compiled dictionary and mibs/oid details"""
def __init__(self, mibs_location=None, files=None, mibs=None, err_mibs=None... | stack_v2_sparse_classes_10k_train_006660 | 18,780 | permissive | [
{
"docstring": "Takes: mibs_location: where the .mib files are located (can be a list of dirs) files: the name of the .mib/.txt files (without the extension) mibs: e.g. sysDescr, sysObjectID, etc err_mibs: wrong mibs (just for testing that the compiler rejects invalid mibs)",
"name": "__init__",
"signat... | 2 | stack_v2_sparse_classes_30k_test_000304 | Implement the Python class `SnmpMibsUnitTest` described below.
Class description:
Unit test for the SnmpMibs class to be run as a standalone module DEBUG: BFT_DEBUG=y shows the compiled dictionary BFT_DEBUG=yy VERY verbose, shows the compiled dictionary and mibs/oid details
Method signatures and docstrings:
- def __i... | Implement the Python class `SnmpMibsUnitTest` described below.
Class description:
Unit test for the SnmpMibs class to be run as a standalone module DEBUG: BFT_DEBUG=y shows the compiled dictionary BFT_DEBUG=yy VERY verbose, shows the compiled dictionary and mibs/oid details
Method signatures and docstrings:
- def __i... | 100521fde1fb67536682cafecc2f91a6e2e8a6f8 | <|skeleton|>
class SnmpMibsUnitTest:
"""Unit test for the SnmpMibs class to be run as a standalone module DEBUG: BFT_DEBUG=y shows the compiled dictionary BFT_DEBUG=yy VERY verbose, shows the compiled dictionary and mibs/oid details"""
def __init__(self, mibs_location=None, files=None, mibs=None, err_mibs=None... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SnmpMibsUnitTest:
"""Unit test for the SnmpMibs class to be run as a standalone module DEBUG: BFT_DEBUG=y shows the compiled dictionary BFT_DEBUG=yy VERY verbose, shows the compiled dictionary and mibs/oid details"""
def __init__(self, mibs_location=None, files=None, mibs=None, err_mibs=None):
""... | the_stack_v2_python_sparse | boardfarm/lib/SnmpHelper.py | mattsm/boardfarm | train | 45 |
a3b5b67bccd916f09f37fb18587f6d9f64adf8da | [
"super().__init__()\nif backbone not in FLEXUNET_BACKBONE.register_dict:\n raise ValueError(f'invalid model_name {backbone} found, must be one of {FLEXUNET_BACKBONE.register_dict.keys()}.')\nif spatial_dims not in (2, 3):\n raise ValueError('spatial_dims can only be 2 or 3.')\nencoder = FLEXUNET_BACKBONE.regi... | <|body_start_0|>
super().__init__()
if backbone not in FLEXUNET_BACKBONE.register_dict:
raise ValueError(f'invalid model_name {backbone} found, must be one of {FLEXUNET_BACKBONE.register_dict.keys()}.')
if spatial_dims not in (2, 3):
raise ValueError('spatial_dims can onl... | A flexible implementation of UNet-like encoder-decoder architecture. | FlexibleUNet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlexibleUNet:
"""A flexible implementation of UNet-like encoder-decoder architecture."""
def __init__(self, in_channels: int, out_channels: int, backbone: str, pretrained: bool=False, decoder_channels: tuple=(256, 128, 64, 32, 16), spatial_dims: int=2, norm: str | tuple=('batch', {'eps': 0.0... | stack_v2_sparse_classes_10k_train_006661 | 14,147 | permissive | [
{
"docstring": "A flexible implement of UNet, in which the backbone/encoder can be replaced with any efficient network. Currently the input must have a 2 or 3 spatial dimension and the spatial size of each dimension must be a multiple of 32 if is_pad parameter is False. Please notice each output of backbone mus... | 2 | null | Implement the Python class `FlexibleUNet` described below.
Class description:
A flexible implementation of UNet-like encoder-decoder architecture.
Method signatures and docstrings:
- def __init__(self, in_channels: int, out_channels: int, backbone: str, pretrained: bool=False, decoder_channels: tuple=(256, 128, 64, 3... | Implement the Python class `FlexibleUNet` described below.
Class description:
A flexible implementation of UNet-like encoder-decoder architecture.
Method signatures and docstrings:
- def __init__(self, in_channels: int, out_channels: int, backbone: str, pretrained: bool=False, decoder_channels: tuple=(256, 128, 64, 3... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class FlexibleUNet:
"""A flexible implementation of UNet-like encoder-decoder architecture."""
def __init__(self, in_channels: int, out_channels: int, backbone: str, pretrained: bool=False, decoder_channels: tuple=(256, 128, 64, 32, 16), spatial_dims: int=2, norm: str | tuple=('batch', {'eps': 0.0... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FlexibleUNet:
"""A flexible implementation of UNet-like encoder-decoder architecture."""
def __init__(self, in_channels: int, out_channels: int, backbone: str, pretrained: bool=False, decoder_channels: tuple=(256, 128, 64, 32, 16), spatial_dims: int=2, norm: str | tuple=('batch', {'eps': 0.001, 'momentum... | the_stack_v2_python_sparse | monai/networks/nets/flexible_unet.py | Project-MONAI/MONAI | train | 4,805 |
957dfaa24d2691c1f009285e5044206712165d44 | [
"super(DoubleCritic, self).__init__()\nself.critic1 = tf.keras.Sequential([tf.keras.layers.Dense(256, input_shape=(state_dim + action_dim,), activation=tf.nn.relu, kernel_initializer='orthogonal'), tf.keras.layers.Dense(256, activation=tf.nn.relu, kernel_initializer='orthogonal'), tf.keras.layers.Dense(1, kernel_in... | <|body_start_0|>
super(DoubleCritic, self).__init__()
self.critic1 = tf.keras.Sequential([tf.keras.layers.Dense(256, input_shape=(state_dim + action_dim,), activation=tf.nn.relu, kernel_initializer='orthogonal'), tf.keras.layers.Dense(256, activation=tf.nn.relu, kernel_initializer='orthogonal'), tf.kera... | A critic network that estimates a dual Q-function. | DoubleCritic | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoubleCritic:
"""A critic network that estimates a dual Q-function."""
def __init__(self, state_dim, action_dim):
"""Creates networks. Args: state_dim: State size. action_dim: Action size."""
<|body_0|>
def call(self, states, actions):
"""Returns Q-value estimate... | stack_v2_sparse_classes_10k_train_006662 | 19,382 | permissive | [
{
"docstring": "Creates networks. Args: state_dim: State size. action_dim: Action size.",
"name": "__init__",
"signature": "def __init__(self, state_dim, action_dim)"
},
{
"docstring": "Returns Q-value estimates for given states and actions. Args: states: A batch of states. actions: A batch of a... | 2 | stack_v2_sparse_classes_30k_train_001065 | Implement the Python class `DoubleCritic` described below.
Class description:
A critic network that estimates a dual Q-function.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim): Creates networks. Args: state_dim: State size. action_dim: Action size.
- def call(self, states, actions): Ret... | Implement the Python class `DoubleCritic` described below.
Class description:
A critic network that estimates a dual Q-function.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim): Creates networks. Args: state_dim: State size. action_dim: Action size.
- def call(self, states, actions): Ret... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class DoubleCritic:
"""A critic network that estimates a dual Q-function."""
def __init__(self, state_dim, action_dim):
"""Creates networks. Args: state_dim: State size. action_dim: Action size."""
<|body_0|>
def call(self, states, actions):
"""Returns Q-value estimate... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DoubleCritic:
"""A critic network that estimates a dual Q-function."""
def __init__(self, state_dim, action_dim):
"""Creates networks. Args: state_dim: State size. action_dim: Action size."""
super(DoubleCritic, self).__init__()
self.critic1 = tf.keras.Sequential([tf.keras.layers.... | the_stack_v2_python_sparse | algae_dice/algae.py | Ayoob7/google-research | train | 2 |
187291f3924763d5f90bc146de83075b77c98dcb | [
"x = np.arange(-num_points, num_points + 1, dtype=int)\n\ndef monomial(val: int, deg: int):\n return math.pow(val, deg)\na = np.zeros((2 * num_points + 1, pol_degree + 1), float)\nfor i in range(2 * num_points + 1):\n for j in range(pol_degree + 1):\n a[i, j] = monomial(x[i], j)\na_trans_a = np.dot(a.t... | <|body_start_0|>
x = np.arange(-num_points, num_points + 1, dtype=int)
def monomial(val: int, deg: int):
return math.pow(val, deg)
a = np.zeros((2 * num_points + 1, pol_degree + 1), float)
for i in range(2 * num_points + 1):
for j in range(pol_degree + 1):
... | SG | [
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SG:
def __init__(self, num_points: int, pol_degree: int, diff_order: int=0):
"""Calculates filter coefficients for symmetric savitzky-golay filter. See: U{http://www.nrbook.com/a/bookcpdf/c14-8.pdf} @param num_points: M{(2*num_points+1)} values contribute to the smoother. @param pol_degr... | stack_v2_sparse_classes_10k_train_006663 | 2,388 | permissive | [
{
"docstring": "Calculates filter coefficients for symmetric savitzky-golay filter. See: U{http://www.nrbook.com/a/bookcpdf/c14-8.pdf} @param num_points: M{(2*num_points+1)} values contribute to the smoother. @param pol_degree: degree of fitting polynomial. @param diff_order: degree of implicit differentiation.... | 2 | stack_v2_sparse_classes_30k_train_002164 | Implement the Python class `SG` described below.
Class description:
Implement the SG class.
Method signatures and docstrings:
- def __init__(self, num_points: int, pol_degree: int, diff_order: int=0): Calculates filter coefficients for symmetric savitzky-golay filter. See: U{http://www.nrbook.com/a/bookcpdf/c14-8.pdf... | Implement the Python class `SG` described below.
Class description:
Implement the SG class.
Method signatures and docstrings:
- def __init__(self, num_points: int, pol_degree: int, diff_order: int=0): Calculates filter coefficients for symmetric savitzky-golay filter. See: U{http://www.nrbook.com/a/bookcpdf/c14-8.pdf... | 6e4b569819ff0b2aede33dc1752ca6bd4d00c4c7 | <|skeleton|>
class SG:
def __init__(self, num_points: int, pol_degree: int, diff_order: int=0):
"""Calculates filter coefficients for symmetric savitzky-golay filter. See: U{http://www.nrbook.com/a/bookcpdf/c14-8.pdf} @param num_points: M{(2*num_points+1)} values contribute to the smoother. @param pol_degr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SG:
def __init__(self, num_points: int, pol_degree: int, diff_order: int=0):
"""Calculates filter coefficients for symmetric savitzky-golay filter. See: U{http://www.nrbook.com/a/bookcpdf/c14-8.pdf} @param num_points: M{(2*num_points+1)} values contribute to the smoother. @param pol_degree: degree of ... | the_stack_v2_python_sparse | archived/projects/eyetracking/pipeline/savitzky_golay.py | nirdslab/streaminghub | train | 2 | |
0980c384b69ae5becc6907d91c08b01ea0750f64 | [
"url = reverse('signup')\nresponse = self.client.get(url)\nlogger.info(response)\nself.assertEqual(response.status_code, 200)",
"url = reverse('signup')\nresponse = self.client.post(url, {'username': 'user', 'password1': 'Word9876', 'password2': 'Word9876'})\nlogger.info(response)\nself.assertRedirects(response, ... | <|body_start_0|>
url = reverse('signup')
response = self.client.get(url)
logger.info(response)
self.assertEqual(response.status_code, 200)
<|end_body_0|>
<|body_start_1|>
url = reverse('signup')
response = self.client.post(url, {'username': 'user', 'password1': 'Word9876... | Test register page. | RegisterPageTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterPageTestCase:
"""Test register page."""
def test_register_page_get_request(self):
"""Test get request to Register Page."""
<|body_0|>
def test_register_new_user(self):
"""Test registering new user."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_10k_train_006664 | 3,223 | no_license | [
{
"docstring": "Test get request to Register Page.",
"name": "test_register_page_get_request",
"signature": "def test_register_page_get_request(self)"
},
{
"docstring": "Test registering new user.",
"name": "test_register_new_user",
"signature": "def test_register_new_user(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004559 | Implement the Python class `RegisterPageTestCase` described below.
Class description:
Test register page.
Method signatures and docstrings:
- def test_register_page_get_request(self): Test get request to Register Page.
- def test_register_new_user(self): Test registering new user. | Implement the Python class `RegisterPageTestCase` described below.
Class description:
Test register page.
Method signatures and docstrings:
- def test_register_page_get_request(self): Test get request to Register Page.
- def test_register_new_user(self): Test registering new user.
<|skeleton|>
class RegisterPageTest... | 5d303bfb6f8729d73a34020bbec494ddb8099450 | <|skeleton|>
class RegisterPageTestCase:
"""Test register page."""
def test_register_page_get_request(self):
"""Test get request to Register Page."""
<|body_0|>
def test_register_new_user(self):
"""Test registering new user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RegisterPageTestCase:
"""Test register page."""
def test_register_page_get_request(self):
"""Test get request to Register Page."""
url = reverse('signup')
response = self.client.get(url)
logger.info(response)
self.assertEqual(response.status_code, 200)
def tes... | the_stack_v2_python_sparse | accounts/tests.py | ghrust/cs50w-finalProject-CRM | train | 1 |
3ee5675385b4ad8e75aad1a6c3df8bf123e393ea | [
"nums.sort(reverse=True)\ncount = 0\nfor i in range(1, len(nums)):\n if nums[i] < nums[i - 1]:\n count += 1\n if count == 2:\n return nums[i]\nreturn nums[0]",
"v = [float('-inf'), float('-inf'), float('-inf')]\nfor num in nums:\n if num not in v:\n if num > v[0]:\n v = [n... | <|body_start_0|>
nums.sort(reverse=True)
count = 0
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
count += 1
if count == 2:
return nums[i]
return nums[0]
<|end_body_0|>
<|body_start_1|>
v = [float('-inf'), float('-... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def thirdMax(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def thirdMax1(self, nums):
"""time O(n) space O(1) :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums.sort(reverse=True)
... | stack_v2_sparse_classes_10k_train_006665 | 1,076 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "thirdMax",
"signature": "def thirdMax(self, nums)"
},
{
"docstring": "time O(n) space O(1) :type nums: List[int] :rtype: int",
"name": "thirdMax1",
"signature": "def thirdMax1(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def thirdMax(self, nums): :type nums: List[int] :rtype: int
- def thirdMax1(self, nums): time O(n) space O(1) :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def thirdMax(self, nums): :type nums: List[int] :rtype: int
- def thirdMax1(self, nums): time O(n) space O(1) :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def thirdMax(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def thirdMax1(self, nums):
"""time O(n) space O(1) :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def thirdMax(self, nums):
""":type nums: List[int] :rtype: int"""
nums.sort(reverse=True)
count = 0
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
count += 1
if count == 2:
return nums[i]
return ... | the_stack_v2_python_sparse | LeetCode/Array/414_third_maximum_number.py | XyK0907/for_work | train | 0 | |
1d2a0580db0ce4c1b393a396813ce32bacc0633a | [
"if n == 0:\n return 0\nelif n == 1:\n return k\nelif n == 2:\n return k * k\nelif n > 2 and k == 1:\n return 0\na, b = (k, k * k)\nfor i in range(n - 2):\n a, b = (b, (a + b) * (k - 1))\nreturn b",
"if n == 0:\n return 0\nelif n == 1:\n return k\nelif n == 2:\n return k * k\nelif n > 2 an... | <|body_start_0|>
if n == 0:
return 0
elif n == 1:
return k
elif n == 2:
return k * k
elif n > 2 and k == 1:
return 0
a, b = (k, k * k)
for i in range(n - 2):
a, b = (b, (a + b) * (k - 1))
return b
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numWays(self, n: int, k: int) -> int:
"""20190924, 44 ms 13.9 MB Python3 我大概是个动态规划白痴, 整理了半天头绪, 毫无头绪 此解法参考网友的说法: 从第三根栅栏开始, 前两根颜色相同的情况是 k, 此时只能选不同的颜色, 有 k*(k-1) 种选择 前两根颜色不同的情况有 k*k-k 种, 此时可以尽情地选择, 于是有 (k*k-k)*k 种选择 两个合起来, 有 (k-1)(k*k+k), 这个式子的右边看起来很熟悉, 就是 f(n-1)+f(n-2), 不过这里缺... | stack_v2_sparse_classes_10k_train_006666 | 1,971 | no_license | [
{
"docstring": "20190924, 44 ms 13.9 MB Python3 我大概是个动态规划白痴, 整理了半天头绪, 毫无头绪 此解法参考网友的说法: 从第三根栅栏开始, 前两根颜色相同的情况是 k, 此时只能选不同的颜色, 有 k*(k-1) 种选择 前两根颜色不同的情况有 k*k-k 种, 此时可以尽情地选择, 于是有 (k*k-k)*k 种选择 两个合起来, 有 (k-1)(k*k+k), 这个式子的右边看起来很熟悉, 就是 f(n-1)+f(n-2), 不过这里缺少证据是否如此递推就行了",
"name": "numWays",
"signature": "def num... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numWays(self, n: int, k: int) -> int: 20190924, 44 ms 13.9 MB Python3 我大概是个动态规划白痴, 整理了半天头绪, 毫无头绪 此解法参考网友的说法: 从第三根栅栏开始, 前两根颜色相同的情况是 k, 此时只能选不同的颜色, 有 k*(k-1) 种选择 前两根颜色不同的情况有 k*... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numWays(self, n: int, k: int) -> int: 20190924, 44 ms 13.9 MB Python3 我大概是个动态规划白痴, 整理了半天头绪, 毫无头绪 此解法参考网友的说法: 从第三根栅栏开始, 前两根颜色相同的情况是 k, 此时只能选不同的颜色, 有 k*(k-1) 种选择 前两根颜色不同的情况有 k*... | 99a3abf1774933af73a8405f9b59e5e64906bca4 | <|skeleton|>
class Solution:
def numWays(self, n: int, k: int) -> int:
"""20190924, 44 ms 13.9 MB Python3 我大概是个动态规划白痴, 整理了半天头绪, 毫无头绪 此解法参考网友的说法: 从第三根栅栏开始, 前两根颜色相同的情况是 k, 此时只能选不同的颜色, 有 k*(k-1) 种选择 前两根颜色不同的情况有 k*k-k 种, 此时可以尽情地选择, 于是有 (k*k-k)*k 种选择 两个合起来, 有 (k-1)(k*k+k), 这个式子的右边看起来很熟悉, 就是 f(n-1)+f(n-2), 不过这里缺... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def numWays(self, n: int, k: int) -> int:
"""20190924, 44 ms 13.9 MB Python3 我大概是个动态规划白痴, 整理了半天头绪, 毫无头绪 此解法参考网友的说法: 从第三根栅栏开始, 前两根颜色相同的情况是 k, 此时只能选不同的颜色, 有 k*(k-1) 种选择 前两根颜色不同的情况有 k*k-k 种, 此时可以尽情地选择, 于是有 (k*k-k)*k 种选择 两个合起来, 有 (k-1)(k*k+k), 这个式子的右边看起来很熟悉, 就是 f(n-1)+f(n-2), 不过这里缺少证据是否如此递推就行了""... | the_stack_v2_python_sparse | leetcode/276.paint-fence.py | iamkissg/leetcode | train | 0 | |
0fda43b41181acbc181034010d6aecaab7d1d5d7 | [
"self.count = 0\nself.prefix = prefix\nself.name = name\nself.f5 = f5",
"if self.f5 is not None:\n file = self.name + '%03d.f5' % self.count\n filename = os.path.join(self.prefix, file)\n self.f5.writeToFile(filename)\nself.count += 1\nreturn"
] | <|body_start_0|>
self.count = 0
self.prefix = prefix
self.name = name
self.f5 = f5
<|end_body_0|>
<|body_start_1|>
if self.f5 is not None:
file = self.name + '%03d.f5' % self.count
filename = os.path.join(self.prefix, file)
self.f5.writeToFile... | TacsOutputGenerator | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TacsOutputGenerator:
def __init__(self, prefix, name='tacs_output_file', f5=None):
"""Store information about how to write TACS output files"""
<|body_0|>
def __call__(self):
"""Generate the output from TACS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_006667 | 41,127 | permissive | [
{
"docstring": "Store information about how to write TACS output files",
"name": "__init__",
"signature": "def __init__(self, prefix, name='tacs_output_file', f5=None)"
},
{
"docstring": "Generate the output from TACS",
"name": "__call__",
"signature": "def __call__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000332 | Implement the Python class `TacsOutputGenerator` described below.
Class description:
Implement the TacsOutputGenerator class.
Method signatures and docstrings:
- def __init__(self, prefix, name='tacs_output_file', f5=None): Store information about how to write TACS output files
- def __call__(self): Generate the outp... | Implement the Python class `TacsOutputGenerator` described below.
Class description:
Implement the TacsOutputGenerator class.
Method signatures and docstrings:
- def __init__(self, prefix, name='tacs_output_file', f5=None): Store information about how to write TACS output files
- def __call__(self): Generate the outp... | 4c11b61397100f9d8b455f7d20cf3b507a15c1e9 | <|skeleton|>
class TacsOutputGenerator:
def __init__(self, prefix, name='tacs_output_file', f5=None):
"""Store information about how to write TACS output files"""
<|body_0|>
def __call__(self):
"""Generate the output from TACS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TacsOutputGenerator:
def __init__(self, prefix, name='tacs_output_file', f5=None):
"""Store information about how to write TACS output files"""
self.count = 0
self.prefix = prefix
self.name = name
self.f5 = f5
def __call__(self):
"""Generate the output from... | the_stack_v2_python_sparse | funtofem/interface/tacs_interface.py | gjkennedy/funtofem | train | 0 | |
b312eea0cc5712c349f9cccf09ce237d0718761d | [
"self.report_periods = {}\nself.reports = {}\nself.line_items = []\nself.line_item_keys = {}\nself.requested_partitions = set()",
"self.report_periods = {}\nself.reports = {}\nself.line_items = []"
] | <|body_start_0|>
self.report_periods = {}
self.reports = {}
self.line_items = []
self.line_item_keys = {}
self.requested_partitions = set()
<|end_body_0|>
<|body_start_1|>
self.report_periods = {}
self.reports = {}
self.line_items = []
<|end_body_1|>
| Usage report transcribed to our database models. Effectively a struct for associated database tables. | ProcessedOCPReport | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcessedOCPReport:
"""Usage report transcribed to our database models. Effectively a struct for associated database tables."""
def __init__(self):
"""Initialize new cost entry containers."""
<|body_0|>
def remove_processed_rows(self):
"""Clear a batch of rows fr... | stack_v2_sparse_classes_10k_train_006668 | 22,491 | permissive | [
{
"docstring": "Initialize new cost entry containers.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Clear a batch of rows from their containers.",
"name": "remove_processed_rows",
"signature": "def remove_processed_rows(self)"
}
] | 2 | null | Implement the Python class `ProcessedOCPReport` described below.
Class description:
Usage report transcribed to our database models. Effectively a struct for associated database tables.
Method signatures and docstrings:
- def __init__(self): Initialize new cost entry containers.
- def remove_processed_rows(self): Cle... | Implement the Python class `ProcessedOCPReport` described below.
Class description:
Usage report transcribed to our database models. Effectively a struct for associated database tables.
Method signatures and docstrings:
- def __init__(self): Initialize new cost entry containers.
- def remove_processed_rows(self): Cle... | 2979f03fbdd1c20c3abc365a963a1282b426f321 | <|skeleton|>
class ProcessedOCPReport:
"""Usage report transcribed to our database models. Effectively a struct for associated database tables."""
def __init__(self):
"""Initialize new cost entry containers."""
<|body_0|>
def remove_processed_rows(self):
"""Clear a batch of rows fr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProcessedOCPReport:
"""Usage report transcribed to our database models. Effectively a struct for associated database tables."""
def __init__(self):
"""Initialize new cost entry containers."""
self.report_periods = {}
self.reports = {}
self.line_items = []
self.line... | the_stack_v2_python_sparse | koku/masu/processor/ocp/ocp_report_processor.py | luisfdez/koku | train | 0 |
4f95c96f5cfdd09c25091d7b66879f06782999c2 | [
"arr = self.linked_list_to_array(head)\nself.insertion_sort(arr)\nreturn self.array_to_linked_list(arr)",
"arr = []\nwhile head is not None:\n arr.append(head.val)\n head = head.next\nreturn arr",
"for i in range(1, len(arr)):\n j, tmp = (i, arr[i])\n while j and tmp < arr[j - 1]:\n arr[j] = ... | <|body_start_0|>
arr = self.linked_list_to_array(head)
self.insertion_sort(arr)
return self.array_to_linked_list(arr)
<|end_body_0|>
<|body_start_1|>
arr = []
while head is not None:
arr.append(head.val)
head = head.next
return arr
<|end_body_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
"""Time: O(n ** 2) Space: O(n)"""
<|body_0|>
def linked_list_to_array(self, head: ListNode) -> List[int]:
"""Time/Space: O(n)"""
<|body_1|>
def insertion_sort(self, arr: List[int]) -> Non... | stack_v2_sparse_classes_10k_train_006669 | 1,184 | no_license | [
{
"docstring": "Time: O(n ** 2) Space: O(n)",
"name": "insertionSortList",
"signature": "def insertionSortList(self, head: ListNode) -> ListNode"
},
{
"docstring": "Time/Space: O(n)",
"name": "linked_list_to_array",
"signature": "def linked_list_to_array(self, head: ListNode) -> List[int... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertionSortList(self, head: ListNode) -> ListNode: Time: O(n ** 2) Space: O(n)
- def linked_list_to_array(self, head: ListNode) -> List[int]: Time/Space: O(n)
- def inserti... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertionSortList(self, head: ListNode) -> ListNode: Time: O(n ** 2) Space: O(n)
- def linked_list_to_array(self, head: ListNode) -> List[int]: Time/Space: O(n)
- def inserti... | 359f3b78da90c41c7e42e5c9e13d49b4fc67fe41 | <|skeleton|>
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
"""Time: O(n ** 2) Space: O(n)"""
<|body_0|>
def linked_list_to_array(self, head: ListNode) -> List[int]:
"""Time/Space: O(n)"""
<|body_1|>
def insertion_sort(self, arr: List[int]) -> Non... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
"""Time: O(n ** 2) Space: O(n)"""
arr = self.linked_list_to_array(head)
self.insertion_sort(arr)
return self.array_to_linked_list(arr)
def linked_list_to_array(self, head: ListNode) -> List[int]:
""... | the_stack_v2_python_sparse | problems/147. Insertion Sort List/1 - Back to Array.py | Vasilic-Maxim/LeetCode-Problems | train | 0 | |
e944f9e3128a9961c73d637627ed381829741cc9 | [
"from real_time_detection.GUI.EmotivDeviceReader import EmotivDeviceReader\nself.emotiv_reader = EmotivDeviceReader()\nself.input_type = input_type\nif self.input_type == 'file':\n self.raw_EEG_obj = mne.io.read_raw_fif(file_path, preload=True)\n max_time = self.raw_EEG_obj.times.max()\n self.raw_EEG_obj.c... | <|body_start_0|>
from real_time_detection.GUI.EmotivDeviceReader import EmotivDeviceReader
self.emotiv_reader = EmotivDeviceReader()
self.input_type = input_type
if self.input_type == 'file':
self.raw_EEG_obj = mne.io.read_raw_fif(file_path, preload=True)
max_time... | This class is used to return the EEG data in real time. Attribute: raw_EEG_obj: the data for file input. MNE object. timestamp: the current time. how much second. features: the EEG features. | EEGReader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EEGReader:
"""This class is used to return the EEG data in real time. Attribute: raw_EEG_obj: the data for file input. MNE object. timestamp: the current time. how much second. features: the EEG features."""
def __init__(self, input_type, file_path=None):
"""Arguments: input_type: 'f... | stack_v2_sparse_classes_10k_train_006670 | 3,357 | permissive | [
{
"docstring": "Arguments: input_type: 'file' indicates that the stream is from file. In other case, the stream will from the 'Emotiv insight' device.",
"name": "__init__",
"signature": "def __init__(self, input_type, file_path=None)"
},
{
"docstring": "Return: EEG data: the EEG data timestamp: ... | 2 | stack_v2_sparse_classes_30k_train_004209 | Implement the Python class `EEGReader` described below.
Class description:
This class is used to return the EEG data in real time. Attribute: raw_EEG_obj: the data for file input. MNE object. timestamp: the current time. how much second. features: the EEG features.
Method signatures and docstrings:
- def __init__(sel... | Implement the Python class `EEGReader` described below.
Class description:
This class is used to return the EEG data in real time. Attribute: raw_EEG_obj: the data for file input. MNE object. timestamp: the current time. how much second. features: the EEG features.
Method signatures and docstrings:
- def __init__(sel... | 531f646dcb493dce2575af3b9d77403ebc1f4a35 | <|skeleton|>
class EEGReader:
"""This class is used to return the EEG data in real time. Attribute: raw_EEG_obj: the data for file input. MNE object. timestamp: the current time. how much second. features: the EEG features."""
def __init__(self, input_type, file_path=None):
"""Arguments: input_type: 'f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EEGReader:
"""This class is used to return the EEG data in real time. Attribute: raw_EEG_obj: the data for file input. MNE object. timestamp: the current time. how much second. features: the EEG features."""
def __init__(self, input_type, file_path=None):
"""Arguments: input_type: 'file' indicate... | the_stack_v2_python_sparse | MindLink-Eumpy/real_time_detection/GUI/MLE_tool/EEGReader.py | wozu-dichter/MindLink-Explorer | train | 0 |
e5165bc6d8806030e8083bd2f0f19926188b4369 | [
"self.letters = []\nself.nums = []\nidx = 0\nwhile idx < len(compressedString):\n if compressedString[idx].isalpha():\n self.letters.append(compressedString[idx])\n idx += 1\n else:\n tmp = ''\n while idx < len(compressedString) and compressedString[idx].isdigit():\n tmp... | <|body_start_0|>
self.letters = []
self.nums = []
idx = 0
while idx < len(compressedString):
if compressedString[idx].isalpha():
self.letters.append(compressedString[idx])
idx += 1
else:
tmp = ''
whil... | StringIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
<|body_0|>
def next(self):
""":rtype: str"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
s... | stack_v2_sparse_classes_10k_train_006671 | 1,632 | no_license | [
{
"docstring": ":type compressedString: str",
"name": "__init__",
"signature": "def __init__(self, compressedString)"
},
{
"docstring": ":rtype: str",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",
"signature": "def hasN... | 3 | null | Implement the Python class `StringIterator` described below.
Class description:
Implement the StringIterator class.
Method signatures and docstrings:
- def __init__(self, compressedString): :type compressedString: str
- def next(self): :rtype: str
- def hasNext(self): :rtype: bool | Implement the Python class `StringIterator` described below.
Class description:
Implement the StringIterator class.
Method signatures and docstrings:
- def __init__(self, compressedString): :type compressedString: str
- def next(self): :rtype: str
- def hasNext(self): :rtype: bool
<|skeleton|>
class StringIterator:
... | ee79d3437cf47b26a4bca0ec798dc54d7b623453 | <|skeleton|>
class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
<|body_0|>
def next(self):
""":rtype: str"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
self.letters = []
self.nums = []
idx = 0
while idx < len(compressedString):
if compressedString[idx].isalpha():
self.letters.append(compressedString[idx])... | the_stack_v2_python_sparse | Algorithm/Python/604. Design Compressed String Iterator.py | WuLC/LeetCode | train | 29 | |
fc03807c295a38d09031f06193ca3131d8cd9d21 | [
"new_emp = Employee(*personal_identity)\nregistration_str = new_emp.get_registration_str()\nreturn_value = self.save_object_to_DB('employee', registration_str)\nreturn return_value",
"changed_emp = Employee(*changed_identity)\nchanged_str = changed_emp.get_changes_registration_str()\nreturn_value = self.change_ob... | <|body_start_0|>
new_emp = Employee(*personal_identity)
registration_str = new_emp.get_registration_str()
return_value = self.save_object_to_DB('employee', registration_str)
return return_value
<|end_body_0|>
<|body_start_1|>
changed_emp = Employee(*changed_identity)
cha... | EmployeeLL | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmployeeLL:
def create_employee(self, personal_identity):
"""Creates a new employee and saves to database. personal_identity = ('',ssn,name,address,mobile,email,role,rank,licence)"""
<|body_0|>
def change_employee(self, changed_identity):
"""Changes information about... | stack_v2_sparse_classes_10k_train_006672 | 2,878 | no_license | [
{
"docstring": "Creates a new employee and saves to database. personal_identity = ('',ssn,name,address,mobile,email,role,rank,licence)",
"name": "create_employee",
"signature": "def create_employee(self, personal_identity)"
},
{
"docstring": "Changes information about employee, except ssn, name ... | 4 | stack_v2_sparse_classes_30k_val_000175 | Implement the Python class `EmployeeLL` described below.
Class description:
Implement the EmployeeLL class.
Method signatures and docstrings:
- def create_employee(self, personal_identity): Creates a new employee and saves to database. personal_identity = ('',ssn,name,address,mobile,email,role,rank,licence)
- def cha... | Implement the Python class `EmployeeLL` described below.
Class description:
Implement the EmployeeLL class.
Method signatures and docstrings:
- def create_employee(self, personal_identity): Creates a new employee and saves to database. personal_identity = ('',ssn,name,address,mobile,email,role,rank,licence)
- def cha... | ee2b2e6c1422ebab40e36ed3ed23f6f70ee7adb2 | <|skeleton|>
class EmployeeLL:
def create_employee(self, personal_identity):
"""Creates a new employee and saves to database. personal_identity = ('',ssn,name,address,mobile,email,role,rank,licence)"""
<|body_0|>
def change_employee(self, changed_identity):
"""Changes information about... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EmployeeLL:
def create_employee(self, personal_identity):
"""Creates a new employee and saves to database. personal_identity = ('',ssn,name,address,mobile,email,role,rank,licence)"""
new_emp = Employee(*personal_identity)
registration_str = new_emp.get_registration_str()
return... | the_stack_v2_python_sparse | random code snippets/EmployeeLL_sigurgeir.py | heidars19/3ja-vikna-verkefni | train | 3 | |
81065031a3f5302400e118a6183efdb2dda1ac34 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TeleconferenceDeviceQuality()",
"from .teleconference_device_media_quality import TeleconferenceDeviceMediaQuality\nfrom .teleconference_device_media_quality import TeleconferenceDeviceMediaQuality\nfields: Dict[str, Callable[[Any], No... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TeleconferenceDeviceQuality()
<|end_body_0|>
<|body_start_1|>
from .teleconference_device_media_quality import TeleconferenceDeviceMediaQuality
from .teleconference_device_media_quality ... | TeleconferenceDeviceQuality | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeleconferenceDeviceQuality:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeleconferenceDeviceQuality:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a... | stack_v2_sparse_classes_10k_train_006673 | 6,036 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TeleconferenceDeviceQuality",
"name": "create_from_discriminator_value",
"signature": "def create_from_discr... | 3 | null | Implement the Python class `TeleconferenceDeviceQuality` described below.
Class description:
Implement the TeleconferenceDeviceQuality class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeleconferenceDeviceQuality: Creates a new instance of the appr... | Implement the Python class `TeleconferenceDeviceQuality` described below.
Class description:
Implement the TeleconferenceDeviceQuality class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeleconferenceDeviceQuality: Creates a new instance of the appr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TeleconferenceDeviceQuality:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeleconferenceDeviceQuality:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TeleconferenceDeviceQuality:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeleconferenceDeviceQuality:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | the_stack_v2_python_sparse | msgraph/generated/models/teleconference_device_quality.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
63d9321f25894963ef75a18b8cac17fdd6ccb80a | [
"model = User\nname = 'Users'\nsuper().__init__(model=model, collection_name=name)\nself.__dog_owner_repository = dog_owner_repository",
"users = list()\nowners = self.__dog_owner_repository.search(f'dog_id=={dog_id}')\nfor dog_owner in owners.to_list():\n try:\n user = self.read(dog_owner.owner_id)\n ... | <|body_start_0|>
model = User
name = 'Users'
super().__init__(model=model, collection_name=name)
self.__dog_owner_repository = dog_owner_repository
<|end_body_0|>
<|body_start_1|>
users = list()
owners = self.__dog_owner_repository.search(f'dog_id=={dog_id}')
for... | User repository. | UserRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRepository:
"""User repository."""
def __init__(self, dog_owner_repository):
"""Initialize user repository."""
<|body_0|>
def read_owners_of_dog(self, dog_id):
"""Get dogs associated with this user_id."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_10k_train_006674 | 925 | no_license | [
{
"docstring": "Initialize user repository.",
"name": "__init__",
"signature": "def __init__(self, dog_owner_repository)"
},
{
"docstring": "Get dogs associated with this user_id.",
"name": "read_owners_of_dog",
"signature": "def read_owners_of_dog(self, dog_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000610 | Implement the Python class `UserRepository` described below.
Class description:
User repository.
Method signatures and docstrings:
- def __init__(self, dog_owner_repository): Initialize user repository.
- def read_owners_of_dog(self, dog_id): Get dogs associated with this user_id. | Implement the Python class `UserRepository` described below.
Class description:
User repository.
Method signatures and docstrings:
- def __init__(self, dog_owner_repository): Initialize user repository.
- def read_owners_of_dog(self, dog_id): Get dogs associated with this user_id.
<|skeleton|>
class UserRepository:
... | 129dc7f8213fb3112c35b1551d9ed3d8a14b7fb5 | <|skeleton|>
class UserRepository:
"""User repository."""
def __init__(self, dog_owner_repository):
"""Initialize user repository."""
<|body_0|>
def read_owners_of_dog(self, dog_id):
"""Get dogs associated with this user_id."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserRepository:
"""User repository."""
def __init__(self, dog_owner_repository):
"""Initialize user repository."""
model = User
name = 'Users'
super().__init__(model=model, collection_name=name)
self.__dog_owner_repository = dog_owner_repository
def read_owner... | the_stack_v2_python_sparse | hugbunadarfr_backend/src/app/repository/repositories/user_repository.py | birna17/veff_hugb | train | 0 |
7dc0c34e77219355e4df243a2e90735d469c3c04 | [
"mediawiki_index_url = str(mediawiki_index_url or config['MEDIAWIKI_INDEX_URL'])\nif access_token and access_secret:\n session = OAuth1Session(client_key=consumer_token, client_secret=consumer_secret, resource_owner_key=access_token, resource_owner_secret=access_secret)\n super().__init__(session=session, tok... | <|body_start_0|>
mediawiki_index_url = str(mediawiki_index_url or config['MEDIAWIKI_INDEX_URL'])
if access_token and access_secret:
session = OAuth1Session(client_key=consumer_token, client_secret=consumer_secret, resource_owner_key=access_token, resource_owner_secret=access_secret)
... | OAuth1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OAuth1:
def __init__(self, consumer_token: Optional[str]=None, consumer_secret: Optional[str]=None, access_token: Optional[str]=None, access_secret: Optional[str]=None, callback_url: str='oob', mediawiki_api_url: Optional[str]=None, mediawiki_index_url: Optional[str]=None, token_renew_period: in... | stack_v2_sparse_classes_10k_train_006675 | 13,808 | permissive | [
{
"docstring": "This class is used to interact with the OAuth1 API. :param consumer_token: The consumer token :param consumer_secret: The consumer secret :param access_token: The access token (optional ) :param access_secret: The access secret (optional) :param callback_url: The callback URL used to finalize th... | 2 | stack_v2_sparse_classes_30k_train_005592 | Implement the Python class `OAuth1` described below.
Class description:
Implement the OAuth1 class.
Method signatures and docstrings:
- def __init__(self, consumer_token: Optional[str]=None, consumer_secret: Optional[str]=None, access_token: Optional[str]=None, access_secret: Optional[str]=None, callback_url: str='oo... | Implement the Python class `OAuth1` described below.
Class description:
Implement the OAuth1 class.
Method signatures and docstrings:
- def __init__(self, consumer_token: Optional[str]=None, consumer_secret: Optional[str]=None, access_token: Optional[str]=None, access_secret: Optional[str]=None, callback_url: str='oo... | bec2cb079cf61edf8248120054e673a00e50f457 | <|skeleton|>
class OAuth1:
def __init__(self, consumer_token: Optional[str]=None, consumer_secret: Optional[str]=None, access_token: Optional[str]=None, access_secret: Optional[str]=None, callback_url: str='oob', mediawiki_api_url: Optional[str]=None, mediawiki_index_url: Optional[str]=None, token_renew_period: in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OAuth1:
def __init__(self, consumer_token: Optional[str]=None, consumer_secret: Optional[str]=None, access_token: Optional[str]=None, access_secret: Optional[str]=None, callback_url: str='oob', mediawiki_api_url: Optional[str]=None, mediawiki_index_url: Optional[str]=None, token_renew_period: int=1800, user_a... | the_stack_v2_python_sparse | wikibaseintegrator/wbi_login.py | LeMyst/WikibaseIntegrator | train | 56 | |
ad5481e9b26a8ea9f9d56a19ed369ce6fad3ce59 | [
"user = request.user\ncheck_user_status(user)\nuser_id = user.id\nvalidate(instance=request.data, schema=schemas.user_fav_schema)\nbody = request.data\nbody['user_id'] = user_id\nrest_id = body['restaurant']\nUserFavRestrs.field_validate(body)\nresponse = UserFavRestrs.insert(user_id, rest_id)\nreturn JsonResponse(... | <|body_start_0|>
user = request.user
check_user_status(user)
user_id = user.id
validate(instance=request.data, schema=schemas.user_fav_schema)
body = request.data
body['user_id'] = user_id
rest_id = body['restaurant']
UserFavRestrs.field_validate(body)
... | user fav view | UserFavView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserFavView:
"""user fav view"""
def post(self, request):
"""Add a new user-restaurant-favourite relation"""
<|body_0|>
def get(self, request):
"""Get all restaurants favourited by a user"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = re... | stack_v2_sparse_classes_10k_train_006676 | 19,356 | no_license | [
{
"docstring": "Add a new user-restaurant-favourite relation",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Get all restaurants favourited by a user",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000228 | Implement the Python class `UserFavView` described below.
Class description:
user fav view
Method signatures and docstrings:
- def post(self, request): Add a new user-restaurant-favourite relation
- def get(self, request): Get all restaurants favourited by a user | Implement the Python class `UserFavView` described below.
Class description:
user fav view
Method signatures and docstrings:
- def post(self, request): Add a new user-restaurant-favourite relation
- def get(self, request): Get all restaurants favourited by a user
<|skeleton|>
class UserFavView:
"""user fav view"... | 2707062c9a9a8bb4baca955e8a60ba08cc9f8953 | <|skeleton|>
class UserFavView:
"""user fav view"""
def post(self, request):
"""Add a new user-restaurant-favourite relation"""
<|body_0|>
def get(self, request):
"""Get all restaurants favourited by a user"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserFavView:
"""user fav view"""
def post(self, request):
"""Add a new user-restaurant-favourite relation"""
user = request.user
check_user_status(user)
user_id = user.id
validate(instance=request.data, schema=schemas.user_fav_schema)
body = request.data
... | the_stack_v2_python_sparse | backend/restaurant/views.py | MochiTarts/Find-Dining-The-Bridge | train | 1 |
dc7edeb3d911e5d8e85d52b8b40dd2e9f67f71aa | [
"super(UpsampleChecker, self).__init__()\nself.upsample = nn.Upsample(scale_factor=scale_factor, mode=mode)\nself.reflection_pad = reflection_padding\nself.conv = nn.Conv3d(channels, channels // ch_mult, kernel_size=kernel_size, stride=stride, padding=conv_padding, bias=deconv_bias)",
"print('upsample')\nprint('o... | <|body_start_0|>
super(UpsampleChecker, self).__init__()
self.upsample = nn.Upsample(scale_factor=scale_factor, mode=mode)
self.reflection_pad = reflection_padding
self.conv = nn.Conv3d(channels, channels // ch_mult, kernel_size=kernel_size, stride=stride, padding=conv_padding, bias=deco... | UpsampleChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpsampleChecker:
def __init__(self, scale_factor, mode, reflection_padding, channels, ch_mult, kernel_size, conv_padding, stride, deconv_bias):
"""https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/190 nn.Upsample(scale_factor = 2, mode='bilinear'), nn.ReflectionPad2d(1), nn.... | stack_v2_sparse_classes_10k_train_006677 | 12,177 | no_license | [
{
"docstring": "https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/190 nn.Upsample(scale_factor = 2, mode='bilinear'), nn.ReflectionPad2d(1), nn.Conv2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=1, padding=0) nn.Upsample mode (string, optional) – the upsampling algorithm: one of nearest,... | 2 | stack_v2_sparse_classes_30k_train_003676 | Implement the Python class `UpsampleChecker` described below.
Class description:
Implement the UpsampleChecker class.
Method signatures and docstrings:
- def __init__(self, scale_factor, mode, reflection_padding, channels, ch_mult, kernel_size, conv_padding, stride, deconv_bias): https://github.com/junyanz/pytorch-Cy... | Implement the Python class `UpsampleChecker` described below.
Class description:
Implement the UpsampleChecker class.
Method signatures and docstrings:
- def __init__(self, scale_factor, mode, reflection_padding, channels, ch_mult, kernel_size, conv_padding, stride, deconv_bias): https://github.com/junyanz/pytorch-Cy... | 67f7126cf2f4e5c09e52efd3553754e463e90a0e | <|skeleton|>
class UpsampleChecker:
def __init__(self, scale_factor, mode, reflection_padding, channels, ch_mult, kernel_size, conv_padding, stride, deconv_bias):
"""https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/190 nn.Upsample(scale_factor = 2, mode='bilinear'), nn.ReflectionPad2d(1), nn.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UpsampleChecker:
def __init__(self, scale_factor, mode, reflection_padding, channels, ch_mult, kernel_size, conv_padding, stride, deconv_bias):
"""https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/190 nn.Upsample(scale_factor = 2, mode='bilinear'), nn.ReflectionPad2d(1), nn.Conv2d(ngf * m... | the_stack_v2_python_sparse | mmd_gan/models/decoder_v04_UpsampleConv.py | NYU-CDS-Capstone-Project/HydroGAN | train | 1 | |
395e36665d523d4ccbb30d24c912b8e71cba6822 | [
"wiz = self.browse(cr, uid, ids, context=context)[0]\ndata = {}\ndata['parameters'] = {'partner_id': context.get('active_id'), 'date_start': wiz.date_start, 'date_end': wiz.date_end}\nreturn {'type': 'ir.actions.report.xml', 'report_name': 'statement_general', 'datas': data}",
"wiz = self.browse(cr, uid, ids, con... | <|body_start_0|>
wiz = self.browse(cr, uid, ids, context=context)[0]
data = {}
data['parameters'] = {'partner_id': context.get('active_id'), 'date_start': wiz.date_start, 'date_end': wiz.date_end}
return {'type': 'ir.actions.report.xml', 'report_name': 'statement_general', 'datas': data}... | statement_general_report | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class statement_general_report:
def launch(self, cr, uid, ids, context=None):
"""Launch the report, and pass each value in the form as parameters"""
<|body_0|>
def launch_detail(self, cr, uid, ids, context=None):
"""Launch the report, and pass each value in the form as par... | stack_v2_sparse_classes_10k_train_006678 | 2,762 | no_license | [
{
"docstring": "Launch the report, and pass each value in the form as parameters",
"name": "launch",
"signature": "def launch(self, cr, uid, ids, context=None)"
},
{
"docstring": "Launch the report, and pass each value in the form as parameters",
"name": "launch_detail",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_006810 | Implement the Python class `statement_general_report` described below.
Class description:
Implement the statement_general_report class.
Method signatures and docstrings:
- def launch(self, cr, uid, ids, context=None): Launch the report, and pass each value in the form as parameters
- def launch_detail(self, cr, uid, ... | Implement the Python class `statement_general_report` described below.
Class description:
Implement the statement_general_report class.
Method signatures and docstrings:
- def launch(self, cr, uid, ids, context=None): Launch the report, and pass each value in the form as parameters
- def launch_detail(self, cr, uid, ... | a5e9f95c59be058aead30e1c6de867ed36354e6a | <|skeleton|>
class statement_general_report:
def launch(self, cr, uid, ids, context=None):
"""Launch the report, and pass each value in the form as parameters"""
<|body_0|>
def launch_detail(self, cr, uid, ids, context=None):
"""Launch the report, and pass each value in the form as par... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class statement_general_report:
def launch(self, cr, uid, ids, context=None):
"""Launch the report, and pass each value in the form as parameters"""
wiz = self.browse(cr, uid, ids, context=context)[0]
data = {}
data['parameters'] = {'partner_id': context.get('active_id'), 'date_start... | the_stack_v2_python_sparse | prooaddons/customer_statement/report/report.py | wissemsh/prooaddons | train | 0 | |
a0f494c2b48be27b09132b6613b7089bed6b4555 | [
"create_data = obj_in.dict()\ndb_obj = Message(**create_data)\ndb.add(db_obj)\ndb.commit()\nreturn db_obj",
"res = db.query(self.model).filter(Message.room_id == room_id).order_by(Message.timestamp.desc()).offset(skip).limit(limit).all()\nres.reverse()\nreturn res"
] | <|body_start_0|>
create_data = obj_in.dict()
db_obj = Message(**create_data)
db.add(db_obj)
db.commit()
return db_obj
<|end_body_0|>
<|body_start_1|>
res = db.query(self.model).filter(Message.room_id == room_id).order_by(Message.timestamp.desc()).offset(skip).limit(limit... | CRUDMessage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CRUDMessage:
def create(self, db: Session, *, obj_in: MessageCreate) -> Message:
"""Override base create function, so as to omit json encoder step"""
<|body_0|>
def get_multi_by_room(self, db: Session, *, room_id: int, skip: int=0, limit: int=100) -> List[Message]:
"... | stack_v2_sparse_classes_10k_train_006679 | 1,220 | no_license | [
{
"docstring": "Override base create function, so as to omit json encoder step",
"name": "create",
"signature": "def create(self, db: Session, *, obj_in: MessageCreate) -> Message"
},
{
"docstring": "Get messages for a given room. Messages are sorted in descending order, so that `limit` applies ... | 2 | stack_v2_sparse_classes_30k_train_001585 | Implement the Python class `CRUDMessage` described below.
Class description:
Implement the CRUDMessage class.
Method signatures and docstrings:
- def create(self, db: Session, *, obj_in: MessageCreate) -> Message: Override base create function, so as to omit json encoder step
- def get_multi_by_room(self, db: Session... | Implement the Python class `CRUDMessage` described below.
Class description:
Implement the CRUDMessage class.
Method signatures and docstrings:
- def create(self, db: Session, *, obj_in: MessageCreate) -> Message: Override base create function, so as to omit json encoder step
- def get_multi_by_room(self, db: Session... | d01eab579e33d2af6ab2c7d3a2587fab8b578ad1 | <|skeleton|>
class CRUDMessage:
def create(self, db: Session, *, obj_in: MessageCreate) -> Message:
"""Override base create function, so as to omit json encoder step"""
<|body_0|>
def get_multi_by_room(self, db: Session, *, room_id: int, skip: int=0, limit: int=100) -> List[Message]:
"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CRUDMessage:
def create(self, db: Session, *, obj_in: MessageCreate) -> Message:
"""Override base create function, so as to omit json encoder step"""
create_data = obj_in.dict()
db_obj = Message(**create_data)
db.add(db_obj)
db.commit()
return db_obj
def ge... | the_stack_v2_python_sparse | journeychat/crud/crud_message.py | dustinmichels/journeychat-backend | train | 0 | |
3c1bbb0f188cf6d2e839ff701af3958dbfd89554 | [
"def dfs(n, m):\n if n < 0 or m < 0:\n return 0\n return max(dfs(n - 1, m), dfs(n, m - 1)) + grid[n][m]\nrow = len(grid) - 1\ncolumn = len(grid[0]) - 1\nreturn dfs(row, column)",
"row = len(grid)\ncolumn = len(grid[0])\ndp = [[0] * column for i in range(row)]\nfor i in range(row):\n for j in range... | <|body_start_0|>
def dfs(n, m):
if n < 0 or m < 0:
return 0
return max(dfs(n - 1, m), dfs(n, m - 1)) + grid[n][m]
row = len(grid) - 1
column = len(grid[0]) - 1
return dfs(row, column)
<|end_body_0|>
<|body_start_1|>
row = len(grid)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxValue2(self, grid: List[List[int]]) -> int:
"""递归逆推,超时. 可以优化,加上剪枝"""
<|body_0|>
def maxValue(self, grid: List[List[int]]) -> int:
"""动态规划。 使用一个二维数组DP,计算每一个格子中的最大值,最后取最后一个格子中的值。 Args: grid: Returns:"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_10k_train_006680 | 1,637 | no_license | [
{
"docstring": "递归逆推,超时. 可以优化,加上剪枝",
"name": "maxValue2",
"signature": "def maxValue2(self, grid: List[List[int]]) -> int"
},
{
"docstring": "动态规划。 使用一个二维数组DP,计算每一个格子中的最大值,最后取最后一个格子中的值。 Args: grid: Returns:",
"name": "maxValue",
"signature": "def maxValue(self, grid: List[List[int]]) -> ... | 2 | stack_v2_sparse_classes_30k_train_005938 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxValue2(self, grid: List[List[int]]) -> int: 递归逆推,超时. 可以优化,加上剪枝
- def maxValue(self, grid: List[List[int]]) -> int: 动态规划。 使用一个二维数组DP,计算每一个格子中的最大值,最后取最后一个格子中的值。 Args: grid: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxValue2(self, grid: List[List[int]]) -> int: 递归逆推,超时. 可以优化,加上剪枝
- def maxValue(self, grid: List[List[int]]) -> int: 动态规划。 使用一个二维数组DP,计算每一个格子中的最大值,最后取最后一个格子中的值。 Args: grid: ... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class Solution:
def maxValue2(self, grid: List[List[int]]) -> int:
"""递归逆推,超时. 可以优化,加上剪枝"""
<|body_0|>
def maxValue(self, grid: List[List[int]]) -> int:
"""动态规划。 使用一个二维数组DP,计算每一个格子中的最大值,最后取最后一个格子中的值。 Args: grid: Returns:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxValue2(self, grid: List[List[int]]) -> int:
"""递归逆推,超时. 可以优化,加上剪枝"""
def dfs(n, m):
if n < 0 or m < 0:
return 0
return max(dfs(n - 1, m), dfs(n, m - 1)) + grid[n][m]
row = len(grid) - 1
column = len(grid[0]) - 1
r... | the_stack_v2_python_sparse | leetcode/剑指offer/剑指 Offer 47. 礼物的最大价值.py | tenqaz/crazy_arithmetic | train | 0 | |
ba8cbde3934a244f362fc11ce2e8584d80fe25b9 | [
"super(SimulatedExecutionHandler, self).__init__(data_handler.events, False)\nself.data_handler = data_handler\nself.transaction_cost = transaction_cost",
"symbol = order_event.symbol\nquantity = order_event.quantity\naction = params.action_dict[order_event.direction, order_event.trade_type]\nprice_id = [params.P... | <|body_start_0|>
super(SimulatedExecutionHandler, self).__init__(data_handler.events, False)
self.data_handler = data_handler
self.transaction_cost = transaction_cost
<|end_body_0|>
<|body_start_1|>
symbol = order_event.symbol
quantity = order_event.quantity
action = par... | Simulated Execution Handler Class The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency, slippage or fill-ratio issues. This allows a straightforward 'first go' test of any strategy, before implementation with a more sophisticated execution ha... | SimulatedExecutionHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulatedExecutionHandler:
"""Simulated Execution Handler Class The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency, slippage or fill-ratio issues. This allows a straightforward 'first go' test of any strategy, before ... | stack_v2_sparse_classes_10k_train_006681 | 2,574 | permissive | [
{
"docstring": "Initialize parameters of the simulated execution handler object.",
"name": "__init__",
"signature": "def __init__(self, data_handler, transaction_cost=0.0005)"
},
{
"docstring": "Implementation of abstract base class method.",
"name": "execute_order",
"signature": "def ex... | 2 | stack_v2_sparse_classes_30k_train_006358 | Implement the Python class `SimulatedExecutionHandler` described below.
Class description:
Simulated Execution Handler Class The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency, slippage or fill-ratio issues. This allows a straightforward '... | Implement the Python class `SimulatedExecutionHandler` described below.
Class description:
Simulated Execution Handler Class The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency, slippage or fill-ratio issues. This allows a straightforward '... | e2e9d638c68947d24f1260d35a3527dd84c2523f | <|skeleton|>
class SimulatedExecutionHandler:
"""Simulated Execution Handler Class The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency, slippage or fill-ratio issues. This allows a straightforward 'first go' test of any strategy, before ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SimulatedExecutionHandler:
"""Simulated Execution Handler Class The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency, slippage or fill-ratio issues. This allows a straightforward 'first go' test of any strategy, before implementatio... | the_stack_v2_python_sparse | odin/handlers/execution_handler/simulated_execution_handler.py | stjordanis/Odin | train | 0 |
55a8d31018ec74d8722fc0afe894a7a192e2d665 | [
"schema = AuditListInputSchema()\nparams, errors = schema.load(request.args)\nif errors:\n abort(400, errors)\naudit_query = AuditTable.select(AuditTable, fn.GROUP_CONCAT(ContactTable.name.distinct(), ContactSchema.SEPARATER_NAME_EMAIL, ContactTable.email, python_value=lambda contacts: [dict(zip(['name', 'email'... | <|body_start_0|>
schema = AuditListInputSchema()
params, errors = schema.load(request.args)
if errors:
abort(400, errors)
audit_query = AuditTable.select(AuditTable, fn.GROUP_CONCAT(ContactTable.name.distinct(), ContactSchema.SEPARATER_NAME_EMAIL, ContactTable.email, python_v... | AuditList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuditList:
def get(self):
"""Get audit list"""
<|body_0|>
def post(self):
"""Register new audit"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
schema = AuditListInputSchema()
params, errors = schema.load(request.args)
if errors:
... | stack_v2_sparse_classes_10k_train_006682 | 18,857 | no_license | [
{
"docstring": "Get audit list",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Register new audit",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001609 | Implement the Python class `AuditList` described below.
Class description:
Implement the AuditList class.
Method signatures and docstrings:
- def get(self): Get audit list
- def post(self): Register new audit | Implement the Python class `AuditList` described below.
Class description:
Implement the AuditList class.
Method signatures and docstrings:
- def get(self): Get audit list
- def post(self): Register new audit
<|skeleton|>
class AuditList:
def get(self):
"""Get audit list"""
<|body_0|>
def p... | 7b67aa682d73c8a8d7f0f19b2a90e69c40761c58 | <|skeleton|>
class AuditList:
def get(self):
"""Get audit list"""
<|body_0|>
def post(self):
"""Register new audit"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AuditList:
def get(self):
"""Get audit list"""
schema = AuditListInputSchema()
params, errors = schema.load(request.args)
if errors:
abort(400, errors)
audit_query = AuditTable.select(AuditTable, fn.GROUP_CONCAT(ContactTable.name.distinct(), ContactSchema.SE... | the_stack_v2_python_sparse | rem/apis/audit.py | recruit-tech/casval | train | 6 | |
ddcce92c09f66cba5252185319007086695f1f86 | [
"test_donor1 = Donor('test_donor', [100.0])\ntest_donor2 = Donor('test_donor2', [200.0])\ntest_donor1.add_donation(float(50))\ntest_donor1.name = 'test_donor1'\ncomparison = test_donor1 < test_donor2\nexpected_letter = 'Dear test_donor1,\\n\\nThank you for your generous donation of $50.00.\\n\\nSincerely,\\nThe Cha... | <|body_start_0|>
test_donor1 = Donor('test_donor', [100.0])
test_donor2 = Donor('test_donor2', [200.0])
test_donor1.add_donation(float(50))
test_donor1.name = 'test_donor1'
comparison = test_donor1 < test_donor2
expected_letter = 'Dear test_donor1,\n\nThank you for your g... | Write a class containing a full suite of tests | TestMailroom | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMailroom:
"""Write a class containing a full suite of tests"""
def test_donor_class(self):
"""Check that the data for individual donors is being saved properly"""
<|body_0|>
def test_collection_class(self):
"""Check that the data for a collection of donors is... | stack_v2_sparse_classes_10k_train_006683 | 2,652 | no_license | [
{
"docstring": "Check that the data for individual donors is being saved properly",
"name": "test_donor_class",
"signature": "def test_donor_class(self)"
},
{
"docstring": "Check that the data for a collection of donors is being saved properly",
"name": "test_collection_class",
"signatur... | 4 | null | Implement the Python class `TestMailroom` described below.
Class description:
Write a class containing a full suite of tests
Method signatures and docstrings:
- def test_donor_class(self): Check that the data for individual donors is being saved properly
- def test_collection_class(self): Check that the data for a co... | Implement the Python class `TestMailroom` described below.
Class description:
Write a class containing a full suite of tests
Method signatures and docstrings:
- def test_donor_class(self): Check that the data for individual donors is being saved properly
- def test_collection_class(self): Check that the data for a co... | e298b1151dab639659d8dfa56f47bcb43dd3438f | <|skeleton|>
class TestMailroom:
"""Write a class containing a full suite of tests"""
def test_donor_class(self):
"""Check that the data for individual donors is being saved properly"""
<|body_0|>
def test_collection_class(self):
"""Check that the data for a collection of donors is... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestMailroom:
"""Write a class containing a full suite of tests"""
def test_donor_class(self):
"""Check that the data for individual donors is being saved properly"""
test_donor1 = Donor('test_donor', [100.0])
test_donor2 = Donor('test_donor2', [200.0])
test_donor1.add_don... | the_stack_v2_python_sparse | students/Daniel_Spray/Lesson09/test_mailroom5.py | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | train | 13 |
72538b8a72e12395b10a7f2a0b36901eefdbbe0a | [
"try:\n label = await get_data_from_req(self.request).labels.get(label_id)\nexcept ResourceNotFoundError:\n raise NotFound()\nreturn json_response(label)",
"if not data:\n raise EmptyRequest()\ntry:\n label = await get_data_from_req(self.request).labels.update(label_id=label_id, data=data)\nexcept Res... | <|body_start_0|>
try:
label = await get_data_from_req(self.request).labels.get(label_id)
except ResourceNotFoundError:
raise NotFound()
return json_response(label)
<|end_body_0|>
<|body_start_1|>
if not data:
raise EmptyRequest()
try:
... | LabelView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelView:
async def get(self, label_id: int, /) -> Union[r200[LabelResponse], r404]:
"""Get a label. Fetches the details for a sample label. Status Codes: 200: Successful operation 404: Not found"""
<|body_0|>
async def patch(self, label_id: int, /, data: UpdateLabelRequest... | stack_v2_sparse_classes_10k_train_006684 | 3,972 | permissive | [
{
"docstring": "Get a label. Fetches the details for a sample label. Status Codes: 200: Successful operation 404: Not found",
"name": "get",
"signature": "async def get(self, label_id: int, /) -> Union[r200[LabelResponse], r404]"
},
{
"docstring": "Update a label. Updates an existing sample labe... | 3 | null | Implement the Python class `LabelView` described below.
Class description:
Implement the LabelView class.
Method signatures and docstrings:
- async def get(self, label_id: int, /) -> Union[r200[LabelResponse], r404]: Get a label. Fetches the details for a sample label. Status Codes: 200: Successful operation 404: Not... | Implement the Python class `LabelView` described below.
Class description:
Implement the LabelView class.
Method signatures and docstrings:
- async def get(self, label_id: int, /) -> Union[r200[LabelResponse], r404]: Get a label. Fetches the details for a sample label. Status Codes: 200: Successful operation 404: Not... | 1d17d2ba570cf5487e7514bec29250a5b368bb0a | <|skeleton|>
class LabelView:
async def get(self, label_id: int, /) -> Union[r200[LabelResponse], r404]:
"""Get a label. Fetches the details for a sample label. Status Codes: 200: Successful operation 404: Not found"""
<|body_0|>
async def patch(self, label_id: int, /, data: UpdateLabelRequest... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LabelView:
async def get(self, label_id: int, /) -> Union[r200[LabelResponse], r404]:
"""Get a label. Fetches the details for a sample label. Status Codes: 200: Successful operation 404: Not found"""
try:
label = await get_data_from_req(self.request).labels.get(label_id)
ex... | the_stack_v2_python_sparse | virtool/labels/api.py | virtool/virtool | train | 45 | |
5730b3d0651858fa7d349af2c34395ade286145a | [
"q = deque()\nq.append(root)\ns = []\nwhile q:\n node = q.popleft()\n if node:\n s.append(str(node.val))\n q.append(node.left)\n q.append(node.right)\n else:\n s.append('N')\nreturn ','.join(s)",
"q_s = deque(data.split(','))\nq = deque()\nif q_s:\n val = q_s.popleft()\n ... | <|body_start_0|>
q = deque()
q.append(root)
s = []
while q:
node = q.popleft()
if node:
s.append(str(node.val))
q.append(node.left)
q.append(node.right)
else:
s.append('N')
return ... | 232ms | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
"""232ms"""
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_ske... | stack_v2_sparse_classes_10k_train_006685 | 3,990 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
232ms
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: TreeNode | Implement the Python class `Codec` described below.
Class description:
232ms
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: TreeNode
<|skeleton... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Codec:
"""232ms"""
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_ske... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
"""232ms"""
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
q = deque()
q.append(root)
s = []
while q:
node = q.popleft()
if node:
s.append(str(node.val))
... | the_stack_v2_python_sparse | SerializeAndDeserializeBinaryTree_HARD_297.py | 953250587/leetcode-python | train | 2 |
42c44b3ac8c795e1866562098f9bbd7b1c9d70d6 | [
"self.cache = cache\nself.layers = layers\nself.metadata = metadata",
"stype = config.get(section, 'type')\nfor opt in config.options(section):\n if opt not in ['type', 'module']:\n objargs[opt] = config.get(section, opt)\nobject_module = None\nif config.has_option(section, 'module'):\n object_module... | <|body_start_0|>
self.cache = cache
self.layers = layers
self.metadata = metadata
<|end_body_0|>
<|body_start_1|>
stype = config.get(section, 'type')
for opt in config.options(section):
if opt not in ['type', 'module']:
objargs[opt] = config.get(secti... | Our Service Object | Service | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Service:
"""Our Service Object"""
def __init__(self, cache, layers, metadata=dict()):
"""Constructor"""
<|body_0|>
def _loadFromSection(cls, config, section, module, **objargs):
"""Unsure"""
<|body_1|>
def _load(cls, *files):
"""unsure"""
... | stack_v2_sparse_classes_10k_train_006686 | 9,270 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, cache, layers, metadata=dict())"
},
{
"docstring": "Unsure",
"name": "_loadFromSection",
"signature": "def _loadFromSection(cls, config, section, module, **objargs)"
},
{
"docstring": "unsure",
... | 6 | null | Implement the Python class `Service` described below.
Class description:
Our Service Object
Method signatures and docstrings:
- def __init__(self, cache, layers, metadata=dict()): Constructor
- def _loadFromSection(cls, config, section, module, **objargs): Unsure
- def _load(cls, *files): unsure
- def generate_crossd... | Implement the Python class `Service` described below.
Class description:
Our Service Object
Method signatures and docstrings:
- def __init__(self, cache, layers, metadata=dict()): Constructor
- def _loadFromSection(cls, config, section, module, **objargs): Unsure
- def _load(cls, *files): unsure
- def generate_crossd... | 275b77a65f3b12e26e6cbdb230786b9c7d2b9c9a | <|skeleton|>
class Service:
"""Our Service Object"""
def __init__(self, cache, layers, metadata=dict()):
"""Constructor"""
<|body_0|>
def _loadFromSection(cls, config, section, module, **objargs):
"""Unsure"""
<|body_1|>
def _load(cls, *files):
"""unsure"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Service:
"""Our Service Object"""
def __init__(self, cache, layers, metadata=dict()):
"""Constructor"""
self.cache = cache
self.layers = layers
self.metadata = metadata
def _loadFromSection(cls, config, section, module, **objargs):
"""Unsure"""
stype =... | the_stack_v2_python_sparse | include/python/TileCache/Service.py | jamayfieldjr/iem | train | 1 |
052724f8edd87c4990e534d14e91e68a42d0b3c6 | [
"self.chunk_list = chunk_list\nself.chunk_tensor_index = chunk_tensor_index\nself.cached_src_chunk_id = None\nself.cached_target_chunk_id = None\nself.gpu_fp32_buff = torch.zeros(chunk_size, dtype=torch.float, device=torch.device(f'cuda:{torch.cuda.current_device()}'))",
"assert src_param.ps_attr.param_type == Pa... | <|body_start_0|>
self.chunk_list = chunk_list
self.chunk_tensor_index = chunk_tensor_index
self.cached_src_chunk_id = None
self.cached_target_chunk_id = None
self.gpu_fp32_buff = torch.zeros(chunk_size, dtype=torch.float, device=torch.device(f'cuda:{torch.cuda.current_device()}')... | A buffer for copy the param. At the end of the CPU Adam, we need to copy the updated fp32 params back to the fp16 params for the next iteration of training. And because the params are organized in chunks, we can optimize the copy and cast by doing it at the granularity of chunk. This class is for doing the above copy a... | FP16ChunkWriteBuffer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FP16ChunkWriteBuffer:
"""A buffer for copy the param. At the end of the CPU Adam, we need to copy the updated fp32 params back to the fp16 params for the next iteration of training. And because the params are organized in chunks, we can optimize the copy and cast by doing it at the granularity of... | stack_v2_sparse_classes_10k_train_006687 | 9,910 | permissive | [
{
"docstring": "Args: chunk_list: :class:`ChunkList`. chunk_tensor_index: :class:`ChunkTensorIndex`. chunk_size: `int`.",
"name": "__init__",
"signature": "def __init__(self, chunk_list: ChunkList, chunk_tensor_index: ChunkTensorIndex, chunk_size: int)"
},
{
"docstring": "Write the value of `tar... | 3 | stack_v2_sparse_classes_30k_train_006185 | Implement the Python class `FP16ChunkWriteBuffer` described below.
Class description:
A buffer for copy the param. At the end of the CPU Adam, we need to copy the updated fp32 params back to the fp16 params for the next iteration of training. And because the params are organized in chunks, we can optimize the copy and... | Implement the Python class `FP16ChunkWriteBuffer` described below.
Class description:
A buffer for copy the param. At the end of the CPU Adam, we need to copy the updated fp32 params back to the fp16 params for the next iteration of training. And because the params are organized in chunks, we can optimize the copy and... | 884af4631a5bc51c9812a108cf5c3b5d5516ddfb | <|skeleton|>
class FP16ChunkWriteBuffer:
"""A buffer for copy the param. At the end of the CPU Adam, we need to copy the updated fp32 params back to the fp16 params for the next iteration of training. And because the params are organized in chunks, we can optimize the copy and cast by doing it at the granularity of... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FP16ChunkWriteBuffer:
"""A buffer for copy the param. At the end of the CPU Adam, we need to copy the updated fp32 params back to the fp16 params for the next iteration of training. And because the params are organized in chunks, we can optimize the copy and cast by doing it at the granularity of chunk. This ... | the_stack_v2_python_sparse | patrickstar/ops/chunk_io_buff.py | runzhech/PatrickStar | train | 0 |
0d89b6ad268c77f86a2d09380b09db92df2e67b7 | [
"super().__init__()\nif pre_nonlinear not in ('sigmoid', 'prelu', 'relu', 'tanh', 'linear'):\n raise ValueError('Not supporting pre_nonlinear={}'.format(pre_nonlinear))\nif nonlinear not in ('sigmoid', 'relu', 'tanh', 'linear'):\n raise ValueError('Not supporting nonlinear={}'.format(nonlinear))\nself.tcn = T... | <|body_start_0|>
super().__init__()
if pre_nonlinear not in ('sigmoid', 'prelu', 'relu', 'tanh', 'linear'):
raise ValueError('Not supporting pre_nonlinear={}'.format(pre_nonlinear))
if nonlinear not in ('sigmoid', 'relu', 'tanh', 'linear'):
raise ValueError('Not supportin... | TDSpeakerBeamExtractor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TDSpeakerBeamExtractor:
def __init__(self, input_dim: int, layer: int=8, stack: int=3, bottleneck_dim: int=128, hidden_dim: int=512, skip_dim: int=128, kernel: int=3, causal: bool=False, norm_type: str='gLN', pre_nonlinear: str='prelu', nonlinear: str='relu', i_adapt_layer: int=7, adapt_layer_ty... | stack_v2_sparse_classes_10k_train_006688 | 6,590 | permissive | [
{
"docstring": "Time-Domain SpeakerBeam Extractor. Args: input_dim: input feature dimension layer: int, number of layers in each stack stack: int, number of stacks bottleneck_dim: bottleneck dimension hidden_dim: number of convolution channel skip_dim: int, number of skip connection channels kernel: int, kernel... | 2 | null | Implement the Python class `TDSpeakerBeamExtractor` described below.
Class description:
Implement the TDSpeakerBeamExtractor class.
Method signatures and docstrings:
- def __init__(self, input_dim: int, layer: int=8, stack: int=3, bottleneck_dim: int=128, hidden_dim: int=512, skip_dim: int=128, kernel: int=3, causal:... | Implement the Python class `TDSpeakerBeamExtractor` described below.
Class description:
Implement the TDSpeakerBeamExtractor class.
Method signatures and docstrings:
- def __init__(self, input_dim: int, layer: int=8, stack: int=3, bottleneck_dim: int=128, hidden_dim: int=512, skip_dim: int=128, kernel: int=3, causal:... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class TDSpeakerBeamExtractor:
def __init__(self, input_dim: int, layer: int=8, stack: int=3, bottleneck_dim: int=128, hidden_dim: int=512, skip_dim: int=128, kernel: int=3, causal: bool=False, norm_type: str='gLN', pre_nonlinear: str='prelu', nonlinear: str='relu', i_adapt_layer: int=7, adapt_layer_ty... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TDSpeakerBeamExtractor:
def __init__(self, input_dim: int, layer: int=8, stack: int=3, bottleneck_dim: int=128, hidden_dim: int=512, skip_dim: int=128, kernel: int=3, causal: bool=False, norm_type: str='gLN', pre_nonlinear: str='prelu', nonlinear: str='relu', i_adapt_layer: int=7, adapt_layer_type: str='mul',... | the_stack_v2_python_sparse | espnet2/enh/extractor/td_speakerbeam_extractor.py | espnet/espnet | train | 7,242 | |
102943406712c71ca36bad8495ec6cfc2903fc2c | [
"if np.any(z < 0.0):\n print >> sys.stderr('z has negative values and thus is not a density!')\n return\nif not 0.0 < m < 1.0:\n print >> sys.stderr('m has to be in (0; 1)!')\n return\nmaxVal = np.max(z)\nz *= m / maxVal\nprint('Preparing interpolating function')\nself._interp = RectBivariateSpline(x, y... | <|body_start_0|>
if np.any(z < 0.0):
print >> sys.stderr('z has negative values and thus is not a density!')
return
if not 0.0 < m < 1.0:
print >> sys.stderr('m has to be in (0; 1)!')
return
maxVal = np.max(z)
z *= m / maxVal
print(... | Sampler object. To be instantiated with an (x,y) grid and a PDF function z = z(x,y). | sampler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sampler:
"""Sampler object. To be instantiated with an (x,y) grid and a PDF function z = z(x,y)."""
def __init__(self, x, y, z, m=0.95, cond=None):
"""Create a sampler object from data. Parameters ---------- x,y : arrays 1d arrays for x and y data. z : array PDF of shape [len(x), len... | stack_v2_sparse_classes_10k_train_006689 | 5,426 | permissive | [
{
"docstring": "Create a sampler object from data. Parameters ---------- x,y : arrays 1d arrays for x and y data. z : array PDF of shape [len(x), len(y)]. Does not need to be normalized correctly. m : float, optional Number in [0; 1). Used as new maximum value in renormalization of the PDF. Random samples (x,y)... | 2 | stack_v2_sparse_classes_30k_train_005305 | Implement the Python class `sampler` described below.
Class description:
Sampler object. To be instantiated with an (x,y) grid and a PDF function z = z(x,y).
Method signatures and docstrings:
- def __init__(self, x, y, z, m=0.95, cond=None): Create a sampler object from data. Parameters ---------- x,y : arrays 1d arr... | Implement the Python class `sampler` described below.
Class description:
Sampler object. To be instantiated with an (x,y) grid and a PDF function z = z(x,y).
Method signatures and docstrings:
- def __init__(self, x, y, z, m=0.95, cond=None): Create a sampler object from data. Parameters ---------- x,y : arrays 1d arr... | bd784798b846f76e00a3bbb0fb1acf6a1317be12 | <|skeleton|>
class sampler:
"""Sampler object. To be instantiated with an (x,y) grid and a PDF function z = z(x,y)."""
def __init__(self, x, y, z, m=0.95, cond=None):
"""Create a sampler object from data. Parameters ---------- x,y : arrays 1d arrays for x and y data. z : array PDF of shape [len(x), len... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class sampler:
"""Sampler object. To be instantiated with an (x,y) grid and a PDF function z = z(x,y)."""
def __init__(self, x, y, z, m=0.95, cond=None):
"""Create a sampler object from data. Parameters ---------- x,y : arrays 1d arrays for x and y data. z : array PDF of shape [len(x), len(y)]. Does no... | the_stack_v2_python_sparse | learningml/GoF/data/accept_reject/sampler_example.py | weissercn/learningml | train | 1 |
7971ae69eec593041f3bb59c11e8855bb4f0e8ff | [
"for row in matrix:\n if not is_constant_row(row):\n return False\nreturn True",
"rows = []\nfor _ in range(self.num_rows):\n sampled_atom = random_state.choice(self.num_atoms)\n rows.append([sampled_atom] * self.num_cols)\nreturn np.array(rows)"
] | <|body_start_0|>
for row in matrix:
if not is_constant_row(row):
return False
return True
<|end_body_0|>
<|body_start_1|>
rows = []
for _ in range(self.num_rows):
sampled_atom = random_state.choice(self.num_atoms)
rows.append([sampled_... | Relation where rows in the matrix are constant. | ConstantRelation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConstantRelation:
"""Relation where rows in the matrix are constant."""
def is_consistent(matrix):
"""Checks whether the matrix satisfies the relation."""
<|body_0|>
def sample(self, random_state):
"""Samples a matrix consistent with the relation."""
<|bo... | stack_v2_sparse_classes_10k_train_006690 | 10,947 | permissive | [
{
"docstring": "Checks whether the matrix satisfies the relation.",
"name": "is_consistent",
"signature": "def is_consistent(matrix)"
},
{
"docstring": "Samples a matrix consistent with the relation.",
"name": "sample",
"signature": "def sample(self, random_state)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000185 | Implement the Python class `ConstantRelation` described below.
Class description:
Relation where rows in the matrix are constant.
Method signatures and docstrings:
- def is_consistent(matrix): Checks whether the matrix satisfies the relation.
- def sample(self, random_state): Samples a matrix consistent with the rela... | Implement the Python class `ConstantRelation` described below.
Class description:
Relation where rows in the matrix are constant.
Method signatures and docstrings:
- def is_consistent(matrix): Checks whether the matrix satisfies the relation.
- def sample(self, random_state): Samples a matrix consistent with the rela... | 73d4b995e88efdd5ffbe98a72e48a620c58f4dc7 | <|skeleton|>
class ConstantRelation:
"""Relation where rows in the matrix are constant."""
def is_consistent(matrix):
"""Checks whether the matrix satisfies the relation."""
<|body_0|>
def sample(self, random_state):
"""Samples a matrix consistent with the relation."""
<|bo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConstantRelation:
"""Relation where rows in the matrix are constant."""
def is_consistent(matrix):
"""Checks whether the matrix satisfies the relation."""
for row in matrix:
if not is_constant_row(row):
return False
return True
def sample(self, ran... | the_stack_v2_python_sparse | disentanglement_lib/evaluation/abstract_reasoning/pgm_utils.py | travers-rhodes/disentanglement_lib | train | 0 |
3c4b114a9c3eed4783d30677fe874c8ddcefa2dc | [
"super().__init__()\nself.fc1 = nn.Linear(input_shape[0], hidden_size)\nself.actor_head = nn.Linear(hidden_size, n_actions)\nself.critic_head = nn.Linear(hidden_size, 1)",
"x = F.relu(self.fc1(x.float()))\na = F.log_softmax(self.actor_head(x), dim=-1)\nc = self.critic_head(x)\nreturn (a, c)"
] | <|body_start_0|>
super().__init__()
self.fc1 = nn.Linear(input_shape[0], hidden_size)
self.actor_head = nn.Linear(hidden_size, n_actions)
self.critic_head = nn.Linear(hidden_size, 1)
<|end_body_0|>
<|body_start_1|>
x = F.relu(self.fc1(x.float()))
a = F.log_softmax(self.a... | MLP network with heads for actor and critic. | ActorCriticMLP | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActorCriticMLP:
"""MLP network with heads for actor and critic."""
def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128) -> None:
"""Args: input_shape: observation shape of the environment n_actions: number of discrete actions available in the environment ... | stack_v2_sparse_classes_10k_train_006691 | 15,112 | permissive | [
{
"docstring": "Args: input_shape: observation shape of the environment n_actions: number of discrete actions available in the environment hidden_size: size of hidden layers",
"name": "__init__",
"signature": "def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128) -> None"
}... | 2 | stack_v2_sparse_classes_30k_val_000162 | Implement the Python class `ActorCriticMLP` described below.
Class description:
MLP network with heads for actor and critic.
Method signatures and docstrings:
- def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128) -> None: Args: input_shape: observation shape of the environment n_actions:... | Implement the Python class `ActorCriticMLP` described below.
Class description:
MLP network with heads for actor and critic.
Method signatures and docstrings:
- def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128) -> None: Args: input_shape: observation shape of the environment n_actions:... | bdf311369b236c1e3d0336c7ed4ba249854f8606 | <|skeleton|>
class ActorCriticMLP:
"""MLP network with heads for actor and critic."""
def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128) -> None:
"""Args: input_shape: observation shape of the environment n_actions: number of discrete actions available in the environment ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ActorCriticMLP:
"""MLP network with heads for actor and critic."""
def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128) -> None:
"""Args: input_shape: observation shape of the environment n_actions: number of discrete actions available in the environment hidden_size: ... | the_stack_v2_python_sparse | src/pl_bolts/models/rl/common/networks.py | Lightning-Universe/lightning-bolts | train | 76 |
befc15d5b868844c8667330a7cc64f7966c65520 | [
"self.program = []\nfor line in self.lines:\n stripped_line = line.strip()\n if stripped_line.startswith('#ip '):\n self.ip_reg = int(stripped_line[len('#ip '):])\n elif stripped_line:\n tokens = stripped_line.split(' ')\n instruction = [tokens[0]] + [int(token) for token in tokens[1:]... | <|body_start_0|>
self.program = []
for line in self.lines:
stripped_line = line.strip()
if stripped_line.startswith('#ip '):
self.ip_reg = int(stripped_line[len('#ip '):])
elif stripped_line:
tokens = stripped_line.split(' ')
... | Day 16 challenges | Challenge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Challenge:
"""Day 16 challenges"""
def parse_input(self):
"""Parse input lines"""
<|body_0|>
def execute_program(self, emulator, callback=None, ip=0):
"""Execute the program on the given emulator emulator: The emulator to run the program on callback: Function to ... | stack_v2_sparse_classes_10k_train_006692 | 4,881 | permissive | [
{
"docstring": "Parse input lines",
"name": "parse_input",
"signature": "def parse_input(self)"
},
{
"docstring": "Execute the program on the given emulator emulator: The emulator to run the program on callback: Function to call after each instruction with the current IP ip: initial instruction ... | 4 | stack_v2_sparse_classes_30k_train_005191 | Implement the Python class `Challenge` described below.
Class description:
Day 16 challenges
Method signatures and docstrings:
- def parse_input(self): Parse input lines
- def execute_program(self, emulator, callback=None, ip=0): Execute the program on the given emulator emulator: The emulator to run the program on c... | Implement the Python class `Challenge` described below.
Class description:
Day 16 challenges
Method signatures and docstrings:
- def parse_input(self): Parse input lines
- def execute_program(self, emulator, callback=None, ip=0): Execute the program on the given emulator emulator: The emulator to run the program on c... | 6671ef8c16a837f697bb3fb91004d1bd892814ba | <|skeleton|>
class Challenge:
"""Day 16 challenges"""
def parse_input(self):
"""Parse input lines"""
<|body_0|>
def execute_program(self, emulator, callback=None, ip=0):
"""Execute the program on the given emulator emulator: The emulator to run the program on callback: Function to ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Challenge:
"""Day 16 challenges"""
def parse_input(self):
"""Parse input lines"""
self.program = []
for line in self.lines:
stripped_line = line.strip()
if stripped_line.startswith('#ip '):
self.ip_reg = int(stripped_line[len('#ip '):])
... | the_stack_v2_python_sparse | 2018/day19/challenge.py | ericgreveson/adventofcode | train | 0 |
fd8fc14510a0d3184fb16bc9cb5dba0dac443f25 | [
"def helper(cur):\n if not cur:\n return\n ans.append(cur.val)\n helper(cur.left)\n helper(cur.right)\n return ans\nans = []\nhelper(root)\nreturn ','.join([str(elem) for elem in ans])",
"if not data:\n return None\ndata = data.split(',')\nself.data = [int(elem) for elem in data]\nself.id... | <|body_start_0|>
def helper(cur):
if not cur:
return
ans.append(cur.val)
helper(cur.left)
helper(cur.right)
return ans
ans = []
helper(root)
return ','.join([str(elem) for elem in ans])
<|end_body_0|>
<|body_sta... | 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 helper(cur... | stack_v2_sparse_classes_10k_train_006693 | 5,056 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 1abc28919abb55b93d3879860ac9c1297d493d09 | <|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 helper(cur):
if not cur:
return
ans.append(cur.val)
helper(cur.left)
helper(cur.right)
return ans
ans = []
... | the_stack_v2_python_sparse | lc/449.SerializeAndDeserializeBST.py | akimi-yano/algorithm-practice | train | 0 | |
3586efe294928f4658599dc5081e86498d8d561b | [
"self.fat_type = get_filesystem_type(stream)\nself.fatfs = create_fat(stream)\nself.stream = stream",
"metadata = BadClusterMetadata()\ncluster_count = 0\nwritten_length = 0\nLOGGER.info('%d Bytes in buffer to write', len(instream.peek()))\nwhile instream.peek():\n try:\n next_cluster = self.fatfs.get_f... | <|body_start_0|>
self.fat_type = get_filesystem_type(stream)
self.fatfs = create_fat(stream)
self.stream = stream
<|end_body_0|>
<|body_start_1|>
metadata = BadClusterMetadata()
cluster_count = 0
written_length = 0
LOGGER.info('%d Bytes in buffer to write', len(i... | Provides methods to hide and restore data from bad clusters | BadCluster | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BadCluster:
"""Provides methods to hide and restore data from bad clusters"""
def __init__(self, stream: typ.BinaryIO):
""":param stream: filedescriptor of a FAT filesystem"""
<|body_0|>
def write(self, instream: typ.BinaryIO) -> BadClusterMetadata:
"""writes fro... | stack_v2_sparse_classes_10k_train_006694 | 7,262 | permissive | [
{
"docstring": ":param stream: filedescriptor of a FAT filesystem",
"name": "__init__",
"signature": "def __init__(self, stream: typ.BinaryIO)"
},
{
"docstring": "writes from instream bad clusters :param instream: stream to read from :return: BadCluster",
"name": "write",
"signature": "d... | 5 | stack_v2_sparse_classes_30k_val_000214 | Implement the Python class `BadCluster` described below.
Class description:
Provides methods to hide and restore data from bad clusters
Method signatures and docstrings:
- def __init__(self, stream: typ.BinaryIO): :param stream: filedescriptor of a FAT filesystem
- def write(self, instream: typ.BinaryIO) -> BadCluste... | Implement the Python class `BadCluster` described below.
Class description:
Provides methods to hide and restore data from bad clusters
Method signatures and docstrings:
- def __init__(self, stream: typ.BinaryIO): :param stream: filedescriptor of a FAT filesystem
- def write(self, instream: typ.BinaryIO) -> BadCluste... | b602e90ddecb8e469a28e092da3ca7fec514e3dc | <|skeleton|>
class BadCluster:
"""Provides methods to hide and restore data from bad clusters"""
def __init__(self, stream: typ.BinaryIO):
""":param stream: filedescriptor of a FAT filesystem"""
<|body_0|>
def write(self, instream: typ.BinaryIO) -> BadClusterMetadata:
"""writes fro... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BadCluster:
"""Provides methods to hide and restore data from bad clusters"""
def __init__(self, stream: typ.BinaryIO):
""":param stream: filedescriptor of a FAT filesystem"""
self.fat_type = get_filesystem_type(stream)
self.fatfs = create_fat(stream)
self.stream = stream
... | the_stack_v2_python_sparse | src/fat/bad_cluster.py | VanirLab/weever | train | 3 |
e56f3d1f568c97b2347e301039e2af15d86a6ce8 | [
"rbac_utils = get_rbac_backend().get_utils_class()\nrbac_utils.assert_user_is_admin(user_db=requester_user)\nresult = get_resource_permission_types_with_descriptions()\nreturn result",
"rbac_utils = get_rbac_backend().get_utils_class()\nrbac_utils.assert_user_is_admin(user_db=requester_user)\nall_permission_types... | <|body_start_0|>
rbac_utils = get_rbac_backend().get_utils_class()
rbac_utils.assert_user_is_admin(user_db=requester_user)
result = get_resource_permission_types_with_descriptions()
return result
<|end_body_0|>
<|body_start_1|>
rbac_utils = get_rbac_backend().get_utils_class()
... | Meta controller for listing all the available permission types. | PermissionTypesController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PermissionTypesController:
"""Meta controller for listing all the available permission types."""
def get_all(self, requester_user):
"""List all the available permission types. Handles requests: GET /rbac/permission_types"""
<|body_0|>
def get_one(self, resource_type, req... | stack_v2_sparse_classes_10k_train_006695 | 4,655 | permissive | [
{
"docstring": "List all the available permission types. Handles requests: GET /rbac/permission_types",
"name": "get_all",
"signature": "def get_all(self, requester_user)"
},
{
"docstring": "List all the available permission types for a particular resource type. Handles requests: GET /rbac/permi... | 2 | null | Implement the Python class `PermissionTypesController` described below.
Class description:
Meta controller for listing all the available permission types.
Method signatures and docstrings:
- def get_all(self, requester_user): List all the available permission types. Handles requests: GET /rbac/permission_types
- def ... | Implement the Python class `PermissionTypesController` described below.
Class description:
Meta controller for listing all the available permission types.
Method signatures and docstrings:
- def get_all(self, requester_user): List all the available permission types. Handles requests: GET /rbac/permission_types
- def ... | c3fc181981b141da95dcf6939d09c362556ca048 | <|skeleton|>
class PermissionTypesController:
"""Meta controller for listing all the available permission types."""
def get_all(self, requester_user):
"""List all the available permission types. Handles requests: GET /rbac/permission_types"""
<|body_0|>
def get_one(self, resource_type, req... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PermissionTypesController:
"""Meta controller for listing all the available permission types."""
def get_all(self, requester_user):
"""List all the available permission types. Handles requests: GET /rbac/permission_types"""
rbac_utils = get_rbac_backend().get_utils_class()
rbac_ut... | the_stack_v2_python_sparse | st2api/st2api/controllers/v1/rbac.py | Plexxi/st2 | train | 3 |
1457765821fb3bb34a5656efa0bdc4d9225358d0 | [
"announcement = self.kwargs['announcement']\nsender = announcement.created_by.full_name\nif announcement.from_group:\n sender = announcement.from_group.name\nreturn self._delay_mail(to_email=self.user.email_address, context={'first_name': self.user.first_name, 'sender': sender, 'message': announcement.message}, ... | <|body_start_0|>
announcement = self.kwargs['announcement']
sender = announcement.created_by.full_name
if announcement.from_group:
sender = announcement.from_group.name
return self._delay_mail(to_email=self.user.email_address, context={'first_name': self.user.first_name, 'sen... | Sent a notification to one recipient of an Announcement. The base class verifies the user settings. | AnnouncementNotification | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnnouncementNotification:
"""Sent a notification to one recipient of an Announcement. The base class verifies the user settings."""
def generate_mail(self):
"""Generate the email message the user should receive."""
<|body_0|>
def generate_push(self):
"""Generate ... | stack_v2_sparse_classes_10k_train_006696 | 1,567 | permissive | [
{
"docstring": "Generate the email message the user should receive.",
"name": "generate_mail",
"signature": "def generate_mail(self)"
},
{
"docstring": "Generate the push message the user should receive on his/her phone.",
"name": "generate_push",
"signature": "def generate_push(self)"
... | 2 | null | Implement the Python class `AnnouncementNotification` described below.
Class description:
Sent a notification to one recipient of an Announcement. The base class verifies the user settings.
Method signatures and docstrings:
- def generate_mail(self): Generate the email message the user should receive.
- def generate_... | Implement the Python class `AnnouncementNotification` described below.
Class description:
Sent a notification to one recipient of an Announcement. The base class verifies the user settings.
Method signatures and docstrings:
- def generate_mail(self): Generate the email message the user should receive.
- def generate_... | 2c1909fd84fe3b3e0a9d3792c4bcc51089ad5a87 | <|skeleton|>
class AnnouncementNotification:
"""Sent a notification to one recipient of an Announcement. The base class verifies the user settings."""
def generate_mail(self):
"""Generate the email message the user should receive."""
<|body_0|>
def generate_push(self):
"""Generate ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AnnouncementNotification:
"""Sent a notification to one recipient of an Announcement. The base class verifies the user settings."""
def generate_mail(self):
"""Generate the email message the user should receive."""
announcement = self.kwargs['announcement']
sender = announcement.c... | the_stack_v2_python_sparse | lego/apps/notifications/notifications.py | webkom/lego | train | 53 |
70d4d807891ff208eb54f0241a9d57abbdfa7033 | [
"self._site = site\nself._registry_client = registry_client\nif trust_store:\n self._verify = str(trust_store)\nelse:\n self._verify = True\nif not client_credentials:\n self._cred = None\nelse:\n self._cred = (str(client_credentials[0]), str(client_credentials[1]))",
"try:\n site = self._registry_... | <|body_start_0|>
self._site = site
self._registry_client = registry_client
if trust_store:
self._verify = str(trust_store)
else:
self._verify = True
if not client_credentials:
self._cred = None
else:
self._cred = (str(client... | Handles connecting to other sites' runners and stores. | SiteRestClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SiteRestClient:
"""Handles connecting to other sites' runners and stores."""
def __init__(self, site: str, registry_client: RegistryClient, trust_store: Optional[Path]=None, client_credentials: Optional[Tuple[Path, Path]]=None) -> None:
"""Create a SiteRestClient. Args: site: The sit... | stack_v2_sparse_classes_10k_train_006697 | 6,710 | permissive | [
{
"docstring": "Create a SiteRestClient. Args: site: The site at which this client acts. registry_client: A registry client to get sites from. trust_store: A file with trusted certificates/anchors. client_credentials: An HTTPS client certificate and the corresponding key, as paths to PEM files.",
"name": "_... | 6 | stack_v2_sparse_classes_30k_train_001663 | Implement the Python class `SiteRestClient` described below.
Class description:
Handles connecting to other sites' runners and stores.
Method signatures and docstrings:
- def __init__(self, site: str, registry_client: RegistryClient, trust_store: Optional[Path]=None, client_credentials: Optional[Tuple[Path, Path]]=No... | Implement the Python class `SiteRestClient` described below.
Class description:
Handles connecting to other sites' runners and stores.
Method signatures and docstrings:
- def __init__(self, site: str, registry_client: RegistryClient, trust_store: Optional[Path]=None, client_credentials: Optional[Tuple[Path, Path]]=No... | 22f9533a506e039237227ca66faea5375cce5fcb | <|skeleton|>
class SiteRestClient:
"""Handles connecting to other sites' runners and stores."""
def __init__(self, site: str, registry_client: RegistryClient, trust_store: Optional[Path]=None, client_credentials: Optional[Tuple[Path, Path]]=None) -> None:
"""Create a SiteRestClient. Args: site: The sit... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SiteRestClient:
"""Handles connecting to other sites' runners and stores."""
def __init__(self, site: str, registry_client: RegistryClient, trust_store: Optional[Path]=None, client_credentials: Optional[Tuple[Path, Path]]=None) -> None:
"""Create a SiteRestClient. Args: site: The site at which th... | the_stack_v2_python_sparse | mahiru/rest/site_client.py | SecConNet/mahiru | train | 4 |
97c2671e3516a8d0ab6b381d4ed93cd50ce64e97 | [
"if isinstance(key, int):\n return Packet(key)\nif key not in Packet._member_map_:\n return extend_enum(Packet, key, default)\nreturn Packet[key]",
"if not (isinstance(value, int) and 0 <= value <= 127):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 5 <= value <= 15:\n return ... | <|body_start_0|>
if isinstance(key, int):
return Packet(key)
if key not in Packet._member_map_:
return extend_enum(Packet, key, default)
return Packet[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 127):
raise Va... | [Packet] HIP Packet Types | Packet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Packet:
"""[Packet] HIP Packet Types"""
def get(key: 'int | str', default: 'int'=-1) -> 'Packet':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, value: 'int') -... | stack_v2_sparse_classes_10k_train_006698 | 2,440 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'Packet'"
},
{
"docstring": "Lookup function used when value is not found. Args... | 2 | stack_v2_sparse_classes_30k_train_002058 | Implement the Python class `Packet` described below.
Class description:
[Packet] HIP Packet Types
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'Packet': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:
- de... | Implement the Python class `Packet` described below.
Class description:
[Packet] HIP Packet Types
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'Packet': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:
- de... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class Packet:
"""[Packet] HIP Packet Types"""
def get(key: 'int | str', default: 'int'=-1) -> 'Packet':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, value: 'int') -... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Packet:
"""[Packet] HIP Packet Types"""
def get(key: 'int | str', default: 'int'=-1) -> 'Packet':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(key, int):
return Packet(key)
... | the_stack_v2_python_sparse | pcapkit/const/hip/packet.py | JarryShaw/PyPCAPKit | train | 204 |
6100f1a09996674b67a958a7026ada368ae699fb | [
"nn.Module.__init__(self)\nself.tau = tau\nself.y_list = y_list\nself.batch_size = batch_size\nself.device = device",
"p = torch.cat((z_i, z_j), dim=0)\nsim = nn.CosineSimilarity(dim=2)(p.unsqueeze(1), p.unsqueeze(0)) / self.tau\ny2 = torch.cat([y, y], dim=0).view(-1, 1)\nif self.y_list == 'all':\n mask = torc... | <|body_start_0|>
nn.Module.__init__(self)
self.tau = tau
self.y_list = y_list
self.batch_size = batch_size
self.device = device
<|end_body_0|>
<|body_start_1|>
p = torch.cat((z_i, z_j), dim=0)
sim = nn.CosineSimilarity(dim=2)(p.unsqueeze(1), p.unsqueeze(0)) / sel... | Define the Supervised Contrastive Loss as a Pytorch Module. | SupervisedContrastiveLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupervisedContrastiveLoss:
"""Define the Supervised Contrastive Loss as a Pytorch Module."""
def __init__(self, tau, batch_size, y_list='all', device='cuda'):
"""Initialize a Supervised Contrastive Loss Module. ---------- INPUT |---- tau (float) the temperature hyperparameter. |---- ... | stack_v2_sparse_classes_10k_train_006699 | 18,386 | permissive | [
{
"docstring": "Initialize a Supervised Contrastive Loss Module. ---------- INPUT |---- tau (float) the temperature hyperparameter. |---- y_list (list of int) the list of class to conisder for positive. | Default is using all classes. |---- batch_size (int) the batch_size used. |---- device (str) the device to ... | 2 | stack_v2_sparse_classes_30k_val_000215 | Implement the Python class `SupervisedContrastiveLoss` described below.
Class description:
Define the Supervised Contrastive Loss as a Pytorch Module.
Method signatures and docstrings:
- def __init__(self, tau, batch_size, y_list='all', device='cuda'): Initialize a Supervised Contrastive Loss Module. ---------- INPUT... | Implement the Python class `SupervisedContrastiveLoss` described below.
Class description:
Define the Supervised Contrastive Loss as a Pytorch Module.
Method signatures and docstrings:
- def __init__(self, tau, batch_size, y_list='all', device='cuda'): Initialize a Supervised Contrastive Loss Module. ---------- INPUT... | 850b6195d6290a50eee865b4d5a66f5db5260e8f | <|skeleton|>
class SupervisedContrastiveLoss:
"""Define the Supervised Contrastive Loss as a Pytorch Module."""
def __init__(self, tau, batch_size, y_list='all', device='cuda'):
"""Initialize a Supervised Contrastive Loss Module. ---------- INPUT |---- tau (float) the temperature hyperparameter. |---- ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SupervisedContrastiveLoss:
"""Define the Supervised Contrastive Loss as a Pytorch Module."""
def __init__(self, tau, batch_size, y_list='all', device='cuda'):
"""Initialize a Supervised Contrastive Loss Module. ---------- INPUT |---- tau (float) the temperature hyperparameter. |---- y_list (list ... | the_stack_v2_python_sparse | Code/src/models/optim/CustomLosses.py | antoine-spahr/X-ray-Anomaly-Detection | train | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.