blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
181bb5d15a945fc2593be87cefab46af1ca1d24f
[ "self.root_path = root_path\nif self.root_path == None:\n self.root_path = get_startup_path()\nself.patterns = []\nfor pattern in pattern_list:\n self.patterns.append(re.compile(pattern))\nself.paths_scanned = False", "self.suite = unittest.TestSuite()\nfor dir_path, dir_names, file_names in os.walk(self.ro...
<|body_start_0|> self.root_path = root_path if self.root_path == None: self.root_path = get_startup_path() self.patterns = [] for pattern in pattern_list: self.patterns.append(re.compile(pattern)) self.paths_scanned = False <|end_body_0|> <|body_start_1|>...
Find and load unit test classes as a hierarchy of TestSuites and TestCases. The class provides functions for running or returning the resulting TestSuite and requires a root directory to start searching from. TestCases are identified by the class name matching a pattern (pattern_string).
Test_finder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test_finder: """Find and load unit test classes as a hierarchy of TestSuites and TestCases. The class provides functions for running or returning the resulting TestSuite and requires a root directory to start searching from. TestCases are identified by the class name matching a pattern (pattern_s...
stack_v2_sparse_classes_36k_train_001200
31,701
no_license
[ { "docstring": "Initialise the unit test finder. @keyword root_path: The path to starts searching for unit tests from, all sub directories and files are searched. @type root_path: str @keyword pattern_list: A list of regular expression patterns which identify a file as one containing a unit test TestCase. @type...
2
null
Implement the Python class `Test_finder` described below. Class description: Find and load unit test classes as a hierarchy of TestSuites and TestCases. The class provides functions for running or returning the resulting TestSuite and requires a root directory to start searching from. TestCases are identified by the c...
Implement the Python class `Test_finder` described below. Class description: Find and load unit test classes as a hierarchy of TestSuites and TestCases. The class provides functions for running or returning the resulting TestSuite and requires a root directory to start searching from. TestCases are identified by the c...
c317326ddeacd1a1c608128769676899daeae531
<|skeleton|> class Test_finder: """Find and load unit test classes as a hierarchy of TestSuites and TestCases. The class provides functions for running or returning the resulting TestSuite and requires a root directory to start searching from. TestCases are identified by the class name matching a pattern (pattern_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Test_finder: """Find and load unit test classes as a hierarchy of TestSuites and TestCases. The class provides functions for running or returning the resulting TestSuite and requires a root directory to start searching from. TestCases are identified by the class name matching a pattern (pattern_string).""" ...
the_stack_v2_python_sparse
test_suite/unit_tests/unit_test_runner.py
jlec/relax
train
4
1aabea4bbeffa20e752861b2516e713c805247f1
[ "\"\"\" Take parameters, and Sprite Constants \"\"\"\nsuper(EagleSprite, self).__init__(world_map, EagleSprite.IMAGE, GRID_LOCK, EagleSprite.HEALTH_BAR, EagleSprite.AVG_SPEED, EagleSprite.VISION, coordinates)\nself.type = 'eagle'\nself.prey = ['fish']\nself.movable_terrain = world_map.tile_types\nself.shadow = self...
<|body_start_0|> """ Take parameters, and Sprite Constants """ super(EagleSprite, self).__init__(world_map, EagleSprite.IMAGE, GRID_LOCK, EagleSprite.HEALTH_BAR, EagleSprite.AVG_SPEED, EagleSprite.VISION, coordinates) self.type = 'eagle' self.prey = ['fish'] self.movable_terrain ...
EagleSprite
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EagleSprite: def __init__(self, world_map, GRID_LOCK, coordinates=None): """Create a EagleSprite object :param world_map: WorldMap Object :param coordinates: Array of coordinates [x,y] :param GRID_LOCK: Lock for screen (for threading)""" <|body_0|> def move(self, target=None...
stack_v2_sparse_classes_36k_train_001201
3,211
no_license
[ { "docstring": "Create a EagleSprite object :param world_map: WorldMap Object :param coordinates: Array of coordinates [x,y] :param GRID_LOCK: Lock for screen (for threading)", "name": "__init__", "signature": "def __init__(self, world_map, GRID_LOCK, coordinates=None)" }, { "docstring": "@Overr...
3
stack_v2_sparse_classes_30k_val_000421
Implement the Python class `EagleSprite` described below. Class description: Implement the EagleSprite class. Method signatures and docstrings: - def __init__(self, world_map, GRID_LOCK, coordinates=None): Create a EagleSprite object :param world_map: WorldMap Object :param coordinates: Array of coordinates [x,y] :pa...
Implement the Python class `EagleSprite` described below. Class description: Implement the EagleSprite class. Method signatures and docstrings: - def __init__(self, world_map, GRID_LOCK, coordinates=None): Create a EagleSprite object :param world_map: WorldMap Object :param coordinates: Array of coordinates [x,y] :pa...
8995bd57ae0faaf7420c74e1a7b2c091c64d6942
<|skeleton|> class EagleSprite: def __init__(self, world_map, GRID_LOCK, coordinates=None): """Create a EagleSprite object :param world_map: WorldMap Object :param coordinates: Array of coordinates [x,y] :param GRID_LOCK: Lock for screen (for threading)""" <|body_0|> def move(self, target=None...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EagleSprite: def __init__(self, world_map, GRID_LOCK, coordinates=None): """Create a EagleSprite object :param world_map: WorldMap Object :param coordinates: Array of coordinates [x,y] :param GRID_LOCK: Lock for screen (for threading)""" """ Take parameters, and Sprite Constants """ su...
the_stack_v2_python_sparse
sprites/sprite____eagle.py
EcoSimulator/EcoSim2.0
train
0
955f644102887748654b61f89170995d69784322
[ "super().__init__((), read_only, clip, epsilon)\nself.gamma = gamma\nself.ret = None", "x = np.asarray(x)\nif not self.read_only:\n if self.ret is None:\n self.ret = np.zeros(x.shape[0])\n self.ret = self.ret * self.gamma + x\n self.rms.update(self.ret)\n self.ret[dones.astype(np.long)] = 0\nre...
<|body_start_0|> super().__init__((), read_only, clip, epsilon) self.gamma = gamma self.ret = None <|end_body_0|> <|body_start_1|> x = np.asarray(x) if not self.read_only: if self.ret is None: self.ret = np.zeros(x.shape[0]) self.ret = sel...
Reward normalization by running average of returns. Papers: * arxiv.org/pdf/1808.04355.pdf * arxiv.org/pdf/1810.12894.pdf Also see: * github.com/openai/baselines/issues/538
RewardStdNormalizer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RewardStdNormalizer: """Reward normalization by running average of returns. Papers: * arxiv.org/pdf/1808.04355.pdf * arxiv.org/pdf/1810.12894.pdf Also see: * github.com/openai/baselines/issues/538""" def __init__(self, gamma=0.99, read_only=False, clip=10.0, epsilon=1e-08): """Initia...
stack_v2_sparse_classes_36k_train_001202
6,361
permissive
[ { "docstring": "Initializes the data stream tracker. Args: gamma (float): discount factor for rewards. read_only (bool): if to freeze the tracker. clip (float): bounds on the data. epsilon (float): offset to provide divide-by-zero.", "name": "__init__", "signature": "def __init__(self, gamma=0.99, read_...
2
null
Implement the Python class `RewardStdNormalizer` described below. Class description: Reward normalization by running average of returns. Papers: * arxiv.org/pdf/1808.04355.pdf * arxiv.org/pdf/1810.12894.pdf Also see: * github.com/openai/baselines/issues/538 Method signatures and docstrings: - def __init__(self, gamma...
Implement the Python class `RewardStdNormalizer` described below. Class description: Reward normalization by running average of returns. Papers: * arxiv.org/pdf/1808.04355.pdf * arxiv.org/pdf/1810.12894.pdf Also see: * github.com/openai/baselines/issues/538 Method signatures and docstrings: - def __init__(self, gamma...
140ed17dbd91d73a1f6537520b610adff732b9aa
<|skeleton|> class RewardStdNormalizer: """Reward normalization by running average of returns. Papers: * arxiv.org/pdf/1808.04355.pdf * arxiv.org/pdf/1810.12894.pdf Also see: * github.com/openai/baselines/issues/538""" def __init__(self, gamma=0.99, read_only=False, clip=10.0, epsilon=1e-08): """Initia...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RewardStdNormalizer: """Reward normalization by running average of returns. Papers: * arxiv.org/pdf/1808.04355.pdf * arxiv.org/pdf/1810.12894.pdf Also see: * github.com/openai/baselines/issues/538""" def __init__(self, gamma=0.99, read_only=False, clip=10.0, epsilon=1e-08): """Initializes the dat...
the_stack_v2_python_sparse
safe_control_gym/math_and_models/normalization.py
utiasDSL/safe-control-gym
train
387
5d92ba635398479a1097ad5d99b63cbce43fec2e
[ "try:\n return (ApplicationService.apply_custom_attributes(ApplicationService.get_application(application_id=application_id)), HTTPStatus.OK)\nexcept BusinessException as err:\n return (err.error, err.status_code)", "application_json = request.get_json()\ntry:\n application_schema = ApplicationUpdateSche...
<|body_start_0|> try: return (ApplicationService.apply_custom_attributes(ApplicationService.get_application(application_id=application_id)), HTTPStatus.OK) except BusinessException as err: return (err.error, err.status_code) <|end_body_0|> <|body_start_1|> application_js...
Resource for submissions.
ApplicationResourceById
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ApplicationResourceById: """Resource for submissions.""" def get(application_id): """Get application by id.""" <|body_0|> def put(application_id): """Update application details.""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: re...
stack_v2_sparse_classes_36k_train_001203
12,166
permissive
[ { "docstring": "Get application by id.", "name": "get", "signature": "def get(application_id)" }, { "docstring": "Update application details.", "name": "put", "signature": "def put(application_id)" } ]
2
stack_v2_sparse_classes_30k_train_011560
Implement the Python class `ApplicationResourceById` described below. Class description: Resource for submissions. Method signatures and docstrings: - def get(application_id): Get application by id. - def put(application_id): Update application details.
Implement the Python class `ApplicationResourceById` described below. Class description: Resource for submissions. Method signatures and docstrings: - def get(application_id): Get application by id. - def put(application_id): Update application details. <|skeleton|> class ApplicationResourceById: """Resource for...
a1a447f364d1e7414ccb073b0749920ec3523e4a
<|skeleton|> class ApplicationResourceById: """Resource for submissions.""" def get(application_id): """Get application by id.""" <|body_0|> def put(application_id): """Update application details.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ApplicationResourceById: """Resource for submissions.""" def get(application_id): """Get application by id.""" try: return (ApplicationService.apply_custom_attributes(ApplicationService.get_application(application_id=application_id)), HTTPStatus.OK) except BusinessExce...
the_stack_v2_python_sparse
forms-flow-api/src/api/resources/application.py
sumathi-thirumani-aot/forms-flow-ai
train
0
7fb38954032c71f3f1bc49eb777fe69220fd170e
[ "self.capacity = capacity\nself.map = {}\nself.linklist = DoubleLinkList()", "node = self.map.get(key)\nif not node:\n return -1\nself.linklist.pop(node)\nself.linklist.insert_head(node)\nreturn node.value", "if key in self.map:\n node = self.linklist.pop(self.map[key])\n node.value = value\nelse:\n ...
<|body_start_0|> self.capacity = capacity self.map = {} self.linklist = DoubleLinkList() <|end_body_0|> <|body_start_1|> node = self.map.get(key) if not node: return -1 self.linklist.pop(node) self.linklist.insert_head(node) return node.value ...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_36k_train_001204
5,026
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: void", "name": "pu...
3
null
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void <|sk...
b7e041c8c4d85009139d67eca6d12b431cd875cc
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.capacity = capacity self.map = {} self.linklist = DoubleLinkList() def get(self, key): """:type key: int :rtype: int""" node = self.map.get(key) if not node: return -...
the_stack_v2_python_sparse
unsolved/unsolved_146_LRU_Cache.py
jyu001/New-Leetcode-Solution
train
0
f034d9cf11b174c80b6d9838085cd13788a88a17
[ "index_size, num_examples, batch_size = (32, 24, 8)\nindex = [{'hashed_id': str(i)} for i in range(index_size)]\nretriever = _MockEmbeddingBasedRetriever(index, batch_size=batch_size)\nexamples = [{'hashed_id': str(i)} for i in range(num_examples)]\nresults = list(retriever.retrieve_all(examples))\nself.assertLen(r...
<|body_start_0|> index_size, num_examples, batch_size = (32, 24, 8) index = [{'hashed_id': str(i)} for i in range(index_size)] retriever = _MockEmbeddingBasedRetriever(index, batch_size=batch_size) examples = [{'hashed_id': str(i)} for i in range(num_examples)] results = list(ret...
Tests EmbeddingBasedRetriever.
EmbeddingBasedRetrieverTest
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmbeddingBasedRetrieverTest: """Tests EmbeddingBasedRetriever.""" def test_batching_no_remainder(self): """Tests if batching does not drop any example.""" <|body_0|> def test_batching_has_remainder(self): """Tests if batching does not drop any example.""" ...
stack_v2_sparse_classes_36k_train_001205
7,300
permissive
[ { "docstring": "Tests if batching does not drop any example.", "name": "test_batching_no_remainder", "signature": "def test_batching_no_remainder(self)" }, { "docstring": "Tests if batching does not drop any example.", "name": "test_batching_has_remainder", "signature": "def test_batchin...
2
null
Implement the Python class `EmbeddingBasedRetrieverTest` described below. Class description: Tests EmbeddingBasedRetriever. Method signatures and docstrings: - def test_batching_no_remainder(self): Tests if batching does not drop any example. - def test_batching_has_remainder(self): Tests if batching does not drop an...
Implement the Python class `EmbeddingBasedRetrieverTest` described below. Class description: Tests EmbeddingBasedRetriever. Method signatures and docstrings: - def test_batching_no_remainder(self): Tests if batching does not drop any example. - def test_batching_has_remainder(self): Tests if batching does not drop an...
ac9447064195e06de48cc91ff642f7fffa28ffe8
<|skeleton|> class EmbeddingBasedRetrieverTest: """Tests EmbeddingBasedRetriever.""" def test_batching_no_remainder(self): """Tests if batching does not drop any example.""" <|body_0|> def test_batching_has_remainder(self): """Tests if batching does not drop any example.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EmbeddingBasedRetrieverTest: """Tests EmbeddingBasedRetriever.""" def test_batching_no_remainder(self): """Tests if batching does not drop any example.""" index_size, num_examples, batch_size = (32, 24, 8) index = [{'hashed_id': str(i)} for i in range(index_size)] retrieve...
the_stack_v2_python_sparse
language/casper/retrieve/query_retrievers_test.py
google-research/language
train
1,567
695e7f7fa18f7a450b63358309f53b37d7730efd
[ "self.subscription_key = subscription_key\nself.ocr_url = ocr_url\nself.proxies = proxies", "ocr_url = self.ENDPOINT.format(self.ocr_url)\nresult_path = self.CACHE_FILE_PATTERN.format(file_name)\nif os.path.exists(result_path):\n with open(result_path) as f:\n return json.load(f)\nheaders = {'Ocp-Apim-S...
<|body_start_0|> self.subscription_key = subscription_key self.ocr_url = ocr_url self.proxies = proxies <|end_body_0|> <|body_start_1|> ocr_url = self.ENDPOINT.format(self.ocr_url) result_path = self.CACHE_FILE_PATTERN.format(file_name) if os.path.exists(result_path): ...
Support class for Azure Computer Vision OCR API Details on the API can be found at: https://westcentralus.dev.cognitive.microsoft.com/docs/services/computer-vision-v3-1-ga/operations/56f91f2e778daf14a499f20d
AzureComputerVisionOcrApi
[ "MIT", "BSD-3-Clause", "LGPL-2.1-or-later", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AzureComputerVisionOcrApi: """Support class for Azure Computer Vision OCR API Details on the API can be found at: https://westcentralus.dev.cognitive.microsoft.com/docs/services/computer-vision-v3-1-ga/operations/56f91f2e778daf14a499f20d""" def __init__(self, subscription_key: str, ocr_url: ...
stack_v2_sparse_classes_36k_train_001206
4,153
permissive
[ { "docstring": "Initialize a new instance of AzureComputerVisionOcrApi :param str subscription_key: key for the computer vision instance :param str ocr_url: url for the OCR endpoint with host only. For example, 'https://{instance}.cognitiveservices.azure.com' :param Dict[str,str] proxies: Optional set of proxie...
3
stack_v2_sparse_classes_30k_train_009136
Implement the Python class `AzureComputerVisionOcrApi` described below. Class description: Support class for Azure Computer Vision OCR API Details on the API can be found at: https://westcentralus.dev.cognitive.microsoft.com/docs/services/computer-vision-v3-1-ga/operations/56f91f2e778daf14a499f20d Method signatures a...
Implement the Python class `AzureComputerVisionOcrApi` described below. Class description: Support class for Azure Computer Vision OCR API Details on the API can be found at: https://westcentralus.dev.cognitive.microsoft.com/docs/services/computer-vision-v3-1-ga/operations/56f91f2e778daf14a499f20d Method signatures a...
edded8e8076322684336cc3d90f75859987100cc
<|skeleton|> class AzureComputerVisionOcrApi: """Support class for Azure Computer Vision OCR API Details on the API can be found at: https://westcentralus.dev.cognitive.microsoft.com/docs/services/computer-vision-v3-1-ga/operations/56f91f2e778daf14a499f20d""" def __init__(self, subscription_key: str, ocr_url: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AzureComputerVisionOcrApi: """Support class for Azure Computer Vision OCR API Details on the API can be found at: https://westcentralus.dev.cognitive.microsoft.com/docs/services/computer-vision-v3-1-ga/operations/56f91f2e778daf14a499f20d""" def __init__(self, subscription_key: str, ocr_url: str, proxies:...
the_stack_v2_python_sparse
Analysis/Routing_Forms/src/AzureComputerVisionOcrApi.py
microsoft/knowledge-extraction-recipes-forms
train
145
1e578d18412096d3ff2a3d24ee9e7aae3dd31c9e
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('charr_hu38_npearce', 'charr_hu38_npearce')\nrepo.dropCollection('optstationnum')\nrepo.createCollection('optstationnum')\ndata = repo.charr_hu38_npearce.unionpopbike.find()\ncities = []\nX = []\ny = []\n...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('charr_hu38_npearce', 'charr_hu38_npearce') repo.dropCollection('optstationnum') repo.createCollection('optstationnum') data = repo.charr_h...
OptimalStationNumber
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OptimalStationNumber: def execute(trial=False): """Union dataset containing bike data into the dataset containing city census information""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document desc...
stack_v2_sparse_classes_36k_train_001207
4,074
no_license
[ { "docstring": "Union dataset containing bike data into the dataset containing city census information", "name": "execute", "signature": "def execute(trial=False)" }, { "docstring": "Create the provenance document describing everything happening in this script. Each run of the script will genera...
2
null
Implement the Python class `OptimalStationNumber` described below. Class description: Implement the OptimalStationNumber class. Method signatures and docstrings: - def execute(trial=False): Union dataset containing bike data into the dataset containing city census information - def provenance(doc=prov.model.ProvDocum...
Implement the Python class `OptimalStationNumber` described below. Class description: Implement the OptimalStationNumber class. Method signatures and docstrings: - def execute(trial=False): Union dataset containing bike data into the dataset containing city census information - def provenance(doc=prov.model.ProvDocum...
90284cf3debbac36eead07b8d2339cdd191b86cf
<|skeleton|> class OptimalStationNumber: def execute(trial=False): """Union dataset containing bike data into the dataset containing city census information""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document desc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OptimalStationNumber: def execute(trial=False): """Union dataset containing bike data into the dataset containing city census information""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('charr_hu38_npearce',...
the_stack_v2_python_sparse
charr_hu38_npearce/OptimalStationNumber.py
maximega/course-2019-spr-proj
train
2
939f3811af0f411db4af3b0d56831c8eb2ca2089
[ "if key != 'beginning_line':\n event_data = AndroidLogcatEventData()\n event_data.component_tag = self._GetStringValueFromStructure(structure, 'tag')\n event_data.file_offset = self._current_offset\n event_data.message = self._GetValueFromStructure(structure, 'message')\n event_data.pid = self._GetVa...
<|body_start_0|> if key != 'beginning_line': event_data = AndroidLogcatEventData() event_data.component_tag = self._GetStringValueFromStructure(structure, 'tag') event_data.file_offset = self._current_offset event_data.message = self._GetValueFromStructure(structu...
Text parser plugin for Android logcat files.
AndroidLogcatTextPlugin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AndroidLogcatTextPlugin: """Text parser plugin for Android logcat files.""" def _ParseRecord(self, parser_mediator, key, structure): """Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage an...
stack_v2_sparse_classes_36k_train_001208
9,362
permissive
[ { "docstring": "Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. key (str): name of the parsed structure. structure (pyparsing.ParseResults): tokens from a parsed log line. Raises: ParseError: if the stru...
3
null
Implement the Python class `AndroidLogcatTextPlugin` described below. Class description: Text parser plugin for Android logcat files. Method signatures and docstrings: - def _ParseRecord(self, parser_mediator, key, structure): Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions...
Implement the Python class `AndroidLogcatTextPlugin` described below. Class description: Text parser plugin for Android logcat files. Method signatures and docstrings: - def _ParseRecord(self, parser_mediator, key, structure): Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions...
d6022f8cfebfddf2d08ab2d300a41b61f3349933
<|skeleton|> class AndroidLogcatTextPlugin: """Text parser plugin for Android logcat files.""" def _ParseRecord(self, parser_mediator, key, structure): """Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage an...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AndroidLogcatTextPlugin: """Text parser plugin for Android logcat files.""" def _ParseRecord(self, parser_mediator, key, structure): """Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. key ...
the_stack_v2_python_sparse
plaso/parsers/text_plugins/android_logcat.py
log2timeline/plaso
train
1,506
f5709c5957fc1c79dbd304fbbc816dbc3a8b2e1e
[ "config = Config()\nself._arguments = [(_,) for _ in pattoo_db_records_lists if bool(_) is True]\nself._multiprocess = config.multiprocessing()\nself._pool_size = cpu_count()", "pattoo_db_records_lists_tuple = self._arguments\npool_size = self._pool_size\nwith get_context('spawn').Pool(processes=pool_size) as poo...
<|body_start_0|> config = Config() self._arguments = [(_,) for _ in pattoo_db_records_lists if bool(_) is True] self._multiprocess = config.multiprocessing() self._pool_size = cpu_count() <|end_body_0|> <|body_start_1|> pattoo_db_records_lists_tuple = self._arguments poo...
Process data using multiprocessing.
Records
[ "GPL-3.0-only" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Records: """Process data using multiprocessing.""" def __init__(self, pattoo_db_records_lists): """Initialize the class. Args: pattoo_db_records_lists: List of PattooDBrecord oject lists grouped by source and sorted by timestamp. This data is obtained from PattooShared.converter.extr...
stack_v2_sparse_classes_36k_train_001209
12,404
permissive
[ { "docstring": "Initialize the class. Args: pattoo_db_records_lists: List of PattooDBrecord oject lists grouped by source and sorted by timestamp. This data is obtained from PattooShared.converter.extract Returns: None", "name": "__init__", "signature": "def __init__(self, pattoo_db_records_lists)" },...
6
null
Implement the Python class `Records` described below. Class description: Process data using multiprocessing. Method signatures and docstrings: - def __init__(self, pattoo_db_records_lists): Initialize the class. Args: pattoo_db_records_lists: List of PattooDBrecord oject lists grouped by source and sorted by timestam...
Implement the Python class `Records` described below. Class description: Process data using multiprocessing. Method signatures and docstrings: - def __init__(self, pattoo_db_records_lists): Initialize the class. Args: pattoo_db_records_lists: List of PattooDBrecord oject lists grouped by source and sorted by timestam...
57bd3e82e49d51e3426b13ad53ed8326a735ce29
<|skeleton|> class Records: """Process data using multiprocessing.""" def __init__(self, pattoo_db_records_lists): """Initialize the class. Args: pattoo_db_records_lists: List of PattooDBrecord oject lists grouped by source and sorted by timestamp. This data is obtained from PattooShared.converter.extr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Records: """Process data using multiprocessing.""" def __init__(self, pattoo_db_records_lists): """Initialize the class. Args: pattoo_db_records_lists: List of PattooDBrecord oject lists grouped by source and sorted by timestamp. This data is obtained from PattooShared.converter.extract Returns: ...
the_stack_v2_python_sparse
pattoo/ingest/records.py
palisadoes/pattoo
train
0
3b5976fcb9089cb3256219b36643ee1460dce374
[ "self.southAsian = Coconut('South Asian')\nself.middleEastern = Coconut('Middle Eastern')\nself.american = Coconut('American')", "self.assertTrue(self.southAsian.weight)\nself.assertTrue(self.middleEastern.weight)\nself.assertTrue(self.american.weight)\nself.assertRaises(KeyError, Coconut, 'lime')", "cw = set()...
<|body_start_0|> self.southAsian = Coconut('South Asian') self.middleEastern = Coconut('Middle Eastern') self.american = Coconut('American') <|end_body_0|> <|body_start_1|> self.assertTrue(self.southAsian.weight) self.assertTrue(self.middleEastern.weight) self.assertTrue...
TestCoconuts
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCoconuts: def setUp(self): """Instantiate each of the 3 coconut species""" <|body_0|> def testCoconutsExist(self): """Just check that all coconuts are instances of Coconut Check the taking the lime and the coconut and shake it all up gives a KeyError because it i...
stack_v2_sparse_classes_36k_train_001210
2,108
no_license
[ { "docstring": "Instantiate each of the 3 coconut species", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Just check that all coconuts are instances of Coconut Check the taking the lime and the coconut and shake it all up gives a KeyError because it is not allowed by class C...
4
stack_v2_sparse_classes_30k_val_000764
Implement the Python class `TestCoconuts` described below. Class description: Implement the TestCoconuts class. Method signatures and docstrings: - def setUp(self): Instantiate each of the 3 coconut species - def testCoconutsExist(self): Just check that all coconuts are instances of Coconut Check the taking the lime ...
Implement the Python class `TestCoconuts` described below. Class description: Implement the TestCoconuts class. Method signatures and docstrings: - def setUp(self): Instantiate each of the 3 coconut species - def testCoconutsExist(self): Just check that all coconuts are instances of Coconut Check the taking the lime ...
049c654ed626e97d7fe2f8dc61d84c60f10d7558
<|skeleton|> class TestCoconuts: def setUp(self): """Instantiate each of the 3 coconut species""" <|body_0|> def testCoconutsExist(self): """Just check that all coconuts are instances of Coconut Check the taking the lime and the coconut and shake it all up gives a KeyError because it i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestCoconuts: def setUp(self): """Instantiate each of the 3 coconut species""" self.southAsian = Coconut('South Asian') self.middleEastern = Coconut('Middle Eastern') self.american = Coconut('American') def testCoconutsExist(self): """Just check that all coconuts a...
the_stack_v2_python_sparse
workspace/Python3_Homework02/src/test_coconuts.py
paulrefalo/Python-2---4
train
0
1fb83e321f0ef34b7b6e6ea57e44f8b89acde85e
[ "cube_axes_actor = vtk.vtkCubeAxesActor()\ncube_axes_actor.SetBounds(x_bound[0, 0], x_bound[0, 1], y_bound[0, 0], y_bound[0, 1], z_bound[0, 0], z_bound[0, 1])\ncube_axes_actor.SetCamera(ren.GetActiveCamera())\ncube_axes_actor.GetTitleTextProperty(0).SetColor(1.0, 0.0, 0.0)\ncube_axes_actor.GetLabelTextProperty(0).S...
<|body_start_0|> cube_axes_actor = vtk.vtkCubeAxesActor() cube_axes_actor.SetBounds(x_bound[0, 0], x_bound[0, 1], y_bound[0, 0], y_bound[0, 1], z_bound[0, 0], z_bound[0, 1]) cube_axes_actor.SetCamera(ren.GetActiveCamera()) cube_axes_actor.GetTitleTextProperty(0).SetColor(1.0, 0.0, 0.0) ...
Returns an XYZ axis object (for widgets, structure)
AxisFactory
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AxisFactory: """Returns an XYZ axis object (for widgets, structure)""" def axes_cube(ren, x_bound=np.matrix([[-1.5, 1.5]]), y_bound=np.matrix([[-1.5, 1.5]]), z_bound=np.matrix([[-1.5, 1.5]])): """Helper method to create a VTK cube axis actor""" <|body_0|> def axes_cube_f...
stack_v2_sparse_classes_36k_train_001211
2,710
permissive
[ { "docstring": "Helper method to create a VTK cube axis actor", "name": "axes_cube", "signature": "def axes_cube(ren, x_bound=np.matrix([[-1.5, 1.5]]), y_bound=np.matrix([[-1.5, 1.5]]), z_bound=np.matrix([[-1.5, 1.5]]))" }, { "docstring": "Creates a large axis for the main window of the simulato...
3
null
Implement the Python class `AxisFactory` described below. Class description: Returns an XYZ axis object (for widgets, structure) Method signatures and docstrings: - def axes_cube(ren, x_bound=np.matrix([[-1.5, 1.5]]), y_bound=np.matrix([[-1.5, 1.5]]), z_bound=np.matrix([[-1.5, 1.5]])): Helper method to create a VTK c...
Implement the Python class `AxisFactory` described below. Class description: Returns an XYZ axis object (for widgets, structure) Method signatures and docstrings: - def axes_cube(ren, x_bound=np.matrix([[-1.5, 1.5]]), y_bound=np.matrix([[-1.5, 1.5]]), z_bound=np.matrix([[-1.5, 1.5]])): Helper method to create a VTK c...
1ed45cdcf4aa1695ae69406051ce74df15dc0d45
<|skeleton|> class AxisFactory: """Returns an XYZ axis object (for widgets, structure)""" def axes_cube(ren, x_bound=np.matrix([[-1.5, 1.5]]), y_bound=np.matrix([[-1.5, 1.5]]), z_bound=np.matrix([[-1.5, 1.5]])): """Helper method to create a VTK cube axis actor""" <|body_0|> def axes_cube_f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AxisFactory: """Returns an XYZ axis object (for widgets, structure)""" def axes_cube(ren, x_bound=np.matrix([[-1.5, 1.5]]), y_bound=np.matrix([[-1.5, 1.5]]), z_bound=np.matrix([[-1.5, 1.5]])): """Helper method to create a VTK cube axis actor""" cube_axes_actor = vtk.vtkCubeAxesActor() ...
the_stack_v2_python_sparse
components/simulator/entities/gui/axis_entity.py
smart-scaffolding/swarm_construction
train
2
74ea819c52b17e12eba1017fb439ebe2476e0b52
[ "self.base = util.get_base_color()\nself.view = view\nself.on_cancel = on_cancel\nself.setup_gamut_style()\nself.setup_image_border()\nself.setup_sizes()", "if self.on_cancel is not None:\n call = self.on_cancel.get('command', 'color_helper')\n args = self.on_cancel.get('args', {})\n self.view.run_comman...
<|body_start_0|> self.base = util.get_base_color() self.view = view self.on_cancel = on_cancel self.setup_gamut_style() self.setup_image_border() self.setup_sizes() <|end_body_0|> <|body_start_1|> if self.on_cancel is not None: call = self.on_cancel.g...
Color input handler base class.
_ColorInputHandler
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _ColorInputHandler: """Color input handler base class.""" def __init__(self, view, on_cancel=None, **kwargs): """Initialize.""" <|body_0|> def cancel(self): """On cancel.""" <|body_1|> def get_html_style(self): """Get HTML style.""" <...
stack_v2_sparse_classes_36k_train_001212
2,168
permissive
[ { "docstring": "Initialize.", "name": "__init__", "signature": "def __init__(self, view, on_cancel=None, **kwargs)" }, { "docstring": "On cancel.", "name": "cancel", "signature": "def cancel(self)" }, { "docstring": "Get HTML style.", "name": "get_html_style", "signature"...
3
null
Implement the Python class `_ColorInputHandler` described below. Class description: Color input handler base class. Method signatures and docstrings: - def __init__(self, view, on_cancel=None, **kwargs): Initialize. - def cancel(self): On cancel. - def get_html_style(self): Get HTML style.
Implement the Python class `_ColorInputHandler` described below. Class description: Color input handler base class. Method signatures and docstrings: - def __init__(self, view, on_cancel=None, **kwargs): Initialize. - def cancel(self): On cancel. - def get_html_style(self): Get HTML style. <|skeleton|> class _ColorI...
ad4d779bff57a65b7c77cda0b79c10cf904eb817
<|skeleton|> class _ColorInputHandler: """Color input handler base class.""" def __init__(self, view, on_cancel=None, **kwargs): """Initialize.""" <|body_0|> def cancel(self): """On cancel.""" <|body_1|> def get_html_style(self): """Get HTML style.""" <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _ColorInputHandler: """Color input handler base class.""" def __init__(self, view, on_cancel=None, **kwargs): """Initialize.""" self.base = util.get_base_color() self.view = view self.on_cancel = on_cancel self.setup_gamut_style() self.setup_image_border() ...
the_stack_v2_python_sparse
ch_tools.py
facelessuser/ColorHelper
train
279
117e1c1bad6cd7a6471bbde8d51ed8ed9dede73d
[ "caffe.set_mode_gpu()\ncaffe.set_device(device_id)\nself._net = caffe.Net(net_proto, net_weights, caffe.TEST)\ninput_shape = self._net.blobs['data'].data.shape\ntransformer = caffe.io.Transformer({'data': input_shape})\nif self._net.blobs['data'].data.shape[1] == 3:\n transformer.set_transpose('data', (2, 0, 1))...
<|body_start_0|> caffe.set_mode_gpu() caffe.set_device(device_id) self._net = caffe.Net(net_proto, net_weights, caffe.TEST) input_shape = self._net.blobs['data'].data.shape transformer = caffe.io.Transformer({'data': input_shape}) if self._net.blobs['data'].data.shape[1] ...
CaffeNet
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CaffeNet: def __init__(self, net_proto, net_weights, device_id): """Initialize CaffeNet :param net_proto: file path for deploy protxt :param net_weights: file path for model weights :param device_id: GPU device ID :param input_size: size(H, W) of the input frame""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_001213
3,671
permissive
[ { "docstring": "Initialize CaffeNet :param net_proto: file path for deploy protxt :param net_weights: file path for model weights :param device_id: GPU device ID :param input_size: size(H, W) of the input frame", "name": "__init__", "signature": "def __init__(self, net_proto, net_weights, device_id)" ...
3
stack_v2_sparse_classes_30k_train_003294
Implement the Python class `CaffeNet` described below. Class description: Implement the CaffeNet class. Method signatures and docstrings: - def __init__(self, net_proto, net_weights, device_id): Initialize CaffeNet :param net_proto: file path for deploy protxt :param net_weights: file path for model weights :param de...
Implement the Python class `CaffeNet` described below. Class description: Implement the CaffeNet class. Method signatures and docstrings: - def __init__(self, net_proto, net_weights, device_id): Initialize CaffeNet :param net_proto: file path for deploy protxt :param net_weights: file path for model weights :param de...
f383280d61c80be72cffb77cc1ae6d7dcee7353d
<|skeleton|> class CaffeNet: def __init__(self, net_proto, net_weights, device_id): """Initialize CaffeNet :param net_proto: file path for deploy protxt :param net_weights: file path for model weights :param device_id: GPU device ID :param input_size: size(H, W) of the input frame""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CaffeNet: def __init__(self, net_proto, net_weights, device_id): """Initialize CaffeNet :param net_proto: file path for deploy protxt :param net_weights: file path for model weights :param device_id: GPU device ID :param input_size: size(H, W) of the input frame""" caffe.set_mode_gpu() ...
the_stack_v2_python_sparse
TSN_eval/pyActionRec/action_caffe.py
JaredYeDH/ActionRecognitionDisney
train
1
19eba7f6d685ad9ced4caed6f71b2d671bfccada
[ "response = self.client.get(reverse('accounts:login'))\nself.assertEqual(response.status_code, 200)\nself.assertContains(response, 'Sign up')\nself.assertContains(response, 'Log in')\nself.assertNotContains(response, 'Import Music')\nself.assertNotContains(response, 'Insights')\nself.assertNotContains(response, 'Mu...
<|body_start_0|> response = self.client.get(reverse('accounts:login')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Sign up') self.assertContains(response, 'Log in') self.assertNotContains(response, 'Import Music') self.assertNotContains(resp...
Test views behaviour related to authentication
TestAuthViewsBehaviour
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestAuthViewsBehaviour: """Test views behaviour related to authentication""" def test_navbar(self): """Verify that the navbar does not display login based view to an anonymous user.""" <|body_0|> def test_profile(self): """Make sure that the profile page is login...
stack_v2_sparse_classes_36k_train_001214
3,810
no_license
[ { "docstring": "Verify that the navbar does not display login based view to an anonymous user.", "name": "test_navbar", "signature": "def test_navbar(self)" }, { "docstring": "Make sure that the profile page is login-only and display the required buttons.", "name": "test_profile", "signa...
2
stack_v2_sparse_classes_30k_train_013480
Implement the Python class `TestAuthViewsBehaviour` described below. Class description: Test views behaviour related to authentication Method signatures and docstrings: - def test_navbar(self): Verify that the navbar does not display login based view to an anonymous user. - def test_profile(self): Make sure that the ...
Implement the Python class `TestAuthViewsBehaviour` described below. Class description: Test views behaviour related to authentication Method signatures and docstrings: - def test_navbar(self): Verify that the navbar does not display login based view to an anonymous user. - def test_profile(self): Make sure that the ...
e2d6a0336c7934cae71f833cb34a1f5f21db2d02
<|skeleton|> class TestAuthViewsBehaviour: """Test views behaviour related to authentication""" def test_navbar(self): """Verify that the navbar does not display login based view to an anonymous user.""" <|body_0|> def test_profile(self): """Make sure that the profile page is login...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestAuthViewsBehaviour: """Test views behaviour related to authentication""" def test_navbar(self): """Verify that the navbar does not display login based view to an anonymous user.""" response = self.client.get(reverse('accounts:login')) self.assertEqual(response.status_code, 200...
the_stack_v2_python_sparse
accounts/tests_views.py
gbip/djRDO
train
3
19b9d89ec49f61ae551cb58ed2ed24823b7a7629
[ "if key != 'line':\n raise errors.ParseError('Unable to parse record, unknown structure: {0:s}'.format(key))\ntime_elements_structure = structure.get('date_time', None)\ntry:\n year, month, day_of_month, hours, minutes, seconds = time_elements_structure\n date_time = dfdatetime_time_elements.TimeElements(t...
<|body_start_0|> if key != 'line': raise errors.ParseError('Unable to parse record, unknown structure: {0:s}'.format(key)) time_elements_structure = structure.get('date_time', None) try: year, month, day_of_month, hours, minutes, seconds = time_elements_structure ...
Parser for Debian package manager log (dpkg.log) files.
DpkgParser
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DpkgParser: """Parser for Debian package manager log (dpkg.log) files.""" def ParseRecord(self, parser_mediator, key, structure): """Parses a structure of tokens derived from a line of a text file. Args: parser_mediator (ParserMediator): parser mediator. key (str): identifier of the ...
stack_v2_sparse_classes_36k_train_001215
5,795
permissive
[ { "docstring": "Parses a structure of tokens derived from a line of a text file. Args: parser_mediator (ParserMediator): parser mediator. key (str): identifier of the structure of tokens. structure (pyparsing.ParseResults): structure of tokens derived from a line of a text file. Raises: ParseError: when the str...
2
null
Implement the Python class `DpkgParser` described below. Class description: Parser for Debian package manager log (dpkg.log) files. Method signatures and docstrings: - def ParseRecord(self, parser_mediator, key, structure): Parses a structure of tokens derived from a line of a text file. Args: parser_mediator (Parser...
Implement the Python class `DpkgParser` described below. Class description: Parser for Debian package manager log (dpkg.log) files. Method signatures and docstrings: - def ParseRecord(self, parser_mediator, key, structure): Parses a structure of tokens derived from a line of a text file. Args: parser_mediator (Parser...
c69b2952b608cfce47ff8fd0d1409d856be35cb1
<|skeleton|> class DpkgParser: """Parser for Debian package manager log (dpkg.log) files.""" def ParseRecord(self, parser_mediator, key, structure): """Parses a structure of tokens derived from a line of a text file. Args: parser_mediator (ParserMediator): parser mediator. key (str): identifier of the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DpkgParser: """Parser for Debian package manager log (dpkg.log) files.""" def ParseRecord(self, parser_mediator, key, structure): """Parses a structure of tokens derived from a line of a text file. Args: parser_mediator (ParserMediator): parser mediator. key (str): identifier of the structure of ...
the_stack_v2_python_sparse
plaso/parsers/dpkg.py
cyb3rfox/plaso
train
3
405bf38da00557f01944a124ac4c5ab04c3f26d9
[ "if not api_key_id:\n api_keys = []\n for api_key in API_Key.objects.filter(user=request.user):\n api_keys.append({'id': api_key.id, 'title': api_key.title, 'read': api_key.read, 'write': api_key.write, 'restrict_to_secrets': api_key.restrict_to_secrets, 'allow_insecure_access': api_key.allow_insecure_...
<|body_start_0|> if not api_key_id: api_keys = [] for api_key in API_Key.objects.filter(user=request.user): api_keys.append({'id': api_key.id, 'title': api_key.title, 'read': api_key.read, 'write': api_key.write, 'restrict_to_secrets': api_key.restrict_to_secrets, 'allow_...
Check the REST Token and returns a list of all api_keys or the specified api_keys details
APIKeyView
[ "BSD-3-Clause", "MIT", "Apache-2.0", "BSD-2-Clause", "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class APIKeyView: """Check the REST Token and returns a list of all api_keys or the specified api_keys details""" def get(self, request, api_key_id=None, *args, **kwargs): """Returns either a list of all api_keys with own access privileges or the members specified api_key :param request: :...
stack_v2_sparse_classes_36k_train_001216
7,116
permissive
[ { "docstring": "Returns either a list of all api_keys with own access privileges or the members specified api_key :param request: :type request: :param api_key_id: :type api_key_id: :param args: :type args: :param kwargs: :type kwargs: :return: 200 / 403 :rtype:", "name": "get", "signature": "def get(se...
4
stack_v2_sparse_classes_30k_test_000565
Implement the Python class `APIKeyView` described below. Class description: Check the REST Token and returns a list of all api_keys or the specified api_keys details Method signatures and docstrings: - def get(self, request, api_key_id=None, *args, **kwargs): Returns either a list of all api_keys with own access priv...
Implement the Python class `APIKeyView` described below. Class description: Check the REST Token and returns a list of all api_keys or the specified api_keys details Method signatures and docstrings: - def get(self, request, api_key_id=None, *args, **kwargs): Returns either a list of all api_keys with own access priv...
8936aa8ccdee8b9617ef7d894cb9a9a9f6f473cf
<|skeleton|> class APIKeyView: """Check the REST Token and returns a list of all api_keys or the specified api_keys details""" def get(self, request, api_key_id=None, *args, **kwargs): """Returns either a list of all api_keys with own access privileges or the members specified api_key :param request: :...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class APIKeyView: """Check the REST Token and returns a list of all api_keys or the specified api_keys details""" def get(self, request, api_key_id=None, *args, **kwargs): """Returns either a list of all api_keys with own access privileges or the members specified api_key :param request: :type request:...
the_stack_v2_python_sparse
psono/restapi/views/api_key.py
psono/psono-server
train
76
5d148267feda7ced61fd42724430edf36f69c76b
[ "config = casper_formatters.FormatterConfig.from_dict({'rename_labels': {'SL:MUSIC_ITEM': 'SL:THING', 'SL:PLAYLIST': ''}})\nexemplar_outputs, orig_output = casper_formatters.top_funcall_processor([_MUSIC_EXAMPLES[0], _MUSIC_EXAMPLES[1]], _MUSIC_EXAMPLES[2], config)\nself.assertEqual(exemplar_outputs, ['[IN add to p...
<|body_start_0|> config = casper_formatters.FormatterConfig.from_dict({'rename_labels': {'SL:MUSIC_ITEM': 'SL:THING', 'SL:PLAYLIST': ''}}) exemplar_outputs, orig_output = casper_formatters.top_funcall_processor([_MUSIC_EXAMPLES[0], _MUSIC_EXAMPLES[1]], _MUSIC_EXAMPLES[2], config) self.assertEqua...
TopFuncallProcessorTest
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TopFuncallProcessorTest: def test_rename_labels(self): """Tests rename on the labels.""" <|body_0|> def test_anonymize(self): """Tests anonymization.""" <|body_1|> <|end_skeleton|> <|body_start_0|> config = casper_formatters.FormatterConfig.from_dic...
stack_v2_sparse_classes_36k_train_001217
7,201
permissive
[ { "docstring": "Tests rename on the labels.", "name": "test_rename_labels", "signature": "def test_rename_labels(self)" }, { "docstring": "Tests anonymization.", "name": "test_anonymize", "signature": "def test_anonymize(self)" } ]
2
null
Implement the Python class `TopFuncallProcessorTest` described below. Class description: Implement the TopFuncallProcessorTest class. Method signatures and docstrings: - def test_rename_labels(self): Tests rename on the labels. - def test_anonymize(self): Tests anonymization.
Implement the Python class `TopFuncallProcessorTest` described below. Class description: Implement the TopFuncallProcessorTest class. Method signatures and docstrings: - def test_rename_labels(self): Tests rename on the labels. - def test_anonymize(self): Tests anonymization. <|skeleton|> class TopFuncallProcessorTe...
ac9447064195e06de48cc91ff642f7fffa28ffe8
<|skeleton|> class TopFuncallProcessorTest: def test_rename_labels(self): """Tests rename on the labels.""" <|body_0|> def test_anonymize(self): """Tests anonymization.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TopFuncallProcessorTest: def test_rename_labels(self): """Tests rename on the labels.""" config = casper_formatters.FormatterConfig.from_dict({'rename_labels': {'SL:MUSIC_ITEM': 'SL:THING', 'SL:PLAYLIST': ''}}) exemplar_outputs, orig_output = casper_formatters.top_funcall_processor([_M...
the_stack_v2_python_sparse
language/casper/augment/casper_formatters_test.py
google-research/language
train
1,567
3f62fb6b54a88cda376cdbe83dcf2c24e444bd61
[ "super().__init__()\nself.num_blocks = num_blocks\nself.num_classes = num_classes\nblocks = []\nfor i in range(self.num_blocks):\n subsample = i == 0\n blocks.append(ResNetBlock(c_in=64 if not subsample else 32, act_fn=nn.ReLU(), subsample=subsample, c_out=64))\nself.blocks = nn.Sequential(*blocks)\nself.outp...
<|body_start_0|> super().__init__() self.num_blocks = num_blocks self.num_classes = num_classes blocks = [] for i in range(self.num_blocks): subsample = i == 0 blocks.append(ResNetBlock(c_in=64 if not subsample else 32, act_fn=nn.ReLU(), subsample=subsampl...
ResNet decoder model
Resnet_Decoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Resnet_Decoder: """ResNet decoder model""" def __init__(self, num_blocks, num_classes): """Decoder module of the network Inputs: num_block - Number of ResNet blocks. num_classes - Number of classes of images.""" <|body_0|> def forward(self, encoded_batch, thetas): ...
stack_v2_sparse_classes_36k_train_001218
17,101
no_license
[ { "docstring": "Decoder module of the network Inputs: num_block - Number of ResNet blocks. num_classes - Number of classes of images.", "name": "__init__", "signature": "def __init__(self, num_blocks, num_classes)" }, { "docstring": "Forward pass of the decoder. Inputs: encoded_batch - Input bat...
2
stack_v2_sparse_classes_30k_train_003200
Implement the Python class `Resnet_Decoder` described below. Class description: ResNet decoder model Method signatures and docstrings: - def __init__(self, num_blocks, num_classes): Decoder module of the network Inputs: num_block - Number of ResNet blocks. num_classes - Number of classes of images. - def forward(self...
Implement the Python class `Resnet_Decoder` described below. Class description: ResNet decoder model Method signatures and docstrings: - def __init__(self, num_blocks, num_classes): Decoder module of the network Inputs: num_block - Number of ResNet blocks. num_classes - Number of classes of images. - def forward(self...
0b65d43a9bb5e70d7e4e3fcd322b47b173e16fa6
<|skeleton|> class Resnet_Decoder: """ResNet decoder model""" def __init__(self, num_blocks, num_classes): """Decoder module of the network Inputs: num_block - Number of ResNet blocks. num_classes - Number of classes of images.""" <|body_0|> def forward(self, encoded_batch, thetas): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Resnet_Decoder: """ResNet decoder model""" def __init__(self, num_blocks, num_classes): """Decoder module of the network Inputs: num_block - Number of ResNet blocks. num_classes - Number of classes of images.""" super().__init__() self.num_blocks = num_blocks self.num_clas...
the_stack_v2_python_sparse
models/resnet/complex_resnet.py
RamonDijkstra/AI-FACT
train
0
0cc89a1f219bf1767c7e4bbd8051aea3096bed14
[ "self.w = w\nif not w:\n return\nself.n = len(w)\nself.s = sum(w)\nfor i in range(1, self.n):\n self.w[i] = self.w[i] + self.w[i - 1]", "import random\nseed = random.randint(1, self.s)\nlo, hi = (0, self.n - 1)\nwhile lo < hi:\n mid = (lo + hi) / 2\n if seed <= self.w[mid]:\n hi = mid\n else...
<|body_start_0|> self.w = w if not w: return self.n = len(w) self.s = sum(w) for i in range(1, self.n): self.w[i] = self.w[i] + self.w[i - 1] <|end_body_0|> <|body_start_1|> import random seed = random.randint(1, self.s) lo, hi = (...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def __init__(self, w): """:type w: List[int]""" <|body_0|> def pickIndex(self): """:rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.w = w if not w: return self.n = len(w) self.s = sum(w) ...
stack_v2_sparse_classes_36k_train_001219
980
no_license
[ { "docstring": ":type w: List[int]", "name": "__init__", "signature": "def __init__(self, w)" }, { "docstring": ":rtype: int", "name": "pickIndex", "signature": "def pickIndex(self)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def __init__(self, w): :type w: List[int] - def pickIndex(self): :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def __init__(self, w): :type w: List[int] - def pickIndex(self): :rtype: int <|skeleton|> class Solution: def __init__(self, w): """:type w: List[int]""" <|...
877933424e6d2c590d6ac53db18bee951a3d9de4
<|skeleton|> class Solution: def __init__(self, w): """:type w: List[int]""" <|body_0|> def pickIndex(self): """:rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def __init__(self, w): """:type w: List[int]""" self.w = w if not w: return self.n = len(w) self.s = sum(w) for i in range(1, self.n): self.w[i] = self.w[i] + self.w[i - 1] def pickIndex(self): """:rtype: int""" ...
the_stack_v2_python_sparse
leetcode/528.random-pick-with-weight.py
siddhism/leetcode
train
0
92eefe700a58dd9ded49125a17f3a50c9472e724
[ "self._input_model_blueprint = input_model_blueprint\nif 'galaxy_selection_func' in kwargs.keys():\n self.galaxy_selection_func = kwargs['galaxy_selection_func']", "if hasattr(self, 'mock'):\n self.mock.populate()\nelse:\n if 'snapshot' in kwargs.keys():\n snapshot = kwargs['snapshot']\n de...
<|body_start_0|> self._input_model_blueprint = input_model_blueprint if 'galaxy_selection_func' in kwargs.keys(): self.galaxy_selection_func = kwargs['galaxy_selection_func'] <|end_body_0|> <|body_start_1|> if hasattr(self, 'mock'): self.mock.populate() else: ...
Abstract container class used to build any composite model of the galaxy-halo connection.
ModelFactory
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModelFactory: """Abstract container class used to build any composite model of the galaxy-halo connection.""" def __init__(self, input_model_blueprint, **kwargs): """Parameters ---------- input_model_blueprint : dict Blueprint providing instructions for how to build the composite mod...
stack_v2_sparse_classes_36k_train_001220
28,353
permissive
[ { "docstring": "Parameters ---------- input_model_blueprint : dict Blueprint providing instructions for how to build the composite model from a set of components. galaxy_selection_func : function object, optional keyword argument Function object that imposes a cut on the mock galaxies. Function should take an A...
2
null
Implement the Python class `ModelFactory` described below. Class description: Abstract container class used to build any composite model of the galaxy-halo connection. Method signatures and docstrings: - def __init__(self, input_model_blueprint, **kwargs): Parameters ---------- input_model_blueprint : dict Blueprint ...
Implement the Python class `ModelFactory` described below. Class description: Abstract container class used to build any composite model of the galaxy-halo connection. Method signatures and docstrings: - def __init__(self, input_model_blueprint, **kwargs): Parameters ---------- input_model_blueprint : dict Blueprint ...
f63988f7e1d66c7c19d7c2b4d628ed2524b7aec1
<|skeleton|> class ModelFactory: """Abstract container class used to build any composite model of the galaxy-halo connection.""" def __init__(self, input_model_blueprint, **kwargs): """Parameters ---------- input_model_blueprint : dict Blueprint providing instructions for how to build the composite mod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ModelFactory: """Abstract container class used to build any composite model of the galaxy-halo connection.""" def __init__(self, input_model_blueprint, **kwargs): """Parameters ---------- input_model_blueprint : dict Blueprint providing instructions for how to build the composite model from a set...
the_stack_v2_python_sparse
halotools/empirical_models/model_factories.py
lanakurdi/halotools
train
1
a6839b95fb0910b808a46135e0ba37d8e2997d52
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn FeatureRolloutPolicy()", "from .directory_object import DirectoryObject\nfrom .entity import Entity\nfrom .staged_feature_name import StagedFeatureName\nfrom .directory_object import DirectoryObject\nfrom .entity import Entity\nfrom .s...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return FeatureRolloutPolicy() <|end_body_0|> <|body_start_1|> from .directory_object import DirectoryObject from .entity import Entity from .staged_feature_name import StagedFeatureName...
FeatureRolloutPolicy
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeatureRolloutPolicy: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FeatureRolloutPolicy: """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 ...
stack_v2_sparse_classes_36k_train_001221
3,749
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: FeatureRolloutPolicy", "name": "create_from_discriminator_value", "signature": "def create_from_discriminato...
3
stack_v2_sparse_classes_30k_train_014095
Implement the Python class `FeatureRolloutPolicy` described below. Class description: Implement the FeatureRolloutPolicy class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FeatureRolloutPolicy: Creates a new instance of the appropriate class based o...
Implement the Python class `FeatureRolloutPolicy` described below. Class description: Implement the FeatureRolloutPolicy class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FeatureRolloutPolicy: Creates a new instance of the appropriate class based o...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class FeatureRolloutPolicy: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FeatureRolloutPolicy: """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 ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FeatureRolloutPolicy: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FeatureRolloutPolicy: """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...
the_stack_v2_python_sparse
msgraph/generated/models/feature_rollout_policy.py
microsoftgraph/msgraph-sdk-python
train
135
80f395b024f362925ada43334b415ffb18d71c11
[ "command_name = command_node.get('CommandName')\ncommand_id = command_node.get('CommandId')\ncommand_params = defaultdict(list)\nnamespace = XMLHelper.get_node_namespace(command_node)\nparameters_node = command_node.find(namespace + 'Parameters')\nif parameters_node is not None:\n for param_node in parameters_no...
<|body_start_0|> command_name = command_node.get('CommandName') command_id = command_node.get('CommandId') command_params = defaultdict(list) namespace = XMLHelper.get_node_namespace(command_node) parameters_node = command_node.find(namespace + 'Parameters') if parameters...
Parse request data and build command requests.
RequestsParser
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RequestsParser: """Parse request data and build command requests.""" def _build_command_instance(command_node: Element) -> CommandRequest: """Build command instance for command node.""" <|body_0|> def parse_request_commands(xml_request: str) -> list: """Parse xml...
stack_v2_sparse_classes_36k_train_001222
1,428
no_license
[ { "docstring": "Build command instance for command node.", "name": "_build_command_instance", "signature": "def _build_command_instance(command_node: Element) -> CommandRequest" }, { "docstring": "Parse xml request and create command instances.", "name": "parse_request_commands", "signat...
2
stack_v2_sparse_classes_30k_train_015324
Implement the Python class `RequestsParser` described below. Class description: Parse request data and build command requests. Method signatures and docstrings: - def _build_command_instance(command_node: Element) -> CommandRequest: Build command instance for command node. - def parse_request_commands(xml_request: st...
Implement the Python class `RequestsParser` described below. Class description: Parse request data and build command requests. Method signatures and docstrings: - def _build_command_instance(command_node: Element) -> CommandRequest: Build command instance for command node. - def parse_request_commands(xml_request: st...
82562665834908294136bbe8e7bc46da1a21b8e2
<|skeleton|> class RequestsParser: """Parse request data and build command requests.""" def _build_command_instance(command_node: Element) -> CommandRequest: """Build command instance for command node.""" <|body_0|> def parse_request_commands(xml_request: str) -> list: """Parse xml...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RequestsParser: """Parse request data and build command requests.""" def _build_command_instance(command_node: Element) -> CommandRequest: """Build command instance for command node.""" command_name = command_node.get('CommandName') command_id = command_node.get('CommandId') ...
the_stack_v2_python_sparse
cloudshell/layer_one/core/request/requests_parser.py
QualiSystems/cloudshell-L1-networking-core
train
1
48db0ce376d1cb5ac2397a62f510204955c4d039
[ "self.client_id = client_id\nself.client_secret = client_secret\nself.redirect_uri = redirect_uri\nsuper(XiaoMiOAuth, self).__init__()", "url = 'https://account.xiaomi.com/oauth2/token'\ntry:\n resp = requests.get(url, params={'client_id': self.client_id, 'redirect_uri': self.redirect_uri, 'client_secret': sel...
<|body_start_0|> self.client_id = client_id self.client_secret = client_secret self.redirect_uri = redirect_uri super(XiaoMiOAuth, self).__init__() <|end_body_0|> <|body_start_1|> url = 'https://account.xiaomi.com/oauth2/token' try: resp = requests.get(url, p...
微信APP登录后端Oauth SDK
XiaoMiOAuth
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XiaoMiOAuth: """微信APP登录后端Oauth SDK""" def __init__(self, client_id, client_secret, redirect_uri): """:param str client_id: 应用id :param str client_secret: 应用secret :param str redirect_uri: 应用重定向url""" <|body_0|> def get_access_token(self, code): """根据code获取access_...
stack_v2_sparse_classes_36k_train_001223
6,043
no_license
[ { "docstring": ":param str client_id: 应用id :param str client_secret: 应用secret :param str redirect_uri: 应用重定向url", "name": "__init__", "signature": "def __init__(self, client_id, client_secret, redirect_uri)" }, { "docstring": "根据code获取access_token :param str code: 客户端从小米那里获取的获取access_token的串码 :e...
6
null
Implement the Python class `XiaoMiOAuth` described below. Class description: 微信APP登录后端Oauth SDK Method signatures and docstrings: - def __init__(self, client_id, client_secret, redirect_uri): :param str client_id: 应用id :param str client_secret: 应用secret :param str redirect_uri: 应用重定向url - def get_access_token(self, c...
Implement the Python class `XiaoMiOAuth` described below. Class description: 微信APP登录后端Oauth SDK Method signatures and docstrings: - def __init__(self, client_id, client_secret, redirect_uri): :param str client_id: 应用id :param str client_secret: 应用secret :param str redirect_uri: 应用重定向url - def get_access_token(self, c...
437cbb94af1c8c407158f5a1757fbce72ebd64fd
<|skeleton|> class XiaoMiOAuth: """微信APP登录后端Oauth SDK""" def __init__(self, client_id, client_secret, redirect_uri): """:param str client_id: 应用id :param str client_secret: 应用secret :param str redirect_uri: 应用重定向url""" <|body_0|> def get_access_token(self, code): """根据code获取access_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class XiaoMiOAuth: """微信APP登录后端Oauth SDK""" def __init__(self, client_id, client_secret, redirect_uri): """:param str client_id: 应用id :param str client_secret: 应用secret :param str redirect_uri: 应用重定向url""" self.client_id = client_id self.client_secret = client_secret self.redire...
the_stack_v2_python_sparse
pieces/oauth/xiaomiOAuth.py
weidwonder/python_codes
train
0
e6164e470ea8b3e7fb60a21db9dd465ee5738e07
[ "miner = Miner(name='Miner', version='1.0.b')\nminer.slug = get_unique_slug(miner, 'slug', 'name', 'version')\nminer.save()\nother_miner = Miner(name='MineR', version='1.0.b')\nother_miner.slug = get_unique_slug(other_miner, 'slug', 'name', 'version')\nself.assertNotEqual(miner.slug, other_miner.slug)", "miner = ...
<|body_start_0|> miner = Miner(name='Miner', version='1.0.b') miner.slug = get_unique_slug(miner, 'slug', 'name', 'version') miner.save() other_miner = Miner(name='MineR', version='1.0.b') other_miner.slug = get_unique_slug(other_miner, 'slug', 'name', 'version') self.ass...
Тестирование гнерератора slug
GetSlugTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetSlugTest: """Тестирование гнерератора slug""" def test_get_unique_slug(self): """Генерация уникального slug""" <|body_0|> def test_get_unique_slug_conflict(self): """Генерация уникального slug недопустимого значения""" <|body_1|> def test_get_slug...
stack_v2_sparse_classes_36k_train_001224
13,105
permissive
[ { "docstring": "Генерация уникального slug", "name": "test_get_unique_slug", "signature": "def test_get_unique_slug(self)" }, { "docstring": "Генерация уникального slug недопустимого значения", "name": "test_get_unique_slug_conflict", "signature": "def test_get_unique_slug_conflict(self)...
5
stack_v2_sparse_classes_30k_train_019690
Implement the Python class `GetSlugTest` described below. Class description: Тестирование гнерератора slug Method signatures and docstrings: - def test_get_unique_slug(self): Генерация уникального slug - def test_get_unique_slug_conflict(self): Генерация уникального slug недопустимого значения - def test_get_slug(sel...
Implement the Python class `GetSlugTest` described below. Class description: Тестирование гнерератора slug Method signatures and docstrings: - def test_get_unique_slug(self): Генерация уникального slug - def test_get_unique_slug_conflict(self): Генерация уникального slug недопустимого значения - def test_get_slug(sel...
d173f1bee44d0752eefb53b1a0da847a3882a352
<|skeleton|> class GetSlugTest: """Тестирование гнерератора slug""" def test_get_unique_slug(self): """Генерация уникального slug""" <|body_0|> def test_get_unique_slug_conflict(self): """Генерация уникального slug недопустимого значения""" <|body_1|> def test_get_slug...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GetSlugTest: """Тестирование гнерератора slug""" def test_get_unique_slug(self): """Генерация уникального slug""" miner = Miner(name='Miner', version='1.0.b') miner.slug = get_unique_slug(miner, 'slug', 'name', 'version') miner.save() other_miner = Miner(name='Mine...
the_stack_v2_python_sparse
miningstatistic/core/tests.py
crowmurk/miners
train
0
b73f7baa472282578856cf05f8255f75c69f1e8c
[ "hc = self.job.hazard_calculation\noutput = models.Output.objects.create(owner=self.job.owner, oq_job=self.job, display_name='ses-coll-rlz-%s' % lt_rlz.id, output_type='ses')\nses_coll = models.SESCollection.objects.create(output=output, lt_realization=lt_rlz)\nfor i in xrange(1, hc.ses_per_logic_tree_path + 1):\n ...
<|body_start_0|> hc = self.job.hazard_calculation output = models.Output.objects.create(owner=self.job.owner, oq_job=self.job, display_name='ses-coll-rlz-%s' % lt_rlz.id, output_type='ses') ses_coll = models.SESCollection.objects.create(output=output, lt_realization=lt_rlz) for i in xran...
Probabilistic Event-Based hazard calculator. Computes stochastic event sets and (optionally) ground motion fields.
EventBasedHazardCalculator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EventBasedHazardCalculator: """Probabilistic Event-Based hazard calculator. Computes stochastic event sets and (optionally) ground motion fields.""" def initialize_ses_db_records(self, lt_rlz): """Create :class:`~openquake.db.models.Output`, :class:`~openquake.db.models.SESCollection...
stack_v2_sparse_classes_36k_train_001225
24,175
no_license
[ { "docstring": "Create :class:`~openquake.db.models.Output`, :class:`~openquake.db.models.SESCollection` and :class:`~openquake.db.models.SES` \"container\" records for a single realization. Stochastic event set ruptures computed for this realization will be associated to these containers.", "name": "initia...
6
null
Implement the Python class `EventBasedHazardCalculator` described below. Class description: Probabilistic Event-Based hazard calculator. Computes stochastic event sets and (optionally) ground motion fields. Method signatures and docstrings: - def initialize_ses_db_records(self, lt_rlz): Create :class:`~openquake.db.m...
Implement the Python class `EventBasedHazardCalculator` described below. Class description: Probabilistic Event-Based hazard calculator. Computes stochastic event sets and (optionally) ground motion fields. Method signatures and docstrings: - def initialize_ses_db_records(self, lt_rlz): Create :class:`~openquake.db.m...
d253f09d7848e6cf32e8c7756551436da413176b
<|skeleton|> class EventBasedHazardCalculator: """Probabilistic Event-Based hazard calculator. Computes stochastic event sets and (optionally) ground motion fields.""" def initialize_ses_db_records(self, lt_rlz): """Create :class:`~openquake.db.models.Output`, :class:`~openquake.db.models.SESCollection...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EventBasedHazardCalculator: """Probabilistic Event-Based hazard calculator. Computes stochastic event sets and (optionally) ground motion fields.""" def initialize_ses_db_records(self, lt_rlz): """Create :class:`~openquake.db.models.Output`, :class:`~openquake.db.models.SESCollection` and :class:...
the_stack_v2_python_sparse
noq/openquake/calculators/hazard/event_based/core_next.py
arbeit/openquake-packages
train
1
f1eb27336ec62cf7253d36e84459404c05f4cfc1
[ "lowerInput = str(stringNeedingStrip).lower()\nfor item in trailingWords:\n lowerItem = item.lower()\n if lowerInput.endswith(lowerItem):\n return stringNeedingStrip[:-len(item)]\nreturn stringNeedingStrip", "valid = {'true': True, 't': True, '1': True, 'false': False, 'f': False, '0': False}\nif isi...
<|body_start_0|> lowerInput = str(stringNeedingStrip).lower() for item in trailingWords: lowerItem = item.lower() if lowerInput.endswith(lowerItem): return stringNeedingStrip[:-len(item)] return stringNeedingStrip <|end_body_0|> <|body_start_1|> v...
Utility functions for parsing input strings
StringUtils
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StringUtils: """Utility functions for parsing input strings""" def stripTrailingWordsIgnoreCase(cls, stringNeedingStrip, trailingWords): """params string to parse, trailing word list eg trailingWords = ["f","ft","feet","m","meters"] NB this ignores case""" <|body_0|> def...
stack_v2_sparse_classes_36k_train_001226
1,397
permissive
[ { "docstring": "params string to parse, trailing word list eg trailingWords = [\"f\",\"ft\",\"feet\",\"m\",\"meters\"] NB this ignores case", "name": "stripTrailingWordsIgnoreCase", "signature": "def stripTrailingWordsIgnoreCase(cls, stringNeedingStrip, trailingWords)" }, { "docstring": "in most...
2
null
Implement the Python class `StringUtils` described below. Class description: Utility functions for parsing input strings Method signatures and docstrings: - def stripTrailingWordsIgnoreCase(cls, stringNeedingStrip, trailingWords): params string to parse, trailing word list eg trailingWords = ["f","ft","feet","m","met...
Implement the Python class `StringUtils` described below. Class description: Utility functions for parsing input strings Method signatures and docstrings: - def stripTrailingWordsIgnoreCase(cls, stringNeedingStrip, trailingWords): params string to parse, trailing word list eg trailingWords = ["f","ft","feet","m","met...
20fba1b1fd1a42add223d9e8af2d267665bec493
<|skeleton|> class StringUtils: """Utility functions for parsing input strings""" def stripTrailingWordsIgnoreCase(cls, stringNeedingStrip, trailingWords): """params string to parse, trailing word list eg trailingWords = ["f","ft","feet","m","meters"] NB this ignores case""" <|body_0|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StringUtils: """Utility functions for parsing input strings""" def stripTrailingWordsIgnoreCase(cls, stringNeedingStrip, trailingWords): """params string to parse, trailing word list eg trailingWords = ["f","ft","feet","m","meters"] NB this ignores case""" lowerInput = str(stringNeedingSt...
the_stack_v2_python_sparse
qrutilities/stringutils.py
ABV-Hub/qreservoir
train
0
eed46b232de6089dfbc0c94bdc459644f0fc17fb
[ "self._cwp_pairwise_inclusive_reference = cwp_pairwise_inclusive_reference\nself._cwp_pairwise_inclusive_test = cwp_pairwise_inclusive_test\nself._cwp_inclusive_reference = cwp_inclusive_reference\nself._cwp_inclusive_test = cwp_inclusive_test\nself._cwp_function_groups_file = cwp_function_groups_file\nself._cwp_fu...
<|body_start_0|> self._cwp_pairwise_inclusive_reference = cwp_pairwise_inclusive_reference self._cwp_pairwise_inclusive_test = cwp_pairwise_inclusive_test self._cwp_inclusive_reference = cwp_inclusive_reference self._cwp_inclusive_test = cwp_inclusive_test self._cwp_function_grou...
Runs an experiment with the benchmark metrics on a pair of data sets.
MetricsExperiment
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetricsExperiment: """Runs an experiment with the benchmark metrics on a pair of data sets.""" def __init__(self, cwp_pairwise_inclusive_reference, cwp_pairwise_inclusive_test, cwp_inclusive_reference, cwp_inclusive_test, cwp_function_groups_file, cwp_function_groups_statistics_file, cwp_fun...
stack_v2_sparse_classes_36k_train_001227
10,188
permissive
[ { "docstring": "Initializes the MetricsExperiment class. Args: cwp_pairwise_inclusive_reference: The CSV file containing the pairwise inclusive values from the reference data set. cwp_pairwise_inclusive_test: The CSV file containing the pairwise inclusive values from the test data set. cwp_inclusive_reference: ...
2
null
Implement the Python class `MetricsExperiment` described below. Class description: Runs an experiment with the benchmark metrics on a pair of data sets. Method signatures and docstrings: - def __init__(self, cwp_pairwise_inclusive_reference, cwp_pairwise_inclusive_test, cwp_inclusive_reference, cwp_inclusive_test, cw...
Implement the Python class `MetricsExperiment` described below. Class description: Runs an experiment with the benchmark metrics on a pair of data sets. Method signatures and docstrings: - def __init__(self, cwp_pairwise_inclusive_reference, cwp_pairwise_inclusive_test, cwp_inclusive_reference, cwp_inclusive_test, cw...
e2745b756317aac3c7a27a4c10bdfe0921a82a1c
<|skeleton|> class MetricsExperiment: """Runs an experiment with the benchmark metrics on a pair of data sets.""" def __init__(self, cwp_pairwise_inclusive_reference, cwp_pairwise_inclusive_test, cwp_inclusive_reference, cwp_inclusive_test, cwp_function_groups_file, cwp_function_groups_statistics_file, cwp_fun...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MetricsExperiment: """Runs an experiment with the benchmark metrics on a pair of data sets.""" def __init__(self, cwp_pairwise_inclusive_reference, cwp_pairwise_inclusive_test, cwp_inclusive_reference, cwp_inclusive_test, cwp_function_groups_file, cwp_function_groups_statistics_file, cwp_function_statist...
the_stack_v2_python_sparse
app/src/main/java/com/syd/source/aosp/external/toolchain-utils/user_activity_benchmarks/benchmark_metrics_experiment.py
lz-purple/Source
train
4
37da4aae6ba58ab9c46ad3801c1f2baffd7a71a1
[ "kwargs, independent = common._SimplePluginStart('AccessTerminal').startDisplay()\nkwargs['parent'] = parent\nreturn (self(**kwargs), independent)", "super(AccessTerminal, self).__init__(name=name, parent=parent)\nself.central_widget = QtWidgets.QWidget()\nself.setCentralWidget(self.central_widget)\nself.layout =...
<|body_start_0|> kwargs, independent = common._SimplePluginStart('AccessTerminal').startDisplay() kwargs['parent'] = parent return (self(**kwargs), independent) <|end_body_0|> <|body_start_1|> super(AccessTerminal, self).__init__(name=name, parent=parent) self.central_widget = Q...
Open an interactive python console so the direct manipulation
AccessTerminal
[ "LGPL-2.1-or-later", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccessTerminal: """Open an interactive python console so the direct manipulation""" def guiStart(self, parent=None): """Graphical interface for starting this class.""" <|body_0|> def __init__(self, name='AccessTerminal', parent=None): """Initialize the class to c...
stack_v2_sparse_classes_36k_train_001228
2,902
permissive
[ { "docstring": "Graphical interface for starting this class.", "name": "guiStart", "signature": "def guiStart(self, parent=None)" }, { "docstring": "Initialize the class to create the interface. Parameters ---------- [Optional] name : string Field Radiobutton window name. parent : PyQt instance ...
3
stack_v2_sparse_classes_30k_train_013499
Implement the Python class `AccessTerminal` described below. Class description: Open an interactive python console so the direct manipulation Method signatures and docstrings: - def guiStart(self, parent=None): Graphical interface for starting this class. - def __init__(self, name='AccessTerminal', parent=None): Init...
Implement the Python class `AccessTerminal` described below. Class description: Open an interactive python console so the direct manipulation Method signatures and docstrings: - def guiStart(self, parent=None): Graphical interface for starting this class. - def __init__(self, name='AccessTerminal', parent=None): Init...
9b522f61054b51979b24150f7f668a05741e92dd
<|skeleton|> class AccessTerminal: """Open an interactive python console so the direct manipulation""" def guiStart(self, parent=None): """Graphical interface for starting this class.""" <|body_0|> def __init__(self, name='AccessTerminal', parent=None): """Initialize the class to c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AccessTerminal: """Open an interactive python console so the direct manipulation""" def guiStart(self, parent=None): """Graphical interface for starting this class.""" kwargs, independent = common._SimplePluginStart('AccessTerminal').startDisplay() kwargs['parent'] = parent ...
the_stack_v2_python_sparse
artview/components/console.py
nguy/artview
train
43
b899d11a8b78014fff368dc0db489a6f1af290e1
[ "if not isinstance(hint_name, str):\n raise _BeartypeDecorBeartypistryException(f'Beartypistry key {repr(hint_name)} not string.')\nelif hint_name in self:\n raise _BeartypeDecorBeartypistryException(f'Beartypistry key \"{hint_name}\" already registered (i.e., key collision between prior registered value {rep...
<|body_start_0|> if not isinstance(hint_name, str): raise _BeartypeDecorBeartypistryException(f'Beartypistry key {repr(hint_name)} not string.') elif hint_name in self: raise _BeartypeDecorBeartypistryException(f'Beartypistry key "{hint_name}" already registered (i.e., key collis...
**Beartypistry** (i.e., singleton dictionary mapping from strings uniquely identifying PEP-noncompliant type hints annotating callables decorated by the :func:`beartype.beartype` decorator to those hints).** This dictionary implements a global registry for **PEP-noncompliant type hints** (i.e., :mod:`beartype`-specific...
Beartypistry
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Beartypistry: """**Beartypistry** (i.e., singleton dictionary mapping from strings uniquely identifying PEP-noncompliant type hints annotating callables decorated by the :func:`beartype.beartype` decorator to those hints).** This dictionary implements a global registry for **PEP-noncompliant type...
stack_v2_sparse_classes_36k_train_001229
30,402
permissive
[ { "docstring": "Dunder method explicitly called by the superclass on setting the passed key-value pair with``[``- and ``]``-delimited syntax, mapping the passed string uniquely identifying the passed PEP-noncompliant type hint to that hint. Parameters ---------- hint_name: str String uniquely identifying this h...
2
stack_v2_sparse_classes_30k_train_020697
Implement the Python class `Beartypistry` described below. Class description: **Beartypistry** (i.e., singleton dictionary mapping from strings uniquely identifying PEP-noncompliant type hints annotating callables decorated by the :func:`beartype.beartype` decorator to those hints).** This dictionary implements a glob...
Implement the Python class `Beartypistry` described below. Class description: **Beartypistry** (i.e., singleton dictionary mapping from strings uniquely identifying PEP-noncompliant type hints annotating callables decorated by the :func:`beartype.beartype` decorator to those hints).** This dictionary implements a glob...
afaaa0d8c25f8e5c06dd093982787b794ee48f2d
<|skeleton|> class Beartypistry: """**Beartypistry** (i.e., singleton dictionary mapping from strings uniquely identifying PEP-noncompliant type hints annotating callables decorated by the :func:`beartype.beartype` decorator to those hints).** This dictionary implements a global registry for **PEP-noncompliant type...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Beartypistry: """**Beartypistry** (i.e., singleton dictionary mapping from strings uniquely identifying PEP-noncompliant type hints annotating callables decorated by the :func:`beartype.beartype` decorator to those hints).** This dictionary implements a global registry for **PEP-noncompliant type hints** (i.e...
the_stack_v2_python_sparse
beartype/_decor/_cache/cachetype.py
yamgent/beartype
train
0
2c2df5cf4ec76b8ec589973776dccc1c966cda6b
[ "dependency_types = ('show_question', 'show_selected')\nif dependency_type not in dependency_types:\n raise ValueError(f'Dependency Type must be one of {dependency_types}')\nif dependency_type == 'show_question':\n if choices is None and condition is None:\n raise ValueError('Must give choice or condit...
<|body_start_0|> dependency_types = ('show_question', 'show_selected') if dependency_type not in dependency_types: raise ValueError(f'Dependency Type must be one of {dependency_types}') if dependency_type == 'show_question': if choices is None and condition is None: ...
Class to place a dependency on whether a question is asked or not.
Dependency
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dependency: """Class to place a dependency on whether a question is asked or not.""" def __init__(self, dependency_type: str, independent: str, choices: Optional[List[str]]=None, condition: Optional[str]=None): """Create a new Dependency. Must specify the name of the independent ques...
stack_v2_sparse_classes_36k_train_001230
3,654
permissive
[ { "docstring": "Create a new Dependency. Must specify the name of the independent question which will be used to test if the dependency is satisfied and either (a) a list of choices which will satisfy the dependency if any of them are selected, OR (b) a string which specifies the dependency in a way the reader ...
2
stack_v2_sparse_classes_30k_train_018419
Implement the Python class `Dependency` described below. Class description: Class to place a dependency on whether a question is asked or not. Method signatures and docstrings: - def __init__(self, dependency_type: str, independent: str, choices: Optional[List[str]]=None, condition: Optional[str]=None): Create a new ...
Implement the Python class `Dependency` described below. Class description: Class to place a dependency on whether a question is asked or not. Method signatures and docstrings: - def __init__(self, dependency_type: str, independent: str, choices: Optional[List[str]]=None, condition: Optional[str]=None): Create a new ...
1a0fcf0c22e2c7306cba0218f82d24c97d28ee1f
<|skeleton|> class Dependency: """Class to place a dependency on whether a question is asked or not.""" def __init__(self, dependency_type: str, independent: str, choices: Optional[List[str]]=None, condition: Optional[str]=None): """Create a new Dependency. Must specify the name of the independent ques...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Dependency: """Class to place a dependency on whether a question is asked or not.""" def __init__(self, dependency_type: str, independent: str, choices: Optional[List[str]]=None, condition: Optional[str]=None): """Create a new Dependency. Must specify the name of the independent question which wi...
the_stack_v2_python_sparse
survey/generation/dependency.py
vahndi/quant-survey
train
2
36b7d7396db6d1295406598de4598b75d73465db
[ "self.arduino = Serial(config)\nself.arduino.add_listener(self.parse_data)\nObservableComponent.__init__(self, self.arduino)", "if len(reading) == 5:\n try:\n packet = TrollPacket.from_binary_packet(reading)\n self.update_listeners(packet)\n except KeyError as e:\n err_msg = 'Arduino me...
<|body_start_0|> self.arduino = Serial(config) self.arduino.add_listener(self.parse_data) ObservableComponent.__init__(self, self.arduino) <|end_body_0|> <|body_start_1|> if len(reading) == 5: try: packet = TrollPacket.from_binary_packet(reading) ...
Arduino layer for handling data inconsistensies.
Arduino
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Arduino: """Arduino layer for handling data inconsistensies.""" def __init__(self, config): """:param config: Dictionary containing connection headers :type config: dict""" <|body_0|> def parse_data(self, reading): """Arduino sends data incosistently sometimes. T...
stack_v2_sparse_classes_36k_train_001231
10,572
permissive
[ { "docstring": ":param config: Dictionary containing connection headers :type config: dict", "name": "__init__", "signature": "def __init__(self, config)" }, { "docstring": "Arduino sends data incosistently sometimes. This implementation assumes a format when receiving from arduino: - First byte...
2
stack_v2_sparse_classes_30k_train_013468
Implement the Python class `Arduino` described below. Class description: Arduino layer for handling data inconsistensies. Method signatures and docstrings: - def __init__(self, config): :param config: Dictionary containing connection headers :type config: dict - def parse_data(self, reading): Arduino sends data incos...
Implement the Python class `Arduino` described below. Class description: Arduino layer for handling data inconsistensies. Method signatures and docstrings: - def __init__(self, config): :param config: Dictionary containing connection headers :type config: dict - def parse_data(self, reading): Arduino sends data incos...
d554403dc73e8de43e723c08994b3dae08ac0c1c
<|skeleton|> class Arduino: """Arduino layer for handling data inconsistensies.""" def __init__(self, config): """:param config: Dictionary containing connection headers :type config: dict""" <|body_0|> def parse_data(self, reading): """Arduino sends data incosistently sometimes. T...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Arduino: """Arduino layer for handling data inconsistensies.""" def __init__(self, config): """:param config: Dictionary containing connection headers :type config: dict""" self.arduino = Serial(config) self.arduino.add_listener(self.parse_data) ObservableComponent.__init_...
the_stack_v2_python_sparse
backend/endpoints.py
trolllabs/trollsim
train
0
b02e8266cccc49fe44832bb5871e5cdd34da6d8a
[ "bttbPage.__init__(self)\nself.file_name = MapLinks(fileName)\nself.alt_file_name = self.file_name\nif altFileName is not None:\n self.alt_file_name = MapLinks(altFileName)", "file_name = self.file_name\ntry:\n if self.requestor:\n if self.can_view_page() == VIEW_OKAY:\n file_name = self.a...
<|body_start_0|> bttbPage.__init__(self) self.file_name = MapLinks(fileName) self.alt_file_name = self.file_name if altFileName is not None: self.alt_file_name = MapLinks(altFileName) <|end_body_0|> <|body_start_1|> file_name = self.file_name try: ...
Base class for pages that are read from hardcoded files
bttbPageFile
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class bttbPageFile: """Base class for pages that are read from hardcoded files""" def __init__(self, fileName, altFileName=None): """Set up the page""" <|body_0|> def content(self): """:return: a string with the content for this web page.""" <|body_1|> <|end_s...
stack_v2_sparse_classes_36k_train_001232
1,928
no_license
[ { "docstring": "Set up the page", "name": "__init__", "signature": "def __init__(self, fileName, altFileName=None)" }, { "docstring": ":return: a string with the content for this web page.", "name": "content", "signature": "def content(self)" } ]
2
null
Implement the Python class `bttbPageFile` described below. Class description: Base class for pages that are read from hardcoded files Method signatures and docstrings: - def __init__(self, fileName, altFileName=None): Set up the page - def content(self): :return: a string with the content for this web page.
Implement the Python class `bttbPageFile` described below. Class description: Base class for pages that are read from hardcoded files Method signatures and docstrings: - def __init__(self, fileName, altFileName=None): Set up the page - def content(self): :return: a string with the content for this web page. <|skelet...
344a26dca4b80f8cd42f4d60a1997bbafd6b282d
<|skeleton|> class bttbPageFile: """Base class for pages that are read from hardcoded files""" def __init__(self, fileName, altFileName=None): """Set up the page""" <|body_0|> def content(self): """:return: a string with the content for this web page.""" <|body_1|> <|end_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class bttbPageFile: """Base class for pages that are read from hardcoded files""" def __init__(self, fileName, altFileName=None): """Set up the page""" bttbPage.__init__(self) self.file_name = MapLinks(fileName) self.alt_file_name = self.file_name if altFileName is not N...
the_stack_v2_python_sparse
www.bttbalumni.ca/cgi-bin/pages/bttbPageFile.py
kpicott/bttbalumni
train
0
c0fd54562ecd8568c8ca336634898ad3789ca6b7
[ "res = copy.deepcopy(nums)\na = len(nums)\nb = len(nums[0])\nfor i in range(a):\n for j in range(b):\n if nums[i][j] == 0:\n res[i] = [0] * b\n for k in range(a):\n res[k][j] = 0\nreturn res", "index = []\nfor i in range(len(nums)):\n for j in range(len(nums[i])):...
<|body_start_0|> res = copy.deepcopy(nums) a = len(nums) b = len(nums[0]) for i in range(a): for j in range(b): if nums[i][j] == 0: res[i] = [0] * b for k in range(a): res[k][j] = 0 return...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def setZeros(self, nums): """O(m*n) :param nums: list[list[int]] :return: list[list[int]]""" <|body_0|> def setZeros2(self, nums): """:param nums: list[list[int]] :return: list[list[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> res...
stack_v2_sparse_classes_36k_train_001233
1,835
no_license
[ { "docstring": "O(m*n) :param nums: list[list[int]] :return: list[list[int]]", "name": "setZeros", "signature": "def setZeros(self, nums)" }, { "docstring": ":param nums: list[list[int]] :return: list[list[int]]", "name": "setZeros2", "signature": "def setZeros2(self, nums)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def setZeros(self, nums): O(m*n) :param nums: list[list[int]] :return: list[list[int]] - def setZeros2(self, nums): :param nums: list[list[int]] :return: list[list[int]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def setZeros(self, nums): O(m*n) :param nums: list[list[int]] :return: list[list[int]] - def setZeros2(self, nums): :param nums: list[list[int]] :return: list[list[int]] <|skele...
4f2802d4773eddd2a2e06e61c51463056886b730
<|skeleton|> class Solution: def setZeros(self, nums): """O(m*n) :param nums: list[list[int]] :return: list[list[int]]""" <|body_0|> def setZeros2(self, nums): """:param nums: list[list[int]] :return: list[list[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def setZeros(self, nums): """O(m*n) :param nums: list[list[int]] :return: list[list[int]]""" res = copy.deepcopy(nums) a = len(nums) b = len(nums[0]) for i in range(a): for j in range(b): if nums[i][j] == 0: res[...
the_stack_v2_python_sparse
leetcode2/51_setZeros.py
Yara7L/python_algorithm
train
0
e1ddcf8193c6ef040285c378805513b83cd3464c
[ "stock_prices_first_order = np.array([[10, 15, 20, 15, 10], [5, 15, 10, 15, 20], [30, 25, 20, 25, 30], [10, 15, 30, 40, 50]], dtype=float)\nstock_prices_second_order = np.array([[10, 15, 30, 40, 50], [10, 15, 20, 15, 10], [5, 15, 10, 15, 20], [30, 25, 20, 25, 30]], dtype=float)\ntest_case_first_order = StockMarket(...
<|body_start_0|> stock_prices_first_order = np.array([[10, 15, 20, 15, 10], [5, 15, 10, 15, 20], [30, 25, 20, 25, 30], [10, 15, 30, 40, 50]], dtype=float) stock_prices_second_order = np.array([[10, 15, 30, 40, 50], [10, 15, 20, 15, 10], [5, 15, 10, 15, 20], [30, 25, 20, 25, 30]], dtype=float) te...
TestStockMarket
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestStockMarket: def test_four_stocks_two_optimal_paths(self): """This unittest tests the 'dynamic_programming_bottom_up()' method by testing 4 stocks given in two different orders. There are two different paths in which different stocks can be bought to achieve the maximum equity of 50....
stack_v2_sparse_classes_36k_train_001234
3,083
no_license
[ { "docstring": "This unittest tests the 'dynamic_programming_bottom_up()' method by testing 4 stocks given in two different orders. There are two different paths in which different stocks can be bought to achieve the maximum equity of 50. :return: Succes if both stock orders lead to the maximum equity of 50 in ...
3
stack_v2_sparse_classes_30k_train_003386
Implement the Python class `TestStockMarket` described below. Class description: Implement the TestStockMarket class. Method signatures and docstrings: - def test_four_stocks_two_optimal_paths(self): This unittest tests the 'dynamic_programming_bottom_up()' method by testing 4 stocks given in two different orders. Th...
Implement the Python class `TestStockMarket` described below. Class description: Implement the TestStockMarket class. Method signatures and docstrings: - def test_four_stocks_two_optimal_paths(self): This unittest tests the 'dynamic_programming_bottom_up()' method by testing 4 stocks given in two different orders. Th...
98478976eac1fe3c3052d4deac1b382788d4e509
<|skeleton|> class TestStockMarket: def test_four_stocks_two_optimal_paths(self): """This unittest tests the 'dynamic_programming_bottom_up()' method by testing 4 stocks given in two different orders. There are two different paths in which different stocks can be bought to achieve the maximum equity of 50....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestStockMarket: def test_four_stocks_two_optimal_paths(self): """This unittest tests the 'dynamic_programming_bottom_up()' method by testing 4 stocks given in two different orders. There are two different paths in which different stocks can be bought to achieve the maximum equity of 50. :return: Succ...
the_stack_v2_python_sparse
Stockmarket/test_private.py
Macquine/Code-Portfolio
train
0
fb352c903151138b6edb907704871be84cfb4244
[ "l, r = (0, len(nums) - 1)\nwhile l <= r:\n mid = (l + r) / 2\n if nums[mid] == target:\n return True\n if nums[mid] == nums[l]:\n l += 1\n elif nums[mid] > nums[l]:\n if nums[l] <= target < nums[mid]:\n r = mid - 1\n else:\n l = mid + 1\n elif nums[m...
<|body_start_0|> l, r = (0, len(nums) - 1) while l <= r: mid = (l + r) / 2 if nums[mid] == target: return True if nums[mid] == nums[l]: l += 1 elif nums[mid] > nums[l]: if nums[l] <= target < nums[mid]: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def search(self, nums, target): """:type nums: List[int] :type target: int :rtype: bool bisect: 注意!! [)""" <|body_0|> def fuck(self, nums, target): """:type nums: List[int] :type target: int :rtype: bool bisect: 注意!! [)""" <|body_1|> <|end_skeleton...
stack_v2_sparse_classes_36k_train_001235
3,174
no_license
[ { "docstring": ":type nums: List[int] :type target: int :rtype: bool bisect: 注意!! [)", "name": "search", "signature": "def search(self, nums, target)" }, { "docstring": ":type nums: List[int] :type target: int :rtype: bool bisect: 注意!! [)", "name": "fuck", "signature": "def fuck(self, nu...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def search(self, nums, target): :type nums: List[int] :type target: int :rtype: bool bisect: 注意!! [) - def fuck(self, nums, target): :type nums: List[int] :type target: int :rtyp...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def search(self, nums, target): :type nums: List[int] :type target: int :rtype: bool bisect: 注意!! [) - def fuck(self, nums, target): :type nums: List[int] :type target: int :rtyp...
6350568d16b0f8c49a020f055bb6d72e2705ea56
<|skeleton|> class Solution: def search(self, nums, target): """:type nums: List[int] :type target: int :rtype: bool bisect: 注意!! [)""" <|body_0|> def fuck(self, nums, target): """:type nums: List[int] :type target: int :rtype: bool bisect: 注意!! [)""" <|body_1|> <|end_skeleton...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def search(self, nums, target): """:type nums: List[int] :type target: int :rtype: bool bisect: 注意!! [)""" l, r = (0, len(nums) - 1) while l <= r: mid = (l + r) / 2 if nums[mid] == target: return True if nums[mid] == nums[l]...
the_stack_v2_python_sparse
co_ms/81_Search_in_Rotated_Sorted_Array_II.py
vsdrun/lc_public
train
6
194057b16c5aa66526301b1d2b0d2aff4e206cd9
[ "threading.Thread.__init__(self)\nself.daemon = True\nself.queue = queue\nself.found = found\nself.initialSize = self.queue.qsize()", "lastActionTime = time.time()\nwhile True:\n if time.time() - lastActionTime > 5:\n print('Found: %d/%d/%d.' % (self.found.qsize(), self.initialSize - self.queue.qsize(),...
<|body_start_0|> threading.Thread.__init__(self) self.daemon = True self.queue = queue self.found = found self.initialSize = self.queue.qsize() <|end_body_0|> <|body_start_1|> lastActionTime = time.time() while True: if time.time() - lastActionTime > ...
CheckerMonitor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CheckerMonitor: def __init__(self, queue, found): """Инициализация""" <|body_0|> def run(self): """Каждые 5 секунд выводим текущую информацию""" <|body_1|> <|end_skeleton|> <|body_start_0|> threading.Thread.__init__(self) self.daemon = True ...
stack_v2_sparse_classes_36k_train_001236
4,389
no_license
[ { "docstring": "Инициализация", "name": "__init__", "signature": "def __init__(self, queue, found)" }, { "docstring": "Каждые 5 секунд выводим текущую информацию", "name": "run", "signature": "def run(self)" } ]
2
null
Implement the Python class `CheckerMonitor` described below. Class description: Implement the CheckerMonitor class. Method signatures and docstrings: - def __init__(self, queue, found): Инициализация - def run(self): Каждые 5 секунд выводим текущую информацию
Implement the Python class `CheckerMonitor` described below. Class description: Implement the CheckerMonitor class. Method signatures and docstrings: - def __init__(self, queue, found): Инициализация - def run(self): Каждые 5 секунд выводим текущую информацию <|skeleton|> class CheckerMonitor: def __init__(self...
d2771bf04aa187dda6d468883a5a167237589369
<|skeleton|> class CheckerMonitor: def __init__(self, queue, found): """Инициализация""" <|body_0|> def run(self): """Каждые 5 секунд выводим текущую информацию""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CheckerMonitor: def __init__(self, queue, found): """Инициализация""" threading.Thread.__init__(self) self.daemon = True self.queue = queue self.found = found self.initialSize = self.queue.qsize() def run(self): """Каждые 5 секунд выводим текущую ин...
the_stack_v2_python_sparse
doorsagents/basechecker.py
cash2one/doorscenter
train
0
8bcf8f138a5cf56ec0dc08858d1901de4035465c
[ "ans = []\nfor i in range(len(nums) - k + 1):\n ans.append(sum(nums[i:i + k]))\nreturn max(ans)", "sums = sum(nums[0:k])\nmaxSum = sums\nfor i in range(k, len(nums)):\n sums = sums - nums[i - k] + nums[i]\n maxSum = max(sums, maxSum)\nreturn maxSum / k", "sums = [0] + list(itertools.accumulate(nums))\n...
<|body_start_0|> ans = [] for i in range(len(nums) - k + 1): ans.append(sum(nums[i:i + k])) return max(ans) <|end_body_0|> <|body_start_1|> sums = sum(nums[0:k]) maxSum = sums for i in range(k, len(nums)): sums = sums - nums[i - k] + nums[i] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findMaxAverage(self, nums, k): """:type nums: List[int] :type k: int :rtype: float""" <|body_0|> def findMaxAverageSlidingWindows(self, nums, k): """:type nums: List[int] :type k: int :rtype: float""" <|body_1|> def findMaxAverageMap(self, ...
stack_v2_sparse_classes_36k_train_001237
1,056
no_license
[ { "docstring": ":type nums: List[int] :type k: int :rtype: float", "name": "findMaxAverage", "signature": "def findMaxAverage(self, nums, k)" }, { "docstring": ":type nums: List[int] :type k: int :rtype: float", "name": "findMaxAverageSlidingWindows", "signature": "def findMaxAverageSlid...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findMaxAverage(self, nums, k): :type nums: List[int] :type k: int :rtype: float - def findMaxAverageSlidingWindows(self, nums, k): :type nums: List[int] :type k: int :rtype: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findMaxAverage(self, nums, k): :type nums: List[int] :type k: int :rtype: float - def findMaxAverageSlidingWindows(self, nums, k): :type nums: List[int] :type k: int :rtype: ...
a13e7faaf55cd68249267e46a91e93c97e3190c2
<|skeleton|> class Solution: def findMaxAverage(self, nums, k): """:type nums: List[int] :type k: int :rtype: float""" <|body_0|> def findMaxAverageSlidingWindows(self, nums, k): """:type nums: List[int] :type k: int :rtype: float""" <|body_1|> def findMaxAverageMap(self, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findMaxAverage(self, nums, k): """:type nums: List[int] :type k: int :rtype: float""" ans = [] for i in range(len(nums) - k + 1): ans.append(sum(nums[i:i + k])) return max(ans) def findMaxAverageSlidingWindows(self, nums, k): """:type nums...
the_stack_v2_python_sparse
LeetCode/Array/643.py
xiaojkql/Algorithm-Data-Structure
train
1
ff5ee6997b097f1367bcbd9434ff708ceca8c1da
[ "if not root:\n return '{}'\nresult = {}\ndq = deque([(0, root)])\nwhile dq:\n i, node = dq.popleft()\n if node.left:\n dq.append([2 * i + 1, node.left])\n if node.right:\n dq.append([2 * i + 2, node.right])\n result[i] = node.val\nreturn str(result)", "nodes = {i: TreeNode(val) for i...
<|body_start_0|> if not root: return '{}' result = {} dq = deque([(0, root)]) while dq: i, node = dq.popleft() if node.left: dq.append([2 * i + 1, node.left]) if node.right: dq.append([2 * i + 2, node.right])...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_001238
942
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
f4cd43f082b58d4410008af49325770bc84d3aba
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return '{}' result = {} dq = deque([(0, root)]) while dq: i, node = dq.popleft() if node.left: dq...
the_stack_v2_python_sparse
297.Serialize_and_Deserialize_Binary_Tree.py
welsny/solutions
train
1
4e2c6199492496a573cfeaf44fafd0df56c35824
[ "dp = [[0] * N for i in range(N)]\nself.N = N\n\ndef postion(r, c):\n pos = set()\n lists = [(-2, -1), (-1, -2), (1, -2), (2, -1), (2, 1), (1, 2), (-1, 2), (-2, 1)]\n for i in lists:\n x = r + i[0]\n y = c + i[1]\n if (x >= 0 and x < self.N) and (y >= 0 and y < self.N):\n po...
<|body_start_0|> dp = [[0] * N for i in range(N)] self.N = N def postion(r, c): pos = set() lists = [(-2, -1), (-1, -2), (1, -2), (2, -1), (2, 1), (1, 2), (-1, 2), (-2, 1)] for i in lists: x = r + i[0] y = c + i[1] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def knightProbability(self, N, K, r, c): """:type N: int :type K: int :type r: int :type c: int :rtype: float 385ms""" <|body_0|> def knightProbability_1(self, N, K, r, c): """:type N: int :type K: int :type r: int :type c: int :rtype: float 192ms""" ...
stack_v2_sparse_classes_36k_train_001239
4,909
no_license
[ { "docstring": ":type N: int :type K: int :type r: int :type c: int :rtype: float 385ms", "name": "knightProbability", "signature": "def knightProbability(self, N, K, r, c)" }, { "docstring": ":type N: int :type K: int :type r: int :type c: int :rtype: float 192ms", "name": "knightProbabilit...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def knightProbability(self, N, K, r, c): :type N: int :type K: int :type r: int :type c: int :rtype: float 385ms - def knightProbability_1(self, N, K, r, c): :type N: int :type K...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def knightProbability(self, N, K, r, c): :type N: int :type K: int :type r: int :type c: int :rtype: float 385ms - def knightProbability_1(self, N, K, r, c): :type N: int :type K...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution: def knightProbability(self, N, K, r, c): """:type N: int :type K: int :type r: int :type c: int :rtype: float 385ms""" <|body_0|> def knightProbability_1(self, N, K, r, c): """:type N: int :type K: int :type r: int :type c: int :rtype: float 192ms""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def knightProbability(self, N, K, r, c): """:type N: int :type K: int :type r: int :type c: int :rtype: float 385ms""" dp = [[0] * N for i in range(N)] self.N = N def postion(r, c): pos = set() lists = [(-2, -1), (-1, -2), (1, -2), (2, -1), (2...
the_stack_v2_python_sparse
KnightProbabilityInChessboard_MID_688.py
953250587/leetcode-python
train
2
98a0e702cc5df157fd32d387767acc8b2f588187
[ "super(AttENC, self).__init__()\nself.cnn = CNN(n_in * 2, n_hid, n_hid, do_prob)\nself.n2e_i = MLP(n_hid, n_hid, n_hid, do_prob)\nself.e2n = MLP(n_hid, n_hid, n_hid, do_prob)\nself.n2e_o = MLP(n_hid * 3, n_hid, n_hid, do_prob)\nself.intra_att = SelfAtt(n_hid, n_hid)\nself.inter_att = SelfAtt(n_hid, n_hid)\nself.fc_...
<|body_start_0|> super(AttENC, self).__init__() self.cnn = CNN(n_in * 2, n_hid, n_hid, do_prob) self.n2e_i = MLP(n_hid, n_hid, n_hid, do_prob) self.e2n = MLP(n_hid, n_hid, n_hid, do_prob) self.n2e_o = MLP(n_hid * 3, n_hid, n_hid, do_prob) self.intra_att = SelfAtt(n_hid, n...
Encoder using the relation interaction mechanism implemented by self-attention.
AttENC
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttENC: """Encoder using the relation interaction mechanism implemented by self-attention.""" def __init__(self, n_in: int, n_hid: int, n_out: int, do_prob: float=0.0): """Parameters ---------- n_in : int input dimension. n_hid : int dimension of hidden layers. n_out : int output dim...
stack_v2_sparse_classes_36k_train_001240
12,491
permissive
[ { "docstring": "Parameters ---------- n_in : int input dimension. n_hid : int dimension of hidden layers. n_out : int output dimension, i.e., number of edge types. do_prob : float, optional rate of dropout. The default is 0.. factor : bool, optional using a factor graph or not. The default is True. reducer : st...
5
stack_v2_sparse_classes_30k_train_011779
Implement the Python class `AttENC` described below. Class description: Encoder using the relation interaction mechanism implemented by self-attention. Method signatures and docstrings: - def __init__(self, n_in: int, n_hid: int, n_out: int, do_prob: float=0.0): Parameters ---------- n_in : int input dimension. n_hid...
Implement the Python class `AttENC` described below. Class description: Encoder using the relation interaction mechanism implemented by self-attention. Method signatures and docstrings: - def __init__(self, n_in: int, n_hid: int, n_out: int, do_prob: float=0.0): Parameters ---------- n_in : int input dimension. n_hid...
eab643f51336dbf7d711f02d27e6516e5affee59
<|skeleton|> class AttENC: """Encoder using the relation interaction mechanism implemented by self-attention.""" def __init__(self, n_in: int, n_hid: int, n_out: int, do_prob: float=0.0): """Parameters ---------- n_in : int input dimension. n_hid : int dimension of hidden layers. n_out : int output dim...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AttENC: """Encoder using the relation interaction mechanism implemented by self-attention.""" def __init__(self, n_in: int, n_hid: int, n_out: int, do_prob: float=0.0): """Parameters ---------- n_in : int input dimension. n_hid : int dimension of hidden layers. n_out : int output dimension, i.e.,...
the_stack_v2_python_sparse
research/gnn/nri-mpm/models/nri.py
mindspore-ai/models
train
301
37b28e64af619c0e5d98194caab3f15a16fa00e4
[ "threading.Thread.__init__(self)\nself._parent = parent\nself._motnum = motnum\nself._start_position = start_position\nself._dest_position = dest_position", "self._parent.ic.RapidScan(self._motnum, self._start_position, self._dest_position)\nevt = DoneEvent(myEVT_DONE, -1, None)\nwx.PostEvent(self._parent, evt)" ...
<|body_start_0|> threading.Thread.__init__(self) self._parent = parent self._motnum = motnum self._start_position = start_position self._dest_position = dest_position <|end_body_0|> <|body_start_1|> self._parent.ic.RapidScan(self._motnum, self._start_position, self._dest...
RapidScanThread
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RapidScanThread: def __init__(self, parent, motnum, start_position, dest_position): """@param parent: The gui object that should recieve the value @param value: value to 'calculate' to""" <|body_0|> def run(self): """Overrides Thread.run. Don't call this directly its...
stack_v2_sparse_classes_36k_train_001241
7,803
no_license
[ { "docstring": "@param parent: The gui object that should recieve the value @param value: value to 'calculate' to", "name": "__init__", "signature": "def __init__(self, parent, motnum, start_position, dest_position)" }, { "docstring": "Overrides Thread.run. Don't call this directly its called in...
2
null
Implement the Python class `RapidScanThread` described below. Class description: Implement the RapidScanThread class. Method signatures and docstrings: - def __init__(self, parent, motnum, start_position, dest_position): @param parent: The gui object that should recieve the value @param value: value to 'calculate' to...
Implement the Python class `RapidScanThread` described below. Class description: Implement the RapidScanThread class. Method signatures and docstrings: - def __init__(self, parent, motnum, start_position, dest_position): @param parent: The gui object that should recieve the value @param value: value to 'calculate' to...
29468ae4d8a4a9de5cac8988fd3620f806a71907
<|skeleton|> class RapidScanThread: def __init__(self, parent, motnum, start_position, dest_position): """@param parent: The gui object that should recieve the value @param value: value to 'calculate' to""" <|body_0|> def run(self): """Overrides Thread.run. Don't call this directly its...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RapidScanThread: def __init__(self, parent, motnum, start_position, dest_position): """@param parent: The gui object that should recieve the value @param value: value to 'calculate' to""" threading.Thread.__init__(self) self._parent = parent self._motnum = motnum self._...
the_stack_v2_python_sparse
pyrecs/RapidScanCombinedGui.py
bmaranville/pyrecs
train
0
cc15e2111cd96a422debe0d6bf491ae7cdd6723a
[ "self.bot_id = kwargs.get('bot_id')\nself.bot_type = kwargs.get('bot_type')\nself.position = kwargs.get('position')\nself.rotation = kwargs.get('rotation')", "self.bot_id = kwargs['bot_id']\nself.bot_type = kwargs['bot_type']\nself.position = kwargs['position']\nself.rotation = kwargs['rotation']", "ret = {}\nr...
<|body_start_0|> self.bot_id = kwargs.get('bot_id') self.bot_type = kwargs.get('bot_type') self.position = kwargs.get('position') self.rotation = kwargs.get('rotation') <|end_body_0|> <|body_start_1|> self.bot_id = kwargs['bot_id'] self.bot_type = kwargs['bot_type'] ...
SpawnBotRequest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpawnBotRequest: def __init__(self, **kwargs): """Params: bot_id: int bot_type: str position: Vector3 rotation: float""" <|body_0|> def load(self, **kwargs): """load from dict Exception: KeyError""" <|body_1|> def dump(self): """dump -> dict""" ...
stack_v2_sparse_classes_36k_train_001242
26,590
no_license
[ { "docstring": "Params: bot_id: int bot_type: str position: Vector3 rotation: float", "name": "__init__", "signature": "def __init__(self, **kwargs)" }, { "docstring": "load from dict Exception: KeyError", "name": "load", "signature": "def load(self, **kwargs)" }, { "docstring": ...
3
stack_v2_sparse_classes_30k_train_003691
Implement the Python class `SpawnBotRequest` described below. Class description: Implement the SpawnBotRequest class. Method signatures and docstrings: - def __init__(self, **kwargs): Params: bot_id: int bot_type: str position: Vector3 rotation: float - def load(self, **kwargs): load from dict Exception: KeyError - d...
Implement the Python class `SpawnBotRequest` described below. Class description: Implement the SpawnBotRequest class. Method signatures and docstrings: - def __init__(self, **kwargs): Params: bot_id: int bot_type: str position: Vector3 rotation: float - def load(self, **kwargs): load from dict Exception: KeyError - d...
aa0b2697e295889e8c23a7104889ea95f2a4b6b1
<|skeleton|> class SpawnBotRequest: def __init__(self, **kwargs): """Params: bot_id: int bot_type: str position: Vector3 rotation: float""" <|body_0|> def load(self, **kwargs): """load from dict Exception: KeyError""" <|body_1|> def dump(self): """dump -> dict""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpawnBotRequest: def __init__(self, **kwargs): """Params: bot_id: int bot_type: str position: Vector3 rotation: float""" self.bot_id = kwargs.get('bot_id') self.bot_type = kwargs.get('bot_type') self.position = kwargs.get('position') self.rotation = kwargs.get('rotation...
the_stack_v2_python_sparse
message.py
songhui17/Server
train
0
138eb3ab5e261f8bc5ec13406a1c5a1a472aa0a6
[ "self.application_id_local = kwargs.pop('id')\nself.child = kwargs.pop('child')\nsuper(OtherPeopleChildrenDetailsForm, self).__init__(*args, **kwargs)\nfull_stop_stripper(self)\nif ChildInHome.objects.filter(application_id=self.application_id_local, child=self.child).count() > 0:\n child_record = ChildInHome.obj...
<|body_start_0|> self.application_id_local = kwargs.pop('id') self.child = kwargs.pop('child') super(OtherPeopleChildrenDetailsForm, self).__init__(*args, **kwargs) full_stop_stripper(self) if ChildInHome.objects.filter(application_id=self.application_id_local, child=self.child)....
GOV.UK form for the People in your home: children details page
OtherPeopleChildrenDetailsForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OtherPeopleChildrenDetailsForm: """GOV.UK form for the People in your home: children details page""" def __init__(self, *args, **kwargs): """Method to configure the initialisation of the People in your home: children details form :param args: arguments passed to the form :param kwarg...
stack_v2_sparse_classes_36k_train_001243
20,631
no_license
[ { "docstring": "Method to configure the initialisation of the People in your home: children details form :param args: arguments passed to the form :param kwargs: keyword arguments passed to the form, e.g. application ID", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { ...
5
stack_v2_sparse_classes_30k_train_011404
Implement the Python class `OtherPeopleChildrenDetailsForm` described below. Class description: GOV.UK form for the People in your home: children details page Method signatures and docstrings: - def __init__(self, *args, **kwargs): Method to configure the initialisation of the People in your home: children details fo...
Implement the Python class `OtherPeopleChildrenDetailsForm` described below. Class description: GOV.UK form for the People in your home: children details page Method signatures and docstrings: - def __init__(self, *args, **kwargs): Method to configure the initialisation of the People in your home: children details fo...
fa6ca6a8164763e1dfe1581702ca5d36e44859de
<|skeleton|> class OtherPeopleChildrenDetailsForm: """GOV.UK form for the People in your home: children details page""" def __init__(self, *args, **kwargs): """Method to configure the initialisation of the People in your home: children details form :param args: arguments passed to the form :param kwarg...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OtherPeopleChildrenDetailsForm: """GOV.UK form for the People in your home: children details page""" def __init__(self, *args, **kwargs): """Method to configure the initialisation of the People in your home: children details form :param args: arguments passed to the form :param kwargs: keyword ar...
the_stack_v2_python_sparse
application/forms/other_people.py
IS-JAQU-CAZ/OFS-MORE-Childminder-Website
train
0
36af8e8c36192d5bed83b30257147efd749d217d
[ "self.default_authority = default_authority\nself.mailer = mailer\nself.session = session\nself.signup_email = signup_email\nself.stats = stats", "kwargs.setdefault('authority', self.default_authority)\nuser = User(**kwargs)\nself.session.add(user)\nactivation = Activation()\nself.session.add(activation)\nuser.ac...
<|body_start_0|> self.default_authority = default_authority self.mailer = mailer self.session = session self.signup_email = signup_email self.stats = stats <|end_body_0|> <|body_start_1|> kwargs.setdefault('authority', self.default_authority) user = User(**kwargs...
A service for registering users.
UserSignupService
[ "MIT", "BSD-2-Clause", "BSD-3-Clause", "BSD-2-Clause-Views" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserSignupService: """A service for registering users.""" def __init__(self, default_authority, mailer, session, signup_email, stats=None): """Create a new user signup service. :param default_authority: the default authority for new users :param mailer: a mailer (such as :py:mod:`h.m...
stack_v2_sparse_classes_36k_train_001244
4,049
permissive
[ { "docstring": "Create a new user signup service. :param default_authority: the default authority for new users :param mailer: a mailer (such as :py:mod:`h.mailer`) :param session: the SQLAlchemy session object :param signup_email: a function for generating a signup email :param stats: the stats service", "...
2
stack_v2_sparse_classes_30k_test_001004
Implement the Python class `UserSignupService` described below. Class description: A service for registering users. Method signatures and docstrings: - def __init__(self, default_authority, mailer, session, signup_email, stats=None): Create a new user signup service. :param default_authority: the default authority fo...
Implement the Python class `UserSignupService` described below. Class description: A service for registering users. Method signatures and docstrings: - def __init__(self, default_authority, mailer, session, signup_email, stats=None): Create a new user signup service. :param default_authority: the default authority fo...
fd1decafdce981b681ef3bd59e001b1284498dae
<|skeleton|> class UserSignupService: """A service for registering users.""" def __init__(self, default_authority, mailer, session, signup_email, stats=None): """Create a new user signup service. :param default_authority: the default authority for new users :param mailer: a mailer (such as :py:mod:`h.m...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserSignupService: """A service for registering users.""" def __init__(self, default_authority, mailer, session, signup_email, stats=None): """Create a new user signup service. :param default_authority: the default authority for new users :param mailer: a mailer (such as :py:mod:`h.mailer`) :para...
the_stack_v2_python_sparse
h/accounts/services.py
project-star/h
train
1
183a51ef6102dda5856fb3341d90030a8185bc54
[ "end_date = start_date + relativedelta(months=duration)\nif timezone.now() <= end_date:\n return False\nreturn True", "try:\n subscription_history = SubscriptionHistory.objects.get(user=user)\nexcept SubscriptionHistory.DoesNotExist as e:\n logger.exception(e)\n return False\nif not cls._is_subscripti...
<|body_start_0|> end_date = start_date + relativedelta(months=duration) if timezone.now() <= end_date: return False return True <|end_body_0|> <|body_start_1|> try: subscription_history = SubscriptionHistory.objects.get(user=user) except SubscriptionHisto...
View for various checks of a user subscription
SubscriptionView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubscriptionView: """View for various checks of a user subscription""" def _is_subscription_expired(cls, start_date, duration): """Checks if a user subscription is expired or not. Args: start_date (datetime): Start date of subscription duration (int): Duration of subscription Returns...
stack_v2_sparse_classes_36k_train_001245
2,628
no_license
[ { "docstring": "Checks if a user subscription is expired or not. Args: start_date (datetime): Start date of subscription duration (int): Duration of subscription Returns: A bool value denoting if a user subscription is expired or not.", "name": "_is_subscription_expired", "signature": "def _is_subscript...
3
stack_v2_sparse_classes_30k_test_000168
Implement the Python class `SubscriptionView` described below. Class description: View for various checks of a user subscription Method signatures and docstrings: - def _is_subscription_expired(cls, start_date, duration): Checks if a user subscription is expired or not. Args: start_date (datetime): Start date of subs...
Implement the Python class `SubscriptionView` described below. Class description: View for various checks of a user subscription Method signatures and docstrings: - def _is_subscription_expired(cls, start_date, duration): Checks if a user subscription is expired or not. Args: start_date (datetime): Start date of subs...
ab04535bc307167b2d79fa7e2b37e74e16f63963
<|skeleton|> class SubscriptionView: """View for various checks of a user subscription""" def _is_subscription_expired(cls, start_date, duration): """Checks if a user subscription is expired or not. Args: start_date (datetime): Start date of subscription duration (int): Duration of subscription Returns...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SubscriptionView: """View for various checks of a user subscription""" def _is_subscription_expired(cls, start_date, duration): """Checks if a user subscription is expired or not. Args: start_date (datetime): Start date of subscription duration (int): Duration of subscription Returns: A bool valu...
the_stack_v2_python_sparse
utils/subscription.py
suraj-iitb/bodhitree
train
1
8b57c5dc657fee3490a9dae1ab9e5a154da9fb4f
[ "self.mapping = {}\nfor i in xrange(len(words)):\n self.mapping[words[i]] = self.mapping.get(words[i], []) + [i]", "wl1 = self.mapping[word1]\nwl2 = self.mapping[word2]\ni = j = 0\nminlen = 1 << 31\nwhile i < len(wl1) and j < len(wl2):\n minlen = min(abs(wl1[i] - wl2[j]), minlen)\n if wl1[i] < wl2[j]:\n ...
<|body_start_0|> self.mapping = {} for i in xrange(len(words)): self.mapping[words[i]] = self.mapping.get(words[i], []) + [i] <|end_body_0|> <|body_start_1|> wl1 = self.mapping[word1] wl2 = self.mapping[word2] i = j = 0 minlen = 1 << 31 while i < len(...
WordDistance
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordDistance: def __init__(self, words): """initialize your data structure here. :type words: List[str]""" <|body_0|> def shortest(self, word1, word2): """Adds a word into the data structure. :type word1: str :type word2: str :rtype: int""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k_train_001246
982
permissive
[ { "docstring": "initialize your data structure here. :type words: List[str]", "name": "__init__", "signature": "def __init__(self, words)" }, { "docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int", "name": "shortest", "signature": "def shortes...
2
stack_v2_sparse_classes_30k_train_005824
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, words): initialize your data structure here. :type words: List[str] - def shortest(self, word1, word2): Adds a word into the data structure. :type word...
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, words): initialize your data structure here. :type words: List[str] - def shortest(self, word1, word2): Adds a word into the data structure. :type word...
86f1cb98de801f58c39d9a48ce9de12df7303d20
<|skeleton|> class WordDistance: def __init__(self, words): """initialize your data structure here. :type words: List[str]""" <|body_0|> def shortest(self, word1, word2): """Adds a word into the data structure. :type word1: str :type word2: str :rtype: int""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WordDistance: def __init__(self, words): """initialize your data structure here. :type words: List[str]""" self.mapping = {} for i in xrange(len(words)): self.mapping[words[i]] = self.mapping.get(words[i], []) + [i] def shortest(self, word1, word2): """Adds a w...
the_stack_v2_python_sparse
244-Shortest-Word-Distance-II/solution.py
Tanych/CodeTracking
train
0
957af1f455c3986a871f29441c61d050dc21fe4c
[ "try:\n if document_id is None:\n return resource_utils.path_param_error_response('document ID')\n account_id = resource_utils.get_account_id(request)\n if account_id is None:\n return resource_utils.account_required_response()\n if not authorized(account_id, jwt):\n return resource...
<|body_start_0|> try: if document_id is None: return resource_utils.path_param_error_response('document ID') account_id = resource_utils.get_account_id(request) if account_id is None: return resource_utils.account_required_response() ...
Resource for maintaining existing, individual draft statements.
MaintainDraftResource
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MaintainDraftResource: """Resource for maintaining existing, individual draft statements.""" def get(document_id): """Get a draft statement by document ID.""" <|body_0|> def put(document_id): """Update a draft statement by document ID with data in the request bod...
stack_v2_sparse_classes_36k_train_001247
9,959
permissive
[ { "docstring": "Get a draft statement by document ID.", "name": "get", "signature": "def get(document_id)" }, { "docstring": "Update a draft statement by document ID with data in the request body.", "name": "put", "signature": "def put(document_id)" }, { "docstring": "Delete a dr...
3
stack_v2_sparse_classes_30k_train_007995
Implement the Python class `MaintainDraftResource` described below. Class description: Resource for maintaining existing, individual draft statements. Method signatures and docstrings: - def get(document_id): Get a draft statement by document ID. - def put(document_id): Update a draft statement by document ID with da...
Implement the Python class `MaintainDraftResource` described below. Class description: Resource for maintaining existing, individual draft statements. Method signatures and docstrings: - def get(document_id): Get a draft statement by document ID. - def put(document_id): Update a draft statement by document ID with da...
af1a4458bb78c16ecca484514d4bd0d1d8c24b5d
<|skeleton|> class MaintainDraftResource: """Resource for maintaining existing, individual draft statements.""" def get(document_id): """Get a draft statement by document ID.""" <|body_0|> def put(document_id): """Update a draft statement by document ID with data in the request bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MaintainDraftResource: """Resource for maintaining existing, individual draft statements.""" def get(document_id): """Get a draft statement by document ID.""" try: if document_id is None: return resource_utils.path_param_error_response('document ID') ...
the_stack_v2_python_sparse
ppr-api/src/ppr_api/resources/drafts.py
bcgov/ppr
train
4
b92d2293ceab5e38c594bc117870c95af48b82ec
[ "super().__init__()\nself.size = size\nself.padding_idx = padding_idx\nself.smoothing = smoothing\nself.confidence = 1.0 - smoothing\nself.normalize_length = normalize_length\nself.criterion = nn.KLDivLoss(reduction='none')", "B, T, D = x.shape\nassert D == self.size\nx = x.reshape((-1, self.size))\ntarget = targ...
<|body_start_0|> super().__init__() self.size = size self.padding_idx = padding_idx self.smoothing = smoothing self.confidence = 1.0 - smoothing self.normalize_length = normalize_length self.criterion = nn.KLDivLoss(reduction='none') <|end_body_0|> <|body_start_1...
Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. e.g. smoothing=0.1 [0,1,2] -> [ [0.9, 0.05, 0....
LabelSmoothingLoss
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LabelSmoothingLoss: """Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. ...
stack_v2_sparse_classes_36k_train_001248
6,854
permissive
[ { "docstring": "Label-smoothing loss. Args: size (int): the number of class padding_idx (int): padding class id which will be ignored for loss smoothing (float): smoothing rate (0.0 means the conventional CE) normalize_length (bool): True, normalize loss by sequence length; False, normalize loss by batch size. ...
2
stack_v2_sparse_classes_30k_train_003945
Implement the Python class `LabelSmoothingLoss` described below. Class description: Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1....
Implement the Python class `LabelSmoothingLoss` described below. Class description: Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1....
17854a04d43c231eff66bfed9d6aa55e94a29e79
<|skeleton|> class LabelSmoothingLoss: """Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LabelSmoothingLoss: """Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. e.g. smoothin...
the_stack_v2_python_sparse
paddlespeech/s2t/modules/loss.py
anniyanvr/DeepSpeech-1
train
0
7a58c3ef9345b1d72a4c280dbd2c449d896c8605
[ "Event.__init__(self)\nself.clearnames = []\nself.role = ''\nself.note_ref = []\nself.citation_ref = []\nself.place_ref = []\nself.place = None\nself.media_ref = []\nself.note_ref = []\nself.citations = []\nself.person = None", "with shareds.driver.session() as session:\n try:\n result = session.run(Cyp...
<|body_start_0|> Event.__init__(self) self.clearnames = [] self.role = '' self.note_ref = [] self.citation_ref = [] self.place_ref = [] self.place = None self.media_ref = [] self.note_ref = [] self.citations = [] self.person = None ...
Tapahtumat, lähteet, huomautukset, henkilön uniq_id Event combo includes operations for accessing - Event - related Sources, Notes - related Person id Lisäksi on kätevä olla metodi __str__(), joka antaa lyhyen sanalliseen muodon "syntynyt välillä 1.3.1840...31.3.1840 Hauho".
Event_combo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Event_combo: """Tapahtumat, lähteet, huomautukset, henkilön uniq_id Event combo includes operations for accessing - Event - related Sources, Notes - related Person id Lisäksi on kätevä olla metodi __str__(), joka antaa lyhyen sanalliseen muodon "syntynyt välillä 1.3.1840...31.3.1840 Hauho".""" ...
stack_v2_sparse_classes_36k_train_001249
11,789
no_license
[ { "docstring": "Constructor Luo uuden Event_combo -instanssin", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Read this event with uniq_id's of related Place, Note, and Citation nodes. #TODO: Tulisi lukea Notes ja Citations vasta get_persondata_by_id() lopuksi Luetaan ...
5
stack_v2_sparse_classes_30k_train_009876
Implement the Python class `Event_combo` described below. Class description: Tapahtumat, lähteet, huomautukset, henkilön uniq_id Event combo includes operations for accessing - Event - related Sources, Notes - related Person id Lisäksi on kätevä olla metodi __str__(), joka antaa lyhyen sanalliseen muodon "syntynyt väl...
Implement the Python class `Event_combo` described below. Class description: Tapahtumat, lähteet, huomautukset, henkilön uniq_id Event combo includes operations for accessing - Event - related Sources, Notes - related Person id Lisäksi on kätevä olla metodi __str__(), joka antaa lyhyen sanalliseen muodon "syntynyt väl...
0f8d6ba035e3cca8dc756531b7cc51029a549a4f
<|skeleton|> class Event_combo: """Tapahtumat, lähteet, huomautukset, henkilön uniq_id Event combo includes operations for accessing - Event - related Sources, Notes - related Person id Lisäksi on kätevä olla metodi __str__(), joka antaa lyhyen sanalliseen muodon "syntynyt välillä 1.3.1840...31.3.1840 Hauho".""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Event_combo: """Tapahtumat, lähteet, huomautukset, henkilön uniq_id Event combo includes operations for accessing - Event - related Sources, Notes - related Person id Lisäksi on kätevä olla metodi __str__(), joka antaa lyhyen sanalliseen muodon "syntynyt välillä 1.3.1840...31.3.1840 Hauho".""" def __init...
the_stack_v2_python_sparse
models/gen/event_combo.py
kkujansuu/stk
train
0
2a845448eb653775a56b847a7086e5def4ce1a4b
[ "self._write = write\nself._bufsize = bufsize\nself._wbuf = BytesIO()\nself._buflen = 0", "line = pkt_line(data)\nline_len = len(line)\nover = self._buflen + line_len - self._bufsize\nif over >= 0:\n start = line_len - over\n self._wbuf.write(line[:start])\n self.flush()\nelse:\n start = 0\nsaved = li...
<|body_start_0|> self._write = write self._bufsize = bufsize self._wbuf = BytesIO() self._buflen = 0 <|end_body_0|> <|body_start_1|> line = pkt_line(data) line_len = len(line) over = self._buflen + line_len - self._bufsize if over >= 0: start ...
Writer that wraps its data in pkt-lines and has an independent buffer. Consecutive calls to write() wrap the data in a pkt-line and then buffers it until enough lines have been written such that their total length (including length prefix) reach the buffer size.
BufferedPktLineWriter
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BufferedPktLineWriter: """Writer that wraps its data in pkt-lines and has an independent buffer. Consecutive calls to write() wrap the data in a pkt-line and then buffers it until enough lines have been written such that their total length (including length prefix) reach the buffer size.""" ...
stack_v2_sparse_classes_36k_train_001250
17,727
permissive
[ { "docstring": "Initialize the BufferedPktLineWriter. :param write: A write callback for the underlying writer. :param bufsize: The internal buffer size, including length prefixes.", "name": "__init__", "signature": "def __init__(self, write, bufsize=65515)" }, { "docstring": "Write data, wrappi...
3
stack_v2_sparse_classes_30k_train_002294
Implement the Python class `BufferedPktLineWriter` described below. Class description: Writer that wraps its data in pkt-lines and has an independent buffer. Consecutive calls to write() wrap the data in a pkt-line and then buffers it until enough lines have been written such that their total length (including length ...
Implement the Python class `BufferedPktLineWriter` described below. Class description: Writer that wraps its data in pkt-lines and has an independent buffer. Consecutive calls to write() wrap the data in a pkt-line and then buffers it until enough lines have been written such that their total length (including length ...
d59c99dcdcd280d7eec36a693dd80f8c8c831ea2
<|skeleton|> class BufferedPktLineWriter: """Writer that wraps its data in pkt-lines and has an independent buffer. Consecutive calls to write() wrap the data in a pkt-line and then buffers it until enough lines have been written such that their total length (including length prefix) reach the buffer size.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BufferedPktLineWriter: """Writer that wraps its data in pkt-lines and has an independent buffer. Consecutive calls to write() wrap the data in a pkt-line and then buffers it until enough lines have been written such that their total length (including length prefix) reach the buffer size.""" def __init__(...
the_stack_v2_python_sparse
modules/dbnd/src/dbnd/_vendor/dulwich/protocol.py
databand-ai/dbnd
train
257
2ccc503f8a9efd4aa08f95ef77e3b4988adb1420
[ "comments = CommentsShopItems.query.order_by(asc(CommentsShopItems.ShopItemID), asc(CommentsShopItems.Created)).all()\ncontents = jsonify({'comments': [{'commentID': comment.CommentID, 'shopitemID': comment.ShopItemID, 'userID': comment.UserID, 'name': get_username(comment.UserID), 'comment': comment.Comment, 'crea...
<|body_start_0|> comments = CommentsShopItems.query.order_by(asc(CommentsShopItems.ShopItemID), asc(CommentsShopItems.Created)).all() contents = jsonify({'comments': [{'commentID': comment.CommentID, 'shopitemID': comment.ShopItemID, 'userID': comment.UserID, 'name': get_username(comment.UserID), 'comme...
ShopItemCommentsView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ShopItemCommentsView: def index(self): """Return all comments for all shopitems.""" <|body_0|> def get(self, shopitem_id): """Return the comments for a specific shopitem.""" <|body_1|> def post(self): """Add a comment to a shopitem specified in t...
stack_v2_sparse_classes_36k_train_001251
26,847
permissive
[ { "docstring": "Return all comments for all shopitems.", "name": "index", "signature": "def index(self)" }, { "docstring": "Return the comments for a specific shopitem.", "name": "get", "signature": "def get(self, shopitem_id)" }, { "docstring": "Add a comment to a shopitem speci...
5
stack_v2_sparse_classes_30k_train_017535
Implement the Python class `ShopItemCommentsView` described below. Class description: Implement the ShopItemCommentsView class. Method signatures and docstrings: - def index(self): Return all comments for all shopitems. - def get(self, shopitem_id): Return the comments for a specific shopitem. - def post(self): Add a...
Implement the Python class `ShopItemCommentsView` described below. Class description: Implement the ShopItemCommentsView class. Method signatures and docstrings: - def index(self): Return all comments for all shopitems. - def get(self, shopitem_id): Return the comments for a specific shopitem. - def post(self): Add a...
62f8e8e904e379541193f0cbb91a8434b47f538f
<|skeleton|> class ShopItemCommentsView: def index(self): """Return all comments for all shopitems.""" <|body_0|> def get(self, shopitem_id): """Return the comments for a specific shopitem.""" <|body_1|> def post(self): """Add a comment to a shopitem specified in t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ShopItemCommentsView: def index(self): """Return all comments for all shopitems.""" comments = CommentsShopItems.query.order_by(asc(CommentsShopItems.ShopItemID), asc(CommentsShopItems.Created)).all() contents = jsonify({'comments': [{'commentID': comment.CommentID, 'shopitemID': comme...
the_stack_v2_python_sparse
apps/comments/views.py
Torniojaws/vortech-backend
train
0
60bb2fdfed4a553c8a3fc83d9e8a314ec694162b
[ "authenticated_user_id = token_auth.current_user()\nif authenticated_user_id:\n campaign = CampaignService.get_campaign_as_dto(campaign_id, authenticated_user_id)\nelse:\n campaign = CampaignService.get_campaign_as_dto(campaign_id, 0)\nreturn (campaign.to_primitive(), 200)", "try:\n orgs_dto = Organisati...
<|body_start_0|> authenticated_user_id = token_auth.current_user() if authenticated_user_id: campaign = CampaignService.get_campaign_as_dto(campaign_id, authenticated_user_id) else: campaign = CampaignService.get_campaign_as_dto(campaign_id, 0) return (campaign.to...
CampaignsRestAPI
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CampaignsRestAPI: def get(self, campaign_id): """Get an active campaign's information --- tags: - campaigns produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token type: string default: Token sessionTokenHere== - in: header name...
stack_v2_sparse_classes_36k_train_001252
9,923
permissive
[ { "docstring": "Get an active campaign's information --- tags: - campaigns produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token type: string default: Token sessionTokenHere== - in: header name: Accept-Language description: Language user is requestin...
3
stack_v2_sparse_classes_30k_test_001128
Implement the Python class `CampaignsRestAPI` described below. Class description: Implement the CampaignsRestAPI class. Method signatures and docstrings: - def get(self, campaign_id): Get an active campaign's information --- tags: - campaigns produces: - application/json parameters: - in: header name: Authorization d...
Implement the Python class `CampaignsRestAPI` described below. Class description: Implement the CampaignsRestAPI class. Method signatures and docstrings: - def get(self, campaign_id): Get an active campaign's information --- tags: - campaigns produces: - application/json parameters: - in: header name: Authorization d...
45bf3937c74902226096aee5b49e7abea62df524
<|skeleton|> class CampaignsRestAPI: def get(self, campaign_id): """Get an active campaign's information --- tags: - campaigns produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token type: string default: Token sessionTokenHere== - in: header name...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CampaignsRestAPI: def get(self, campaign_id): """Get an active campaign's information --- tags: - campaigns produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token type: string default: Token sessionTokenHere== - in: header name: Accept-Langu...
the_stack_v2_python_sparse
backend/api/campaigns/resources.py
hotosm/tasking-manager
train
526
75c5bb73d3c8cf0fe3670e371ef632f42633f240
[ "all_node_names = set(config['nodes'])\nfor node_pool in config['node_pools'].values():\n invalid_names = set(node_pool.nodes) - all_node_names\n if invalid_names:\n msg = 'NodePool %s contains other NodePools: ' % node_pool.name\n raise ConfigError(msg + ','.join(invalid_names))", "node_names...
<|body_start_0|> all_node_names = set(config['nodes']) for node_pool in config['node_pools'].values(): invalid_names = set(node_pool.nodes) - all_node_names if invalid_names: msg = 'NodePool %s contains other NodePools: ' % node_pool.name raise Con...
Given a parsed config file (should be only basic literals and containers), return an immutable, fully populated series of namedtuples and dicts with all defaults filled in, all valid values, and no unused values. Throws a ConfigError if any part of the input dict is invalid.
ValidateConfig
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidateConfig: """Given a parsed config file (should be only basic literals and containers), return an immutable, fully populated series of namedtuples and dicts with all defaults filled in, all valid values, and no unused values. Throws a ConfigError if any part of the input dict is invalid."""...
stack_v2_sparse_classes_36k_train_001253
34,183
permissive
[ { "docstring": "Validate that each node in a node_pool is in fact a node, and not another pool.", "name": "validate_node_pool_nodes", "signature": "def validate_node_pool_nodes(self, config)" }, { "docstring": "Validate a non-named config.", "name": "post_validation", "signature": "def p...
2
stack_v2_sparse_classes_30k_train_017247
Implement the Python class `ValidateConfig` described below. Class description: Given a parsed config file (should be only basic literals and containers), return an immutable, fully populated series of namedtuples and dicts with all defaults filled in, all valid values, and no unused values. Throws a ConfigError if an...
Implement the Python class `ValidateConfig` described below. Class description: Given a parsed config file (should be only basic literals and containers), return an immutable, fully populated series of namedtuples and dicts with all defaults filled in, all valid values, and no unused values. Throws a ConfigError if an...
958a2e22a6ac733cba043bc4238f3bf2b8048f4b
<|skeleton|> class ValidateConfig: """Given a parsed config file (should be only basic literals and containers), return an immutable, fully populated series of namedtuples and dicts with all defaults filled in, all valid values, and no unused values. Throws a ConfigError if any part of the input dict is invalid."""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ValidateConfig: """Given a parsed config file (should be only basic literals and containers), return an immutable, fully populated series of namedtuples and dicts with all defaults filled in, all valid values, and no unused values. Throws a ConfigError if any part of the input dict is invalid.""" def val...
the_stack_v2_python_sparse
tron/config/config_parse.py
Yelp/Tron
train
226
2e1ca49fb763d986e1920e6b7dbce5a606c8bf1d
[ "contacts = CompanyContact.get_contacts(gets_email=True)\nemail_tuple = (self.email_contact(contact) for contact in contacts)\nsend_mass_mail(email_tuple)", "if mig_alum:\n replace_text = self.mig_alum_text\nelif other_alum:\n replace_text = self.other_tbp_alum_text\nelif previous_contact:\n replace_text...
<|body_start_0|> contacts = CompanyContact.get_contacts(gets_email=True) email_tuple = (self.email_contact(contact) for contact in contacts) send_mass_mail(email_tuple) <|end_body_0|> <|body_start_1|> if mig_alum: replace_text = self.mig_alum_text elif other_alum: ...
Represents an email to be sent to the corporate contacts list. Provides an interface for creating and sending such emails.
CorporateEmail
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CorporateEmail: """Represents an email to be sent to the corporate contacts list. Provides an interface for creating and sending such emails.""" def send_corporate_email(self): """Sends the email to all company contacts who should receive it.""" <|body_0|> def preview_em...
stack_v2_sparse_classes_36k_train_001254
18,793
permissive
[ { "docstring": "Sends the email to all company contacts who should receive it.", "name": "send_corporate_email", "signature": "def send_corporate_email(self)" }, { "docstring": "Returns an example email based on the flags provided. Used to spot check emails before sending.", "name": "preview...
3
null
Implement the Python class `CorporateEmail` described below. Class description: Represents an email to be sent to the corporate contacts list. Provides an interface for creating and sending such emails. Method signatures and docstrings: - def send_corporate_email(self): Sends the email to all company contacts who sho...
Implement the Python class `CorporateEmail` described below. Class description: Represents an email to be sent to the corporate contacts list. Provides an interface for creating and sending such emails. Method signatures and docstrings: - def send_corporate_email(self): Sends the email to all company contacts who sho...
527f9dd39a6b50caa24ea5d0d97b19a0c9b675d1
<|skeleton|> class CorporateEmail: """Represents an email to be sent to the corporate contacts list. Provides an interface for creating and sending such emails.""" def send_corporate_email(self): """Sends the email to all company contacts who should receive it.""" <|body_0|> def preview_em...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CorporateEmail: """Represents an email to be sent to the corporate contacts list. Provides an interface for creating and sending such emails.""" def send_corporate_email(self): """Sends the email to all company contacts who should receive it.""" contacts = CompanyContact.get_contacts(gets...
the_stack_v2_python_sparse
corporate/models.py
tbpmig/mig-website
train
7
1b24588ec16026a310004395bf1c768dd85d33fd
[ "self.name = name\nself.label = label\nself.tag_name = tag_name\nself.description = description\nself.uri = None", "def cpo(method, *args, **kwargs):\n f = getattr(self, method)\n out = f(*args, **kwargs)\n result = {'method': method, 'result': out, 'schema': None}\n return result\nreturn cpo", "nam...
<|body_start_0|> self.name = name self.label = label self.tag_name = tag_name self.description = description self.uri = None <|end_body_0|> <|body_start_1|> def cpo(method, *args, **kwargs): f = getattr(self, method) out = f(*args, **kwargs) ...
View
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class View: def __init__(self, name, label, tag_name, description=''): """Initializes a View object Parameters ---------- name : The full name of the view label : The label to display in a (tab) layout tag_name : The web component labels description : Decription text for view""" <|body...
stack_v2_sparse_classes_36k_train_001255
2,887
no_license
[ { "docstring": "Initializes a View object Parameters ---------- name : The full name of the view label : The label to display in a (tab) layout tag_name : The web component labels description : Decription text for view", "name": "__init__", "signature": "def __init__(self, name, label, tag_name, descrip...
4
stack_v2_sparse_classes_30k_train_017997
Implement the Python class `View` described below. Class description: Implement the View class. Method signatures and docstrings: - def __init__(self, name, label, tag_name, description=''): Initializes a View object Parameters ---------- name : The full name of the view label : The label to display in a (tab) layout...
Implement the Python class `View` described below. Class description: Implement the View class. Method signatures and docstrings: - def __init__(self, name, label, tag_name, description=''): Initializes a View object Parameters ---------- name : The full name of the view label : The label to display in a (tab) layout...
535472844a046cadd9230302da647a54afff95e8
<|skeleton|> class View: def __init__(self, name, label, tag_name, description=''): """Initializes a View object Parameters ---------- name : The full name of the view label : The label to display in a (tab) layout tag_name : The web component labels description : Decription text for view""" <|body...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class View: def __init__(self, name, label, tag_name, description=''): """Initializes a View object Parameters ---------- name : The full name of the view label : The label to display in a (tab) layout tag_name : The web component labels description : Decription text for view""" self.name = name ...
the_stack_v2_python_sparse
env/lib/python2.7/site-packages/graphlab/_beta/views/platform/_view.py
hophamtenquang/RecSys
train
2
028d80b24867f09946d11df436e66ed39985cbb7
[ "super(CrossEntropyLoss, self).__init__()\nif weight is not None:\n weight = torch.tensor(weight).float()\nself.weight = weight", "num_class = logits.shape[1]\nassert num_class > 2, 'For class num 1 or 2, use BecLoss instead'\nif self.weight is not None:\n weight = self.weight.to(logits.device)\nelse:\n ...
<|body_start_0|> super(CrossEntropyLoss, self).__init__() if weight is not None: weight = torch.tensor(weight).float() self.weight = weight <|end_body_0|> <|body_start_1|> num_class = logits.shape[1] assert num_class > 2, 'For class num 1 or 2, use BecLoss instead' ...
CrossEntropyLoss
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CrossEntropyLoss: def __init__(self, weight=None): """computes the weighted multi-class cross-entropy loss. :param weight:a tensor of shape [C,], tuple or list. The weights attributed to each class.""" <|body_0|> def forward(self, gt, logits): """computes the weighte...
stack_v2_sparse_classes_36k_train_001256
12,362
no_license
[ { "docstring": "computes the weighted multi-class cross-entropy loss. :param weight:a tensor of shape [C,], tuple or list. The weights attributed to each class.", "name": "__init__", "signature": "def __init__(self, weight=None)" }, { "docstring": "computes the weighted multi-class cross-entropy...
2
stack_v2_sparse_classes_30k_train_011287
Implement the Python class `CrossEntropyLoss` described below. Class description: Implement the CrossEntropyLoss class. Method signatures and docstrings: - def __init__(self, weight=None): computes the weighted multi-class cross-entropy loss. :param weight:a tensor of shape [C,], tuple or list. The weights attributed...
Implement the Python class `CrossEntropyLoss` described below. Class description: Implement the CrossEntropyLoss class. Method signatures and docstrings: - def __init__(self, weight=None): computes the weighted multi-class cross-entropy loss. :param weight:a tensor of shape [C,], tuple or list. The weights attributed...
8e6f42e3a0cbc87c66b148fb61fcb44af287619e
<|skeleton|> class CrossEntropyLoss: def __init__(self, weight=None): """computes the weighted multi-class cross-entropy loss. :param weight:a tensor of shape [C,], tuple or list. The weights attributed to each class.""" <|body_0|> def forward(self, gt, logits): """computes the weighte...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CrossEntropyLoss: def __init__(self, weight=None): """computes the weighted multi-class cross-entropy loss. :param weight:a tensor of shape [C,], tuple or list. The weights attributed to each class.""" super(CrossEntropyLoss, self).__init__() if weight is not None: weight =...
the_stack_v2_python_sparse
lib/loss/loss.py
yangsenwxy/colonoscopy_tissue_screen_and_segmentation
train
0
0a698957917bc3d99a1b1bd69d904c86ba99a5ac
[ "super(DisplayShowOnly, self).__init__(parent)\nself.mainLayout = QtGui.QGridLayout(self)\nself.setLayout(self.mainLayout)\nself.show_cb = None\nself.btn_func = None\nself.info = None\nself.nothingtodo = None\nself.todo = todo\nself.listS = listS\nself.functionCalled = functionCalled\nself.populate()", "self.noth...
<|body_start_0|> super(DisplayShowOnly, self).__init__(parent) self.mainLayout = QtGui.QGridLayout(self) self.setLayout(self.mainLayout) self.show_cb = None self.btn_func = None self.info = None self.nothingtodo = None self.todo = todo self.listS =...
display list
DisplayShowOnly
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DisplayShowOnly: """display list""" def __init__(self, listS, functionCalled, todo, parent=None): """initialisation""" <|body_0|> def populate(self): """create layout""" <|body_1|> def displayButtons(self, value): """display or not Buttons"""...
stack_v2_sparse_classes_36k_train_001257
2,139
no_license
[ { "docstring": "initialisation", "name": "__init__", "signature": "def __init__(self, listS, functionCalled, todo, parent=None)" }, { "docstring": "create layout", "name": "populate", "signature": "def populate(self)" }, { "docstring": "display or not Buttons", "name": "displ...
5
stack_v2_sparse_classes_30k_train_013178
Implement the Python class `DisplayShowOnly` described below. Class description: display list Method signatures and docstrings: - def __init__(self, listS, functionCalled, todo, parent=None): initialisation - def populate(self): create layout - def displayButtons(self, value): display or not Buttons - def btn_pushed(...
Implement the Python class `DisplayShowOnly` described below. Class description: display list Method signatures and docstrings: - def __init__(self, listS, functionCalled, todo, parent=None): initialisation - def populate(self): create layout - def displayButtons(self, value): display or not Buttons - def btn_pushed(...
a24b3e4e8acbd4da9ba4c83bf96c0b2d2a2cca9c
<|skeleton|> class DisplayShowOnly: """display list""" def __init__(self, listS, functionCalled, todo, parent=None): """initialisation""" <|body_0|> def populate(self): """create layout""" <|body_1|> def displayButtons(self, value): """display or not Buttons"""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DisplayShowOnly: """display list""" def __init__(self, listS, functionCalled, todo, parent=None): """initialisation""" super(DisplayShowOnly, self).__init__(parent) self.mainLayout = QtGui.QGridLayout(self) self.setLayout(self.mainLayout) self.show_cb = None ...
the_stack_v2_python_sparse
gui/DisplayShowOnly.py
sensini42/flvdown
train
0
d6e7fa50785ceaf02442276608ad24910e38d016
[ "published = super(PageManager, self).published(for_user=for_user)\nunauthenticated = for_user and (not is_authenticated(for_user))\nif unauthenticated and (not include_login_required) and (not settings.PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED):\n published = published.exclude(login_required=True)\nreturn publishe...
<|body_start_0|> published = super(PageManager, self).published(for_user=for_user) unauthenticated = for_user and (not is_authenticated(for_user)) if unauthenticated and (not include_login_required) and (not settings.PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED): published = published.excl...
PageManager
[ "BSD-2-Clause", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PageManager: def published(self, for_user=None, include_login_required=False): """Override ``DisplayableManager.published`` to exclude pages with ``login_required`` set to ``True``. if the user is unauthenticated and the setting ``PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED`` is ``False``. Th...
stack_v2_sparse_classes_36k_train_001258
4,052
permissive
[ { "docstring": "Override ``DisplayableManager.published`` to exclude pages with ``login_required`` set to ``True``. if the user is unauthenticated and the setting ``PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED`` is ``False``. The extra ``include_login_required`` arg allows callers to override the ``PAGES_PUBLISHED_IN...
2
stack_v2_sparse_classes_30k_test_000601
Implement the Python class `PageManager` described below. Class description: Implement the PageManager class. Method signatures and docstrings: - def published(self, for_user=None, include_login_required=False): Override ``DisplayableManager.published`` to exclude pages with ``login_required`` set to ``True``. if the...
Implement the Python class `PageManager` described below. Class description: Implement the PageManager class. Method signatures and docstrings: - def published(self, for_user=None, include_login_required=False): Override ``DisplayableManager.published`` to exclude pages with ``login_required`` set to ``True``. if the...
29203de1d111a6d94d576a89430b37edd24cef55
<|skeleton|> class PageManager: def published(self, for_user=None, include_login_required=False): """Override ``DisplayableManager.published`` to exclude pages with ``login_required`` set to ``True``. if the user is unauthenticated and the setting ``PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED`` is ``False``. Th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PageManager: def published(self, for_user=None, include_login_required=False): """Override ``DisplayableManager.published`` to exclude pages with ``login_required`` set to ``True``. if the user is unauthenticated and the setting ``PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED`` is ``False``. The extra ``incl...
the_stack_v2_python_sparse
mezzanine/pages/managers.py
fermorltd/mezzanine
train
6
29344c8d49a2e83dd2b3cddd1c951817faf74026
[ "self.hass = hass\nself.last_approved_entities: dict[str, tuple[State, Any]] = {}\nself.extra_significant_check = extra_significant_check", "old_data: tuple[State, Any] | None = self.last_approved_entities.get(new_state.entity_id)\nif old_data is None:\n self.last_approved_entities[new_state.entity_id] = (new_...
<|body_start_0|> self.hass = hass self.last_approved_entities: dict[str, tuple[State, Any]] = {} self.extra_significant_check = extra_significant_check <|end_body_0|> <|body_start_1|> old_data: tuple[State, Any] | None = self.last_approved_entities.get(new_state.entity_id) if ol...
Class to keep track of entities to see if they have significantly changed. Will always compare the entity to the last entity that was considered significant.
SignificantlyChangedChecker
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SignificantlyChangedChecker: """Class to keep track of entities to see if they have significantly changed. Will always compare the entity to the last entity that was considered significant.""" def __init__(self, hass: HomeAssistant, extra_significant_check: ExtraCheckTypeFunc | None=None) ->...
stack_v2_sparse_classes_36k_train_001259
7,052
permissive
[ { "docstring": "Test if an entity has significantly changed.", "name": "__init__", "signature": "def __init__(self, hass: HomeAssistant, extra_significant_check: ExtraCheckTypeFunc | None=None) -> None" }, { "docstring": "Return if this was a significant change. Extra kwargs are passed to the ex...
2
null
Implement the Python class `SignificantlyChangedChecker` described below. Class description: Class to keep track of entities to see if they have significantly changed. Will always compare the entity to the last entity that was considered significant. Method signatures and docstrings: - def __init__(self, hass: HomeAs...
Implement the Python class `SignificantlyChangedChecker` described below. Class description: Class to keep track of entities to see if they have significantly changed. Will always compare the entity to the last entity that was considered significant. Method signatures and docstrings: - def __init__(self, hass: HomeAs...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class SignificantlyChangedChecker: """Class to keep track of entities to see if they have significantly changed. Will always compare the entity to the last entity that was considered significant.""" def __init__(self, hass: HomeAssistant, extra_significant_check: ExtraCheckTypeFunc | None=None) ->...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SignificantlyChangedChecker: """Class to keep track of entities to see if they have significantly changed. Will always compare the entity to the last entity that was considered significant.""" def __init__(self, hass: HomeAssistant, extra_significant_check: ExtraCheckTypeFunc | None=None) -> None: ...
the_stack_v2_python_sparse
homeassistant/helpers/significant_change.py
home-assistant/core
train
35,501
0ecd0dc1f5fc84a7eebe2715e1499a95db3a860f
[ "if config is None:\n config = {}\nself._config = config\nself._mapper = Mapper('Cleaner')", "cols_to_drop = []\nif self._config.get('REMOVE_WHERE_Y_MISSING', False) and (not predicted_col is None):\n self._mapper.set('Remove_Y_missing', True)\n self._mapper.set('Predicted_col', predicted_col)\n if pr...
<|body_start_0|> if config is None: config = {} self._config = config self._mapper = Mapper('Cleaner') <|end_body_0|> <|body_start_1|> cols_to_drop = [] if self._config.get('REMOVE_WHERE_Y_MISSING', False) and (not predicted_col is None): self._mapper.set...
Cleaner class - responsible for data cleaning Methods: - clean: cleans a dataset according to the configuration file - convert: based on previous cleaning logic it converts a dataset to a clean one
Cleaner
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Cleaner: """Cleaner class - responsible for data cleaning Methods: - clean: cleans a dataset according to the configuration file - convert: based on previous cleaning logic it converts a dataset to a clean one""" def __init__(self, config: dict=None): """Initializes a Cleaner :param ...
stack_v2_sparse_classes_36k_train_001260
4,299
permissive
[ { "docstring": "Initializes a Cleaner :param config: the configuration file: expected to receive the DATA_CLEANING_CONFIG part of the config file", "name": "__init__", "signature": "def __init__(self, config: dict=None)" }, { "docstring": "Cleans the data by removing rows/columns where necessary...
3
stack_v2_sparse_classes_30k_train_018311
Implement the Python class `Cleaner` described below. Class description: Cleaner class - responsible for data cleaning Methods: - clean: cleans a dataset according to the configuration file - convert: based on previous cleaning logic it converts a dataset to a clean one Method signatures and docstrings: - def __init_...
Implement the Python class `Cleaner` described below. Class description: Cleaner class - responsible for data cleaning Methods: - clean: cleans a dataset according to the configuration file - convert: based on previous cleaning logic it converts a dataset to a clean one Method signatures and docstrings: - def __init_...
96e8e3d8574873e1cdae4f90d53cde20bd28b1e1
<|skeleton|> class Cleaner: """Cleaner class - responsible for data cleaning Methods: - clean: cleans a dataset according to the configuration file - convert: based on previous cleaning logic it converts a dataset to a clean one""" def __init__(self, config: dict=None): """Initializes a Cleaner :param ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Cleaner: """Cleaner class - responsible for data cleaning Methods: - clean: cleans a dataset according to the configuration file - convert: based on previous cleaning logic it converts a dataset to a clean one""" def __init__(self, config: dict=None): """Initializes a Cleaner :param config: the c...
the_stack_v2_python_sparse
Pipeline/DataProcessor/DataCleaning/cleaner.py
Sanyam07/AutoML
train
0
53f7d1dfaeaff3b42532264f3aacec70e2b4f672
[ "dims = [1 for _ in shape]\nself.shape = tuple(shape[-3:-1])\ndims[-3:-1] = self.shape\nfull_width_half_maximum, acceleration = self.choose_acceleration()\nif not isinstance(full_width_half_maximum, list):\n full_width_half_maximum = [full_width_half_maximum] * 2\nself.full_width_half_maximum = full_width_half_m...
<|body_start_0|> dims = [1 for _ in shape] self.shape = tuple(shape[-3:-1]) dims[-3:-1] = self.shape full_width_half_maximum, acceleration = self.choose_acceleration() if not isinstance(full_width_half_maximum, list): full_width_half_maximum = [full_width_half_maximum...
Creates a 2D sub-sampling mask of a given shape. For autocalibration purposes, data points near the k-space center will be fully sampled within an ellipse of which the half-axes will set to the set scale % of the fully sampled region. The remaining points will be sampled according to a Gaussian distribution. The center...
Gaussian2DMaskFunc
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Gaussian2DMaskFunc: """Creates a 2D sub-sampling mask of a given shape. For autocalibration purposes, data points near the k-space center will be fully sampled within an ellipse of which the half-axes will set to the set scale % of the fully sampled region. The remaining points will be sampled ac...
stack_v2_sparse_classes_36k_train_001261
27,455
permissive
[ { "docstring": "Parameters ---------- shape: The shape of the mask to be created. The shape should have at least 3 dimensions. Samples are drawn along the second last dimension. seed: Seed for the random number generator. Setting the seed ensures the same mask is generated each time for the same shape. The rand...
4
null
Implement the Python class `Gaussian2DMaskFunc` described below. Class description: Creates a 2D sub-sampling mask of a given shape. For autocalibration purposes, data points near the k-space center will be fully sampled within an ellipse of which the half-axes will set to the set scale % of the fully sampled region. ...
Implement the Python class `Gaussian2DMaskFunc` described below. Class description: Creates a 2D sub-sampling mask of a given shape. For autocalibration purposes, data points near the k-space center will be fully sampled within an ellipse of which the half-axes will set to the set scale % of the fully sampled region. ...
6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066
<|skeleton|> class Gaussian2DMaskFunc: """Creates a 2D sub-sampling mask of a given shape. For autocalibration purposes, data points near the k-space center will be fully sampled within an ellipse of which the half-axes will set to the set scale % of the fully sampled region. The remaining points will be sampled ac...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Gaussian2DMaskFunc: """Creates a 2D sub-sampling mask of a given shape. For autocalibration purposes, data points near the k-space center will be fully sampled within an ellipse of which the half-axes will set to the set scale % of the fully sampled region. The remaining points will be sampled according to a ...
the_stack_v2_python_sparse
mridc/collections/reconstruction/data/subsample.py
wdika/mridc
train
40
266932c0ff377ca2f57e3a2b80d0a020037f56bd
[ "viewlet = zope.component.queryMultiAdapter((self.context, self.request, self.__parent__, self), interfaces.IViewlet, name=name)\nif viewlet is None:\n raise zope.interface.interfaces.ComponentLookupError('No provider with name `%s` found.' % name)\nif not guarded_hasattr(viewlet, 'render'):\n raise zope.secu...
<|body_start_0|> viewlet = zope.component.queryMultiAdapter((self.context, self.request, self.__parent__, self), interfaces.IViewlet, name=name) if viewlet is None: raise zope.interface.interfaces.ComponentLookupError('No provider with name `%s` found.' % name) if not guarded_hasattr...
A base class for Viewlet managers to work in Zope2
ViewletManagerBase
[ "ZPL-2.1" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ViewletManagerBase: """A base class for Viewlet managers to work in Zope2""" def __getitem__(self, name): """See zope.interface.common.mapping.IReadMapping""" <|body_0|> def filter(self, viewlets): """Sort out all content providers ``viewlets`` is a list of tuple...
stack_v2_sparse_classes_36k_train_001262
3,873
permissive
[ { "docstring": "See zope.interface.common.mapping.IReadMapping", "name": "__getitem__", "signature": "def __getitem__(self, name)" }, { "docstring": "Sort out all content providers ``viewlets`` is a list of tuples of the form (name, viewlet).", "name": "filter", "signature": "def filter(...
3
null
Implement the Python class `ViewletManagerBase` described below. Class description: A base class for Viewlet managers to work in Zope2 Method signatures and docstrings: - def __getitem__(self, name): See zope.interface.common.mapping.IReadMapping - def filter(self, viewlets): Sort out all content providers ``viewlets...
Implement the Python class `ViewletManagerBase` described below. Class description: A base class for Viewlet managers to work in Zope2 Method signatures and docstrings: - def __getitem__(self, name): See zope.interface.common.mapping.IReadMapping - def filter(self, viewlets): Sort out all content providers ``viewlets...
c31b1c635e85a1766f2666cb0bd117337ae5fa67
<|skeleton|> class ViewletManagerBase: """A base class for Viewlet managers to work in Zope2""" def __getitem__(self, name): """See zope.interface.common.mapping.IReadMapping""" <|body_0|> def filter(self, viewlets): """Sort out all content providers ``viewlets`` is a list of tuple...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ViewletManagerBase: """A base class for Viewlet managers to work in Zope2""" def __getitem__(self, name): """See zope.interface.common.mapping.IReadMapping""" viewlet = zope.component.queryMultiAdapter((self.context, self.request, self.__parent__, self), interfaces.IViewlet, name=name) ...
the_stack_v2_python_sparse
src/Products/Five/viewlet/manager.py
zopefoundation/Zope
train
335
90e8c7804115a43dcecf8095d145941766d59127
[ "self.record_value = dict()\nself.max_length = capacity\nself.queue = collections.deque()", "if key not in self.record_value:\n return -1\nif key in self.queue:\n self.queue.remove(key)\nself.queue.append(key)\nreturn self.record_value.get(key)", "if key in self.record_value:\n self.record_value[key] =...
<|body_start_0|> self.record_value = dict() self.max_length = capacity self.queue = collections.deque() <|end_body_0|> <|body_start_1|> if key not in self.record_value: return -1 if key in self.queue: self.queue.remove(key) self.queue.append(key) ...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_36k_train_001263
1,517
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: None", "name": "pu...
3
stack_v2_sparse_classes_30k_train_016503
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None <|sk...
f43d70cac56bdf6377b22b865174af822902ff78
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.record_value = dict() self.max_length = capacity self.queue = collections.deque() def get(self, key): """:type key: int :rtype: int""" if key not in self.record_value: return...
the_stack_v2_python_sparse
队列/LeetCode146_LRU缓存机制.py
ltzp/LeetCode
train
0
27d16dbabc6824f2669645c78ebb245681e8f3b0
[ "if User.objects.filter(id=value).exists():\n raise serializers.ValidationError('该用户已经存在!')\nreturn value", "r = requests.get('http://app.bjtitle.com/rui/bj-band.php?u=%d&t=1' % value)\nif r.text == '参数错误':\n raise serializers.ValidationError('请正确输入uid')\nreturn value" ]
<|body_start_0|> if User.objects.filter(id=value).exists(): raise serializers.ValidationError('该用户已经存在!') return value <|end_body_0|> <|body_start_1|> r = requests.get('http://app.bjtitle.com/rui/bj-band.php?u=%d&t=1' % value) if r.text == '参数错误': raise serialize...
UserCreateSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserCreateSerializer: def validate_id(self, value): """检查id是否重复""" <|body_0|> def validate_uid(self, value): """检查uid""" <|body_1|> <|end_skeleton|> <|body_start_0|> if User.objects.filter(id=value).exists(): raise serializers.Validation...
stack_v2_sparse_classes_36k_train_001264
6,644
no_license
[ { "docstring": "检查id是否重复", "name": "validate_id", "signature": "def validate_id(self, value)" }, { "docstring": "检查uid", "name": "validate_uid", "signature": "def validate_uid(self, value)" } ]
2
stack_v2_sparse_classes_30k_train_018917
Implement the Python class `UserCreateSerializer` described below. Class description: Implement the UserCreateSerializer class. Method signatures and docstrings: - def validate_id(self, value): 检查id是否重复 - def validate_uid(self, value): 检查uid
Implement the Python class `UserCreateSerializer` described below. Class description: Implement the UserCreateSerializer class. Method signatures and docstrings: - def validate_id(self, value): 检查id是否重复 - def validate_uid(self, value): 检查uid <|skeleton|> class UserCreateSerializer: def validate_id(self, value):...
a8e54c6ea1725d558b1485d7849860af4e177687
<|skeleton|> class UserCreateSerializer: def validate_id(self, value): """检查id是否重复""" <|body_0|> def validate_uid(self, value): """检查uid""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserCreateSerializer: def validate_id(self, value): """检查id是否重复""" if User.objects.filter(id=value).exists(): raise serializers.ValidationError('该用户已经存在!') return value def validate_uid(self, value): """检查uid""" r = requests.get('http://app.bjtitle.com/...
the_stack_v2_python_sparse
young_university_study/user/serializers.py
wzekin/bupt-youth-learning-server
train
0
80e130debf343b1ea7769e77323115739ddc4391
[ "if not graph.is_directed():\n raise ValueError('the graph is not directed')\nself.graph = graph\nself.T = dict()\nfor source in self.graph.iternodes():\n self.T[source] = dict()\n for target in self.graph.iternodes():\n self.T[source][target] = False\n self.T[source][source] = True", "for sour...
<|body_start_0|> if not graph.is_directed(): raise ValueError('the graph is not directed') self.graph = graph self.T = dict() for source in self.graph.iternodes(): self.T[source] = dict() for target in self.graph.iternodes(): self.T[sou...
Based on the DFS, O(V*(V+E)) time.
TransitiveClosureDFS
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransitiveClosureDFS: """Based on the DFS, O(V*(V+E)) time.""" def __init__(self, graph): """The algorithm initialization, O(V**2) time.""" <|body_0|> def run(self): """Executable pseudocode.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if no...
stack_v2_sparse_classes_36k_train_001265
3,816
permissive
[ { "docstring": "The algorithm initialization, O(V**2) time.", "name": "__init__", "signature": "def __init__(self, graph)" }, { "docstring": "Executable pseudocode.", "name": "run", "signature": "def run(self)" } ]
2
stack_v2_sparse_classes_30k_train_007943
Implement the Python class `TransitiveClosureDFS` described below. Class description: Based on the DFS, O(V*(V+E)) time. Method signatures and docstrings: - def __init__(self, graph): The algorithm initialization, O(V**2) time. - def run(self): Executable pseudocode.
Implement the Python class `TransitiveClosureDFS` described below. Class description: Based on the DFS, O(V*(V+E)) time. Method signatures and docstrings: - def __init__(self, graph): The algorithm initialization, O(V**2) time. - def run(self): Executable pseudocode. <|skeleton|> class TransitiveClosureDFS: """B...
0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60
<|skeleton|> class TransitiveClosureDFS: """Based on the DFS, O(V*(V+E)) time.""" def __init__(self, graph): """The algorithm initialization, O(V**2) time.""" <|body_0|> def run(self): """Executable pseudocode.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TransitiveClosureDFS: """Based on the DFS, O(V*(V+E)) time.""" def __init__(self, graph): """The algorithm initialization, O(V**2) time.""" if not graph.is_directed(): raise ValueError('the graph is not directed') self.graph = graph self.T = dict() for ...
the_stack_v2_python_sparse
graphtheory/algorithms/closure.py
kgashok/graphs-dict
train
0
e07e35976407d5147f6c4b3c88d7e9014483afa4
[ "if not cov.shape[0] == cov.shape[1]:\n raise ValueError('Covariance matrix is not square.')\nif not mean.shape[0] == cov.shape[0]:\n raise ValueError('Dimension mismatch between mean and covariance.')\nif not torch.allclose(cov, cov.transpose(-1, -2)):\n raise ValueError('Covariance matrix is not symmetri...
<|body_start_0|> if not cov.shape[0] == cov.shape[1]: raise ValueError('Covariance matrix is not square.') if not mean.shape[0] == cov.shape[0]: raise ValueError('Dimension mismatch between mean and covariance.') if not torch.allclose(cov, cov.transpose(-1, -2)): ...
Engine for qMC sampling from a multivariate Normal `N(\\mu, \\Sigma)`. By default, this implementation uses Box-Muller transformed Sobol samples following pg. 123 in [Pages2018numprob]_. To use the inverse transform instead, set `inv_transform=True`. Example: >>> mean = torch.tensor([1.0, 2.0]) >>> cov = torch.tensor([...
MultivariateNormalQMCEngine
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultivariateNormalQMCEngine: """Engine for qMC sampling from a multivariate Normal `N(\\mu, \\Sigma)`. By default, this implementation uses Box-Muller transformed Sobol samples following pg. 123 in [Pages2018numprob]_. To use the inverse transform instead, set `inv_transform=True`. Example: >>> m...
stack_v2_sparse_classes_36k_train_001266
6,555
permissive
[ { "docstring": "Engine for qMC sampling from a multivariate Normal `N(\\\\mu, \\\\Sigma)`. Args: mean: The mean vector. cov: The covariance matrix. seed: The seed with which to seed the random number generator of the underlying SobolEngine. inv_transform: If True, use inverse transform instead of Box-Muller.", ...
2
stack_v2_sparse_classes_30k_train_001460
Implement the Python class `MultivariateNormalQMCEngine` described below. Class description: Engine for qMC sampling from a multivariate Normal `N(\\mu, \\Sigma)`. By default, this implementation uses Box-Muller transformed Sobol samples following pg. 123 in [Pages2018numprob]_. To use the inverse transform instead, s...
Implement the Python class `MultivariateNormalQMCEngine` described below. Class description: Engine for qMC sampling from a multivariate Normal `N(\\mu, \\Sigma)`. By default, this implementation uses Box-Muller transformed Sobol samples following pg. 123 in [Pages2018numprob]_. To use the inverse transform instead, s...
4cc5ed59b2e8a9c780f786830c548e05cc74d53c
<|skeleton|> class MultivariateNormalQMCEngine: """Engine for qMC sampling from a multivariate Normal `N(\\mu, \\Sigma)`. By default, this implementation uses Box-Muller transformed Sobol samples following pg. 123 in [Pages2018numprob]_. To use the inverse transform instead, set `inv_transform=True`. Example: >>> m...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultivariateNormalQMCEngine: """Engine for qMC sampling from a multivariate Normal `N(\\mu, \\Sigma)`. By default, this implementation uses Box-Muller transformed Sobol samples following pg. 123 in [Pages2018numprob]_. To use the inverse transform instead, set `inv_transform=True`. Example: >>> mean = torch.t...
the_stack_v2_python_sparse
botorch/sampling/qmc.py
pytorch/botorch
train
2,891
0b8be7d632a87860456d1394f85d567a4941313f
[ "if not nums:\n return 0\nif len(nums) < 3:\n return max(nums)\nres = max(self.helper(nums[1:]), self.helper(nums[:-1]))\nreturn res", "max_ = [nums[0], max(nums[:2])]\nfor i in range(2, len(nums)):\n max_.append(max(nums[i] + max_[i - 2], max_[i - 1]))\nreturn max_[-1]" ]
<|body_start_0|> if not nums: return 0 if len(nums) < 3: return max(nums) res = max(self.helper(nums[1:]), self.helper(nums[:-1])) return res <|end_body_0|> <|body_start_1|> max_ = [nums[0], max(nums[:2])] for i in range(2, len(nums)): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def helper(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not nums: return 0 if len(nums) < 3...
stack_v2_sparse_classes_36k_train_001267
1,303
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "rob", "signature": "def rob(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "helper", "signature": "def helper(self, nums)" } ]
2
stack_v2_sparse_classes_30k_test_001000
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 helper(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 helper(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def rob(self, nums): ...
d181f2075c6c3881772dfbf54df3ac3390936079
<|skeleton|> class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def helper(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" if not nums: return 0 if len(nums) < 3: return max(nums) res = max(self.helper(nums[1:]), self.helper(nums[:-1])) return res def helper(self, nums): """:type nums...
the_stack_v2_python_sparse
213. House Robber II.py
melekoktay/Leetcode-Practice
train
0
0d5b0980006d7d84f441efd1bf72c8524f437176
[ "super().__init__(parent=parent)\nself._plot = self.plotBar()\nself._title_template = Template(f'ROI Histogram (mean: $mean, median: $median, std: $std)')\nself.updateTitle()\nself.setLabel('left', 'Counts')\nself.setLabel('bottom', 'Pixel value')", "hist = data.roi.hist\nif hist.hist is None:\n self.reset()\n...
<|body_start_0|> super().__init__(parent=parent) self._plot = self.plotBar() self._title_template = Template(f'ROI Histogram (mean: $mean, median: $median, std: $std)') self.updateTitle() self.setLabel('left', 'Counts') self.setLabel('bottom', 'Pixel value') <|end_body_0|...
RoiHist class. Widget for visualizing the ROI histogram.
RoiHist
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RoiHist: """RoiHist class. Widget for visualizing the ROI histogram.""" def __init__(self, *, parent=None): """Initialization.""" <|body_0|> def updateF(self, data): """Override.""" <|body_1|> <|end_skeleton|> <|body_start_0|> super().__init__(p...
stack_v2_sparse_classes_36k_train_001268
8,044
permissive
[ { "docstring": "Initialization.", "name": "__init__", "signature": "def __init__(self, *, parent=None)" }, { "docstring": "Override.", "name": "updateF", "signature": "def updateF(self, data)" } ]
2
stack_v2_sparse_classes_30k_val_000455
Implement the Python class `RoiHist` described below. Class description: RoiHist class. Widget for visualizing the ROI histogram. Method signatures and docstrings: - def __init__(self, *, parent=None): Initialization. - def updateF(self, data): Override.
Implement the Python class `RoiHist` described below. Class description: RoiHist class. Widget for visualizing the ROI histogram. Method signatures and docstrings: - def __init__(self, *, parent=None): Initialization. - def updateF(self, data): Override. <|skeleton|> class RoiHist: """RoiHist class. Widget for v...
a6ee28040b15ae8d110570bd9f3c37e5a3e70fc0
<|skeleton|> class RoiHist: """RoiHist class. Widget for visualizing the ROI histogram.""" def __init__(self, *, parent=None): """Initialization.""" <|body_0|> def updateF(self, data): """Override.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RoiHist: """RoiHist class. Widget for visualizing the ROI histogram.""" def __init__(self, *, parent=None): """Initialization.""" super().__init__(parent=parent) self._plot = self.plotBar() self._title_template = Template(f'ROI Histogram (mean: $mean, median: $median, std:...
the_stack_v2_python_sparse
extra_foam/gui/image_tool/corrected_view.py
European-XFEL/EXtra-foam
train
8
945e3e23bd75205f80350df351a7c10d5f780a75
[ "self.accu_matrix = [row[:] for row in matrix]\nfor row in self.accu_matrix:\n for idx in range(1, len(row)):\n row[idx] += row[idx - 1]", "res = 0\nfor row in self.accu_matrix[row1:row2 + 1]:\n res += row[col2] - (row[col1 - 1] if col1 > 0 else 0)\nreturn res" ]
<|body_start_0|> self.accu_matrix = [row[:] for row in matrix] for row in self.accu_matrix: for idx in range(1, len(row)): row[idx] += row[idx - 1] <|end_body_0|> <|body_start_1|> res = 0 for row in self.accu_matrix[row1:row2 + 1]: res += row[col2...
NumMatrix
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" <|body_0|> def sumRegion(self, row1, col1, row2, col2): """:type row1: int :type col1: int :type row2: int :type col2: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_36k_train_001269
1,079
no_license
[ { "docstring": ":type matrix: List[List[int]]", "name": "__init__", "signature": "def __init__(self, matrix)" }, { "docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int", "name": "sumRegion", "signature": "def sumRegion(self, row1, col1, row2, col2)" ...
2
null
Implement the Python class `NumMatrix` described below. Class description: Implement the NumMatrix class. Method signatures and docstrings: - def __init__(self, matrix): :type matrix: List[List[int]] - def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:...
Implement the Python class `NumMatrix` described below. Class description: Implement the NumMatrix class. Method signatures and docstrings: - def __init__(self, matrix): :type matrix: List[List[int]] - def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:...
dbdb227e12f329e4ca064b338f1fbdca42f3a848
<|skeleton|> class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" <|body_0|> def sumRegion(self, row1, col1, row2, col2): """:type row1: int :type col1: int :type row2: int :type col2: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" self.accu_matrix = [row[:] for row in matrix] for row in self.accu_matrix: for idx in range(1, len(row)): row[idx] += row[idx - 1] def sumRegion(self, row1, col1, row2, col2): ...
the_stack_v2_python_sparse
LC304.py
Qiao-Liang/LeetCode
train
0
bc5794678b6d15877265ea20a2fcd6180bdb13db
[ "self.class_dict = {0: 'airplane', 1: 'automobile', 2: 'bird', 3: 'cat', 4: 'deer', 5: 'dog', 6: 'frog', 7: 'horse', 8: 'ship', 9: 'truck'}\nself.file_path = file_path\nself.label_path = label_path\nself.batch_size = batch_size\nself.image_size = image_size\nself.rotation = rotation\nself.mirroring = mirroring\nsel...
<|body_start_0|> self.class_dict = {0: 'airplane', 1: 'automobile', 2: 'bird', 3: 'cat', 4: 'deer', 5: 'dog', 6: 'frog', 7: 'horse', 8: 'ship', 9: 'truck'} self.file_path = file_path self.label_path = label_path self.batch_size = batch_size self.image_size = image_size se...
This class creates an image generator. Generator objects in python are defined as having a next function. This next function returns the next generated object. In our case it returns the input of a neural network each time it gets called. This input consists of a batch of images and its corresponding labels.
ImageGenerator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImageGenerator: """This class creates an image generator. Generator objects in python are defined as having a next function. This next function returns the next generated object. In our case it returns the input of a neural network each time it gets called. This input consists of a batch of image...
stack_v2_sparse_classes_36k_train_001270
6,141
no_license
[ { "docstring": "Constructor. :param file_path: Path to the directory containing all images. :param label_path: Path to the JSON file containing the labels. :param batch_size: Number of images in a batch. :param image_size: list of [height, width, channel] defining the desired image size. :param rotation: If the...
5
stack_v2_sparse_classes_30k_train_010235
Implement the Python class `ImageGenerator` described below. Class description: This class creates an image generator. Generator objects in python are defined as having a next function. This next function returns the next generated object. In our case it returns the input of a neural network each time it gets called. ...
Implement the Python class `ImageGenerator` described below. Class description: This class creates an image generator. Generator objects in python are defined as having a next function. This next function returns the next generated object. In our case it returns the input of a neural network each time it gets called. ...
1d2d990c75bb7977d76430a50a31bd9ce31da37d
<|skeleton|> class ImageGenerator: """This class creates an image generator. Generator objects in python are defined as having a next function. This next function returns the next generated object. In our case it returns the input of a neural network each time it gets called. This input consists of a batch of image...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ImageGenerator: """This class creates an image generator. Generator objects in python are defined as having a next function. This next function returns the next generated object. In our case it returns the input of a neural network each time it gets called. This input consists of a batch of images and its cor...
the_stack_v2_python_sparse
Exercise 0/Code/generator.py
StefanFischer/Deep-Learning-Framework
train
0
aeb3ab99d75b26bd66743ad4a6bee3666807a4ab
[ "v = version.inventreeVersionTuple()\nself.assertEqual(len(v), 3)\ns = '.'.join([str(i) for i in v])\nself.assertTrue(s in version.inventreeVersion())", "v_a = version.inventreeVersionTuple('1.2.0')\nv_b = version.inventreeVersionTuple('1.2.3')\nv_c = version.inventreeVersionTuple('1.2.4')\nv_d = version.inventre...
<|body_start_0|> v = version.inventreeVersionTuple() self.assertEqual(len(v), 3) s = '.'.join([str(i) for i in v]) self.assertTrue(s in version.inventreeVersion()) <|end_body_0|> <|body_start_1|> v_a = version.inventreeVersionTuple('1.2.0') v_b = version.inventreeVersion...
Unit tests for version number functions.
TestVersionNumber
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestVersionNumber: """Unit tests for version number functions.""" def test_tuple(self): """Test inventreeVersionTuple.""" <|body_0|> def test_comparison(self): """Test direct comparison of version numbers.""" <|body_1|> def test_commit_info(self): ...
stack_v2_sparse_classes_36k_train_001271
41,191
permissive
[ { "docstring": "Test inventreeVersionTuple.", "name": "test_tuple", "signature": "def test_tuple(self)" }, { "docstring": "Test direct comparison of version numbers.", "name": "test_comparison", "signature": "def test_comparison(self)" }, { "docstring": "Test that the git commit ...
3
null
Implement the Python class `TestVersionNumber` described below. Class description: Unit tests for version number functions. Method signatures and docstrings: - def test_tuple(self): Test inventreeVersionTuple. - def test_comparison(self): Test direct comparison of version numbers. - def test_commit_info(self): Test t...
Implement the Python class `TestVersionNumber` described below. Class description: Unit tests for version number functions. Method signatures and docstrings: - def test_tuple(self): Test inventreeVersionTuple. - def test_comparison(self): Test direct comparison of version numbers. - def test_commit_info(self): Test t...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class TestVersionNumber: """Unit tests for version number functions.""" def test_tuple(self): """Test inventreeVersionTuple.""" <|body_0|> def test_comparison(self): """Test direct comparison of version numbers.""" <|body_1|> def test_commit_info(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestVersionNumber: """Unit tests for version number functions.""" def test_tuple(self): """Test inventreeVersionTuple.""" v = version.inventreeVersionTuple() self.assertEqual(len(v), 3) s = '.'.join([str(i) for i in v]) self.assertTrue(s in version.inventreeVersion...
the_stack_v2_python_sparse
InvenTree/InvenTree/tests.py
inventree/InvenTree
train
3,077
7259a6fc3e5774d12421de3215b5af6ab1b4a80a
[ "if not root:\n return None\nif root.val > p.val:\n return self.inorderSuccessor(root.left, p) or root\nreturn self.inorderSuccessor(root.right, p)", "def push_next(node):\n it = node.right\n while it:\n ancestors.append(it)\n it = it.left\nancestors = []\ndummy = TreeNode(-1)\ndummy.rig...
<|body_start_0|> if not root: return None if root.val > p.val: return self.inorderSuccessor(root.left, p) or root return self.inorderSuccessor(root.right, p) <|end_body_0|> <|body_start_1|> def push_next(node): it = node.right while it: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def inorderSuccessor(self, root, p): """:type root: TreeNode :type p: TreeNode :rtype: TreeNode""" <|body_0|> def inorderSuccessor_(self, root, p): """:type root: TreeNode :type p: TreeNode :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_st...
stack_v2_sparse_classes_36k_train_001272
1,397
no_license
[ { "docstring": ":type root: TreeNode :type p: TreeNode :rtype: TreeNode", "name": "inorderSuccessor", "signature": "def inorderSuccessor(self, root, p)" }, { "docstring": ":type root: TreeNode :type p: TreeNode :rtype: TreeNode", "name": "inorderSuccessor_", "signature": "def inorderSucc...
2
stack_v2_sparse_classes_30k_train_018493
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def inorderSuccessor(self, root, p): :type root: TreeNode :type p: TreeNode :rtype: TreeNode - def inorderSuccessor_(self, root, p): :type root: TreeNode :type p: TreeNode :rtype...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def inorderSuccessor(self, root, p): :type root: TreeNode :type p: TreeNode :rtype: TreeNode - def inorderSuccessor_(self, root, p): :type root: TreeNode :type p: TreeNode :rtype...
ef052efcbcceb38e44fdd7cbcb6a7e6bd7ff8aa2
<|skeleton|> class Solution: def inorderSuccessor(self, root, p): """:type root: TreeNode :type p: TreeNode :rtype: TreeNode""" <|body_0|> def inorderSuccessor_(self, root, p): """:type root: TreeNode :type p: TreeNode :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def inorderSuccessor(self, root, p): """:type root: TreeNode :type p: TreeNode :rtype: TreeNode""" if not root: return None if root.val > p.val: return self.inorderSuccessor(root.left, p) or root return self.inorderSuccessor(root.right, p) ...
the_stack_v2_python_sparse
bfs_dfs/inorder_successor_in_bst.py
moyuanhuang/leetcode
train
2
edf3e90b1b0882d0160e358ca9b9f7a3b2da8534
[ "with open(self.file_path, mode='rt') as fid:\n all_lines = self._parse_file(fid)\nsta_codes = self._parse_stations(all_lines)\nnum_obs = self._parse_scans(all_lines)\nself.data = {STATION_NAME_MAP.get(sta_codes[k], sta_codes[k]): v for k, v in num_obs.items() if k in sta_codes}\nif not self.data:\n self.data...
<|body_start_0|> with open(self.file_path, mode='rt') as fid: all_lines = self._parse_file(fid) sta_codes = self._parse_stations(all_lines) num_obs = self._parse_scans(all_lines) self.data = {STATION_NAME_MAP.get(sta_codes[k], sta_codes[k]): v for k, v in num_obs.items() if k...
A parser for reading VLBI schedule files produced by SKED.
VlbiSkdParser
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VlbiSkdParser: """A parser for reading VLBI schedule files produced by SKED.""" def read_data(self): """Reads the schedule file and stores the information in self.data""" <|body_0|> def _parse_file(self, fid): """Store each line in the file in a dictionary based ...
stack_v2_sparse_classes_36k_train_001273
3,431
permissive
[ { "docstring": "Reads the schedule file and stores the information in self.data", "name": "read_data", "signature": "def read_data(self)" }, { "docstring": "Store each line in the file in a dictionary based on blocks Each block is defined by with the \"$\" character and the name of the block. Re...
4
null
Implement the Python class `VlbiSkdParser` described below. Class description: A parser for reading VLBI schedule files produced by SKED. Method signatures and docstrings: - def read_data(self): Reads the schedule file and stores the information in self.data - def _parse_file(self, fid): Store each line in the file i...
Implement the Python class `VlbiSkdParser` described below. Class description: A parser for reading VLBI schedule files produced by SKED. Method signatures and docstrings: - def read_data(self): Reads the schedule file and stores the information in self.data - def _parse_file(self, fid): Store each line in the file i...
0c8c5c68adca08f97e22cab1bce10e382a7fbf77
<|skeleton|> class VlbiSkdParser: """A parser for reading VLBI schedule files produced by SKED.""" def read_data(self): """Reads the schedule file and stores the information in self.data""" <|body_0|> def _parse_file(self, fid): """Store each line in the file in a dictionary based ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VlbiSkdParser: """A parser for reading VLBI schedule files produced by SKED.""" def read_data(self): """Reads the schedule file and stores the information in self.data""" with open(self.file_path, mode='rt') as fid: all_lines = self._parse_file(fid) sta_codes = self._p...
the_stack_v2_python_sparse
where/parsers/vlbi_skd.py
kartverket/where
train
21
f0bdc18bbdc65c9e968d24215b8e50bef2352cc7
[ "super(Conv2dSubsampling8, 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(), torch.nn.Conv2d(odim, odim, 3, 2), torch.nn.ReLU())\nself.out = torch.nn.Sequential(torch.nn.Linear(odim * ((((idim - 1) // 2 - 1) // 2 - ...
<|body_start_0|> super(Conv2dSubsampling8, 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(), torch.nn.Conv2d(odim, odim, 3, 2), torch.nn.ReLU()) self.out = torch.nn.Sequential(torch.nn.Linear(odim...
Convolutional 2D subsampling (to 1/8 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer.
Conv2dSubsampling8
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Conv2dSubsampling8: """Convolutional 2D subsampling (to 1/8 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=None): ...
stack_v2_sparse_classes_36k_train_001274
14,351
permissive
[ { "docstring": "Construct an Conv2dSubsampling8 object.", "name": "__init__", "signature": "def __init__(self, idim, odim, dropout_rate, pos_enc=None)" }, { "docstring": "Subsample x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tensor): Input mask (#batch, 1, time). ...
2
null
Implement the Python class `Conv2dSubsampling8` described below. Class description: Convolutional 2D subsampling (to 1/8 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 docstr...
Implement the Python class `Conv2dSubsampling8` described below. Class description: Convolutional 2D subsampling (to 1/8 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 docstr...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class Conv2dSubsampling8: """Convolutional 2D subsampling (to 1/8 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=None): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Conv2dSubsampling8: """Convolutional 2D subsampling (to 1/8 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=None): """Co...
the_stack_v2_python_sparse
espnet/nets/pytorch_backend/transformer/subsampling.py
espnet/espnet
train
7,242
f0cbe2b871553f2a2bb0e7f0f5b9c2921638d0c6
[ "result = []\npostor_order(root, result)\nreturn result", "if root is None:\n return []\nresult = []\nstack = [[root, 'L']]\nwhile stack:\n now, flag = stack[-1]\n if flag == 'L':\n stack[-1][1] = 'R'\n if now.left is not None:\n stack.append([now.left, 'L'])\n elif flag == 'R...
<|body_start_0|> result = [] postor_order(root, result) return result <|end_body_0|> <|body_start_1|> if root is None: return [] result = [] stack = [[root, 'L']] while stack: now, flag = stack[-1] if flag == 'L': ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: """递归方式 :param root: :return:""" <|body_0|> def postorderTraversal1(self, root: TreeNode) -> List[int]: """非递归方式 :param root: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_001275
1,553
no_license
[ { "docstring": "递归方式 :param root: :return:", "name": "postorderTraversal", "signature": "def postorderTraversal(self, root: TreeNode) -> List[int]" }, { "docstring": "非递归方式 :param root: :return:", "name": "postorderTraversal1", "signature": "def postorderTraversal1(self, root: TreeNode) ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def postorderTraversal(self, root: TreeNode) -> List[int]: 递归方式 :param root: :return: - def postorderTraversal1(self, root: TreeNode) -> List[int]: 非递归方式 :param root: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def postorderTraversal(self, root: TreeNode) -> List[int]: 递归方式 :param root: :return: - def postorderTraversal1(self, root: TreeNode) -> List[int]: 非递归方式 :param root: :return: <...
ef1d29a769f2fd6d517497f8b42121c02f8307cc
<|skeleton|> class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: """递归方式 :param root: :return:""" <|body_0|> def postorderTraversal1(self, root: TreeNode) -> List[int]: """非递归方式 :param root: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: """递归方式 :param root: :return:""" result = [] postor_order(root, result) return result def postorderTraversal1(self, root: TreeNode) -> List[int]: """非递归方式 :param root: :return:""" if root ...
the_stack_v2_python_sparse
力扣网/二叉树的后序遍历_非递归.py
longkun-uestc/examination
train
1
8b637b2936f6b52b8de2c6627be59b0a631aa901
[ "mainDpath = '/umbc/xfs1/zzbatmos/users/charaj1/'\nself.d865SZAx = POLCARTdset('d865SZAx', mainDpath + 'Toy_clouds_MSCART/Fractal_Cloud/')\nself.d865SZAx.readPOLCARThdf5('fractal_cld_b865re12ve05_x40km_MSCART_SZA' + sza + '_SAA000_VAA000plus_NPH1e5.hdf5', dpath=mainDpath + '/Toy_clouds_MSCART/Fractal_Cloud/results/...
<|body_start_0|> mainDpath = '/umbc/xfs1/zzbatmos/users/charaj1/' self.d865SZAx = POLCARTdset('d865SZAx', mainDpath + 'Toy_clouds_MSCART/Fractal_Cloud/') self.d865SZAx.readPOLCARThdf5('fractal_cld_b865re12ve05_x40km_MSCART_SZA' + sza + '_SAA000_VAA000plus_NPH1e5.hdf5', dpath=mainDpath + '/Toy_cl...
Fractal_CLD
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Fractal_CLD: def __init__(self, sza): """sza: SZA string""" <|body_0|> def find_3DimpFac(self, VZAi, R2p13_th, LUT_SWIRre=None, LUT_VNIRre=None): """Find 3D impact factor f=(3D-1D)/1D VZAi: viewing zenith angle index (usually 61 for zero degrees) R2p13_th: R2p13 thre...
stack_v2_sparse_classes_36k_train_001276
9,908
no_license
[ { "docstring": "sza: SZA string", "name": "__init__", "signature": "def __init__(self, sza)" }, { "docstring": "Find 3D impact factor f=(3D-1D)/1D VZAi: viewing zenith angle index (usually 61 for zero degrees) R2p13_th: R2p13 threshold -------------------------- Give LUT_SWIRre and LUT_VNIRre to...
2
null
Implement the Python class `Fractal_CLD` described below. Class description: Implement the Fractal_CLD class. Method signatures and docstrings: - def __init__(self, sza): sza: SZA string - def find_3DimpFac(self, VZAi, R2p13_th, LUT_SWIRre=None, LUT_VNIRre=None): Find 3D impact factor f=(3D-1D)/1D VZAi: viewing zenit...
Implement the Python class `Fractal_CLD` described below. Class description: Implement the Fractal_CLD class. Method signatures and docstrings: - def __init__(self, sza): sza: SZA string - def find_3DimpFac(self, VZAi, R2p13_th, LUT_SWIRre=None, LUT_VNIRre=None): Find 3D impact factor f=(3D-1D)/1D VZAi: viewing zenit...
def08c990dba12bc5a0a392863b8e1e3411f0a32
<|skeleton|> class Fractal_CLD: def __init__(self, sza): """sza: SZA string""" <|body_0|> def find_3DimpFac(self, VZAi, R2p13_th, LUT_SWIRre=None, LUT_VNIRre=None): """Find 3D impact factor f=(3D-1D)/1D VZAi: viewing zenith angle index (usually 61 for zero degrees) R2p13_th: R2p13 thre...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Fractal_CLD: def __init__(self, sza): """sza: SZA string""" mainDpath = '/umbc/xfs1/zzbatmos/users/charaj1/' self.d865SZAx = POLCARTdset('d865SZAx', mainDpath + 'Toy_clouds_MSCART/Fractal_Cloud/') self.d865SZAx.readPOLCARThdf5('fractal_cld_b865re12ve05_x40km_MSCART_SZA' + sza +...
the_stack_v2_python_sparse
Retrievals/Pol_retrievals/pol_toy_cloud_ret.py
cpnHere/ACRS
train
0
694642e8064b83ba3a85b5f58f0fd8e6093d3ca2
[ "n2 = 1 << (n - 1).bit_length()\nself.offset = n2\nself.tree = [INF] * (n2 << 1)\nself.INF = INF", "i += self.offset\nself.tree[i] = x\nwhile i > 1:\n y = self.tree[i ^ 1]\n if y <= x:\n break\n i >>= 1\n self.tree[i] = x", "result = self.INF\nl = a + self.offset\nr = b + self.offset\nwhile l...
<|body_start_0|> n2 = 1 << (n - 1).bit_length() self.offset = n2 self.tree = [INF] * (n2 << 1) self.INF = INF <|end_body_0|> <|body_start_1|> i += self.offset self.tree[i] = x while i > 1: y = self.tree[i ^ 1] if y <= x: br...
SegmentTree
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SegmentTree: def __init__(self, n, first_status): """:param n: 要素数 :param INF: 初期値(入りうる要素より十分に大きな数)""" <|body_0|> def update(self, i, x): """i番目の値をxに更新 :param i: index(0-indexed) :param x: update value""" <|body_1|> def get_min(self, a, b): """[a...
stack_v2_sparse_classes_36k_train_001277
1,305
no_license
[ { "docstring": ":param n: 要素数 :param INF: 初期値(入りうる要素より十分に大きな数)", "name": "__init__", "signature": "def __init__(self, n, first_status)" }, { "docstring": "i番目の値をxに更新 :param i: index(0-indexed) :param x: update value", "name": "update", "signature": "def update(self, i, x)" }, { "...
3
null
Implement the Python class `SegmentTree` described below. Class description: Implement the SegmentTree class. Method signatures and docstrings: - def __init__(self, n, first_status): :param n: 要素数 :param INF: 初期値(入りうる要素より十分に大きな数) - def update(self, i, x): i番目の値をxに更新 :param i: index(0-indexed) :param x: update value -...
Implement the Python class `SegmentTree` described below. Class description: Implement the SegmentTree class. Method signatures and docstrings: - def __init__(self, n, first_status): :param n: 要素数 :param INF: 初期値(入りうる要素より十分に大きな数) - def update(self, i, x): i番目の値をxに更新 :param i: index(0-indexed) :param x: update value -...
46a7d9b9b33d4fbbcffeb6bb90d4bfca8d5dfa2a
<|skeleton|> class SegmentTree: def __init__(self, n, first_status): """:param n: 要素数 :param INF: 初期値(入りうる要素より十分に大きな数)""" <|body_0|> def update(self, i, x): """i番目の値をxに更新 :param i: index(0-indexed) :param x: update value""" <|body_1|> def get_min(self, a, b): """[a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SegmentTree: def __init__(self, n, first_status): """:param n: 要素数 :param INF: 初期値(入りうる要素より十分に大きな数)""" n2 = 1 << (n - 1).bit_length() self.offset = n2 self.tree = [INF] * (n2 << 1) self.INF = INF def update(self, i, x): """i番目の値をxに更新 :param i: index(0-index...
the_stack_v2_python_sparse
contest/abc185/f.py
konchanksu/AtCoder-practice
train
0
ff277ea152d3e2e1823c9aa20297bb4e325dc49e
[ "self.Npr = Npr\nself.rmin = rmin\nself.rmax = rmax\nself.Nptheta = Nptheta\nself.n = n\nself.dens_func = dens_func\nself.ux_m = ux_m\nself.uy_m = uy_m\nself.uz_m = uz_m\nself.ux_th = ux_th\nself.uy_th = uy_th\nself.uz_th = uz_th\nif Npz != 0:\n self.dz_particles = (zmax - zmin) / Npz\nelse:\n self.dz_particl...
<|body_start_0|> self.Npr = Npr self.rmin = rmin self.rmax = rmax self.Nptheta = Nptheta self.n = n self.dens_func = dens_func self.ux_m = ux_m self.uy_m = uy_m self.uz_m = uz_m self.ux_th = ux_th self.uy_th = uy_th self.uz_...
Class that stores a number of attributes that are needed for continuous injection by a moving window.
ContinuousInjector
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ContinuousInjector: """Class that stores a number of attributes that are needed for continuous injection by a moving window.""" def __init__(self, Npz, zmin, zmax, dz_particles, Npr, rmin, rmax, Nptheta, n, dens_func, ux_m, uy_m, uz_m, ux_th, uy_th, uz_th): """Initialize continuous i...
stack_v2_sparse_classes_36k_train_001278
14,108
permissive
[ { "docstring": "Initialize continuous injection Parameters ---------- See the docstring of the `Particles` object", "name": "__init__", "signature": "def __init__(self, Npz, zmin, zmax, dz_particles, Npr, rmin, rmax, Nptheta, n, dens_func, ux_m, uy_m, uz_m, ux_th, uy_th, uz_th)" }, { "docstring"...
5
null
Implement the Python class `ContinuousInjector` described below. Class description: Class that stores a number of attributes that are needed for continuous injection by a moving window. Method signatures and docstrings: - def __init__(self, Npz, zmin, zmax, dz_particles, Npr, rmin, rmax, Nptheta, n, dens_func, ux_m, ...
Implement the Python class `ContinuousInjector` described below. Class description: Class that stores a number of attributes that are needed for continuous injection by a moving window. Method signatures and docstrings: - def __init__(self, Npz, zmin, zmax, dz_particles, Npr, rmin, rmax, Nptheta, n, dens_func, ux_m, ...
5744598571eab40c4fb45cc3db21f346b69b1f37
<|skeleton|> class ContinuousInjector: """Class that stores a number of attributes that are needed for continuous injection by a moving window.""" def __init__(self, Npz, zmin, zmax, dz_particles, Npr, rmin, rmax, Nptheta, n, dens_func, ux_m, uy_m, uz_m, ux_th, uy_th, uz_th): """Initialize continuous i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ContinuousInjector: """Class that stores a number of attributes that are needed for continuous injection by a moving window.""" def __init__(self, Npz, zmin, zmax, dz_particles, Npr, rmin, rmax, Nptheta, n, dens_func, ux_m, uy_m, uz_m, ux_th, uy_th, uz_th): """Initialize continuous injection Para...
the_stack_v2_python_sparse
fbpic/particles/injection/continuous_injection.py
fbpic/fbpic
train
163
513458306708ce9e8fb57f5bdc8e099adfab2629
[ "Parametre.__init__(self, 'joueur', 'player')\nself.schema = '<nom_joueur>'\nself.aide_courte = 'banni définitivement un joueur'\nself.aide_longue = 'Cette commande permet de bannir définitivement un joueur. Toutefois, si le joueur est déjà banni, utiliser cette commande une nouvelle fois permet de lever le banniss...
<|body_start_0|> Parametre.__init__(self, 'joueur', 'player') self.schema = '<nom_joueur>' self.aide_courte = 'banni définitivement un joueur' self.aide_longue = 'Cette commande permet de bannir définitivement un joueur. Toutefois, si le joueur est déjà banni, utiliser cette commande une...
Commande 'bannir joueur'.
PrmJoueur
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PrmJoueur: """Commande 'bannir joueur'.""" 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_36k_train_001279
3,253
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
stack_v2_sparse_classes_30k_train_011076
Implement the Python class `PrmJoueur` described below. Class description: Commande 'bannir joueur'. 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 `PrmJoueur` described below. Class description: Commande 'bannir joueur'. Method signatures and docstrings: - def __init__(self): Constructeur du paramètre - def interpreter(self, personnage, dic_masques): Interprétation du paramètre <|skeleton|> class PrmJoueur: """Commande 'bannir jo...
7e93bff08cdf891352efba587e89c40f3b4a2301
<|skeleton|> class PrmJoueur: """Commande 'bannir joueur'.""" def __init__(self): """Constructeur du paramètre""" <|body_0|> def interpreter(self, personnage, dic_masques): """Interprétation du paramètre""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PrmJoueur: """Commande 'bannir joueur'.""" def __init__(self): """Constructeur du paramètre""" Parametre.__init__(self, 'joueur', 'player') self.schema = '<nom_joueur>' self.aide_courte = 'banni définitivement un joueur' self.aide_longue = 'Cette commande permet de...
the_stack_v2_python_sparse
src/primaires/joueur/commandes/bannir/joueur.py
vincent-lg/tsunami
train
5
8f31ed944aa942639b0b7975aa33d03dddfbdc7d
[ "self.auth = ('api', api_key)\nself.api_url = f'https://api.mailgun.net/v3/{domain}'\nself.sender = f'{sender_name} <noreply@{domain}>'", "data['from'] = self.sender\ntry:\n return requests.post(f'{self.api_url}/messages', auth=self.auth, data=data)\nexcept (requests.HTTPError, requests.ConnectionError):\n ...
<|body_start_0|> self.auth = ('api', api_key) self.api_url = f'https://api.mailgun.net/v3/{domain}' self.sender = f'{sender_name} <noreply@{domain}>' <|end_body_0|> <|body_start_1|> data['from'] = self.sender try: return requests.post(f'{self.api_url}/messages', auth...
Send a mail through the Mailgun API.
Mailer
[ "ISC" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Mailer: """Send a mail through the Mailgun API.""" def __init__(self, domain: str, api_key: str, sender_name: str) -> None: """Initialize the Mailer class. :param domain: Domain name of the sender :type domain: str :param api_key: API key of the Mailgun API :type api_key: str :param ...
stack_v2_sparse_classes_36k_train_001280
1,385
permissive
[ { "docstring": "Initialize the Mailer class. :param domain: Domain name of the sender :type domain: str :param api_key: API key of the Mailgun API :type api_key: str :param sender_name: name of the person sending the email :type sender_name: str", "name": "__init__", "signature": "def __init__(self, dom...
2
stack_v2_sparse_classes_30k_train_003648
Implement the Python class `Mailer` described below. Class description: Send a mail through the Mailgun API. Method signatures and docstrings: - def __init__(self, domain: str, api_key: str, sender_name: str) -> None: Initialize the Mailer class. :param domain: Domain name of the sender :type domain: str :param api_k...
Implement the Python class `Mailer` described below. Class description: Send a mail through the Mailgun API. Method signatures and docstrings: - def __init__(self, domain: str, api_key: str, sender_name: str) -> None: Initialize the Mailer class. :param domain: Domain name of the sender :type domain: str :param api_k...
cd28d87ae7dbb37b40c549fb2312896603809385
<|skeleton|> class Mailer: """Send a mail through the Mailgun API.""" def __init__(self, domain: str, api_key: str, sender_name: str) -> None: """Initialize the Mailer class. :param domain: Domain name of the sender :type domain: str :param api_key: API key of the Mailgun API :type api_key: str :param ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Mailer: """Send a mail through the Mailgun API.""" def __init__(self, domain: str, api_key: str, sender_name: str) -> None: """Initialize the Mailer class. :param domain: Domain name of the sender :type domain: str :param api_key: API key of the Mailgun API :type api_key: str :param sender_name: ...
the_stack_v2_python_sparse
mailer.py
CCExtractor/sample-platform
train
30
beca3243125d45162bc261a3bc482de847122625
[ "n = len(gas)\nfor i in range(n):\n j = i\n remain = gas[i]\n while remain - cost[j] >= 0:\n remain += gas[(j + 1) % n] - cost[j]\n j = (j + 1) % n\n if i == j:\n return i\nreturn -1", "remain, start, minn = (0, 0, 0)\nn = len(gas)\nfor i in range(n):\n remain += gas[i]...
<|body_start_0|> n = len(gas) for i in range(n): j = i remain = gas[i] while remain - cost[j] >= 0: remain += gas[(j + 1) % n] - cost[j] j = (j + 1) % n if i == j: return i return -1 <|end_bod...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: """直接暴力法 :param gas: :param cost: :return:""" <|body_0|> def canCompleteCircuit2(self, gas: List[int], cost: List[int]) -> int: """超过99解法,目前仍不得其意 :param gas: :param cost: :return:""" ...
stack_v2_sparse_classes_36k_train_001281
1,442
no_license
[ { "docstring": "直接暴力法 :param gas: :param cost: :return:", "name": "canCompleteCircuit", "signature": "def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int" }, { "docstring": "超过99解法,目前仍不得其意 :param gas: :param cost: :return:", "name": "canCompleteCircuit2", "signature": "d...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 直接暴力法 :param gas: :param cost: :return: - def canCompleteCircuit2(self, gas: List[int], cost: List[int]) -> ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 直接暴力法 :param gas: :param cost: :return: - def canCompleteCircuit2(self, gas: List[int], cost: List[int]) -> ...
578cacff5851c5c2522981693c34e3c318002d30
<|skeleton|> class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: """直接暴力法 :param gas: :param cost: :return:""" <|body_0|> def canCompleteCircuit2(self, gas: List[int], cost: List[int]) -> int: """超过99解法,目前仍不得其意 :param gas: :param cost: :return:""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: """直接暴力法 :param gas: :param cost: :return:""" n = len(gas) for i in range(n): j = i remain = gas[i] while remain - cost[j] >= 0: remain += gas[(j + 1) % n...
the_stack_v2_python_sparse
加油站.py
cjrzs/MyLeetCode
train
8
a432bcbd2e46908b3495fec346de2d4f21394bba
[ "lv, rv, s = (0, 0, 0)\ns = motor.getInstance().get_speed()\nif motor.richtingl == 1:\n lv -= motor.getInstance().get_value_left()\nelse:\n lv = motor.getInstance().get_value_left()\nif motor.richtingr == 1:\n rv -= motor.getInstance().get_value_right()\nelse:\n rv = motor.getInstance().get_value_right(...
<|body_start_0|> lv, rv, s = (0, 0, 0) s = motor.getInstance().get_speed() if motor.richtingl == 1: lv -= motor.getInstance().get_value_left() else: lv = motor.getInstance().get_value_left() if motor.richtingr == 1: rv -= motor.getInstance().ge...
Motor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Motor: def get_motor_status() -> json: """get the motor status (speed value and actual speed) @return json object""" <|body_0|> def get(self): """get motor information from `self.get_motor_status()` @return json to sender.""" <|body_1|> def put(self): ...
stack_v2_sparse_classes_36k_train_001282
5,524
no_license
[ { "docstring": "get the motor status (speed value and actual speed) @return json object", "name": "get_motor_status", "signature": "def get_motor_status() -> json" }, { "docstring": "get motor information from `self.get_motor_status()` @return json to sender.", "name": "get", "signature"...
3
stack_v2_sparse_classes_30k_train_014745
Implement the Python class `Motor` described below. Class description: Implement the Motor class. Method signatures and docstrings: - def get_motor_status() -> json: get the motor status (speed value and actual speed) @return json object - def get(self): get motor information from `self.get_motor_status()` @return js...
Implement the Python class `Motor` described below. Class description: Implement the Motor class. Method signatures and docstrings: - def get_motor_status() -> json: get the motor status (speed value and actual speed) @return json object - def get(self): get motor information from `self.get_motor_status()` @return js...
646583889954f52ea44eb0bae73c6e4a05a07846
<|skeleton|> class Motor: def get_motor_status() -> json: """get the motor status (speed value and actual speed) @return json object""" <|body_0|> def get(self): """get motor information from `self.get_motor_status()` @return json to sender.""" <|body_1|> def put(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Motor: def get_motor_status() -> json: """get the motor status (speed value and actual speed) @return json object""" lv, rv, s = (0, 0, 0) s = motor.getInstance().get_speed() if motor.richtingl == 1: lv -= motor.getInstance().get_value_left() else: ...
the_stack_v2_python_sparse
src/processing/api.py
rummens1337/project-row-rover
train
1
df81cec06f5cd393272fe4bc431fcc10527cbde2
[ "@wraps(func)\ndef wrapper(*args, **kwargs) -> None:\n cli_message('<yellow>Heads up! This feature is Experimental. It may change. Please give us your feedback!</yellow>')\n func(*args, **kwargs)\nreturn wrapper", "@wraps(func)\ndef wrapper(*args, **kwargs) -> None:\n cli_message('<yellow>Heads up! This ...
<|body_start_0|> @wraps(func) def wrapper(*args, **kwargs) -> None: cli_message('<yellow>Heads up! This feature is Experimental. It may change. Please give us your feedback!</yellow>') func(*args, **kwargs) return wrapper <|end_body_0|> <|body_start_1|> @wraps(fu...
Marks for feature readiness. Usage: from great_expectations.cli.mark import Mark as mark @mark.blah def your_function()
Mark
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Mark: """Marks for feature readiness. Usage: from great_expectations.cli.mark import Mark as mark @mark.blah def your_function()""" def cli_as_experimental(func: Callable) -> Callable: """Apply as a decorator to CLI commands that are Experimental.""" <|body_0|> def cli_a...
stack_v2_sparse_classes_36k_train_001283
1,663
permissive
[ { "docstring": "Apply as a decorator to CLI commands that are Experimental.", "name": "cli_as_experimental", "signature": "def cli_as_experimental(func: Callable) -> Callable" }, { "docstring": "Apply as a decorator to CLI commands that are beta.", "name": "cli_as_beta", "signature": "de...
3
null
Implement the Python class `Mark` described below. Class description: Marks for feature readiness. Usage: from great_expectations.cli.mark import Mark as mark @mark.blah def your_function() Method signatures and docstrings: - def cli_as_experimental(func: Callable) -> Callable: Apply as a decorator to CLI commands th...
Implement the Python class `Mark` described below. Class description: Marks for feature readiness. Usage: from great_expectations.cli.mark import Mark as mark @mark.blah def your_function() Method signatures and docstrings: - def cli_as_experimental(func: Callable) -> Callable: Apply as a decorator to CLI commands th...
b0290e2fd2aa05aec6d7d8871b91cb4478e9501d
<|skeleton|> class Mark: """Marks for feature readiness. Usage: from great_expectations.cli.mark import Mark as mark @mark.blah def your_function()""" def cli_as_experimental(func: Callable) -> Callable: """Apply as a decorator to CLI commands that are Experimental.""" <|body_0|> def cli_a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Mark: """Marks for feature readiness. Usage: from great_expectations.cli.mark import Mark as mark @mark.blah def your_function()""" def cli_as_experimental(func: Callable) -> Callable: """Apply as a decorator to CLI commands that are Experimental.""" @wraps(func) def wrapper(*args...
the_stack_v2_python_sparse
great_expectations/cli/mark.py
great-expectations/great_expectations
train
8,931
e050353d8607e737e4d72d8b96e2961d1eebb66c
[ "self.Clear(deleteWindows=False)\nself._child = component\nif component is not None:\n child_widget = component.toolkit_widget\n res = super(WXScrollAreaSizer, self).Add(child_widget)\n self.Layout()\n return res", "component = self._child\nif component is not None:\n res = component.min_size()\nel...
<|body_start_0|> self.Clear(deleteWindows=False) self._child = component if component is not None: child_widget = component.toolkit_widget res = super(WXScrollAreaSizer, self).Add(child_widget) self.Layout() return res <|end_body_0|> <|body_start_...
A custom wx Sizer for use in the WXScrollArea. This sizer expands its child to fit the allowable space, regardless of the settings on the child settings. There can only be one component in this sizer at a time and it should be added via the .Add(...) method. Old items will be removed automatically (but not destroyed).
WXScrollAreaSizer
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WXScrollAreaSizer: """A custom wx Sizer for use in the WXScrollArea. This sizer expands its child to fit the allowable space, regardless of the settings on the child settings. There can only be one component in this sizer at a time and it should be added via the .Add(...) method. Old items will b...
stack_v2_sparse_classes_36k_train_001284
8,031
permissive
[ { "docstring": "Adds the given child component to the sizer, removing the old widget if present. The old widget is not destroyed.", "name": "Add", "signature": "def Add(self, component)" }, { "docstring": "Returns the minimum size for the children this sizer is managing. Since the size of the Di...
3
null
Implement the Python class `WXScrollAreaSizer` described below. Class description: A custom wx Sizer for use in the WXScrollArea. This sizer expands its child to fit the allowable space, regardless of the settings on the child settings. There can only be one component in this sizer at a time and it should be added via...
Implement the Python class `WXScrollAreaSizer` described below. Class description: A custom wx Sizer for use in the WXScrollArea. This sizer expands its child to fit the allowable space, regardless of the settings on the child settings. There can only be one component in this sizer at a time and it should be added via...
96828b254ac9fdfa2e5b6b31eff93a4933cbc0aa
<|skeleton|> class WXScrollAreaSizer: """A custom wx Sizer for use in the WXScrollArea. This sizer expands its child to fit the allowable space, regardless of the settings on the child settings. There can only be one component in this sizer at a time and it should be added via the .Add(...) method. Old items will b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WXScrollAreaSizer: """A custom wx Sizer for use in the WXScrollArea. This sizer expands its child to fit the allowable space, regardless of the settings on the child settings. There can only be one component in this sizer at a time and it should be added via the .Add(...) method. Old items will be removed aut...
the_stack_v2_python_sparse
enaml/backends/wx/wx_scroll_area.py
agrawalprash/enaml
train
0
3a45b6f3b41ea2813e9e5f14b295f1caec0ff739
[ "self.name = name\nself.charge = charge\nself.radius = radius", "try:\n item = getattr(self, name)\n return item\nexcept AttributeError:\n message = 'Unable to access object \"%s\" in class ForcefieldAtom' % name\n raise ValueError(message)" ]
<|body_start_0|> self.name = name self.charge = charge self.radius = radius <|end_body_0|> <|body_start_1|> try: item = getattr(self, name) return item except AttributeError: message = 'Unable to access object "%s" in class ForcefieldAtom' % n...
ForcefieldAtom class The ForcefieldAtom object contains fields that are related to the forcefield at the atom level
ForcefieldAtom
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ForcefieldAtom: """ForcefieldAtom class The ForcefieldAtom object contains fields that are related to the forcefield at the atom level""" def __init__(self, name, charge, radius): """Initialize the object Parameters name: The atom name (string) charge: The charge on the atom (float) ...
stack_v2_sparse_classes_36k_train_001285
19,869
permissive
[ { "docstring": "Initialize the object Parameters name: The atom name (string) charge: The charge on the atom (float) radius: The radius of the atom (float)", "name": "__init__", "signature": "def __init__(self, name, charge, radius)" }, { "docstring": "Get a member of the ForcefieldAtom class Pa...
2
stack_v2_sparse_classes_30k_train_020383
Implement the Python class `ForcefieldAtom` described below. Class description: ForcefieldAtom class The ForcefieldAtom object contains fields that are related to the forcefield at the atom level Method signatures and docstrings: - def __init__(self, name, charge, radius): Initialize the object Parameters name: The a...
Implement the Python class `ForcefieldAtom` described below. Class description: ForcefieldAtom class The ForcefieldAtom object contains fields that are related to the forcefield at the atom level Method signatures and docstrings: - def __init__(self, name, charge, radius): Initialize the object Parameters name: The a...
a50f0b2f7104007c730baa51b4ec65c891008c47
<|skeleton|> class ForcefieldAtom: """ForcefieldAtom class The ForcefieldAtom object contains fields that are related to the forcefield at the atom level""" def __init__(self, name, charge, radius): """Initialize the object Parameters name: The atom name (string) charge: The charge on the atom (float) ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ForcefieldAtom: """ForcefieldAtom class The ForcefieldAtom object contains fields that are related to the forcefield at the atom level""" def __init__(self, name, charge, radius): """Initialize the object Parameters name: The atom name (string) charge: The charge on the atom (float) radius: The r...
the_stack_v2_python_sparse
mscreen/autodocktools_prepare_py3k/MolKit/pdb2pqr/forcefield.py
e-mayo/mscreen
train
10
adceb34cc1354771dc7f8f5c8b56b6bc4d5d00ed
[ "prefix_sum = []\nnums = map(lambda x: -1 if x == 0 else x, nums)\ntmp = 0\npair = namedtuple('pair', ('idx', 'sum'))\nfor idx, v in enumerate(nums):\n tmp += v\n prefix_sum.append(pair(idx, tmp))\nprefix_sum.sort(key=lambda x: x.sum)\nans = 0\nfor i, v in enumerate(prefix_sum):\n if v.sum == 0:\n a...
<|body_start_0|> prefix_sum = [] nums = map(lambda x: -1 if x == 0 else x, nums) tmp = 0 pair = namedtuple('pair', ('idx', 'sum')) for idx, v in enumerate(nums): tmp += v prefix_sum.append(pair(idx, tmp)) prefix_sum.sort(key=lambda x: x.sum) ...
@param nums: a binary array @return: the maximum length of a contiguous subarray
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """@param nums: a binary array @return: the maximum length of a contiguous subarray""" def findMaxLength(self, nums): """0 -> -1, 前缀和排序, 如果两者和相等, 说明不是交集的那部分 0和1的数量相等 时间复杂度度, N * logN""" <|body_0|> def findMaxLength2(self, nums): """进一步优化上述代码, 无需排序, 只是为了...
stack_v2_sparse_classes_36k_train_001286
2,714
no_license
[ { "docstring": "0 -> -1, 前缀和排序, 如果两者和相等, 说明不是交集的那部分 0和1的数量相等 时间复杂度度, N * logN", "name": "findMaxLength", "signature": "def findMaxLength(self, nums)" }, { "docstring": "进一步优化上述代码, 无需排序, 只是为了找值相等的前缀和 时间复杂度 O(N)", "name": "findMaxLength2", "signature": "def findMaxLength2(self, nums)" } ...
2
stack_v2_sparse_classes_30k_train_018836
Implement the Python class `Solution` described below. Class description: @param nums: a binary array @return: the maximum length of a contiguous subarray Method signatures and docstrings: - def findMaxLength(self, nums): 0 -> -1, 前缀和排序, 如果两者和相等, 说明不是交集的那部分 0和1的数量相等 时间复杂度度, N * logN - def findMaxLength2(self, nums): ...
Implement the Python class `Solution` described below. Class description: @param nums: a binary array @return: the maximum length of a contiguous subarray Method signatures and docstrings: - def findMaxLength(self, nums): 0 -> -1, 前缀和排序, 如果两者和相等, 说明不是交集的那部分 0和1的数量相等 时间复杂度度, N * logN - def findMaxLength2(self, nums): ...
c34757e66163e3be7b18d23c150c463e39c98442
<|skeleton|> class Solution: """@param nums: a binary array @return: the maximum length of a contiguous subarray""" def findMaxLength(self, nums): """0 -> -1, 前缀和排序, 如果两者和相等, 说明不是交集的那部分 0和1的数量相等 时间复杂度度, N * logN""" <|body_0|> def findMaxLength2(self, nums): """进一步优化上述代码, 无需排序, 只是为了...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """@param nums: a binary array @return: the maximum length of a contiguous subarray""" def findMaxLength(self, nums): """0 -> -1, 前缀和排序, 如果两者和相等, 说明不是交集的那部分 0和1的数量相等 时间复杂度度, N * logN""" prefix_sum = [] nums = map(lambda x: -1 if x == 0 else x, nums) tmp = 0 ...
the_stack_v2_python_sparse
lintcode/contiguous_array.py
liujunsheng0/notes
train
6
f861df83cc6489b1335b98f357947d8a179962b4
[ "if self._t.has_entry(key):\n self._t.add_override_const(key, value)\nelse:\n super().__setattr__(key, value)", "if self._t.has_entry(item):\n self._t.clear_override(item)\nelse:\n super().__delattr__(item)" ]
<|body_start_0|> if self._t.has_entry(key): self._t.add_override_const(key, value) else: super().__setattr__(key, value) <|end_body_0|> <|body_start_1|> if self._t.has_entry(item): self._t.clear_override(item) else: super().__delattr__(ite...
DynObjectMetaClass
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DynObjectMetaClass: def __setattr__(self, key, value): """Set a dynamic value. This is always local - it will not replace the parent attribute""" <|body_0|> def __delitem__(self, item): """Remove an attribute from elements it it exists :param item: :return:""" ...
stack_v2_sparse_classes_36k_train_001287
8,680
permissive
[ { "docstring": "Set a dynamic value. This is always local - it will not replace the parent attribute", "name": "__setattr__", "signature": "def __setattr__(self, key, value)" }, { "docstring": "Remove an attribute from elements it it exists :param item: :return:", "name": "__delitem__", ...
2
stack_v2_sparse_classes_30k_train_000987
Implement the Python class `DynObjectMetaClass` described below. Class description: Implement the DynObjectMetaClass class. Method signatures and docstrings: - def __setattr__(self, key, value): Set a dynamic value. This is always local - it will not replace the parent attribute - def __delitem__(self, item): Remove ...
Implement the Python class `DynObjectMetaClass` described below. Class description: Implement the DynObjectMetaClass class. Method signatures and docstrings: - def __setattr__(self, key, value): Set a dynamic value. This is always local - it will not replace the parent attribute - def __delitem__(self, item): Remove ...
ce0046302e9b60c5647dcd0a87af44583fb29578
<|skeleton|> class DynObjectMetaClass: def __setattr__(self, key, value): """Set a dynamic value. This is always local - it will not replace the parent attribute""" <|body_0|> def __delitem__(self, item): """Remove an attribute from elements it it exists :param item: :return:""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DynObjectMetaClass: def __setattr__(self, key, value): """Set a dynamic value. This is always local - it will not replace the parent attribute""" if self._t.has_entry(key): self._t.add_override_const(key, value) else: super().__setattr__(key, value) def __d...
the_stack_v2_python_sparse
i2fhirb2/sqlsupport/dynobject.py
gkovaig/i2FHIRb2
train
1
e1b2bdfaf429e13961bbd4ab22fd47fbb189e11f
[ "self.bit_tree = [0] * (len(input_array) + 1)\nfor i in range(len(input_array)):\n self.update(i, input_array[i], len(input_array))", "index += 1\nwhile index <= length:\n self.bit_tree[index] = self.bit_tree[index] + value\n index += index & -index", "total_sum = 0\nindex = index + 1\nwhile index > 0:...
<|body_start_0|> self.bit_tree = [0] * (len(input_array) + 1) for i in range(len(input_array)): self.update(i, input_array[i], len(input_array)) <|end_body_0|> <|body_start_1|> index += 1 while index <= length: self.bit_tree[index] = self.bit_tree[index] + value ...
An implementation of Binary Indexed Tree.
BinaryIndexedTree
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinaryIndexedTree: """An implementation of Binary Indexed Tree.""" def __init__(self, input_array): """init BITTree Args: Returns: None Raises: None""" <|body_0|> def update(self, index, value, length): """Update the BitTree The idea is based on the fact that all...
stack_v2_sparse_classes_36k_train_001288
3,020
no_license
[ { "docstring": "init BITTree Args: Returns: None Raises: None", "name": "__init__", "signature": "def __init__(self, input_array)" }, { "docstring": "Update the BitTree The idea is based on the fact that all positive integers can be represented as the sum of powers of 2. For example 19 can be re...
3
null
Implement the Python class `BinaryIndexedTree` described below. Class description: An implementation of Binary Indexed Tree. Method signatures and docstrings: - def __init__(self, input_array): init BITTree Args: Returns: None Raises: None - def update(self, index, value, length): Update the BitTree The idea is based...
Implement the Python class `BinaryIndexedTree` described below. Class description: An implementation of Binary Indexed Tree. Method signatures and docstrings: - def __init__(self, input_array): init BITTree Args: Returns: None Raises: None - def update(self, index, value, length): Update the BitTree The idea is based...
11f4d25cb211740514c119a60962d075a0817abd
<|skeleton|> class BinaryIndexedTree: """An implementation of Binary Indexed Tree.""" def __init__(self, input_array): """init BITTree Args: Returns: None Raises: None""" <|body_0|> def update(self, index, value, length): """Update the BitTree The idea is based on the fact that all...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BinaryIndexedTree: """An implementation of Binary Indexed Tree.""" def __init__(self, input_array): """init BITTree Args: Returns: None Raises: None""" self.bit_tree = [0] * (len(input_array) + 1) for i in range(len(input_array)): self.update(i, input_array[i], len(inp...
the_stack_v2_python_sparse
python/common/binary_indexed_tree.py
santhosh-kumar/AlgorithmsAndDataStructures
train
2
4c800e9797b99902e085e8d2f0bc59be893c3afd
[ "print('deployment task data: %s' % validated_data)\naction = getattr(models.ApplicationDeploymentTask, validated_data.get('action', models.ApplicationDeploymentTask.HEALTH_CHECK))\nrequest = self.context.get('view').request\ndpk = self.context['view'].kwargs.get('deployment_pk')\ndpl = models.ApplicationDeployment...
<|body_start_0|> print('deployment task data: %s' % validated_data) action = getattr(models.ApplicationDeploymentTask, validated_data.get('action', models.ApplicationDeploymentTask.HEALTH_CHECK)) request = self.context.get('view').request dpk = self.context['view'].kwargs.get('deployment...
DeploymentTaskSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeploymentTaskSerializer: def create(self, validated_data): """Fire off a new task for the supplied action. Called automatically by the DRF following a POST request. :type validated_data: ``dict`` :param validated_data: Dict containing action the task should perform. Valid actions are `H...
stack_v2_sparse_classes_36k_train_001289
11,774
no_license
[ { "docstring": "Fire off a new task for the supplied action. Called automatically by the DRF following a POST request. :type validated_data: ``dict`` :param validated_data: Dict containing action the task should perform. Valid actions are `HEALTH_CHECK`, `DELETE`.", "name": "create", "signature": "def c...
2
stack_v2_sparse_classes_30k_train_005030
Implement the Python class `DeploymentTaskSerializer` described below. Class description: Implement the DeploymentTaskSerializer class. Method signatures and docstrings: - def create(self, validated_data): Fire off a new task for the supplied action. Called automatically by the DRF following a POST request. :type val...
Implement the Python class `DeploymentTaskSerializer` described below. Class description: Implement the DeploymentTaskSerializer class. Method signatures and docstrings: - def create(self, validated_data): Fire off a new task for the supplied action. Called automatically by the DRF following a POST request. :type val...
a7fef384bc109fa9474e9b60d2d4a6357b5e2d49
<|skeleton|> class DeploymentTaskSerializer: def create(self, validated_data): """Fire off a new task for the supplied action. Called automatically by the DRF following a POST request. :type validated_data: ``dict`` :param validated_data: Dict containing action the task should perform. Valid actions are `H...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeploymentTaskSerializer: def create(self, validated_data): """Fire off a new task for the supplied action. Called automatically by the DRF following a POST request. :type validated_data: ``dict`` :param validated_data: Dict containing action the task should perform. Valid actions are `HEALTH_CHECK`, ...
the_stack_v2_python_sparse
django-cloudlaunch/baselaunch/serializers.py
thobalose/cloudlaunch
train
1
d64f1531904cd18f62496545a8b0f020a4d220c8
[ "self.sensor = sensor\nself.pump = pump\nself.decider = decider\nself.actions = {'PUMP_IN': pump.PUMP_IN, 'PUMP_OUT': pump.PUMP_OUT, 'PUMP_OFF': pump.PUMP_OFF}", "try:\n self.pump.set_state(self.decider.decide(self.sensor.measure(), self.pump.get_state(), self.actions))\nexcept TypeError:\n return False\nre...
<|body_start_0|> self.sensor = sensor self.pump = pump self.decider = decider self.actions = {'PUMP_IN': pump.PUMP_IN, 'PUMP_OUT': pump.PUMP_OUT, 'PUMP_OFF': pump.PUMP_OFF} <|end_body_0|> <|body_start_1|> try: self.pump.set_state(self.decider.decide(self.sensor.measu...
Encapsulates command and coordination for the water-regulation module
Controller
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Controller: """Encapsulates command and coordination for the water-regulation module""" def __init__(self, sensor, pump, decider): """Create a new controller""" <|body_0|> def tick(self): """On each call to tick, the controller shall: 1. query the sensor for the ...
stack_v2_sparse_classes_36k_train_001290
1,365
no_license
[ { "docstring": "Create a new controller", "name": "__init__", "signature": "def __init__(self, sensor, pump, decider)" }, { "docstring": "On each call to tick, the controller shall: 1. query the sensor for the current height of liquid in the tank 2. query the pump for its current state (pumping ...
2
null
Implement the Python class `Controller` described below. Class description: Encapsulates command and coordination for the water-regulation module Method signatures and docstrings: - def __init__(self, sensor, pump, decider): Create a new controller - def tick(self): On each call to tick, the controller shall: 1. quer...
Implement the Python class `Controller` described below. Class description: Encapsulates command and coordination for the water-regulation module Method signatures and docstrings: - def __init__(self, sensor, pump, decider): Create a new controller - def tick(self): On each call to tick, the controller shall: 1. quer...
b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1
<|skeleton|> class Controller: """Encapsulates command and coordination for the water-regulation module""" def __init__(self, sensor, pump, decider): """Create a new controller""" <|body_0|> def tick(self): """On each call to tick, the controller shall: 1. query the sensor for the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Controller: """Encapsulates command and coordination for the water-regulation module""" def __init__(self, sensor, pump, decider): """Create a new controller""" self.sensor = sensor self.pump = pump self.decider = decider self.actions = {'PUMP_IN': pump.PUMP_IN, 'P...
the_stack_v2_python_sparse
students/MicahBraun/Lesson 6/water-regulation/waterregulation/controller.py
UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018
train
4
a9c72b6f07fdb04975c7ae6169dd5975986f67cf
[ "ProgressTracker.current_product = hd.product_name\nProgressTracker.current_subproduct = hd.subproduct_name\nProgressTracker.current_download = hd.machine_name", "global start_time\nif start_time:\n elapsed = time.time() - start_time\n fasts = ProgressTracker.download_size_current / elapsed\n remaining =...
<|body_start_0|> ProgressTracker.current_product = hd.product_name ProgressTracker.current_subproduct = hd.subproduct_name ProgressTracker.current_download = hd.machine_name <|end_body_0|> <|body_start_1|> global start_time if start_time: elapsed = time.time() - star...
Helps with tracking progress, and determining what to output, when.
ProgressTracker
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProgressTracker: """Helps with tracking progress, and determining what to output, when.""" def assign_download(hd): """Translates a Humble Download object to a tracked download. :param hd: The Humble Download to be tracked.""" <|body_0|> def display_summary(): ""...
stack_v2_sparse_classes_36k_train_001291
5,412
permissive
[ { "docstring": "Translates a Humble Download object to a tracked download. :param hd: The Humble Download to be tracked.", "name": "assign_download", "signature": "def assign_download(hd)" }, { "docstring": "Displays the current tracked download's progress.", "name": "display_summary", "...
6
stack_v2_sparse_classes_30k_train_004721
Implement the Python class `ProgressTracker` described below. Class description: Helps with tracking progress, and determining what to output, when. Method signatures and docstrings: - def assign_download(hd): Translates a Humble Download object to a tracked download. :param hd: The Humble Download to be tracked. - d...
Implement the Python class `ProgressTracker` described below. Class description: Helps with tracking progress, and determining what to output, when. Method signatures and docstrings: - def assign_download(hd): Translates a Humble Download object to a tracked download. :param hd: The Humble Download to be tracked. - d...
3830f5b5c13b40b88e7fd02340d8e7d6b3acbc01
<|skeleton|> class ProgressTracker: """Helps with tracking progress, and determining what to output, when.""" def assign_download(hd): """Translates a Humble Download object to a tracked download. :param hd: The Humble Download to be tracked.""" <|body_0|> def display_summary(): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProgressTracker: """Helps with tracking progress, and determining what to output, when.""" def assign_download(hd): """Translates a Humble Download object to a tracked download. :param hd: The Humble Download to be tracked.""" ProgressTracker.current_product = hd.product_name Prog...
the_stack_v2_python_sparse
hb_downloader/progress_tracker.py
MKindy/hb-downloader
train
7
a20ab60f2fd58d736f90d452537eb5dd08c91dbc
[ "super().__init__()\nself.grid = torch.stack(torch.meshgrid(*map(lambda x: torch.arange(x, dtype=torch.float), heat_map_shape)), -1)[:, :, None].cuda()\nself.soft_min_fn = lambda x: x.pow(alpha).mean(0).mean(0).pow(1 / alpha)\nself.heat_map_shape = torch.FloatTensor([[heat_map_shape]]).cuda()\nself.eps = eps\nself....
<|body_start_0|> super().__init__() self.grid = torch.stack(torch.meshgrid(*map(lambda x: torch.arange(x, dtype=torch.float), heat_map_shape)), -1)[:, :, None].cuda() self.soft_min_fn = lambda x: x.pow(alpha).mean(0).mean(0).pow(1 / alpha) self.heat_map_shape = torch.FloatTensor([[heat_m...
WeightedHausdorffDistance
[ "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WeightedHausdorffDistance: def __init__(self, heat_map_shape, eps=1e-05, alpha=-1, trainer=None): """This is a pytorch implementation of the [Locating Objects Without Bounding Boxes](https://arxiv.org/pdf/1806.07564.pdf) note: this distance metric takes effect when the input heatmap valu...
stack_v2_sparse_classes_36k_train_001292
3,912
permissive
[ { "docstring": "This is a pytorch implementation of the [Locating Objects Without Bounding Boxes](https://arxiv.org/pdf/1806.07564.pdf) note: this distance metric takes effect when the input heatmap values are within [0,1] SINGLE_IMAGE", "name": "__init__", "signature": "def __init__(self, heat_map_shap...
2
stack_v2_sparse_classes_30k_train_004689
Implement the Python class `WeightedHausdorffDistance` described below. Class description: Implement the WeightedHausdorffDistance class. Method signatures and docstrings: - def __init__(self, heat_map_shape, eps=1e-05, alpha=-1, trainer=None): This is a pytorch implementation of the [Locating Objects Without Boundin...
Implement the Python class `WeightedHausdorffDistance` described below. Class description: Implement the WeightedHausdorffDistance class. Method signatures and docstrings: - def __init__(self, heat_map_shape, eps=1e-05, alpha=-1, trainer=None): This is a pytorch implementation of the [Locating Objects Without Boundin...
a87f1e972528081505f89c9ede4d3bdd9aadb2ce
<|skeleton|> class WeightedHausdorffDistance: def __init__(self, heat_map_shape, eps=1e-05, alpha=-1, trainer=None): """This is a pytorch implementation of the [Locating Objects Without Bounding Boxes](https://arxiv.org/pdf/1806.07564.pdf) note: this distance metric takes effect when the input heatmap valu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WeightedHausdorffDistance: def __init__(self, heat_map_shape, eps=1e-05, alpha=-1, trainer=None): """This is a pytorch implementation of the [Locating Objects Without Bounding Boxes](https://arxiv.org/pdf/1806.07564.pdf) note: this distance metric takes effect when the input heatmap values are within ...
the_stack_v2_python_sparse
src/lib/trains/hau_iou.py
whklwhkl/CenterNet
train
0
f7c52c3b5fb896486459d835011df2f69fdf3779
[ "node = Node(value)\nif not self.root:\n self.root = node\nelse:\n current = self.root\n while current:\n if node.value < current.value:\n if current.left:\n current = current.left\n else:\n current.left = node\n break\n elif ...
<|body_start_0|> node = Node(value) if not self.root: self.root = node else: current = self.root while current: if node.value < current.value: if current.left: current = current.left ...
* This class is responible for adding new nodes to te tree following binary search approach keeping the tree always sorted, and the root is always the middle value. * Search the tree for a spesific value
BinarySearchTree
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinarySearchTree: """* This class is responible for adding new nodes to te tree following binary search approach keeping the tree always sorted, and the root is always the middle value. * Search the tree for a spesific value""" def add(self, value): """Adds a new node in the correct ...
stack_v2_sparse_classes_36k_train_001293
5,557
no_license
[ { "docstring": "Adds a new node in the correct location in the binary search tree. Arguments: value -- value of the new node", "name": "add", "signature": "def add(self, value)" }, { "docstring": "Returns a boolean indicating whether or not the value is in the tree at least once. Arguments: node...
2
stack_v2_sparse_classes_30k_train_005155
Implement the Python class `BinarySearchTree` described below. Class description: * This class is responible for adding new nodes to te tree following binary search approach keeping the tree always sorted, and the root is always the middle value. * Search the tree for a spesific value Method signatures and docstrings...
Implement the Python class `BinarySearchTree` described below. Class description: * This class is responible for adding new nodes to te tree following binary search approach keeping the tree always sorted, and the root is always the middle value. * Search the tree for a spesific value Method signatures and docstrings...
d14da6fae81e2a92f8c3961a77624e892bdc8043
<|skeleton|> class BinarySearchTree: """* This class is responible for adding new nodes to te tree following binary search approach keeping the tree always sorted, and the root is always the middle value. * Search the tree for a spesific value""" def add(self, value): """Adds a new node in the correct ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BinarySearchTree: """* This class is responible for adding new nodes to te tree following binary search approach keeping the tree always sorted, and the root is always the middle value. * Search the tree for a spesific value""" def add(self, value): """Adds a new node in the correct location in t...
the_stack_v2_python_sparse
data_structures_and_algorithms/tree/tree_basic.py
DanaAbbadi/data-structures-and-algorithms-python
train
0
197944923f0725487de36ad51cf2be98d440e635
[ "val = self.request.get('x-id', None)\nif val is None:\n success = False\n data = {}\n msg = 'no x id given'\n self.post\nelse:\n val = int(val)\n try:\n x = X.get_by_id(val)\n if not x:\n success = False\n data = {}\n msg = 'not found'\n else:...
<|body_start_0|> val = self.request.get('x-id', None) if val is None: success = False data = {} msg = 'no x id given' self.post else: val = int(val) try: x = X.get_by_id(val) if not x: ...
Handler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Handler: def get(self): """curl "http://localhost:8082/x/handler?x-id=6192449487634432" {"status": "success", "data": {"val": "1234 1234 5678 5678"}, "description": "found"}%""" <|body_0|> def post(self): """curl -k --data "x-no=1234 1234 5678 5678" http://localhost:...
stack_v2_sparse_classes_36k_train_001294
3,283
no_license
[ { "docstring": "curl \"http://localhost:8082/x/handler?x-id=6192449487634432\" {\"status\": \"success\", \"data\": {\"val\": \"1234 1234 5678 5678\"}, \"description\": \"found\"}%", "name": "get", "signature": "def get(self)" }, { "docstring": "curl -k --data \"x-no=1234 1234 5678 5678\" http://...
2
stack_v2_sparse_classes_30k_train_007541
Implement the Python class `Handler` described below. Class description: Implement the Handler class. Method signatures and docstrings: - def get(self): curl "http://localhost:8082/x/handler?x-id=6192449487634432" {"status": "success", "data": {"val": "1234 1234 5678 5678"}, "description": "found"}% - def post(self):...
Implement the Python class `Handler` described below. Class description: Implement the Handler class. Method signatures and docstrings: - def get(self): curl "http://localhost:8082/x/handler?x-id=6192449487634432" {"status": "success", "data": {"val": "1234 1234 5678 5678"}, "description": "found"}% - def post(self):...
3ed82c08e79e553450c55a68099fe2d7f36eb068
<|skeleton|> class Handler: def get(self): """curl "http://localhost:8082/x/handler?x-id=6192449487634432" {"status": "success", "data": {"val": "1234 1234 5678 5678"}, "description": "found"}%""" <|body_0|> def post(self): """curl -k --data "x-no=1234 1234 5678 5678" http://localhost:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Handler: def get(self): """curl "http://localhost:8082/x/handler?x-id=6192449487634432" {"status": "success", "data": {"val": "1234 1234 5678 5678"}, "description": "found"}%""" val = self.request.get('x-id', None) if val is None: success = False data = {} ...
the_stack_v2_python_sparse
x.py
samuelchase/yougee
train
0
d23afe80842f6ed92145de531f1ed1e14d4f19fb
[ "remain = collections.Counter(s)\nstack = list()\nfor c in s:\n if c not in stack:\n while stack and stack[-1] > c and (remain[stack[-1]] > 0):\n stack.pop()\n stack.append(c)\n remain[c] -= 1\nreturn ''.join(stack)", "rindex = {x: i for i, x in enumerate(s)}\nstack = list()\nfor i,...
<|body_start_0|> remain = collections.Counter(s) stack = list() for c in s: if c not in stack: while stack and stack[-1] > c and (remain[stack[-1]] > 0): stack.pop() stack.append(c) remain[c] -= 1 return ''.join(...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def removeDuplicateLetters1(self, s: str) -> str: """类似单调栈: 1.参考题解402. 本题中的letter的移除个数取决于重复的次数 2.遍历字符串,对于每个字符: a.已经在栈中,则无需继续判断,直接丢弃 b.不在栈中,如果栈顶元素字典序更大且后面还会出现,则丢弃栈顶元素 3.每遍历一个字符,其剩余出现次数-1""" <|body_0|> def removeDuplicateLetters2(self, s: str) -> str: """记录每个...
stack_v2_sparse_classes_36k_train_001295
1,879
no_license
[ { "docstring": "类似单调栈: 1.参考题解402. 本题中的letter的移除个数取决于重复的次数 2.遍历字符串,对于每个字符: a.已经在栈中,则无需继续判断,直接丢弃 b.不在栈中,如果栈顶元素字典序更大且后面还会出现,则丢弃栈顶元素 3.每遍历一个字符,其剩余出现次数-1", "name": "removeDuplicateLetters1", "signature": "def removeDuplicateLetters1(self, s: str) -> str" }, { "docstring": "记录每个字符最右的索引,用于是否从栈中弹出", ...
2
stack_v2_sparse_classes_30k_train_008226
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeDuplicateLetters1(self, s: str) -> str: 类似单调栈: 1.参考题解402. 本题中的letter的移除个数取决于重复的次数 2.遍历字符串,对于每个字符: a.已经在栈中,则无需继续判断,直接丢弃 b.不在栈中,如果栈顶元素字典序更大且后面还会出现,则丢弃栈顶元素 3.每遍历一个字符,其剩余出现...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeDuplicateLetters1(self, s: str) -> str: 类似单调栈: 1.参考题解402. 本题中的letter的移除个数取决于重复的次数 2.遍历字符串,对于每个字符: a.已经在栈中,则无需继续判断,直接丢弃 b.不在栈中,如果栈顶元素字典序更大且后面还会出现,则丢弃栈顶元素 3.每遍历一个字符,其剩余出现...
2bbb1640589aab34f2bc42489283033cc11fb885
<|skeleton|> class Solution: def removeDuplicateLetters1(self, s: str) -> str: """类似单调栈: 1.参考题解402. 本题中的letter的移除个数取决于重复的次数 2.遍历字符串,对于每个字符: a.已经在栈中,则无需继续判断,直接丢弃 b.不在栈中,如果栈顶元素字典序更大且后面还会出现,则丢弃栈顶元素 3.每遍历一个字符,其剩余出现次数-1""" <|body_0|> def removeDuplicateLetters2(self, s: str) -> str: """记录每个...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def removeDuplicateLetters1(self, s: str) -> str: """类似单调栈: 1.参考题解402. 本题中的letter的移除个数取决于重复的次数 2.遍历字符串,对于每个字符: a.已经在栈中,则无需继续判断,直接丢弃 b.不在栈中,如果栈顶元素字典序更大且后面还会出现,则丢弃栈顶元素 3.每遍历一个字符,其剩余出现次数-1""" remain = collections.Counter(s) stack = list() for c in s: if c not...
the_stack_v2_python_sparse
316_remove-duplicate-letters.py
helloocc/algorithm
train
1
e1558902249e61200b10a4d59ca1335ab7f78671
[ "array_sum = sum(A)\narray_count = 0\nfor _index, value in enumerate(A):\n array_count += _index * value\nresult_max = result_min = array_count\nfor i in range(len(A) - 1, 0, -1):\n array_count += array_sum - len(A) * A[i]\n result_max = max(array_count, result_max)\n result_min = min(array_count, resul...
<|body_start_0|> array_sum = sum(A) array_count = 0 for _index, value in enumerate(A): array_count += _index * value result_max = result_min = array_count for i in range(len(A) - 1, 0, -1): array_count += array_sum - len(A) * A[i] result_max = ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def max_n_min_rotation(self, A): """:type A: List[int] :rtype: int""" <|body_0|> def max_n_min_rotation(self, A): """:type A: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> array_sum = sum(A) array_count = 0 ...
stack_v2_sparse_classes_36k_train_001296
2,370
no_license
[ { "docstring": ":type A: List[int] :rtype: int", "name": "max_n_min_rotation", "signature": "def max_n_min_rotation(self, A)" }, { "docstring": ":type A: List[int] :rtype: int", "name": "max_n_min_rotation", "signature": "def max_n_min_rotation(self, A)" } ]
2
stack_v2_sparse_classes_30k_train_017835
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def max_n_min_rotation(self, A): :type A: List[int] :rtype: int - def max_n_min_rotation(self, A): :type A: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def max_n_min_rotation(self, A): :type A: List[int] :rtype: int - def max_n_min_rotation(self, A): :type A: List[int] :rtype: int <|skeleton|> class Solution: def max_n_min...
9f660ac27b83e77b147e3688b7042bf3bcd27f26
<|skeleton|> class Solution: def max_n_min_rotation(self, A): """:type A: List[int] :rtype: int""" <|body_0|> def max_n_min_rotation(self, A): """:type A: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def max_n_min_rotation(self, A): """:type A: List[int] :rtype: int""" array_sum = sum(A) array_count = 0 for _index, value in enumerate(A): array_count += _index * value result_max = result_min = array_count for i in range(len(A) - 1, 0, -1...
the_stack_v2_python_sparse
code_test/problem.py
umunusb1/Python_for_interview_preparation
train
0
46f324c5e26717807963c5ebe1bd34e28eacbc0e
[ "feats = Feat.objects.all()\nserializer = FeatListSerializer(feats, many=True)\nreturn Response(serializer.data)", "queryset = Character.objects.all()\ncharacter = get_object_or_404(queryset, pk=character_id)\nfeats = CharacterManager(character).get_feats_by_character()\nserializer = FeatListSerializer(feats, man...
<|body_start_0|> feats = Feat.objects.all() serializer = FeatListSerializer(feats, many=True) return Response(serializer.data) <|end_body_0|> <|body_start_1|> queryset = Character.objects.all() character = get_object_or_404(queryset, pk=character_id) feats = CharacterMan...
FeatView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeatView: def list(self, request): """Получение списка черт""" <|body_0|> def get_feats_by_character(self, request, character_id): """Получение списка черт доступны для выбора персонажем""" <|body_1|> def add_feat_to_character(self, request): """...
stack_v2_sparse_classes_36k_train_001297
12,404
no_license
[ { "docstring": "Получение списка черт", "name": "list", "signature": "def list(self, request)" }, { "docstring": "Получение списка черт доступны для выбора персонажем", "name": "get_feats_by_character", "signature": "def get_feats_by_character(self, request, character_id)" }, { "...
3
stack_v2_sparse_classes_30k_train_006614
Implement the Python class `FeatView` described below. Class description: Implement the FeatView class. Method signatures and docstrings: - def list(self, request): Получение списка черт - def get_feats_by_character(self, request, character_id): Получение списка черт доступны для выбора персонажем - def add_feat_to_c...
Implement the Python class `FeatView` described below. Class description: Implement the FeatView class. Method signatures and docstrings: - def list(self, request): Получение списка черт - def get_feats_by_character(self, request, character_id): Получение списка черт доступны для выбора персонажем - def add_feat_to_c...
be47a0a6f50bf8680b22e0b9cae3e3b34a198a3d
<|skeleton|> class FeatView: def list(self, request): """Получение списка черт""" <|body_0|> def get_feats_by_character(self, request, character_id): """Получение списка черт доступны для выбора персонажем""" <|body_1|> def add_feat_to_character(self, request): """...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FeatView: def list(self, request): """Получение списка черт""" feats = Feat.objects.all() serializer = FeatListSerializer(feats, many=True) return Response(serializer.data) def get_feats_by_character(self, request, character_id): """Получение списка черт доступны д...
the_stack_v2_python_sparse
StarfinderBack/starfinder/views.py
Skirgus/StarfinderMasterAssistant
train
0
0b83a347d22ecd041522f5ec3328c64d084b3776
[ "self.addr = range(Uss.ADDR_BASE, Uss.ADDR_BASE + Uss.NUM)\nself.srf = []\nfor x in self.addr:\n self.srf.append(SRF02(x))\nself.vals = [0] * Uss.NUM", "for srf in self.srf:\n srf.emit()\nsleep(0.055)\n\ndef f(x):\n return x.get()\ntmp = map(f, self.srf)\nself.vals = list(tmp)" ]
<|body_start_0|> self.addr = range(Uss.ADDR_BASE, Uss.ADDR_BASE + Uss.NUM) self.srf = [] for x in self.addr: self.srf.append(SRF02(x)) self.vals = [0] * Uss.NUM <|end_body_0|> <|body_start_1|> for srf in self.srf: srf.emit() sleep(0.055) ...
I2Cを介した超音波センサとの通信タスクです。 値の取得はtaskPollからのポーリングで行われます。 taskMainからはvalsにアクセスされ、taskCommからはget()にアクセスされます。
Uss
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Uss: """I2Cを介した超音波センサとの通信タスクです。 値の取得はtaskPollからのポーリングで行われます。 taskMainからはvalsにアクセスされ、taskCommからはget()にアクセスされます。""" def __init__(self): """コンストラクタです。 I2Cオブジェクトを取得し、超音波センサをオープンします。""" <|body_0|> def get(self): """値を取得します。取得した値はvalsへ格納されます。 :return: None""" <...
stack_v2_sparse_classes_36k_train_001298
2,418
no_license
[ { "docstring": "コンストラクタです。 I2Cオブジェクトを取得し、超音波センサをオープンします。", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "値を取得します。取得した値はvalsへ格納されます。 :return: None", "name": "get", "signature": "def get(self)" } ]
2
stack_v2_sparse_classes_30k_train_001575
Implement the Python class `Uss` described below. Class description: I2Cを介した超音波センサとの通信タスクです。 値の取得はtaskPollからのポーリングで行われます。 taskMainからはvalsにアクセスされ、taskCommからはget()にアクセスされます。 Method signatures and docstrings: - def __init__(self): コンストラクタです。 I2Cオブジェクトを取得し、超音波センサをオープンします。 - def get(self): 値を取得します。取得した値はvalsへ格納されます。 :retu...
Implement the Python class `Uss` described below. Class description: I2Cを介した超音波センサとの通信タスクです。 値の取得はtaskPollからのポーリングで行われます。 taskMainからはvalsにアクセスされ、taskCommからはget()にアクセスされます。 Method signatures and docstrings: - def __init__(self): コンストラクタです。 I2Cオブジェクトを取得し、超音波センサをオープンします。 - def get(self): 値を取得します。取得した値はvalsへ格納されます。 :retu...
e8b6d08916841e68171d558356f49ddbf5581ad5
<|skeleton|> class Uss: """I2Cを介した超音波センサとの通信タスクです。 値の取得はtaskPollからのポーリングで行われます。 taskMainからはvalsにアクセスされ、taskCommからはget()にアクセスされます。""" def __init__(self): """コンストラクタです。 I2Cオブジェクトを取得し、超音波センサをオープンします。""" <|body_0|> def get(self): """値を取得します。取得した値はvalsへ格納されます。 :return: None""" <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Uss: """I2Cを介した超音波センサとの通信タスクです。 値の取得はtaskPollからのポーリングで行われます。 taskMainからはvalsにアクセスされ、taskCommからはget()にアクセスされます。""" def __init__(self): """コンストラクタです。 I2Cオブジェクトを取得し、超音波センサをオープンします。""" self.addr = range(Uss.ADDR_BASE, Uss.ADDR_BASE + Uss.NUM) self.srf = [] for x in self.addr: ...
the_stack_v2_python_sparse
uss.py
fclef978/MIRS1701_Pi
train
0
e4ff882ac432ed2ee43f9e7487b700100fccbea4
[ "super(Chan_Vese, self).__init__(paramlist)\nself.params['algorithm'] = 'Chan_Vese'\nself.params['alpha1'] = 1\nself.params['beta1'] = 1\nself.params['beta2'] = 1\nself.params['max_iter'] = 10\nself.params['alpha2'] = 0.1\nself.params['n_segments'] = 0\nself.paramindexes = ['alpha1', 'alpha2', 'beta1', 'beta2', 'n_...
<|body_start_0|> super(Chan_Vese, self).__init__(paramlist) self.params['algorithm'] = 'Chan_Vese' self.params['alpha1'] = 1 self.params['beta1'] = 1 self.params['beta2'] = 1 self.params['max_iter'] = 10 self.params['alpha2'] = 0.1 self.params['n_segments'...
Peform Chan Vese segmentation algorithm. ONLY GRAYSCALE. Segments objects without clear boundaries. Returns segmentation array of algorithm. Parameters: image -- ndarray grayscale image to be segmented mu -- float, 'edge length' weight parameter. Higher mu vals make a 'round edge' closer to zero will detect smaller obj...
Chan_Vese
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Chan_Vese: """Peform Chan Vese segmentation algorithm. ONLY GRAYSCALE. Segments objects without clear boundaries. Returns segmentation array of algorithm. Parameters: image -- ndarray grayscale image to be segmented mu -- float, 'edge length' weight parameter. Higher mu vals make a 'round edge' c...
stack_v2_sparse_classes_36k_train_001299
29,598
permissive
[ { "docstring": "Get parameters from parameter list that are used in segmentation algorithm. Assign default values to these parameters.", "name": "__init__", "signature": "def __init__(self, paramlist=None)" }, { "docstring": "Evaluate segmentation algorithm on training image. Keyword arguments: ...
2
stack_v2_sparse_classes_30k_train_018645
Implement the Python class `Chan_Vese` described below. Class description: Peform Chan Vese segmentation algorithm. ONLY GRAYSCALE. Segments objects without clear boundaries. Returns segmentation array of algorithm. Parameters: image -- ndarray grayscale image to be segmented mu -- float, 'edge length' weight paramete...
Implement the Python class `Chan_Vese` described below. Class description: Peform Chan Vese segmentation algorithm. ONLY GRAYSCALE. Segments objects without clear boundaries. Returns segmentation array of algorithm. Parameters: image -- ndarray grayscale image to be segmented mu -- float, 'edge length' weight paramete...
9246b8b20510d4c89357a6764ed96b919eb92d5a
<|skeleton|> class Chan_Vese: """Peform Chan Vese segmentation algorithm. ONLY GRAYSCALE. Segments objects without clear boundaries. Returns segmentation array of algorithm. Parameters: image -- ndarray grayscale image to be segmented mu -- float, 'edge length' weight parameter. Higher mu vals make a 'round edge' c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Chan_Vese: """Peform Chan Vese segmentation algorithm. ONLY GRAYSCALE. Segments objects without clear boundaries. Returns segmentation array of algorithm. Parameters: image -- ndarray grayscale image to be segmented mu -- float, 'edge length' weight parameter. Higher mu vals make a 'round edge' closer to zero...
the_stack_v2_python_sparse
see/Segmentors.py
Deepak768/see-segment
train
0