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
e8917b7bcabb16ec9c35d4f475362ded7101711d
[ "results = []\nnums.sort()\ni = 0\nwhile i < len(nums):\n j = i + 1\n k = len(nums) - 1\n while j < k:\n v = nums[i] + nums[j] + nums[k] - target\n if v == 0:\n results.append([nums[i], nums[j], nums[k]])\n while j < len(nums) - 2 and nums[j] == nums[j + 1]:\n ...
<|body_start_0|> results = [] nums.sort() i = 0 while i < len(nums): j = i + 1 k = len(nums) - 1 while j < k: v = nums[i] + nums[j] + nums[k] - target if v == 0: results.append([nums[i], nums[j], nums...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def threeSum(self, nums, target): """:type nums: List[int] :rtype: List[List[int]]""" <|body_0|> def fourSum(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_10k_train_005300
1,456
no_license
[ { "docstring": ":type nums: List[int] :rtype: List[List[int]]", "name": "threeSum", "signature": "def threeSum(self, nums, target)" }, { "docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]", "name": "fourSum", "signature": "def fourSum(self, nums, target)" } ]
2
stack_v2_sparse_classes_30k_train_003665
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def threeSum(self, nums, target): :type nums: List[int] :rtype: List[List[int]] - def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def threeSum(self, nums, target): :type nums: List[int] :rtype: List[List[int]] - def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]...
d8ed762d1005975f0de4f07760c9671195621c88
<|skeleton|> class Solution: def threeSum(self, nums, target): """:type nums: List[int] :rtype: List[List[int]]""" <|body_0|> def fourSum(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def threeSum(self, nums, target): """:type nums: List[int] :rtype: List[List[int]]""" results = [] nums.sort() i = 0 while i < len(nums): j = i + 1 k = len(nums) - 1 while j < k: v = nums[i] + nums[j] + nums[...
the_stack_v2_python_sparse
4sum/solution.py
uxlsl/leetcode_practice
train
0
d0c44c99119ac2e02260ff2f0b0d23a3c6d45be4
[ "super().__init__()\nself.weights = torch.nn.Parameter(torch.zeros(feature_number, feature_number))\ntorch.nn.init.xavier_uniform_(self.weights)", "attention = torch.nn.functional.normalize(self.weights, dim=-1)\nleft_representations = torch.nn.functional.normalize(left_representations, dim=-1)\nright_representat...
<|body_start_0|> super().__init__() self.weights = torch.nn.Parameter(torch.zeros(feature_number, feature_number)) torch.nn.init.xavier_uniform_(self.weights) <|end_body_0|> <|body_start_1|> attention = torch.nn.functional.normalize(self.weights, dim=-1) left_representations = t...
Attention layer.
EmbeddingLayer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmbeddingLayer: """Attention layer.""" def __init__(self, feature_number: int): """Initialize the relational embedding layer. :param feature_number: Number of features.""" <|body_0|> def forward(self, left_representations: torch.FloatTensor, right_representations: torch....
stack_v2_sparse_classes_10k_train_005301
25,672
no_license
[ { "docstring": "Initialize the relational embedding layer. :param feature_number: Number of features.", "name": "__init__", "signature": "def __init__(self, feature_number: int)" }, { "docstring": "Make a forward pass with the drug representations. :param left_representations: Left side drug rep...
2
stack_v2_sparse_classes_30k_train_003706
Implement the Python class `EmbeddingLayer` described below. Class description: Attention layer. Method signatures and docstrings: - def __init__(self, feature_number: int): Initialize the relational embedding layer. :param feature_number: Number of features. - def forward(self, left_representations: torch.FloatTenso...
Implement the Python class `EmbeddingLayer` described below. Class description: Attention layer. Method signatures and docstrings: - def __init__(self, feature_number: int): Initialize the relational embedding layer. :param feature_number: Number of features. - def forward(self, left_representations: torch.FloatTenso...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class EmbeddingLayer: """Attention layer.""" def __init__(self, feature_number: int): """Initialize the relational embedding layer. :param feature_number: Number of features.""" <|body_0|> def forward(self, left_representations: torch.FloatTensor, right_representations: torch....
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class EmbeddingLayer: """Attention layer.""" def __init__(self, feature_number: int): """Initialize the relational embedding layer. :param feature_number: Number of features.""" super().__init__() self.weights = torch.nn.Parameter(torch.zeros(feature_number, feature_number)) tor...
the_stack_v2_python_sparse
generated/test_AstraZeneca_chemicalx.py
jansel/pytorch-jit-paritybench
train
35
337dc67ed4620a488f66b001d77dd9753dde6486
[ "try:\n activity = request.json\n (services.log_service().upsert_activity(activity), 201)\nexcept Exception as e:\n nsp.abort(500, 'An internal error has occurred: {}'.format(e))", "try:\n activity = request.json\n (services.log_service().upsert_activity(activity), 204)\nexcept Exception as e:\n ...
<|body_start_0|> try: activity = request.json (services.log_service().upsert_activity(activity), 201) except Exception as e: nsp.abort(500, 'An internal error has occurred: {}'.format(e)) <|end_body_0|> <|body_start_1|> try: activity = request.jso...
Activity
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Activity: def post(self): """Insert a new activity log""" <|body_0|> def put(self): """Update an activity object by it's id.""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: activity = request.json (services.log_service()...
stack_v2_sparse_classes_10k_train_005302
4,427
no_license
[ { "docstring": "Insert a new activity log", "name": "post", "signature": "def post(self)" }, { "docstring": "Update an activity object by it's id.", "name": "put", "signature": "def put(self)" } ]
2
stack_v2_sparse_classes_30k_train_002949
Implement the Python class `Activity` described below. Class description: Implement the Activity class. Method signatures and docstrings: - def post(self): Insert a new activity log - def put(self): Update an activity object by it's id.
Implement the Python class `Activity` described below. Class description: Implement the Activity class. Method signatures and docstrings: - def post(self): Insert a new activity log - def put(self): Update an activity object by it's id. <|skeleton|> class Activity: def post(self): """Insert a new activi...
df826cf7098aee59e0a1ced6f465c2e8bb3df9a5
<|skeleton|> class Activity: def post(self): """Insert a new activity log""" <|body_0|> def put(self): """Update an activity object by it's id.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Activity: def post(self): """Insert a new activity log""" try: activity = request.json (services.log_service().upsert_activity(activity), 201) except Exception as e: nsp.abort(500, 'An internal error has occurred: {}'.format(e)) def put(self): ...
the_stack_v2_python_sparse
patient_portal/patient_portal/api/logs.py
bkh148/patient-cloud
train
0
e2f8e186dd4e84c355fece22dfbccc7e0d81834a
[ "self.is_categorical = is_categorical\nself.is_binary = len(unique_values) == 2\nself.unique_values = unique_values\nif not is_categorical and (not self.is_binary):\n self.unique_values = self.__get_stdev_band(unique_values)", "mean = stats.mean(unique_values)\nstdev = stats.stdev(unique_values)\nreturn [mean ...
<|body_start_0|> self.is_categorical = is_categorical self.is_binary = len(unique_values) == 2 self.unique_values = unique_values if not is_categorical and (not self.is_binary): self.unique_values = self.__get_stdev_band(unique_values) <|end_body_0|> <|body_start_1|> ...
Encoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Encoder: def __init__(self, unique_values, is_categorical): """Constructor of an Encoder using one-hot-encoding""" <|body_0|> def __get_stdev_band(self, unique_values): """Get the lower bound and upper bound for the standard devaitation band for continuous value.""" ...
stack_v2_sparse_classes_10k_train_005303
1,683
no_license
[ { "docstring": "Constructor of an Encoder using one-hot-encoding", "name": "__init__", "signature": "def __init__(self, unique_values, is_categorical)" }, { "docstring": "Get the lower bound and upper bound for the standard devaitation band for continuous value.", "name": "__get_stdev_band",...
3
stack_v2_sparse_classes_30k_train_002081
Implement the Python class `Encoder` described below. Class description: Implement the Encoder class. Method signatures and docstrings: - def __init__(self, unique_values, is_categorical): Constructor of an Encoder using one-hot-encoding - def __get_stdev_band(self, unique_values): Get the lower bound and upper bound...
Implement the Python class `Encoder` described below. Class description: Implement the Encoder class. Method signatures and docstrings: - def __init__(self, unique_values, is_categorical): Constructor of an Encoder using one-hot-encoding - def __get_stdev_band(self, unique_values): Get the lower bound and upper bound...
9ae339f81fc7134ba9058fe975dec9ac7e3aaba4
<|skeleton|> class Encoder: def __init__(self, unique_values, is_categorical): """Constructor of an Encoder using one-hot-encoding""" <|body_0|> def __get_stdev_band(self, unique_values): """Get the lower bound and upper bound for the standard devaitation band for continuous value.""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Encoder: def __init__(self, unique_values, is_categorical): """Constructor of an Encoder using one-hot-encoding""" self.is_categorical = is_categorical self.is_binary = len(unique_values) == 2 self.unique_values = unique_values if not is_categorical and (not self.is_bin...
the_stack_v2_python_sparse
Project5/encoding.py
vincy0320/School_Intro_to_ML
train
0
ab52207902ac62cb372c9c550e8a29caa4abae0c
[ "independent_pc = param_domain.ParamChange('a', 'Copier', {'value': 'firstValue', 'parse_with_jinja': False})\ndependent_pc = param_domain.ParamChange('b', 'Copier', {'value': '{{a}}', 'parse_with_jinja': True})\nexp_param_specs = {'a': param_domain.ParamSpec('UnicodeString'), 'b': param_domain.ParamSpec('UnicodeSt...
<|body_start_0|> independent_pc = param_domain.ParamChange('a', 'Copier', {'value': 'firstValue', 'parse_with_jinja': False}) dependent_pc = param_domain.ParamChange('b', 'Copier', {'value': '{{a}}', 'parse_with_jinja': True}) exp_param_specs = {'a': param_domain.ParamSpec('UnicodeString'), 'b':...
Test methods relating to exploration parameters.
ExplorationParametersUnitTests
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExplorationParametersUnitTests: """Test methods relating to exploration parameters.""" def test_get_init_params(self): """Test the get_init_params() method.""" <|body_0|> def test_update_learner_params(self): """Test the update_learner_params() method.""" ...
stack_v2_sparse_classes_10k_train_005304
15,833
permissive
[ { "docstring": "Test the get_init_params() method.", "name": "test_get_init_params", "signature": "def test_get_init_params(self)" }, { "docstring": "Test the update_learner_params() method.", "name": "test_update_learner_params", "signature": "def test_update_learner_params(self)" } ]
2
stack_v2_sparse_classes_30k_train_004507
Implement the Python class `ExplorationParametersUnitTests` described below. Class description: Test methods relating to exploration parameters. Method signatures and docstrings: - def test_get_init_params(self): Test the get_init_params() method. - def test_update_learner_params(self): Test the update_learner_params...
Implement the Python class `ExplorationParametersUnitTests` described below. Class description: Test methods relating to exploration parameters. Method signatures and docstrings: - def test_get_init_params(self): Test the get_init_params() method. - def test_update_learner_params(self): Test the update_learner_params...
50994926e9e4fab925a0cf1f366cad3de2ed4d7b
<|skeleton|> class ExplorationParametersUnitTests: """Test methods relating to exploration parameters.""" def test_get_init_params(self): """Test the get_init_params() method.""" <|body_0|> def test_update_learner_params(self): """Test the update_learner_params() method.""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ExplorationParametersUnitTests: """Test methods relating to exploration parameters.""" def test_get_init_params(self): """Test the get_init_params() method.""" independent_pc = param_domain.ParamChange('a', 'Copier', {'value': 'firstValue', 'parse_with_jinja': False}) dependent_pc...
the_stack_v2_python_sparse
core/controllers/reader_test.py
CMDann/oppia
train
2
0dbb563dc5e7ac920c597c3a48abb2fc84c0c2bf
[ "self.assertEqual(D20Coin.pp(1), 1000)\nself.assertEqual(D20Coin.gp(1), 100)\nself.assertEqual(D20Coin.sp(1), 10)\nself.assertEqual(D20Coin.cp(1), 1)", "treasure = D20Coin(pp=1, gp=2, sp=3, cp=4)\nself.assertEqual(treasure.value, 1234)\nself.assertEqual(treasure.sale_value, 1234)\nself.assertEqual(treasure.name, ...
<|body_start_0|> self.assertEqual(D20Coin.pp(1), 1000) self.assertEqual(D20Coin.gp(1), 100) self.assertEqual(D20Coin.sp(1), 10) self.assertEqual(D20Coin.cp(1), 1) <|end_body_0|> <|body_start_1|> treasure = D20Coin(pp=1, gp=2, sp=3, cp=4) self.assertEqual(treasure.value, ...
A test suite for the D20Coin class
TestD20Coin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestD20Coin: """A test suite for the D20Coin class""" def test_convert_coin_types(self): """Try the four coin type conversions""" <|body_0|> def test_coin_treasure(self): """Create a coin-only treasure object""" <|body_1|> <|end_skeleton|> <|body_start_...
stack_v2_sparse_classes_10k_train_005305
3,068
permissive
[ { "docstring": "Try the four coin type conversions", "name": "test_convert_coin_types", "signature": "def test_convert_coin_types(self)" }, { "docstring": "Create a coin-only treasure object", "name": "test_coin_treasure", "signature": "def test_coin_treasure(self)" } ]
2
stack_v2_sparse_classes_30k_train_006099
Implement the Python class `TestD20Coin` described below. Class description: A test suite for the D20Coin class Method signatures and docstrings: - def test_convert_coin_types(self): Try the four coin type conversions - def test_coin_treasure(self): Create a coin-only treasure object
Implement the Python class `TestD20Coin` described below. Class description: A test suite for the D20Coin class Method signatures and docstrings: - def test_convert_coin_types(self): Try the four coin type conversions - def test_coin_treasure(self): Create a coin-only treasure object <|skeleton|> class TestD20Coin: ...
75504d2443cdc80db120c5dcdc14db379d15396e
<|skeleton|> class TestD20Coin: """A test suite for the D20Coin class""" def test_convert_coin_types(self): """Try the four coin type conversions""" <|body_0|> def test_coin_treasure(self): """Create a coin-only treasure object""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TestD20Coin: """A test suite for the D20Coin class""" def test_convert_coin_types(self): """Try the four coin type conversions""" self.assertEqual(D20Coin.pp(1), 1000) self.assertEqual(D20Coin.gp(1), 100) self.assertEqual(D20Coin.sp(1), 10) self.assertEqual(D20Coin...
the_stack_v2_python_sparse
games/d20/pathfinder/test_pathfindertreasure.py
ajs/tools
train
5
18a986925e2e8bf1b4f45ec1f4cdc3312485112d
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')" ]
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
The greeting service definition.
GreeterServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GreeterServicer: """The greeting service definition.""" def SayHello(self, request, context): """Sends a greeting""" <|body_0|> def SayHelloAgain(self, request, context): """Sends another greeting""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_10k_train_005306
2,740
permissive
[ { "docstring": "Sends a greeting", "name": "SayHello", "signature": "def SayHello(self, request, context)" }, { "docstring": "Sends another greeting", "name": "SayHelloAgain", "signature": "def SayHelloAgain(self, request, context)" } ]
2
null
Implement the Python class `GreeterServicer` described below. Class description: The greeting service definition. Method signatures and docstrings: - def SayHello(self, request, context): Sends a greeting - def SayHelloAgain(self, request, context): Sends another greeting
Implement the Python class `GreeterServicer` described below. Class description: The greeting service definition. Method signatures and docstrings: - def SayHello(self, request, context): Sends a greeting - def SayHelloAgain(self, request, context): Sends another greeting <|skeleton|> class GreeterServicer: """T...
44e819e713c3885e38c99c16dc73b7d7478acfe8
<|skeleton|> class GreeterServicer: """The greeting service definition.""" def SayHello(self, request, context): """Sends a greeting""" <|body_0|> def SayHelloAgain(self, request, context): """Sends another greeting""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GreeterServicer: """The greeting service definition.""" def SayHello(self, request, context): """Sends a greeting""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def...
the_stack_v2_python_sparse
endpoints/getting-started-grpc/helloworld_pb2_grpc.py
GoogleCloudPlatform/python-docs-samples
train
7,035
51090fa6641f4d07d527782c325f98819873d476
[ "for t in self.rotationTests:\n point = Geometry.rotate(t[0][0], t[0][1], t[0][2], t[0][3], t[0][4])\n self.assertEqual(point, t[1])", "for t in self.translationTests:\n point = Geometry.translate(t[0][0], t[0][1], t[0][2], t[0][3])\n self.assertEqual(point, t[1])", "for t in self.scalingTests:\n ...
<|body_start_0|> for t in self.rotationTests: point = Geometry.rotate(t[0][0], t[0][1], t[0][2], t[0][3], t[0][4]) self.assertEqual(point, t[1]) <|end_body_0|> <|body_start_1|> for t in self.translationTests: point = Geometry.translate(t[0][0], t[0][1], t[0][2], t[0]...
testGeometry
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class testGeometry: def testRotation(self): """testing rotation primitive""" <|body_0|> def testTranslation(self): """testing translation primitive""" <|body_1|> def testScaling(self): """testing scaling primitive""" <|body_2|> <|end_skeleton|...
stack_v2_sparse_classes_10k_train_005307
27,361
no_license
[ { "docstring": "testing rotation primitive", "name": "testRotation", "signature": "def testRotation(self)" }, { "docstring": "testing translation primitive", "name": "testTranslation", "signature": "def testTranslation(self)" }, { "docstring": "testing scaling primitive", "na...
3
null
Implement the Python class `testGeometry` described below. Class description: Implement the testGeometry class. Method signatures and docstrings: - def testRotation(self): testing rotation primitive - def testTranslation(self): testing translation primitive - def testScaling(self): testing scaling primitive
Implement the Python class `testGeometry` described below. Class description: Implement the testGeometry class. Method signatures and docstrings: - def testRotation(self): testing rotation primitive - def testTranslation(self): testing translation primitive - def testScaling(self): testing scaling primitive <|skelet...
d900f58f0ddc1891831b298d9b37fbe98193719d
<|skeleton|> class testGeometry: def testRotation(self): """testing rotation primitive""" <|body_0|> def testTranslation(self): """testing translation primitive""" <|body_1|> def testScaling(self): """testing scaling primitive""" <|body_2|> <|end_skeleton|...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class testGeometry: def testRotation(self): """testing rotation primitive""" for t in self.rotationTests: point = Geometry.rotate(t[0][0], t[0][1], t[0][2], t[0][3], t[0][4]) self.assertEqual(point, t[1]) def testTranslation(self): """testing translation primitiv...
the_stack_v2_python_sparse
Assignment4/atom3/Kernel/GraphicEditor/testGraphics.py
pombreda/comp304
train
1
e6f517acbb6bd64f7c13cbc13ba6b6e320dc3174
[ "startTime = datetime.datetime.now()\nopener = urllib.request.build_opener()\nopener.addheaders = [('User-agent', 'Mozilla/5.0')]\nurllib.request.install_opener(opener)\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('arshadr_rcallah_shaikh1', 'arshadr_rcallah_shaikh1')\nprint('Connected'...
<|body_start_0|> startTime = datetime.datetime.now() opener = urllib.request.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] urllib.request.install_opener(opener) client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('arshadr_r...
income_data
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class income_data: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everything h...
stack_v2_sparse_classes_10k_train_005308
4,837
no_license
[ { "docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).", "name": "execute", "signature": "def execute(trial=False)" }, { "docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d...
2
null
Implement the Python class `income_data` described below. Class description: Implement the income_data class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTi...
Implement the Python class `income_data` described below. Class description: Implement the income_data class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTi...
90284cf3debbac36eead07b8d2339cdd191b86cf
<|skeleton|> class income_data: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everything h...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class income_data: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" startTime = datetime.datetime.now() opener = urllib.request.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] urllib.request.instal...
the_stack_v2_python_sparse
arshadr_rcallah_shaikh1/income_data.py
maximega/course-2019-spr-proj
train
2
d48eaf3f2ca2f639f53e1be750b170bc47851085
[ "try:\n email = username\n user = self.user_class.objects.get(contact__email_addresses__email_address__iexact=email, contact__email_addresses__is_primary=True)\n if user.is_active and (user.check_password(password) or no_pass):\n return user\n return None\nexcept self.user_class.DoesNotExist:\n ...
<|body_start_0|> try: email = username user = self.user_class.objects.get(contact__email_addresses__email_address__iexact=email, contact__email_addresses__is_primary=True) if user.is_active and (user.check_password(password) or no_pass): return user ...
Authenticate a CustomUser with e-mail address instead of username.
EmailAuthenticationBackend
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmailAuthenticationBackend: """Authenticate a CustomUser with e-mail address instead of username.""" def authenticate(self, username=None, password=None, no_pass=False): """Check if the user is properly authenticated, either logging in by e-mail address and password or programmatical...
stack_v2_sparse_classes_10k_train_005309
1,808
no_license
[ { "docstring": "Check if the user is properly authenticated, either logging in by e-mail address and password or programmatically logged in (e.g. upon activation of account) using no_pass=True.", "name": "authenticate", "signature": "def authenticate(self, username=None, password=None, no_pass=False)" ...
3
stack_v2_sparse_classes_30k_train_001971
Implement the Python class `EmailAuthenticationBackend` described below. Class description: Authenticate a CustomUser with e-mail address instead of username. Method signatures and docstrings: - def authenticate(self, username=None, password=None, no_pass=False): Check if the user is properly authenticated, either lo...
Implement the Python class `EmailAuthenticationBackend` described below. Class description: Authenticate a CustomUser with e-mail address instead of username. Method signatures and docstrings: - def authenticate(self, username=None, password=None, no_pass=False): Check if the user is properly authenticated, either lo...
0a284e2aae3ca08955215418a76bb70ad9af1f81
<|skeleton|> class EmailAuthenticationBackend: """Authenticate a CustomUser with e-mail address instead of username.""" def authenticate(self, username=None, password=None, no_pass=False): """Check if the user is properly authenticated, either logging in by e-mail address and password or programmatical...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class EmailAuthenticationBackend: """Authenticate a CustomUser with e-mail address instead of username.""" def authenticate(self, username=None, password=None, no_pass=False): """Check if the user is properly authenticated, either logging in by e-mail address and password or programmatically logged in ...
the_stack_v2_python_sparse
lily/users/auth_backends.py
rmoorman/hellolily
train
0
0c1b699d18933ca76dcc0358803abd2a50a8c082
[ "mix = mix.to(self.device)\nmix_w = self.modules.encoder(mix)\nest_mask = self.modules.masknet(mix_w)\nmix_w = torch.stack([mix_w] * self.hparams.num_spks)\nsep_h = mix_w * est_mask\nest_source = torch.cat([self.modules.decoder(sep_h[i]).unsqueeze(-1) for i in range(self.hparams.num_spks)], dim=-1)\nT_origin = mix....
<|body_start_0|> mix = mix.to(self.device) mix_w = self.modules.encoder(mix) est_mask = self.modules.masknet(mix_w) mix_w = torch.stack([mix_w] * self.hparams.num_spks) sep_h = mix_w * est_mask est_source = torch.cat([self.modules.decoder(sep_h[i]).unsqueeze(-1) for i in ...
A "ready-to-use" speech separation model. Uses Sepformer architecture. Example ------- >>> tmpdir = getfixture("tmpdir") >>> model = SepformerSeparation.from_hparams( ... source="speechbrain/sepformer-wsj02mix", ... savedir=tmpdir) >>> mix = torch.randn(1, 400) >>> est_sources = model.separate_batch(mix) >>> print(est_...
SepformerSeparation
[ "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference", "GPL-1.0-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SepformerSeparation: """A "ready-to-use" speech separation model. Uses Sepformer architecture. Example ------- >>> tmpdir = getfixture("tmpdir") >>> model = SepformerSeparation.from_hparams( ... source="speechbrain/sepformer-wsj02mix", ... savedir=tmpdir) >>> mix = torch.randn(1, 400) >>> est_sou...
stack_v2_sparse_classes_10k_train_005310
35,100
permissive
[ { "docstring": "Run source separation on batch of audio. Arguments --------- mix : torch.tensor The mixture of sources. Returns ------- tensor Separated sources", "name": "separate_batch", "signature": "def separate_batch(self, mix)" }, { "docstring": "Separate sources from file. Arguments -----...
2
null
Implement the Python class `SepformerSeparation` described below. Class description: A "ready-to-use" speech separation model. Uses Sepformer architecture. Example ------- >>> tmpdir = getfixture("tmpdir") >>> model = SepformerSeparation.from_hparams( ... source="speechbrain/sepformer-wsj02mix", ... savedir=tmpdir) >>...
Implement the Python class `SepformerSeparation` described below. Class description: A "ready-to-use" speech separation model. Uses Sepformer architecture. Example ------- >>> tmpdir = getfixture("tmpdir") >>> model = SepformerSeparation.from_hparams( ... source="speechbrain/sepformer-wsj02mix", ... savedir=tmpdir) >>...
92acc188d3a0f634de58463b6676e70df83ef808
<|skeleton|> class SepformerSeparation: """A "ready-to-use" speech separation model. Uses Sepformer architecture. Example ------- >>> tmpdir = getfixture("tmpdir") >>> model = SepformerSeparation.from_hparams( ... source="speechbrain/sepformer-wsj02mix", ... savedir=tmpdir) >>> mix = torch.randn(1, 400) >>> est_sou...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SepformerSeparation: """A "ready-to-use" speech separation model. Uses Sepformer architecture. Example ------- >>> tmpdir = getfixture("tmpdir") >>> model = SepformerSeparation.from_hparams( ... source="speechbrain/sepformer-wsj02mix", ... savedir=tmpdir) >>> mix = torch.randn(1, 400) >>> est_sources = model....
the_stack_v2_python_sparse
ACL_PyTorch/contrib/audio/tdnn/interfaces.py
Ascend/ModelZoo-PyTorch
train
23
ce3749ee1424c6adce799fe1e348471b79ae42af
[ "super(BowElmoEmbedder, self).__init__()\nself.emb_dim = emb_dim\nself.dropout_value = dropout_value\nself.layer_aggregation_type = layer_aggregation\nself.allowed_layer_aggregation_types = ['sum', 'average', 'last', 'first']\nself.cuda_device_id = cuda_device_id\nself.device = torch.device('cpu') if cuda_device_id...
<|body_start_0|> super(BowElmoEmbedder, self).__init__() self.emb_dim = emb_dim self.dropout_value = dropout_value self.layer_aggregation_type = layer_aggregation self.allowed_layer_aggregation_types = ['sum', 'average', 'last', 'first'] self.cuda_device_id = cuda_device_...
BowElmoEmbedder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BowElmoEmbedder: def __init__(self, emb_dim: int=1024, dropout_value: float=0.0, layer_aggregation: str='sum', cuda_device_id: int=-1): """Bag of words Elmo Embedder which aggregates elmo embedding for every token Parameters ---------- emb_dim : int Embedding dimension dropout_value : fl...
stack_v2_sparse_classes_10k_train_005311
4,125
permissive
[ { "docstring": "Bag of words Elmo Embedder which aggregates elmo embedding for every token Parameters ---------- emb_dim : int Embedding dimension dropout_value : float Any input dropout to be applied to the embeddings layer_aggregation : str You can chose one of ``[sum, average, last, first]`` which decides ho...
2
stack_v2_sparse_classes_30k_train_002649
Implement the Python class `BowElmoEmbedder` described below. Class description: Implement the BowElmoEmbedder class. Method signatures and docstrings: - def __init__(self, emb_dim: int=1024, dropout_value: float=0.0, layer_aggregation: str='sum', cuda_device_id: int=-1): Bag of words Elmo Embedder which aggregates e...
Implement the Python class `BowElmoEmbedder` described below. Class description: Implement the BowElmoEmbedder class. Method signatures and docstrings: - def __init__(self, emb_dim: int=1024, dropout_value: float=0.0, layer_aggregation: str='sum', cuda_device_id: int=-1): Bag of words Elmo Embedder which aggregates e...
cb4c1413ddc3c749835e1cb80db31c0060e7a1eb
<|skeleton|> class BowElmoEmbedder: def __init__(self, emb_dim: int=1024, dropout_value: float=0.0, layer_aggregation: str='sum', cuda_device_id: int=-1): """Bag of words Elmo Embedder which aggregates elmo embedding for every token Parameters ---------- emb_dim : int Embedding dimension dropout_value : fl...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class BowElmoEmbedder: def __init__(self, emb_dim: int=1024, dropout_value: float=0.0, layer_aggregation: str='sum', cuda_device_id: int=-1): """Bag of words Elmo Embedder which aggregates elmo embedding for every token Parameters ---------- emb_dim : int Embedding dimension dropout_value : float Any input ...
the_stack_v2_python_sparse
sciwing/modules/embedders/bow_elmo_embedder.py
yaxche-io/sciwing
train
0
97ba2c8dbb90199871ebead20570ddb79ccca4d5
[ "args = movies_parser.parse_args()\npage = args['page']\nper_page = args['per_page']\nsort_by = args['sort_by']\nsort_order = args['order']\nstart = per_page * (page - 1)\nstop = start + per_page\ndescending = sort_order == 'desc'\nkwargs = {'start': start, 'stop': stop, 'list_id': list_id, 'order_by': sort_by, 'de...
<|body_start_0|> args = movies_parser.parse_args() page = args['page'] per_page = args['per_page'] sort_by = args['sort_by'] sort_order = args['order'] start = per_page * (page - 1) stop = start + per_page descending = sort_order == 'desc' kwargs =...
MovieListMoviesAPI
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovieListMoviesAPI: def get(self, list_id, session=None): """Get movies by list ID""" <|body_0|> def post(self, list_id, session=None): """Add movies to list by ID""" <|body_1|> <|end_skeleton|> <|body_start_0|> args = movies_parser.parse_args() ...
stack_v2_sparse_classes_10k_train_005312
12,846
permissive
[ { "docstring": "Get movies by list ID", "name": "get", "signature": "def get(self, list_id, session=None)" }, { "docstring": "Add movies to list by ID", "name": "post", "signature": "def post(self, list_id, session=None)" } ]
2
null
Implement the Python class `MovieListMoviesAPI` described below. Class description: Implement the MovieListMoviesAPI class. Method signatures and docstrings: - def get(self, list_id, session=None): Get movies by list ID - def post(self, list_id, session=None): Add movies to list by ID
Implement the Python class `MovieListMoviesAPI` described below. Class description: Implement the MovieListMoviesAPI class. Method signatures and docstrings: - def get(self, list_id, session=None): Get movies by list ID - def post(self, list_id, session=None): Add movies to list by ID <|skeleton|> class MovieListMov...
ea95ff60041beaea9aacbc2d93549e3a6b981dc5
<|skeleton|> class MovieListMoviesAPI: def get(self, list_id, session=None): """Get movies by list ID""" <|body_0|> def post(self, list_id, session=None): """Add movies to list by ID""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MovieListMoviesAPI: def get(self, list_id, session=None): """Get movies by list ID""" args = movies_parser.parse_args() page = args['page'] per_page = args['per_page'] sort_by = args['sort_by'] sort_order = args['order'] start = per_page * (page - 1) ...
the_stack_v2_python_sparse
flexget/components/managed_lists/lists/movie_list/api.py
BrutuZ/Flexget
train
1
608eda567b1c98079ef6384daee47e21bb89f84b
[ "writer = KvDbWriter(KvDbClient(**config))\nfor configured_stream in configured_catalog.streams:\n if configured_stream.destination_sync_mode == DestinationSyncMode.overwrite:\n writer.delete_stream_entries(configured_stream.stream.name)\nfor message in input_messages:\n if message.type == Type.STATE:\...
<|body_start_0|> writer = KvDbWriter(KvDbClient(**config)) for configured_stream in configured_catalog.streams: if configured_stream.destination_sync_mode == DestinationSyncMode.overwrite: writer.delete_stream_entries(configured_stream.stream.name) for message in inpu...
DestinationKvdb
[ "MIT", "Apache-2.0", "BSD-3-Clause", "Elastic-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DestinationKvdb: def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessage]: """Reads the input stream of messages, config, and catalog to write data to the destination. This method return...
stack_v2_sparse_classes_10k_train_005313
3,439
permissive
[ { "docstring": "Reads the input stream of messages, config, and catalog to write data to the destination. This method returns an iterable (typically a generator of AirbyteMessages via yield) containing state messages received in the input message stream. Outputting a state message means that every AirbyteRecord...
2
stack_v2_sparse_classes_30k_train_006855
Implement the Python class `DestinationKvdb` described below. Class description: Implement the DestinationKvdb class. Method signatures and docstrings: - def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessage]: Read...
Implement the Python class `DestinationKvdb` described below. Class description: Implement the DestinationKvdb class. Method signatures and docstrings: - def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessage]: Read...
8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6
<|skeleton|> class DestinationKvdb: def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessage]: """Reads the input stream of messages, config, and catalog to write data to the destination. This method return...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class DestinationKvdb: def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessage]: """Reads the input stream of messages, config, and catalog to write data to the destination. This method returns an iterable ...
the_stack_v2_python_sparse
dts/airbyte/airbyte-integrations/connectors/destination-kvdb/destination_kvdb/destination.py
alldatacenter/alldata
train
774
af50065004b0f65f1417d3839533b261a29f9b2a
[ "self.queue = []\nself.front = None\nself.rare = None\nself.max_size = 5", "if self.rare == self.max_size - 1:\n print('Overflow')\nelse:\n self.queue.append(item)\n if self.front == None:\n self.front = 0\n self.rare = 0\n else:\n self.rare += 1", "if self.front == None:\n p...
<|body_start_0|> self.queue = [] self.front = None self.rare = None self.max_size = 5 <|end_body_0|> <|body_start_1|> if self.rare == self.max_size - 1: print('Overflow') else: self.queue.append(item) if self.front == None: ...
This class contains functions for queue data structure implementation. Enqueue: To add at rare position. Dequeue: To remove at front position.
Queue
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Queue: """This class contains functions for queue data structure implementation. Enqueue: To add at rare position. Dequeue: To remove at front position.""" def __init__(self): """Constructor function. Argument: self -- represents the object of the class.""" <|body_0|> de...
stack_v2_sparse_classes_10k_train_005314
2,051
no_license
[ { "docstring": "Constructor function. Argument: self -- represents the object of the class.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "This function will add the item to the queue. Argument: self -- represents the object of the class. item -- integer value.", ...
4
stack_v2_sparse_classes_30k_train_006935
Implement the Python class `Queue` described below. Class description: This class contains functions for queue data structure implementation. Enqueue: To add at rare position. Dequeue: To remove at front position. Method signatures and docstrings: - def __init__(self): Constructor function. Argument: self -- represen...
Implement the Python class `Queue` described below. Class description: This class contains functions for queue data structure implementation. Enqueue: To add at rare position. Dequeue: To remove at front position. Method signatures and docstrings: - def __init__(self): Constructor function. Argument: self -- represen...
6870426104aef417086788221dad29e887ddfe3f
<|skeleton|> class Queue: """This class contains functions for queue data structure implementation. Enqueue: To add at rare position. Dequeue: To remove at front position.""" def __init__(self): """Constructor function. Argument: self -- represents the object of the class.""" <|body_0|> de...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Queue: """This class contains functions for queue data structure implementation. Enqueue: To add at rare position. Dequeue: To remove at front position.""" def __init__(self): """Constructor function. Argument: self -- represents the object of the class.""" self.queue = [] self.fr...
the_stack_v2_python_sparse
Data Structure/03. Queue/01. Queue Implementation/py_code.py
Slothfulwave612/Coding-Problems
train
5
8cc0dc9633f9b9cee52b2c36367c06a63ea75666
[ "self.terms = terms\n\ndef form():\n res = 0\n for x in terms:\n res += x.base ** x.power\n return res\nself.form = form", "if isinstance(target, Formula) == False:\n raise ValueError('Require Formula instance!')\n\ndef form():\n res = 0\n for t in target.terms:\n for x in self.ter...
<|body_start_0|> self.terms = terms def form(): res = 0 for x in terms: res += x.base ** x.power return res self.form = form <|end_body_0|> <|body_start_1|> if isinstance(target, Formula) == False: raise ValueError('Requir...
Formula class. Have base number and multiplier.
Formula
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Formula: """Formula class. Have base number and multiplier.""" def __init__(self, terms): """Recieved Term object list.""" <|body_0|> def __mul__(self, target): """Multiply out.""" <|body_1|> def calc(self): """Retaining formula caluculate.""...
stack_v2_sparse_classes_10k_train_005315
7,281
no_license
[ { "docstring": "Recieved Term object list.", "name": "__init__", "signature": "def __init__(self, terms)" }, { "docstring": "Multiply out.", "name": "__mul__", "signature": "def __mul__(self, target)" }, { "docstring": "Retaining formula caluculate.", "name": "calc", "sig...
3
stack_v2_sparse_classes_30k_train_003045
Implement the Python class `Formula` described below. Class description: Formula class. Have base number and multiplier. Method signatures and docstrings: - def __init__(self, terms): Recieved Term object list. - def __mul__(self, target): Multiply out. - def calc(self): Retaining formula caluculate.
Implement the Python class `Formula` described below. Class description: Formula class. Have base number and multiplier. Method signatures and docstrings: - def __init__(self, terms): Recieved Term object list. - def __mul__(self, target): Multiply out. - def calc(self): Retaining formula caluculate. <|skeleton|> cl...
0c4f79ce5c370027b76ec9a336b392ee61b12a7a
<|skeleton|> class Formula: """Formula class. Have base number and multiplier.""" def __init__(self, terms): """Recieved Term object list.""" <|body_0|> def __mul__(self, target): """Multiply out.""" <|body_1|> def calc(self): """Retaining formula caluculate.""...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Formula: """Formula class. Have base number and multiplier.""" def __init__(self, terms): """Recieved Term object list.""" self.terms = terms def form(): res = 0 for x in terms: res += x.base ** x.power return res self.f...
the_stack_v2_python_sparse
pheasant/numtheory.py
moguonyanko/pheasant
train
0
a94619b76fd9dd0dc0e3afa02ececd22d1290059
[ "if data is None:\n raise ValidationError('No data was provided')\nreturn Performance(**data)", "if data['start_datetime'].date() > data['end_datetime'].date():\n raise ValidationError('Start date must be before end date.')\nelif data['start_datetime'].date() == data['end_datetime'].date() and data['start_d...
<|body_start_0|> if data is None: raise ValidationError('No data was provided') return Performance(**data) <|end_body_0|> <|body_start_1|> if data['start_datetime'].date() > data['end_datetime'].date(): raise ValidationError('Start date must be before end date.') ...
Class to serialize and deserialize Performance objects.
PerformanceSchema
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PerformanceSchema: """Class to serialize and deserialize Performance objects.""" def make_object(self, data, **kwargs): """Return a performance object from the validated data.""" <|body_0|> def validate_datetimes(self, data, **kwargs): """Raise a ValidationError ...
stack_v2_sparse_classes_10k_train_005316
2,121
no_license
[ { "docstring": "Return a performance object from the validated data.", "name": "make_object", "signature": "def make_object(self, data, **kwargs)" }, { "docstring": "Raise a ValidationError if the start_datetime is after the end_datetime.", "name": "validate_datetimes", "signature": "def...
2
stack_v2_sparse_classes_30k_train_002659
Implement the Python class `PerformanceSchema` described below. Class description: Class to serialize and deserialize Performance objects. Method signatures and docstrings: - def make_object(self, data, **kwargs): Return a performance object from the validated data. - def validate_datetimes(self, data, **kwargs): Rai...
Implement the Python class `PerformanceSchema` described below. Class description: Class to serialize and deserialize Performance objects. Method signatures and docstrings: - def make_object(self, data, **kwargs): Return a performance object from the validated data. - def validate_datetimes(self, data, **kwargs): Rai...
d5ae552d383f5f971e29a38055c518fc68172f32
<|skeleton|> class PerformanceSchema: """Class to serialize and deserialize Performance objects.""" def make_object(self, data, **kwargs): """Return a performance object from the validated data.""" <|body_0|> def validate_datetimes(self, data, **kwargs): """Raise a ValidationError ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PerformanceSchema: """Class to serialize and deserialize Performance objects.""" def make_object(self, data, **kwargs): """Return a performance object from the validated data.""" if data is None: raise ValidationError('No data was provided') return Performance(**data) ...
the_stack_v2_python_sparse
server/app/api/schemas/performance.py
EricMontague/MailChimp-Newsletter-Project
train
0
12bfaad3d93abc8989bf3065f638200430de6f5c
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.chatMessageHostedContent'.casefold():\n ...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') try: mapping_value = parse_node.get_child_node('@odata.type').get_str_value() except AttributeError: mapping_value = None if mapping_value and mapping_value.casefold() ==...
TeamworkHostedContent
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TeamworkHostedContent: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkHostedContent: """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 th...
stack_v2_sparse_classes_10k_train_005317
2,909
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: TeamworkHostedContent", "name": "create_from_discriminator_value", "signature": "def create_from_discriminat...
3
null
Implement the Python class `TeamworkHostedContent` described below. Class description: Implement the TeamworkHostedContent class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkHostedContent: Creates a new instance of the appropriate class base...
Implement the Python class `TeamworkHostedContent` described below. Class description: Implement the TeamworkHostedContent class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkHostedContent: Creates a new instance of the appropriate class base...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class TeamworkHostedContent: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkHostedContent: """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 th...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TeamworkHostedContent: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkHostedContent: """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 Retur...
the_stack_v2_python_sparse
msgraph/generated/models/teamwork_hosted_content.py
microsoftgraph/msgraph-sdk-python
train
135
28658cda49c965f5add0ab92473812c45c28d8e7
[ "self.label = label\nself.paths = paths\nif self.paths is None:\n self.paths = {}\nself.reset()", "str_ = \"Vertex '{label}' - visited: {visited}, parent: {parent}, cost: {cost}\\n\"\nstr_ += ' paths: {paths}'\nreturn str_.format(**self.__dict__)", "self.visited = False\nself.parent = None\nself.cost = No...
<|body_start_0|> self.label = label self.paths = paths if self.paths is None: self.paths = {} self.reset() <|end_body_0|> <|body_start_1|> str_ = "Vertex '{label}' - visited: {visited}, parent: {parent}, cost: {cost}\n" str_ += ' paths: {paths}' re...
A graph vertex with a set of paths to other vertices. A vertex is characterized by a label (or name) and a dictionary of paths from the vertex to other vertices. For application of Dijkstra's algorithm for calculating the shortest path from any vertex to all other vertices, each vertex also has the 'visited', 'parent' ...
Vertex
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Vertex: """A graph vertex with a set of paths to other vertices. A vertex is characterized by a label (or name) and a dictionary of paths from the vertex to other vertices. For application of Dijkstra's algorithm for calculating the shortest path from any vertex to all other vertices, each vertex...
stack_v2_sparse_classes_10k_train_005318
15,275
no_license
[ { "docstring": "Create a new vertex.", "name": "__init__", "signature": "def __init__(self, label, paths=None)" }, { "docstring": "Format the vertex as a string.", "name": "__str__", "signature": "def __str__(self)" }, { "docstring": "Reset the vertex to its default values. This ...
3
stack_v2_sparse_classes_30k_train_002581
Implement the Python class `Vertex` described below. Class description: A graph vertex with a set of paths to other vertices. A vertex is characterized by a label (or name) and a dictionary of paths from the vertex to other vertices. For application of Dijkstra's algorithm for calculating the shortest path from any ve...
Implement the Python class `Vertex` described below. Class description: A graph vertex with a set of paths to other vertices. A vertex is characterized by a label (or name) and a dictionary of paths from the vertex to other vertices. For application of Dijkstra's algorithm for calculating the shortest path from any ve...
c80ea145c758f3b392f956e4311f11cfc099a149
<|skeleton|> class Vertex: """A graph vertex with a set of paths to other vertices. A vertex is characterized by a label (or name) and a dictionary of paths from the vertex to other vertices. For application of Dijkstra's algorithm for calculating the shortest path from any vertex to all other vertices, each vertex...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Vertex: """A graph vertex with a set of paths to other vertices. A vertex is characterized by a label (or name) and a dictionary of paths from the vertex to other vertices. For application of Dijkstra's algorithm for calculating the shortest path from any vertex to all other vertices, each vertex also has the...
the_stack_v2_python_sparse
dailyprogrammer/challenges/038e.py
UltimateTimmeh/r-daily-programmer
train
0
f9505cb6e584b53da247837e9d22c998696971b5
[ "if tree:\n print(tree.get_root_val())\n Orders.preorder(tree.get_left_child())\n Orders.preorder(tree.get_right_child())", "if tree != None:\n Orders.inorder(tree.get_left_child())\n print(tree.get_root_val())\n Orders.inorder(tree.get_right_child())", "if tree != None:\n Orders.postorder(...
<|body_start_0|> if tree: print(tree.get_root_val()) Orders.preorder(tree.get_left_child()) Orders.preorder(tree.get_right_child()) <|end_body_0|> <|body_start_1|> if tree != None: Orders.inorder(tree.get_left_child()) print(tree.get_root_val(...
Стат методы для обхода дерева
Orders
[ "WTFPL" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Orders: """Стат методы для обхода дерева""" def preorder(tree): """Прямой обход дерева""" <|body_0|> def inorder(tree): """Симметричный обход дерева""" <|body_1|> def postorder(tree): """Обратный обход""" <|body_2|> <|end_skeleton|> ...
stack_v2_sparse_classes_10k_train_005319
2,441
permissive
[ { "docstring": "Прямой обход дерева", "name": "preorder", "signature": "def preorder(tree)" }, { "docstring": "Симметричный обход дерева", "name": "inorder", "signature": "def inorder(tree)" }, { "docstring": "Обратный обход", "name": "postorder", "signature": "def postor...
3
stack_v2_sparse_classes_30k_train_002886
Implement the Python class `Orders` described below. Class description: Стат методы для обхода дерева Method signatures and docstrings: - def preorder(tree): Прямой обход дерева - def inorder(tree): Симметричный обход дерева - def postorder(tree): Обратный обход
Implement the Python class `Orders` described below. Class description: Стат методы для обхода дерева Method signatures and docstrings: - def preorder(tree): Прямой обход дерева - def inorder(tree): Симметричный обход дерева - def postorder(tree): Обратный обход <|skeleton|> class Orders: """Стат методы для обхо...
9575c43fa01c261ea1ed573df9b5686b5a6f4211
<|skeleton|> class Orders: """Стат методы для обхода дерева""" def preorder(tree): """Прямой обход дерева""" <|body_0|> def inorder(tree): """Симметричный обход дерева""" <|body_1|> def postorder(tree): """Обратный обход""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Orders: """Стат методы для обхода дерева""" def preorder(tree): """Прямой обход дерева""" if tree: print(tree.get_root_val()) Orders.preorder(tree.get_left_child()) Orders.preorder(tree.get_right_child()) def inorder(tree): """Симметричный ...
the_stack_v2_python_sparse
Course_I/Алгоритмы Python/Part2/семинары/pract6/task3/task.py
GeorgiyDemo/FA
train
46
f23e2f45bb2cad751652bd5bc4fcc3f1d08e49a7
[ "if user_id is None:\n return None\nSessionId = super().create_session(user_id)\nif SessionId is None:\n return None\nusInstance = UserSession()\nusInstance.user_id = user_id\nusInstance.session_id = SessionId\nusInstance.save()\nreturn SessionId", "UserSession.load_from_file()\nobj = UserSession.search({'s...
<|body_start_0|> if user_id is None: return None SessionId = super().create_session(user_id) if SessionId is None: return None usInstance = UserSession() usInstance.user_id = user_id usInstance.session_id = SessionId usInstance.save() ...
[summary] Args: SessionExpAuth ([type]): [description]
SessionDBAuth
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionDBAuth: """[summary] Args: SessionExpAuth ([type]): [description]""" def create_session(self, user_id=None): """[summary] Args: user_id ([type], optional): [description]. Defaults to None.""" <|body_0|> def user_id_for_session_id(self, session_id=None): ""...
stack_v2_sparse_classes_10k_train_005320
2,155
no_license
[ { "docstring": "[summary] Args: user_id ([type], optional): [description]. Defaults to None.", "name": "create_session", "signature": "def create_session(self, user_id=None)" }, { "docstring": "[Request database and return user_id based on the session_id] Args: session_id ([type], optional): [de...
3
stack_v2_sparse_classes_30k_train_006694
Implement the Python class `SessionDBAuth` described below. Class description: [summary] Args: SessionExpAuth ([type]): [description] Method signatures and docstrings: - def create_session(self, user_id=None): [summary] Args: user_id ([type], optional): [description]. Defaults to None. - def user_id_for_session_id(se...
Implement the Python class `SessionDBAuth` described below. Class description: [summary] Args: SessionExpAuth ([type]): [description] Method signatures and docstrings: - def create_session(self, user_id=None): [summary] Args: user_id ([type], optional): [description]. Defaults to None. - def user_id_for_session_id(se...
94cae2ce3aa4cd72fc5907bd0148694054a9e60f
<|skeleton|> class SessionDBAuth: """[summary] Args: SessionExpAuth ([type]): [description]""" def create_session(self, user_id=None): """[summary] Args: user_id ([type], optional): [description]. Defaults to None.""" <|body_0|> def user_id_for_session_id(self, session_id=None): ""...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SessionDBAuth: """[summary] Args: SessionExpAuth ([type]): [description]""" def create_session(self, user_id=None): """[summary] Args: user_id ([type], optional): [description]. Defaults to None.""" if user_id is None: return None SessionId = super().create_session(use...
the_stack_v2_python_sparse
0x07-Session_authentication/api/v1/auth/session_db_auth.py
nakadorx/holbertonschool-web_back_end
train
0
6e496121999f5a37a17d3e184866cc98b9a7d96e
[ "if not matrix:\n return\nn = matrix.__len__()\nrotate = [[0 for _ in range(n)] for _ in range(n)]\nfor i in range(n):\n for j in range(n):\n rotate[j][n - 1 - i] = matrix[i][j]\nmatrix[:] = rotate[:]", "if not matrix:\n return\nn = matrix.__len__()\nmatrix.reverse()\nfor i in range(n):\n for j...
<|body_start_0|> if not matrix: return n = matrix.__len__() rotate = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): for j in range(n): rotate[j][n - 1 - i] = matrix[i][j] matrix[:] = rotate[:] <|end_body_0|> <|body_start_1|> ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rotate(self, matrix): """:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.""" <|body_0|> def rotate1(self, matrix): """:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-p...
stack_v2_sparse_classes_10k_train_005321
1,454
no_license
[ { "docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.", "name": "rotate", "signature": "def rotate(self, matrix)" }, { "docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.", ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. - def rotate1(self, matrix): :type matrix: List[List[...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. - def rotate1(self, matrix): :type matrix: List[List[...
472f780c3214aab5c713612812d834ccbe589434
<|skeleton|> class Solution: def rotate(self, matrix): """:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.""" <|body_0|> def rotate1(self, matrix): """:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-p...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def rotate(self, matrix): """:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.""" if not matrix: return n = matrix.__len__() rotate = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): ...
the_stack_v2_python_sparse
2/48-Rotate_Image.py
ChangXiaodong/Leetcode-solutions
train
4
221af954ec827e037fdab8c1c32d0d14bcb7daeb
[ "if accepting_variables is None and rejecting_variables is None and (not no_variables):\n raise ValueError('Cannot create a symbolic subring since nothing is specified.')\nif accepting_variables is not None and rejecting_variables is not None or (rejecting_variables is not None and no_variables) or (no_variables...
<|body_start_0|> if accepting_variables is None and rejecting_variables is None and (not no_variables): raise ValueError('Cannot create a symbolic subring since nothing is specified.') if accepting_variables is not None and rejecting_variables is not None or (rejecting_variables is not None ...
A factory creating a symbolic subring. INPUT: Specify one of the following keywords to create a subring. - ``accepting_variables`` (default: ``None``) -- a tuple or other iterable of variables. If specified, then a symbolic subring of expressions in only these variables is created. - ``rejecting_variables`` (default: `...
SymbolicSubringFactory
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SymbolicSubringFactory: """A factory creating a symbolic subring. INPUT: Specify one of the following keywords to create a subring. - ``accepting_variables`` (default: ``None``) -- a tuple or other iterable of variables. If specified, then a symbolic subring of expressions in only these variables...
stack_v2_sparse_classes_10k_train_005322
31,870
no_license
[ { "docstring": "Given the arguments and keyword, create a key that uniquely determines this object. See :class:`SymbolicSubringFactory` for details. TESTS:: sage: from sage.symbolic.subring import SymbolicSubring sage: SymbolicSubring.create_key_and_extra_args() Traceback (most recent call last): ... ValueError...
2
null
Implement the Python class `SymbolicSubringFactory` described below. Class description: A factory creating a symbolic subring. INPUT: Specify one of the following keywords to create a subring. - ``accepting_variables`` (default: ``None``) -- a tuple or other iterable of variables. If specified, then a symbolic subring...
Implement the Python class `SymbolicSubringFactory` described below. Class description: A factory creating a symbolic subring. INPUT: Specify one of the following keywords to create a subring. - ``accepting_variables`` (default: ``None``) -- a tuple or other iterable of variables. If specified, then a symbolic subring...
0d9eacbf74e2acffefde93e39f8bcbec745cdaba
<|skeleton|> class SymbolicSubringFactory: """A factory creating a symbolic subring. INPUT: Specify one of the following keywords to create a subring. - ``accepting_variables`` (default: ``None``) -- a tuple or other iterable of variables. If specified, then a symbolic subring of expressions in only these variables...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SymbolicSubringFactory: """A factory creating a symbolic subring. INPUT: Specify one of the following keywords to create a subring. - ``accepting_variables`` (default: ``None``) -- a tuple or other iterable of variables. If specified, then a symbolic subring of expressions in only these variables is created. ...
the_stack_v2_python_sparse
sage/src/sage/symbolic/subring.py
bopopescu/geosci
train
0
0e5a14d238bc7cc34fd3aad87fc634e42a176871
[ "super(WordDatatype_iter_with_caching, self).__init__(parent, iter, length)\nself._data, self._gen = itertools.tee(self._data)\nself._list = []\nself._last_index = -1", "for a in self._list:\n yield a\nfor a in self._gen:\n self._list.append(a)\n self._last_index += 1\n yield a\nif self._len is None:\...
<|body_start_0|> super(WordDatatype_iter_with_caching, self).__init__(parent, iter, length) self._data, self._gen = itertools.tee(self._data) self._list = [] self._last_index = -1 <|end_body_0|> <|body_start_1|> for a in self._list: yield a for a in self._gen...
WordDatatype_iter_with_caching
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordDatatype_iter_with_caching: def __init__(self, parent, iter, length=None): """INPUT: - ``parent`` - a parent - ``iter`` - an iterator - ``length`` - (default: ``None``) the length of the word EXAMPLES:: sage: import itertools sage: Word(itertools.cycle("abbabaab")) word: abbabaababba...
stack_v2_sparse_classes_10k_train_005323
39,600
no_license
[ { "docstring": "INPUT: - ``parent`` - a parent - ``iter`` - an iterator - ``length`` - (default: ``None``) the length of the word EXAMPLES:: sage: import itertools sage: Word(itertools.cycle(\"abbabaab\")) word: abbabaababbabaababbabaababbabaababbabaab... sage: w = Word(iter(\"abbabaab\"), length=\"finite\"); w...
5
null
Implement the Python class `WordDatatype_iter_with_caching` described below. Class description: Implement the WordDatatype_iter_with_caching class. Method signatures and docstrings: - def __init__(self, parent, iter, length=None): INPUT: - ``parent`` - a parent - ``iter`` - an iterator - ``length`` - (default: ``None...
Implement the Python class `WordDatatype_iter_with_caching` described below. Class description: Implement the WordDatatype_iter_with_caching class. Method signatures and docstrings: - def __init__(self, parent, iter, length=None): INPUT: - ``parent`` - a parent - ``iter`` - an iterator - ``length`` - (default: ``None...
0d9eacbf74e2acffefde93e39f8bcbec745cdaba
<|skeleton|> class WordDatatype_iter_with_caching: def __init__(self, parent, iter, length=None): """INPUT: - ``parent`` - a parent - ``iter`` - an iterator - ``length`` - (default: ``None``) the length of the word EXAMPLES:: sage: import itertools sage: Word(itertools.cycle("abbabaab")) word: abbabaababba...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class WordDatatype_iter_with_caching: def __init__(self, parent, iter, length=None): """INPUT: - ``parent`` - a parent - ``iter`` - an iterator - ``length`` - (default: ``None``) the length of the word EXAMPLES:: sage: import itertools sage: Word(itertools.cycle("abbabaab")) word: abbabaababbabaababbabaabab...
the_stack_v2_python_sparse
sage/src/sage/combinat/words/word_infinite_datatypes.py
bopopescu/geosci
train
0
a47911233f844849c984eb6c3d5768e95fc92b51
[ "self.out_filters = out_filters\nself.strides = strides\nself.in_filters = None\nsuper(Upscore, self).__init__(name)", "if self.in_filters is None:\n self.in_filters = x.get_shape().as_list()[-1]\nassert self.in_filters == x.get_shape().as_list()[-1], 'Module was initialised for a different input shape'\nif se...
<|body_start_0|> self.out_filters = out_filters self.strides = strides self.in_filters = None super(Upscore, self).__init__(name) <|end_body_0|> <|body_start_1|> if self.in_filters is None: self.in_filters = x.get_shape().as_list()[-1] assert self.in_filters ...
Upscore module according to J. Long.
Upscore
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Upscore: """Upscore module according to J. Long.""" def __init__(self, out_filters, strides, name='upscore'): """Constructs an Upscore module Parameters ---------- out_filters : int number of output filters strides : list or tuple strides to use for upsampling name : string name of t...
stack_v2_sparse_classes_10k_train_005324
11,734
permissive
[ { "docstring": "Constructs an Upscore module Parameters ---------- out_filters : int number of output filters strides : list or tuple strides to use for upsampling name : string name of the module", "name": "__init__", "signature": "def __init__(self, out_filters, strides, name='upscore')" }, { ...
2
stack_v2_sparse_classes_30k_train_002764
Implement the Python class `Upscore` described below. Class description: Upscore module according to J. Long. Method signatures and docstrings: - def __init__(self, out_filters, strides, name='upscore'): Constructs an Upscore module Parameters ---------- out_filters : int number of output filters strides : list or tu...
Implement the Python class `Upscore` described below. Class description: Upscore module according to J. Long. Method signatures and docstrings: - def __init__(self, out_filters, strides, name='upscore'): Constructs an Upscore module Parameters ---------- out_filters : int number of output filters strides : list or tu...
80d1a04dc163590aa44b62688b06aece78fb7fd6
<|skeleton|> class Upscore: """Upscore module according to J. Long.""" def __init__(self, out_filters, strides, name='upscore'): """Constructs an Upscore module Parameters ---------- out_filters : int number of output filters strides : list or tuple strides to use for upsampling name : string name of t...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Upscore: """Upscore module according to J. Long.""" def __init__(self, out_filters, strides, name='upscore'): """Constructs an Upscore module Parameters ---------- out_filters : int number of output filters strides : list or tuple strides to use for upsampling name : string name of the module""" ...
the_stack_v2_python_sparse
dltk/models/segmentation/deepmedic.py
pawni/DLTK-1
train
1
5969474fa3c92f5089d35dbfabadb8e6b0364fb8
[ "kth = None\ncnt = 0\n\ndef find_kth_smallest(node):\n if not node:\n return False\n if find_kth_smallest(node.left):\n return True\n nonlocal cnt, kth\n cnt += 1\n if cnt == k:\n kth = node.val\n return True\n return find_kth_smallest(node.right)\nfind_kth_smallest(roo...
<|body_start_0|> kth = None cnt = 0 def find_kth_smallest(node): if not node: return False if find_kth_smallest(node.left): return True nonlocal cnt, kth cnt += 1 if cnt == k: kth = node....
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: """08/25/2019 16:16""" <|body_0|> def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: """05/01/2022 19:49""" <|body_1|> <|end_skeleton|> <|body_start_0|> kth = None ...
stack_v2_sparse_classes_10k_train_005325
2,893
no_license
[ { "docstring": "08/25/2019 16:16", "name": "kthSmallest", "signature": "def kthSmallest(self, root: TreeNode, k: int) -> int" }, { "docstring": "05/01/2022 19:49", "name": "kthSmallest", "signature": "def kthSmallest(self, root: Optional[TreeNode], k: int) -> int" } ]
2
stack_v2_sparse_classes_30k_train_004134
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def kthSmallest(self, root: TreeNode, k: int) -> int: 08/25/2019 16:16 - def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: 05/01/2022 19:49
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def kthSmallest(self, root: TreeNode, k: int) -> int: 08/25/2019 16:16 - def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: 05/01/2022 19:49 <|skeleton|> class Solu...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: """08/25/2019 16:16""" <|body_0|> def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: """05/01/2022 19:49""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: """08/25/2019 16:16""" kth = None cnt = 0 def find_kth_smallest(node): if not node: return False if find_kth_smallest(node.left): return True non...
the_stack_v2_python_sparse
leetcode/solved/230_Kth_Smallest_Element_in_a_BST/solution.py
sungminoh/algorithms
train
0
52ddaa0a584115434cd4de02da4cc3118a7a2b63
[ "try:\n res = requests.get(url, params=params, **kwargs)\nexcept Exception:\n logging.info('访问get请求不成功')\nelse:\n return res", "try:\n res = requests.post(url, data=data, json=json, **kwargs)\nexcept Exception:\n logging.info(url, data, json, **kwargs)\n logging.info('访问post请求不成功')\nelse:\n r...
<|body_start_0|> try: res = requests.get(url, params=params, **kwargs) except Exception: logging.info('访问get请求不成功') else: return res <|end_body_0|> <|body_start_1|> try: res = requests.post(url, data=data, json=json, **kwargs) exce...
不需要记住cookie信息的请求类
RequestsHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RequestsHandler: """不需要记住cookie信息的请求类""" def get(self, url, params=None, **kwargs): """发送get请求 params 传递参数就是放到URL里面传递 data 在form表单中传递参数""" <|body_0|> def post(self, url, data=None, json=None, **kwargs): """发送post请求""" <|body_1|> def visit(self, metho...
stack_v2_sparse_classes_10k_train_005326
4,741
no_license
[ { "docstring": "发送get请求 params 传递参数就是放到URL里面传递 data 在form表单中传递参数", "name": "get", "signature": "def get(self, url, params=None, **kwargs)" }, { "docstring": "发送post请求", "name": "post", "signature": "def post(self, url, data=None, json=None, **kwargs)" }, { "docstring": "访问 get 和 ...
4
null
Implement the Python class `RequestsHandler` described below. Class description: 不需要记住cookie信息的请求类 Method signatures and docstrings: - def get(self, url, params=None, **kwargs): 发送get请求 params 传递参数就是放到URL里面传递 data 在form表单中传递参数 - def post(self, url, data=None, json=None, **kwargs): 发送post请求 - def visit(self, method, u...
Implement the Python class `RequestsHandler` described below. Class description: 不需要记住cookie信息的请求类 Method signatures and docstrings: - def get(self, url, params=None, **kwargs): 发送get请求 params 传递参数就是放到URL里面传递 data 在form表单中传递参数 - def post(self, url, data=None, json=None, **kwargs): 发送post请求 - def visit(self, method, u...
cfadd3132c2c7c518c784589e0dab6510a662a6c
<|skeleton|> class RequestsHandler: """不需要记住cookie信息的请求类""" def get(self, url, params=None, **kwargs): """发送get请求 params 传递参数就是放到URL里面传递 data 在form表单中传递参数""" <|body_0|> def post(self, url, data=None, json=None, **kwargs): """发送post请求""" <|body_1|> def visit(self, metho...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class RequestsHandler: """不需要记住cookie信息的请求类""" def get(self, url, params=None, **kwargs): """发送get请求 params 传递参数就是放到URL里面传递 data 在form表单中传递参数""" try: res = requests.get(url, params=params, **kwargs) except Exception: logging.info('访问get请求不成功') else: ...
the_stack_v2_python_sparse
yiqihai/tebiemiao/Interface/common/requests_handler.py
songyongzhuang/PythonCode_office
train
0
a01f40def4606dbbb33e812126fdf5e3713e20a7
[ "n = len(nums)\ndp = [0] * (n + 2)\nfor i in reversed(range(n)):\n dp[i] = max(nums[i] + dp[i + 2], dp[i + 1])\nreturn dp[0]", "last, now = (0, 0)\nfor x in nums:\n last, now = (now, max(last + x, now))\nreturn now" ]
<|body_start_0|> n = len(nums) dp = [0] * (n + 2) for i in reversed(range(n)): dp[i] = max(nums[i] + dp[i + 2], dp[i + 1]) return dp[0] <|end_body_0|> <|body_start_1|> last, now = (0, 0) for x in nums: last, now = (now, max(last + x, now)) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def rob2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(nums) dp = [0] * (n + 2) for i in re...
stack_v2_sparse_classes_10k_train_005327
1,446
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "rob", "signature": "def rob(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "rob2", "signature": "def rob2(self, nums)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rob(self, nums): :type nums: List[int] :rtype: int - def rob2(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rob(self, nums): :type nums: List[int] :rtype: int - def rob2(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def rob(self, nums): "...
fa6504cb5145d10952f4615478fa745f4b35ba13
<|skeleton|> class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def rob2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" n = len(nums) dp = [0] * (n + 2) for i in reversed(range(n)): dp[i] = max(nums[i] + dp[i + 2], dp[i + 1]) return dp[0] def rob2(self, nums): """:type nums: List[int] :rtype: ...
the_stack_v2_python_sparse
Algorithms/challenges/lc198_house_robber.py
snowdj/cs_course
train
0
e32dd38bec112369a53caf2b775e3f6a0665dee2
[ "if not nums:\n return 0\nactive = []\nfor num in nums:\n if not active:\n active.append(num)\n continue\n if num <= active[0]:\n active[0] = num\n elif num > active[-1]:\n active.append(num)\n else:\n i = 0\n while i < len(active) and num > active[i]:\n ...
<|body_start_0|> if not nums: return 0 active = [] for num in nums: if not active: active.append(num) continue if num <= active[0]: active[0] = num elif num > active[-1]: active.append...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lengthOfLIS(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def lengthOfLIS_DP(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not nums: return 0 ...
stack_v2_sparse_classes_10k_train_005328
3,192
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "lengthOfLIS", "signature": "def lengthOfLIS(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "lengthOfLIS_DP", "signature": "def lengthOfLIS_DP(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_007299
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int - def lengthOfLIS_DP(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int - def lengthOfLIS_DP(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def lengthOf...
d308e0e41c288f23a846b8505e572943d30b1392
<|skeleton|> class Solution: def lengthOfLIS(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def lengthOfLIS_DP(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def lengthOfLIS(self, nums): """:type nums: List[int] :rtype: int""" if not nums: return 0 active = [] for num in nums: if not active: active.append(num) continue if num <= active[0]: ...
the_stack_v2_python_sparse
python/300_Longest_Increasing_Subsequence.py
HankerZheng/LeetCode-Problems
train
2
91b6f562d8058a2b569f1b7b7736b02e24d6348d
[ "supercategorys = []\ncategories_id = {}\nfor item in categories:\n supercategory = item['supercategory']\n name = item['name']\n id = item['id']\n categories_id[name] = id\nreturn categories_id", "annotations_id = []\nfor item in annotations:\n id = item['id']\n annotations_id.append(id)\nretur...
<|body_start_0|> supercategorys = [] categories_id = {} for item in categories: supercategory = item['supercategory'] name = item['name'] id = item['id'] categories_id[name] = id return categories_id <|end_body_0|> <|body_start_1|> ...
COCO Tools
COCOTools
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class COCOTools: """COCO Tools""" def get_categories_id(categories): """get categories id dict :param categories: :return: dict:{name:id}""" <|body_0|> def get_annotations_id(annotations): """get annotations id list :param annotations: :return: annotations id list""" ...
stack_v2_sparse_classes_10k_train_005329
11,741
no_license
[ { "docstring": "get categories id dict :param categories: :return: dict:{name:id}", "name": "get_categories_id", "signature": "def get_categories_id(categories)" }, { "docstring": "get annotations id list :param annotations: :return: annotations id list", "name": "get_annotations_id", "s...
5
stack_v2_sparse_classes_30k_train_007047
Implement the Python class `COCOTools` described below. Class description: COCO Tools Method signatures and docstrings: - def get_categories_id(categories): get categories id dict :param categories: :return: dict:{name:id} - def get_annotations_id(annotations): get annotations id list :param annotations: :return: ann...
Implement the Python class `COCOTools` described below. Class description: COCO Tools Method signatures and docstrings: - def get_categories_id(categories): get categories id dict :param categories: :return: dict:{name:id} - def get_annotations_id(annotations): get annotations id list :param annotations: :return: ann...
f45f0879cc70eb59de67a270a6ec8dbb2cf8e742
<|skeleton|> class COCOTools: """COCO Tools""" def get_categories_id(categories): """get categories id dict :param categories: :return: dict:{name:id}""" <|body_0|> def get_annotations_id(annotations): """get annotations id list :param annotations: :return: annotations id list""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class COCOTools: """COCO Tools""" def get_categories_id(categories): """get categories id dict :param categories: :return: dict:{name:id}""" supercategorys = [] categories_id = {} for item in categories: supercategory = item['supercategory'] name = item['...
the_stack_v2_python_sparse
modules/dataset_tool/coco_tools/convert_voc2coco.py
zuiyueyin/python-learning-notes
train
0
6b45c00a9bc4dbb74d987b80149d4e7f1fa85b78
[ "self.tailed_file = tailed_file\nself.check_file_validity()\nself.tailed_file = tailed_file", "with open(self.tailed_file, 'r') as file_:\n file_.seek(0, 2)\n fsize = file_.tell()\n file_.seek(max(fsize - 10000, 0), 0)\n lines = file_.readlines()\nlines = lines[-max_lines:]\nfor line in lines:\n pr...
<|body_start_0|> self.tailed_file = tailed_file self.check_file_validity() self.tailed_file = tailed_file <|end_body_0|> <|body_start_1|> with open(self.tailed_file, 'r') as file_: file_.seek(0, 2) fsize = file_.tell() file_.seek(max(fsize - 10000, 0)...
Represent a tail command.
File
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class File: """Represent a tail command.""" def __init__(self, tailed_file): """Method that instantiates the class. Check for file validity, assigns callback function to standard out. Args: tailed_file - File to be followed.""" <|body_0|> def tail(self, seconds=1, max_lines=50...
stack_v2_sparse_classes_10k_train_005330
3,083
permissive
[ { "docstring": "Method that instantiates the class. Check for file validity, assigns callback function to standard out. Args: tailed_file - File to be followed.", "name": "__init__", "signature": "def __init__(self, tailed_file)" }, { "docstring": "Do a tail follow. If a callback function is reg...
3
stack_v2_sparse_classes_30k_test_000147
Implement the Python class `File` described below. Class description: Represent a tail command. Method signatures and docstrings: - def __init__(self, tailed_file): Method that instantiates the class. Check for file validity, assigns callback function to standard out. Args: tailed_file - File to be followed. - def ta...
Implement the Python class `File` described below. Class description: Represent a tail command. Method signatures and docstrings: - def __init__(self, tailed_file): Method that instantiates the class. Check for file validity, assigns callback function to standard out. Args: tailed_file - File to be followed. - def ta...
ae82589fbbab77fef6d6be09c1fcca5846f595a8
<|skeleton|> class File: """Represent a tail command.""" def __init__(self, tailed_file): """Method that instantiates the class. Check for file validity, assigns callback function to standard out. Args: tailed_file - File to be followed.""" <|body_0|> def tail(self, seconds=1, max_lines=50...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class File: """Represent a tail command.""" def __init__(self, tailed_file): """Method that instantiates the class. Check for file validity, assigns callback function to standard out. Args: tailed_file - File to be followed.""" self.tailed_file = tailed_file self.check_file_validity() ...
the_stack_v2_python_sparse
switchmap/utils/input_output.py
PalisadoesFoundation/switchmap-ng
train
8
3dbf0ac49449127672d21b514c773321ffae9278
[ "self.host = host\nself.port = port\nself.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nself.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nself.sock.bind((self.host, self.port))\nself.messagesList = []\nself.connected = []", "self.sock.listen(5)\nwhile True:\n client, address = self.s...
<|body_start_0|> self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.host, self.port)) self.messagesList = [] self.connected = [] <|end...
ChatServer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChatServer: def __init__(self, host, port): """Initialization for the server""" <|body_0|> def listen(self): """Loop for accepting clients""" <|body_1|> def listenToClient(self, client, address): """Client thread method""" <|body_2|> ...
stack_v2_sparse_classes_10k_train_005331
2,925
no_license
[ { "docstring": "Initialization for the server", "name": "__init__", "signature": "def __init__(self, host, port)" }, { "docstring": "Loop for accepting clients", "name": "listen", "signature": "def listen(self)" }, { "docstring": "Client thread method", "name": "listenToClien...
4
stack_v2_sparse_classes_30k_train_003498
Implement the Python class `ChatServer` described below. Class description: Implement the ChatServer class. Method signatures and docstrings: - def __init__(self, host, port): Initialization for the server - def listen(self): Loop for accepting clients - def listenToClient(self, client, address): Client thread method...
Implement the Python class `ChatServer` described below. Class description: Implement the ChatServer class. Method signatures and docstrings: - def __init__(self, host, port): Initialization for the server - def listen(self): Loop for accepting clients - def listenToClient(self, client, address): Client thread method...
0249a73062f6bef9e40d0ab792f9cf30eaa363ed
<|skeleton|> class ChatServer: def __init__(self, host, port): """Initialization for the server""" <|body_0|> def listen(self): """Loop for accepting clients""" <|body_1|> def listenToClient(self, client, address): """Client thread method""" <|body_2|> ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ChatServer: def __init__(self, host, port): """Initialization for the server""" self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.h...
the_stack_v2_python_sparse
Bimester2/Class10/ChatServer.py
aloysiogl/CES-22_solutions
train
0
bdd16bb6870ea5a9ded39bef95448c15cdc1223b
[ "super(GraphVisualizerPointDraw, self).__init__()\nself.setMinimumSize(QSize(13, 13))\nself.setMaximumSize(QSize(13, 13))", "painter = QPainter(self)\npainter.drawEllipse(self.rect().center(), 6, 6)\npainter.setBrush(Qt.black)\npainter.drawEllipse(self.rect().center(), 2, 2)" ]
<|body_start_0|> super(GraphVisualizerPointDraw, self).__init__() self.setMinimumSize(QSize(13, 13)) self.setMaximumSize(QSize(13, 13)) <|end_body_0|> <|body_start_1|> painter = QPainter(self) painter.drawEllipse(self.rect().center(), 6, 6) painter.setBrush(Qt.black) ...
Define an empty widget with a point drew.
GraphVisualizerPointDraw
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GraphVisualizerPointDraw: """Define an empty widget with a point drew.""" def __init__(self): """Initialize a GraphVisualizerPointDraw instance.""" <|body_0|> def paintEvent(self, event): """Paint an event.""" <|body_1|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_10k_train_005332
24,840
permissive
[ { "docstring": "Initialize a GraphVisualizerPointDraw instance.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Paint an event.", "name": "paintEvent", "signature": "def paintEvent(self, event)" } ]
2
stack_v2_sparse_classes_30k_train_003757
Implement the Python class `GraphVisualizerPointDraw` described below. Class description: Define an empty widget with a point drew. Method signatures and docstrings: - def __init__(self): Initialize a GraphVisualizerPointDraw instance. - def paintEvent(self, event): Paint an event.
Implement the Python class `GraphVisualizerPointDraw` described below. Class description: Define an empty widget with a point drew. Method signatures and docstrings: - def __init__(self): Initialize a GraphVisualizerPointDraw instance. - def paintEvent(self, event): Paint an event. <|skeleton|> class GraphVisualizer...
bbcf475a4b4e85836123452053bbbf34cc44063a
<|skeleton|> class GraphVisualizerPointDraw: """Define an empty widget with a point drew.""" def __init__(self): """Initialize a GraphVisualizerPointDraw instance.""" <|body_0|> def paintEvent(self, event): """Paint an event.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GraphVisualizerPointDraw: """Define an empty widget with a point drew.""" def __init__(self): """Initialize a GraphVisualizerPointDraw instance.""" super(GraphVisualizerPointDraw, self).__init__() self.setMinimumSize(QSize(13, 13)) self.setMaximumSize(QSize(13, 13)) d...
the_stack_v2_python_sparse
posydon/visualization/VH_diagram/GraphVisualizer.py
POSYDON-code/POSYDON
train
11
f5583083a3c3cec400b7c5689b140822ca889d5f
[ "result = []\nfor model in cls.model_list:\n result += list(model.objects.filter(*args, **kwargs))\nreturn result", "try:\n ls = cls.filter(*args, **kwargs)\n if len(ls) > 1:\n raise MultipleObjectsReturned()\n return cls.filter(*args, **kwargs)[0]\nexcept IndexError:\n raise ObjectDoesNotEx...
<|body_start_0|> result = [] for model in cls.model_list: result += list(model.objects.filter(*args, **kwargs)) return result <|end_body_0|> <|body_start_1|> try: ls = cls.filter(*args, **kwargs) if len(ls) > 1: raise MultipleObjectsRe...
This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models.
AbstractModelQuery
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AbstractModelQuery: """This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models.""" def filter(cls, *args, **kwargs): """Query all concrete model classes. Iterates over the model list and returns a list of a...
stack_v2_sparse_classes_10k_train_005333
1,753
permissive
[ { "docstring": "Query all concrete model classes. Iterates over the model list and returns a list of all matching models from the classes given. Filter queries are given here as normal and are passed into the Django ORM for each concrete model", "name": "filter", "signature": "def filter(cls, *args, **k...
2
stack_v2_sparse_classes_30k_train_007312
Implement the Python class `AbstractModelQuery` described below. Class description: This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models. Method signatures and docstrings: - def filter(cls, *args, **kwargs): Query all concrete model clas...
Implement the Python class `AbstractModelQuery` described below. Class description: This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models. Method signatures and docstrings: - def filter(cls, *args, **kwargs): Query all concrete model clas...
886a644432ff53f97babccbae4eee555338caec1
<|skeleton|> class AbstractModelQuery: """This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models.""" def filter(cls, *args, **kwargs): """Query all concrete model classes. Iterates over the model list and returns a list of a...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class AbstractModelQuery: """This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models.""" def filter(cls, *args, **kwargs): """Query all concrete model classes. Iterates over the model list and returns a list of all matching m...
the_stack_v2_python_sparse
src/dashboard/utils.py
opnfv/laas
train
3
3ae99b698b17e25fe5fc4832727a51c6df6142f7
[ "super(Model, self).__init__()\nself.model1 = MlpNet(layer_sizes1, input_size1).double()\nself.model2 = MlpNet(layer_sizes2, input_size2).double()\nself.loss = cca_loss(outdim_size, use_all_singular_values, device).loss", "output1 = self.model1(x1)\noutput2 = self.model2(x2)\nreturn (output1, output2)" ]
<|body_start_0|> super(Model, self).__init__() self.model1 = MlpNet(layer_sizes1, input_size1).double() self.model2 = MlpNet(layer_sizes2, input_size2).double() self.loss = cca_loss(outdim_size, use_all_singular_values, device).loss <|end_body_0|> <|body_start_1|> output1 = self...
Model
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Model: def __init__(self, layer_sizes1: list, layer_sizes2: list, input_size1: int, input_size2: int, outdim_size: int, use_all_singular_values: bool=False, device=torch.device('cpu')): """model initialization Parameters ---------- layer_sizes1 (list): list of layer shape of view 1 layer...
stack_v2_sparse_classes_10k_train_005334
2,797
permissive
[ { "docstring": "model initialization Parameters ---------- layer_sizes1 (list): list of layer shape of view 1 layer_sizes2 (list): list of layer shape of view 1 input_size1 (int): input dimension of view 1 input_size2 (int): input dimension of view 2 outdim_size (int): output dimension of data use_all_singular_...
2
stack_v2_sparse_classes_30k_train_007004
Implement the Python class `Model` described below. Class description: Implement the Model class. Method signatures and docstrings: - def __init__(self, layer_sizes1: list, layer_sizes2: list, input_size1: int, input_size2: int, outdim_size: int, use_all_singular_values: bool=False, device=torch.device('cpu')): model...
Implement the Python class `Model` described below. Class description: Implement the Model class. Method signatures and docstrings: - def __init__(self, layer_sizes1: list, layer_sizes2: list, input_size1: int, input_size2: int, outdim_size: int, use_all_singular_values: bool=False, device=torch.device('cpu')): model...
89ba01c18d3ed36942ffdf3e1f3c68fd08b05324
<|skeleton|> class Model: def __init__(self, layer_sizes1: list, layer_sizes2: list, input_size1: int, input_size2: int, outdim_size: int, use_all_singular_values: bool=False, device=torch.device('cpu')): """model initialization Parameters ---------- layer_sizes1 (list): list of layer shape of view 1 layer...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Model: def __init__(self, layer_sizes1: list, layer_sizes2: list, input_size1: int, input_size2: int, outdim_size: int, use_all_singular_values: bool=False, device=torch.device('cpu')): """model initialization Parameters ---------- layer_sizes1 (list): list of layer shape of view 1 layer_sizes2 (list)...
the_stack_v2_python_sparse
Groups/Group_ID_7/DeepCCA/DeepCCAModels.py
aryapushpa/DataScience
train
0
a5428b1a799611dac61e81dbc7ee2f8a16a80f57
[ "if str2bool(value):\n return queryset.filter(status__in=BuildStatusGroups.ACTIVE_CODES)\nelse:\n return queryset.exclude(status__in=BuildStatusGroups.ACTIVE_CODES)", "if str2bool(value):\n return queryset.filter(Build.OVERDUE_FILTER)\nelse:\n return queryset.exclude(Build.OVERDUE_FILTER)", "value =...
<|body_start_0|> if str2bool(value): return queryset.filter(status__in=BuildStatusGroups.ACTIVE_CODES) else: return queryset.exclude(status__in=BuildStatusGroups.ACTIVE_CODES) <|end_body_0|> <|body_start_1|> if str2bool(value): return queryset.filter(Build.OV...
Custom filterset for BuildList API endpoint.
BuildFilter
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BuildFilter: """Custom filterset for BuildList API endpoint.""" def filter_active(self, queryset, name, value): """Filter the queryset to either include or exclude orders which are active.""" <|body_0|> def filter_overdue(self, queryset, name, value): """Filter t...
stack_v2_sparse_classes_10k_train_005335
20,912
permissive
[ { "docstring": "Filter the queryset to either include or exclude orders which are active.", "name": "filter_active", "signature": "def filter_active(self, queryset, name, value)" }, { "docstring": "Filter the queryset to either include or exclude orders which are overdue.", "name": "filter_o...
5
null
Implement the Python class `BuildFilter` described below. Class description: Custom filterset for BuildList API endpoint. Method signatures and docstrings: - def filter_active(self, queryset, name, value): Filter the queryset to either include or exclude orders which are active. - def filter_overdue(self, queryset, n...
Implement the Python class `BuildFilter` described below. Class description: Custom filterset for BuildList API endpoint. Method signatures and docstrings: - def filter_active(self, queryset, name, value): Filter the queryset to either include or exclude orders which are active. - def filter_overdue(self, queryset, n...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class BuildFilter: """Custom filterset for BuildList API endpoint.""" def filter_active(self, queryset, name, value): """Filter the queryset to either include or exclude orders which are active.""" <|body_0|> def filter_overdue(self, queryset, name, value): """Filter t...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class BuildFilter: """Custom filterset for BuildList API endpoint.""" def filter_active(self, queryset, name, value): """Filter the queryset to either include or exclude orders which are active.""" if str2bool(value): return queryset.filter(status__in=BuildStatusGroups.ACTIVE_CODES)...
the_stack_v2_python_sparse
InvenTree/build/api.py
inventree/InvenTree
train
3,077
1f149501ee1f991a2fe0e31947b627d399d8a74a
[ "self.distance_x = distance_x\nself.distance_y = distance_y\nself.rho = rho\nself.eps = eps\nself.auditor_nsteps = auditor_nsteps\nself.auditor_lr = auditor_lr\nsuper().__init__(module=module, criterion=criterion, regression=regression, **kwargs)", "self.initialize_criterion()\nkwargs = self.get_params_for('modul...
<|body_start_0|> self.distance_x = distance_x self.distance_y = distance_y self.rho = rho self.eps = eps self.auditor_nsteps = auditor_nsteps self.auditor_lr = auditor_lr super().__init__(module=module, criterion=criterion, regression=regression, **kwargs) <|end_b...
Sensitive Set Invariance (SenSeI). SenSeI is an in-processing method for individual fairness [#yurochkin20]_. In this method, individual fairness is formulated as invariance on certain sensitive sets. SenSeI minimizes a transport-based regularizer that enforces this version of individual fairness. References: .. [#yuro...
SenSeI
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SenSeI: """Sensitive Set Invariance (SenSeI). SenSeI is an in-processing method for individual fairness [#yurochkin20]_. In this method, individual fairness is formulated as invariance on certain sensitive sets. SenSeI minimizes a transport-based regularizer that enforces this version of individu...
stack_v2_sparse_classes_10k_train_005336
15,710
permissive
[ { "docstring": "Args: module (torch.nn.Module): Network architecture. criterion (torch.nn.Module): Loss function. distance_x (inFairness.distances.Distance): Distance metric in the input space. distance_y (inFairness.distances.Distance): Distance metric in the output space. rho (float): :math:`\\\\rho` paramete...
2
stack_v2_sparse_classes_30k_train_000864
Implement the Python class `SenSeI` described below. Class description: Sensitive Set Invariance (SenSeI). SenSeI is an in-processing method for individual fairness [#yurochkin20]_. In this method, individual fairness is formulated as invariance on certain sensitive sets. SenSeI minimizes a transport-based regularizer...
Implement the Python class `SenSeI` described below. Class description: Sensitive Set Invariance (SenSeI). SenSeI is an in-processing method for individual fairness [#yurochkin20]_. In this method, individual fairness is formulated as invariance on certain sensitive sets. SenSeI minimizes a transport-based regularizer...
6f9972e4a7dbca2402f29b86ea67889143dbeb3e
<|skeleton|> class SenSeI: """Sensitive Set Invariance (SenSeI). SenSeI is an in-processing method for individual fairness [#yurochkin20]_. In this method, individual fairness is formulated as invariance on certain sensitive sets. SenSeI minimizes a transport-based regularizer that enforces this version of individu...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SenSeI: """Sensitive Set Invariance (SenSeI). SenSeI is an in-processing method for individual fairness [#yurochkin20]_. In this method, individual fairness is formulated as invariance on certain sensitive sets. SenSeI minimizes a transport-based regularizer that enforces this version of individual fairness. ...
the_stack_v2_python_sparse
aif360/sklearn/inprocessing/infairness.py
Trusted-AI/AIF360
train
1,157
5614132ffaceb5ea3e84b0434d7dc4e71450f20b
[ "super().__init__(adguard, entry)\nself.entity_description = description\nself._attr_unique_id = '_'.join([DOMAIN, adguard.host, str(adguard.port), 'sensor', description.key])", "value = await self.entity_description.value_fn(self.adguard)\nself._attr_native_value = value\nif isinstance(value, float):\n self._...
<|body_start_0|> super().__init__(adguard, entry) self.entity_description = description self._attr_unique_id = '_'.join([DOMAIN, adguard.host, str(adguard.port), 'sensor', description.key]) <|end_body_0|> <|body_start_1|> value = await self.entity_description.value_fn(self.adguard) ...
Defines a AdGuard Home sensor.
AdGuardHomeSensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdGuardHomeSensor: """Defines a AdGuard Home sensor.""" def __init__(self, adguard: AdGuardHome, entry: ConfigEntry, description: AdGuardHomeEntityDescription) -> None: """Initialize AdGuard Home sensor.""" <|body_0|> async def _adguard_update(self) -> None: """U...
stack_v2_sparse_classes_10k_train_005337
4,982
permissive
[ { "docstring": "Initialize AdGuard Home sensor.", "name": "__init__", "signature": "def __init__(self, adguard: AdGuardHome, entry: ConfigEntry, description: AdGuardHomeEntityDescription) -> None" }, { "docstring": "Update AdGuard Home entity.", "name": "_adguard_update", "signature": "a...
2
null
Implement the Python class `AdGuardHomeSensor` described below. Class description: Defines a AdGuard Home sensor. Method signatures and docstrings: - def __init__(self, adguard: AdGuardHome, entry: ConfigEntry, description: AdGuardHomeEntityDescription) -> None: Initialize AdGuard Home sensor. - async def _adguard_up...
Implement the Python class `AdGuardHomeSensor` described below. Class description: Defines a AdGuard Home sensor. Method signatures and docstrings: - def __init__(self, adguard: AdGuardHome, entry: ConfigEntry, description: AdGuardHomeEntityDescription) -> None: Initialize AdGuard Home sensor. - async def _adguard_up...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class AdGuardHomeSensor: """Defines a AdGuard Home sensor.""" def __init__(self, adguard: AdGuardHome, entry: ConfigEntry, description: AdGuardHomeEntityDescription) -> None: """Initialize AdGuard Home sensor.""" <|body_0|> async def _adguard_update(self) -> None: """U...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class AdGuardHomeSensor: """Defines a AdGuard Home sensor.""" def __init__(self, adguard: AdGuardHome, entry: ConfigEntry, description: AdGuardHomeEntityDescription) -> None: """Initialize AdGuard Home sensor.""" super().__init__(adguard, entry) self.entity_description = description ...
the_stack_v2_python_sparse
homeassistant/components/adguard/sensor.py
home-assistant/core
train
35,501
4f5627fc3183b6714c6c39d26d80be832e9f5f16
[ "self.fileHandle = fileHandle\nself.dagPath = dagPath\nself.fFluid = OpenMayaFX.MFnFluid(dagPath)", "xPtr = OpenMaya.MScriptUtil().asDoublePtr()\nyPtr = OpenMaya.MScriptUtil().asDoublePtr()\nzPtr = OpenMaya.MScriptUtil().asDoublePtr()\nself.fFluid.getDimensions(xPtr, yPtr, zPtr)\ndimX = OpenMaya.MScriptUtil(xPtr)...
<|body_start_0|> self.fileHandle = fileHandle self.dagPath = dagPath self.fFluid = OpenMayaFX.MFnFluid(dagPath) <|end_body_0|> <|body_start_1|> xPtr = OpenMaya.MScriptUtil().asDoublePtr() yPtr = OpenMaya.MScriptUtil().asDoublePtr() zPtr = OpenMaya.MScriptUtil().asDoubleP...
Fluid volume export module
Volume
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Volume: """Fluid volume export module""" def __init__(self, fileHandle, dagPath): """Set up the objects we're dealing with""" <|body_0|> def getOutput(self): """Read Fluid data and export as volumegrid""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_10k_train_005338
2,972
no_license
[ { "docstring": "Set up the objects we're dealing with", "name": "__init__", "signature": "def __init__(self, fileHandle, dagPath)" }, { "docstring": "Read Fluid data and export as volumegrid", "name": "getOutput", "signature": "def getOutput(self)" } ]
2
stack_v2_sparse_classes_30k_train_004572
Implement the Python class `Volume` described below. Class description: Fluid volume export module Method signatures and docstrings: - def __init__(self, fileHandle, dagPath): Set up the objects we're dealing with - def getOutput(self): Read Fluid data and export as volumegrid
Implement the Python class `Volume` described below. Class description: Fluid volume export module Method signatures and docstrings: - def __init__(self, fileHandle, dagPath): Set up the objects we're dealing with - def getOutput(self): Read Fluid data and export as volumegrid <|skeleton|> class Volume: """Fluid...
3891e40c3c4c3a054e5ff1ff16d051d4e690cc4a
<|skeleton|> class Volume: """Fluid volume export module""" def __init__(self, fileHandle, dagPath): """Set up the objects we're dealing with""" <|body_0|> def getOutput(self): """Read Fluid data and export as volumegrid""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Volume: """Fluid volume export module""" def __init__(self, fileHandle, dagPath): """Set up the objects we're dealing with""" self.fileHandle = fileHandle self.dagPath = dagPath self.fFluid = OpenMayaFX.MFnFluid(dagPath) def getOutput(self): """Read Fluid data...
the_stack_v2_python_sparse
luxPlugin/Lux/LuxExportModules/Volume.py
LuxRender/LuxMaya
train
0
08d63d9a573f23c0ae83b2507add617971dbbd47
[ "Model.__init__(self, data, verbose=verbose)\nself.α = α\nif G is None:\n self.G = stats.norm(loc=0, scale=10000)\nelse:\n self.G = G\nself.col_lookups = [{unique_val: count for unique_val, count in zip(*np.unique(self.X.data[:, d][~self.X.mask[:, d]], return_counts=True))} for d in range(self.D)]\nself._calc...
<|body_start_0|> Model.__init__(self, data, verbose=verbose) self.α = α if G is None: self.G = stats.norm(loc=0, scale=10000) else: self.G = G self.col_lookups = [{unique_val: count for unique_val, count in zip(*np.unique(self.X.data[:, d][~self.X.mask[:, ...
DP
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DP: def __init__(self, data, verbose=None, α=1, G=None): """Creates the model object. Args: data: The dataset with missing data as a numpy masked array. verbose: bool, indicating whether or not information should be written to std_err. α: floating point concentration parameter. G: prior ...
stack_v2_sparse_classes_10k_train_005339
7,946
permissive
[ { "docstring": "Creates the model object. Args: data: The dataset with missing data as a numpy masked array. verbose: bool, indicating whether or not information should be written to std_err. α: floating point concentration parameter. G: prior distribution: scipy.stats objects or other objects with similar inte...
6
stack_v2_sparse_classes_30k_train_005463
Implement the Python class `DP` described below. Class description: Implement the DP class. Method signatures and docstrings: - def __init__(self, data, verbose=None, α=1, G=None): Creates the model object. Args: data: The dataset with missing data as a numpy masked array. verbose: bool, indicating whether or not inf...
Implement the Python class `DP` described below. Class description: Implement the DP class. Method signatures and docstrings: - def __init__(self, data, verbose=None, α=1, G=None): Creates the model object. Args: data: The dataset with missing data as a numpy masked array. verbose: bool, indicating whether or not inf...
99aaa6364898e5e67a9fc7e21d8c5dc0052d9edc
<|skeleton|> class DP: def __init__(self, data, verbose=None, α=1, G=None): """Creates the model object. Args: data: The dataset with missing data as a numpy masked array. verbose: bool, indicating whether or not information should be written to std_err. α: floating point concentration parameter. G: prior ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class DP: def __init__(self, data, verbose=None, α=1, G=None): """Creates the model object. Args: data: The dataset with missing data as a numpy masked array. verbose: bool, indicating whether or not information should be written to std_err. α: floating point concentration parameter. G: prior distribution: ...
the_stack_v2_python_sparse
auto_impute/dp.py
JamesAllingham/AutoImpute
train
1
f81f8f325de4d2b29662b70777cf97b8fc5957d1
[ "Parametre.__init__(self, 'vitesse', 'speed')\nself.schema = '<vitesse_rames>'\nself.aide_courte = 'change la vitesse des rames'\nself.aide_longue = \"Cette commande permet de modifier la vitesse des rames que vous tenez en main. Les vitesses disponibles sont |cmd|arrière|ff| (pour aller en marche arrière), |cmd|im...
<|body_start_0|> Parametre.__init__(self, 'vitesse', 'speed') self.schema = '<vitesse_rames>' self.aide_courte = 'change la vitesse des rames' self.aide_longue = "Cette commande permet de modifier la vitesse des rames que vous tenez en main. Les vitesses disponibles sont |cmd|arrière|ff|...
Commande 'rames vitesse'.
PrmVitesse
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PrmVitesse: """Commande 'rames vitesse'.""" def __init__(self): """Constructeur du paramètre""" <|body_0|> def interpreter(self, personnage, dic_masques): """Interprétation du paramètre""" <|body_1|> <|end_skeleton|> <|body_start_0|> Parametre._...
stack_v2_sparse_classes_10k_train_005340
3,270
permissive
[ { "docstring": "Constructeur du paramètre", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Interprétation du paramètre", "name": "interpreter", "signature": "def interpreter(self, personnage, dic_masques)" } ]
2
null
Implement the Python class `PrmVitesse` described below. Class description: Commande 'rames vitesse'. Method signatures and docstrings: - def __init__(self): Constructeur du paramètre - def interpreter(self, personnage, dic_masques): Interprétation du paramètre
Implement the Python class `PrmVitesse` described below. Class description: Commande 'rames vitesse'. Method signatures and docstrings: - def __init__(self): Constructeur du paramètre - def interpreter(self, personnage, dic_masques): Interprétation du paramètre <|skeleton|> class PrmVitesse: """Commande 'rames v...
7e93bff08cdf891352efba587e89c40f3b4a2301
<|skeleton|> class PrmVitesse: """Commande 'rames vitesse'.""" def __init__(self): """Constructeur du paramètre""" <|body_0|> def interpreter(self, personnage, dic_masques): """Interprétation du paramètre""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PrmVitesse: """Commande 'rames vitesse'.""" def __init__(self): """Constructeur du paramètre""" Parametre.__init__(self, 'vitesse', 'speed') self.schema = '<vitesse_rames>' self.aide_courte = 'change la vitesse des rames' self.aide_longue = "Cette commande permet d...
the_stack_v2_python_sparse
src/secondaires/navigation/commandes/rames/vitesse.py
vincent-lg/tsunami
train
5
6f5f9de9c3ff9f3ff37e76660fd3d93a701d479f
[ "self.mb_dir_path.mkdir(parents=True, exist_ok=True)\nfor i in range(self.n_boxes):\n mb_path = self.path_to_mailbox(i)\n with mb_path.open('w') as fh:\n fh.write(header)", "if index_name is None:\n start = '\\t'\nelse:\n start = f'{index_name}\\t'\ncolstring = '\\t'.join(columns)\nself.mb_dir_...
<|body_start_0|> self.mb_dir_path.mkdir(parents=True, exist_ok=True) for i in range(self.n_boxes): mb_path = self.path_to_mailbox(i) with mb_path.open('w') as fh: fh.write(header) <|end_body_0|> <|body_start_1|> if index_name is None: start = ...
Pass data to and from on-disk FIFOs.
DataMailboxes
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataMailboxes: """Pass data to and from on-disk FIFOs.""" def write_headers(self, header): """Initialize the mailboxes, writing a free-form header.""" <|body_0|> def write_tsv_headers(self, columns, index_name=None): """Initialize the mailboxes, writing a tab-sep...
stack_v2_sparse_classes_10k_train_005341
7,728
permissive
[ { "docstring": "Initialize the mailboxes, writing a free-form header.", "name": "write_headers", "signature": "def write_headers(self, header)" }, { "docstring": "Initialize the mailboxes, writing a tab-separated header.", "name": "write_tsv_headers", "signature": "def write_tsv_headers(...
6
stack_v2_sparse_classes_30k_train_005899
Implement the Python class `DataMailboxes` described below. Class description: Pass data to and from on-disk FIFOs. Method signatures and docstrings: - def write_headers(self, header): Initialize the mailboxes, writing a free-form header. - def write_tsv_headers(self, columns, index_name=None): Initialize the mailbox...
Implement the Python class `DataMailboxes` described below. Class description: Pass data to and from on-disk FIFOs. Method signatures and docstrings: - def write_headers(self, header): Initialize the mailboxes, writing a free-form header. - def write_tsv_headers(self, columns, index_name=None): Initialize the mailbox...
90b6f52d9208458053001e49a9537cd9870c5f15
<|skeleton|> class DataMailboxes: """Pass data to and from on-disk FIFOs.""" def write_headers(self, header): """Initialize the mailboxes, writing a free-form header.""" <|body_0|> def write_tsv_headers(self, columns, index_name=None): """Initialize the mailboxes, writing a tab-sep...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class DataMailboxes: """Pass data to and from on-disk FIFOs.""" def write_headers(self, header): """Initialize the mailboxes, writing a free-form header.""" self.mb_dir_path.mkdir(parents=True, exist_ok=True) for i in range(self.n_boxes): mb_path = self.path_to_mailbox(i) ...
the_stack_v2_python_sparse
azulejo/mailboxes.py
legumeinfo/azulejo
train
0
0e5e7d507e358cab8c33d98a1957c9316c750f38
[ "merge_df = graph.merge_by_year(1807)\nself.assertEqual(['Country', 'Region', 'Income'], merge_df.columns.values.tolist())\nself.assertEqual(merge_df.ix[0, 'Country'], 'Algeria')\nself.assertEqual(merge_df.ix[0, 'Region'], 'AFRICA')\nself.assertEqual(merge_df.ix[0, 'Income'], 766.121479698518)", "self.assertEqual...
<|body_start_0|> merge_df = graph.merge_by_year(1807) self.assertEqual(['Country', 'Region', 'Income'], merge_df.columns.values.tolist()) self.assertEqual(merge_df.ix[0, 'Country'], 'Algeria') self.assertEqual(merge_df.ix[0, 'Region'], 'AFRICA') self.assertEqual(merge_df.ix[0, 'I...
Test
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test: def test_merge_by_year(self): """Unit test for the merge_by_year function.""" <|body_0|> def test_year_string_to_int(self): """Unit test for the year_string_to_int function.""" <|body_1|> <|end_skeleton|> <|body_start_0|> merge_df = graph.merg...
stack_v2_sparse_classes_10k_train_005342
1,235
no_license
[ { "docstring": "Unit test for the merge_by_year function.", "name": "test_merge_by_year", "signature": "def test_merge_by_year(self)" }, { "docstring": "Unit test for the year_string_to_int function.", "name": "test_year_string_to_int", "signature": "def test_year_string_to_int(self)" ...
2
null
Implement the Python class `Test` described below. Class description: Implement the Test class. Method signatures and docstrings: - def test_merge_by_year(self): Unit test for the merge_by_year function. - def test_year_string_to_int(self): Unit test for the year_string_to_int function.
Implement the Python class `Test` described below. Class description: Implement the Test class. Method signatures and docstrings: - def test_merge_by_year(self): Unit test for the merge_by_year function. - def test_year_string_to_int(self): Unit test for the year_string_to_int function. <|skeleton|> class Test: ...
f5bb1e51de4f84ab3dd62d3073aee4f56534afa1
<|skeleton|> class Test: def test_merge_by_year(self): """Unit test for the merge_by_year function.""" <|body_0|> def test_year_string_to_int(self): """Unit test for the year_string_to_int function.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Test: def test_merge_by_year(self): """Unit test for the merge_by_year function.""" merge_df = graph.merge_by_year(1807) self.assertEqual(['Country', 'Region', 'Income'], merge_df.columns.values.tolist()) self.assertEqual(merge_df.ix[0, 'Country'], 'Algeria') self.asser...
the_stack_v2_python_sparse
lj1035/package/test.py
ds-ga-1007/assignment9
train
2
79f1f9403e408b557a41330ebb7d2d08d8b3f800
[ "try:\n self.assertEqual(add(17, 23), 40)\nexcept Exception as error:\n print(error)", "try:\n self.assertEqual(add(-7, -11), -18)\nexcept Exception as error:\n print(error)", "try:\n self.assertEqual(add(0, 15), 15)\nexcept Exception as error:\n print(error)" ]
<|body_start_0|> try: self.assertEqual(add(17, 23), 40) except Exception as error: print(error) <|end_body_0|> <|body_start_1|> try: self.assertEqual(add(-7, -11), -18) except Exception as error: print(error) <|end_body_1|> <|body_start_2...
Test add function from calculation.py module.
TestAddFunction
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestAddFunction: """Test add function from calculation.py module.""" def test_add_all_args_greater_zero(self): """Test add function if all arguments are greater than zero.""" <|body_0|> def test_add_all_args_less_zero(self): """Test add function if all arguments ...
stack_v2_sparse_classes_10k_train_005343
1,838
no_license
[ { "docstring": "Test add function if all arguments are greater than zero.", "name": "test_add_all_args_greater_zero", "signature": "def test_add_all_args_greater_zero(self)" }, { "docstring": "Test add function if all arguments are less than zero.", "name": "test_add_all_args_less_zero", ...
3
stack_v2_sparse_classes_30k_train_005481
Implement the Python class `TestAddFunction` described below. Class description: Test add function from calculation.py module. Method signatures and docstrings: - def test_add_all_args_greater_zero(self): Test add function if all arguments are greater than zero. - def test_add_all_args_less_zero(self): Test add funct...
Implement the Python class `TestAddFunction` described below. Class description: Test add function from calculation.py module. Method signatures and docstrings: - def test_add_all_args_greater_zero(self): Test add function if all arguments are greater than zero. - def test_add_all_args_less_zero(self): Test add funct...
3a500c9d55fecf4032b5faf59a1cbecf64592e9a
<|skeleton|> class TestAddFunction: """Test add function from calculation.py module.""" def test_add_all_args_greater_zero(self): """Test add function if all arguments are greater than zero.""" <|body_0|> def test_add_all_args_less_zero(self): """Test add function if all arguments ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TestAddFunction: """Test add function from calculation.py module.""" def test_add_all_args_greater_zero(self): """Test add function if all arguments are greater than zero.""" try: self.assertEqual(add(17, 23), 40) except Exception as error: print(error) ...
the_stack_v2_python_sparse
python10/test_calculation.py
maksimok93/Dp-189
train
0
34eb3eabde4d8665502d141338d7b82776449095
[ "if len(s) == 0:\n return ''\nvowelsTable = ['a', 'A', 'i', 'I', 'e', 'E', 'o', 'O', 'u', 'U']\ntemp = []\nans = []\nvowels = []\nfor i in xrange(len(s)):\n if s[i] in vowelsTable:\n x = '~'\n vowels.append(s[i])\n else:\n x = s[i]\n temp.append(x)\nfor i in temp:\n if i == '~':\...
<|body_start_0|> if len(s) == 0: return '' vowelsTable = ['a', 'A', 'i', 'I', 'e', 'E', 'o', 'O', 'u', 'U'] temp = [] ans = [] vowels = [] for i in xrange(len(s)): if s[i] in vowelsTable: x = '~' vowels.append(s[i]) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseVowels(self, s): """:type s: str :rtype: str""" <|body_0|> def reverseVowels2(self, s): """:type s: str :rtype: str""" <|body_1|> def reverseVowels_2_ptr(self, s): """:type s: str :rtype: str""" <|body_2|> <|end_skel...
stack_v2_sparse_classes_10k_train_005344
2,402
no_license
[ { "docstring": ":type s: str :rtype: str", "name": "reverseVowels", "signature": "def reverseVowels(self, s)" }, { "docstring": ":type s: str :rtype: str", "name": "reverseVowels2", "signature": "def reverseVowels2(self, s)" }, { "docstring": ":type s: str :rtype: str", "name...
3
stack_v2_sparse_classes_30k_train_004310
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseVowels(self, s): :type s: str :rtype: str - def reverseVowels2(self, s): :type s: str :rtype: str - def reverseVowels_2_ptr(self, s): :type s: str :rtype: str
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseVowels(self, s): :type s: str :rtype: str - def reverseVowels2(self, s): :type s: str :rtype: str - def reverseVowels_2_ptr(self, s): :type s: str :rtype: str <|skele...
2d5fa4cd696d5035ea8859befeadc5cc436959c9
<|skeleton|> class Solution: def reverseVowels(self, s): """:type s: str :rtype: str""" <|body_0|> def reverseVowels2(self, s): """:type s: str :rtype: str""" <|body_1|> def reverseVowels_2_ptr(self, s): """:type s: str :rtype: str""" <|body_2|> <|end_skel...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def reverseVowels(self, s): """:type s: str :rtype: str""" if len(s) == 0: return '' vowelsTable = ['a', 'A', 'i', 'I', 'e', 'E', 'o', 'O', 'u', 'U'] temp = [] ans = [] vowels = [] for i in xrange(len(s)): if s[i] in vow...
the_stack_v2_python_sparse
SourceCode/Python/Problem/00345.Reverse_Vowels_of_a_String.py
roger6blog/LeetCode
train
0
7800f605df3594d34514037b2dc687591114871b
[ "def traverse(arr, start, path, seen):\n if len(path) >= 2 and path not in self.res and (path == sorted(path)):\n self.res.append(path[:])\n for i in range(start, len(arr)):\n if i not in seen:\n path.append(arr[i])\n seen.add(i)\n traverse(arr, i + 1, path, seen...
<|body_start_0|> def traverse(arr, start, path, seen): if len(path) >= 2 and path not in self.res and (path == sorted(path)): self.res.append(path[:]) for i in range(start, len(arr)): if i not in seen: path.append(arr[i]) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findSubsequences(self, nums: List[int]) -> List[List[int]]: """Purpose: Returns all different possible increasing subsequences of a given array with at least two elements. Note: Answer can be returned in any order.""" <|body_0|> def findSubsequences1(self, nums...
stack_v2_sparse_classes_10k_train_005345
1,854
no_license
[ { "docstring": "Purpose: Returns all different possible increasing subsequences of a given array with at least two elements. Note: Answer can be returned in any order.", "name": "findSubsequences", "signature": "def findSubsequences(self, nums: List[int]) -> List[List[int]]" }, { "docstring": "I...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findSubsequences(self, nums: List[int]) -> List[List[int]]: Purpose: Returns all different possible increasing subsequences of a given array with at least two elements. Note:...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findSubsequences(self, nums: List[int]) -> List[List[int]]: Purpose: Returns all different possible increasing subsequences of a given array with at least two elements. Note:...
95a86cbbca28d0c0f6d72d28a2f1cb5a86327934
<|skeleton|> class Solution: def findSubsequences(self, nums: List[int]) -> List[List[int]]: """Purpose: Returns all different possible increasing subsequences of a given array with at least two elements. Note: Answer can be returned in any order.""" <|body_0|> def findSubsequences1(self, nums...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def findSubsequences(self, nums: List[int]) -> List[List[int]]: """Purpose: Returns all different possible increasing subsequences of a given array with at least two elements. Note: Answer can be returned in any order.""" def traverse(arr, start, path, seen): if len(path)...
the_stack_v2_python_sparse
backtrackIncSubseq.py
tashakim/puzzles_python
train
8
444c933da2aa8a9ba07727fc24653096bed66861
[ "self.device = device\nself.conn_cmd = conn_cmd\nself.device.conn_cmd = conn_cmd", "bft_pexpect_helper.spawn.__init__(self.device, command='/bin/bash', args=['-c', self.conn_cmd])\ntry:\n result = self.device.expect(['assword:', 'ser2net.*\\r\\n', 'OpenGear Serial Server', 'to access the port escape menu'])\ne...
<|body_start_0|> self.device = device self.conn_cmd = conn_cmd self.device.conn_cmd = conn_cmd <|end_body_0|> <|body_start_1|> bft_pexpect_helper.spawn.__init__(self.device, command='/bin/bash', args=['-c', self.conn_cmd]) try: result = self.device.expect(['assword:'...
The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board.
Ser2NetConnection
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Ser2NetConnection: """The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board.""" def __init__(self, device=None, conn_cmd=None, **kwarg...
stack_v2_sparse_classes_10k_train_005346
2,190
permissive
[ { "docstring": "This method initializes the class instance to open a pexpect session. :param device: device to connect, defaults to None :type device: object :param conn_cmd: conn_cmd to connect to device, defaults to None :type conn_cmd: string :param **kwargs: args to be used :type **kwargs: dict", "name"...
3
stack_v2_sparse_classes_30k_train_001552
Implement the Python class `Ser2NetConnection` described below. Class description: The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board. Method signatures and ...
Implement the Python class `Ser2NetConnection` described below. Class description: The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board. Method signatures and ...
100521fde1fb67536682cafecc2f91a6e2e8a6f8
<|skeleton|> class Ser2NetConnection: """The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board.""" def __init__(self, device=None, conn_cmd=None, **kwarg...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Ser2NetConnection: """The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board.""" def __init__(self, device=None, conn_cmd=None, **kwargs): "...
the_stack_v2_python_sparse
boardfarm/devices/ser2net_connection.py
mattsm/boardfarm
train
45
9d4e352c6c1384e32d4fbdc8faa94da3bb24bb8c
[ "self.server_host = server_host\nself.password = password\nself.from_user = from_user\nself.to_user_list = to_user_list\nself.server = self._init_server()", "server = smtplib.SMTP(self.server_host, 25)\nserver.login(self.from_user, self.password)\nreturn server", "from_user_format = Header(str(self.from_user) +...
<|body_start_0|> self.server_host = server_host self.password = password self.from_user = from_user self.to_user_list = to_user_list self.server = self._init_server() <|end_body_0|> <|body_start_1|> server = smtplib.SMTP(self.server_host, 25) server.login(self.fr...
EmailUtil
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmailUtil: def __init__(self, server_host, password, from_user, to_user_list): """初始化发送邮件设置 :param server_host: 发送邮件的邮件服务器 :param password: 发送用户的密码 :param from_user: 发送邮件的用户邮箱 :param to_user_list: 接收邮件的用户邮箱列表""" <|body_0|> def _init_server(self): """邮件服务器初始化 :return:...
stack_v2_sparse_classes_10k_train_005347
1,955
permissive
[ { "docstring": "初始化发送邮件设置 :param server_host: 发送邮件的邮件服务器 :param password: 发送用户的密码 :param from_user: 发送邮件的用户邮箱 :param to_user_list: 接收邮件的用户邮箱列表", "name": "__init__", "signature": "def __init__(self, server_host, password, from_user, to_user_list)" }, { "docstring": "邮件服务器初始化 :return: 邮件服务器对象", ...
3
stack_v2_sparse_classes_30k_train_003156
Implement the Python class `EmailUtil` described below. Class description: Implement the EmailUtil class. Method signatures and docstrings: - def __init__(self, server_host, password, from_user, to_user_list): 初始化发送邮件设置 :param server_host: 发送邮件的邮件服务器 :param password: 发送用户的密码 :param from_user: 发送邮件的用户邮箱 :param to_user...
Implement the Python class `EmailUtil` described below. Class description: Implement the EmailUtil class. Method signatures and docstrings: - def __init__(self, server_host, password, from_user, to_user_list): 初始化发送邮件设置 :param server_host: 发送邮件的邮件服务器 :param password: 发送用户的密码 :param from_user: 发送邮件的用户邮箱 :param to_user...
ed360d5aa7f733991fbbc8ab5af96e739c9e1142
<|skeleton|> class EmailUtil: def __init__(self, server_host, password, from_user, to_user_list): """初始化发送邮件设置 :param server_host: 发送邮件的邮件服务器 :param password: 发送用户的密码 :param from_user: 发送邮件的用户邮箱 :param to_user_list: 接收邮件的用户邮箱列表""" <|body_0|> def _init_server(self): """邮件服务器初始化 :return:...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class EmailUtil: def __init__(self, server_host, password, from_user, to_user_list): """初始化发送邮件设置 :param server_host: 发送邮件的邮件服务器 :param password: 发送用户的密码 :param from_user: 发送邮件的用户邮箱 :param to_user_list: 接收邮件的用户邮箱列表""" self.server_host = server_host self.password = password self.from_...
the_stack_v2_python_sparse
automated_testing/requests_unittest_test/app/utils/EmailUtil.py
tzytammy/requests_unittest
train
0
15738df061286b930ffd74a960dab282029e65a7
[ "self = object.__new__(cls)\nself.name = cls.DEFAULT_NAME\nself.value = value\nself.max_per_guild = 1\nself.metadata_type = AutoModerationRuleTriggerMetadataBase\nreturn self", "self.value = value\nself.name = name\nself.max_per_guild = max_per_guild\nself.metadata_type = metadata_type\nself.INSTANCES[value] = se...
<|body_start_0|> self = object.__new__(cls) self.name = cls.DEFAULT_NAME self.value = value self.max_per_guild = 1 self.metadata_type = AutoModerationRuleTriggerMetadataBase return self <|end_body_0|> <|body_start_1|> self.value = value self.name = name ...
Represents an auto moderation rule's trigger type. Attributes ---------- value : `int` The Discord side identifier value of the auto moderation trigger type. name : `str` The default name of the auto moderation trigger type. max_per_guild : `int` The maximal amount of rules of this type per guild. metadata_type : `Auto...
AutoModerationRuleTriggerType
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AutoModerationRuleTriggerType: """Represents an auto moderation rule's trigger type. Attributes ---------- value : `int` The Discord side identifier value of the auto moderation trigger type. name : `str` The default name of the auto moderation trigger type. max_per_guild : `int` The maximal amou...
stack_v2_sparse_classes_10k_train_005348
7,201
permissive
[ { "docstring": "Creates a new auto moderation trigger type with the given value. Parameters ---------- value : `int` The auto moderation trigger type's identifier value. Returns ------- self : ``AutoModerationRuleTriggerType`` The created instance.", "name": "_from_value", "signature": "def _from_value(...
2
stack_v2_sparse_classes_30k_train_004355
Implement the Python class `AutoModerationRuleTriggerType` described below. Class description: Represents an auto moderation rule's trigger type. Attributes ---------- value : `int` The Discord side identifier value of the auto moderation trigger type. name : `str` The default name of the auto moderation trigger type....
Implement the Python class `AutoModerationRuleTriggerType` described below. Class description: Represents an auto moderation rule's trigger type. Attributes ---------- value : `int` The Discord side identifier value of the auto moderation trigger type. name : `str` The default name of the auto moderation trigger type....
53f24fdb38459dc5a4fd04f11bdbfee8295b76a4
<|skeleton|> class AutoModerationRuleTriggerType: """Represents an auto moderation rule's trigger type. Attributes ---------- value : `int` The Discord side identifier value of the auto moderation trigger type. name : `str` The default name of the auto moderation trigger type. max_per_guild : `int` The maximal amou...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class AutoModerationRuleTriggerType: """Represents an auto moderation rule's trigger type. Attributes ---------- value : `int` The Discord side identifier value of the auto moderation trigger type. name : `str` The default name of the auto moderation trigger type. max_per_guild : `int` The maximal amount of rules o...
the_stack_v2_python_sparse
hata/discord/auto_moderation/rule/preinstanced.py
HuyaneMatsu/hata
train
3
d5b4d11dedf2138bffd1c08e7f3cb0ff528c2f91
[ "self.p0 = p0\nself.p1 = p1\nself.p2 = p2\nself.p3 = p3", "\"\"\"\n Caso en que la coordenada \"y\" es igual a cero. \n \"\"\"\nif self.y == 0:\n '\\n Caso en que la coordenada \"x\" es mayor que cero. \\n '\n if checkSign(self.x) == 2:\n return 0\n '\\n ...
<|body_start_0|> self.p0 = p0 self.p1 = p1 self.p2 = p2 self.p3 = p3 <|end_body_0|> <|body_start_1|> """ Caso en que la coordenada "y" es igual a cero. """ if self.y == 0: '\n Caso en que la coordenada "x" es mayor ...
Face3d
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Face3d: def __init__(self, p0, p1, p2, p3): """@param p0: instancia de Point3d @param p1: instancia de Point3d @param p2: instancia de Point3d @param p3: instancia de Point3d""" <|body_0|> def Triangulate(self): """Metodo que se encarga de triangular una cara en el e...
stack_v2_sparse_classes_10k_train_005349
3,592
no_license
[ { "docstring": "@param p0: instancia de Point3d @param p1: instancia de Point3d @param p2: instancia de Point3d @param p3: instancia de Point3d", "name": "__init__", "signature": "def __init__(self, p0, p1, p2, p3)" }, { "docstring": "Metodo que se encarga de triangular una cara en el espacio 3D...
3
stack_v2_sparse_classes_30k_train_001892
Implement the Python class `Face3d` described below. Class description: Implement the Face3d class. Method signatures and docstrings: - def __init__(self, p0, p1, p2, p3): @param p0: instancia de Point3d @param p1: instancia de Point3d @param p2: instancia de Point3d @param p3: instancia de Point3d - def Triangulate(...
Implement the Python class `Face3d` described below. Class description: Implement the Face3d class. Method signatures and docstrings: - def __init__(self, p0, p1, p2, p3): @param p0: instancia de Point3d @param p1: instancia de Point3d @param p2: instancia de Point3d @param p3: instancia de Point3d - def Triangulate(...
a93de278ea92ad8d57d66fcb76744d394400bd11
<|skeleton|> class Face3d: def __init__(self, p0, p1, p2, p3): """@param p0: instancia de Point3d @param p1: instancia de Point3d @param p2: instancia de Point3d @param p3: instancia de Point3d""" <|body_0|> def Triangulate(self): """Metodo que se encarga de triangular una cara en el e...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Face3d: def __init__(self, p0, p1, p2, p3): """@param p0: instancia de Point3d @param p1: instancia de Point3d @param p2: instancia de Point3d @param p3: instancia de Point3d""" self.p0 = p0 self.p1 = p1 self.p2 = p2 self.p3 = p3 def Triangulate(self): """M...
the_stack_v2_python_sparse
geometry/controller/geometry_3d/face_3d.py
nvergarayi/Cubicador
train
0
5629ad020469bb4f0749842a5e0a615cc8c15d4c
[ "Frame.__init__(self, master)\nself.pack()\nself.createAlbumWidgets()", "top_frame = Frame(self)\nself.labelInput = Label(top_frame, text='Album Name')\nself.text_in = Entry(top_frame)\nself.labelResult = Label(top_frame, text='Result')\nself.labelInput.pack()\nself.text_in.pack()\nself.labelResult.pack()\ntop_fr...
<|body_start_0|> Frame.__init__(self, master) self.pack() self.createAlbumWidgets() <|end_body_0|> <|body_start_1|> top_frame = Frame(self) self.labelInput = Label(top_frame, text='Album Name') self.text_in = Entry(top_frame) self.labelResult = Label(top_frame, t...
Application main window class.
getAlbum_UI
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class getAlbum_UI: """Application main window class.""" def __init__(self, master=None): """Main frame initialization (mostly delegated)""" <|body_0|> def createAlbumWidgets(self): """Add all the widgets to the main frame.""" <|body_1|> def handle(self): ...
stack_v2_sparse_classes_10k_train_005350
10,077
no_license
[ { "docstring": "Main frame initialization (mostly delegated)", "name": "__init__", "signature": "def __init__(self, master=None)" }, { "docstring": "Add all the widgets to the main frame.", "name": "createAlbumWidgets", "signature": "def createAlbumWidgets(self)" }, { "docstring"...
3
stack_v2_sparse_classes_30k_val_000194
Implement the Python class `getAlbum_UI` described below. Class description: Application main window class. Method signatures and docstrings: - def __init__(self, master=None): Main frame initialization (mostly delegated) - def createAlbumWidgets(self): Add all the widgets to the main frame. - def handle(self): Handl...
Implement the Python class `getAlbum_UI` described below. Class description: Application main window class. Method signatures and docstrings: - def __init__(self, master=None): Main frame initialization (mostly delegated) - def createAlbumWidgets(self): Add all the widgets to the main frame. - def handle(self): Handl...
2dba11861f91e4bdc1ef28279132a6d8dd4ccf54
<|skeleton|> class getAlbum_UI: """Application main window class.""" def __init__(self, master=None): """Main frame initialization (mostly delegated)""" <|body_0|> def createAlbumWidgets(self): """Add all the widgets to the main frame.""" <|body_1|> def handle(self): ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class getAlbum_UI: """Application main window class.""" def __init__(self, master=None): """Main frame initialization (mostly delegated)""" Frame.__init__(self, master) self.pack() self.createAlbumWidgets() def createAlbumWidgets(self): """Add all the widgets to the...
the_stack_v2_python_sparse
Mux_src/Fix_All_Music_Guis.py
rduvalwa5/Mux
train
0
ce98243afa4fc7e5ce7810748beff8c2a791c298
[ "if surface is not None:\n self.t = surface.index\n assert np.all(self.t == profile.index.unique())\n self.surface = surface\nelse:\n self.t = profile.index.unique()\n self.surface = pd.DataFrame(index=self.t)\nself.z = profile['z'].unique()\nself.info = info\nself.N = len(self.z)\nself.info['levels'...
<|body_start_0|> if surface is not None: self.t = surface.index assert np.all(self.t == profile.index.unique()) self.surface = surface else: self.t = profile.index.unique() self.surface = pd.DataFrame(index=self.t) self.z = profile['z']...
MMCdata
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MMCdata: def __init__(self, profile, surface, info, na_values=-999.0): """Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns corresponding to the data arrays described above; a 'z' column describes the height AGL. surface: p...
stack_v2_sparse_classes_10k_train_005351
6,740
no_license
[ { "docstring": "Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns corresponding to the data arrays described above; a 'z' column describes the height AGL. surface: pandas.DataFrame, optional Dataframe with datetime index and columns corresponding ...
3
stack_v2_sparse_classes_30k_train_000795
Implement the Python class `MMCdata` described below. Class description: Implement the MMCdata class. Method signatures and docstrings: - def __init__(self, profile, surface, info, na_values=-999.0): Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns cor...
Implement the Python class `MMCdata` described below. Class description: Implement the MMCdata class. Method signatures and docstrings: - def __init__(self, profile, surface, info, na_values=-999.0): Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns cor...
c34afb2a13fc0075f95a43bac99219b25b3984a2
<|skeleton|> class MMCdata: def __init__(self, profile, surface, info, na_values=-999.0): """Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns corresponding to the data arrays described above; a 'z' column describes the height AGL. surface: p...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MMCdata: def __init__(self, profile, surface, info, na_values=-999.0): """Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns corresponding to the data arrays described above; a 'z' column describes the height AGL. surface: pandas.DataFram...
the_stack_v2_python_sparse
MMC/output_profile.py
ewquon/pylib
train
2
e84cbe88cb65b7ae6709666f376c9453d867f726
[ "super().__init__(reduction=reduction, name='fenchel_young')\nself._batched = batched\nself._maximize = maximize\nself.func = func\nself.perturbed = perturbations.perturbed(func=func, num_samples=num_samples, sigma=sigma, noise=noise, batched=batched)", "@tf.custom_gradient\ndef forward(theta):\n diff = self.p...
<|body_start_0|> super().__init__(reduction=reduction, name='fenchel_young') self._batched = batched self._maximize = maximize self.func = func self.perturbed = perturbations.perturbed(func=func, num_samples=num_samples, sigma=sigma, noise=noise, batched=batched) <|end_body_0|> ...
Implementation of a Fenchel Young loss.
FenchelYoungLoss
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FenchelYoungLoss: """Implementation of a Fenchel Young loss.""" def __init__(self, func=None, num_samples=1000, sigma=0.01, noise=perturbations._NORMAL, batched=True, maximize=True, reduction=tf.keras.losses.Reduction.SUM): """Initializes the Fenchel-Young loss. Args: func: the funct...
stack_v2_sparse_classes_10k_train_005352
3,623
permissive
[ { "docstring": "Initializes the Fenchel-Young loss. Args: func: the function whose argmax is to be differentiated by perturbation. num_samples: (int) the number of perturbed inputs. sigma: (float) the amount of noise to be considered noise: (str) the noise distribution to be used to sample perturbations. batche...
2
stack_v2_sparse_classes_30k_train_004255
Implement the Python class `FenchelYoungLoss` described below. Class description: Implementation of a Fenchel Young loss. Method signatures and docstrings: - def __init__(self, func=None, num_samples=1000, sigma=0.01, noise=perturbations._NORMAL, batched=True, maximize=True, reduction=tf.keras.losses.Reduction.SUM): ...
Implement the Python class `FenchelYoungLoss` described below. Class description: Implementation of a Fenchel Young loss. Method signatures and docstrings: - def __init__(self, func=None, num_samples=1000, sigma=0.01, noise=perturbations._NORMAL, batched=True, maximize=True, reduction=tf.keras.losses.Reduction.SUM): ...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class FenchelYoungLoss: """Implementation of a Fenchel Young loss.""" def __init__(self, func=None, num_samples=1000, sigma=0.01, noise=perturbations._NORMAL, batched=True, maximize=True, reduction=tf.keras.losses.Reduction.SUM): """Initializes the Fenchel-Young loss. Args: func: the funct...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class FenchelYoungLoss: """Implementation of a Fenchel Young loss.""" def __init__(self, func=None, num_samples=1000, sigma=0.01, noise=perturbations._NORMAL, batched=True, maximize=True, reduction=tf.keras.losses.Reduction.SUM): """Initializes the Fenchel-Young loss. Args: func: the function whose arg...
the_stack_v2_python_sparse
perturbations/fenchel_young.py
Jimmy-INL/google-research
train
1
9d9a710003f6c1d85d64fb7af652826307c50ef9
[ "if isinstance(value, collections.abc.Iterable):\n return numpy.ones_like(value, dtype=numpy.bool_)\nelse:\n return True", "data = None if data is None else numpy.array(data, copy=False)\nif data is None or data.size == 0:\n return self.DEFAULT_RANGE\nif mode == 'minmax':\n vmin, vmax = self.autoscale...
<|body_start_0|> if isinstance(value, collections.abc.Iterable): return numpy.ones_like(value, dtype=numpy.bool_) else: return True <|end_body_0|> <|body_start_1|> data = None if data is None else numpy.array(data, copy=False) if data is None or data.size == 0: ...
Colormap normalization mix-in class
_NormalizationMixIn
[ "MIT", "LicenseRef-scancode-public-domain-disclaimer", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _NormalizationMixIn: """Colormap normalization mix-in class""" def is_valid(self, value): """Check if a value is in the valid range for this normalization. Override in subclass. :param Union[float,numpy.ndarray] value: :rtype: Union[bool,numpy.ndarray]""" <|body_0|> def ...
stack_v2_sparse_classes_10k_train_005353
16,802
permissive
[ { "docstring": "Check if a value is in the valid range for this normalization. Override in subclass. :param Union[float,numpy.ndarray] value: :rtype: Union[bool,numpy.ndarray]", "name": "is_valid", "signature": "def is_valid(self, value)" }, { "docstring": "Returns range for given data and autos...
4
null
Implement the Python class `_NormalizationMixIn` described below. Class description: Colormap normalization mix-in class Method signatures and docstrings: - def is_valid(self, value): Check if a value is in the valid range for this normalization. Override in subclass. :param Union[float,numpy.ndarray] value: :rtype: ...
Implement the Python class `_NormalizationMixIn` described below. Class description: Colormap normalization mix-in class Method signatures and docstrings: - def is_valid(self, value): Check if a value is in the valid range for this normalization. Override in subclass. :param Union[float,numpy.ndarray] value: :rtype: ...
5e33cb69afd2a8b1cfe3183282acdd8b34c1a74f
<|skeleton|> class _NormalizationMixIn: """Colormap normalization mix-in class""" def is_valid(self, value): """Check if a value is in the valid range for this normalization. Override in subclass. :param Union[float,numpy.ndarray] value: :rtype: Union[bool,numpy.ndarray]""" <|body_0|> def ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class _NormalizationMixIn: """Colormap normalization mix-in class""" def is_valid(self, value): """Check if a value is in the valid range for this normalization. Override in subclass. :param Union[float,numpy.ndarray] value: :rtype: Union[bool,numpy.ndarray]""" if isinstance(value, collections....
the_stack_v2_python_sparse
src/silx/math/colormap.py
silx-kit/silx
train
120
0ebc8acedc20dab13f0f55b1fb2a72636170567f
[ "self.session = session\nsuper().__init__(cmdlist)\nself.sighandle = self.session.sighandle\nfor cmd in cmdlist:\n cmdname = cmd.__name__.lower()\n cmdinst = getattr(self, cmdname)\n cmdinst.sighandle = self.sighandle\nself.session_lock_string = ''", "self.mem_handle = self.session.mem_handle\nself.cmdlo...
<|body_start_0|> self.session = session super().__init__(cmdlist) self.sighandle = self.session.sighandle for cmd in cmdlist: cmdname = cmd.__name__.lower() cmdinst = getattr(self, cmdname) cmdinst.sighandle = self.sighandle self.session_lock_s...
@brief Overloading the logging functions and user input methods to allow for interactions through the web GUI
GUIcontrolterm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GUIcontrolterm: """@brief Overloading the logging functions and user input methods to allow for interactions through the web GUI""" def __init__(self, cmdlist, session, **kwargs): """User action prompts requires a reference to the socketio interface""" <|body_0|> def ini...
stack_v2_sparse_classes_10k_train_005354
16,012
no_license
[ { "docstring": "User action prompts requires a reference to the socketio interface", "name": "__init__", "signature": "def __init__(self, cmdlist, session, **kwargs)" }, { "docstring": "@brief Overloading the settings for the logger instances. @details Additional settings for the memory settings...
3
stack_v2_sparse_classes_30k_train_000638
Implement the Python class `GUIcontrolterm` described below. Class description: @brief Overloading the logging functions and user input methods to allow for interactions through the web GUI Method signatures and docstrings: - def __init__(self, cmdlist, session, **kwargs): User action prompts requires a reference to ...
Implement the Python class `GUIcontrolterm` described below. Class description: @brief Overloading the logging functions and user input methods to allow for interactions through the web GUI Method signatures and docstrings: - def __init__(self, cmdlist, session, **kwargs): User action prompts requires a reference to ...
592a21b2361969faab075f31cc70e1fc05af7fd1
<|skeleton|> class GUIcontrolterm: """@brief Overloading the logging functions and user input methods to allow for interactions through the web GUI""" def __init__(self, cmdlist, session, **kwargs): """User action prompts requires a reference to the socketio interface""" <|body_0|> def ini...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GUIcontrolterm: """@brief Overloading the logging functions and user input methods to allow for interactions through the web GUI""" def __init__(self, cmdlist, session, **kwargs): """User action prompts requires a reference to the socketio interface""" self.session = session super...
the_stack_v2_python_sparse
server/session.py
yimuchen/SiPMCalibControl
train
0
8c9f11bf8c5da7f13b577e1eb7ace6f51bf87516
[ "inv.Inventory.__init__(self, item_code, description, market_price, rental_price)\nself.material = material\nself.size = size", "output_dict = {}\noutput_dict['item_code'] = self.item_code\noutput_dict['description'] = self.description\noutput_dict['market_price'] = self.market_price\noutput_dict['rental_price'] ...
<|body_start_0|> inv.Inventory.__init__(self, item_code, description, market_price, rental_price) self.material = material self.size = size <|end_body_0|> <|body_start_1|> output_dict = {} output_dict['item_code'] = self.item_code output_dict['description'] = self.descri...
Contains class methods and attributes for furniture items.
Furniture
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Furniture: """Contains class methods and attributes for furniture items.""" def __init__(self, item_code, description, market_price, rental_price, material, size): """Creates furniture item.""" <|body_0|> def return_as_dictionary(self): """Return furniture item i...
stack_v2_sparse_classes_10k_train_005355
1,070
no_license
[ { "docstring": "Creates furniture item.", "name": "__init__", "signature": "def __init__(self, item_code, description, market_price, rental_price, material, size)" }, { "docstring": "Return furniture item information as a dictionary.", "name": "return_as_dictionary", "signature": "def re...
2
stack_v2_sparse_classes_30k_train_002489
Implement the Python class `Furniture` described below. Class description: Contains class methods and attributes for furniture items. Method signatures and docstrings: - def __init__(self, item_code, description, market_price, rental_price, material, size): Creates furniture item. - def return_as_dictionary(self): Re...
Implement the Python class `Furniture` described below. Class description: Contains class methods and attributes for furniture items. Method signatures and docstrings: - def __init__(self, item_code, description, market_price, rental_price, material, size): Creates furniture item. - def return_as_dictionary(self): Re...
5dac60f39e3909ff05b26721d602ed20f14d6be3
<|skeleton|> class Furniture: """Contains class methods and attributes for furniture items.""" def __init__(self, item_code, description, market_price, rental_price, material, size): """Creates furniture item.""" <|body_0|> def return_as_dictionary(self): """Return furniture item i...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Furniture: """Contains class methods and attributes for furniture items.""" def __init__(self, item_code, description, market_price, rental_price, material, size): """Creates furniture item.""" inv.Inventory.__init__(self, item_code, description, market_price, rental_price) self.m...
the_stack_v2_python_sparse
students/alexander_boone/lesson01/assignment/inventory_management/furniture_class.py
JavaRod/SP_Python220B_2019
train
1
9b47e728a7d3d53fe94ca8d616f41a45c4d59fd9
[ "super(AutomaticWeightedLoss, self).__init__()\nself.mode = mode\nif self.mode not in ['cls', 'reg']:\n raise ValueError('mode argument must be cls or reg.')\nparams = torch.ones(num, requires_grad=True)\nself.params = torch.nn.Parameter(params)", "loss_sum = 0\nloss_num = len(x)\nfor i, loss in enumerate(x):\...
<|body_start_0|> super(AutomaticWeightedLoss, self).__init__() self.mode = mode if self.mode not in ['cls', 'reg']: raise ValueError('mode argument must be cls or reg.') params = torch.ones(num, requires_grad=True) self.params = torch.nn.Parameter(params) <|end_body_0...
automatically weighted multi-task(classification task) loss Examples: loss1=1 loss2=2 awl = AutomaticWeightedLoss(2) loss_sum = awl(loss1, loss2)
AutomaticWeightedLoss
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AutomaticWeightedLoss: """automatically weighted multi-task(classification task) loss Examples: loss1=1 loss2=2 awl = AutomaticWeightedLoss(2) loss_sum = awl(loss1, loss2)""" def __init__(self, num=2, mode='cls'): """Args: num (int, optional): the number of loss. Defaults to 2. mode ...
stack_v2_sparse_classes_10k_train_005356
1,891
permissive
[ { "docstring": "Args: num (int, optional): the number of loss. Defaults to 2. mode (str, optional): 'cls' for classification multi-task, 'reg' for regression multi-task. Defaults to 'cls'.", "name": "__init__", "signature": "def __init__(self, num=2, mode='cls')" }, { "docstring": "[summary] Arg...
2
stack_v2_sparse_classes_30k_train_000576
Implement the Python class `AutomaticWeightedLoss` described below. Class description: automatically weighted multi-task(classification task) loss Examples: loss1=1 loss2=2 awl = AutomaticWeightedLoss(2) loss_sum = awl(loss1, loss2) Method signatures and docstrings: - def __init__(self, num=2, mode='cls'): Args: num ...
Implement the Python class `AutomaticWeightedLoss` described below. Class description: automatically weighted multi-task(classification task) loss Examples: loss1=1 loss2=2 awl = AutomaticWeightedLoss(2) loss_sum = awl(loss1, loss2) Method signatures and docstrings: - def __init__(self, num=2, mode='cls'): Args: num ...
b4c049fd30db39b67984edfadc49b4354d52be83
<|skeleton|> class AutomaticWeightedLoss: """automatically weighted multi-task(classification task) loss Examples: loss1=1 loss2=2 awl = AutomaticWeightedLoss(2) loss_sum = awl(loss1, loss2)""" def __init__(self, num=2, mode='cls'): """Args: num (int, optional): the number of loss. Defaults to 2. mode ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class AutomaticWeightedLoss: """automatically weighted multi-task(classification task) loss Examples: loss1=1 loss2=2 awl = AutomaticWeightedLoss(2) loss_sum = awl(loss1, loss2)""" def __init__(self, num=2, mode='cls'): """Args: num (int, optional): the number of loss. Defaults to 2. mode (str, optiona...
the_stack_v2_python_sparse
pasaie/losses/autoweighted_loss.py
tracy-talent/AIPolicy
train
0
a7b71c941db485bfa8b423f413a785dfb4fd4da2
[ "versions = []\nfor key, data in VERSIONS.items():\n v = BaseVersion(data['id'], data['status'], request.application_url, data['updated'])\n versions.append(v)\nreturn wsgi.Result(VersionsDataView(versions))", "data = VERSIONS[request.url_version]\nv = Version(data['id'], data['status'], request.application...
<|body_start_0|> versions = [] for key, data in VERSIONS.items(): v = BaseVersion(data['id'], data['status'], request.application_url, data['updated']) versions.append(v) return wsgi.Result(VersionsDataView(versions)) <|end_body_0|> <|body_start_1|> data = VERSIO...
VersionsController
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VersionsController: def index(self, request): """Respond to a request for API versions.""" <|body_0|> def show(self, request): """Respond to a request for a specific API version.""" <|body_1|> <|end_skeleton|> <|body_start_0|> versions = [] ...
stack_v2_sparse_classes_10k_train_005357
3,164
permissive
[ { "docstring": "Respond to a request for API versions.", "name": "index", "signature": "def index(self, request)" }, { "docstring": "Respond to a request for a specific API version.", "name": "show", "signature": "def show(self, request)" } ]
2
null
Implement the Python class `VersionsController` described below. Class description: Implement the VersionsController class. Method signatures and docstrings: - def index(self, request): Respond to a request for API versions. - def show(self, request): Respond to a request for a specific API version.
Implement the Python class `VersionsController` described below. Class description: Implement the VersionsController class. Method signatures and docstrings: - def index(self, request): Respond to a request for API versions. - def show(self, request): Respond to a request for a specific API version. <|skeleton|> cla...
4288b8f78250cc3a1c93b019e2c3b4bf78df177c
<|skeleton|> class VersionsController: def index(self, request): """Respond to a request for API versions.""" <|body_0|> def show(self, request): """Respond to a request for a specific API version.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class VersionsController: def index(self, request): """Respond to a request for API versions.""" versions = [] for key, data in VERSIONS.items(): v = BaseVersion(data['id'], data['status'], request.application_url, data['updated']) versions.append(v) return ws...
the_stack_v2_python_sparse
trove/versions.py
openstack/trove
train
258
26f1b91faa9f85f22214419e9e526798dee252e7
[ "cache = {}\n\ndef dfs(n, rpl):\n if n in cache:\n return cache[n]\n if n == 1:\n return rpl\n if n & 1:\n temp = 1 + min(dfs(n + 1, rpl), dfs(n - 1, rpl))\n else:\n temp = 1 + dfs(n // 2, rpl)\n cache[n] = temp\n return temp\nreturn dfs(n, 0)", "res = 0\nwhile n > 1:...
<|body_start_0|> cache = {} def dfs(n, rpl): if n in cache: return cache[n] if n == 1: return rpl if n & 1: temp = 1 + min(dfs(n + 1, rpl), dfs(n - 1, rpl)) else: temp = 1 + dfs(n // 2, rpl) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def integerReplacement(self, n): """:type n: int :rtype: int""" <|body_0|> def integerReplacement2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> cache = {} def dfs(n, rpl): if n ...
stack_v2_sparse_classes_10k_train_005358
899
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "integerReplacement", "signature": "def integerReplacement(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "integerReplacement2", "signature": "def integerReplacement2(self, n)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def integerReplacement(self, n): :type n: int :rtype: int - def integerReplacement2(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def integerReplacement(self, n): :type n: int :rtype: int - def integerReplacement2(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def integerReplacement(s...
dbdb227e12f329e4ca064b338f1fbdca42f3a848
<|skeleton|> class Solution: def integerReplacement(self, n): """:type n: int :rtype: int""" <|body_0|> def integerReplacement2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def integerReplacement(self, n): """:type n: int :rtype: int""" cache = {} def dfs(n, rpl): if n in cache: return cache[n] if n == 1: return rpl if n & 1: temp = 1 + min(dfs(n + 1, rpl), dfs(...
the_stack_v2_python_sparse
LC397.py
Qiao-Liang/LeetCode
train
0
8f4a9be4611d012c6f8a05fe6183fda335c322e5
[ "self.nums = nums\nself.dicts = {}\n\ndef dfs(start, end):\n if start > end:\n return 0\n if (start, end) in self.dicts.keys():\n return self.dicts[start, end]\n if start == end:\n self.dicts[start, end] = self.nums[start]\n return self.nums[start]\n else:\n a = dfs(st...
<|body_start_0|> self.nums = nums self.dicts = {} def dfs(start, end): if start > end: return 0 if (start, end) in self.dicts.keys(): return self.dicts[start, end] if start == end: self.dicts[start, end] = self....
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def PredictTheWinner(self, nums): """:type nums: List[int] :rtype: bool 62ms""" <|body_0|> def PredictTheWinner_1(self, nums): """:type nums: List[int] :rtype: bool 32ms""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.nums = nums ...
stack_v2_sparse_classes_10k_train_005359
2,954
no_license
[ { "docstring": ":type nums: List[int] :rtype: bool 62ms", "name": "PredictTheWinner", "signature": "def PredictTheWinner(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: bool 32ms", "name": "PredictTheWinner_1", "signature": "def PredictTheWinner_1(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_002177
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def PredictTheWinner(self, nums): :type nums: List[int] :rtype: bool 62ms - def PredictTheWinner_1(self, nums): :type nums: List[int] :rtype: bool 32ms
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def PredictTheWinner(self, nums): :type nums: List[int] :rtype: bool 62ms - def PredictTheWinner_1(self, nums): :type nums: List[int] :rtype: bool 32ms <|skeleton|> class Soluti...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution: def PredictTheWinner(self, nums): """:type nums: List[int] :rtype: bool 62ms""" <|body_0|> def PredictTheWinner_1(self, nums): """:type nums: List[int] :rtype: bool 32ms""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def PredictTheWinner(self, nums): """:type nums: List[int] :rtype: bool 62ms""" self.nums = nums self.dicts = {} def dfs(start, end): if start > end: return 0 if (start, end) in self.dicts.keys(): return self.di...
the_stack_v2_python_sparse
PredictTheWinner_MID_486.py
953250587/leetcode-python
train
2
d1996d89dfe707a7f259692889eb85139eaa28d0
[ "ans = []\nfrom collections import deque\nqueue = deque()\nfor i in range(len(nums)):\n while queue and queue[0] < i - k + 1:\n queue.popleft()\n while queue and nums[i] > nums[queue[-1]]:\n queue.pop()\n queue.append(i)\n if i >= k - 1:\n ans.append(nums[queue[0]])\nreturn ans", ...
<|body_start_0|> ans = [] from collections import deque queue = deque() for i in range(len(nums)): while queue and queue[0] < i - k + 1: queue.popleft() while queue and nums[i] > nums[queue[-1]]: queue.pop() queue.append...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxSlidingWindow(self, nums, k): """Disscussion Method 算法:单调双向队列 思路: 和单调栈类似,单调栈是栈内元素保持某种单调性,单调双向队列是队列内保持某种单调性,然后由于本题的背景, 所以使用双向队列 首先要明确➡️单调队列保持队列内有序 用一个单调队列来记录遍历过的值的下标 比如1,3,2,0遍历到3的时候,由于3进来后,前面比3小的元素一定不可能是目标的元素,所以将其弹出,而遍历 到2的时候,2不大于3,并且不知道2后面的元素会不会比2更小,也就是2可能是一个候选的最大值,所以入队...
stack_v2_sparse_classes_10k_train_005360
3,046
no_license
[ { "docstring": "Disscussion Method 算法:单调双向队列 思路: 和单调栈类似,单调栈是栈内元素保持某种单调性,单调双向队列是队列内保持某种单调性,然后由于本题的背景, 所以使用双向队列 首先要明确➡️单调队列保持队列内有序 用一个单调队列来记录遍历过的值的下标 比如1,3,2,0遍历到3的时候,由于3进来后,前面比3小的元素一定不可能是目标的元素,所以将其弹出,而遍历 到2的时候,2不大于3,并且不知道2后面的元素会不会比2更小,也就是2可能是一个候选的最大值,所以入队列。如此 一来便可以在遍历到第i个元素时确认这个元素的留存状态,即它大于队列尾元素,队列尾弹出,然后第i元素入队列。...
2
stack_v2_sparse_classes_30k_val_000292
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSlidingWindow(self, nums, k): Disscussion Method 算法:单调双向队列 思路: 和单调栈类似,单调栈是栈内元素保持某种单调性,单调双向队列是队列内保持某种单调性,然后由于本题的背景, 所以使用双向队列 首先要明确➡️单调队列保持队列内有序 用一个单调队列来记录遍历过的值的下标 比如1,3,2,0...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSlidingWindow(self, nums, k): Disscussion Method 算法:单调双向队列 思路: 和单调栈类似,单调栈是栈内元素保持某种单调性,单调双向队列是队列内保持某种单调性,然后由于本题的背景, 所以使用双向队列 首先要明确➡️单调队列保持队列内有序 用一个单调队列来记录遍历过的值的下标 比如1,3,2,0...
a1c074ff0d542f7ef0e5e01e280b16e52fa7a33d
<|skeleton|> class Solution: def maxSlidingWindow(self, nums, k): """Disscussion Method 算法:单调双向队列 思路: 和单调栈类似,单调栈是栈内元素保持某种单调性,单调双向队列是队列内保持某种单调性,然后由于本题的背景, 所以使用双向队列 首先要明确➡️单调队列保持队列内有序 用一个单调队列来记录遍历过的值的下标 比如1,3,2,0遍历到3的时候,由于3进来后,前面比3小的元素一定不可能是目标的元素,所以将其弹出,而遍历 到2的时候,2不大于3,并且不知道2后面的元素会不会比2更小,也就是2可能是一个候选的最大值,所以入队...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def maxSlidingWindow(self, nums, k): """Disscussion Method 算法:单调双向队列 思路: 和单调栈类似,单调栈是栈内元素保持某种单调性,单调双向队列是队列内保持某种单调性,然后由于本题的背景, 所以使用双向队列 首先要明确➡️单调队列保持队列内有序 用一个单调队列来记录遍历过的值的下标 比如1,3,2,0遍历到3的时候,由于3进来后,前面比3小的元素一定不可能是目标的元素,所以将其弹出,而遍历 到2的时候,2不大于3,并且不知道2后面的元素会不会比2更小,也就是2可能是一个候选的最大值,所以入队列。如此 一来便可以在遍历到...
the_stack_v2_python_sparse
239_Sliding Window Maximum.py
xhwupup/xhw_project
train
0
c41d30eab0f767478cf32aa263c7a3335ca48226
[ "tax_amount = 0\nself.tax_amount = tax_amount\nself.amount_with_tax = self.amount_without_tax + tax_amount", "res = super(sale_anticipated_invoice, self).default_get(fields_list=fields_list)\nsale_id = self.env.context.get('active_id')\nif sale_id and self.env.context.get('active_model') == 'sale.order':\n res...
<|body_start_0|> tax_amount = 0 self.tax_amount = tax_amount self.amount_with_tax = self.amount_without_tax + tax_amount <|end_body_0|> <|body_start_1|> res = super(sale_anticipated_invoice, self).default_get(fields_list=fields_list) sale_id = self.env.context.get('active_id') ...
Wizard to create an anticipated invoice from the sale
sale_anticipated_invoice
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class sale_anticipated_invoice: """Wizard to create an anticipated invoice from the sale""" def _compute_amount_with_tax(self): """Calcul du montant total avec les taxes""" <|body_0|> def default_get(self, fields_list): """Surcharge afin de récupérer la vente pour laqu...
stack_v2_sparse_classes_10k_train_005361
7,286
no_license
[ { "docstring": "Calcul du montant total avec les taxes", "name": "_compute_amount_with_tax", "signature": "def _compute_amount_with_tax(self)" }, { "docstring": "Surcharge afin de récupérer la vente pour laquelle on effectue la facture anticipée", "name": "default_get", "signature": "def...
5
stack_v2_sparse_classes_30k_train_000477
Implement the Python class `sale_anticipated_invoice` described below. Class description: Wizard to create an anticipated invoice from the sale Method signatures and docstrings: - def _compute_amount_with_tax(self): Calcul du montant total avec les taxes - def default_get(self, fields_list): Surcharge afin de récupér...
Implement the Python class `sale_anticipated_invoice` described below. Class description: Wizard to create an anticipated invoice from the sale Method signatures and docstrings: - def _compute_amount_with_tax(self): Calcul du montant total avec les taxes - def default_get(self, fields_list): Surcharge afin de récupér...
eb394e1f79ba1995da2dcd81adfdd511c22caff9
<|skeleton|> class sale_anticipated_invoice: """Wizard to create an anticipated invoice from the sale""" def _compute_amount_with_tax(self): """Calcul du montant total avec les taxes""" <|body_0|> def default_get(self, fields_list): """Surcharge afin de récupérer la vente pour laqu...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class sale_anticipated_invoice: """Wizard to create an anticipated invoice from the sale""" def _compute_amount_with_tax(self): """Calcul du montant total avec les taxes""" tax_amount = 0 self.tax_amount = tax_amount self.amount_with_tax = self.amount_without_tax + tax_amount ...
the_stack_v2_python_sparse
OpenPROD/openprod-addons/sale/wizard/anticipated_invoice.py
kazacube-mziouadi/ceci
train
0
463ef791225c225cde13a3c88c80e1896fce1606
[ "data = {'id': str(user_id), 'first_name': '', 'last_name': '', 'fullname': '', 'email': '', 'internal': False}\ntry:\n _ = UUID(user_id)\nexcept (ValueError, AttributeError):\n logger.error(f'Actor id is not a valid UUID: {user_id}')\nelse:\n if user_id == SystemUser.id:\n raw_data = SystemUser\n ...
<|body_start_0|> data = {'id': str(user_id), 'first_name': '', 'last_name': '', 'fullname': '', 'email': '', 'internal': False} try: _ = UUID(user_id) except (ValueError, AttributeError): logger.error(f'Actor id is not a valid UUID: {user_id}') else: i...
Stub implementation of the IUserProfileQuery interface.
BaseUserProfileQuery
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseUserProfileQuery: """Stub implementation of the IUserProfileQuery interface.""" def get_data(self, user_id: str) -> dict: """Get a map with user data.""" <|body_0|> def update_wf_history(self, state_history: list) -> list: """Update workflow history with user...
stack_v2_sparse_classes_10k_train_005362
1,795
no_license
[ { "docstring": "Get a map with user data.", "name": "get_data", "signature": "def get_data(self, user_id: str) -> dict" }, { "docstring": "Update workflow history with user data.", "name": "update_wf_history", "signature": "def update_wf_history(self, state_history: list) -> list" } ]
2
stack_v2_sparse_classes_30k_train_003023
Implement the Python class `BaseUserProfileQuery` described below. Class description: Stub implementation of the IUserProfileQuery interface. Method signatures and docstrings: - def get_data(self, user_id: str) -> dict: Get a map with user data. - def update_wf_history(self, state_history: list) -> list: Update workf...
Implement the Python class `BaseUserProfileQuery` described below. Class description: Stub implementation of the IUserProfileQuery interface. Method signatures and docstrings: - def get_data(self, user_id: str) -> dict: Get a map with user data. - def update_wf_history(self, state_history: list) -> list: Update workf...
0f27d5de4b04fe1d0ce2c2c9ccd3f2893b833128
<|skeleton|> class BaseUserProfileQuery: """Stub implementation of the IUserProfileQuery interface.""" def get_data(self, user_id: str) -> dict: """Get a map with user data.""" <|body_0|> def update_wf_history(self, state_history: list) -> list: """Update workflow history with user...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class BaseUserProfileQuery: """Stub implementation of the IUserProfileQuery interface.""" def get_data(self, user_id: str) -> dict: """Get a map with user data.""" data = {'id': str(user_id), 'first_name': '', 'last_name': '', 'fullname': '', 'email': '', 'internal': False} try: ...
the_stack_v2_python_sparse
src/briefy/common/utilities/userprofile.py
BriefyHQ/briefy.common
train
0
d899a9406e323751205c9405d8c20b1af8791ea9
[ "self.email_addresses = email_addresses\nself.email_delivery_targets = email_delivery_targets\nself.raise_object_level_failure_alert = raise_object_level_failure_alert", "if dictionary is None:\n return None\nemail_addresses = dictionary.get('emailAddresses')\nemail_delivery_targets = None\nif dictionary.get('...
<|body_start_0|> self.email_addresses = email_addresses self.email_delivery_targets = email_delivery_targets self.raise_object_level_failure_alert = raise_object_level_failure_alert <|end_body_0|> <|body_start_1|> if dictionary is None: return None email_addresses = ...
Implementation of the 'AlertingConfig' model. Specifies optional settings for alerting. Attributes: email_addresses (list of string): Exists to maintain backwards compatibility with versions before eff8198. email_delivery_targets (list of EmailDeliveryTarget): Specifies additional email addresses where alert notificati...
AlertingConfig
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AlertingConfig: """Implementation of the 'AlertingConfig' model. Specifies optional settings for alerting. Attributes: email_addresses (list of string): Exists to maintain backwards compatibility with versions before eff8198. email_delivery_targets (list of EmailDeliveryTarget): Specifies additio...
stack_v2_sparse_classes_10k_train_005363
2,719
permissive
[ { "docstring": "Constructor for the AlertingConfig class", "name": "__init__", "signature": "def __init__(self, email_addresses=None, email_delivery_targets=None, raise_object_level_failure_alert=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dict...
2
stack_v2_sparse_classes_30k_test_000394
Implement the Python class `AlertingConfig` described below. Class description: Implementation of the 'AlertingConfig' model. Specifies optional settings for alerting. Attributes: email_addresses (list of string): Exists to maintain backwards compatibility with versions before eff8198. email_delivery_targets (list of ...
Implement the Python class `AlertingConfig` described below. Class description: Implementation of the 'AlertingConfig' model. Specifies optional settings for alerting. Attributes: email_addresses (list of string): Exists to maintain backwards compatibility with versions before eff8198. email_delivery_targets (list of ...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class AlertingConfig: """Implementation of the 'AlertingConfig' model. Specifies optional settings for alerting. Attributes: email_addresses (list of string): Exists to maintain backwards compatibility with versions before eff8198. email_delivery_targets (list of EmailDeliveryTarget): Specifies additio...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class AlertingConfig: """Implementation of the 'AlertingConfig' model. Specifies optional settings for alerting. Attributes: email_addresses (list of string): Exists to maintain backwards compatibility with versions before eff8198. email_delivery_targets (list of EmailDeliveryTarget): Specifies additional email add...
the_stack_v2_python_sparse
cohesity_management_sdk/models/alerting_config.py
cohesity/management-sdk-python
train
24
f8a8c0ae49a906382844e3bf70f9c24985b78624
[ "ts = TopologicalSorter()\nfor cur, pre in prerequisites:\n ts.add(cur, pre)\ntry:\n ts.prepare()\n return True\nexcept CycleError:\n return False", "adjList = [[] for _ in range(numCourses)]\ndeg = [0] * numCourses\nfor cur, pre in prerequisites:\n adjList[pre].append(cur)\n deg[cur] += 1\nretu...
<|body_start_0|> ts = TopologicalSorter() for cur, pre in prerequisites: ts.add(cur, pre) try: ts.prepare() return True except CycleError: return False <|end_body_0|> <|body_start_1|> adjList = [[] for _ in range(numCourses)] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canFinish(self, numCourses: int, prerequisites: list[list[int]]) -> bool: """有向图是否无环""" <|body_0|> def canFinish2(self, numCourses: int, prerequisites: list[list[int]]) -> bool: """有向图是否无环""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_10k_train_005364
1,875
no_license
[ { "docstring": "有向图是否无环", "name": "canFinish", "signature": "def canFinish(self, numCourses: int, prerequisites: list[list[int]]) -> bool" }, { "docstring": "有向图是否无环", "name": "canFinish2", "signature": "def canFinish2(self, numCourses: int, prerequisites: list[list[int]]) -> bool" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canFinish(self, numCourses: int, prerequisites: list[list[int]]) -> bool: 有向图是否无环 - def canFinish2(self, numCourses: int, prerequisites: list[list[int]]) -> bool: 有向图是否无环
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canFinish(self, numCourses: int, prerequisites: list[list[int]]) -> bool: 有向图是否无环 - def canFinish2(self, numCourses: int, prerequisites: list[list[int]]) -> bool: 有向图是否无环 <|...
7e79e26bb8f641868561b186e34c1127ed63c9e0
<|skeleton|> class Solution: def canFinish(self, numCourses: int, prerequisites: list[list[int]]) -> bool: """有向图是否无环""" <|body_0|> def canFinish2(self, numCourses: int, prerequisites: list[list[int]]) -> bool: """有向图是否无环""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def canFinish(self, numCourses: int, prerequisites: list[list[int]]) -> bool: """有向图是否无环""" ts = TopologicalSorter() for cur, pre in prerequisites: ts.add(cur, pre) try: ts.prepare() return True except CycleError: ...
the_stack_v2_python_sparse
7_graph/拓扑排序/课程表/207. 课程表拓扑排序调库.py
981377660LMT/algorithm-study
train
225
fdf52c53e8c01d13ae12d342deb658977903b435
[ "self.host = host\nself.port = port\nself.sock = None\nself._sensor = sensor\nself.stopped = threading.Event()", "_LOGGER.debug('Setting up socket...')\nself.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nself.sock.settimeout(10)\nself.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)\ntry:\n ...
<|body_start_0|> self.host = host self.port = port self.sock = None self._sensor = sensor self.stopped = threading.Event() <|end_body_0|> <|body_start_1|> _LOGGER.debug('Setting up socket...') self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
Event listener to monitor calls on the Fritz!Box.
FritzBoxCallMonitor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FritzBoxCallMonitor: """Event listener to monitor calls on the Fritz!Box.""" def __init__(self, host, port, sensor): """Initialize Fritz!Box monitor instance.""" <|body_0|> def connect(self): """Connect to the Fritz!Box.""" <|body_1|> def _listen(sel...
stack_v2_sparse_classes_10k_train_005365
9,842
permissive
[ { "docstring": "Initialize Fritz!Box monitor instance.", "name": "__init__", "signature": "def __init__(self, host, port, sensor)" }, { "docstring": "Connect to the Fritz!Box.", "name": "connect", "signature": "def connect(self)" }, { "docstring": "Listen to incoming or outgoing ...
4
null
Implement the Python class `FritzBoxCallMonitor` described below. Class description: Event listener to monitor calls on the Fritz!Box. Method signatures and docstrings: - def __init__(self, host, port, sensor): Initialize Fritz!Box monitor instance. - def connect(self): Connect to the Fritz!Box. - def _listen(self): ...
Implement the Python class `FritzBoxCallMonitor` described below. Class description: Event listener to monitor calls on the Fritz!Box. Method signatures and docstrings: - def __init__(self, host, port, sensor): Initialize Fritz!Box monitor instance. - def connect(self): Connect to the Fritz!Box. - def _listen(self): ...
ed4ab403deaed9e8c95e0db728477fcb012bf4fa
<|skeleton|> class FritzBoxCallMonitor: """Event listener to monitor calls on the Fritz!Box.""" def __init__(self, host, port, sensor): """Initialize Fritz!Box monitor instance.""" <|body_0|> def connect(self): """Connect to the Fritz!Box.""" <|body_1|> def _listen(sel...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class FritzBoxCallMonitor: """Event listener to monitor calls on the Fritz!Box.""" def __init__(self, host, port, sensor): """Initialize Fritz!Box monitor instance.""" self.host = host self.port = port self.sock = None self._sensor = sensor self.stopped = threadi...
the_stack_v2_python_sparse
homeassistant/components/fritzbox_callmonitor/sensor.py
tchellomello/home-assistant
train
8
2f9b042a47b9ab8e5f5919eac4c752cf41f5ba49
[ "if not root:\n return []\nret = deque()\nstk = [root]\nvisited = set()\nwhile stk:\n cur = stk.pop()\n ret.appendleft(cur.val)\n for c in cur.children:\n stk.append(c)\nreturn list(ret)", "ret = []\nif not root:\n return ret\nstk = [root]\nvisited = set()\nwhile stk:\n cur = stk[-1]\n ...
<|body_start_0|> if not root: return [] ret = deque() stk = [root] visited = set() while stk: cur = stk.pop() ret.appendleft(cur.val) for c in cur.children: stk.append(c) return list(ret) <|end_body_0|> <|bo...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def postorder(self, root: 'Node') -> List[int]: """maintain a stack, pop and reverse""" <|body_0|> def postorder_visited(self, root: 'Node') -> List[int]: """maintain a stack, if visited before, then pop""" <|body_1|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_10k_train_005366
1,410
no_license
[ { "docstring": "maintain a stack, pop and reverse", "name": "postorder", "signature": "def postorder(self, root: 'Node') -> List[int]" }, { "docstring": "maintain a stack, if visited before, then pop", "name": "postorder_visited", "signature": "def postorder_visited(self, root: 'Node') -...
2
stack_v2_sparse_classes_30k_train_000497
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def postorder(self, root: 'Node') -> List[int]: maintain a stack, pop and reverse - def postorder_visited(self, root: 'Node') -> List[int]: maintain a stack, if visited before, t...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def postorder(self, root: 'Node') -> List[int]: maintain a stack, pop and reverse - def postorder_visited(self, root: 'Node') -> List[int]: maintain a stack, if visited before, t...
929dde1723fb2f54870c8a9badc80fc23e8400d3
<|skeleton|> class Solution: def postorder(self, root: 'Node') -> List[int]: """maintain a stack, pop and reverse""" <|body_0|> def postorder_visited(self, root: 'Node') -> List[int]: """maintain a stack, if visited before, then pop""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def postorder(self, root: 'Node') -> List[int]: """maintain a stack, pop and reverse""" if not root: return [] ret = deque() stk = [root] visited = set() while stk: cur = stk.pop() ret.appendleft(cur.val) ...
the_stack_v2_python_sparse
_algorithms_challenges/leetcode/LeetCode/590 N-ary Tree Postorder Traversal.py
syurskyi/Algorithms_and_Data_Structure
train
4
ad29b1837ce39a4be0200f090d59eb124731e5f3
[ "self.number = number\nself.current_color = '000000'\nself.log = logging.getLogger('RASPLed')\nself.strip = strip", "new_color = '{0}{1}{2}'.format(hex(int(color[0]))[2:].zfill(2), hex(int(color[1]))[2:].zfill(2), hex(int(color[2]))[2:].zfill(2))\ntry:\n self.current_color = new_color\n self.strip.setPixelC...
<|body_start_0|> self.number = number self.current_color = '000000' self.log = logging.getLogger('RASPLed') self.strip = strip <|end_body_0|> <|body_start_1|> new_color = '{0}{1}{2}'.format(hex(int(color[0]))[2:].zfill(2), hex(int(color[1]))[2:].zfill(2), hex(int(color[2]))[2:]....
RASPLed
[ "MIT", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RASPLed: def __init__(self, config, number, strip): """Initialise led.""" <|body_0|> def color(self, color): """Set the LED to the specified color. Args: color: a list of int colors. one for each channel. Returns: None""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_10k_train_005367
20,244
permissive
[ { "docstring": "Initialise led.", "name": "__init__", "signature": "def __init__(self, config, number, strip)" }, { "docstring": "Set the LED to the specified color. Args: color: a list of int colors. one for each channel. Returns: None", "name": "color", "signature": "def color(self, co...
2
stack_v2_sparse_classes_30k_train_005234
Implement the Python class `RASPLed` described below. Class description: Implement the RASPLed class. Method signatures and docstrings: - def __init__(self, config, number, strip): Initialise led. - def color(self, color): Set the LED to the specified color. Args: color: a list of int colors. one for each channel. Re...
Implement the Python class `RASPLed` described below. Class description: Implement the RASPLed class. Method signatures and docstrings: - def __init__(self, config, number, strip): Initialise led. - def color(self, color): Set the LED to the specified color. Args: color: a list of int colors. one for each channel. Re...
00937ab2ff51b1dc668bf465282ffa8ff1eebbd8
<|skeleton|> class RASPLed: def __init__(self, config, number, strip): """Initialise led.""" <|body_0|> def color(self, color): """Set the LED to the specified color. Args: color: a list of int colors. one for each channel. Returns: None""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class RASPLed: def __init__(self, config, number, strip): """Initialise led.""" self.number = number self.current_color = '000000' self.log = logging.getLogger('RASPLed') self.strip = strip def color(self, color): """Set the LED to the specified color. Args: colo...
the_stack_v2_python_sparse
mpf/platforms/rasppinball/rasppinball.py
vgrillot/mpf
train
0
7d38576cba07c7d04df5b702cea8c998a3d6cfd5
[ "super(Conv2dSubsampling, self).__init__()\nself.conv = torch.nn.Sequential(torch.nn.Conv2d(1, odim, 3, 2), torch.nn.ReLU(), torch.nn.Conv2d(odim, odim, 3, 2), torch.nn.ReLU())\nself.out = torch.nn.Sequential(torch.nn.Linear(odim * (((idim - 1) // 2 - 1) // 2), odim), pos_enc)", "x = x.unsqueeze(1)\nx = self.conv...
<|body_start_0|> super(Conv2dSubsampling, self).__init__() self.conv = torch.nn.Sequential(torch.nn.Conv2d(1, odim, 3, 2), torch.nn.ReLU(), torch.nn.Conv2d(odim, odim, 3, 2), torch.nn.ReLU()) self.out = torch.nn.Sequential(torch.nn.Linear(odim * (((idim - 1) // 2 - 1) // 2), odim), pos_enc) <|en...
Convolutional 2D subsampling (to 1/4 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer.
Conv2dSubsampling
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Conv2dSubsampling: """Convolutional 2D subsampling (to 1/4 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer.""" def __init__(self, idim, odim, dropout_rate, pos_enc): ...
stack_v2_sparse_classes_10k_train_005368
2,435
permissive
[ { "docstring": "Construct an Conv2dSubsampling object.", "name": "__init__", "signature": "def __init__(self, idim, odim, dropout_rate, pos_enc)" }, { "docstring": "Subsample x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tensor): Input mask (#batch, 1, time). Return...
2
stack_v2_sparse_classes_30k_train_003834
Implement the Python class `Conv2dSubsampling` described below. Class description: Convolutional 2D subsampling (to 1/4 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer. Method signatures and docstri...
Implement the Python class `Conv2dSubsampling` described below. Class description: Convolutional 2D subsampling (to 1/4 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer. Method signatures and docstri...
e2f834dd60e7939672c1795b4ac62e89ad0bca49
<|skeleton|> class Conv2dSubsampling: """Convolutional 2D subsampling (to 1/4 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer.""" def __init__(self, idim, odim, dropout_rate, pos_enc): ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Conv2dSubsampling: """Convolutional 2D subsampling (to 1/4 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer.""" def __init__(self, idim, odim, dropout_rate, pos_enc): """Construc...
the_stack_v2_python_sparse
speech/conformer/pytorch/src/layers/subsampling.py
graphcore/examples
train
311
f168839eeabc277e5920dd9e2f0e72d6306efd6c
[ "logger.debug('Start validator_email.')\nemail_from_database = User.objects.filter(email=email)\nif email_from_database.exists():\n raise ValidationError({'email': [_(constants.EMAIL_EXISTS)]})\nelif email is None:\n raise forms.ValidationError({'email': [_(constants.EMAIL_NONE)]})\nelif len(email) > constant...
<|body_start_0|> logger.debug('Start validator_email.') email_from_database = User.objects.filter(email=email) if email_from_database.exists(): raise ValidationError({'email': [_(constants.EMAIL_EXISTS)]}) elif email is None: raise forms.ValidationError({'email': ...
Validating user fields.
UserValidator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserValidator: """Validating user fields.""" def validator_email(self, email): """Validating email.""" <|body_0|> def validator_email_in_reset_password(self, email): """Validating email.""" <|body_1|> def validator_password(self, password, password_c...
stack_v2_sparse_classes_10k_train_005369
4,003
permissive
[ { "docstring": "Validating email.", "name": "validator_email", "signature": "def validator_email(self, email)" }, { "docstring": "Validating email.", "name": "validator_email_in_reset_password", "signature": "def validator_email_in_reset_password(self, email)" }, { "docstring": "...
6
stack_v2_sparse_classes_30k_train_005699
Implement the Python class `UserValidator` described below. Class description: Validating user fields. Method signatures and docstrings: - def validator_email(self, email): Validating email. - def validator_email_in_reset_password(self, email): Validating email. - def validator_password(self, password, password_confi...
Implement the Python class `UserValidator` described below. Class description: Validating user fields. Method signatures and docstrings: - def validator_email(self, email): Validating email. - def validator_email_in_reset_password(self, email): Validating email. - def validator_password(self, password, password_confi...
5387eb80dfb354e948abe64f7d8bbe087fc4f136
<|skeleton|> class UserValidator: """Validating user fields.""" def validator_email(self, email): """Validating email.""" <|body_0|> def validator_email_in_reset_password(self, email): """Validating email.""" <|body_1|> def validator_password(self, password, password_c...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class UserValidator: """Validating user fields.""" def validator_email(self, email): """Validating email.""" logger.debug('Start validator_email.') email_from_database = User.objects.filter(email=email) if email_from_database.exists(): raise ValidationError({'email':...
the_stack_v2_python_sparse
medical_prescription/user/validators/uservalidator.py
ristovao/2017.2-Receituario-Medico
train
0
4eca387528e53aa20835173db4bbc588aa27c96d
[ "super().__init__()\nassert d % h == 0, 'd must divide by h'\nself.dk = d // h\nself.h = h\nself.d = d\nself.n1 = nn.Linear(d, d)\nself.n2 = nn.Linear(d, d)\nself.n3 = nn.Linear(d, d)\nself.n4 = nn.Linear(d, d)\nself.dropout = nn.Dropout(drop)", "N, _, d = Q.size()\nq = self.n1(Q).view(N, -1, self.h, self.dk).tra...
<|body_start_0|> super().__init__() assert d % h == 0, 'd must divide by h' self.dk = d // h self.h = h self.d = d self.n1 = nn.Linear(d, d) self.n2 = nn.Linear(d, d) self.n3 = nn.Linear(d, d) self.n4 = nn.Linear(d, d) self.dropout = nn.Dro...
MultiAttentionLayer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiAttentionLayer: def __init__(self, d, h, drop=0.1): """d: hidden size h:split factor""" <|body_0|> def forward(self, Q, K, V, mask=None): """Q:(N,T1,d) K:(N,T2,d) V:(N,T2,d) mask:(N,T1,T2) return out:(N,T1,d) p_attn:(N,T1,T2)""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_10k_train_005370
11,927
no_license
[ { "docstring": "d: hidden size h:split factor", "name": "__init__", "signature": "def __init__(self, d, h, drop=0.1)" }, { "docstring": "Q:(N,T1,d) K:(N,T2,d) V:(N,T2,d) mask:(N,T1,T2) return out:(N,T1,d) p_attn:(N,T1,T2)", "name": "forward", "signature": "def forward(self, Q, K, V, mask...
2
stack_v2_sparse_classes_30k_train_004025
Implement the Python class `MultiAttentionLayer` described below. Class description: Implement the MultiAttentionLayer class. Method signatures and docstrings: - def __init__(self, d, h, drop=0.1): d: hidden size h:split factor - def forward(self, Q, K, V, mask=None): Q:(N,T1,d) K:(N,T2,d) V:(N,T2,d) mask:(N,T1,T2) r...
Implement the Python class `MultiAttentionLayer` described below. Class description: Implement the MultiAttentionLayer class. Method signatures and docstrings: - def __init__(self, d, h, drop=0.1): d: hidden size h:split factor - def forward(self, Q, K, V, mask=None): Q:(N,T1,d) K:(N,T2,d) V:(N,T2,d) mask:(N,T1,T2) r...
24e60f24b6e442db22507adddd6bf3e2c343c013
<|skeleton|> class MultiAttentionLayer: def __init__(self, d, h, drop=0.1): """d: hidden size h:split factor""" <|body_0|> def forward(self, Q, K, V, mask=None): """Q:(N,T1,d) K:(N,T2,d) V:(N,T2,d) mask:(N,T1,T2) return out:(N,T1,d) p_attn:(N,T1,T2)""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MultiAttentionLayer: def __init__(self, d, h, drop=0.1): """d: hidden size h:split factor""" super().__init__() assert d % h == 0, 'd must divide by h' self.dk = d // h self.h = h self.d = d self.n1 = nn.Linear(d, d) self.n2 = nn.Linear(d, d) ...
the_stack_v2_python_sparse
daily/8/pytorch_tutoral/nmt/model.py
mckjzhangxk/deepAI
train
1
7a174be35bef155fa4e649a67ecfae0012fc3153
[ "l = []\n\ndef preOrder(root):\n if not root:\n l.append('n')\n return\n l.append(str(root.val))\n preOrder(root.left)\n preOrder(root.right)\npreOrder(root)\nreturn ','.join(l)", "l = list(map(lambda x: int(x) if x != 'n' else None, data.split(',')))\nif not l or l[0] is None:\n retu...
<|body_start_0|> l = [] def preOrder(root): if not root: l.append('n') return l.append(str(root.val)) preOrder(root.left) preOrder(root.right) preOrder(root) return ','.join(l) <|end_body_0|> <|body_start_1...
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|> l = [] ...
stack_v2_sparse_classes_10k_train_005371
2,159
no_license
[ { "docstring": "Encodes a tree to a single string.", "name": "serialize", "signature": "def serialize(self, root: TreeNode) -> str" }, { "docstring": "Decodes your encoded data to tree.", "name": "deserialize", "signature": "def deserialize(self, data: str) -> TreeNode" } ]
2
stack_v2_sparse_classes_30k_train_001709
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...
f6f7b548b29abe53b88a7396296d7edc932450cc
<|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.""" l = [] def preOrder(root): if not root: l.append('n') return l.append(str(root.val)) preOrder(root.left) preOrder...
the_stack_v2_python_sparse
leetcode/daily challenges/2020-10/09-serialize-and-deserialize-bst.py
Nayald/algorithm-portfolio
train
0
5ba893e3eabf8c8b829b30d5dbc442d913aa700d
[ "parser.add_argument('name', help='The name of the peered DNS domain to create.')\nparser.add_argument('--network', metavar='NETWORK', required=True, help='The network in the consumer project peered with the service.')\nparser.add_argument('--service', metavar='SERVICE', default='servicenetworking.googleapis.com', ...
<|body_start_0|> parser.add_argument('name', help='The name of the peered DNS domain to create.') parser.add_argument('--network', metavar='NETWORK', required=True, help='The network in the consumer project peered with the service.') parser.add_argument('--service', metavar='SERVICE', default='s...
Create a peered DNS domain for a private service connection.
Create
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Create: """Create a peered DNS domain for a private service connection.""" def Args(parser): """Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Position...
stack_v2_sparse_classes_10k_train_005372
4,396
permissive
[ { "docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.", "name": "Args", "signature": "def Args(parser)" }, { "docstring"...
2
stack_v2_sparse_classes_30k_train_000107
Implement the Python class `Create` described below. Class description: Create a peered DNS domain for a private service connection. Method signatures and docstrings: - def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments...
Implement the Python class `Create` described below. Class description: Create a peered DNS domain for a private service connection. Method signatures and docstrings: - def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments...
392abf004b16203030e6efd2f0af24db7c8d669e
<|skeleton|> class Create: """Create a peered DNS domain for a private service connection.""" def Args(parser): """Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Position...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Create: """Create a peered DNS domain for a private service connection.""" def Args(parser): """Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments ...
the_stack_v2_python_sparse
lib/surface/services/peered_dns_domains/create.py
google-cloud-sdk-unofficial/google-cloud-sdk
train
9
1be80efcea639df77cbd5a9e4bafb825296629bf
[ "assert isinstance(decoding, Decoding), 'Invalid decoding %s' % decoding\nif decoding.doDecode:\n return\nif isinstance(decoding.type, (Iter, Dict)):\n return\nif not decoding.type.isPrimitive:\n return\ndecoding.doDecode = self.createDecode(decoding)", "assert isinstance(decoding, Decoding), 'Invalid de...
<|body_start_0|> assert isinstance(decoding, Decoding), 'Invalid decoding %s' % decoding if decoding.doDecode: return if isinstance(decoding.type, (Iter, Dict)): return if not decoding.type.isPrimitive: return decoding.doDecode = self.createDec...
Implementation for a handler that provides the primitive parameters values decoding.
PrimitiveDecode
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PrimitiveDecode: """Implementation for a handler that provides the primitive parameters values decoding.""" def process(self, chain, decoding: Decoding, **keyargs): """@see: HandlerProcessor.process Create the primitive decode.""" <|body_0|> def createDecode(self, decodi...
stack_v2_sparse_classes_10k_train_005373
3,264
no_license
[ { "docstring": "@see: HandlerProcessor.process Create the primitive decode.", "name": "process", "signature": "def process(self, chain, decoding: Decoding, **keyargs)" }, { "docstring": "Create the primitive do decode.", "name": "createDecode", "signature": "def createDecode(self, decodi...
2
stack_v2_sparse_classes_30k_train_000580
Implement the Python class `PrimitiveDecode` described below. Class description: Implementation for a handler that provides the primitive parameters values decoding. Method signatures and docstrings: - def process(self, chain, decoding: Decoding, **keyargs): @see: HandlerProcessor.process Create the primitive decode....
Implement the Python class `PrimitiveDecode` described below. Class description: Implementation for a handler that provides the primitive parameters values decoding. Method signatures and docstrings: - def process(self, chain, decoding: Decoding, **keyargs): @see: HandlerProcessor.process Create the primitive decode....
e0b3466b34d31548996d57be4a9dac134d904380
<|skeleton|> class PrimitiveDecode: """Implementation for a handler that provides the primitive parameters values decoding.""" def process(self, chain, decoding: Decoding, **keyargs): """@see: HandlerProcessor.process Create the primitive decode.""" <|body_0|> def createDecode(self, decodi...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PrimitiveDecode: """Implementation for a handler that provides the primitive parameters values decoding.""" def process(self, chain, decoding: Decoding, **keyargs): """@see: HandlerProcessor.process Create the primitive decode.""" assert isinstance(decoding, Decoding), 'Invalid decoding %...
the_stack_v2_python_sparse
components/ally-core/ally/core/impl/processor/decoder/general/primitive.py
cristidomsa/Ally-Py
train
0
b8996bf48c29938c7c14e599decb94ae6c9945e0
[ "words_to_counts = {'cat': 1}\nexpected_result = {'cat': 1}\ntweets.common_words(words_to_counts, 1)\nself.assertEqual(words_to_counts, expected_result, 'none removed')", "dic = {'I': 10, 'you': 5, 'miss': 8, 'here': 6, 'how': 6}\ntweets.common_words(dic, 3)\nexpect_result = {'I': 10, 'miss': 8}\nself.assertEqual...
<|body_start_0|> words_to_counts = {'cat': 1} expected_result = {'cat': 1} tweets.common_words(words_to_counts, 1) self.assertEqual(words_to_counts, expected_result, 'none removed') <|end_body_0|> <|body_start_1|> dic = {'I': 10, 'you': 5, 'miss': 8, 'here': 6, 'how': 6} ...
TestCommonWords
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCommonWords: def test_none_removed(self): """Test common_words with N so that no words are removed.""" <|body_0|> def test_tie_removed(self): """Test common_words with N so that tied words are removed.""" <|body_1|> def test_tie_remained(self): ...
stack_v2_sparse_classes_10k_train_005374
1,649
permissive
[ { "docstring": "Test common_words with N so that no words are removed.", "name": "test_none_removed", "signature": "def test_none_removed(self)" }, { "docstring": "Test common_words with N so that tied words are removed.", "name": "test_tie_removed", "signature": "def test_tie_removed(se...
5
stack_v2_sparse_classes_30k_train_004963
Implement the Python class `TestCommonWords` described below. Class description: Implement the TestCommonWords class. Method signatures and docstrings: - def test_none_removed(self): Test common_words with N so that no words are removed. - def test_tie_removed(self): Test common_words with N so that tied words are re...
Implement the Python class `TestCommonWords` described below. Class description: Implement the TestCommonWords class. Method signatures and docstrings: - def test_none_removed(self): Test common_words with N so that no words are removed. - def test_tie_removed(self): Test common_words with N so that tied words are re...
214525afeeb2da2409f451bf269e792c6940a1ba
<|skeleton|> class TestCommonWords: def test_none_removed(self): """Test common_words with N so that no words are removed.""" <|body_0|> def test_tie_removed(self): """Test common_words with N so that tied words are removed.""" <|body_1|> def test_tie_remained(self): ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TestCommonWords: def test_none_removed(self): """Test common_words with N so that no words are removed.""" words_to_counts = {'cat': 1} expected_result = {'cat': 1} tweets.common_words(words_to_counts, 1) self.assertEqual(words_to_counts, expected_result, 'none removed'...
the_stack_v2_python_sparse
Python/Tweet/test_common_words.py
LilyYC/legendary-train
train
0
a9cb6a3513a09023b92674b7bae47bd27cbaeac7
[ "self.gpf_core.float()\nself.likelihood.train()\noptimizer = torch.optim.Adam([{'params': self.gpf_core.parameters()}], lr=0.1)\nmll = gpytorch.mlls.ExactMarginalLogLikelihood(self.likelihood, self.gpf_core)\nfor _ in range(500):\n optimizer.zero_grad()\n output = self.gpf_core(self.tensor_x)\n loss = -mll...
<|body_start_0|> self.gpf_core.float() self.likelihood.train() optimizer = torch.optim.Adam([{'params': self.gpf_core.parameters()}], lr=0.1) mll = gpytorch.mlls.ExactMarginalLogLikelihood(self.likelihood, self.gpf_core) for _ in range(500): optimizer.zero_grad() ...
PytorchGPFitter
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PytorchGPFitter: def fit_gp(self): """Fit the GP according to options.""" <|body_0|> def get_next_gp(self): """Get the next GP from previously fitted. Returns: GPWrapper object.""" <|body_1|> def _init_gpf(self): """Initialize the GP fitter.""" ...
stack_v2_sparse_classes_10k_train_005375
6,453
permissive
[ { "docstring": "Fit the GP according to options.", "name": "fit_gp", "signature": "def fit_gp(self)" }, { "docstring": "Get the next GP from previously fitted. Returns: GPWrapper object.", "name": "get_next_gp", "signature": "def get_next_gp(self)" }, { "docstring": "Initialize t...
3
stack_v2_sparse_classes_30k_train_006444
Implement the Python class `PytorchGPFitter` described below. Class description: Implement the PytorchGPFitter class. Method signatures and docstrings: - def fit_gp(self): Fit the GP according to options. - def get_next_gp(self): Get the next GP from previously fitted. Returns: GPWrapper object. - def _init_gpf(self)...
Implement the Python class `PytorchGPFitter` described below. Class description: Implement the PytorchGPFitter class. Method signatures and docstrings: - def fit_gp(self): Fit the GP according to options. - def get_next_gp(self): Get the next GP from previously fitted. Returns: GPWrapper object. - def _init_gpf(self)...
fb330ec4ac2ed0f6167eebd849c23fe61692c11c
<|skeleton|> class PytorchGPFitter: def fit_gp(self): """Fit the GP according to options.""" <|body_0|> def get_next_gp(self): """Get the next GP from previously fitted. Returns: GPWrapper object.""" <|body_1|> def _init_gpf(self): """Initialize the GP fitter.""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PytorchGPFitter: def fit_gp(self): """Fit the GP according to options.""" self.gpf_core.float() self.likelihood.train() optimizer = torch.optim.Adam([{'params': self.gpf_core.parameters()}], lr=0.1) mll = gpytorch.mlls.ExactMarginalLogLikelihood(self.likelihood, self.gp...
the_stack_v2_python_sparse
src/gp/gpytorch_interface.py
haowenCS/OCBO_offline
train
0
e8cdd5a31a81ba6252d02232dcdcd7d0d602c153
[ "if campo is None:\n return ''\nif campo in request.POST:\n return request.POST[campo].strip().encode('utf8')\nreturn ''", "if campo is None:\n return ''\nif campo in request.FILES:\n return request.FILES[campo]\nreturn ''" ]
<|body_start_0|> if campo is None: return '' if campo in request.POST: return request.POST[campo].strip().encode('utf8') return '' <|end_body_0|> <|body_start_1|> if campo is None: return '' if campo in request.FILES: return reques...
UtilsForAll
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UtilsForAll: def getfromPost(self, request, campo=None): """Given a field return its value if exists. Return an empty string otherwise.""" <|body_0|> def getfilefromPost(self, request, campo=None): """Given a field return its value if exists. Return an empty string o...
stack_v2_sparse_classes_10k_train_005376
914
no_license
[ { "docstring": "Given a field return its value if exists. Return an empty string otherwise.", "name": "getfromPost", "signature": "def getfromPost(self, request, campo=None)" }, { "docstring": "Given a field return its value if exists. Return an empty string otherwise.", "name": "getfilefrom...
2
stack_v2_sparse_classes_30k_train_003001
Implement the Python class `UtilsForAll` described below. Class description: Implement the UtilsForAll class. Method signatures and docstrings: - def getfromPost(self, request, campo=None): Given a field return its value if exists. Return an empty string otherwise. - def getfilefromPost(self, request, campo=None): Gi...
Implement the Python class `UtilsForAll` described below. Class description: Implement the UtilsForAll class. Method signatures and docstrings: - def getfromPost(self, request, campo=None): Given a field return its value if exists. Return an empty string otherwise. - def getfilefromPost(self, request, campo=None): Gi...
7a390f98fec62825360c462f65944018ace7c265
<|skeleton|> class UtilsForAll: def getfromPost(self, request, campo=None): """Given a field return its value if exists. Return an empty string otherwise.""" <|body_0|> def getfilefromPost(self, request, campo=None): """Given a field return its value if exists. Return an empty string o...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class UtilsForAll: def getfromPost(self, request, campo=None): """Given a field return its value if exists. Return an empty string otherwise.""" if campo is None: return '' if campo in request.POST: return request.POST[campo].strip().encode('utf8') return '' ...
the_stack_v2_python_sparse
Welpe/site_utils.py
itziar/Welpe
train
1
0c3c1cd131a9b48e3fb2161f5c4ba03364623892
[ "self.copy_only_backup = copy_only_backup\nself.disable_metadata = disable_metadata\nself.disable_notification = disable_notification\nself.excluded_vss_writers = excluded_vss_writers", "if dictionary is None:\n return None\ncopy_only_backup = dictionary.get('copyOnlyBackup')\ndisable_metadata = dictionary.get...
<|body_start_0|> self.copy_only_backup = copy_only_backup self.disable_metadata = disable_metadata self.disable_notification = disable_notification self.excluded_vss_writers = excluded_vss_writers <|end_body_0|> <|body_start_1|> if dictionary is None: return None ...
Implementation of the 'WindowsHostSnapshotParameters' model. Specifies settings that are meaningful only on Windows hosts. Attributes: copy_only_backup (bool): Specifies whether to backup regardless of the state of each file's backup history. Backup history will not be updated. Refer Microsoft documentation on VSS_BT_C...
WindowsHostSnapshotParameters
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WindowsHostSnapshotParameters: """Implementation of the 'WindowsHostSnapshotParameters' model. Specifies settings that are meaningful only on Windows hosts. Attributes: copy_only_backup (bool): Specifies whether to backup regardless of the state of each file's backup history. Backup history will ...
stack_v2_sparse_classes_10k_train_005377
2,957
permissive
[ { "docstring": "Constructor for the WindowsHostSnapshotParameters class", "name": "__init__", "signature": "def __init__(self, copy_only_backup=None, disable_metadata=None, disable_notification=None, excluded_vss_writers=None)" }, { "docstring": "Creates an instance of this model from a dictiona...
2
null
Implement the Python class `WindowsHostSnapshotParameters` described below. Class description: Implementation of the 'WindowsHostSnapshotParameters' model. Specifies settings that are meaningful only on Windows hosts. Attributes: copy_only_backup (bool): Specifies whether to backup regardless of the state of each file...
Implement the Python class `WindowsHostSnapshotParameters` described below. Class description: Implementation of the 'WindowsHostSnapshotParameters' model. Specifies settings that are meaningful only on Windows hosts. Attributes: copy_only_backup (bool): Specifies whether to backup regardless of the state of each file...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class WindowsHostSnapshotParameters: """Implementation of the 'WindowsHostSnapshotParameters' model. Specifies settings that are meaningful only on Windows hosts. Attributes: copy_only_backup (bool): Specifies whether to backup regardless of the state of each file's backup history. Backup history will ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class WindowsHostSnapshotParameters: """Implementation of the 'WindowsHostSnapshotParameters' model. Specifies settings that are meaningful only on Windows hosts. Attributes: copy_only_backup (bool): Specifies whether to backup regardless of the state of each file's backup history. Backup history will not be update...
the_stack_v2_python_sparse
cohesity_management_sdk/models/windows_host_snapshot_parameters.py
cohesity/management-sdk-python
train
24
25c6377bf1a7101a2c8440f6ea06152f0e8bb476
[ "if not root:\n return []\nqueue = [(root, 0)]\nvalues = defaultdict(list)\nwhile queue:\n cur, height = queue.pop(0)\n values[height].append(cur.val)\n if cur.left:\n queue.append((cur.left, height + 1))\n if cur.right:\n queue.append((cur.right, height + 1))\nres = []\niter = True\nfo...
<|body_start_0|> if not root: return [] queue = [(root, 0)] values = defaultdict(list) while queue: cur, height = queue.pop(0) values[height].append(cur.val) if cur.left: queue.append((cur.left, height + 1)) if c...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def zigzagLevelOrder(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_0|> def zigzagLevelOrder2(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not root:...
stack_v2_sparse_classes_10k_train_005378
2,087
no_license
[ { "docstring": ":type root: TreeNode :rtype: List[List[int]]", "name": "zigzagLevelOrder", "signature": "def zigzagLevelOrder(self, root)" }, { "docstring": ":type root: TreeNode :rtype: List[List[int]]", "name": "zigzagLevelOrder2", "signature": "def zigzagLevelOrder2(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_007103
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def zigzagLevelOrder(self, root): :type root: TreeNode :rtype: List[List[int]] - def zigzagLevelOrder2(self, root): :type root: TreeNode :rtype: List[List[int]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def zigzagLevelOrder(self, root): :type root: TreeNode :rtype: List[List[int]] - def zigzagLevelOrder2(self, root): :type root: TreeNode :rtype: List[List[int]] <|skeleton|> cla...
0fc4c7af59246e3064db41989a45d9db413a624b
<|skeleton|> class Solution: def zigzagLevelOrder(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_0|> def zigzagLevelOrder2(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def zigzagLevelOrder(self, root): """:type root: TreeNode :rtype: List[List[int]]""" if not root: return [] queue = [(root, 0)] values = defaultdict(list) while queue: cur, height = queue.pop(0) values[height].append(cur.val...
the_stack_v2_python_sparse
103. Binary Tree Zigzag Level Order Traversal/zigzag.py
Macielyoung/LeetCode
train
1
6d8eb49159978b4fec61bec4051b7d4e6ed7cb88
[ "from collections import defaultdict\n\ndef f(path, res):\n word = ''\n i = 0\n while i < max_word and i < len(res):\n word += res[i]\n if word in wordDict:\n path.append(word)\n mem[''.join(path)].append(' '.join(path))\n f(path, res[i + 1:])\n pat...
<|body_start_0|> from collections import defaultdict def f(path, res): word = '' i = 0 while i < max_word and i < len(res): word += res[i] if word in wordDict: path.append(word) mem[''.join(path)...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def wordBreak1(self, s, wordDict): """:type s: str :type wordDict: List[str] :rtype: List[str]""" <|body_0|> def wordBreak(self, s, wordDict): """:type s: str :type wordDict: List[str] :rtype: List[str]""" <|body_1|> <|end_skeleton|> <|body_start_...
stack_v2_sparse_classes_10k_train_005379
1,443
no_license
[ { "docstring": ":type s: str :type wordDict: List[str] :rtype: List[str]", "name": "wordBreak1", "signature": "def wordBreak1(self, s, wordDict)" }, { "docstring": ":type s: str :type wordDict: List[str] :rtype: List[str]", "name": "wordBreak", "signature": "def wordBreak(self, s, wordDi...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def wordBreak1(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: List[str] - def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: Lis...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def wordBreak1(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: List[str] - def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: Lis...
d8ed762d1005975f0de4f07760c9671195621c88
<|skeleton|> class Solution: def wordBreak1(self, s, wordDict): """:type s: str :type wordDict: List[str] :rtype: List[str]""" <|body_0|> def wordBreak(self, s, wordDict): """:type s: str :type wordDict: List[str] :rtype: List[str]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def wordBreak1(self, s, wordDict): """:type s: str :type wordDict: List[str] :rtype: List[str]""" from collections import defaultdict def f(path, res): word = '' i = 0 while i < max_word and i < len(res): word += res[i] ...
the_stack_v2_python_sparse
word-break-ii/solution.py
uxlsl/leetcode_practice
train
0
f0c70892e1d24be8bbb1e7328e3ea37404aad208
[ "dictionary = dict()\nfor i in range(len(nums)):\n if nums[i] in dictionary:\n nums[i].append(i)\n if any(lambda x: x >= abs(i - k) and x <= i + k, nums):\n return True\n else:\n dictionary[nums[i]] = [i]\nreturn False", "tracker = dict()\nfor i in range(len(nums)):\n if t...
<|body_start_0|> dictionary = dict() for i in range(len(nums)): if nums[i] in dictionary: nums[i].append(i) if any(lambda x: x >= abs(i - k) and x <= i + k, nums): return True else: dictionary[nums[i]] = [i] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" <|body_0|> def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_10k_train_005380
1,257
no_license
[ { "docstring": ":type nums: List[int] :type k: int :rtype: bool", "name": "containsNearbyDuplicate", "signature": "def containsNearbyDuplicate(self, nums, k)" }, { "docstring": ":type nums: List[int] :type k: int :rtype: bool", "name": "containsNearbyDuplicate", "signature": "def contain...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool - def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtyp...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool - def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtyp...
d40c24736a6fee43b56aa1c80150c5f14be4ff22
<|skeleton|> class Solution: def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" <|body_0|> def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" dictionary = dict() for i in range(len(nums)): if nums[i] in dictionary: nums[i].append(i) if any(lambda x: x >= abs(i - k) and x <= i...
the_stack_v2_python_sparse
LeetCodePractice/219. Contains Duplicate II.py
deepika087/CompetitiveProgramming
train
10
3e7493bba61b7f6cb13a492764f5d6407b894617
[ "self.X = X_init\nself.Y = Y_init\nself.sigma_f = sigma_f\nself.l = l\nself.K = self.kernel(self.X, self.X)", "a = np.sum(X1 ** 2, 1).reshape(-1, 1)\nb = np.sum(X2 ** 2, 1) - 2 * np.dot(X1, X2.T)\nsqdist = a + b\nreturn self.sigma_f ** 2 * np.exp(-0.5 / self.l ** 2 * sqdist)", "K = self.kernel(self.X, self.X)\n...
<|body_start_0|> self.X = X_init self.Y = Y_init self.sigma_f = sigma_f self.l = l self.K = self.kernel(self.X, self.X) <|end_body_0|> <|body_start_1|> a = np.sum(X1 ** 2, 1).reshape(-1, 1) b = np.sum(X2 ** 2, 1) - 2 * np.dot(X1, X2.T) sqdist = a + b ...
Gaussian class
GaussianProcess
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GaussianProcess: """Gaussian class""" def __init__(self, X_init, Y_init, l=1, sigma_f=1): """Create the class GaussianProcess that represents a noiseless 1D Gaussian process: :param X_init: is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box ...
stack_v2_sparse_classes_10k_train_005381
2,092
no_license
[ { "docstring": "Create the class GaussianProcess that represents a noiseless 1D Gaussian process: :param X_init: is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function :param Y_init: is a numpy.ndarray of shape (t, 1) representing the outputs of the black-box func...
3
stack_v2_sparse_classes_30k_test_000343
Implement the Python class `GaussianProcess` described below. Class description: Gaussian class Method signatures and docstrings: - def __init__(self, X_init, Y_init, l=1, sigma_f=1): Create the class GaussianProcess that represents a noiseless 1D Gaussian process: :param X_init: is a numpy.ndarray of shape (t, 1) re...
Implement the Python class `GaussianProcess` described below. Class description: Gaussian class Method signatures and docstrings: - def __init__(self, X_init, Y_init, l=1, sigma_f=1): Create the class GaussianProcess that represents a noiseless 1D Gaussian process: :param X_init: is a numpy.ndarray of shape (t, 1) re...
f83a60babb1d2a510a4a0e0f58aa3880fd9f93a7
<|skeleton|> class GaussianProcess: """Gaussian class""" def __init__(self, X_init, Y_init, l=1, sigma_f=1): """Create the class GaussianProcess that represents a noiseless 1D Gaussian process: :param X_init: is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GaussianProcess: """Gaussian class""" def __init__(self, X_init, Y_init, l=1, sigma_f=1): """Create the class GaussianProcess that represents a noiseless 1D Gaussian process: :param X_init: is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function :par...
the_stack_v2_python_sparse
unsupervised_learning/0x03-hyperparameter_tuning/1-gp.py
jalondono/holbertonschool-machine_learning
train
2
d44f55e449332180c0a5ec051cb0813a453deca6
[ "batch_size = self.tensors.batch_size\nmask = self._get_mask()\nspatial_temporal_log_loss = self._get_spatial_temporal_loss(n_location_categories, layer_2_output_socres) * mask\ncategorical_log_loss = self._get_categorical_loss(layer_1_output_socres) * mask\nreturn [tf.reduce_sum(categorical_log_loss) / batch_size,...
<|body_start_0|> batch_size = self.tensors.batch_size mask = self._get_mask() spatial_temporal_log_loss = self._get_spatial_temporal_loss(n_location_categories, layer_2_output_socres) * mask categorical_log_loss = self._get_categorical_loss(layer_1_output_socres) * mask return [t...
TwoLayerCategoricalLocationLossFunction
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TwoLayerCategoricalLocationLossFunction: def get_loss(self, n_location_categories, layer_1_output_socres, layer_2_output_socres): """Get total loss from layer 1 and layer 2 output.""" <|body_0|> def _get_spatial_temporal_loss(self, n_location_categories, output_socres): ...
stack_v2_sparse_classes_10k_train_005382
3,718
permissive
[ { "docstring": "Get total loss from layer 1 and layer 2 output.", "name": "get_loss", "signature": "def get_loss(self, n_location_categories, layer_1_output_socres, layer_2_output_socres)" }, { "docstring": "Compute the spatial-temporal log loss", "name": "_get_spatial_temporal_loss", "s...
2
stack_v2_sparse_classes_30k_train_004013
Implement the Python class `TwoLayerCategoricalLocationLossFunction` described below. Class description: Implement the TwoLayerCategoricalLocationLossFunction class. Method signatures and docstrings: - def get_loss(self, n_location_categories, layer_1_output_socres, layer_2_output_socres): Get total loss from layer 1...
Implement the Python class `TwoLayerCategoricalLocationLossFunction` described below. Class description: Implement the TwoLayerCategoricalLocationLossFunction class. Method signatures and docstrings: - def get_loss(self, n_location_categories, layer_1_output_socres, layer_2_output_socres): Get total loss from layer 1...
36f21b46a5c9382f90ece561a3efb1885be3c74f
<|skeleton|> class TwoLayerCategoricalLocationLossFunction: def get_loss(self, n_location_categories, layer_1_output_socres, layer_2_output_socres): """Get total loss from layer 1 and layer 2 output.""" <|body_0|> def _get_spatial_temporal_loss(self, n_location_categories, output_socres): ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TwoLayerCategoricalLocationLossFunction: def get_loss(self, n_location_categories, layer_1_output_socres, layer_2_output_socres): """Get total loss from layer 1 and layer 2 output.""" batch_size = self.tensors.batch_size mask = self._get_mask() spatial_temporal_log_loss = self....
the_stack_v2_python_sparse
lstm_mobility_model/two_layer_categorical_location/loss_function.py
zihenglin/LSTM-Mobility-Model
train
20
c5fb65e1f817982556c16501ba58eaad232509c5
[ "super(GroupL1Norm, self).__init__()\nassert reg_lambda >= 0, 'regularization weight should be 0 or positive'\nassert isinstance(groups, list), 'groups needs to be a list'\nself.reg_lambda = reg_lambda\nself.groups = groups\nself.stabilizing_val = stabilizing_val", "squared = net.Sqr(param)\nreduced_sum = net.Red...
<|body_start_0|> super(GroupL1Norm, self).__init__() assert reg_lambda >= 0, 'regularization weight should be 0 or positive' assert isinstance(groups, list), 'groups needs to be a list' self.reg_lambda = reg_lambda self.groups = groups self.stabilizing_val = stabilizing_v...
Scardapane, Simone, et al. "Group sparse regularization for deep neural networks." Neurocomputing 241 (2017): 81-89. This regularizer computes l1 norm of a weight matrix based on groups. There are essentially three stages in the computation: 1. Compute the l2 norm on all the members of each group 2. Scale each l2 norm ...
GroupL1Norm
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GroupL1Norm: """Scardapane, Simone, et al. "Group sparse regularization for deep neural networks." Neurocomputing 241 (2017): 81-89. This regularizer computes l1 norm of a weight matrix based on groups. There are essentially three stages in the computation: 1. Compute the l2 norm on all the membe...
stack_v2_sparse_classes_10k_train_005383
11,669
permissive
[ { "docstring": "Args: reg_lambda: The weight of the regularization term. groups: A list of integers describing the size of each group. The length of the list is the number of groups. Optional Args: stabilizing_val: The computation of GroupL1Norm involves the Sqrt operator. When values are small, its gradient ca...
2
stack_v2_sparse_classes_30k_train_003183
Implement the Python class `GroupL1Norm` described below. Class description: Scardapane, Simone, et al. "Group sparse regularization for deep neural networks." Neurocomputing 241 (2017): 81-89. This regularizer computes l1 norm of a weight matrix based on groups. There are essentially three stages in the computation: ...
Implement the Python class `GroupL1Norm` described below. Class description: Scardapane, Simone, et al. "Group sparse regularization for deep neural networks." Neurocomputing 241 (2017): 81-89. This regularizer computes l1 norm of a weight matrix based on groups. There are essentially three stages in the computation: ...
cabf6e4f1970dc14302f87414f170de19944bac2
<|skeleton|> class GroupL1Norm: """Scardapane, Simone, et al. "Group sparse regularization for deep neural networks." Neurocomputing 241 (2017): 81-89. This regularizer computes l1 norm of a weight matrix based on groups. There are essentially three stages in the computation: 1. Compute the l2 norm on all the membe...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GroupL1Norm: """Scardapane, Simone, et al. "Group sparse regularization for deep neural networks." Neurocomputing 241 (2017): 81-89. This regularizer computes l1 norm of a weight matrix based on groups. There are essentially three stages in the computation: 1. Compute the l2 norm on all the members of each gr...
the_stack_v2_python_sparse
pytorch/source/caffe2/python/regularizer.py
ryfeus/lambda-packs
train
1,283
d3dcd82fe22869609945cb73474af1c159388268
[ "for pol in self.auth:\n if pol.actor == uid:\n return pol\nreturn None", "pol = self.get_policy(uid)\nif pol is not None:\n session.delete(pol)", "del session\npol = self.get_policy(uid)\npol.role = new_role" ]
<|body_start_0|> for pol in self.auth: if pol.actor == uid: return pol return None <|end_body_0|> <|body_start_1|> pol = self.get_policy(uid) if pol is not None: session.delete(pol) <|end_body_1|> <|body_start_2|> del session pol ...
Base class for models with a list of authorization policies
Authorized
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Authorized: """Base class for models with a list of authorization policies""" def get_policy(self, uid): """Retrieve policy associated with a given actor. Args: uid: (str) id of actor Returns: (Policy) or None if no actor in auth list""" <|body_0|> def remove_policy(self...
stack_v2_sparse_classes_10k_train_005384
3,240
no_license
[ { "docstring": "Retrieve policy associated with a given actor. Args: uid: (str) id of actor Returns: (Policy) or None if no actor in auth list", "name": "get_policy", "signature": "def get_policy(self, uid)" }, { "docstring": "Remove access granted to actor Args: session: (DBSession) uid: (str) ...
3
stack_v2_sparse_classes_30k_train_005257
Implement the Python class `Authorized` described below. Class description: Base class for models with a list of authorization policies Method signatures and docstrings: - def get_policy(self, uid): Retrieve policy associated with a given actor. Args: uid: (str) id of actor Returns: (Policy) or None if no actor in au...
Implement the Python class `Authorized` described below. Class description: Base class for models with a list of authorization policies Method signatures and docstrings: - def get_policy(self, uid): Retrieve policy associated with a given actor. Args: uid: (str) id of actor Returns: (Policy) or None if no actor in au...
ff1feea27efa6544c0e443b953951bb50cbdd9bb
<|skeleton|> class Authorized: """Base class for models with a list of authorization policies""" def get_policy(self, uid): """Retrieve policy associated with a given actor. Args: uid: (str) id of actor Returns: (Policy) or None if no actor in auth list""" <|body_0|> def remove_policy(self...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Authorized: """Base class for models with a list of authorization policies""" def get_policy(self, uid): """Retrieve policy associated with a given actor. Args: uid: (str) id of actor Returns: (Policy) or None if no actor in auth list""" for pol in self.auth: if pol.actor == u...
the_stack_v2_python_sparse
seeweb/models/auth.py
pradal/seeweb
train
0
2dfab900e499be7cdca312690e8e338fc11f5091
[ "for item in os.listdir(source):\n if os.path.isfile(os.path.join(source, item)):\n self.put(os.path.join(source, item), '%s/%s' % (target, item))\n else:\n self.mkdir('%s/%s' % (target, item), ignore_existing=True)\n self.put_dir(os.path.join(source, item), '%s/%s' % (target, item))", ...
<|body_start_0|> for item in os.listdir(source): if os.path.isfile(os.path.join(source, item)): self.put(os.path.join(source, item), '%s/%s' % (target, item)) else: self.mkdir('%s/%s' % (target, item), ignore_existing=True) self.put_dir(os....
RSFTPClient
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RSFTPClient: def put_dir(self, source, target): """Uploads the contents of the source directory to the target path. The target directory needs to exists. All subdirectories in source are created under target.""" <|body_0|> def mkdir(self, path, mode=511, ignore_existing=Fals...
stack_v2_sparse_classes_10k_train_005385
43,347
permissive
[ { "docstring": "Uploads the contents of the source directory to the target path. The target directory needs to exists. All subdirectories in source are created under target.", "name": "put_dir", "signature": "def put_dir(self, source, target)" }, { "docstring": "Augments mkdir by adding an optio...
2
stack_v2_sparse_classes_30k_train_004677
Implement the Python class `RSFTPClient` described below. Class description: Implement the RSFTPClient class. Method signatures and docstrings: - def put_dir(self, source, target): Uploads the contents of the source directory to the target path. The target directory needs to exists. All subdirectories in source are c...
Implement the Python class `RSFTPClient` described below. Class description: Implement the RSFTPClient class. Method signatures and docstrings: - def put_dir(self, source, target): Uploads the contents of the source directory to the target path. The target directory needs to exists. All subdirectories in source are c...
981afa736547ad08e48a11137788fba5b8980cd9
<|skeleton|> class RSFTPClient: def put_dir(self, source, target): """Uploads the contents of the source directory to the target path. The target directory needs to exists. All subdirectories in source are created under target.""" <|body_0|> def mkdir(self, path, mode=511, ignore_existing=Fals...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class RSFTPClient: def put_dir(self, source, target): """Uploads the contents of the source directory to the target path. The target directory needs to exists. All subdirectories in source are created under target.""" for item in os.listdir(source): if os.path.isfile(os.path.join(source,...
the_stack_v2_python_sparse
src/riaps/ctrl/ctrl.py
RIAPS/riaps-pycom
train
7
420be07774e250b1b3349a22a54715b27b101592
[ "gen = ind + FigureControl.minPossibleGenNumber\nfor cplot in gs.cloud_plots:\n fitness = cplot.update_annot(gen)\ntext = '{}'.format(gen)\ngs.fitness_plot.floating_annot.xy = (gen, fitness)\ngs.fitness_plot.floating_annot.set_text(text)", "for cplot in gs.cloud_plots:\n cplot.annot.set_visible(vis)\ngs.fit...
<|body_start_0|> gen = ind + FigureControl.minPossibleGenNumber for cplot in gs.cloud_plots: fitness = cplot.update_annot(gen) text = '{}'.format(gen) gs.fitness_plot.floating_annot.xy = (gen, fitness) gs.fitness_plot.floating_annot.set_text(text) <|end_body_0|> <|bo...
mouse move event on plots
MouseMove
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MouseMove: """mouse move event on plots""" def update_annot(cls, ind): """update the parent floating annotations""" <|body_0|> def update_plot(cls, vis): """update the plots""" <|body_1|> def update(cls, event, curve, preferred_idx): """updat...
stack_v2_sparse_classes_10k_train_005386
4,481
permissive
[ { "docstring": "update the parent floating annotations", "name": "update_annot", "signature": "def update_annot(cls, ind)" }, { "docstring": "update the plots", "name": "update_plot", "signature": "def update_plot(cls, vis)" }, { "docstring": "update the plots and/or annotations"...
4
stack_v2_sparse_classes_30k_train_000260
Implement the Python class `MouseMove` described below. Class description: mouse move event on plots Method signatures and docstrings: - def update_annot(cls, ind): update the parent floating annotations - def update_plot(cls, vis): update the plots - def update(cls, event, curve, preferred_idx): update the plots and...
Implement the Python class `MouseMove` described below. Class description: mouse move event on plots Method signatures and docstrings: - def update_annot(cls, ind): update the parent floating annotations - def update_plot(cls, vis): update the plots - def update(cls, event, curve, preferred_idx): update the plots and...
d0132c8a64516fbb45eb1e645c6312bbe56a7bc5
<|skeleton|> class MouseMove: """mouse move event on plots""" def update_annot(cls, ind): """update the parent floating annotations""" <|body_0|> def update_plot(cls, vis): """update the plots""" <|body_1|> def update(cls, event, curve, preferred_idx): """updat...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MouseMove: """mouse move event on plots""" def update_annot(cls, ind): """update the parent floating annotations""" gen = ind + FigureControl.minPossibleGenNumber for cplot in gs.cloud_plots: fitness = cplot.update_annot(gen) text = '{}'.format(gen) gs....
the_stack_v2_python_sparse
visual_inspector/figure_base/mouse_event.py
justin-nguyen-1996/deep-neuroevolution
train
1
3ae8f4497a46691adefeaf6f67a5cbd1d1491ace
[ "x = input_dict[node.inputs[0]]\nind = input_dict[node.inputs[1]]\nif len(node.inputs) > 2:\n output_shape = input_dict.get(node.inputs[2], None)\nelse:\n output_shape = None\nkernel_shape = node.attrs['kernel_shape']\nspatial_size = len(kernel_shape)\nx_rank = spatial_size + 2\nstorage_format, _ = get_data_f...
<|body_start_0|> x = input_dict[node.inputs[0]] ind = input_dict[node.inputs[1]] if len(node.inputs) > 2: output_shape = input_dict.get(node.inputs[2], None) else: output_shape = None kernel_shape = node.attrs['kernel_shape'] spatial_size = len(ker...
UnpoolMixin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UnpoolMixin: def max_unpool(cls, node, input_dict): """MaxUnpooling operation""" <|body_0|> def _get_default_shape(cls, input_shape, kernel_shape, strides): """Calculates default shape from kernel_shape and strides Args: input_shape: shape of the input to unpool op k...
stack_v2_sparse_classes_10k_train_005387
5,295
permissive
[ { "docstring": "MaxUnpooling operation", "name": "max_unpool", "signature": "def max_unpool(cls, node, input_dict)" }, { "docstring": "Calculates default shape from kernel_shape and strides Args: input_shape: shape of the input to unpool op kernel_shape: the size of the kernel along each axis ou...
5
stack_v2_sparse_classes_30k_train_000808
Implement the Python class `UnpoolMixin` described below. Class description: Implement the UnpoolMixin class. Method signatures and docstrings: - def max_unpool(cls, node, input_dict): MaxUnpooling operation - def _get_default_shape(cls, input_shape, kernel_shape, strides): Calculates default shape from kernel_shape ...
Implement the Python class `UnpoolMixin` described below. Class description: Implement the UnpoolMixin class. Method signatures and docstrings: - def max_unpool(cls, node, input_dict): MaxUnpooling operation - def _get_default_shape(cls, input_shape, kernel_shape, strides): Calculates default shape from kernel_shape ...
44c09275a803e04eeeb4e0d24c372adf1f9ff1f5
<|skeleton|> class UnpoolMixin: def max_unpool(cls, node, input_dict): """MaxUnpooling operation""" <|body_0|> def _get_default_shape(cls, input_shape, kernel_shape, strides): """Calculates default shape from kernel_shape and strides Args: input_shape: shape of the input to unpool op k...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class UnpoolMixin: def max_unpool(cls, node, input_dict): """MaxUnpooling operation""" x = input_dict[node.inputs[0]] ind = input_dict[node.inputs[1]] if len(node.inputs) > 2: output_shape = input_dict.get(node.inputs[2], None) else: output_shape = Non...
the_stack_v2_python_sparse
onnx_tf/handlers/backend/unpool_mixin.py
sdmonov/onnx-tensorflow
train
3
f2fc41d312acec66667a9d52162ca4663649520b
[ "def rserialize(root, string):\n if root == None:\n string += '# '\n else:\n string += str(root.val) + ' '\n string = rserialize(root.left, string)\n string = rserialize(root.right, string)\n return string\nstring = rserialize(root, '')\nreturn string", "def rdeserialize(l):\n...
<|body_start_0|> def rserialize(root, string): if root == None: string += '# ' else: string += str(root.val) + ' ' string = rserialize(root.left, string) string = rserialize(root.right, string) return string ...
Codec
[ "Apache-2.0" ]
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_005388
1,755
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
stack_v2_sparse_classes_30k_train_001569
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:...
fb3fa6df7c77feb2d252feea7f3507569e057c70
<|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 rserialize(root, string): if root == None: string += '# ' else: string += str(root.val) + ' ' string = rserial...
the_stack_v2_python_sparse
297/serializeanddeserializebinarytree.py
cccccccccccccc/Myleetcode
train
0
b9b149b2b78d9611ce71b794833735cffeeccbfb
[ "if request.method == 'PUT':\n if 'bio' not in data or 'website' not in data:\n raise ValidationError('Missing one or more fields.')", "if data is None:\n raise ValidationError('No data was provided')\nreturn Artist(**data)" ]
<|body_start_0|> if request.method == 'PUT': if 'bio' not in data or 'website' not in data: raise ValidationError('Missing one or more fields.') <|end_body_0|> <|body_start_1|> if data is None: raise ValidationError('No data was provided') return Artist(*...
Class to serialize and deserialize Artist objects.
ArtistSchema
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ArtistSchema: """Class to serialize and deserialize Artist objects.""" def validate_on_put_request(self, data, **kwargs): """Raise a ValidationError if certain fields are not sent during a PUT request.""" <|body_0|> def make_object(self, data, **kwargs): """Retur...
stack_v2_sparse_classes_10k_train_005389
1,406
no_license
[ { "docstring": "Raise a ValidationError if certain fields are not sent during a PUT request.", "name": "validate_on_put_request", "signature": "def validate_on_put_request(self, data, **kwargs)" }, { "docstring": "Return an artist object from the validated data.", "name": "make_object", ...
2
stack_v2_sparse_classes_30k_train_003976
Implement the Python class `ArtistSchema` described below. Class description: Class to serialize and deserialize Artist objects. Method signatures and docstrings: - def validate_on_put_request(self, data, **kwargs): Raise a ValidationError if certain fields are not sent during a PUT request. - def make_object(self, d...
Implement the Python class `ArtistSchema` described below. Class description: Class to serialize and deserialize Artist objects. Method signatures and docstrings: - def validate_on_put_request(self, data, **kwargs): Raise a ValidationError if certain fields are not sent during a PUT request. - def make_object(self, d...
d5ae552d383f5f971e29a38055c518fc68172f32
<|skeleton|> class ArtistSchema: """Class to serialize and deserialize Artist objects.""" def validate_on_put_request(self, data, **kwargs): """Raise a ValidationError if certain fields are not sent during a PUT request.""" <|body_0|> def make_object(self, data, **kwargs): """Retur...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ArtistSchema: """Class to serialize and deserialize Artist objects.""" def validate_on_put_request(self, data, **kwargs): """Raise a ValidationError if certain fields are not sent during a PUT request.""" if request.method == 'PUT': if 'bio' not in data or 'website' not in dat...
the_stack_v2_python_sparse
server/app/api/schemas/artist.py
EricMontague/MailChimp-Newsletter-Project
train
0
528c8b5d28b583c4a0e0d04572fdcf3a2e36fd38
[ "args = {}\nargs.update(cls.args_map_export())\nargs.update({'json_flat': False})\nreturn args", "super(Json, self).start(**kwargs)\nflat = self.get_arg_value('json_flat')\nself._first_row = True\nself.open_fd()\nbegin = '' if flat else '['\nself._fd.write(begin)", "super(Json, self).stop(**kwargs)\nflat = self...
<|body_start_0|> args = {} args.update(cls.args_map_export()) args.update({'json_flat': False}) return args <|end_body_0|> <|body_start_1|> super(Json, self).start(**kwargs) flat = self.get_arg_value('json_flat') self._first_row = True self.open_fd() ...
Callbacks for formatting asset data and exporting it in JSON format. Examples: Create a ``client`` using :obj:`axonius_api_client.connect.Connect` and assume ``apiobj`` is either ``client.devices`` or ``client.users`` >>> apiobj = client.devices # or client.users * :meth:`args_map` for callback generic arguments to for...
Json
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Json: """Callbacks for formatting asset data and exporting it in JSON format. Examples: Create a ``client`` using :obj:`axonius_api_client.connect.Connect` and assume ``apiobj`` is either ``client.devices`` or ``client.users`` >>> apiobj = client.devices # or client.users * :meth:`args_map` for c...
stack_v2_sparse_classes_10k_train_005390
4,497
permissive
[ { "docstring": "Get the custom argument names and their defaults for this callbacks object. Examples: Export the output to STDOUT. If ``export_file`` is not supplied, the default is to print the output to STDOUT. >>> assets = apiobj.get(export=\"json\") Export the output to a file in the default path :attr:`axo...
6
stack_v2_sparse_classes_30k_train_007091
Implement the Python class `Json` described below. Class description: Callbacks for formatting asset data and exporting it in JSON format. Examples: Create a ``client`` using :obj:`axonius_api_client.connect.Connect` and assume ``apiobj`` is either ``client.devices`` or ``client.users`` >>> apiobj = client.devices # o...
Implement the Python class `Json` described below. Class description: Callbacks for formatting asset data and exporting it in JSON format. Examples: Create a ``client`` using :obj:`axonius_api_client.connect.Connect` and assume ``apiobj`` is either ``client.devices`` or ``client.users`` >>> apiobj = client.devices # o...
be49566e590834df1b46494c8588651fa029b8c5
<|skeleton|> class Json: """Callbacks for formatting asset data and exporting it in JSON format. Examples: Create a ``client`` using :obj:`axonius_api_client.connect.Connect` and assume ``apiobj`` is either ``client.devices`` or ``client.users`` >>> apiobj = client.devices # or client.users * :meth:`args_map` for c...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Json: """Callbacks for formatting asset data and exporting it in JSON format. Examples: Create a ``client`` using :obj:`axonius_api_client.connect.Connect` and assume ``apiobj`` is either ``client.devices`` or ``client.users`` >>> apiobj = client.devices # or client.users * :meth:`args_map` for callback gener...
the_stack_v2_python_sparse
axonius_api_client/api/asset_callbacks/base_json.py
Axonius/axonius_api_client
train
17
09fe5ee15fa30a41280845e67458dec0e82c22e5
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Missing associated documentation comment in .proto file.
AzureSecretServiceServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AzureSecretServiceServicer: """Missing associated documentation comment in .proto file.""" def getAzureSecret(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def createAzureSecret(self, request, context): """Miss...
stack_v2_sparse_classes_10k_train_005391
8,199
permissive
[ { "docstring": "Missing associated documentation comment in .proto file.", "name": "getAzureSecret", "signature": "def getAzureSecret(self, request, context)" }, { "docstring": "Missing associated documentation comment in .proto file.", "name": "createAzureSecret", "signature": "def crea...
4
stack_v2_sparse_classes_30k_train_001655
Implement the Python class `AzureSecretServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def getAzureSecret(self, request, context): Missing associated documentation comment in .proto file. - def createAzureSecret(self, re...
Implement the Python class `AzureSecretServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def getAzureSecret(self, request, context): Missing associated documentation comment in .proto file. - def createAzureSecret(self, re...
c69e14b409add099d151434b9add711e41f41b20
<|skeleton|> class AzureSecretServiceServicer: """Missing associated documentation comment in .proto file.""" def getAzureSecret(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def createAzureSecret(self, request, context): """Miss...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class AzureSecretServiceServicer: """Missing associated documentation comment in .proto file.""" def getAzureSecret(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not imp...
the_stack_v2_python_sparse
python-sdk/src/airavata_mft_sdk/azure/AzureSecretService_pb2_grpc.py
apache/airavata-mft
train
23
2283b88a918d63730ab37f2bfb086374cd614d32
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ProvisioningErrorInfo()", "from .provisioning_status_error_category import ProvisioningStatusErrorCategory\nfrom .provisioning_status_error_category import ProvisioningStatusErrorCategory\nfields: Dict[str, Callable[[Any], None]] = {'a...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return ProvisioningErrorInfo() <|end_body_0|> <|body_start_1|> from .provisioning_status_error_category import ProvisioningStatusErrorCategory from .provisioning_status_error_category import Pr...
ProvisioningErrorInfo
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProvisioningErrorInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProvisioningErrorInfo: """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 th...
stack_v2_sparse_classes_10k_train_005392
3,926
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: ProvisioningErrorInfo", "name": "create_from_discriminator_value", "signature": "def create_from_discriminat...
3
null
Implement the Python class `ProvisioningErrorInfo` described below. Class description: Implement the ProvisioningErrorInfo class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProvisioningErrorInfo: Creates a new instance of the appropriate class base...
Implement the Python class `ProvisioningErrorInfo` described below. Class description: Implement the ProvisioningErrorInfo class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProvisioningErrorInfo: Creates a new instance of the appropriate class base...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class ProvisioningErrorInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProvisioningErrorInfo: """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 th...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ProvisioningErrorInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProvisioningErrorInfo: """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 Retur...
the_stack_v2_python_sparse
msgraph/generated/models/provisioning_error_info.py
microsoftgraph/msgraph-sdk-python
train
135
4f3901abda7eb63d34bc0f8cb786235a013196b0
[ "def bits_to_abbr(target, bits):\n abbr = []\n pre = 0\n for i in range(len(target)):\n if bits & 1:\n if i - pre > 0:\n abbr.append(str(i - pre))\n pre = i + 1\n abbr.append(str(target[i]))\n elif i == len(target) - 1:\n abbr.append(...
<|body_start_0|> def bits_to_abbr(target, bits): abbr = [] pre = 0 for i in range(len(target)): if bits & 1: if i - pre > 0: abbr.append(str(i - pre)) pre = i + 1 abbr.append(s...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minAbbreviationAC(self, target, dictionary): """:type target: str :type dictionary: List[str] :rtype: str""" <|body_0|> def minAbbreviation(self, target, dictionary): """:type target: str :type dictionary: List[str] :rtype: str""" <|body_1|> <|...
stack_v2_sparse_classes_10k_train_005393
3,484
no_license
[ { "docstring": ":type target: str :type dictionary: List[str] :rtype: str", "name": "minAbbreviationAC", "signature": "def minAbbreviationAC(self, target, dictionary)" }, { "docstring": ":type target: str :type dictionary: List[str] :rtype: str", "name": "minAbbreviation", "signature": "...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minAbbreviationAC(self, target, dictionary): :type target: str :type dictionary: List[str] :rtype: str - def minAbbreviation(self, target, dictionary): :type target: str :typ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minAbbreviationAC(self, target, dictionary): :type target: str :type dictionary: List[str] :rtype: str - def minAbbreviation(self, target, dictionary): :type target: str :typ...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class Solution: def minAbbreviationAC(self, target, dictionary): """:type target: str :type dictionary: List[str] :rtype: str""" <|body_0|> def minAbbreviation(self, target, dictionary): """:type target: str :type dictionary: List[str] :rtype: str""" <|body_1|> <|...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def minAbbreviationAC(self, target, dictionary): """:type target: str :type dictionary: List[str] :rtype: str""" def bits_to_abbr(target, bits): abbr = [] pre = 0 for i in range(len(target)): if bits & 1: if i - ...
the_stack_v2_python_sparse
M/MinimumUniqueWordAbbreviation.py
bssrdf/pyleet
train
2
60a6bc4edc2623c992baddf2529b7324c1a8bf47
[ "def dfs(root):\n if not root:\n return\n res.append(str(root.val) + ',')\n dfs(root.left)\n dfs(root.right)\nres = []\ndfs(root)\nreturn ''.join(res)", "lst = data.split(',')\nlst.pop()\nstack = []\nhead = None\nfor n in lst:\n n = int(n)\n if not head:\n head = TreeNode(n)\n ...
<|body_start_0|> def dfs(root): if not root: return res.append(str(root.val) + ',') dfs(root.left) dfs(root.right) res = [] dfs(root) return ''.join(res) <|end_body_0|> <|body_start_1|> lst = data.split(',') ...
Codec2
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec2: 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 dfs(root)...
stack_v2_sparse_classes_10k_train_005394
1,478
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 `Codec2` described below. Class description: Implement the Codec2 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 `Codec2` described below. Class description: Implement the Codec2 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 ...
3f0ffd519404165fd1a735441b212c801fd1ad1e
<|skeleton|> class Codec2: 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 Codec2: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" def dfs(root): if not root: return res.append(str(root.val) + ',') dfs(root.left) dfs(root.right) res = [] dfs(root) ...
the_stack_v2_python_sparse
Problems/0400_0499/0449_Serialize_and_Deserialize_BST/Project_Python3/TreeNode/Codec2.py
NobuyukiInoue/LeetCode
train
0
4986d7562765fae465ddffef852a0071fca82fc4
[ "conv_dt = naive.astimezone(pytz.timezone(tz)).strftime('%Y-%m-%d %H:%M:%S')\nlogger.logic_log('LOSI13022', tz, naive, conv_dt, request=request)\nreturn conv_dt", "tz_ex = pytz.timezone(tz)\nnaive = naive.replace('/', '-')\nuser_dt = datetime.datetime.strptime(naive, '%Y-%m-%d %H:%M:%S')\ncou_dt = tz_ex.localize(...
<|body_start_0|> conv_dt = naive.astimezone(pytz.timezone(tz)).strftime('%Y-%m-%d %H:%M:%S') logger.logic_log('LOSI13022', tz, naive, conv_dt, request=request) return conv_dt <|end_body_0|> <|body_start_1|> tz_ex = pytz.timezone(tz) naive = naive.replace('/', '-') user_d...
TimeConversion
[ "Apache-2.0", "BSD-3-Clause", "LGPL-3.0-only", "MIT", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TimeConversion: def get_time_conversion(cls, naive, tz, request=None): """[概要] 時刻変換処理を行う [戻り値] 変換した時刻""" <|body_0|> def get_time_conversion_utc(cls, naive, tz, request=None): """[概要] 時刻変換処理を行う [戻り値] utc_dt : 変換した時刻(UTC)""" <|body_1|> <|end_skeleton|> <|body...
stack_v2_sparse_classes_10k_train_005395
9,642
permissive
[ { "docstring": "[概要] 時刻変換処理を行う [戻り値] 変換した時刻", "name": "get_time_conversion", "signature": "def get_time_conversion(cls, naive, tz, request=None)" }, { "docstring": "[概要] 時刻変換処理を行う [戻り値] utc_dt : 変換した時刻(UTC)", "name": "get_time_conversion_utc", "signature": "def get_time_conversion_utc(cl...
2
stack_v2_sparse_classes_30k_train_000358
Implement the Python class `TimeConversion` described below. Class description: Implement the TimeConversion class. Method signatures and docstrings: - def get_time_conversion(cls, naive, tz, request=None): [概要] 時刻変換処理を行う [戻り値] 変換した時刻 - def get_time_conversion_utc(cls, naive, tz, request=None): [概要] 時刻変換処理を行う [戻り値] u...
Implement the Python class `TimeConversion` described below. Class description: Implement the TimeConversion class. Method signatures and docstrings: - def get_time_conversion(cls, naive, tz, request=None): [概要] 時刻変換処理を行う [戻り値] 変換した時刻 - def get_time_conversion_utc(cls, naive, tz, request=None): [概要] 時刻変換処理を行う [戻り値] u...
c00ea4fe1bf4b4a18d545aabeaaf1d95c7664b94
<|skeleton|> class TimeConversion: def get_time_conversion(cls, naive, tz, request=None): """[概要] 時刻変換処理を行う [戻り値] 変換した時刻""" <|body_0|> def get_time_conversion_utc(cls, naive, tz, request=None): """[概要] 時刻変換処理を行う [戻り値] utc_dt : 変換した時刻(UTC)""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TimeConversion: def get_time_conversion(cls, naive, tz, request=None): """[概要] 時刻変換処理を行う [戻り値] 変換した時刻""" conv_dt = naive.astimezone(pytz.timezone(tz)).strftime('%Y-%m-%d %H:%M:%S') logger.logic_log('LOSI13022', tz, naive, conv_dt, request=request) return conv_dt def get_ti...
the_stack_v2_python_sparse
oase-root/libs/webcommonlibs/common.py
exastro-suite/oase
train
10
73e2e2d32a970b297706cefd49903747f9c9867d
[ "super().__init__(filterFineData, universeSettings)\nself.NumberOfSymbolsCoarse = 500\nself.NumberOfSymbolsFine = 20\nself.NumberOfSymbolsInPortfolio = 10\nself.lastMonth = -1\nself.dollarVolumeBySymbol = {}", "month = algorithm.Time.month\nif month == self.lastMonth:\n return Universe.Unchanged\nself.lastMont...
<|body_start_0|> super().__init__(filterFineData, universeSettings) self.NumberOfSymbolsCoarse = 500 self.NumberOfSymbolsFine = 20 self.NumberOfSymbolsInPortfolio = 10 self.lastMonth = -1 self.dollarVolumeBySymbol = {} <|end_body_0|> <|body_start_1|> month = algo...
Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm. From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Value to EBITDA (EV/EBITDA) and Return on Assets (ROA).
GreenBlattMagicFormulaUniverseSelectionModel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GreenBlattMagicFormulaUniverseSelectionModel: """Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm. From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Value to EBITDA (EV/EBITDA) and Return on ...
stack_v2_sparse_classes_10k_train_005396
9,868
permissive
[ { "docstring": "Initializes a new default instance of the MagicFormulaUniverseSelectionModel", "name": "__init__", "signature": "def __init__(self, filterFineData=True, universeSettings=None)" }, { "docstring": "Performs coarse selection for constituents. The stocks must have fundamental data", ...
3
null
Implement the Python class `GreenBlattMagicFormulaUniverseSelectionModel` described below. Class description: Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm. From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Val...
Implement the Python class `GreenBlattMagicFormulaUniverseSelectionModel` described below. Class description: Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm. From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Val...
b33dd3bc140e14b883f39ecf848a793cf7292277
<|skeleton|> class GreenBlattMagicFormulaUniverseSelectionModel: """Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm. From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Value to EBITDA (EV/EBITDA) and Return on ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GreenBlattMagicFormulaUniverseSelectionModel: """Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm. From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Value to EBITDA (EV/EBITDA) and Return on Assets (ROA)....
the_stack_v2_python_sparse
Algorithm.Python/Alphas/GreenblattMagicFormulaAlpha.py
Capnode/Algoloop
train
87
5e8b9932734bec2eac26839189e7c997956ec95b
[ "if self.request.version == 'v6':\n return WorkspaceDetailsSerializerV6\nelif self.request.version == 'v7':\n return WorkspaceDetailsSerializerV6", "if request.version == 'v6':\n return self._get_v6(request, workspace_id)\nelif request.version == 'v7':\n return self._get_v6(request, workspace_id)\nrai...
<|body_start_0|> if self.request.version == 'v6': return WorkspaceDetailsSerializerV6 elif self.request.version == 'v7': return WorkspaceDetailsSerializerV6 <|end_body_0|> <|body_start_1|> if request.version == 'v6': return self._get_v6(request, workspace_id)...
This view is the endpoint for retrieving/updating details of a workspace.
WorkspaceDetailsView
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WorkspaceDetailsView: """This view is the endpoint for retrieving/updating details of a workspace.""" def get_serializer_class(self): """Returns the appropriate serializer based off the requests version of the REST API""" <|body_0|> def get(self, request, workspace_id): ...
stack_v2_sparse_classes_10k_train_005397
19,677
permissive
[ { "docstring": "Returns the appropriate serializer based off the requests version of the REST API", "name": "get_serializer_class", "signature": "def get_serializer_class(self)" }, { "docstring": "Retrieves the details for a workspace and return them in JSON form :param request: the HTTP GET req...
5
stack_v2_sparse_classes_30k_train_006896
Implement the Python class `WorkspaceDetailsView` described below. Class description: This view is the endpoint for retrieving/updating details of a workspace. Method signatures and docstrings: - def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API - def ge...
Implement the Python class `WorkspaceDetailsView` described below. Class description: This view is the endpoint for retrieving/updating details of a workspace. Method signatures and docstrings: - def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API - def ge...
28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b
<|skeleton|> class WorkspaceDetailsView: """This view is the endpoint for retrieving/updating details of a workspace.""" def get_serializer_class(self): """Returns the appropriate serializer based off the requests version of the REST API""" <|body_0|> def get(self, request, workspace_id): ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class WorkspaceDetailsView: """This view is the endpoint for retrieving/updating details of a workspace.""" def get_serializer_class(self): """Returns the appropriate serializer based off the requests version of the REST API""" if self.request.version == 'v6': return WorkspaceDetail...
the_stack_v2_python_sparse
scale/storage/views.py
kfconsultant/scale
train
0
0e324456ce8625f2fa22a1a85266f646beaf4f7e
[ "def backTrack(n, res, tmp, flag, row):\n if row == n:\n z = []\n for t in tmp:\n z.append(''.join(t))\n res.append(z)\n else:\n for col in range(n):\n if flag[row] and flag[n + col] and flag[2 * n + row + col] and flag[5 * n - 2 + col - row]:\n ...
<|body_start_0|> def backTrack(n, res, tmp, flag, row): if row == n: z = [] for t in tmp: z.append(''.join(t)) res.append(z) else: for col in range(n): if flag[row] and flag[n + col] a...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def solveNQueens(self, n): """:type n: int :rtype: List[List[str]]""" <|body_0|> def solveNQueens0(self, n): """:type n: int :rtype: List[List[str]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> def backTrack(n, res, tmp, flag, row): ...
stack_v2_sparse_classes_10k_train_005398
2,064
no_license
[ { "docstring": ":type n: int :rtype: List[List[str]]", "name": "solveNQueens", "signature": "def solveNQueens(self, n)" }, { "docstring": ":type n: int :rtype: List[List[str]]", "name": "solveNQueens0", "signature": "def solveNQueens0(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_004286
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def solveNQueens(self, n): :type n: int :rtype: List[List[str]] - def solveNQueens0(self, n): :type n: int :rtype: List[List[str]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def solveNQueens(self, n): :type n: int :rtype: List[List[str]] - def solveNQueens0(self, n): :type n: int :rtype: List[List[str]] <|skeleton|> class Solution: def solveNQu...
9e49b2c6003b957276737005d4aaac276b44d251
<|skeleton|> class Solution: def solveNQueens(self, n): """:type n: int :rtype: List[List[str]]""" <|body_0|> def solveNQueens0(self, n): """:type n: int :rtype: List[List[str]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def solveNQueens(self, n): """:type n: int :rtype: List[List[str]]""" def backTrack(n, res, tmp, flag, row): if row == n: z = [] for t in tmp: z.append(''.join(t)) res.append(z) else: ...
the_stack_v2_python_sparse
PythonCode/src/0051_N-Queens.py
oneyuan/CodeforFun
train
0
e0c7cdf2a0e61f20341632eb84be7f031633a20f
[ "extension_path = os.path.join(util.GetUnittestDataDir(), 'foo')\noptions = options_for_unittests.GetCopy()\nself.assertRaises(extension_to_load.ExtensionPathNonExistentException, lambda: extension_to_load.ExtensionToLoad(extension_path, options.browser_type))", "extension_path = os.path.join(util.GetUnittestData...
<|body_start_0|> extension_path = os.path.join(util.GetUnittestDataDir(), 'foo') options = options_for_unittests.GetCopy() self.assertRaises(extension_to_load.ExtensionPathNonExistentException, lambda: extension_to_load.ExtensionToLoad(extension_path, options.browser_type)) <|end_body_0|> <|bod...
NonExistentExtensionTest
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NonExistentExtensionTest: def testNonExistentExtensionPath(self): """Test that a non-existent extension path will raise an exception.""" <|body_0|> def testExtensionNotLoaded(self): """Querying an extension that was not loaded will return None""" <|body_1|> ...
stack_v2_sparse_classes_10k_train_005399
9,822
permissive
[ { "docstring": "Test that a non-existent extension path will raise an exception.", "name": "testNonExistentExtensionPath", "signature": "def testNonExistentExtensionPath(self)" }, { "docstring": "Querying an extension that was not loaded will return None", "name": "testExtensionNotLoaded", ...
2
null
Implement the Python class `NonExistentExtensionTest` described below. Class description: Implement the NonExistentExtensionTest class. Method signatures and docstrings: - def testNonExistentExtensionPath(self): Test that a non-existent extension path will raise an exception. - def testExtensionNotLoaded(self): Query...
Implement the Python class `NonExistentExtensionTest` described below. Class description: Implement the NonExistentExtensionTest class. Method signatures and docstrings: - def testNonExistentExtensionPath(self): Test that a non-existent extension path will raise an exception. - def testExtensionNotLoaded(self): Query...
72a05af97787001756bae2511b7985e61498c965
<|skeleton|> class NonExistentExtensionTest: def testNonExistentExtensionPath(self): """Test that a non-existent extension path will raise an exception.""" <|body_0|> def testExtensionNotLoaded(self): """Querying an extension that was not loaded will return None""" <|body_1|> ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class NonExistentExtensionTest: def testNonExistentExtensionPath(self): """Test that a non-existent extension path will raise an exception.""" extension_path = os.path.join(util.GetUnittestDataDir(), 'foo') options = options_for_unittests.GetCopy() self.assertRaises(extension_to_load...
the_stack_v2_python_sparse
third_party/catapult/telemetry/telemetry/internal/browser/extension_unittest.py
metux/chromium-suckless
train
5