blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
7.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
467
8.64k
id
stringlengths
40
40
length_bytes
int64
515
49.7k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
160
3.93k
prompted_full_text
stringlengths
681
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.09k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
331
8.3k
source
stringclasses
1 value
source_path
stringlengths
5
177
source_repo
stringlengths
6
88
split
stringclasses
1 value
star_events_count
int64
0
209k
66f57efd2fb3b880082dc65d28211ae5996bfdbf
[ "d = devicemanage(self.driver)\nd.open_devicemanage()\nself.assertEqual(d.verify(), True)\nd.delete_obj()\nself.assertEqual(d.result(), '您确定要删除这条信息吗')\nd.confirm()\nself.assertEqual(d.result(), '删除成功')\nfunction.screenshot(self.driver, 'delete_device.jpg')", "d = devicemanage(self.driver)\nd.open_devicemanage()\n...
<|body_start_0|> d = devicemanage(self.driver) d.open_devicemanage() self.assertEqual(d.verify(), True) d.delete_obj() self.assertEqual(d.result(), '您确定要删除这条信息吗') d.confirm() self.assertEqual(d.result(), '删除成功') function.screenshot(self.driver, 'delete_dev...
Test036_Device_Delete_P1
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test036_Device_Delete_P1: def test_delete(self): """删除设备""" <|body_0|> def test_cancle(self): """取消删除""" <|body_1|> <|end_skeleton|> <|body_start_0|> d = devicemanage(self.driver) d.open_devicemanage() self.assertEqual(d.verify(), Tr...
stack_v2_sparse_classes_10k_train_008200
1,077
no_license
[ { "docstring": "删除设备", "name": "test_delete", "signature": "def test_delete(self)" }, { "docstring": "取消删除", "name": "test_cancle", "signature": "def test_cancle(self)" } ]
2
stack_v2_sparse_classes_30k_train_001010
Implement the Python class `Test036_Device_Delete_P1` described below. Class description: Implement the Test036_Device_Delete_P1 class. Method signatures and docstrings: - def test_delete(self): 删除设备 - def test_cancle(self): 取消删除
Implement the Python class `Test036_Device_Delete_P1` described below. Class description: Implement the Test036_Device_Delete_P1 class. Method signatures and docstrings: - def test_delete(self): 删除设备 - def test_cancle(self): 取消删除 <|skeleton|> class Test036_Device_Delete_P1: def test_delete(self): """删除设...
6f42c25249fc642cecc270578a180820988d45b5
<|skeleton|> class Test036_Device_Delete_P1: def test_delete(self): """删除设备""" <|body_0|> def test_cancle(self): """取消删除""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Test036_Device_Delete_P1: def test_delete(self): """删除设备""" d = devicemanage(self.driver) d.open_devicemanage() self.assertEqual(d.verify(), True) d.delete_obj() self.assertEqual(d.result(), '您确定要删除这条信息吗') d.confirm() self.assertEqual(d.result(),...
the_stack_v2_python_sparse
GlxssLive_web/TestCase/Manage_Device/Test036_device_delete_P1.py
rrmiracle/GlxssLive
train
0
91ff456eec8fb1c6dd81c91e33e58bb700157511
[ "FeatureDefinition.__init__(self)\nnbTypes = self._getTypeNumber(kwargs)\nprint('BETTER FEATURES')\nblock_transformer = FeatureUnion([('xywh', Pipeline([('selector', NodeTransformerXYWH_v2()), ('xywh', QuantileTransformer(n_quantiles=self.n_QUANTILES, copy=False))])), ('neighbors', Pipeline([('selector', NodeTransf...
<|body_start_0|> FeatureDefinition.__init__(self) nbTypes = self._getTypeNumber(kwargs) print('BETTER FEATURES') block_transformer = FeatureUnion([('xywh', Pipeline([('selector', NodeTransformerXYWH_v2()), ('xywh', QuantileTransformer(n_quantiles=self.n_QUANTILES, copy=False))])), ('neig...
Multitype version: so the node_transformer actually is a list of node_transformer of length n_class the edge_transformer actually is a list of node_transformer of length n_class^2 We also inherit from FeatureDefinition_T !!!
My_FeatureDefinition_v2
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class My_FeatureDefinition_v2: """Multitype version: so the node_transformer actually is a list of node_transformer of length n_class the edge_transformer actually is a list of node_transformer of length n_class^2 We also inherit from FeatureDefinition_T !!!""" def __init__(self, **kwargs): ...
stack_v2_sparse_classes_10k_train_008201
9,141
permissive
[ { "docstring": "set _node_transformer, _edge_transformer, tdifNodeTextVectorizer", "name": "__init__", "signature": "def __init__(self, **kwargs)" }, { "docstring": "Fit the transformers using the graphs, but TYPE BY TYPE !!! return True", "name": "fitTranformers", "signature": "def fitT...
2
stack_v2_sparse_classes_30k_train_000195
Implement the Python class `My_FeatureDefinition_v2` described below. Class description: Multitype version: so the node_transformer actually is a list of node_transformer of length n_class the edge_transformer actually is a list of node_transformer of length n_class^2 We also inherit from FeatureDefinition_T !!! Meth...
Implement the Python class `My_FeatureDefinition_v2` described below. Class description: Multitype version: so the node_transformer actually is a list of node_transformer of length n_class the edge_transformer actually is a list of node_transformer of length n_class^2 We also inherit from FeatureDefinition_T !!! Meth...
9f2fed81672dc222ca52ee4329eac3126b500d21
<|skeleton|> class My_FeatureDefinition_v2: """Multitype version: so the node_transformer actually is a list of node_transformer of length n_class the edge_transformer actually is a list of node_transformer of length n_class^2 We also inherit from FeatureDefinition_T !!!""" def __init__(self, **kwargs): ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class My_FeatureDefinition_v2: """Multitype version: so the node_transformer actually is a list of node_transformer of length n_class the edge_transformer actually is a list of node_transformer of length n_class^2 We also inherit from FeatureDefinition_T !!!""" def __init__(self, **kwargs): """set _nod...
the_stack_v2_python_sparse
TranskribusDU/tasks/TablePrototypes/DU_ABPTableRG2.py
Transkribus/TranskribusDU
train
24
34b54ca5614d3efaafe4dcd8703581cfa3a061bb
[ "super(Pan, self).__init__(image=Pan.pan_image, x=games.mouse.x, bottom=games.screen.height)\nself.score = games.Text(value=0, size=25, color=color.black, top=5, right=games.screen.width - 10)\ngames.screen.add(self.score)\nself.player_level = games.Text(value=Chef.level, size=25, color=color.black, top=5, right=20...
<|body_start_0|> super(Pan, self).__init__(image=Pan.pan_image, x=games.mouse.x, bottom=games.screen.height) self.score = games.Text(value=0, size=25, color=color.black, top=5, right=games.screen.width - 10) games.screen.add(self.score) self.player_level = games.Text(value=Chef.level, si...
Pan to catch pizza
Pan
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Pan: """Pan to catch pizza""" def __init__(self): """Initialize Pan and create text counter""" <|body_0|> def update(self): """Move object to mouse position""" <|body_1|> def check_catch(self): """Check if pizza is catched""" <|body_2...
stack_v2_sparse_classes_10k_train_008202
4,179
no_license
[ { "docstring": "Initialize Pan and create text counter", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Move object to mouse position", "name": "update", "signature": "def update(self)" }, { "docstring": "Check if pizza is catched", "name": "check_ca...
3
null
Implement the Python class `Pan` described below. Class description: Pan to catch pizza Method signatures and docstrings: - def __init__(self): Initialize Pan and create text counter - def update(self): Move object to mouse position - def check_catch(self): Check if pizza is catched
Implement the Python class `Pan` described below. Class description: Pan to catch pizza Method signatures and docstrings: - def __init__(self): Initialize Pan and create text counter - def update(self): Move object to mouse position - def check_catch(self): Check if pizza is catched <|skeleton|> class Pan: """Pa...
19343c985f368770dc01ce415506506d62a23285
<|skeleton|> class Pan: """Pan to catch pizza""" def __init__(self): """Initialize Pan and create text counter""" <|body_0|> def update(self): """Move object to mouse position""" <|body_1|> def check_catch(self): """Check if pizza is catched""" <|body_2...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Pan: """Pan to catch pizza""" def __init__(self): """Initialize Pan and create text counter""" super(Pan, self).__init__(image=Pan.pan_image, x=games.mouse.x, bottom=games.screen.height) self.score = games.Text(value=0, size=25, color=color.black, top=5, right=games.screen.width -...
the_stack_v2_python_sparse
graphics/pizza_panic.py
gofr1/python-learning
train
0
2b895cf4392273b689ddafc6f26c5ab11f737a5a
[ "super(CustomCrossEntropyLoss, self).__init__()\nself.use_sigmoid = use_sigmoid\nself.use_mask = use_mask\nself.reduction = reduction\nself.loss_weight = loss_weight\nif self.use_sigmoid:\n self.loss_function = binary_cross_entropy\nelif self.use_mask:\n self.loss_function = mask_cross_entropy\nelse:\n sel...
<|body_start_0|> super(CustomCrossEntropyLoss, self).__init__() self.use_sigmoid = use_sigmoid self.use_mask = use_mask self.reduction = reduction self.loss_weight = loss_weight if self.use_sigmoid: self.loss_function = binary_cross_entropy elif self.u...
Cross Entropy Loss.
CustomCrossEntropyLoss
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomCrossEntropyLoss: """Cross Entropy Loss.""" def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', loss_weight=1.0): """Init Cross Entropy loss. :param desc: config dict""" <|body_0|> def forward(self, cls_score, label, weight, avg_factor, reductio...
stack_v2_sparse_classes_10k_train_008203
13,829
permissive
[ { "docstring": "Init Cross Entropy loss. :param desc: config dict", "name": "__init__", "signature": "def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', loss_weight=1.0)" }, { "docstring": "Forward compute.", "name": "forward", "signature": "def forward(self, cls_sco...
2
null
Implement the Python class `CustomCrossEntropyLoss` described below. Class description: Cross Entropy Loss. Method signatures and docstrings: - def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', loss_weight=1.0): Init Cross Entropy loss. :param desc: config dict - def forward(self, cls_score, lab...
Implement the Python class `CustomCrossEntropyLoss` described below. Class description: Cross Entropy Loss. Method signatures and docstrings: - def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', loss_weight=1.0): Init Cross Entropy loss. :param desc: config dict - def forward(self, cls_score, lab...
df51ed9c1d6dbde1deef63f2a037a369f8554406
<|skeleton|> class CustomCrossEntropyLoss: """Cross Entropy Loss.""" def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', loss_weight=1.0): """Init Cross Entropy loss. :param desc: config dict""" <|body_0|> def forward(self, cls_score, label, weight, avg_factor, reductio...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class CustomCrossEntropyLoss: """Cross Entropy Loss.""" def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', loss_weight=1.0): """Init Cross Entropy loss. :param desc: config dict""" super(CustomCrossEntropyLoss, self).__init__() self.use_sigmoid = use_sigmoid ...
the_stack_v2_python_sparse
built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/search_space/networks/pytorch/operator/rpn.py
Huawei-Ascend/modelzoo
train
1
b69807a0d225de85c67cd4bd291d9f6454805238
[ "uri = f'{self.bulk.endpoint}/job/{job_id}/batch'\nresponse = requests.get(uri, headers=self.bulk.headers())\nresponse.raise_for_status()\nreturn self._parse_job_state(response.content)", "tree = lxml_parse_string(xml)\nstatuses = [el.text for el in tree.iterfind('.//{%s}state' % self.bulk.jobNS)]\nstate_messages...
<|body_start_0|> uri = f'{self.bulk.endpoint}/job/{job_id}/batch' response = requests.get(uri, headers=self.bulk.headers()) response.raise_for_status() return self._parse_job_state(response.content) <|end_body_0|> <|body_start_1|> tree = lxml_parse_string(xml) statuses =...
Provides mixin utilities for classes that manage Bulk API jobs.
BulkJobMixin
[ "LicenseRef-scancode-free-unknown" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BulkJobMixin: """Provides mixin utilities for classes that manage Bulk API jobs.""" def _job_state_from_batches(self, job_id): """Query for batches under job_id and return overall status inferred from batch-level status values.""" <|body_0|> def _parse_job_state(self, xm...
stack_v2_sparse_classes_10k_train_008204
22,114
permissive
[ { "docstring": "Query for batches under job_id and return overall status inferred from batch-level status values.", "name": "_job_state_from_batches", "signature": "def _job_state_from_batches(self, job_id)" }, { "docstring": "Parse the Bulk API return value and generate a summary status record ...
3
null
Implement the Python class `BulkJobMixin` described below. Class description: Provides mixin utilities for classes that manage Bulk API jobs. Method signatures and docstrings: - def _job_state_from_batches(self, job_id): Query for batches under job_id and return overall status inferred from batch-level status values....
Implement the Python class `BulkJobMixin` described below. Class description: Provides mixin utilities for classes that manage Bulk API jobs. Method signatures and docstrings: - def _job_state_from_batches(self, job_id): Query for batches under job_id and return overall status inferred from batch-level status values....
9ccf3c9566f78c6e9102ac214db30470cef660c1
<|skeleton|> class BulkJobMixin: """Provides mixin utilities for classes that manage Bulk API jobs.""" def _job_state_from_batches(self, job_id): """Query for batches under job_id and return overall status inferred from batch-level status values.""" <|body_0|> def _parse_job_state(self, xm...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class BulkJobMixin: """Provides mixin utilities for classes that manage Bulk API jobs.""" def _job_state_from_batches(self, job_id): """Query for batches under job_id and return overall status inferred from batch-level status values.""" uri = f'{self.bulk.endpoint}/job/{job_id}/batch' r...
the_stack_v2_python_sparse
cumulusci/tasks/bulkdata/step.py
SFDO-Tooling/CumulusCI
train
226
cb56898ebeae70e1c76faeaf5afa14abf8fccc75
[ "self.full_backup_script = full_backup_script\nself.incremental_backup_script = incremental_backup_script\nself.log_backup_script = log_backup_script\nself.remote_host = remote_host\nself.username = username", "if dictionary is None:\n return None\nfull_backup_script = cohesity_management_sdk.models.remote_scr...
<|body_start_0|> self.full_backup_script = full_backup_script self.incremental_backup_script = incremental_backup_script self.log_backup_script = log_backup_script self.remote_host = remote_host self.username = username <|end_body_0|> <|body_start_1|> if dictionary is No...
Implementation of the 'RemoteJobScript' model. Provides details about the Remote Adapter associated with a 'kPuppeteer' Protection Job. Attributes: full_backup_script (RemoteScriptPathAndParams): Specifies the script that should run for the Full (no CBT) backup schedule of a Remote Adapter 'kPuppeteer' Job. This field ...
RemoteJobScript
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RemoteJobScript: """Implementation of the 'RemoteJobScript' model. Provides details about the Remote Adapter associated with a 'kPuppeteer' Protection Job. Attributes: full_backup_script (RemoteScriptPathAndParams): Specifies the script that should run for the Full (no CBT) backup schedule of a R...
stack_v2_sparse_classes_10k_train_008205
4,552
permissive
[ { "docstring": "Constructor for the RemoteJobScript class", "name": "__init__", "signature": "def __init__(self, full_backup_script=None, incremental_backup_script=None, log_backup_script=None, remote_host=None, username=None)" }, { "docstring": "Creates an instance of this model from a dictiona...
2
null
Implement the Python class `RemoteJobScript` described below. Class description: Implementation of the 'RemoteJobScript' model. Provides details about the Remote Adapter associated with a 'kPuppeteer' Protection Job. Attributes: full_backup_script (RemoteScriptPathAndParams): Specifies the script that should run for t...
Implement the Python class `RemoteJobScript` described below. Class description: Implementation of the 'RemoteJobScript' model. Provides details about the Remote Adapter associated with a 'kPuppeteer' Protection Job. Attributes: full_backup_script (RemoteScriptPathAndParams): Specifies the script that should run for t...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class RemoteJobScript: """Implementation of the 'RemoteJobScript' model. Provides details about the Remote Adapter associated with a 'kPuppeteer' Protection Job. Attributes: full_backup_script (RemoteScriptPathAndParams): Specifies the script that should run for the Full (no CBT) backup schedule of a R...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class RemoteJobScript: """Implementation of the 'RemoteJobScript' model. Provides details about the Remote Adapter associated with a 'kPuppeteer' Protection Job. Attributes: full_backup_script (RemoteScriptPathAndParams): Specifies the script that should run for the Full (no CBT) backup schedule of a Remote Adapter...
the_stack_v2_python_sparse
cohesity_management_sdk/models/remote_job_script.py
cohesity/management-sdk-python
train
24
e075372cc751608e976f3158ff9fc191014742a3
[ "super(TempMediaMixin, self).setup_test_environment()\nsettings._original_media_root = settings.MEDIA_ROOT\nsettings._original_file_storage = settings.DEFAULT_FILE_STORAGE\nself._temp_media = tempfile.mkdtemp()\nsettings.MEDIA_ROOT = self._temp_media\nsettings.DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileS...
<|body_start_0|> super(TempMediaMixin, self).setup_test_environment() settings._original_media_root = settings.MEDIA_ROOT settings._original_file_storage = settings.DEFAULT_FILE_STORAGE self._temp_media = tempfile.mkdtemp() settings.MEDIA_ROOT = self._temp_media settings....
Mixin to create MEDIA_ROOT in temp and tear down when complete.
TempMediaMixin
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TempMediaMixin: """Mixin to create MEDIA_ROOT in temp and tear down when complete.""" def setup_test_environment(self): """Create temp directory and update MEDIA_ROOT and default storage.""" <|body_0|> def teardown_test_environment(self): """Delete temp storage."...
stack_v2_sparse_classes_10k_train_008206
1,207
permissive
[ { "docstring": "Create temp directory and update MEDIA_ROOT and default storage.", "name": "setup_test_environment", "signature": "def setup_test_environment(self)" }, { "docstring": "Delete temp storage.", "name": "teardown_test_environment", "signature": "def teardown_test_environment(...
2
stack_v2_sparse_classes_30k_train_001551
Implement the Python class `TempMediaMixin` described below. Class description: Mixin to create MEDIA_ROOT in temp and tear down when complete. Method signatures and docstrings: - def setup_test_environment(self): Create temp directory and update MEDIA_ROOT and default storage. - def teardown_test_environment(self): ...
Implement the Python class `TempMediaMixin` described below. Class description: Mixin to create MEDIA_ROOT in temp and tear down when complete. Method signatures and docstrings: - def setup_test_environment(self): Create temp directory and update MEDIA_ROOT and default storage. - def teardown_test_environment(self): ...
bb3512caf7c2a6d14f6e0b425d9605b9831fab2d
<|skeleton|> class TempMediaMixin: """Mixin to create MEDIA_ROOT in temp and tear down when complete.""" def setup_test_environment(self): """Create temp directory and update MEDIA_ROOT and default storage.""" <|body_0|> def teardown_test_environment(self): """Delete temp storage."...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TempMediaMixin: """Mixin to create MEDIA_ROOT in temp and tear down when complete.""" def setup_test_environment(self): """Create temp directory and update MEDIA_ROOT and default storage.""" super(TempMediaMixin, self).setup_test_environment() settings._original_media_root = setti...
the_stack_v2_python_sparse
service_info/runner.py
theirc/ServiceInfo
train
2
dfec3e1e50c88a5c261ad10c3a3d86d935d092bf
[ "self.log = logging.getLogger(__name__)\nself.appinfo = {'app': app, 'email': email, 'project': project, 'repo': repo, 'provider': provider}\nself.appname = app\nself.pipeline_config = pipeline_config", "self.appinfo['accounts'] = ['default']\nself.log.debug('Pipeline Config\\n%s', pformat(self.pipeline_config))\...
<|body_start_0|> self.log = logging.getLogger(__name__) self.appinfo = {'app': app, 'email': email, 'project': project, 'repo': repo, 'provider': provider} self.appname = app self.pipeline_config = pipeline_config <|end_body_0|> <|body_start_1|> self.appinfo['accounts'] = ['defa...
Base App.
SpinnakerApp
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpinnakerApp: """Base App.""" def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None): """Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json data. app (str): Application name. email (str): Email asso...
stack_v2_sparse_classes_10k_train_008207
3,461
permissive
[ { "docstring": "Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json data. app (str): Application name. email (str): Email associated with application. project (str): Git namespace or project group repo (str): Repository name", "name": "__init__", "signature": "d...
5
stack_v2_sparse_classes_30k_train_004093
Implement the Python class `SpinnakerApp` described below. Class description: Base App. Method signatures and docstrings: - def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None): Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json d...
Implement the Python class `SpinnakerApp` described below. Class description: Base App. Method signatures and docstrings: - def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None): Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json d...
d88001ea0e33fcd09707b81b5c4ed40e5e21fb59
<|skeleton|> class SpinnakerApp: """Base App.""" def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None): """Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json data. app (str): Application name. email (str): Email asso...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SpinnakerApp: """Base App.""" def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None): """Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json data. app (str): Application name. email (str): Email associated with a...
the_stack_v2_python_sparse
src/foremast/app/spinnaker_app.py
foremast/foremast
train
151
354f16929366eb40ceaf926254be2c26b1b215f8
[ "self.m = height\nself.n = width\nself.food = food + [[-1, -1]]\nself.foodIdx = 0\nself.bodyQueue = deque([(0, 0)])\nself.bodySet = {(0, 0)}", "oldHead = self.bodyQueue[-1]\nnewHead = (oldHead[0] + int(direction == 'D') - int(direction == 'U'), oldHead[1] + int(direction == 'R') - int(direction == 'L'))\nif not (...
<|body_start_0|> self.m = height self.n = width self.food = food + [[-1, -1]] self.foodIdx = 0 self.bodyQueue = deque([(0, 0)]) self.bodySet = {(0, 0)} <|end_body_0|> <|body_start_1|> oldHead = self.bodyQueue[-1] newHead = (oldHead[0] + int(direction == '...
SnakeGame
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SnakeGame: def __init__(self, width, height, food): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ...
stack_v2_sparse_classes_10k_train_008208
3,174
no_license
[ { "docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]]", ...
2
stack_v2_sparse_classes_30k_val_000034
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E...
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class SnakeGame: def __init__(self, width, height, food): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SnakeGame: def __init__(self, width, height, food): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :...
the_stack_v2_python_sparse
D/DesignSnakeGame.py
bssrdf/pyleet
train
2
aa4c911080a2b16c3b1ca2ff1c583e5a7b4a32a6
[ "nums.sort()\nn = len(nums)\nresidual = float('inf')\nfor i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n if nums[i] + nums[j] + nums[k] > target:\n new_residual = abs(nums[i] + nums[j] + nums[k] - target)\n if new_residual < residual:\n residual = ne...
<|body_start_0|> nums.sort() n = len(nums) residual = float('inf') for i in range(n - 2): j = i + 1 k = n - 1 while j < k: if nums[i] + nums[j] + nums[k] > target: new_residual = abs(nums[i] + nums[j] + nums[k] - tar...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def threeSumClosest(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_0|> def threeSumClosest1(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_st...
stack_v2_sparse_classes_10k_train_008209
2,553
no_license
[ { "docstring": ":type nums: List[int] :type target: int :rtype: int", "name": "threeSumClosest", "signature": "def threeSumClosest(self, nums, target)" }, { "docstring": ":type nums: List[int] :type target: int :rtype: int", "name": "threeSumClosest1", "signature": "def threeSumClosest1(...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def threeSumClosest(self, nums, target): :type nums: List[int] :type target: int :rtype: int - def threeSumClosest1(self, nums, target): :type nums: List[int] :type target: int :...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def threeSumClosest(self, nums, target): :type nums: List[int] :type target: int :rtype: int - def threeSumClosest1(self, nums, target): :type nums: List[int] :type target: int :...
c55b0cfd2967a2221c27ed738e8de15034775945
<|skeleton|> class Solution: def threeSumClosest(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_0|> def threeSumClosest1(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def threeSumClosest(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" nums.sort() n = len(nums) residual = float('inf') for i in range(n - 2): j = i + 1 k = n - 1 while j < k: if ...
the_stack_v2_python_sparse
PycharmProjects/leetcode/Find/16最接近的三数之和.py
crystal30/DataStructure
train
0
1a60f9b0a2e952e1e1d45df6f2b80025d74a534b
[ "if 'style' in kwargs:\n style = kwargs['style']\nelse:\n style = wx.FRAME_TOOL_WINDOW | wx.FRAME_FLOAT_ON_PARENT | wx.FRAME_NO_TASKBAR | wx.CLIP_CHILDREN\nif fwidgets.inSSHSession():\n style &= ~wx.FRAME_TOOL_WINDOW\nkwargs['style'] = style\nsuper().__init__(*args, **kwargs)", "super().SetPaneWindow(pan...
<|body_start_0|> if 'style' in kwargs: style = kwargs['style'] else: style = wx.FRAME_TOOL_WINDOW | wx.FRAME_FLOAT_ON_PARENT | wx.FRAME_NO_TASKBAR | wx.CLIP_CHILDREN if fwidgets.inSSHSession(): style &= ~wx.FRAME_TOOL_WINDOW kwargs['style'] = style ...
Here I am monkey patching the ``wx.agw.aui.framemanager.AuiFloatingFrame.__init__`` method. I am doing this because I have observed some strange behaviour when running a remote instance of this application over an SSH/X11 session, with the X11 server (i.e. the local machine) running in OS X. When a combobox is embedded...
MyAuiFloatingFrame
[ "Apache-2.0", "CC-BY-3.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyAuiFloatingFrame: """Here I am monkey patching the ``wx.agw.aui.framemanager.AuiFloatingFrame.__init__`` method. I am doing this because I have observed some strange behaviour when running a remote instance of this application over an SSH/X11 session, with the X11 server (i.e. the local machine...
stack_v2_sparse_classes_10k_train_008210
3,585
permissive
[ { "docstring": "My new constructor, which makes sure that the ``FRAME_TOOL_WINDOW`` style is not passed through to the ``AuiFloatingFrame`` constructor", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Make sure that floated toolbars are sized correctly....
2
stack_v2_sparse_classes_30k_train_000509
Implement the Python class `MyAuiFloatingFrame` described below. Class description: Here I am monkey patching the ``wx.agw.aui.framemanager.AuiFloatingFrame.__init__`` method. I am doing this because I have observed some strange behaviour when running a remote instance of this application over an SSH/X11 session, with...
Implement the Python class `MyAuiFloatingFrame` described below. Class description: Here I am monkey patching the ``wx.agw.aui.framemanager.AuiFloatingFrame.__init__`` method. I am doing this because I have observed some strange behaviour when running a remote instance of this application over an SSH/X11 session, with...
37b45d034d60660b6de3e4bdf5dd6349ed6d853b
<|skeleton|> class MyAuiFloatingFrame: """Here I am monkey patching the ``wx.agw.aui.framemanager.AuiFloatingFrame.__init__`` method. I am doing this because I have observed some strange behaviour when running a remote instance of this application over an SSH/X11 session, with the X11 server (i.e. the local machine...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MyAuiFloatingFrame: """Here I am monkey patching the ``wx.agw.aui.framemanager.AuiFloatingFrame.__init__`` method. I am doing this because I have observed some strange behaviour when running a remote instance of this application over an SSH/X11 session, with the X11 server (i.e. the local machine) running in ...
the_stack_v2_python_sparse
fsleyes/patches/wx_lib_agw_aui_framemanager.py
CGSchwarzMayo/fsleyes
train
0
4ee9e21fd765cb3f5386e032853356eb6d935eb8
[ "super(QNetwork, self).__init__()\nself.state_size = state_size\nself.action_size = action_size\ninput_size = state_size\nself.layers = []\nfor layer_hidden_units in hidden_units:\n layer = nn.Linear(input_size, layer_hidden_units)\n bound = 1 / np.sqrt(input_size)\n with torch.no_grad():\n layer.we...
<|body_start_0|> super(QNetwork, self).__init__() self.state_size = state_size self.action_size = action_size input_size = state_size self.layers = [] for layer_hidden_units in hidden_units: layer = nn.Linear(input_size, layer_hidden_units) bound =...
QNetwork
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QNetwork: def __init__(self, state_size, action_size, hidden_units: List[int]): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed""" <|body_0|> def forward(sel...
stack_v2_sparse_classes_10k_train_008211
9,801
no_license
[ { "docstring": "Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed", "name": "__init__", "signature": "def __init__(self, state_size, action_size, hidden_units: List[int])" }, { "docst...
2
stack_v2_sparse_classes_30k_train_002848
Implement the Python class `QNetwork` described below. Class description: Implement the QNetwork class. Method signatures and docstrings: - def __init__(self, state_size, action_size, hidden_units: List[int]): Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (...
Implement the Python class `QNetwork` described below. Class description: Implement the QNetwork class. Method signatures and docstrings: - def __init__(self, state_size, action_size, hidden_units: List[int]): Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (...
125268908919661a508abc7bddc1015a92116f96
<|skeleton|> class QNetwork: def __init__(self, state_size, action_size, hidden_units: List[int]): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed""" <|body_0|> def forward(sel...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class QNetwork: def __init__(self, state_size, action_size, hidden_units: List[int]): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed""" super(QNetwork, self).__init__() self...
the_stack_v2_python_sparse
LeducPoker/NFSP/Dqn.py
mzktbyjc2016/nfsp-pytorch
train
2
b675b047dea080792425c8c74b72abaf6ba42094
[ "dic = dict()\nm = n = head\nwhile m:\n dic[m] = Node(m.val)\n m = m.next\nwhile n:\n dic[n].next = dic.get(n.next)\n dic[n].random = dic.get(n.random)\n n = n.next\nreturn dic.get(head)", "map_new = collections.defaultdict(lambda: Node(0, None, None))\nmap_new[None] = None\nnd_old = head\nwhile nd...
<|body_start_0|> dic = dict() m = n = head while m: dic[m] = Node(m.val) m = m.next while n: dic[n].next = dic.get(n.next) dic[n].random = dic.get(n.random) n = n.next return dic.get(head) <|end_body_0|> <|body_start_1|...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def copyRandomList(self, head: 'Node') -> 'Node': """O(2n)""" <|body_0|> def copyRandomList(self, head: 'Node') -> 'Node': """dict with old Nodes as keys and new Nodes as values. Doing so allows us to create node's next and random as we iterate through the ...
stack_v2_sparse_classes_10k_train_008212
1,508
no_license
[ { "docstring": "O(2n)", "name": "copyRandomList", "signature": "def copyRandomList(self, head: 'Node') -> 'Node'" }, { "docstring": "dict with old Nodes as keys and new Nodes as values. Doing so allows us to create node's next and random as we iterate through the list from head to tail. Otherwis...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def copyRandomList(self, head: 'Node') -> 'Node': O(2n) - def copyRandomList(self, head: 'Node') -> 'Node': dict with old Nodes as keys and new Nodes as values. Doing so allows u...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def copyRandomList(self, head: 'Node') -> 'Node': O(2n) - def copyRandomList(self, head: 'Node') -> 'Node': dict with old Nodes as keys and new Nodes as values. Doing so allows u...
e50dc0642f087f37ab3234390be3d8a0ed48fe62
<|skeleton|> class Solution: def copyRandomList(self, head: 'Node') -> 'Node': """O(2n)""" <|body_0|> def copyRandomList(self, head: 'Node') -> 'Node': """dict with old Nodes as keys and new Nodes as values. Doing so allows us to create node's next and random as we iterate through the ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def copyRandomList(self, head: 'Node') -> 'Node': """O(2n)""" dic = dict() m = n = head while m: dic[m] = Node(m.val) m = m.next while n: dic[n].next = dic.get(n.next) dic[n].random = dic.get(n.random) ...
the_stack_v2_python_sparse
Leetcode/138. Copy List with Random Pointer.py
brlala/Educative-Grokking-Coding-Exercise
train
3
4f8f8882dff8b6615d3b58435b94f47e839bacc7
[ "if hasattr(cls, '_factory'):\n parameter_configs = []\n for pc in proto.parameters:\n parameter_configs.append(proto_converters.ParameterConfigConverter.from_proto(pc))\n return cls._factory(parameter_configs=parameter_configs)\nresult = cls()\nfor pc in proto.parameters:\n result.add(proto_conv...
<|body_start_0|> if hasattr(cls, '_factory'): parameter_configs = [] for pc in proto.parameters: parameter_configs.append(proto_converters.ParameterConfigConverter.from_proto(pc)) return cls._factory(parameter_configs=parameter_configs) result = cls() ...
A Selector for all, or part of a SearchSpace.
SearchSpace
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SearchSpace: """A Selector for all, or part of a SearchSpace.""" def from_proto(cls, proto: study_pb2.StudySpec) -> 'SearchSpace': """Extracts a SearchSpace object from a StudyConfig proto.""" <|body_0|> def parameter_protos(self) -> List[study_pb2.StudySpec.ParameterSpe...
stack_v2_sparse_classes_10k_train_008213
18,489
permissive
[ { "docstring": "Extracts a SearchSpace object from a StudyConfig proto.", "name": "from_proto", "signature": "def from_proto(cls, proto: study_pb2.StudySpec) -> 'SearchSpace'" }, { "docstring": "Returns the search space as a List of ParameterConfig protos.", "name": "parameter_protos", "...
2
stack_v2_sparse_classes_30k_train_004896
Implement the Python class `SearchSpace` described below. Class description: A Selector for all, or part of a SearchSpace. Method signatures and docstrings: - def from_proto(cls, proto: study_pb2.StudySpec) -> 'SearchSpace': Extracts a SearchSpace object from a StudyConfig proto. - def parameter_protos(self) -> List[...
Implement the Python class `SearchSpace` described below. Class description: A Selector for all, or part of a SearchSpace. Method signatures and docstrings: - def from_proto(cls, proto: study_pb2.StudySpec) -> 'SearchSpace': Extracts a SearchSpace object from a StudyConfig proto. - def parameter_protos(self) -> List[...
76b95b92c1d3b87c72d754d8c02b1bca652b9a27
<|skeleton|> class SearchSpace: """A Selector for all, or part of a SearchSpace.""" def from_proto(cls, proto: study_pb2.StudySpec) -> 'SearchSpace': """Extracts a SearchSpace object from a StudyConfig proto.""" <|body_0|> def parameter_protos(self) -> List[study_pb2.StudySpec.ParameterSpe...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SearchSpace: """A Selector for all, or part of a SearchSpace.""" def from_proto(cls, proto: study_pb2.StudySpec) -> 'SearchSpace': """Extracts a SearchSpace object from a StudyConfig proto.""" if hasattr(cls, '_factory'): parameter_configs = [] for pc in proto.para...
the_stack_v2_python_sparse
google/cloud/aiplatform/vizier/pyvizier/study_config.py
googleapis/python-aiplatform
train
418
3522d507ac363021815a9c9d49e9bb52a0cf409a
[ "l, r = (0, len(height) - 1)\nmax_c = 0\nwhile l != r:\n l_h = height[l]\n r_h = height[r]\n tem = min(l_h, r_h) * (r - l)\n max_c = max(max_c, tem)\n if l_h < r_h:\n l += 1\n else:\n r -= 1\nreturn max_c", "i, j = (0, len(height) - 1)\nv = (j - i) * min(height[i], height[j])\nwhil...
<|body_start_0|> l, r = (0, len(height) - 1) max_c = 0 while l != r: l_h = height[l] r_h = height[r] tem = min(l_h, r_h) * (r - l) max_c = max(max_c, tem) if l_h < r_h: l += 1 else: r -= 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxArea(self, height): """:type height: List[int] :rtype: int""" <|body_0|> def maxArea(self, height): """:type height: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> l, r = (0, len(height) - 1) max_c = 0...
stack_v2_sparse_classes_10k_train_008214
888
no_license
[ { "docstring": ":type height: List[int] :rtype: int", "name": "maxArea", "signature": "def maxArea(self, height)" }, { "docstring": ":type height: List[int] :rtype: int", "name": "maxArea", "signature": "def maxArea(self, height)" } ]
2
stack_v2_sparse_classes_30k_train_000802
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxArea(self, height): :type height: List[int] :rtype: int - def maxArea(self, height): :type height: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxArea(self, height): :type height: List[int] :rtype: int - def maxArea(self, height): :type height: List[int] :rtype: int <|skeleton|> class Solution: def maxArea(sel...
bd8df12c0d4afd048cf1b58b04c27fa1f3622769
<|skeleton|> class Solution: def maxArea(self, height): """:type height: List[int] :rtype: int""" <|body_0|> def maxArea(self, height): """:type height: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def maxArea(self, height): """:type height: List[int] :rtype: int""" l, r = (0, len(height) - 1) max_c = 0 while l != r: l_h = height[l] r_h = height[r] tem = min(l_h, r_h) * (r - l) max_c = max(max_c, tem) i...
the_stack_v2_python_sparse
11_container_with_most_water.py
aojugg/leetcode
train
0
27f9cdad439ebf131b58723dd5264b3a0970a9ef
[ "result = 0.0\nfor i in range(0, old_centroids.shape[0]):\n result += cls.calculate_euclidean_distance(old_centroids[i], new_centroids[i])\nreturn result / old_centroids.shape[0]", "norm = 0.0\nfor i in range(0, first.shape[0]):\n norm += pow(first[i] - second[i], 2)\nreturn sqrt(norm)" ]
<|body_start_0|> result = 0.0 for i in range(0, old_centroids.shape[0]): result += cls.calculate_euclidean_distance(old_centroids[i], new_centroids[i]) return result / old_centroids.shape[0] <|end_body_0|> <|body_start_1|> norm = 0.0 for i in range(0, first.shape[0])...
A service class for all kind of convergence calculations.
ConvergenceCalculationService
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConvergenceCalculationService: """A service class for all kind of convergence calculations.""" def calculate_averaged_euclidean_distance(cls, old_centroids, new_centroids): """Calculates the pairwise distance of the old and new centroid location, sum them up and divide by the amount ...
stack_v2_sparse_classes_10k_train_008215
977
no_license
[ { "docstring": "Calculates the pairwise distance of the old and new centroid location, sum them up and divide by the amount of centroids.", "name": "calculate_averaged_euclidean_distance", "signature": "def calculate_averaged_euclidean_distance(cls, old_centroids, new_centroids)" }, { "docstring...
2
stack_v2_sparse_classes_30k_train_006492
Implement the Python class `ConvergenceCalculationService` described below. Class description: A service class for all kind of convergence calculations. Method signatures and docstrings: - def calculate_averaged_euclidean_distance(cls, old_centroids, new_centroids): Calculates the pairwise distance of the old and new...
Implement the Python class `ConvergenceCalculationService` described below. Class description: A service class for all kind of convergence calculations. Method signatures and docstrings: - def calculate_averaged_euclidean_distance(cls, old_centroids, new_centroids): Calculates the pairwise distance of the old and new...
ee78db14c0d5fc37d9990cf8ad634f5e264c161b
<|skeleton|> class ConvergenceCalculationService: """A service class for all kind of convergence calculations.""" def calculate_averaged_euclidean_distance(cls, old_centroids, new_centroids): """Calculates the pairwise distance of the old and new centroid location, sum them up and divide by the amount ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ConvergenceCalculationService: """A service class for all kind of convergence calculations.""" def calculate_averaged_euclidean_distance(cls, old_centroids, new_centroids): """Calculates the pairwise distance of the old and new centroid location, sum them up and divide by the amount of centroids....
the_stack_v2_python_sparse
qhana_openapi/clustering/convergenceCalculationService.py
IndikaKuma/quantum
train
0
77541a206df1eade4bd31f98a04bacaf070e4b71
[ "super().__init__(coordinator, serial)\nself._attr_unique_id = f'{serial}_{description.key}'\nself.entity_description = description\nself._attr_is_on = False\nself._delay_listener: Callable | None = None", "if not (last_state := (await self.async_get_last_state())):\n return\nself._attr_is_on = last_state.stat...
<|body_start_0|> super().__init__(coordinator, serial) self._attr_unique_id = f'{serial}_{description.key}' self.entity_description = description self._attr_is_on = False self._delay_listener: Callable | None = None <|end_body_0|> <|body_start_1|> if not (last_state := (...
Representation of a EZVIZ Siren entity.
EzvizSirenEntity
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EzvizSirenEntity: """Representation of a EZVIZ Siren entity.""" def __init__(self, coordinator: EzvizDataUpdateCoordinator, serial: str, description: SirenEntityDescription) -> None: """Initialize the Siren.""" <|body_0|> async def async_added_to_hass(self) -> None: ...
stack_v2_sparse_classes_10k_train_008216
4,462
permissive
[ { "docstring": "Initialize the Siren.", "name": "__init__", "signature": "def __init__(self, coordinator: EzvizDataUpdateCoordinator, serial: str, description: SirenEntityDescription) -> None" }, { "docstring": "Run when entity about to be added to hass.", "name": "async_added_to_hass", ...
5
stack_v2_sparse_classes_30k_train_005828
Implement the Python class `EzvizSirenEntity` described below. Class description: Representation of a EZVIZ Siren entity. Method signatures and docstrings: - def __init__(self, coordinator: EzvizDataUpdateCoordinator, serial: str, description: SirenEntityDescription) -> None: Initialize the Siren. - async def async_a...
Implement the Python class `EzvizSirenEntity` described below. Class description: Representation of a EZVIZ Siren entity. Method signatures and docstrings: - def __init__(self, coordinator: EzvizDataUpdateCoordinator, serial: str, description: SirenEntityDescription) -> None: Initialize the Siren. - async def async_a...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class EzvizSirenEntity: """Representation of a EZVIZ Siren entity.""" def __init__(self, coordinator: EzvizDataUpdateCoordinator, serial: str, description: SirenEntityDescription) -> None: """Initialize the Siren.""" <|body_0|> async def async_added_to_hass(self) -> None: ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class EzvizSirenEntity: """Representation of a EZVIZ Siren entity.""" def __init__(self, coordinator: EzvizDataUpdateCoordinator, serial: str, description: SirenEntityDescription) -> None: """Initialize the Siren.""" super().__init__(coordinator, serial) self._attr_unique_id = f'{serial...
the_stack_v2_python_sparse
homeassistant/components/ezviz/siren.py
home-assistant/core
train
35,501
06d6bffe2f90495eabda0f709bfa13d1ab5b3098
[ "if not prices:\n return 0\nn = len(prices)\nif maxK > n // 2:\n return self.maxProfit_inf_k(prices)\ndp = [[[0] * 2 for _ in range(maxK + 1)] for _ in range(n)]\nfor i in range(n):\n for k in range(maxK, 0, -1):\n if i == 0:\n dp[i][k][0], dp[i][k][1] = (0, -prices[i])\n else:\n ...
<|body_start_0|> if not prices: return 0 n = len(prices) if maxK > n // 2: return self.maxProfit_inf_k(prices) dp = [[[0] * 2 for _ in range(maxK + 1)] for _ in range(n)] for i in range(n): for k in range(maxK, 0, -1): if i == 0...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit(self, maxK: int, prices: list) -> int: """动态规划 跟之前分析的一致,不同的是此题k的大小会是任意的数字,要对k这个状态进行穷举 状态方程依旧是: dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1] + prices[i]) dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k-1][0] - prices[i])""" <|body_0|> def maxProfit_inf_k(...
stack_v2_sparse_classes_10k_train_008217
2,396
no_license
[ { "docstring": "动态规划 跟之前分析的一致,不同的是此题k的大小会是任意的数字,要对k这个状态进行穷举 状态方程依旧是: dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1] + prices[i]) dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k-1][0] - prices[i])", "name": "maxProfit", "signature": "def maxProfit(self, maxK: int, prices: list) -> int" }, { "docstring...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, maxK: int, prices: list) -> int: 动态规划 跟之前分析的一致,不同的是此题k的大小会是任意的数字,要对k这个状态进行穷举 状态方程依旧是: dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1] + prices[i]) dp[i][k][1] ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, maxK: int, prices: list) -> int: 动态规划 跟之前分析的一致,不同的是此题k的大小会是任意的数字,要对k这个状态进行穷举 状态方程依旧是: dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1] + prices[i]) dp[i][k][1] ...
3508e1ce089131b19603c3206aab4cf43023bb19
<|skeleton|> class Solution: def maxProfit(self, maxK: int, prices: list) -> int: """动态规划 跟之前分析的一致,不同的是此题k的大小会是任意的数字,要对k这个状态进行穷举 状态方程依旧是: dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1] + prices[i]) dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k-1][0] - prices[i])""" <|body_0|> def maxProfit_inf_k(...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit(self, maxK: int, prices: list) -> int: """动态规划 跟之前分析的一致,不同的是此题k的大小会是任意的数字,要对k这个状态进行穷举 状态方程依旧是: dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1] + prices[i]) dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k-1][0] - prices[i])""" if not prices: return 0 n = le...
the_stack_v2_python_sparse
algorithm/leetcode/dp/11-买卖股票的最佳时机Ⅳ.py
lxconfig/UbuntuCode_bak
train
0
408e74d4c066cd0124e4d9d2affa16ef24a32999
[ "rows, cols = (len(matrix), len(matrix[0]))\nself.prefixSumMatrix = []\nfor i in range(rows):\n l = [matrix[i][0]]\n for j in range(1, cols):\n l.append(l[-1] + matrix[i][j])\n self.prefixSumMatrix.append(l)", "res = 0\nfor i in range(row1, row2 + 1):\n if col1 != 0:\n res += self.prefix...
<|body_start_0|> rows, cols = (len(matrix), len(matrix[0])) self.prefixSumMatrix = [] for i in range(rows): l = [matrix[i][0]] for j in range(1, cols): l.append(l[-1] + matrix[i][j]) self.prefixSumMatrix.append(l) <|end_body_0|> <|body_start_1...
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_10k_train_008218
1,206
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:...
ee59b82125f100970c842d5e1245287c484d6649
<|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_10k
data/stack_v2_sparse_classes_30k
class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" rows, cols = (len(matrix), len(matrix[0])) self.prefixSumMatrix = [] for i in range(rows): l = [matrix[i][0]] for j in range(1, cols): l.append(l[-1] + matrix[i][j...
the_stack_v2_python_sparse
_CodeTopics/LeetCode/201-400/000304/RE--000304.py
BIAOXYZ/variousCodes
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_10k_train_008219
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
null
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_10k
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
30494a7b1a538396380a9897b4209b08a10edfaa
[ "try:\n ScfUser.objects.get(username=data)\n raise ValidationError('User {} name already exist'.format(data))\nexcept ScfUser.DoesNotExist:\n return data", "try:\n ScfUser.objects.get(email=data)\n raise ValidationError('User {} email already exist'.format(data))\nexcept ScfUser.DoesNotExist:\n ...
<|body_start_0|> try: ScfUser.objects.get(username=data) raise ValidationError('User {} name already exist'.format(data)) except ScfUser.DoesNotExist: return data <|end_body_0|> <|body_start_1|> try: ScfUser.objects.get(email=data) rai...
Signup with mandatory fields
SignupSerializer
[ "Apache-2.0", "GPL-3.0-only", "BSD-3-Clause", "AGPL-3.0-only", "GPL-1.0-or-later", "Python-2.0", "BSD-2-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SignupSerializer: """Signup with mandatory fields""" def validate_username(self, data): """check user name is exist or not""" <|body_0|> def validate_email(self, data): """check email is exist or not""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_10k_train_008220
4,134
permissive
[ { "docstring": "check user name is exist or not", "name": "validate_username", "signature": "def validate_username(self, data)" }, { "docstring": "check email is exist or not", "name": "validate_email", "signature": "def validate_email(self, data)" } ]
2
stack_v2_sparse_classes_30k_train_005370
Implement the Python class `SignupSerializer` described below. Class description: Signup with mandatory fields Method signatures and docstrings: - def validate_username(self, data): check user name is exist or not - def validate_email(self, data): check email is exist or not
Implement the Python class `SignupSerializer` described below. Class description: Signup with mandatory fields Method signatures and docstrings: - def validate_username(self, data): check user name is exist or not - def validate_email(self, data): check email is exist or not <|skeleton|> class SignupSerializer: ...
4df3f46e35eb8fcab796be27fc1cc7fa7ed561f3
<|skeleton|> class SignupSerializer: """Signup with mandatory fields""" def validate_username(self, data): """check user name is exist or not""" <|body_0|> def validate_email(self, data): """check email is exist or not""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SignupSerializer: """Signup with mandatory fields""" def validate_username(self, data): """check user name is exist or not""" try: ScfUser.objects.get(username=data) raise ValidationError('User {} name already exist'.format(data)) except ScfUser.DoesNotExis...
the_stack_v2_python_sparse
SCRM/ums/serializers.py
aricent/secure-cloud-native-fabric
train
2
e23c611eef6184227698000f33da0114c9df3191
[ "try:\n\n def generate(vo):\n for subscription in list_subscriptions(name=name, account=account, vo=vo):\n yield (render_json(**subscription) + '\\n')\n return try_stream(generate(vo=request.environ.get('vo')))\nexcept SubscriptionNotFound as error:\n return generate_http_error_flask(404,...
<|body_start_0|> try: def generate(vo): for subscription in list_subscriptions(name=name, account=account, vo=vo): yield (render_json(**subscription) + '\n') return try_stream(generate(vo=request.environ.get('vo'))) except SubscriptionNotFound...
REST APIs for subscriptions.
Subscription
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Subscription: """REST APIs for subscriptions.""" def get(self, account=None, name=None): """--- summary: Get Subscription description: Retrieve a subscription. tags: - Replicas parameters: - name: account in: path description: The account name. schema: type: string style: simple - na...
stack_v2_sparse_classes_10k_train_008221
24,180
permissive
[ { "docstring": "--- summary: Get Subscription description: Retrieve a subscription. tags: - Replicas parameters: - name: account in: path description: The account name. schema: type: string style: simple - name: name in: path description: The subscription name. schema: type: string style: simple responses: 200:...
3
null
Implement the Python class `Subscription` described below. Class description: REST APIs for subscriptions. Method signatures and docstrings: - def get(self, account=None, name=None): --- summary: Get Subscription description: Retrieve a subscription. tags: - Replicas parameters: - name: account in: path description: ...
Implement the Python class `Subscription` described below. Class description: REST APIs for subscriptions. Method signatures and docstrings: - def get(self, account=None, name=None): --- summary: Get Subscription description: Retrieve a subscription. tags: - Replicas parameters: - name: account in: path description: ...
7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b
<|skeleton|> class Subscription: """REST APIs for subscriptions.""" def get(self, account=None, name=None): """--- summary: Get Subscription description: Retrieve a subscription. tags: - Replicas parameters: - name: account in: path description: The account name. schema: type: string style: simple - na...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Subscription: """REST APIs for subscriptions.""" def get(self, account=None, name=None): """--- summary: Get Subscription description: Retrieve a subscription. tags: - Replicas parameters: - name: account in: path description: The account name. schema: type: string style: simple - name: name in: ...
the_stack_v2_python_sparse
lib/rucio/web/rest/flaskapi/v1/subscriptions.py
rucio/rucio
train
232
b63161d220b2066182b0baf591d11e67affa1bae
[ "adj_list = {0: [1, 2], 1: [2], 2: [0], 3: []}\nresult = find_friend_groups(adj_list)\nself.assertEqual(result, 2)", "adj_list = {0: [1, 2], 1: [0, 5], 2: [0], 3: [6], 4: [], 5: [1], 6: [3]}\nresult = find_friend_groups(adj_list)\nself.assertEqual(result, 3)" ]
<|body_start_0|> adj_list = {0: [1, 2], 1: [2], 2: [0], 3: []} result = find_friend_groups(adj_list) self.assertEqual(result, 2) <|end_body_0|> <|body_start_1|> adj_list = {0: [1, 2], 1: [0, 5], 2: [0], 3: [6], 4: [], 5: [1], 6: [3]} result = find_friend_groups(adj_list) ...
TestFindFriendGroups
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestFindFriendGroups: def test_returns_two_groups(self): """Takes in an adjacency list of friends and returns 2""" <|body_0|> def test_returns_three_groups(self): """Takes in an adjacency list of friends and returns 3""" <|body_1|> <|end_skeleton|> <|body_s...
stack_v2_sparse_classes_10k_train_008222
674
permissive
[ { "docstring": "Takes in an adjacency list of friends and returns 2", "name": "test_returns_two_groups", "signature": "def test_returns_two_groups(self)" }, { "docstring": "Takes in an adjacency list of friends and returns 3", "name": "test_returns_three_groups", "signature": "def test_r...
2
stack_v2_sparse_classes_30k_train_000660
Implement the Python class `TestFindFriendGroups` described below. Class description: Implement the TestFindFriendGroups class. Method signatures and docstrings: - def test_returns_two_groups(self): Takes in an adjacency list of friends and returns 2 - def test_returns_three_groups(self): Takes in an adjacency list o...
Implement the Python class `TestFindFriendGroups` described below. Class description: Implement the TestFindFriendGroups class. Method signatures and docstrings: - def test_returns_two_groups(self): Takes in an adjacency list of friends and returns 2 - def test_returns_three_groups(self): Takes in an adjacency list o...
27ffb6b32d6d18d279c51cfa45bf305a409be5c2
<|skeleton|> class TestFindFriendGroups: def test_returns_two_groups(self): """Takes in an adjacency list of friends and returns 2""" <|body_0|> def test_returns_three_groups(self): """Takes in an adjacency list of friends and returns 3""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TestFindFriendGroups: def test_returns_two_groups(self): """Takes in an adjacency list of friends and returns 2""" adj_list = {0: [1, 2], 1: [2], 2: [0], 3: []} result = find_friend_groups(adj_list) self.assertEqual(result, 2) def test_returns_three_groups(self): "...
the_stack_v2_python_sparse
src/daily-coding-problem/easy/find-friend-groups/test_find_friend_group.py
nwthomas/code-challenges
train
2
fa4c7bf4224f2b13e4f02b76348002374384aa90
[ "super().__init__(schema)\nhcs_cust = Customer.objects.filter(schema_name=schema).first()\nself._ebs_acct_num = hcs_cust.account_id\nself._org_id = hcs_cust.org_id", "ctx = {'schema': self.schema, 'provider_type': provider, 'provider_uuid': provider_uuid, 'date': date, 'org_id': self._org_id, 'ebs_account': self....
<|body_start_0|> super().__init__(schema) hcs_cust = Customer.objects.filter(schema_name=schema).first() self._ebs_acct_num = hcs_cust.account_id self._org_id = hcs_cust.org_id <|end_body_0|> <|body_start_1|> ctx = {'schema': self.schema, 'provider_type': provider, 'provider_uui...
Class to interact with customer reporting tables.
HCSReportDBAccessor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HCSReportDBAccessor: """Class to interact with customer reporting tables.""" def __init__(self, schema): """Establish the database connection. :param schema (str): The customer schema to associate with""" <|body_0|> def get_hcs_daily_summary(self, date, provider, provide...
stack_v2_sparse_classes_10k_train_008223
4,327
permissive
[ { "docstring": "Establish the database connection. :param schema (str): The customer schema to associate with", "name": "__init__", "signature": "def __init__(self, schema)" }, { "docstring": "Build HCS daily report. :param date (datetime.date) The date to process :param provider (str) The provi...
2
stack_v2_sparse_classes_30k_train_004984
Implement the Python class `HCSReportDBAccessor` described below. Class description: Class to interact with customer reporting tables. Method signatures and docstrings: - def __init__(self, schema): Establish the database connection. :param schema (str): The customer schema to associate with - def get_hcs_daily_summa...
Implement the Python class `HCSReportDBAccessor` described below. Class description: Class to interact with customer reporting tables. Method signatures and docstrings: - def __init__(self, schema): Establish the database connection. :param schema (str): The customer schema to associate with - def get_hcs_daily_summa...
0416e5216eb1ec4b41c8dd4999adde218b1ab2e1
<|skeleton|> class HCSReportDBAccessor: """Class to interact with customer reporting tables.""" def __init__(self, schema): """Establish the database connection. :param schema (str): The customer schema to associate with""" <|body_0|> def get_hcs_daily_summary(self, date, provider, provide...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class HCSReportDBAccessor: """Class to interact with customer reporting tables.""" def __init__(self, schema): """Establish the database connection. :param schema (str): The customer schema to associate with""" super().__init__(schema) hcs_cust = Customer.objects.filter(schema_name=sche...
the_stack_v2_python_sparse
koku/hcs/database/report_db_accessor.py
project-koku/koku
train
225
98f3498b4190f094fde9bbae1169915961817cfb
[ "if not arg:\n self.push('501 Syntax: HELO hostname')\n return\nself.push('250-PyBitmessage %s' % softwareVersion)\nself.push('250 AUTH PLAIN')", "if not arg or arg[0:5] not in ['PLAIN']:\n self.push('501 Syntax: AUTH PLAIN')\n return\nauthstring = arg[6:]\ntry:\n decoded = base64.b64decode(authstr...
<|body_start_0|> if not arg: self.push('501 Syntax: HELO hostname') return self.push('250-PyBitmessage %s' % softwareVersion) self.push('250 AUTH PLAIN') <|end_body_0|> <|body_start_1|> if not arg or arg[0:5] not in ['PLAIN']: self.push('501 Syntax: A...
Asyncore channel for SMTP protocol (server)
smtpServerChannel
[ "HPND", "MIT", "BSD-2-Clause-Views", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class smtpServerChannel: """Asyncore channel for SMTP protocol (server)""" def smtp_EHLO(self, arg): """Process an EHLO""" <|body_0|> def smtp_AUTH(self, arg): """Process AUTH""" <|body_1|> def smtp_DATA(self, arg): """Process DATA""" <|bod...
stack_v2_sparse_classes_10k_train_008224
7,298
permissive
[ { "docstring": "Process an EHLO", "name": "smtp_EHLO", "signature": "def smtp_EHLO(self, arg)" }, { "docstring": "Process AUTH", "name": "smtp_AUTH", "signature": "def smtp_AUTH(self, arg)" }, { "docstring": "Process DATA", "name": "smtp_DATA", "signature": "def smtp_DATA...
3
stack_v2_sparse_classes_30k_train_002582
Implement the Python class `smtpServerChannel` described below. Class description: Asyncore channel for SMTP protocol (server) Method signatures and docstrings: - def smtp_EHLO(self, arg): Process an EHLO - def smtp_AUTH(self, arg): Process AUTH - def smtp_DATA(self, arg): Process DATA
Implement the Python class `smtpServerChannel` described below. Class description: Asyncore channel for SMTP protocol (server) Method signatures and docstrings: - def smtp_EHLO(self, arg): Process an EHLO - def smtp_AUTH(self, arg): Process AUTH - def smtp_DATA(self, arg): Process DATA <|skeleton|> class smtpServerC...
035fac1fc5e7900146230055627f62a23e7f0686
<|skeleton|> class smtpServerChannel: """Asyncore channel for SMTP protocol (server)""" def smtp_EHLO(self, arg): """Process an EHLO""" <|body_0|> def smtp_AUTH(self, arg): """Process AUTH""" <|body_1|> def smtp_DATA(self, arg): """Process DATA""" <|bod...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class smtpServerChannel: """Asyncore channel for SMTP protocol (server)""" def smtp_EHLO(self, arg): """Process an EHLO""" if not arg: self.push('501 Syntax: HELO hostname') return self.push('250-PyBitmessage %s' % softwareVersion) self.push('250 AUTH PLA...
the_stack_v2_python_sparse
src/class_smtpServer.py
PeterSurda/PyBitmessage
train
2
63cfb61ea82d11af274acd160ae070c6992fb9d6
[ "self._deferred = deferred\nself._buff = []\nself._uid = None\nself._key = createKey()", "if not self._uid:\n if not definition.validateSuffix(line):\n raise ValueError('Received address suffix is not valid.')\n self._uid = line\n self.transport.write('{0}{1}{1}'.format(dumpCertReq(createCertReq(s...
<|body_start_0|> self._deferred = deferred self._buff = [] self._uid = None self._key = createKey() <|end_body_0|> <|body_start_1|> if not self._uid: if not definition.validateSuffix(line): raise ValueError('Received address suffix is not valid.') ...
Protocol which is used by a client to retrieve a new UID and certificate for a machine.
_SSLClientProtocol
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _SSLClientProtocol: """Protocol which is used by a client to retrieve a new UID and certificate for a machine.""" def __init__(self, deferred): """Initialize SSLClientProtocol. @param deferred: Deferred which should be called with the received UID, certificate and private key. @type ...
stack_v2_sparse_classes_10k_train_008225
18,143
permissive
[ { "docstring": "Initialize SSLClientProtocol. @param deferred: Deferred which should be called with the received UID, certificate and private key. @type deferred: Deferred", "name": "__init__", "signature": "def __init__(self, deferred)" }, { "docstring": "Callback which is called by twisted whe...
3
stack_v2_sparse_classes_30k_train_001481
Implement the Python class `_SSLClientProtocol` described below. Class description: Protocol which is used by a client to retrieve a new UID and certificate for a machine. Method signatures and docstrings: - def __init__(self, deferred): Initialize SSLClientProtocol. @param deferred: Deferred which should be called w...
Implement the Python class `_SSLClientProtocol` described below. Class description: Protocol which is used by a client to retrieve a new UID and certificate for a machine. Method signatures and docstrings: - def __init__(self, deferred): Initialize SSLClientProtocol. @param deferred: Deferred which should be called w...
c277efd809fce8f0f18b009fb3b9c7f785cc3739
<|skeleton|> class _SSLClientProtocol: """Protocol which is used by a client to retrieve a new UID and certificate for a machine.""" def __init__(self, deferred): """Initialize SSLClientProtocol. @param deferred: Deferred which should be called with the received UID, certificate and private key. @type ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class _SSLClientProtocol: """Protocol which is used by a client to retrieve a new UID and certificate for a machine.""" def __init__(self, deferred): """Initialize SSLClientProtocol. @param deferred: Deferred which should be called with the received UID, certificate and private key. @type deferred: Def...
the_stack_v2_python_sparse
framework/core/machine.py
LCROBOT/rce
train
0
665d6428c4e4bb264bf7313e961b9e625f5f77e4
[ "self._capacity = float(tokens)\nself._tokens = float(tokens)\nself._fill_rate = float(fill_rate)\nself._timestamp = time.time()", "while block and tokens > self.tokens:\n deficit = tokens - self._tokens\n delay = deficit / self._fill_rate\n time.sleep(delay)\nif tokens <= self.tokens:\n self._tokens ...
<|body_start_0|> self._capacity = float(tokens) self._tokens = float(tokens) self._fill_rate = float(fill_rate) self._timestamp = time.time() <|end_body_0|> <|body_start_1|> while block and tokens > self.tokens: deficit = tokens - self._tokens delay = def...
An implementation of the token bucket algorithm. Usage:: >>> bucket = TokenBucket(80, 0.5) >>> print(bucket.consume(10)) True Not thread safe.
TokenBucket
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TokenBucket: """An implementation of the token bucket algorithm. Usage:: >>> bucket = TokenBucket(80, 0.5) >>> print(bucket.consume(10)) True Not thread safe.""" def __init__(self, tokens, fill_rate): """:param int tokens: the total tokens in the bucket :param float fill_rate: the ra...
stack_v2_sparse_classes_10k_train_008226
2,497
permissive
[ { "docstring": ":param int tokens: the total tokens in the bucket :param float fill_rate: the rate in tokens/second that the bucket will be refilled.", "name": "__init__", "signature": "def __init__(self, tokens, fill_rate)" }, { "docstring": "Consume tokens from the bucket. Returns True if ther...
3
null
Implement the Python class `TokenBucket` described below. Class description: An implementation of the token bucket algorithm. Usage:: >>> bucket = TokenBucket(80, 0.5) >>> print(bucket.consume(10)) True Not thread safe. Method signatures and docstrings: - def __init__(self, tokens, fill_rate): :param int tokens: the ...
Implement the Python class `TokenBucket` described below. Class description: An implementation of the token bucket algorithm. Usage:: >>> bucket = TokenBucket(80, 0.5) >>> print(bucket.consume(10)) True Not thread safe. Method signatures and docstrings: - def __init__(self, tokens, fill_rate): :param int tokens: the ...
a9562268497c1b95cb2a5f38deba1dcde9b08cf7
<|skeleton|> class TokenBucket: """An implementation of the token bucket algorithm. Usage:: >>> bucket = TokenBucket(80, 0.5) >>> print(bucket.consume(10)) True Not thread safe.""" def __init__(self, tokens, fill_rate): """:param int tokens: the total tokens in the bucket :param float fill_rate: the ra...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TokenBucket: """An implementation of the token bucket algorithm. Usage:: >>> bucket = TokenBucket(80, 0.5) >>> print(bucket.consume(10)) True Not thread safe.""" def __init__(self, tokens, fill_rate): """:param int tokens: the total tokens in the bucket :param float fill_rate: the rate in tokens/...
the_stack_v2_python_sparse
spinnman/connections/token_bucket.py
SpiNNakerManchester/SpiNNMan
train
8
9a5dbc727fc9964b0caf645d871ee4f4fb224824
[ "self.module_name = module_name\nself.mail_templates = mail_templates\nsuper(Logic, self).__init__(model=model, base_model=base_model, scope_logic=scope_logic)", "current_status = record.status\nif current_status == 'pre-accepted':\n new_status = 'accepted'\nelif current_status == 'pre-rejected':\n new_stat...
<|body_start_0|> self.module_name = module_name self.mail_templates = mail_templates super(Logic, self).__init__(model=model, base_model=base_model, scope_logic=scope_logic) <|end_body_0|> <|body_start_1|> current_status = record.status if current_status == 'pre-accepted': ...
Logic class for OrgAppRecord.
Logic
[ "Apache-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Logic: """Logic class for OrgAppRecord.""" def __init__(self, model=org_app_model, base_model=SurveyRecord, scope_logic=None, module_name=None, mail_templates=None): """Defines the name, key_name and model for this entity.""" <|body_0|> def processRecord(self, record): ...
stack_v2_sparse_classes_10k_train_008227
2,779
permissive
[ { "docstring": "Defines the name, key_name and model for this entity.", "name": "__init__", "signature": "def __init__(self, model=org_app_model, base_model=SurveyRecord, scope_logic=None, module_name=None, mail_templates=None)" }, { "docstring": "Processes an OrgAppRecord that is in the pre-acc...
3
stack_v2_sparse_classes_30k_train_004341
Implement the Python class `Logic` described below. Class description: Logic class for OrgAppRecord. Method signatures and docstrings: - def __init__(self, model=org_app_model, base_model=SurveyRecord, scope_logic=None, module_name=None, mail_templates=None): Defines the name, key_name and model for this entity. - de...
Implement the Python class `Logic` described below. Class description: Logic class for OrgAppRecord. Method signatures and docstrings: - def __init__(self, model=org_app_model, base_model=SurveyRecord, scope_logic=None, module_name=None, mail_templates=None): Defines the name, key_name and model for this entity. - de...
9bd45c168f8ddb5c0e6c04eacdcaeafd61908be7
<|skeleton|> class Logic: """Logic class for OrgAppRecord.""" def __init__(self, model=org_app_model, base_model=SurveyRecord, scope_logic=None, module_name=None, mail_templates=None): """Defines the name, key_name and model for this entity.""" <|body_0|> def processRecord(self, record): ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Logic: """Logic class for OrgAppRecord.""" def __init__(self, model=org_app_model, base_model=SurveyRecord, scope_logic=None, module_name=None, mail_templates=None): """Defines the name, key_name and model for this entity.""" self.module_name = module_name self.mail_templates = ma...
the_stack_v2_python_sparse
app/soc/logic/models/org_app_record.py
pombredanne/Melange-1
train
0
500cad510c1774e236f51681a70eb769a038f9c1
[ "for subkey in application_identifiers_key.GetSubkeys():\n name = subkey.name.lower()\n if len(name) == 38 and name[0] == '{' and (name[37] == '}'):\n description = self._GetValueFromKey(subkey, '')\n yield ApplicationIdentifier(name, description)", "application_identifiers_key = registry.GetK...
<|body_start_0|> for subkey in application_identifiers_key.GetSubkeys(): name = subkey.name.lower() if len(name) == 38 and name[0] == '{' and (name[37] == '}'): description = self._GetValueFromKey(subkey, '') yield ApplicationIdentifier(name, description) ...
Windows application identifiers collector.
ApplicationIdentifiersCollector
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ApplicationIdentifiersCollector: """Windows application identifiers collector.""" def _CollectApplicationIdentifiers(self, application_identifiers_key): """Collects Windows application identifiers (AppID). Args: application_identifiers_key (dfwinreg.WinRegistryKey): application ident...
stack_v2_sparse_classes_10k_train_008228
1,906
permissive
[ { "docstring": "Collects Windows application identifiers (AppID). Args: application_identifiers_key (dfwinreg.WinRegistryKey): application identifiers Windows Registry key. Yields: ApplicationIdentifier: an application identifier.", "name": "_CollectApplicationIdentifiers", "signature": "def _CollectApp...
2
stack_v2_sparse_classes_30k_val_000217
Implement the Python class `ApplicationIdentifiersCollector` described below. Class description: Windows application identifiers collector. Method signatures and docstrings: - def _CollectApplicationIdentifiers(self, application_identifiers_key): Collects Windows application identifiers (AppID). Args: application_ide...
Implement the Python class `ApplicationIdentifiersCollector` described below. Class description: Windows application identifiers collector. Method signatures and docstrings: - def _CollectApplicationIdentifiers(self, application_identifiers_key): Collects Windows application identifiers (AppID). Args: application_ide...
d149aff1b8ff97e1cc8d7416fc583b964bad4ccd
<|skeleton|> class ApplicationIdentifiersCollector: """Windows application identifiers collector.""" def _CollectApplicationIdentifiers(self, application_identifiers_key): """Collects Windows application identifiers (AppID). Args: application_identifiers_key (dfwinreg.WinRegistryKey): application ident...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ApplicationIdentifiersCollector: """Windows application identifiers collector.""" def _CollectApplicationIdentifiers(self, application_identifiers_key): """Collects Windows application identifiers (AppID). Args: application_identifiers_key (dfwinreg.WinRegistryKey): application identifiers Window...
the_stack_v2_python_sparse
winregrc/application_identifiers.py
libyal/winreg-kb
train
129
fbba8018f1d961854ca82b15ad62cfc3088ff181
[ "getpermsessages = getpermsessage()\nif getpermsessages:\n self.uri = getpermsessages.get('zabbixurl', '')\n self.zabbixuser = getpermsessages.get('zabbixuser', '')\n self.zabbixpassword = encrypt_and_decode().decrypted_text(getpermsessages.get('zabbixpassword', ''))\nif zabbixurl:\n self.uri = zabbixur...
<|body_start_0|> getpermsessages = getpermsessage() if getpermsessages: self.uri = getpermsessages.get('zabbixurl', '') self.zabbixuser = getpermsessages.get('zabbixuser', '') self.zabbixpassword = encrypt_and_decode().decrypted_text(getpermsessages.get('zabbixpasswor...
Zabbix API类
ZabbixApi
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ZabbixApi: """Zabbix API类""" def __init__(self, encode='utf-8', zabbixurl=None, zabbixuser=None, zabbixpassword=None): """构造函数 :param request_id:JSON-RPC请求标识符""" <|body_0|> def call(self, method, params, AUTH=None): """ZabbixAPI请求程序 :param method: Zabbix API方法名称 ...
stack_v2_sparse_classes_10k_train_008229
21,075
no_license
[ { "docstring": "构造函数 :param request_id:JSON-RPC请求标识符", "name": "__init__", "signature": "def __init__(self, encode='utf-8', zabbixurl=None, zabbixuser=None, zabbixpassword=None)" }, { "docstring": "ZabbixAPI请求程序 :param method: Zabbix API方法名称 :param params: Zabbix API方法参数 :param through_authentic...
3
stack_v2_sparse_classes_30k_train_005051
Implement the Python class `ZabbixApi` described below. Class description: Zabbix API类 Method signatures and docstrings: - def __init__(self, encode='utf-8', zabbixurl=None, zabbixuser=None, zabbixpassword=None): 构造函数 :param request_id:JSON-RPC请求标识符 - def call(self, method, params, AUTH=None): ZabbixAPI请求程序 :param me...
Implement the Python class `ZabbixApi` described below. Class description: Zabbix API类 Method signatures and docstrings: - def __init__(self, encode='utf-8', zabbixurl=None, zabbixuser=None, zabbixpassword=None): 构造函数 :param request_id:JSON-RPC请求标识符 - def call(self, method, params, AUTH=None): ZabbixAPI请求程序 :param me...
5552af663ed2c668a16b9c687c2a50ed02595a01
<|skeleton|> class ZabbixApi: """Zabbix API类""" def __init__(self, encode='utf-8', zabbixurl=None, zabbixuser=None, zabbixpassword=None): """构造函数 :param request_id:JSON-RPC请求标识符""" <|body_0|> def call(self, method, params, AUTH=None): """ZabbixAPI请求程序 :param method: Zabbix API方法名称 ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ZabbixApi: """Zabbix API类""" def __init__(self, encode='utf-8', zabbixurl=None, zabbixuser=None, zabbixpassword=None): """构造函数 :param request_id:JSON-RPC请求标识符""" getpermsessages = getpermsessage() if getpermsessages: self.uri = getpermsessages.get('zabbixurl', '') ...
the_stack_v2_python_sparse
ADapi/zapi.py
openitsystem/itops
train
144
cc878044d30b3563836322d6f429d72294c9dd17
[ "settings = current.deployment_settings\nscope = 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile'\nuser_agent = 'google-api-client-python-plus-cmdline/1.0'\nredirect_uri = '%s/%s/default/google/login' % (settings.get_base_public_url(), current.request.application)\nO...
<|body_start_0|> settings = current.deployment_settings scope = 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile' user_agent = 'google-api-client-python-plus-cmdline/1.0' redirect_uri = '%s/%s/default/google/login' % (settings.get_base_publ...
OAuth implementation for Google https://code.google.com/apis/console/
GooglePlusAccount
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GooglePlusAccount: """OAuth implementation for Google https://code.google.com/apis/console/""" def __init__(self, channel): """Constructor @param channel: dict with Google API credentials: {id=clientID, secret=clientSecret}""" <|body_0|> def __build_url_opener(self, uri)...
stack_v2_sparse_classes_10k_train_008230
31,965
permissive
[ { "docstring": "Constructor @param channel: dict with Google API credentials: {id=clientID, secret=clientSecret}", "name": "__init__", "signature": "def __init__(self, channel)" }, { "docstring": "Build the url opener for managing HTTP Basic Authentication", "name": "__build_url_opener", ...
6
null
Implement the Python class `GooglePlusAccount` described below. Class description: OAuth implementation for Google https://code.google.com/apis/console/ Method signatures and docstrings: - def __init__(self, channel): Constructor @param channel: dict with Google API credentials: {id=clientID, secret=clientSecret} - d...
Implement the Python class `GooglePlusAccount` described below. Class description: OAuth implementation for Google https://code.google.com/apis/console/ Method signatures and docstrings: - def __init__(self, channel): Constructor @param channel: dict with Google API credentials: {id=clientID, secret=clientSecret} - d...
7ec4b959d009daf26d5ca6ce91dd9c3c0bd978d6
<|skeleton|> class GooglePlusAccount: """OAuth implementation for Google https://code.google.com/apis/console/""" def __init__(self, channel): """Constructor @param channel: dict with Google API credentials: {id=clientID, secret=clientSecret}""" <|body_0|> def __build_url_opener(self, uri)...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GooglePlusAccount: """OAuth implementation for Google https://code.google.com/apis/console/""" def __init__(self, channel): """Constructor @param channel: dict with Google API credentials: {id=clientID, secret=clientSecret}""" settings = current.deployment_settings scope = 'https:...
the_stack_v2_python_sparse
modules/core/aaa/oauth.py
nursix/drkcm
train
3
ea92aca8b46c3388f67c9d72671ba2e698f2ebcf
[ "super(EditUserForm, self).__init__(*args, **kwargs)\nif self.instance.is_superuser:\n self.fields['is_admin'].initial = True", "user = super(EditUserForm, self).save(commit=False)\nif self.cleaned_data['is_admin']:\n user.is_superuser = True\nif commit:\n user.save()\nreturn user" ]
<|body_start_0|> super(EditUserForm, self).__init__(*args, **kwargs) if self.instance.is_superuser: self.fields['is_admin'].initial = True <|end_body_0|> <|body_start_1|> user = super(EditUserForm, self).save(commit=False) if self.cleaned_data['is_admin']: user.i...
Class for creating a new user
EditUserForm
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EditUserForm: """Class for creating a new user""" def __init__(self, *args, **kwargs): """Override init to customise the UserCreationForm widget class appearance""" <|body_0|> def save(self, commit=True): """Override save to make user a superuser""" <|bod...
stack_v2_sparse_classes_10k_train_008231
30,652
permissive
[ { "docstring": "Override init to customise the UserCreationForm widget class appearance", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Override save to make user a superuser", "name": "save", "signature": "def save(self, commit=True)" } ]
2
stack_v2_sparse_classes_30k_train_003401
Implement the Python class `EditUserForm` described below. Class description: Class for creating a new user Method signatures and docstrings: - def __init__(self, *args, **kwargs): Override init to customise the UserCreationForm widget class appearance - def save(self, commit=True): Override save to make user a super...
Implement the Python class `EditUserForm` described below. Class description: Class for creating a new user Method signatures and docstrings: - def __init__(self, *args, **kwargs): Override init to customise the UserCreationForm widget class appearance - def save(self, commit=True): Override save to make user a super...
fdff8b8ddc202c53edda2a509a50c4e83013474d
<|skeleton|> class EditUserForm: """Class for creating a new user""" def __init__(self, *args, **kwargs): """Override init to customise the UserCreationForm widget class appearance""" <|body_0|> def save(self, commit=True): """Override save to make user a superuser""" <|bod...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class EditUserForm: """Class for creating a new user""" def __init__(self, *args, **kwargs): """Override init to customise the UserCreationForm widget class appearance""" super(EditUserForm, self).__init__(*args, **kwargs) if self.instance.is_superuser: self.fields['is_admin...
the_stack_v2_python_sparse
rse/forms.py
RSE-Sheffield/RSEAdmin
train
22
13ea48fa18ba96b6908198712b90d09339d5f1bf
[ "couple: Couple = Couple.query.filter(Couple.id == couple_id).first()\nif couple:\n return couple.json()\nreturn abort(404)", "couple: Couple = Couple.query.filter(Couple.id == couple_id).first()\nif couple:\n couple.lead_id = api.payload['lead_id']\n couple.follow_id = api.payload['follow_id']\n db.s...
<|body_start_0|> couple: Couple = Couple.query.filter(Couple.id == couple_id).first() if couple: return couple.json() return abort(404) <|end_body_0|> <|body_start_1|> couple: Couple = Couple.query.filter(Couple.id == couple_id).first() if couple: couple....
CoupleSpecific
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CoupleSpecific: def get(self, couple_id): """Get person""" <|body_0|> def put(self, couple_id): """Update couple""" <|body_1|> def delete(self, couple_id): """Delete couple""" <|body_2|> <|end_skeleton|> <|body_start_0|> couple:...
stack_v2_sparse_classes_10k_train_008232
2,281
no_license
[ { "docstring": "Get person", "name": "get", "signature": "def get(self, couple_id)" }, { "docstring": "Update couple", "name": "put", "signature": "def put(self, couple_id)" }, { "docstring": "Delete couple", "name": "delete", "signature": "def delete(self, couple_id)" ...
3
stack_v2_sparse_classes_30k_train_005870
Implement the Python class `CoupleSpecific` described below. Class description: Implement the CoupleSpecific class. Method signatures and docstrings: - def get(self, couple_id): Get person - def put(self, couple_id): Update couple - def delete(self, couple_id): Delete couple
Implement the Python class `CoupleSpecific` described below. Class description: Implement the CoupleSpecific class. Method signatures and docstrings: - def get(self, couple_id): Get person - def put(self, couple_id): Update couple - def delete(self, couple_id): Delete couple <|skeleton|> class CoupleSpecific: d...
22733b2a9638c4c0a58f28e7b7f933586730ecd4
<|skeleton|> class CoupleSpecific: def get(self, couple_id): """Get person""" <|body_0|> def put(self, couple_id): """Update couple""" <|body_1|> def delete(self, couple_id): """Delete couple""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class CoupleSpecific: def get(self, couple_id): """Get person""" couple: Couple = Couple.query.filter(Couple.id == couple_id).first() if couple: return couple.json() return abort(404) def put(self, couple_id): """Update couple""" couple: Couple = Coup...
the_stack_v2_python_sparse
apis/couple/apis.py
AlenAlic/4hf-corona-api
train
0
d71dc2f1a3351639ea8c3e0b6aa5060781363e2d
[ "parser = MagicCommandParser(description='changes matplotlib style', prog='mpl_style')\nparser.add_argument('style', type=str, help='style, ggplot for exemple', default='ggplot')\nreturn parser", "parser = self.get_parser(MagicGraph.mpl_style_parser, 'mpl_style')\nargs = self.get_args(line, parser)\nif args is no...
<|body_start_0|> parser = MagicCommandParser(description='changes matplotlib style', prog='mpl_style') parser.add_argument('style', type=str, help='style, ggplot for exemple', default='ggplot') return parser <|end_body_0|> <|body_start_1|> parser = self.get_parser(MagicGraph.mpl_style_p...
Defines magic commands about graphs .. versionadded:: 1.1
MagicGraph
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MagicGraph: """Defines magic commands about graphs .. versionadded:: 1.1""" def mpl_style_parser(): """defines the way to parse the magic command ``%mpl_style``""" <|body_0|> def mpl_style(self, line): """defines ``%mpl_style`` which changes the style of matplotl...
stack_v2_sparse_classes_10k_train_008233
1,955
permissive
[ { "docstring": "defines the way to parse the magic command ``%mpl_style``", "name": "mpl_style_parser", "signature": "def mpl_style_parser()" }, { "docstring": "defines ``%mpl_style`` which changes the style of matplotlib graphs, example: ``%mpl_style ggplot`` .. nbref:: :title: mpl_style This m...
2
stack_v2_sparse_classes_30k_train_001978
Implement the Python class `MagicGraph` described below. Class description: Defines magic commands about graphs .. versionadded:: 1.1 Method signatures and docstrings: - def mpl_style_parser(): defines the way to parse the magic command ``%mpl_style`` - def mpl_style(self, line): defines ``%mpl_style`` which changes ...
Implement the Python class `MagicGraph` described below. Class description: Defines magic commands about graphs .. versionadded:: 1.1 Method signatures and docstrings: - def mpl_style_parser(): defines the way to parse the magic command ``%mpl_style`` - def mpl_style(self, line): defines ``%mpl_style`` which changes ...
33af98adb093f525df7fac7c86613fa7cd181b44
<|skeleton|> class MagicGraph: """Defines magic commands about graphs .. versionadded:: 1.1""" def mpl_style_parser(): """defines the way to parse the magic command ``%mpl_style``""" <|body_0|> def mpl_style(self, line): """defines ``%mpl_style`` which changes the style of matplotl...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MagicGraph: """Defines magic commands about graphs .. versionadded:: 1.1""" def mpl_style_parser(): """defines the way to parse the magic command ``%mpl_style``""" parser = MagicCommandParser(description='changes matplotlib style', prog='mpl_style') parser.add_argument('style', ty...
the_stack_v2_python_sparse
src/pyensae/graphhelper/magic_graph.py
sdpython/pyensae
train
33
94bbc1267cb51ddbed5c530d554d05ac03de21cd
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Missing associated documentation comment in .proto file.
OuAppServiceServicer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OuAppServiceServicer: """Missing associated documentation comment in .proto file.""" def ou_by_name(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def ou_by_id(self, request, context): """Missing associated docu...
stack_v2_sparse_classes_10k_train_008234
7,781
no_license
[ { "docstring": "Missing associated documentation comment in .proto file.", "name": "ou_by_name", "signature": "def ou_by_name(self, request, context)" }, { "docstring": "Missing associated documentation comment in .proto file.", "name": "ou_by_id", "signature": "def ou_by_id(self, reques...
4
stack_v2_sparse_classes_30k_train_006660
Implement the Python class `OuAppServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def ou_by_name(self, request, context): Missing associated documentation comment in .proto file. - def ou_by_id(self, request, context): Mi...
Implement the Python class `OuAppServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def ou_by_name(self, request, context): Missing associated documentation comment in .proto file. - def ou_by_id(self, request, context): Mi...
55d36c068e26e13ee5bae5c033e2e17784c63feb
<|skeleton|> class OuAppServiceServicer: """Missing associated documentation comment in .proto file.""" def ou_by_name(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def ou_by_id(self, request, context): """Missing associated docu...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class OuAppServiceServicer: """Missing associated documentation comment in .proto file.""" def ou_by_name(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!'...
the_stack_v2_python_sparse
src/resource/proto/_generated/identity/ou_app_service_pb2_grpc.py
arkanmgerges/cafm.identity
train
0
631de2942d6f0b78ea75799a7cdf87ae27958f39
[ "super().__init__()\nif not isinstance(volumes, Volumes):\n raise ValueError(\"'volumes' have to be an instance of the 'Volumes' class.\")\nself._volumes = volumes\nself._sample_mode = sample_mode", "world2local = self._volumes.get_world_to_local_coords_transform().get_matrix()\ndirections_transform_matrix = e...
<|body_start_0|> super().__init__() if not isinstance(volumes, Volumes): raise ValueError("'volumes' have to be an instance of the 'Volumes' class.") self._volumes = volumes self._sample_mode = sample_mode <|end_body_0|> <|body_start_1|> world2local = self._volumes.g...
A module to sample a batch of volumes `Volumes` at 3D points sampled along projection rays.
VolumeSampler
[ "MIT", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VolumeSampler: """A module to sample a batch of volumes `Volumes` at 3D points sampled along projection rays.""" def __init__(self, volumes: Volumes, sample_mode: str='bilinear') -> None: """Args: volumes: An instance of the `Volumes` class representing a batch of volumes that are be...
stack_v2_sparse_classes_10k_train_008235
17,111
permissive
[ { "docstring": "Args: volumes: An instance of the `Volumes` class representing a batch of volumes that are being rendered. sample_mode: Defines the algorithm used to sample the volumetric voxel grid. Can be either \"bilinear\" or \"nearest\".", "name": "__init__", "signature": "def __init__(self, volume...
3
stack_v2_sparse_classes_30k_train_005145
Implement the Python class `VolumeSampler` described below. Class description: A module to sample a batch of volumes `Volumes` at 3D points sampled along projection rays. Method signatures and docstrings: - def __init__(self, volumes: Volumes, sample_mode: str='bilinear') -> None: Args: volumes: An instance of the `V...
Implement the Python class `VolumeSampler` described below. Class description: A module to sample a batch of volumes `Volumes` at 3D points sampled along projection rays. Method signatures and docstrings: - def __init__(self, volumes: Volumes, sample_mode: str='bilinear') -> None: Args: volumes: An instance of the `V...
a3d99cab6bf5eb69be8d5eb48895da6edd859565
<|skeleton|> class VolumeSampler: """A module to sample a batch of volumes `Volumes` at 3D points sampled along projection rays.""" def __init__(self, volumes: Volumes, sample_mode: str='bilinear') -> None: """Args: volumes: An instance of the `Volumes` class representing a batch of volumes that are be...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class VolumeSampler: """A module to sample a batch of volumes `Volumes` at 3D points sampled along projection rays.""" def __init__(self, volumes: Volumes, sample_mode: str='bilinear') -> None: """Args: volumes: An instance of the `Volumes` class representing a batch of volumes that are being rendered....
the_stack_v2_python_sparse
pytorch3d/renderer/implicit/renderer.py
facebookresearch/pytorch3d
train
7,964
5b82728ecdb8af261742df9cdf47c4237b1d2a6e
[ "assert resource and containerOsh\nosh = self._getBuilder().buildResource(resource)\nosh.setContainer(containerOsh)\nreturn osh", "assert pdo and containerOsh\nosh = self._getBuilder().buildResourcePdo(pdo)\nosh.setContainer(containerOsh)\nreturn osh" ]
<|body_start_0|> assert resource and containerOsh osh = self._getBuilder().buildResource(resource) osh.setContainer(containerOsh) return osh <|end_body_0|> <|body_start_1|> assert pdo and containerOsh osh = self._getBuilder().buildResourcePdo(pdo) osh.setContaine...
ResourceReporter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResourceReporter: def reportResource(self, resource, containerOsh): """@types: Resource, ObjectStateHolder -> ObjectStateHolder""" <|body_0|> def reportResourcePdo(self, pdo, containerOsh): """@types: ResourceBuilder.Pdo, ObjectStateHolder -> ObjectStateHolder""" ...
stack_v2_sparse_classes_10k_train_008236
15,554
no_license
[ { "docstring": "@types: Resource, ObjectStateHolder -> ObjectStateHolder", "name": "reportResource", "signature": "def reportResource(self, resource, containerOsh)" }, { "docstring": "@types: ResourceBuilder.Pdo, ObjectStateHolder -> ObjectStateHolder", "name": "reportResourcePdo", "sign...
2
null
Implement the Python class `ResourceReporter` described below. Class description: Implement the ResourceReporter class. Method signatures and docstrings: - def reportResource(self, resource, containerOsh): @types: Resource, ObjectStateHolder -> ObjectStateHolder - def reportResourcePdo(self, pdo, containerOsh): @type...
Implement the Python class `ResourceReporter` described below. Class description: Implement the ResourceReporter class. Method signatures and docstrings: - def reportResource(self, resource, containerOsh): @types: Resource, ObjectStateHolder -> ObjectStateHolder - def reportResourcePdo(self, pdo, containerOsh): @type...
c431e809e8d0f82e1bca7e3429dd0245560b5680
<|skeleton|> class ResourceReporter: def reportResource(self, resource, containerOsh): """@types: Resource, ObjectStateHolder -> ObjectStateHolder""" <|body_0|> def reportResourcePdo(self, pdo, containerOsh): """@types: ResourceBuilder.Pdo, ObjectStateHolder -> ObjectStateHolder""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ResourceReporter: def reportResource(self, resource, containerOsh): """@types: Resource, ObjectStateHolder -> ObjectStateHolder""" assert resource and containerOsh osh = self._getBuilder().buildResource(resource) osh.setContainer(containerOsh) return osh def report...
the_stack_v2_python_sparse
reference/ucmdb/discovery/ms_cluster.py
madmonkyang/cda-record
train
0
89f507bc0e205ae3fc33ab4b8d80c3be9424c360
[ "super(MidasNet_StackedHourGlass, self).__init__()\nuse_pretrained = False if path else True\nself.pretrained, self.scratch = _make_encoder(backbone, features, use_pretrained)\nself.scratch.refinenet4 = ProgressiveUpsample(features, features // 2, 32)\nself.scratch.refinenet3 = ProgressiveUpsample(features + featur...
<|body_start_0|> super(MidasNet_StackedHourGlass, self).__init__() use_pretrained = False if path else True self.pretrained, self.scratch = _make_encoder(backbone, features, use_pretrained) self.scratch.refinenet4 = ProgressiveUpsample(features, features // 2, 32) self.scratch.re...
Network for monocular depth estimation.
MidasNet_StackedHourGlass
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MidasNet_StackedHourGlass: """Network for monocular depth estimation.""" def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True): """Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defa...
stack_v2_sparse_classes_10k_train_008237
13,019
permissive
[ { "docstring": "Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone network for encoder. Defaults to resnet50", "name": "__init__", "signature": "def __init__(self, path=None, features=...
2
null
Implement the Python class `MidasNet_StackedHourGlass` described below. Class description: Network for monocular depth estimation. Method signatures and docstrings: - def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True): Init. Args: path (str, optional): Path to saved model. Defaults to...
Implement the Python class `MidasNet_StackedHourGlass` described below. Class description: Network for monocular depth estimation. Method signatures and docstrings: - def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True): Init. Args: path (str, optional): Path to saved model. Defaults to...
a00c3619bf4042e446e1919087f0b09fe9fa3a65
<|skeleton|> class MidasNet_StackedHourGlass: """Network for monocular depth estimation.""" def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True): """Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defa...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MidasNet_StackedHourGlass: """Network for monocular depth estimation.""" def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True): """Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. ...
the_stack_v2_python_sparse
nasws/cnn/search_space/monodepth/models/midas_net.py
kcyu2014/nas-landmarkreg
train
10
1db502042c35527194bcbcd7cb402454fdf77eaf
[ "self.savepath = savepath\nself.fig = fig\nself.ax = ax\nself.loss = loss", "self.ax.plot(train)\nself.ax.plot(validation)\nself.ax.set_xlabel('epochs')\nif self.loss:\n self.ax.set_ylabel('loss')\nelse:\n self.ax.set_ylabel('accuracy')\nself.ax.legend(['train', 'validation'])", "graph = 'loss' if self.lo...
<|body_start_0|> self.savepath = savepath self.fig = fig self.ax = ax self.loss = loss <|end_body_0|> <|body_start_1|> self.ax.plot(train) self.ax.plot(validation) self.ax.set_xlabel('epochs') if self.loss: self.ax.set_ylabel('loss') e...
Graph
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Graph: def __init__(self, savepath: str, fig: matplotlib.figure.Figure, ax: matplotlib.figure.Axes, loss: bool=True): """represents a graph to show the evolution of the loss and accuracy during training. :param savepath: path to save the images. :param fig: matplotlib figure object. :par...
stack_v2_sparse_classes_10k_train_008238
1,544
permissive
[ { "docstring": "represents a graph to show the evolution of the loss and accuracy during training. :param savepath: path to save the images. :param fig: matplotlib figure object. :param ax: matplotlib axis object. :param loss: whether the graph is a loss one or not.", "name": "__init__", "signature": "d...
3
stack_v2_sparse_classes_30k_train_002693
Implement the Python class `Graph` described below. Class description: Implement the Graph class. Method signatures and docstrings: - def __init__(self, savepath: str, fig: matplotlib.figure.Figure, ax: matplotlib.figure.Axes, loss: bool=True): represents a graph to show the evolution of the loss and accuracy during ...
Implement the Python class `Graph` described below. Class description: Implement the Graph class. Method signatures and docstrings: - def __init__(self, savepath: str, fig: matplotlib.figure.Figure, ax: matplotlib.figure.Axes, loss: bool=True): represents a graph to show the evolution of the loss and accuracy during ...
583e6868864582f081f18689124e74e9ca169f28
<|skeleton|> class Graph: def __init__(self, savepath: str, fig: matplotlib.figure.Figure, ax: matplotlib.figure.Axes, loss: bool=True): """represents a graph to show the evolution of the loss and accuracy during training. :param savepath: path to save the images. :param fig: matplotlib figure object. :par...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Graph: def __init__(self, savepath: str, fig: matplotlib.figure.Figure, ax: matplotlib.figure.Axes, loss: bool=True): """represents a graph to show the evolution of the loss and accuracy during training. :param savepath: path to save the images. :param fig: matplotlib figure object. :param ax: matplot...
the_stack_v2_python_sparse
utils/graphs.py
beaupreda/domain-networks
train
1
90482e06115bdef708c6f8059322cc3b17a63c66
[ "try:\n metric = Metric.objects.get(name=name, project=project, sample=sample, rna=rna)\nexcept Metric.DoesNotExist:\n metric = self.create_and_symlink(name, project, sample, rna)\nreturn metric", "res = []\nsample_names = [sample.name for sample in project.samples]\nmetric_info = dna_parse.get_metrics(proj...
<|body_start_0|> try: metric = Metric.objects.get(name=name, project=project, sample=sample, rna=rna) except Metric.DoesNotExist: metric = self.create_and_symlink(name, project, sample, rna) return metric <|end_body_0|> <|body_start_1|> res = [] sample_na...
Metrics are trickier than BAMs or VCFs because Metrics have an associated symlink that lives in the static/metrics directory. Whenever a metric is created, you have to make sure to create the symlink, and whenever a metric is deleted, you have to make sure to delete it.
MetricManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetricManager: """Metrics are trickier than BAMs or VCFs because Metrics have an associated symlink that lives in the static/metrics directory. Whenever a metric is created, you have to make sure to create the symlink, and whenever a metric is deleted, you have to make sure to delete it.""" ...
stack_v2_sparse_classes_10k_train_008239
27,913
no_license
[ { "docstring": "Overrides the standard get_or_create by calling create_or_symlink instead of vanilla create.", "name": "get_or_create", "signature": "def get_or_create(self, name, project, sample=None, rna=False)" }, { "docstring": "Uses the get_metrics function in the dna_parse toolkit script i...
4
stack_v2_sparse_classes_30k_train_001731
Implement the Python class `MetricManager` described below. Class description: Metrics are trickier than BAMs or VCFs because Metrics have an associated symlink that lives in the static/metrics directory. Whenever a metric is created, you have to make sure to create the symlink, and whenever a metric is deleted, you h...
Implement the Python class `MetricManager` described below. Class description: Metrics are trickier than BAMs or VCFs because Metrics have an associated symlink that lives in the static/metrics directory. Whenever a metric is created, you have to make sure to create the symlink, and whenever a metric is deleted, you h...
c863c79c0cbc784834534a8ce894f9ff6b5ed4c1
<|skeleton|> class MetricManager: """Metrics are trickier than BAMs or VCFs because Metrics have an associated symlink that lives in the static/metrics directory. Whenever a metric is created, you have to make sure to create the symlink, and whenever a metric is deleted, you have to make sure to delete it.""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MetricManager: """Metrics are trickier than BAMs or VCFs because Metrics have an associated symlink that lives in the static/metrics directory. Whenever a metric is created, you have to make sure to create the symlink, and whenever a metric is deleted, you have to make sure to delete it.""" def get_or_cr...
the_stack_v2_python_sparse
pbg/apps/analysis/models.py
mdschramm/dashboardngs
train
0
be61de41076fae63ad04c0beee3b101c50e2ae5e
[ "def dfs(node):\n if node is None:\n return\n l = node.left\n r = node.right\n while l:\n l.next = r\n l = l.right\n r = r.left\n if node.left:\n dfs(node.left)\n dfs(node.right)\ndfs(root)\nreturn root", "from collections import deque\nif root is None:\n ...
<|body_start_0|> def dfs(node): if node is None: return l = node.left r = node.right while l: l.next = r l = l.right r = r.left if node.left: dfs(node.left) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def connect(self, root: 'Node') -> 'Node': """Recursive1, Time: O(n), Space: O(logn) for recursive stack""" <|body_0|> def connect(self, root: 'Node') -> 'Node': """BFS, Time: O(n), Space: O(logn)""" <|body_1|> def connect(self, root: 'Node') -...
stack_v2_sparse_classes_10k_train_008240
2,251
no_license
[ { "docstring": "Recursive1, Time: O(n), Space: O(logn) for recursive stack", "name": "connect", "signature": "def connect(self, root: 'Node') -> 'Node'" }, { "docstring": "BFS, Time: O(n), Space: O(logn)", "name": "connect", "signature": "def connect(self, root: 'Node') -> 'Node'" }, ...
4
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def connect(self, root: 'Node') -> 'Node': Recursive1, Time: O(n), Space: O(logn) for recursive stack - def connect(self, root: 'Node') -> 'Node': BFS, Time: O(n), Space: O(logn)...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def connect(self, root: 'Node') -> 'Node': Recursive1, Time: O(n), Space: O(logn) for recursive stack - def connect(self, root: 'Node') -> 'Node': BFS, Time: O(n), Space: O(logn)...
72136e3487d239f5b37e2d6393e034262a6bf599
<|skeleton|> class Solution: def connect(self, root: 'Node') -> 'Node': """Recursive1, Time: O(n), Space: O(logn) for recursive stack""" <|body_0|> def connect(self, root: 'Node') -> 'Node': """BFS, Time: O(n), Space: O(logn)""" <|body_1|> def connect(self, root: 'Node') -...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def connect(self, root: 'Node') -> 'Node': """Recursive1, Time: O(n), Space: O(logn) for recursive stack""" def dfs(node): if node is None: return l = node.left r = node.right while l: l.next = r ...
the_stack_v2_python_sparse
python/116-Populating Next Right Pointers in Each Node.py
cwza/leetcode
train
0
957b78e29cf69664f62a167ca39a226dfb80fadc
[ "self.M_min = -20\nself.M_max = -18\nself.a_min = -20\nself.a_max = 20\nself.b_min = -20\nself.b_max = 20\nif g_lim != None:\n self.g_min = g_lim[0]\n self.g_max = g_lim[1]", "m = rng.rand()\nM = 1000.0 * rng.rand()\nM = dnest4.wrap(M, self.M_min, self.M_max)\na = 1000.0 * rng.rand()\na = dnest4.wrap(a, sel...
<|body_start_0|> self.M_min = -20 self.M_max = -18 self.a_min = -20 self.a_max = 20 self.b_min = -20 self.b_max = 20 if g_lim != None: self.g_min = g_lim[0] self.g_max = g_lim[1] <|end_body_0|> <|body_start_1|> m = rng.rand() ...
Specify the model in Python.
Model
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Model: """Specify the model in Python.""" def __init__(self, g_lim=None): """Parameter values *are not* stored inside the class""" <|body_0|> def from_prior(self): """Unlike in C++, this must *return* a numpy array of parameters.""" <|body_1|> def pe...
stack_v2_sparse_classes_10k_train_008241
13,227
permissive
[ { "docstring": "Parameter values *are not* stored inside the class", "name": "__init__", "signature": "def __init__(self, g_lim=None)" }, { "docstring": "Unlike in C++, this must *return* a numpy array of parameters.", "name": "from_prior", "signature": "def from_prior(self)" }, { ...
4
stack_v2_sparse_classes_30k_train_001785
Implement the Python class `Model` described below. Class description: Specify the model in Python. Method signatures and docstrings: - def __init__(self, g_lim=None): Parameter values *are not* stored inside the class - def from_prior(self): Unlike in C++, this must *return* a numpy array of parameters. - def pertur...
Implement the Python class `Model` described below. Class description: Specify the model in Python. Method signatures and docstrings: - def __init__(self, g_lim=None): Parameter values *are not* stored inside the class - def from_prior(self): Unlike in C++, this must *return* a numpy array of parameters. - def pertur...
c355d18021467cf92546cf2fc9cb1d1abe59b8d8
<|skeleton|> class Model: """Specify the model in Python.""" def __init__(self, g_lim=None): """Parameter values *are not* stored inside the class""" <|body_0|> def from_prior(self): """Unlike in C++, this must *return* a numpy array of parameters.""" <|body_1|> def pe...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Model: """Specify the model in Python.""" def __init__(self, g_lim=None): """Parameter values *are not* stored inside the class""" self.M_min = -20 self.M_max = -18 self.a_min = -20 self.a_max = 20 self.b_min = -20 self.b_max = 20 if g_lim !...
the_stack_v2_python_sparse
zprev versions/Models_py_backup/Models backup/Bfactor.py
lefthandedroo/Cosmodels
train
1
532567743785ac0a8dc4bb239079169e2a1f2c31
[ "try:\n return import_module('nis')\nexcept ImportError:\n logger.error('The nis module is not available on your version of Python.')\n return None", "if not username or not password:\n logger.error('Attempted to authenticate NIS user without supplying either a username or password parameter! This may...
<|body_start_0|> try: return import_module('nis') except ImportError: logger.error('The nis module is not available on your version of Python.') return None <|end_body_0|> <|body_start_1|> if not username or not password: logger.error('Attempted t...
Authenticate against a user on an NIS server.
NISBackend
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NISBackend: """Authenticate against a user on an NIS server.""" def nis(self) -> Optional[ModuleType]: """The nis module, used for interacting with NIS. On first access, this will check if NIS is available, logging an error if missing. This safeguards against Python environments with...
stack_v2_sparse_classes_10k_train_008242
6,661
permissive
[ { "docstring": "The nis module, used for interacting with NIS. On first access, this will check if NIS is available, logging an error if missing. This safeguards against Python environments without NIS, and against versions of Python >= 3.13. Type: module", "name": "nis", "signature": "def nis(self) -> ...
4
null
Implement the Python class `NISBackend` described below. Class description: Authenticate against a user on an NIS server. Method signatures and docstrings: - def nis(self) -> Optional[ModuleType]: The nis module, used for interacting with NIS. On first access, this will check if NIS is available, logging an error if ...
Implement the Python class `NISBackend` described below. Class description: Authenticate against a user on an NIS server. Method signatures and docstrings: - def nis(self) -> Optional[ModuleType]: The nis module, used for interacting with NIS. On first access, this will check if NIS is available, logging an error if ...
c3a991f1e9d7682239a1ab0e8661cee6da01d537
<|skeleton|> class NISBackend: """Authenticate against a user on an NIS server.""" def nis(self) -> Optional[ModuleType]: """The nis module, used for interacting with NIS. On first access, this will check if NIS is available, logging an error if missing. This safeguards against Python environments with...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class NISBackend: """Authenticate against a user on an NIS server.""" def nis(self) -> Optional[ModuleType]: """The nis module, used for interacting with NIS. On first access, this will check if NIS is available, logging an error if missing. This safeguards against Python environments without NIS, and ...
the_stack_v2_python_sparse
reviewboard/accounts/backends/nis.py
reviewboard/reviewboard
train
1,141
228d14886b3dc0ccde6ac02482c5c5d907547bc3
[ "base_dtype = [('P0', (np.float32, 3), '!local', (0, 0, 0)), ('P1', (np.float32, 3), '!local', (0, 0, 0)), ('index', (np.float32, 1), '!local', 0), ('color', (np.float32, 4), 'shared', (0, 0, 0, 1)), ('linewidth', (np.float32, 1), 'shared', 1), ('antialias', (np.float32, 1), 'shared', 1)]\ndtype = base_dtype\nif us...
<|body_start_0|> base_dtype = [('P0', (np.float32, 3), '!local', (0, 0, 0)), ('P1', (np.float32, 3), '!local', (0, 0, 0)), ('index', (np.float32, 1), '!local', 0), ('color', (np.float32, 4), 'shared', (0, 0, 0, 1)), ('linewidth', (np.float32, 1), 'shared', 1), ('antialias', (np.float32, 1), 'shared', 1)] ...
Antigrain Geometry Segment Collection This collection provides antialiased and accurate segments with caps. It consume x2 more memory than regular lines and is a bit slower, but the quality of the output is worth the cost.
AggSegmentCollection
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AggSegmentCollection: """Antigrain Geometry Segment Collection This collection provides antialiased and accurate segments with caps. It consume x2 more memory than regular lines and is a bit slower, but the quality of the output is worth the cost.""" def __init__(self, user_dtype=None, trans...
stack_v2_sparse_classes_10k_train_008243
5,126
permissive
[ { "docstring": "Initialize the collection. Parameters ---------- user_dtype: list The base dtype can be completed (appended) by the used_dtype. It only make sense if user also provide vertex and/or fragment shaders transform: glumpy.Transforms The default vertex shader apply the supplied transform to the vertic...
2
stack_v2_sparse_classes_30k_train_003321
Implement the Python class `AggSegmentCollection` described below. Class description: Antigrain Geometry Segment Collection This collection provides antialiased and accurate segments with caps. It consume x2 more memory than regular lines and is a bit slower, but the quality of the output is worth the cost. Method si...
Implement the Python class `AggSegmentCollection` described below. Class description: Antigrain Geometry Segment Collection This collection provides antialiased and accurate segments with caps. It consume x2 more memory than regular lines and is a bit slower, but the quality of the output is worth the cost. Method si...
75408635bd46e48ff10939e308a71eafdaff35e8
<|skeleton|> class AggSegmentCollection: """Antigrain Geometry Segment Collection This collection provides antialiased and accurate segments with caps. It consume x2 more memory than regular lines and is a bit slower, but the quality of the output is worth the cost.""" def __init__(self, user_dtype=None, trans...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class AggSegmentCollection: """Antigrain Geometry Segment Collection This collection provides antialiased and accurate segments with caps. It consume x2 more memory than regular lines and is a bit slower, but the quality of the output is worth the cost.""" def __init__(self, user_dtype=None, transform=None, vi...
the_stack_v2_python_sparse
glumpy/graphics/collections/agg_segment_collection.py
glumpy/glumpy
train
1,228
fc41ac5dcf67b67ef7ff676a857b0707655ba648
[ "if what == None and values == None:\n raise RuntimeWarning('Test convergence is set to ecutwfc')\n self.what = 'ecutwfc'\n self.values = np.arange(20, 80, 10)\nself.pwinput = pwinput\nself.what = what\nself.values = values\nself.Ndata = len(values)\nself.energies = None\nself.prefixInp = prefixInp\nself.p...
<|body_start_0|> if what == None and values == None: raise RuntimeWarning('Test convergence is set to ecutwfc') self.what = 'ecutwfc' self.values = np.arange(20, 80, 10) self.pwinput = pwinput self.what = what self.values = values self.Ndata = ...
A class for doing 1D convergence test.
ConvergenceTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConvergenceTest: """A class for doing 1D convergence test.""" def __init__(self, pwinput, what=None, values=None, prefixInp='TEMP_PWINPUT_', prefixOut='LOG_'): """`what` can be one of ecutwfc, kpts `values`""" <|body_0|> def run(self): """one-time run""" ...
stack_v2_sparse_classes_10k_train_008244
26,022
no_license
[ { "docstring": "`what` can be one of ecutwfc, kpts `values`", "name": "__init__", "signature": "def __init__(self, pwinput, what=None, values=None, prefixInp='TEMP_PWINPUT_', prefixOut='LOG_')" }, { "docstring": "one-time run", "name": "run", "signature": "def run(self)" }, { "do...
4
stack_v2_sparse_classes_30k_train_001223
Implement the Python class `ConvergenceTest` described below. Class description: A class for doing 1D convergence test. Method signatures and docstrings: - def __init__(self, pwinput, what=None, values=None, prefixInp='TEMP_PWINPUT_', prefixOut='LOG_'): `what` can be one of ecutwfc, kpts `values` - def run(self): one...
Implement the Python class `ConvergenceTest` described below. Class description: A class for doing 1D convergence test. Method signatures and docstrings: - def __init__(self, pwinput, what=None, values=None, prefixInp='TEMP_PWINPUT_', prefixOut='LOG_'): `what` can be one of ecutwfc, kpts `values` - def run(self): one...
c173a8fd90134120e3e1fedddf4babeee8aed74e
<|skeleton|> class ConvergenceTest: """A class for doing 1D convergence test.""" def __init__(self, pwinput, what=None, values=None, prefixInp='TEMP_PWINPUT_', prefixOut='LOG_'): """`what` can be one of ecutwfc, kpts `values`""" <|body_0|> def run(self): """one-time run""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ConvergenceTest: """A class for doing 1D convergence test.""" def __init__(self, pwinput, what=None, values=None, prefixInp='TEMP_PWINPUT_', prefixOut='LOG_'): """`what` can be one of ecutwfc, kpts `values`""" if what == None and values == None: raise RuntimeWarning('Test conv...
the_stack_v2_python_sparse
python_modules/qeManager_PWSCF.py
f-fathurrahman/IntroKomputasiMaterial
train
0
667426322e8b20be95be8415c8b544312fa8f4f5
[ "q = g.session.query(db.Role)\nauth_org_id = self.obtain_organization_id()\nargs = request.args\norg_filters = args.getlist('organization_id')\nif org_filters:\n if 'include_root' in args and args['include_root']:\n q = q.filter(or_(db.Role.organization_id.in_(org_filters), db.Role.organization_id == None...
<|body_start_0|> q = g.session.query(db.Role) auth_org_id = self.obtain_organization_id() args = request.args org_filters = args.getlist('organization_id') if org_filters: if 'include_root' in args and args['include_root']: q = q.filter(or_(db.Role.org...
Roles
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Roles: def get(self): """Returns a list of roles --- description: >- Returns a list of roles. Depending on your permission, you get all the roles at the server or only the roles that belong to your organization. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to...
stack_v2_sparse_classes_10k_train_008245
26,260
permissive
[ { "docstring": "Returns a list of roles --- description: >- Returns a list of roles. Depending on your permission, you get all the roles at the server or only the roles that belong to your organization. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |--|--|-...
2
stack_v2_sparse_classes_30k_train_003827
Implement the Python class `Roles` described below. Class description: Implement the Roles class. Method signatures and docstrings: - def get(self): Returns a list of roles --- description: >- Returns a list of roles. Depending on your permission, you get all the roles at the server or only the roles that belong to y...
Implement the Python class `Roles` described below. Class description: Implement the Roles class. Method signatures and docstrings: - def get(self): Returns a list of roles --- description: >- Returns a list of roles. Depending on your permission, you get all the roles at the server or only the roles that belong to y...
b3ff6e91ac4caeaf31c12c20f73dfc61cfd9baca
<|skeleton|> class Roles: def get(self): """Returns a list of roles --- description: >- Returns a list of roles. Depending on your permission, you get all the roles at the server or only the roles that belong to your organization. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Roles: def get(self): """Returns a list of roles --- description: >- Returns a list of roles. Depending on your permission, you get all the roles at the server or only the roles that belong to your organization. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| De...
the_stack_v2_python_sparse
vantage6-server/vantage6/server/resource/role.py
vantage6/vantage6
train
15
4e24d5ac9f01c88edc528b55b9773936cea181b6
[ "def is_palindrone(i, j):\n return s[i:j + 1] == s[i:j + 1][::-1]\nn = len(s)\nresult = 0\nfor i in range(n):\n for j in range(i, n):\n if is_palindrone(i, j):\n result += 1\nreturn result", "@lru_cache(None)\ndef is_palindrone(i, j):\n if j <= i:\n return True\n return s[i] =...
<|body_start_0|> def is_palindrone(i, j): return s[i:j + 1] == s[i:j + 1][::-1] n = len(s) result = 0 for i in range(n): for j in range(i, n): if is_palindrone(i, j): result += 1 return result <|end_body_0|> <|body_star...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countSubstrings(self, s: str) -> int: """Brute Force, Time: O(n^3), Space: O(1)""" <|body_0|> def countSubstrings(self, s: str) -> int: """Top-Down DP for is_palindrone, Time: O(n^2), Space: O(n^2)""" <|body_1|> def countSubstrings(self, s:...
stack_v2_sparse_classes_10k_train_008246
1,729
no_license
[ { "docstring": "Brute Force, Time: O(n^3), Space: O(1)", "name": "countSubstrings", "signature": "def countSubstrings(self, s: str) -> int" }, { "docstring": "Top-Down DP for is_palindrone, Time: O(n^2), Space: O(n^2)", "name": "countSubstrings", "signature": "def countSubstrings(self, s...
3
stack_v2_sparse_classes_30k_train_004455
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countSubstrings(self, s: str) -> int: Brute Force, Time: O(n^3), Space: O(1) - def countSubstrings(self, s: str) -> int: Top-Down DP for is_palindrone, Time: O(n^2), Space: O...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countSubstrings(self, s: str) -> int: Brute Force, Time: O(n^3), Space: O(1) - def countSubstrings(self, s: str) -> int: Top-Down DP for is_palindrone, Time: O(n^2), Space: O...
72136e3487d239f5b37e2d6393e034262a6bf599
<|skeleton|> class Solution: def countSubstrings(self, s: str) -> int: """Brute Force, Time: O(n^3), Space: O(1)""" <|body_0|> def countSubstrings(self, s: str) -> int: """Top-Down DP for is_palindrone, Time: O(n^2), Space: O(n^2)""" <|body_1|> def countSubstrings(self, s:...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def countSubstrings(self, s: str) -> int: """Brute Force, Time: O(n^3), Space: O(1)""" def is_palindrone(i, j): return s[i:j + 1] == s[i:j + 1][::-1] n = len(s) result = 0 for i in range(n): for j in range(i, n): if is_p...
the_stack_v2_python_sparse
python/647-Palindromic Substrings.py
cwza/leetcode
train
0
8c0f71d5070d8640af8e6291bbfd1146b4a75300
[ "if path != None:\n matrix = load_npz(path)\n with open(path + '_rows', 'rb') as f:\n rows = pickle.load(f)\n with open(path + '_columns', 'rb') as f:\n columns = pickle.load(f)\nrow2id = {r: i for i, r in enumerate(rows)}\nid2row = {i: r for i, r in enumerate(rows)}\ncolumn2id = {c: i for i,...
<|body_start_0|> if path != None: matrix = load_npz(path) with open(path + '_rows', 'rb') as f: rows = pickle.load(f) with open(path + '_columns', 'rb') as f: columns = pickle.load(f) row2id = {r: i for i, r in enumerate(rows)} ...
Load and save Space objects.
Space
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Space: """Load and save Space objects.""" def __init__(self, path=None, matrix=csr_matrix([]), rows=[], columns=[]): """Can be either initialized (i) by providing a path, (ii) by providing a matrix, rows and columns, or (iii) by providing neither, then an empty instance is created `p...
stack_v2_sparse_classes_10k_train_008247
1,939
no_license
[ { "docstring": "Can be either initialized (i) by providing a path, (ii) by providing a matrix, rows and columns, or (iii) by providing neither, then an empty instance is created `path` should be path to a matrix in npz format, expects rows and columns in same folder at '[path]_rows' and '[path]_columns' `rows` ...
2
stack_v2_sparse_classes_30k_val_000043
Implement the Python class `Space` described below. Class description: Load and save Space objects. Method signatures and docstrings: - def __init__(self, path=None, matrix=csr_matrix([]), rows=[], columns=[]): Can be either initialized (i) by providing a path, (ii) by providing a matrix, rows and columns, or (iii) b...
Implement the Python class `Space` described below. Class description: Load and save Space objects. Method signatures and docstrings: - def __init__(self, path=None, matrix=csr_matrix([]), rows=[], columns=[]): Can be either initialized (i) by providing a path, (ii) by providing a matrix, rows and columns, or (iii) b...
c25540943031538cbb569c4771c7b6cdefc9408c
<|skeleton|> class Space: """Load and save Space objects.""" def __init__(self, path=None, matrix=csr_matrix([]), rows=[], columns=[]): """Can be either initialized (i) by providing a path, (ii) by providing a matrix, rows and columns, or (iii) by providing neither, then an empty instance is created `p...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Space: """Load and save Space objects.""" def __init__(self, path=None, matrix=csr_matrix([]), rows=[], columns=[]): """Can be either initialized (i) by providing a path, (ii) by providing a matrix, rows and columns, or (iii) by providing neither, then an empty instance is created `path` should b...
the_stack_v2_python_sparse
code/utils_.py
wabyking/unipd-DIACR-Ita
train
0
2738a587cdebd824e5a118e99e4aefeb834e1e21
[ "super(SEopt, self).__init__()\nif nonlinearity is None:\n nonlinearity = nn.Sigmoid\nself._reduced_planes = int(inplanes / reduction)\nself.avgpool = nn.AdaptiveAvgPool2d((1, 1))\nself.fc1 = nn.Linear(inplanes, self._reduced_planes)\nself.relu = nn.ReLU(inplace=True)\nself.fc2 = nn.Linear(self._reduced_planes, ...
<|body_start_0|> super(SEopt, self).__init__() if nonlinearity is None: nonlinearity = nn.Sigmoid self._reduced_planes = int(inplanes / reduction) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc1 = nn.Linear(inplanes, self._reduced_planes) self.relu = nn.R...
squeeze-and-excitation optimization layer structure: - global pooling > fc > relu > fc > sigmoid > skip connect: scale notes: - global pooling = AdaptiveAvgPool((1,1)) -> reduces fmap dimensions to 1x1 - reduction ratio - 1st fc squeeze channels to c/r, where r = reduction ratio - 2nd fc recovers channels to c - scale ...
SEopt
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SEopt: """squeeze-and-excitation optimization layer structure: - global pooling > fc > relu > fc > sigmoid > skip connect: scale notes: - global pooling = AdaptiveAvgPool((1,1)) -> reduces fmap dimensions to 1x1 - reduction ratio - 1st fc squeeze channels to c/r, where r = reduction ratio - 2nd f...
stack_v2_sparse_classes_10k_train_008248
20,656
no_license
[ { "docstring": "Constructor Args: inplanes: (int) number of input channels reduction: (int) reduction ratio nonlinearity: (nn.Module) non-linearity used in SE module; default = nn.sigmoid", "name": "__init__", "signature": "def __init__(self, inplanes, reduction=8, nonlinearity=None)" }, { "docs...
2
stack_v2_sparse_classes_30k_train_005211
Implement the Python class `SEopt` described below. Class description: squeeze-and-excitation optimization layer structure: - global pooling > fc > relu > fc > sigmoid > skip connect: scale notes: - global pooling = AdaptiveAvgPool((1,1)) -> reduces fmap dimensions to 1x1 - reduction ratio - 1st fc squeeze channels to...
Implement the Python class `SEopt` described below. Class description: squeeze-and-excitation optimization layer structure: - global pooling > fc > relu > fc > sigmoid > skip connect: scale notes: - global pooling = AdaptiveAvgPool((1,1)) -> reduces fmap dimensions to 1x1 - reduction ratio - 1st fc squeeze channels to...
a0c51824b9c4c458918ef9a40a925cd576137d75
<|skeleton|> class SEopt: """squeeze-and-excitation optimization layer structure: - global pooling > fc > relu > fc > sigmoid > skip connect: scale notes: - global pooling = AdaptiveAvgPool((1,1)) -> reduces fmap dimensions to 1x1 - reduction ratio - 1st fc squeeze channels to c/r, where r = reduction ratio - 2nd f...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SEopt: """squeeze-and-excitation optimization layer structure: - global pooling > fc > relu > fc > sigmoid > skip connect: scale notes: - global pooling = AdaptiveAvgPool((1,1)) -> reduces fmap dimensions to 1x1 - reduction ratio - 1st fc squeeze channels to c/r, where r = reduction ratio - 2nd fc recovers ch...
the_stack_v2_python_sparse
model/mnasnet.py
baihuaxie/ConvLab
train
0
e8fe9e7e0ad0442326e31da4469c1a303711a6f1
[ "max_sub_sum = max(nums)\nfor i in range(len(nums)):\n tmp = nums[i]\n for j in range(i + 1, len(nums)):\n if tmp + nums[j] > 0:\n tmp += nums[j]\n if max_sub_sum < tmp:\n max_sub_sum = tmp\n else:\n break\nreturn max_sub_sum", "if not nums:\n ...
<|body_start_0|> max_sub_sum = max(nums) for i in range(len(nums)): tmp = nums[i] for j in range(i + 1, len(nums)): if tmp + nums[j] > 0: tmp += nums[j] if max_sub_sum < tmp: max_sub_sum = tmp ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxSubArray(self, nums: list): """时间复杂度为O(n^2) :param nums: :return:""" <|body_0|> def maxSubArray1(self, nums: list): """动态规划,时间复杂度为O(n) :param nums: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> max_sub_sum = max(nums) ...
stack_v2_sparse_classes_10k_train_008249
1,219
no_license
[ { "docstring": "时间复杂度为O(n^2) :param nums: :return:", "name": "maxSubArray", "signature": "def maxSubArray(self, nums: list)" }, { "docstring": "动态规划,时间复杂度为O(n) :param nums: :return:", "name": "maxSubArray1", "signature": "def maxSubArray1(self, nums: list)" } ]
2
stack_v2_sparse_classes_30k_train_005345
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSubArray(self, nums: list): 时间复杂度为O(n^2) :param nums: :return: - def maxSubArray1(self, nums: list): 动态规划,时间复杂度为O(n) :param nums: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSubArray(self, nums: list): 时间复杂度为O(n^2) :param nums: :return: - def maxSubArray1(self, nums: list): 动态规划,时间复杂度为O(n) :param nums: :return: <|skeleton|> class Solution: ...
5f67368e72c376c1299b849e7a92e6d0cbd9ae55
<|skeleton|> class Solution: def maxSubArray(self, nums: list): """时间复杂度为O(n^2) :param nums: :return:""" <|body_0|> def maxSubArray1(self, nums: list): """动态规划,时间复杂度为O(n) :param nums: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def maxSubArray(self, nums: list): """时间复杂度为O(n^2) :param nums: :return:""" max_sub_sum = max(nums) for i in range(len(nums)): tmp = nums[i] for j in range(i + 1, len(nums)): if tmp + nums[j] > 0: tmp += nums[j] ...
the_stack_v2_python_sparse
53-最大子序和/solution.py
BillyChao/leetcode
train
5
c1b3571c1db4c4ad2562061ebbd1de87d411d3e2
[ "story_ids = topic.get_canonical_story_ids()\nexisting_story_ids = set(stories_dict.keys()).intersection(story_ids)\nexp_ids: List[str] = list(itertools.chain.from_iterable((stories_dict[story_id].story_contents.get_all_linked_exp_ids() for story_id in existing_story_ids)))\nexisting_exp_ids = set(exps_dict.keys())...
<|body_start_0|> story_ids = topic.get_canonical_story_ids() existing_story_ids = set(stories_dict.keys()).intersection(story_ids) exp_ids: List[str] = list(itertools.chain.from_iterable((stories_dict[story_id].story_contents.get_all_linked_exp_ids() for story_id in existing_story_ids))) ...
Job that regenerates ExplorationOpportunitySummaryModel. NOTE: The DeleteExplorationOpportunitySummariesJob must be run before this job.
GenerateExplorationOpportunitySummariesJob
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GenerateExplorationOpportunitySummariesJob: """Job that regenerates ExplorationOpportunitySummaryModel. NOTE: The DeleteExplorationOpportunitySummariesJob must be run before this job.""" def _generate_opportunities_related_to_topic(topic: topic_domain.Topic, stories_dict: Dict[str, story_dom...
stack_v2_sparse_classes_10k_train_008250
17,468
permissive
[ { "docstring": "Generate opportunities related to a topic. Args: topic: Topic. Topic for which to generate the opportunities. stories_dict: dict(str, Story). All stories in the datastore, keyed by their ID. exps_dict: dict(str, Exploration). All explorations in the datastore, keyed by their ID. Returns: dict(st...
2
null
Implement the Python class `GenerateExplorationOpportunitySummariesJob` described below. Class description: Job that regenerates ExplorationOpportunitySummaryModel. NOTE: The DeleteExplorationOpportunitySummariesJob must be run before this job. Method signatures and docstrings: - def _generate_opportunities_related_t...
Implement the Python class `GenerateExplorationOpportunitySummariesJob` described below. Class description: Job that regenerates ExplorationOpportunitySummaryModel. NOTE: The DeleteExplorationOpportunitySummariesJob must be run before this job. Method signatures and docstrings: - def _generate_opportunities_related_t...
d16fdf23d790eafd63812bd7239532256e30a21d
<|skeleton|> class GenerateExplorationOpportunitySummariesJob: """Job that regenerates ExplorationOpportunitySummaryModel. NOTE: The DeleteExplorationOpportunitySummariesJob must be run before this job.""" def _generate_opportunities_related_to_topic(topic: topic_domain.Topic, stories_dict: Dict[str, story_dom...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GenerateExplorationOpportunitySummariesJob: """Job that regenerates ExplorationOpportunitySummaryModel. NOTE: The DeleteExplorationOpportunitySummariesJob must be run before this job.""" def _generate_opportunities_related_to_topic(topic: topic_domain.Topic, stories_dict: Dict[str, story_domain.Story], e...
the_stack_v2_python_sparse
core/jobs/batch_jobs/opportunity_management_jobs.py
oppia/oppia
train
6,172
86606bc769437f84b37de8eb1be2a52e0111826a
[ "for key in inconfigs:\n if not key.startswith('text search configuration '):\n raise KeyError('Unrecognized object type: %s' % key)\n tsc = key[26:]\n self[schema.name, tsc] = config = TSConfiguration(schema=schema.name, name=tsc)\n inconfig = inconfigs[key]\n if inconfig:\n for attr, ...
<|body_start_0|> for key in inconfigs: if not key.startswith('text search configuration '): raise KeyError('Unrecognized object type: %s' % key) tsc = key[26:] self[schema.name, tsc] = config = TSConfiguration(schema=schema.name, name=tsc) inconfig...
The collection of text search configurations in a database
TSConfigurationDict
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TSConfigurationDict: """The collection of text search configurations in a database""" def from_map(self, schema, inconfigs): """Initialize the dictionary of configs by examining the input map :param schema: schema owning the configurations :param inconfigs: input YAML map defining th...
stack_v2_sparse_classes_10k_train_008251
15,925
permissive
[ { "docstring": "Initialize the dictionary of configs by examining the input map :param schema: schema owning the configurations :param inconfigs: input YAML map defining the configurations", "name": "from_map", "signature": "def from_map(self, schema, inconfigs)" }, { "docstring": "Generate SQL ...
2
stack_v2_sparse_classes_30k_train_005161
Implement the Python class `TSConfigurationDict` described below. Class description: The collection of text search configurations in a database Method signatures and docstrings: - def from_map(self, schema, inconfigs): Initialize the dictionary of configs by examining the input map :param schema: schema owning the co...
Implement the Python class `TSConfigurationDict` described below. Class description: The collection of text search configurations in a database Method signatures and docstrings: - def from_map(self, schema, inconfigs): Initialize the dictionary of configs by examining the input map :param schema: schema owning the co...
0133f3bc522890e0564d27de6791824acb4d2773
<|skeleton|> class TSConfigurationDict: """The collection of text search configurations in a database""" def from_map(self, schema, inconfigs): """Initialize the dictionary of configs by examining the input map :param schema: schema owning the configurations :param inconfigs: input YAML map defining th...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TSConfigurationDict: """The collection of text search configurations in a database""" def from_map(self, schema, inconfigs): """Initialize the dictionary of configs by examining the input map :param schema: schema owning the configurations :param inconfigs: input YAML map defining the configurati...
the_stack_v2_python_sparse
pyrseas/dbobject/textsearch.py
vayerx/Pyrseas
train
1
bbcdc1844d97f559edeb426e83156f6881993669
[ "self.GET_PARSER.add_argument('id', required=True, type=int, location='args')\nargs = self.GET_PARSER.parse_args()\nid_ = args['id']\npassenger = common.query_single_by_id(models.Passenger, id_)\nif passenger is None:\n return ({'error': 'not found'}, 404)\nreturn marshal(passenger, PASSENGER_STRUCTURE)", "sel...
<|body_start_0|> self.GET_PARSER.add_argument('id', required=True, type=int, location='args') args = self.GET_PARSER.parse_args() id_ = args['id'] passenger = common.query_single_by_id(models.Passenger, id_) if passenger is None: return ({'error': 'not found'}, 404) ...
PassengerResource
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PassengerResource: def get(self): """获取拼车的人的信息 API请求地址: /interaction/api/v2/passenger 方法: GET 参数: 必选参数: id 乘客的id""" <|body_0|> def post(self): """加入某个拼车 API请求地址: /interaction/api/v2/passenger 方法: POST 参数: 参数位置为form 必选参数: carpool_id 已经存在的某个拼车id uid 用户id token 用户token ...
stack_v2_sparse_classes_10k_train_008252
7,122
no_license
[ { "docstring": "获取拼车的人的信息 API请求地址: /interaction/api/v2/passenger 方法: GET 参数: 必选参数: id 乘客的id", "name": "get", "signature": "def get(self)" }, { "docstring": "加入某个拼车 API请求地址: /interaction/api/v2/passenger 方法: POST 参数: 参数位置为form 必选参数: carpool_id 已经存在的某个拼车id uid 用户id token 用户token contact 用户自己的联系信息,...
4
stack_v2_sparse_classes_30k_train_004276
Implement the Python class `PassengerResource` described below. Class description: Implement the PassengerResource class. Method signatures and docstrings: - def get(self): 获取拼车的人的信息 API请求地址: /interaction/api/v2/passenger 方法: GET 参数: 必选参数: id 乘客的id - def post(self): 加入某个拼车 API请求地址: /interaction/api/v2/passenger 方法: P...
Implement the Python class `PassengerResource` described below. Class description: Implement the PassengerResource class. Method signatures and docstrings: - def get(self): 获取拼车的人的信息 API请求地址: /interaction/api/v2/passenger 方法: GET 参数: 必选参数: id 乘客的id - def post(self): 加入某个拼车 API请求地址: /interaction/api/v2/passenger 方法: P...
076f2a6ed334f8a96b741d0c5c9d268f3716c8b3
<|skeleton|> class PassengerResource: def get(self): """获取拼车的人的信息 API请求地址: /interaction/api/v2/passenger 方法: GET 参数: 必选参数: id 乘客的id""" <|body_0|> def post(self): """加入某个拼车 API请求地址: /interaction/api/v2/passenger 方法: POST 参数: 参数位置为form 必选参数: carpool_id 已经存在的某个拼车id uid 用户id token 用户token ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PassengerResource: def get(self): """获取拼车的人的信息 API请求地址: /interaction/api/v2/passenger 方法: GET 参数: 必选参数: id 乘客的id""" self.GET_PARSER.add_argument('id', required=True, type=int, location='args') args = self.GET_PARSER.parse_args() id_ = args['id'] passenger = common.query...
the_stack_v2_python_sparse
app/mod_interaction/resources/PassengerResource.py
xiaofud/syllabus_backend
train
0
1dde1989edbc3ec619c4edf24ea611f8632a3b63
[ "super().__init__()\nself.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)\nself.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_input, drop_rate)\nself.linear = tf.keras.layers.Dense(units=target_vocab)", "out1, _ = self.mha(x, x, x, mask)\nout1 = self.dropout1(out1, training=...
<|body_start_0|> super().__init__() self.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate) self.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_input, drop_rate) self.linear = tf.keras.layers.Dense(units=target_vocab) <|end_body_0|> <|body_start_1|> ...
DecoderBlock class
Transformer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Transformer: """DecoderBlock class""" def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): """Initializer. Args: dm: (int) the dimensionality of the model. h: (int) the number of heads. hidden: (int) the number of hidden units...
stack_v2_sparse_classes_10k_train_008253
1,800
no_license
[ { "docstring": "Initializer. Args: dm: (int) the dimensionality of the model. h: (int) the number of heads. hidden: (int) the number of hidden units in the fully connected layer. drop_rate: (float) the dropout rate.", "name": "__init__", "signature": "def __init__(self, N, dm, h, hidden, input_vocab, ta...
2
stack_v2_sparse_classes_30k_train_004778
Implement the Python class `Transformer` described below. Class description: DecoderBlock class Method signatures and docstrings: - def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): Initializer. Args: dm: (int) the dimensionality of the model. h: (int) the ...
Implement the Python class `Transformer` described below. Class description: DecoderBlock class Method signatures and docstrings: - def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): Initializer. Args: dm: (int) the dimensionality of the model. h: (int) the ...
75274394adb52d740f6cd4000cc00bbde44b9b72
<|skeleton|> class Transformer: """DecoderBlock class""" def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): """Initializer. Args: dm: (int) the dimensionality of the model. h: (int) the number of heads. hidden: (int) the number of hidden units...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Transformer: """DecoderBlock class""" def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): """Initializer. Args: dm: (int) the dimensionality of the model. h: (int) the number of heads. hidden: (int) the number of hidden units in the fully...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/11-transformer.py
jdarangop/holbertonschool-machine_learning
train
2
788b4e5e41538470f9af98cb2da9c30eab75a6cc
[ "self.scraper_class = scraper_class\nself.output_errors_only = output_errors_only\nif checks:\n self.checks = checks\nelse:\n self.checks = (CheckBaseURL,)", "errors = 0\nfor check_class in self.checks:\n if check_class(self.scraper_class).run_check():\n errors += 1" ]
<|body_start_0|> self.scraper_class = scraper_class self.output_errors_only = output_errors_only if checks: self.checks = checks else: self.checks = (CheckBaseURL,) <|end_body_0|> <|body_start_1|> errors = 0 for check_class in self.checks: ...
ScraperChecker
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScraperChecker: def __init__(self, scraper_class, checks=None, output_errors_only=True): """A class for checking the quality of a Scraper Class. :param output_errors_only: (optional) Boolean. :param scraper_class: A :class:`ScraperBase` subclass.""" <|body_0|> def run_checks...
stack_v2_sparse_classes_10k_train_008254
1,650
permissive
[ { "docstring": "A class for checking the quality of a Scraper Class. :param output_errors_only: (optional) Boolean. :param scraper_class: A :class:`ScraperBase` subclass.", "name": "__init__", "signature": "def __init__(self, scraper_class, checks=None, output_errors_only=True)" }, { "docstring"...
2
stack_v2_sparse_classes_30k_train_003879
Implement the Python class `ScraperChecker` described below. Class description: Implement the ScraperChecker class. Method signatures and docstrings: - def __init__(self, scraper_class, checks=None, output_errors_only=True): A class for checking the quality of a Scraper Class. :param output_errors_only: (optional) Bo...
Implement the Python class `ScraperChecker` described below. Class description: Implement the ScraperChecker class. Method signatures and docstrings: - def __init__(self, scraper_class, checks=None, output_errors_only=True): A class for checking the quality of a Scraper Class. :param output_errors_only: (optional) Bo...
13d9c9d11cf4fc3afc4ae52ac439ee4fec926ba3
<|skeleton|> class ScraperChecker: def __init__(self, scraper_class, checks=None, output_errors_only=True): """A class for checking the quality of a Scraper Class. :param output_errors_only: (optional) Boolean. :param scraper_class: A :class:`ScraperBase` subclass.""" <|body_0|> def run_checks...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ScraperChecker: def __init__(self, scraper_class, checks=None, output_errors_only=True): """A class for checking the quality of a Scraper Class. :param output_errors_only: (optional) Boolean. :param scraper_class: A :class:`ScraperBase` subclass.""" self.scraper_class = scraper_class s...
the_stack_v2_python_sparse
lgsf/scrapers/checks.py
DemocracyClub/LGSF
train
4
76bd06a35b90e91d728cbef2fcbb340d055c44e1
[ "if roles.Roles.is_super_admin():\n exit_url = '%s?tab=google_service_account' % handler.LINK_URL\nelse:\n exit_url = cls.request.referer\nrest_url = GoogleServiceAccountRESTHandler.URI\ntemplate_values = {}\ntemplate_values['page_title'] = handler.format_title('Google Service Accounts')\ncontent = safe_dom.N...
<|body_start_0|> if roles.Roles.is_super_admin(): exit_url = '%s?tab=google_service_account' % handler.LINK_URL else: exit_url = cls.request.referer rest_url = GoogleServiceAccountRESTHandler.URI template_values = {} template_values['page_title'] = handler...
GoogleServiceAccountBaseAdminHandler
[ "CC-BY-3.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GoogleServiceAccountBaseAdminHandler: def get_google_service_account(cls, handler): """Displays list of service account settings.""" <|body_0|> def get_edit_google_service_account(cls, handler): """Handles 'get_add_google_service_account_settings' action and renders ...
stack_v2_sparse_classes_10k_train_008255
13,602
permissive
[ { "docstring": "Displays list of service account settings.", "name": "get_google_service_account", "signature": "def get_google_service_account(cls, handler)" }, { "docstring": "Handles 'get_add_google_service_account_settings' action and renders new course entry editor.", "name": "get_edit_...
3
stack_v2_sparse_classes_30k_train_002141
Implement the Python class `GoogleServiceAccountBaseAdminHandler` described below. Class description: Implement the GoogleServiceAccountBaseAdminHandler class. Method signatures and docstrings: - def get_google_service_account(cls, handler): Displays list of service account settings. - def get_edit_google_service_acc...
Implement the Python class `GoogleServiceAccountBaseAdminHandler` described below. Class description: Implement the GoogleServiceAccountBaseAdminHandler class. Method signatures and docstrings: - def get_google_service_account(cls, handler): Displays list of service account settings. - def get_edit_google_service_acc...
2bca9d64499e160b2da9bed6e97fcda712feec72
<|skeleton|> class GoogleServiceAccountBaseAdminHandler: def get_google_service_account(cls, handler): """Displays list of service account settings.""" <|body_0|> def get_edit_google_service_account(cls, handler): """Handles 'get_add_google_service_account_settings' action and renders ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GoogleServiceAccountBaseAdminHandler: def get_google_service_account(cls, handler): """Displays list of service account settings.""" if roles.Roles.is_super_admin(): exit_url = '%s?tab=google_service_account' % handler.LINK_URL else: exit_url = cls.request.refer...
the_stack_v2_python_sparse
coursebuilder/modules/google_service_account/settings.py
RavinderSinghPB/seek
train
0
0f84d908c2fb2461c5b4ab6020352ada431397a0
[ "res = super(account_voucher, self).proforma_voucher()\npurchase_rs = self.purchase_id\nif purchase_rs:\n purchase_rs.write({'check_paid': True})\n purchase_rs.picking_ids.write({'payment_lock': False})\nreturn res", "partner_type_obj = self.env['res.partner.purchase.type']\nsearch_partner_ids = []\nnew_par...
<|body_start_0|> res = super(account_voucher, self).proforma_voucher() purchase_rs = self.purchase_id if purchase_rs: purchase_rs.write({'check_paid': True}) purchase_rs.picking_ids.write({'payment_lock': False}) return res <|end_body_0|> <|body_start_1|> ...
account_voucher
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class account_voucher: def proforma_voucher(self): """Surcharge pour prendre en compte la libération de l'achat et des pickings en cas de validation du paiement""" <|body_0|> def recompute_voucher_lines(self, partner_ids, journal_id, price, currency_id, ttype, date): """Su...
stack_v2_sparse_classes_10k_train_008256
5,566
no_license
[ { "docstring": "Surcharge pour prendre en compte la libération de l'achat et des pickings en cas de validation du paiement", "name": "proforma_voucher", "signature": "def proforma_voucher(self)" }, { "docstring": "Surcharge pour prendre en compte les partenaires facturés du partenaire payeur", ...
2
null
Implement the Python class `account_voucher` described below. Class description: Implement the account_voucher class. Method signatures and docstrings: - def proforma_voucher(self): Surcharge pour prendre en compte la libération de l'achat et des pickings en cas de validation du paiement - def recompute_voucher_lines...
Implement the Python class `account_voucher` described below. Class description: Implement the account_voucher class. Method signatures and docstrings: - def proforma_voucher(self): Surcharge pour prendre en compte la libération de l'achat et des pickings en cas de validation du paiement - def recompute_voucher_lines...
eb394e1f79ba1995da2dcd81adfdd511c22caff9
<|skeleton|> class account_voucher: def proforma_voucher(self): """Surcharge pour prendre en compte la libération de l'achat et des pickings en cas de validation du paiement""" <|body_0|> def recompute_voucher_lines(self, partner_ids, journal_id, price, currency_id, ttype, date): """Su...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class account_voucher: def proforma_voucher(self): """Surcharge pour prendre en compte la libération de l'achat et des pickings en cas de validation du paiement""" res = super(account_voucher, self).proforma_voucher() purchase_rs = self.purchase_id if purchase_rs: purchas...
the_stack_v2_python_sparse
OpenPROD/openprod-addons/purchase/account.py
kazacube-mziouadi/ceci
train
0
826631e93b6d1d4f98441237767f5aaf2ba87972
[ "expected_checksum = database.Database.ChecksumForText(hwid_config_contents)\ncontents_analyzer_inst = contents_analyzer.ContentsAnalyzer(hwid_config_contents, expected_checksum, None)\nreport = contents_analyzer_inst.ValidateIntegrity()\nif report.errors:\n raise ValidationError(report.errors)", "expected_che...
<|body_start_0|> expected_checksum = database.Database.ChecksumForText(hwid_config_contents) contents_analyzer_inst = contents_analyzer.ContentsAnalyzer(hwid_config_contents, expected_checksum, None) report = contents_analyzer_inst.ValidateIntegrity() if report.errors: raise ...
Validates HWID configs.
HwidValidator
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HwidValidator: """Validates HWID configs.""" def Validate(self, hwid_config_contents): """Validates a HWID config. Uses strict validation (i.e. includes checksum validation). Args: hwid_config_contents: the current HWID config as a string.""" <|body_0|> def ValidateChang...
stack_v2_sparse_classes_10k_train_008257
3,013
permissive
[ { "docstring": "Validates a HWID config. Uses strict validation (i.e. includes checksum validation). Args: hwid_config_contents: the current HWID config as a string.", "name": "Validate", "signature": "def Validate(self, hwid_config_contents)" }, { "docstring": "Validates a HWID config change. T...
2
null
Implement the Python class `HwidValidator` described below. Class description: Validates HWID configs. Method signatures and docstrings: - def Validate(self, hwid_config_contents): Validates a HWID config. Uses strict validation (i.e. includes checksum validation). Args: hwid_config_contents: the current HWID config ...
Implement the Python class `HwidValidator` described below. Class description: Validates HWID configs. Method signatures and docstrings: - def Validate(self, hwid_config_contents): Validates a HWID config. Uses strict validation (i.e. includes checksum validation). Args: hwid_config_contents: the current HWID config ...
a1b0fccd68987d8cd9c89710adc3c04b868347ec
<|skeleton|> class HwidValidator: """Validates HWID configs.""" def Validate(self, hwid_config_contents): """Validates a HWID config. Uses strict validation (i.e. includes checksum validation). Args: hwid_config_contents: the current HWID config as a string.""" <|body_0|> def ValidateChang...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class HwidValidator: """Validates HWID configs.""" def Validate(self, hwid_config_contents): """Validates a HWID config. Uses strict validation (i.e. includes checksum validation). Args: hwid_config_contents: the current HWID config as a string.""" expected_checksum = database.Database.Checksum...
the_stack_v2_python_sparse
py/hwid/service/appengine/hwid_validator.py
bridder/factory
train
0
52d75c527b4bad17d5c2a2957a4a417fb031c775
[ "if num_objectives not in (2, 3, 4):\n raise UnsupportedError('GMM only currently supports 2 to 4 objectives.')\nself._ref_point = [-0.2338, -0.2211]\nif num_objectives > 2:\n self._ref_point.append(-0.518)\nif num_objectives > 3:\n self._ref_point.append(-0.1866)\nself.num_objectives = num_objectives\nsup...
<|body_start_0|> if num_objectives not in (2, 3, 4): raise UnsupportedError('GMM only currently supports 2 to 4 objectives.') self._ref_point = [-0.2338, -0.2211] if num_objectives > 2: self._ref_point.append(-0.518) if num_objectives > 3: self._ref_po...
A test problem where each objective is a Gaussian mixture model. This implementation is adapted from the single objective version (proposed by [Frohlich2020]_) at https://github.com/boschresearch/NoisyInputEntropySearch/blob/master/ core/util/objectives.py. See [Daulton2022]_ for details on this multi-objective problem...
GMM
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GMM: """A test problem where each objective is a Gaussian mixture model. This implementation is adapted from the single objective version (proposed by [Frohlich2020]_) at https://github.com/boschresearch/NoisyInputEntropySearch/blob/master/ core/util/objectives.py. See [Daulton2022]_ for details ...
stack_v2_sparse_classes_10k_train_008258
49,438
permissive
[ { "docstring": "Args: noise_std: Standard deviation of the observation noise. negate: If True, negate the objectives. num_objectives: The number of objectives.", "name": "__init__", "signature": "def __init__(self, noise_std: Optional[float]=None, negate: bool=False, num_objectives: int=2) -> None" },...
2
stack_v2_sparse_classes_30k_train_001226
Implement the Python class `GMM` described below. Class description: A test problem where each objective is a Gaussian mixture model. This implementation is adapted from the single objective version (proposed by [Frohlich2020]_) at https://github.com/boschresearch/NoisyInputEntropySearch/blob/master/ core/util/objecti...
Implement the Python class `GMM` described below. Class description: A test problem where each objective is a Gaussian mixture model. This implementation is adapted from the single objective version (proposed by [Frohlich2020]_) at https://github.com/boschresearch/NoisyInputEntropySearch/blob/master/ core/util/objecti...
4cc5ed59b2e8a9c780f786830c548e05cc74d53c
<|skeleton|> class GMM: """A test problem where each objective is a Gaussian mixture model. This implementation is adapted from the single objective version (proposed by [Frohlich2020]_) at https://github.com/boschresearch/NoisyInputEntropySearch/blob/master/ core/util/objectives.py. See [Daulton2022]_ for details ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GMM: """A test problem where each objective is a Gaussian mixture model. This implementation is adapted from the single objective version (proposed by [Frohlich2020]_) at https://github.com/boschresearch/NoisyInputEntropySearch/blob/master/ core/util/objectives.py. See [Daulton2022]_ for details on this multi...
the_stack_v2_python_sparse
botorch/test_functions/multi_objective.py
pytorch/botorch
train
2,891
138f492e01bd023a546bc95d483ef91dce6024ef
[ "self.input_dict = input_dict\nself.output_dict = output_dict\nself.project_name = project_name", "if calculate_costs_input_dict['num_turbines'] > 10:\n calculate_costs_output_dict['substation_cost_usd'] = 11652 * (calculate_costs_input_dict['interconnect_voltage_kV'] + calculate_costs_input_dict['project_size...
<|body_start_0|> self.input_dict = input_dict self.output_dict = output_dict self.project_name = project_name <|end_body_0|> <|body_start_1|> if calculate_costs_input_dict['num_turbines'] > 10: calculate_costs_output_dict['substation_cost_usd'] = 11652 * (calculate_costs_inp...
**SubstationCost.py** - Created by Annika Eberle and Owen Roberts on Dec. 17, 2018 - Refactored by Parangat Bhaskar and Alicia Key on June 3, 2019 Calculates the costs associated with substations for land-based wind projects *(module is currently based on curve fit of empirical data)* Get project size (project_size_meg...
SubstationCost
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubstationCost: """**SubstationCost.py** - Created by Annika Eberle and Owen Roberts on Dec. 17, 2018 - Refactored by Parangat Bhaskar and Alicia Key on June 3, 2019 Calculates the costs associated with substations for land-based wind projects *(module is currently based on curve fit of empirical...
stack_v2_sparse_classes_10k_train_008259
5,371
permissive
[ { "docstring": "Parameters ---------- input_dict : dict The input dictionary with key value pairs described in the class documentation output_dict : dict The output dictionary with key value pairs as found on the output documentation.", "name": "__init__", "signature": "def __init__(self, input_dict, ou...
4
stack_v2_sparse_classes_30k_train_006461
Implement the Python class `SubstationCost` described below. Class description: **SubstationCost.py** - Created by Annika Eberle and Owen Roberts on Dec. 17, 2018 - Refactored by Parangat Bhaskar and Alicia Key on June 3, 2019 Calculates the costs associated with substations for land-based wind projects *(module is cu...
Implement the Python class `SubstationCost` described below. Class description: **SubstationCost.py** - Created by Annika Eberle and Owen Roberts on Dec. 17, 2018 - Refactored by Parangat Bhaskar and Alicia Key on June 3, 2019 Calculates the costs associated with substations for land-based wind projects *(module is cu...
d7270ebe1c554293a9d36730d67ab555c071cb17
<|skeleton|> class SubstationCost: """**SubstationCost.py** - Created by Annika Eberle and Owen Roberts on Dec. 17, 2018 - Refactored by Parangat Bhaskar and Alicia Key on June 3, 2019 Calculates the costs associated with substations for land-based wind projects *(module is currently based on curve fit of empirical...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SubstationCost: """**SubstationCost.py** - Created by Annika Eberle and Owen Roberts on Dec. 17, 2018 - Refactored by Parangat Bhaskar and Alicia Key on June 3, 2019 Calculates the costs associated with substations for land-based wind projects *(module is currently based on curve fit of empirical data)* Get p...
the_stack_v2_python_sparse
wisdem/landbosse/model/SubstationCost.py
WISDEM/WISDEM
train
120
01cd4e1db7e8ae99266325317bf43a283b5a3c59
[ "self._client = None\npool = redis.ConnectionPool\nif blocking_pool:\n pool = redis.BlockingConnectionPool\nself.pool = pool(host=host, port=port, db=db, **kwargs)", "if self._client is None:\n self._client = redis.Redis(connection_pool=self.pool)\nreturn self._client" ]
<|body_start_0|> self._client = None pool = redis.ConnectionPool if blocking_pool: pool = redis.BlockingConnectionPool self.pool = pool(host=host, port=port, db=db, **kwargs) <|end_body_0|> <|body_start_1|> if self._client is None: self._client = redis.Re...
A shared REDIS client connection using a Connection Pool. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The REDIS host. Defaults to localhost. port (int, optional): The REDIS port. Defaul...
RedisClient
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RedisClient: """A shared REDIS client connection using a Connection Pool. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The REDIS host. Defaults to localhost. port ...
stack_v2_sparse_classes_10k_train_008260
1,504
permissive
[ { "docstring": "Initialize class properties", "name": "__init__", "signature": "def __init__(self, host='localhost', port=6379, db=0, blocking_pool=False, **kwargs)" }, { "docstring": "Return an instance of redis.client.Redis.", "name": "client", "signature": "def client(self)" } ]
2
stack_v2_sparse_classes_30k_train_002187
Implement the Python class `RedisClient` described below. Class description: A shared REDIS client connection using a Connection Pool. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The R...
Implement the Python class `RedisClient` described below. Class description: A shared REDIS client connection using a Connection Pool. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The R...
7cf04fec048fadc71ff851970045b8a587269ccf
<|skeleton|> class RedisClient: """A shared REDIS client connection using a Connection Pool. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The REDIS host. Defaults to localhost. port ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class RedisClient: """A shared REDIS client connection using a Connection Pool. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The REDIS host. Defaults to localhost. port (int, optiona...
the_stack_v2_python_sparse
tcex/key_value_store/redis_client.py
TpyoKnig/tcex
train
0
4c423dd8d29685f1f48ab7c9bbf263c25c054ef8
[ "ans = []\nif not intervals:\n return ans\nit = iter(sorted(intervals))\ncurr = next(it)\nfor x in it:\n if x[0] <= curr[1]:\n if x[1] > curr[1]:\n curr[1] = x[1]\n else:\n ans.append(curr)\n curr = x\nans.append(curr)\nreturn ans", "visited = set()\nans = []\nfor i, x in ...
<|body_start_0|> ans = [] if not intervals: return ans it = iter(sorted(intervals)) curr = next(it) for x in it: if x[0] <= curr[1]: if x[1] > curr[1]: curr[1] = x[1] else: ans.append(curr) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def merge_v1(self, intervals: List[List[int]]) -> List[List[int]]: """Sort. A simple method will take O(N^2), comparing each element with the other. If we sort the intervals first, it will be O(N log(N)) + O(N). Here we use the built-in sort method. Alternatively, we may write ...
stack_v2_sparse_classes_10k_train_008261
2,640
no_license
[ { "docstring": "Sort. A simple method will take O(N^2), comparing each element with the other. If we sort the intervals first, it will be O(N log(N)) + O(N). Here we use the built-in sort method. Alternatively, we may write our own sort method (like merge sort) and make some modifications.", "name": "merge_...
2
stack_v2_sparse_classes_30k_train_001565
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def merge_v1(self, intervals: List[List[int]]) -> List[List[int]]: Sort. A simple method will take O(N^2), comparing each element with the other. If we sort the intervals first, ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def merge_v1(self, intervals: List[List[int]]) -> List[List[int]]: Sort. A simple method will take O(N^2), comparing each element with the other. If we sort the intervals first, ...
97a2386f5e3adbd7138fd123810c3232bdf7f622
<|skeleton|> class Solution: def merge_v1(self, intervals: List[List[int]]) -> List[List[int]]: """Sort. A simple method will take O(N^2), comparing each element with the other. If we sort the intervals first, it will be O(N log(N)) + O(N). Here we use the built-in sort method. Alternatively, we may write ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def merge_v1(self, intervals: List[List[int]]) -> List[List[int]]: """Sort. A simple method will take O(N^2), comparing each element with the other. If we sort the intervals first, it will be O(N log(N)) + O(N). Here we use the built-in sort method. Alternatively, we may write our own sort m...
the_stack_v2_python_sparse
python3/sorting_and_search/merge_intervals.py
victorchu/algorithms
train
0
96ee618eeda7a3b9608ede99a7bc61fcefbf705d
[ "self.targets = [0 for i in range(target + 1)]\nself.new_nums = [0]\nwhile self.new_nums != []:\n self.nums = []\n for i in self.new_nums:\n for j in nums:\n a = i + j\n if a <= target:\n self.nums.append(a)\n self.targets[a] += 1\n self.new_nums =...
<|body_start_0|> self.targets = [0 for i in range(target + 1)] self.new_nums = [0] while self.new_nums != []: self.nums = [] for i in self.new_nums: for j in nums: a = i + j if a <= target: se...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def combinationSum4(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_0|> def combinationSum4_1(self, nums, target): """:type nums: List[int] :type target: int :rtype: int 52ms""" <|body_1|> def combinationSu...
stack_v2_sparse_classes_10k_train_008262
2,089
no_license
[ { "docstring": ":type nums: List[int] :type target: int :rtype: int", "name": "combinationSum4", "signature": "def combinationSum4(self, nums, target)" }, { "docstring": ":type nums: List[int] :type target: int :rtype: int 52ms", "name": "combinationSum4_1", "signature": "def combination...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def combinationSum4(self, nums, target): :type nums: List[int] :type target: int :rtype: int - def combinationSum4_1(self, nums, target): :type nums: List[int] :type target: int ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def combinationSum4(self, nums, target): :type nums: List[int] :type target: int :rtype: int - def combinationSum4_1(self, nums, target): :type nums: List[int] :type target: int ...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution: def combinationSum4(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_0|> def combinationSum4_1(self, nums, target): """:type nums: List[int] :type target: int :rtype: int 52ms""" <|body_1|> def combinationSu...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def combinationSum4(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" self.targets = [0 for i in range(target + 1)] self.new_nums = [0] while self.new_nums != []: self.nums = [] for i in self.new_nums: ...
the_stack_v2_python_sparse
CombinationSumIV_MID_377.py
953250587/leetcode-python
train
2
ef9af024a00c829bfb773d16dea0cd6cbb8fd4ee
[ "course_keys = value\nfor course in course_keys:\n try:\n CourseKey.from_string(course)\n except InvalidKeyError:\n raise serializers.ValidationError(f'Course key not valid: {course}')\nreturn value", "if attrs.get('cohorts'):\n if attrs['action'] != 'enroll':\n raise serializers.Val...
<|body_start_0|> course_keys = value for course in course_keys: try: CourseKey.from_string(course) except InvalidKeyError: raise serializers.ValidationError(f'Course key not valid: {course}') return value <|end_body_0|> <|body_start_1|> ...
Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations.
BulkEnrollmentSerializer
[ "AGPL-3.0-only", "AGPL-3.0-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BulkEnrollmentSerializer: """Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations.""" def validate_courses(self, value): """Check that each course key in list is valid.""" ...
stack_v2_sparse_classes_10k_train_008263
2,612
permissive
[ { "docstring": "Check that each course key in list is valid.", "name": "validate_courses", "signature": "def validate_courses(self, value)" }, { "docstring": "Check that the cohorts list is the same size as the courses list.", "name": "validate", "signature": "def validate(self, attrs)" ...
2
null
Implement the Python class `BulkEnrollmentSerializer` described below. Class description: Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations. Method signatures and docstrings: - def validate_courses(self, ...
Implement the Python class `BulkEnrollmentSerializer` described below. Class description: Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations. Method signatures and docstrings: - def validate_courses(self, ...
5809eaca7079a15ee56b0b7fcfea425337046c97
<|skeleton|> class BulkEnrollmentSerializer: """Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations.""" def validate_courses(self, value): """Check that each course key in list is valid.""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class BulkEnrollmentSerializer: """Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations.""" def validate_courses(self, value): """Check that each course key in list is valid.""" course...
the_stack_v2_python_sparse
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/bulk_enroll/serializers.py
luque/better-ways-of-thinking-about-software
train
3
26ee07307cb543a6aba562cddb82d4ad8aceab9d
[ "component_spc = kwargs['spc'] if 'spc' in kwargs else spc.SPC\nwx_panel.COMPONENT.__init__(self, parent=parent, resource=resource, spc=component_spc, context=context)\nolap_query_browser.iqOLAPQueryBrowserProto.__init__(self, *args, parent=parent, **kwargs)", "psp = self.getAttribute('olap_server')\nlog_func.deb...
<|body_start_0|> component_spc = kwargs['spc'] if 'spc' in kwargs else spc.SPC wx_panel.COMPONENT.__init__(self, parent=parent, resource=resource, spc=component_spc, context=context) olap_query_browser.iqOLAPQueryBrowserProto.__init__(self, *args, parent=parent, **kwargs) <|end_body_0|> <|body_...
OLAP server query browser component.
iqWxOLAPQueryBrowser
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class iqWxOLAPQueryBrowser: """OLAP server query browser component.""" def __init__(self, parent=None, resource=None, context=None, *args, **kwargs): """Standard component constructor. :param parent: Parent object. :param resource: Object resource dictionary. :param context: Context dictio...
stack_v2_sparse_classes_10k_train_008264
1,543
no_license
[ { "docstring": "Standard component constructor. :param parent: Parent object. :param resource: Object resource dictionary. :param context: Context dictionary.", "name": "__init__", "signature": "def __init__(self, parent=None, resource=None, context=None, *args, **kwargs)" }, { "docstring": "OLA...
3
stack_v2_sparse_classes_30k_train_006102
Implement the Python class `iqWxOLAPQueryBrowser` described below. Class description: OLAP server query browser component. Method signatures and docstrings: - def __init__(self, parent=None, resource=None, context=None, *args, **kwargs): Standard component constructor. :param parent: Parent object. :param resource: O...
Implement the Python class `iqWxOLAPQueryBrowser` described below. Class description: OLAP server query browser component. Method signatures and docstrings: - def __init__(self, parent=None, resource=None, context=None, *args, **kwargs): Standard component constructor. :param parent: Parent object. :param resource: O...
7550e242746cb2fb1219474463f8db21f8e3e114
<|skeleton|> class iqWxOLAPQueryBrowser: """OLAP server query browser component.""" def __init__(self, parent=None, resource=None, context=None, *args, **kwargs): """Standard component constructor. :param parent: Parent object. :param resource: Object resource dictionary. :param context: Context dictio...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class iqWxOLAPQueryBrowser: """OLAP server query browser component.""" def __init__(self, parent=None, resource=None, context=None, *args, **kwargs): """Standard component constructor. :param parent: Parent object. :param resource: Object resource dictionary. :param context: Context dictionary.""" ...
the_stack_v2_python_sparse
iq/components/wx_olap_query_browser/component.py
XHermitOne/iq_framework
train
1
01cda23f1541d885ff24899f2d840e19b88284b3
[ "result = []\nfor i in range(0, len(nums) + 1):\n result += self.combinationSolo(nums, i)\nreturn result", "nums = sorted(nums)\nif k == 0:\n return [[]]\nelif k == len(nums):\n return [nums]\nelif k == 1:\n result = []\n for i in nums:\n if [i] not in result:\n result.append([i])...
<|body_start_0|> result = [] for i in range(0, len(nums) + 1): result += self.combinationSolo(nums, i) return result <|end_body_0|> <|body_start_1|> nums = sorted(nums) if k == 0: return [[]] elif k == len(nums): return [nums] ...
Solution_A
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution_A: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: """With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back to list""" <|body_0|> def combinationSolo(self, nums: List[int], k: int) -> List[List[i...
stack_v2_sparse_classes_10k_train_008265
4,175
permissive
[ { "docstring": "With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back to list", "name": "subsetsWithDup", "signature": "def subsetsWithDup(self, nums: List[int]) -> List[List[int]]" }, { "docstring": "Helper for A1, refer to LC077, modify ...
2
stack_v2_sparse_classes_30k_train_006767
Implement the Python class `Solution_A` described below. Class description: Implement the Solution_A class. Method signatures and docstrings: - def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back t...
Implement the Python class `Solution_A` described below. Class description: Implement the Solution_A class. Method signatures and docstrings: - def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back t...
143422321cbc3715ca08f6c3af8f960a55887ced
<|skeleton|> class Solution_A: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: """With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back to list""" <|body_0|> def combinationSolo(self, nums: List[int], k: int) -> List[List[i...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution_A: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: """With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back to list""" result = [] for i in range(0, len(nums) + 1): result += self.combinationSol...
the_stack_v2_python_sparse
LeetCode/LC090_subsets_ii.py
jxie0755/Learning_Python
train
0
271522da66065e77ba710d952907f78a75fc3536
[ "if not nums:\n return 0\ncum_sum = [0]\nfor num in nums:\n cum_sum.append(cum_sum[-1] + num)\nres = 0\nfor i in range(len(cum_sum) - 1):\n for j in range(i + 1, len(cum_sum)):\n if cum_sum[j] - cum_sum[i] == k:\n res += 1\nreturn res", "if not nums:\n return 0\ncounts_map = {0: 1}\n...
<|body_start_0|> if not nums: return 0 cum_sum = [0] for num in nums: cum_sum.append(cum_sum[-1] + num) res = 0 for i in range(len(cum_sum) - 1): for j in range(i + 1, len(cum_sum)): if cum_sum[j] - cum_sum[i] == k: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def subarray_sum(self, nums: List[int], k: int) -> int: """Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is still not fast enough to pass the test.""" <|body_0|> def subarray_sum_hash_map(self, nu...
stack_v2_sparse_classes_10k_train_008266
1,152
no_license
[ { "docstring": "Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is still not fast enough to pass the test.", "name": "subarray_sum", "signature": "def subarray_sum(self, nums: List[int], k: int) -> int" }, { "docstring": "O(n) so...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def subarray_sum(self, nums: List[int], k: int) -> int: Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is stil...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def subarray_sum(self, nums: List[int], k: int) -> int: Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is stil...
5625e6396b746255f3343253c75447ead95879c7
<|skeleton|> class Solution: def subarray_sum(self, nums: List[int], k: int) -> int: """Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is still not fast enough to pass the test.""" <|body_0|> def subarray_sum_hash_map(self, nu...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def subarray_sum(self, nums: List[int], k: int) -> int: """Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is still not fast enough to pass the test.""" if not nums: return 0 cum_sum = [0] ...
the_stack_v2_python_sparse
560_subarray_sum_equals_k/solution.py
FluffyFu/Leetcode
train
0
23a97525b6c1ca0734babed8602ad52db72ca9b7
[ "if A is None or B is None:\n return None\nm, n, l = (len(A), len(A[0]), len(B[0]))\nif len(B) != n:\n raise Exception(\"A's column number must be equal to B's row number.\")\nC = [[0 for _ in range(l)] for _ in range(m)]\nfor i, row in enumerate(A):\n for k, eleA in enumerate(row):\n if eleA:\n ...
<|body_start_0|> if A is None or B is None: return None m, n, l = (len(A), len(A[0]), len(B[0])) if len(B) != n: raise Exception("A's column number must be equal to B's row number.") C = [[0 for _ in range(l)] for _ in range(m)] for i, row in enumerate(A):...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def multiply(self, A, B): """:type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]""" <|body_0|> def multiply2(self, A, B): """:type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_10k_train_008267
5,317
no_license
[ { "docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]", "name": "multiply", "signature": "def multiply(self, A, B)" }, { "docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]", "name": "multiply2", "signature": "def mu...
2
stack_v2_sparse_classes_30k_train_000719
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def multiply(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] - def multiply2(self, A, B): :type A: List[List[int]] :type B: List[List[int]]...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def multiply(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] - def multiply2(self, A, B): :type A: List[List[int]] :type B: List[List[int]]...
4c0cfe857f5d78a44c1a3bfb2571d72da4911d97
<|skeleton|> class Solution: def multiply(self, A, B): """:type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]""" <|body_0|> def multiply2(self, A, B): """:type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def multiply(self, A, B): """:type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]""" if A is None or B is None: return None m, n, l = (len(A), len(A[0]), len(B[0])) if len(B) != n: raise Exception("A's column number must be...
the_stack_v2_python_sparse
311-SparseMatrixMultiplication.py
minseoch/algorithm
train
0
d0dc059f717ff4cd9b1e0e706d4f6a8f211cd88e
[ "jobs = sorted(zip(startTime, endTime, profit), key=lambda v: v[1])\ndp = [[0, 0]]\nfor start, end, profit in jobs:\n i = bisect.bisect(dp, [start + 1]) - 1\n if dp[i][1] + profit > dp[-1][1]:\n dp.append([end, dp[i][1] + profit])\nreturn dp[-1][1]", "jobs = sorted(zip(startTime, endTime, profit), ke...
<|body_start_0|> jobs = sorted(zip(startTime, endTime, profit), key=lambda v: v[1]) dp = [[0, 0]] for start, end, profit in jobs: i = bisect.bisect(dp, [start + 1]) - 1 if dp[i][1] + profit > dp[-1][1]: dp.append([end, dp[i][1] + profit]) return dp...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def jobScheduling(self, startTime: list[int], endTime: list[int], profit: list[int]) -> int: """https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/409009/JavaC%2B%2BPython-DP-Solution dynamic programming Time O(NlogN) for sorting Time O(NlogN) for binary sea...
stack_v2_sparse_classes_10k_train_008268
2,115
no_license
[ { "docstring": "https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/409009/JavaC%2B%2BPython-DP-Solution dynamic programming Time O(NlogN) for sorting Time O(NlogN) for binary search for each job Space O(N)", "name": "jobScheduling", "signature": "def jobScheduling(self, startTime: li...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def jobScheduling(self, startTime: list[int], endTime: list[int], profit: list[int]) -> int: https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/409009/JavaC%2...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def jobScheduling(self, startTime: list[int], endTime: list[int], profit: list[int]) -> int: https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/409009/JavaC%2...
e50dc0642f087f37ab3234390be3d8a0ed48fe62
<|skeleton|> class Solution: def jobScheduling(self, startTime: list[int], endTime: list[int], profit: list[int]) -> int: """https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/409009/JavaC%2B%2BPython-DP-Solution dynamic programming Time O(NlogN) for sorting Time O(NlogN) for binary sea...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def jobScheduling(self, startTime: list[int], endTime: list[int], profit: list[int]) -> int: """https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/409009/JavaC%2B%2BPython-DP-Solution dynamic programming Time O(NlogN) for sorting Time O(NlogN) for binary search for each j...
the_stack_v2_python_sparse
Leetcode/ByteDance/1235. Maximum Profit in Job Scheduling.py
brlala/Educative-Grokking-Coding-Exercise
train
3
2b95f1484a7e6eadfcceb66050428b71f7794869
[ "res = 0\nfor i in range(32):\n if n & 1 << i != 0:\n res += 1\nreturn res", "res = 0\nwhile n != 0:\n n &= n - 1\n res += 1\nreturn res" ]
<|body_start_0|> res = 0 for i in range(32): if n & 1 << i != 0: res += 1 return res <|end_body_0|> <|body_start_1|> res = 0 while n != 0: n &= n - 1 res += 1 return res <|end_body_1|>
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def hammingWeight(self, n): """:type n: int :rtype: int""" <|body_0|> def hammingWeight0(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = 0 for i in range(32): if n & 1 << i !=...
stack_v2_sparse_classes_10k_train_008269
863
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "hammingWeight", "signature": "def hammingWeight(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "hammingWeight0", "signature": "def hammingWeight0(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_004584
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hammingWeight(self, n): :type n: int :rtype: int - def hammingWeight0(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hammingWeight(self, n): :type n: int :rtype: int - def hammingWeight0(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def hammingWeight(self, n): ...
6e18c5d257840489cc3fb1079ae3804c743982a4
<|skeleton|> class Solution: def hammingWeight(self, n): """:type n: int :rtype: int""" <|body_0|> def hammingWeight0(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def hammingWeight(self, n): """:type n: int :rtype: int""" res = 0 for i in range(32): if n & 1 << i != 0: res += 1 return res def hammingWeight0(self, n): """:type n: int :rtype: int""" res = 0 while n != 0: ...
the_stack_v2_python_sparse
剑指 Offer 15. 二进制中1的个数.py
yangyuxiang1996/leetcode
train
0
403b4b9ba23ba10354f7848c7a985f2d35c59b54
[ "details = {}\nselector = 'table > tbody > tr'\nfor resource, unit, used in root.cssselect(selector):\n name = resource.findtext('strong').strip()\n details[name] = (used.text.strip(), unit.text.strip())\nreturn details", "events = []\nselector = '#ae-billing-logs-table > tbody > tr'\nfor date_elt, event_el...
<|body_start_0|> details = {} selector = 'table > tbody > tr' for resource, unit, used in root.cssselect(selector): name = resource.findtext('strong').strip() details[name] = (used.text.strip(), unit.text.strip()) return details <|end_body_0|> <|body_start_1|> ...
An API for the contents of /billing/history as structured data.
BillingHistory
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BillingHistory: """An API for the contents of /billing/history as structured data.""" def _usage_report_dict(self, root): """Extract usage report details from the element that contains the table with columns resource, unit, used.""" <|body_0|> def event_dicts(self): ...
stack_v2_sparse_classes_10k_train_008270
15,505
no_license
[ { "docstring": "Extract usage report details from the element that contains the table with columns resource, unit, used.", "name": "_usage_report_dict", "signature": "def _usage_report_dict(self, root)" }, { "docstring": "Information about each row in the billing history table. Entries match the...
2
stack_v2_sparse_classes_30k_train_002332
Implement the Python class `BillingHistory` described below. Class description: An API for the contents of /billing/history as structured data. Method signatures and docstrings: - def _usage_report_dict(self, root): Extract usage report details from the element that contains the table with columns resource, unit, use...
Implement the Python class `BillingHistory` described below. Class description: An API for the contents of /billing/history as structured data. Method signatures and docstrings: - def _usage_report_dict(self, root): Extract usage report details from the element that contains the table with columns resource, unit, use...
c4ad2ad67b497ce411a9e5d6d6db407ee304491f
<|skeleton|> class BillingHistory: """An API for the contents of /billing/history as structured data.""" def _usage_report_dict(self, root): """Extract usage report details from the element that contains the table with columns resource, unit, used.""" <|body_0|> def event_dicts(self): ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class BillingHistory: """An API for the contents of /billing/history as structured data.""" def _usage_report_dict(self, root): """Extract usage report details from the element that contains the table with columns resource, unit, used.""" details = {} selector = 'table > tbody > tr' ...
the_stack_v2_python_sparse
src/gae_dashboard/parsers.py
summer-liu/analytics
train
1
b8af26faeb4444367f05b43d3ffe9fba193942e1
[ "obj = context.object\nif obj is None:\n return False\nreturn all([bool(obj), obj.type == 'MESH', obj.mode == 'EDIT'])", "scene = context.scene\npg = scene.pdt_pg\nobj = bpy.context.view_layer.objects.active\nif obj is None:\n self.report({'ERROR'}, PDT_ERR_NO_ACT_OBJ)\n return {'FINISHED'}\nif obj.mode ...
<|body_start_0|> obj = context.object if obj is None: return False return all([bool(obj), obj.type == 'MESH', obj.mode == 'EDIT']) <|end_body_0|> <|body_start_1|> scene = context.scene pg = scene.pdt_pg obj = bpy.context.view_layer.objects.active if o...
Scale Selected Vertices about Pivot Point
PDT_OT_ViewPlaneScale
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PDT_OT_ViewPlaneScale: """Scale Selected Vertices about Pivot Point""" def poll(cls, context): """Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing.""" <|body_0|> def execute(self, context): """Scales Selected Vertices about Pivot...
stack_v2_sparse_classes_10k_train_008271
13,734
permissive
[ { "docstring": "Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing.", "name": "poll", "signature": "def poll(cls, context)" }, { "docstring": "Scales Selected Vertices about Pivot Point. Note: Scales any selected vertices about the Pivot Point in View Oriented coo...
2
null
Implement the Python class `PDT_OT_ViewPlaneScale` described below. Class description: Scale Selected Vertices about Pivot Point Method signatures and docstrings: - def poll(cls, context): Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing. - def execute(self, context): Scales Selected...
Implement the Python class `PDT_OT_ViewPlaneScale` described below. Class description: Scale Selected Vertices about Pivot Point Method signatures and docstrings: - def poll(cls, context): Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing. - def execute(self, context): Scales Selected...
4d5c304878c1e0018d97c1b07bcaa3981632265a
<|skeleton|> class PDT_OT_ViewPlaneScale: """Scale Selected Vertices about Pivot Point""" def poll(cls, context): """Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing.""" <|body_0|> def execute(self, context): """Scales Selected Vertices about Pivot...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PDT_OT_ViewPlaneScale: """Scale Selected Vertices about Pivot Point""" def poll(cls, context): """Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing.""" obj = context.object if obj is None: return False return all([bool(obj), obj...
the_stack_v2_python_sparse
src/bpy/3.6/scripts/addons/precision_drawing_tools/pdt_pivot_point.py
RnoB/3DVisualSwarm
train
0
3c44016df7badbd9f28932a29b14369687079c32
[ "super(DCGAN_D, self).__init__()\nself.ngpu = ngpu\nself.use_sigmoid = use_sigmoid\nassert isize % 16 == 0, 'isize has to be a multiple of 16'\nmain = nn.Sequential()\nmain.add_module('initial_conv_{0}-{1}'.format(nc, ndf), nn.Conv2d(nc, ndf, 4, 2, 1, bias=False))\nmain.add_module('initial_relu_{0}'.format(ndf), nn...
<|body_start_0|> super(DCGAN_D, self).__init__() self.ngpu = ngpu self.use_sigmoid = use_sigmoid assert isize % 16 == 0, 'isize has to be a multiple of 16' main = nn.Sequential() main.add_module('initial_conv_{0}-{1}'.format(nc, ndf), nn.Conv2d(nc, ndf, 4, 2, 1, bias=Fals...
DCGAN Discriminator.
DCGAN_D
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DCGAN_D: """DCGAN Discriminator.""" def __init__(self, isize, nz, nc, ndf, ngpu, n_extra_layers=0, use_sigmoid=True, norm=nn.BatchNorm2d): """Constructor.""" <|body_0|> def forward(self, input): """Forward method.""" <|body_1|> <|end_skeleton|> <|body_s...
stack_v2_sparse_classes_10k_train_008272
34,675
permissive
[ { "docstring": "Constructor.", "name": "__init__", "signature": "def __init__(self, isize, nz, nc, ndf, ngpu, n_extra_layers=0, use_sigmoid=True, norm=nn.BatchNorm2d)" }, { "docstring": "Forward method.", "name": "forward", "signature": "def forward(self, input)" } ]
2
stack_v2_sparse_classes_30k_test_000277
Implement the Python class `DCGAN_D` described below. Class description: DCGAN Discriminator. Method signatures and docstrings: - def __init__(self, isize, nz, nc, ndf, ngpu, n_extra_layers=0, use_sigmoid=True, norm=nn.BatchNorm2d): Constructor. - def forward(self, input): Forward method.
Implement the Python class `DCGAN_D` described below. Class description: DCGAN Discriminator. Method signatures and docstrings: - def __init__(self, isize, nz, nc, ndf, ngpu, n_extra_layers=0, use_sigmoid=True, norm=nn.BatchNorm2d): Constructor. - def forward(self, input): Forward method. <|skeleton|> class DCGAN_D:...
e1e4a8d9a2ab51c2108a4d167bc37fab101f0c2c
<|skeleton|> class DCGAN_D: """DCGAN Discriminator.""" def __init__(self, isize, nz, nc, ndf, ngpu, n_extra_layers=0, use_sigmoid=True, norm=nn.BatchNorm2d): """Constructor.""" <|body_0|> def forward(self, input): """Forward method.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class DCGAN_D: """DCGAN Discriminator.""" def __init__(self, isize, nz, nc, ndf, ngpu, n_extra_layers=0, use_sigmoid=True, norm=nn.BatchNorm2d): """Constructor.""" super(DCGAN_D, self).__init__() self.ngpu = ngpu self.use_sigmoid = use_sigmoid assert isize % 16 == 0, 'is...
the_stack_v2_python_sparse
diffrend/torch/GAN/twin_networks.py
sainatarajan/pix2shape
train
0
1a626ca2792e24235b8194e7009cc965ac169a4f
[ "self.num_map = {}\nfor i in range(len(nums)):\n if nums[i] not in self.num_map:\n self.num_map[nums[i]] = [i]\n else:\n self.num_map[nums[i]].append(i)", "if target in self.num_map:\n high = len(self.num_map[target])\n import numpy as np\n index = np.random.randint(0, high)\n retu...
<|body_start_0|> self.num_map = {} for i in range(len(nums)): if nums[i] not in self.num_map: self.num_map[nums[i]] = [i] else: self.num_map[nums[i]].append(i) <|end_body_0|> <|body_start_1|> if target in self.num_map: high = l...
Solution_1
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution_1: def __init__(self, nums): """:type nums: List[int]""" <|body_0|> def pick(self, target): """:type target: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.num_map = {} for i in range(len(nums)): if...
stack_v2_sparse_classes_10k_train_008273
1,800
no_license
[ { "docstring": ":type nums: List[int]", "name": "__init__", "signature": "def __init__(self, nums)" }, { "docstring": ":type target: int :rtype: int", "name": "pick", "signature": "def pick(self, target)" } ]
2
null
Implement the Python class `Solution_1` described below. Class description: Implement the Solution_1 class. Method signatures and docstrings: - def __init__(self, nums): :type nums: List[int] - def pick(self, target): :type target: int :rtype: int
Implement the Python class `Solution_1` described below. Class description: Implement the Solution_1 class. Method signatures and docstrings: - def __init__(self, nums): :type nums: List[int] - def pick(self, target): :type target: int :rtype: int <|skeleton|> class Solution_1: def __init__(self, nums): ...
176cc1db3291843fb068f06d0180766dd8c3122c
<|skeleton|> class Solution_1: def __init__(self, nums): """:type nums: List[int]""" <|body_0|> def pick(self, target): """:type target: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution_1: def __init__(self, nums): """:type nums: List[int]""" self.num_map = {} for i in range(len(nums)): if nums[i] not in self.num_map: self.num_map[nums[i]] = [i] else: self.num_map[nums[i]].append(i) def pick(self, t...
the_stack_v2_python_sparse
2019/sampling/random_pick_index_398.py
yehongyu/acode
train
0
1551cf21b02340673adabca151988a906dc0f1ae
[ "length = len(array)\nif length < 2:\n return array\nmiddle = length // 2\nleft = Merge.merge_sort(array[:middle])\nright = Merge.merge_sort(array[middle:])\nreturn Merge.merge(left, right)", "new = []\nleft_index, right_index = (0, 0)\nlen_left, len_right = (len(left), len(right))\nwhile left_index < len_left...
<|body_start_0|> length = len(array) if length < 2: return array middle = length // 2 left = Merge.merge_sort(array[:middle]) right = Merge.merge_sort(array[middle:]) return Merge.merge(left, right) <|end_body_0|> <|body_start_1|> new = [] lef...
Contains various merge sort implementations. http://en.wikipedia.org/wiki/Merge_sort
Merge
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Merge: """Contains various merge sort implementations. http://en.wikipedia.org/wiki/Merge_sort""" def merge_sort(array): """A basic implementation of merge sort. Despite enjoying a lower worst case time complexity, quick sort often outperforms merge sort in practical cases. Uses the ...
stack_v2_sparse_classes_10k_train_008274
14,101
no_license
[ { "docstring": "A basic implementation of merge sort. Despite enjoying a lower worst case time complexity, quick sort often outperforms merge sort in practical cases. Uses the helper function merge(). Inplace: No Time complexity: all O(nlogn)", "name": "merge_sort", "signature": "def merge_sort(array)" ...
2
stack_v2_sparse_classes_30k_train_003902
Implement the Python class `Merge` described below. Class description: Contains various merge sort implementations. http://en.wikipedia.org/wiki/Merge_sort Method signatures and docstrings: - def merge_sort(array): A basic implementation of merge sort. Despite enjoying a lower worst case time complexity, quick sort o...
Implement the Python class `Merge` described below. Class description: Contains various merge sort implementations. http://en.wikipedia.org/wiki/Merge_sort Method signatures and docstrings: - def merge_sort(array): A basic implementation of merge sort. Despite enjoying a lower worst case time complexity, quick sort o...
c88059dc66297af577ad2b8afa4e0ac0ad622915
<|skeleton|> class Merge: """Contains various merge sort implementations. http://en.wikipedia.org/wiki/Merge_sort""" def merge_sort(array): """A basic implementation of merge sort. Despite enjoying a lower worst case time complexity, quick sort often outperforms merge sort in practical cases. Uses the ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Merge: """Contains various merge sort implementations. http://en.wikipedia.org/wiki/Merge_sort""" def merge_sort(array): """A basic implementation of merge sort. Despite enjoying a lower worst case time complexity, quick sort often outperforms merge sort in practical cases. Uses the helper functi...
the_stack_v2_python_sparse
codes/BuildLinks1.02/test_input/sort_codes/pysort.py
DaHuO/Supergraph
train
2
90fd34ebfe894eeea4cc242176999a0416d41da3
[ "if hasattr(self, 'set_model_params'):\n set_model_param_method = getattr(self, 'set_model_params')\n args, varargs, kw, default = getargspec_no_self(set_model_param_method)\n if varargs is not None:\n raise RuntimeError(\"Models should always specify their parameters in the signature of their set_m...
<|body_start_0|> if hasattr(self, 'set_model_params'): set_model_param_method = getattr(self, 'set_model_params') args, varargs, kw, default = getargspec_no_self(set_model_param_method) if varargs is not None: raise RuntimeError("Models should always specify t...
Base class for Chainsaws models This class is inspired by sklearn's BaseEstimator class. However, we define parameter names not by the current class' __init__ but have to announce them. This allows us to also remember the parameters of model superclasses. This class can be mixed with Chainsaw and sklearn Estimators.
Model
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Model: """Base class for Chainsaws models This class is inspired by sklearn's BaseEstimator class. However, we define parameter names not by the current class' __init__ but have to announce them. This allows us to also remember the parameters of model superclasses. This class can be mixed with Ch...
stack_v2_sparse_classes_10k_train_008275
4,319
no_license
[ { "docstring": "Get parameter names for the model", "name": "_get_model_param_names", "signature": "def _get_model_param_names(self)" }, { "docstring": "Update given model parameter if they are set to specific values", "name": "update_model_params", "signature": "def update_model_params(...
3
stack_v2_sparse_classes_30k_train_003361
Implement the Python class `Model` described below. Class description: Base class for Chainsaws models This class is inspired by sklearn's BaseEstimator class. However, we define parameter names not by the current class' __init__ but have to announce them. This allows us to also remember the parameters of model superc...
Implement the Python class `Model` described below. Class description: Base class for Chainsaws models This class is inspired by sklearn's BaseEstimator class. However, we define parameter names not by the current class' __init__ but have to announce them. This allows us to also remember the parameters of model superc...
3c67aeb9a4ea26b8304585a70761a2983db19332
<|skeleton|> class Model: """Base class for Chainsaws models This class is inspired by sklearn's BaseEstimator class. However, we define parameter names not by the current class' __init__ but have to announce them. This allows us to also remember the parameters of model superclasses. This class can be mixed with Ch...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Model: """Base class for Chainsaws models This class is inspired by sklearn's BaseEstimator class. However, we define parameter names not by the current class' __init__ but have to announce them. This allows us to also remember the parameters of model superclasses. This class can be mixed with Chainsaw and sk...
the_stack_v2_python_sparse
chainsaw/base/model.py
markovmodel/coordinates
train
0
09108311ac2bdb88b0447bf3bee91a5ed03f0a3c
[ "if uid == 0:\n user = User_Info.objects.get(email=request.session.get('login'))\nelse:\n user = User_Info.objects.filter(id=uid)\n if not user.exists():\n return JsonResponse({'status': False, 'err': '用户不存在'}, status=404)\n user = user[0]\narticles = Article.objects.filter(author=user)\nmarkets ...
<|body_start_0|> if uid == 0: user = User_Info.objects.get(email=request.session.get('login')) else: user = User_Info.objects.filter(id=uid) if not user.exists(): return JsonResponse({'status': False, 'err': '用户不存在'}, status=404) user = use...
UserDashBoardView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserDashBoardView: def get(self, request, uid=0): """用户控制台 :param request: :return:""" <|body_0|> def put(self, request): """用户修改信息 :param request: :return:""" <|body_1|> def post(self, request): """新增/更换头像 :param request: :return:""" <|b...
stack_v2_sparse_classes_10k_train_008276
5,399
no_license
[ { "docstring": "用户控制台 :param request: :return:", "name": "get", "signature": "def get(self, request, uid=0)" }, { "docstring": "用户修改信息 :param request: :return:", "name": "put", "signature": "def put(self, request)" }, { "docstring": "新增/更换头像 :param request: :return:", "name":...
3
stack_v2_sparse_classes_30k_train_001703
Implement the Python class `UserDashBoardView` described below. Class description: Implement the UserDashBoardView class. Method signatures and docstrings: - def get(self, request, uid=0): 用户控制台 :param request: :return: - def put(self, request): 用户修改信息 :param request: :return: - def post(self, request): 新增/更换头像 :para...
Implement the Python class `UserDashBoardView` described below. Class description: Implement the UserDashBoardView class. Method signatures and docstrings: - def get(self, request, uid=0): 用户控制台 :param request: :return: - def put(self, request): 用户修改信息 :param request: :return: - def post(self, request): 新增/更换头像 :para...
526dea540048fc92260bce611c520c50af744e0b
<|skeleton|> class UserDashBoardView: def get(self, request, uid=0): """用户控制台 :param request: :return:""" <|body_0|> def put(self, request): """用户修改信息 :param request: :return:""" <|body_1|> def post(self, request): """新增/更换头像 :param request: :return:""" <|b...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class UserDashBoardView: def get(self, request, uid=0): """用户控制台 :param request: :return:""" if uid == 0: user = User_Info.objects.get(email=request.session.get('login')) else: user = User_Info.objects.filter(id=uid) if not user.exists(): r...
the_stack_v2_python_sparse
apps/account/views/userInfo/userInfo.py
DICKQI/ALGYunXS
train
0
54d0880a9f717d6c635f670547c351655ba950b2
[ "Serializable._init(self, locals())\nsuper().__init__(min_rollouts=min_rollouts, min_steps=min_steps)\nself.env = env\nself.policy = policy\nself.bernoulli_reset = bernoulli_reset\nif self.policy.device == 'cuda':\n mp.set_start_method('spawn', force=True)\nself.pool = SamplerPool(num_envs)\nif seed is not None:...
<|body_start_0|> Serializable._init(self, locals()) super().__init__(min_rollouts=min_rollouts, min_steps=min_steps) self.env = env self.policy = policy self.bernoulli_reset = bernoulli_reset if self.policy.device == 'cuda': mp.set_start_method('spawn', force=...
Class for sampling from multiple environments in parallel
ParallelSampler
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParallelSampler: """Class for sampling from multiple environments in parallel""" def __init__(self, env, policy, num_envs: int, *, min_rollouts: int=None, min_steps: int=None, bernoulli_reset: bool=None, seed: int=None): """Constructor :param env: environment to sample from :param po...
stack_v2_sparse_classes_10k_train_008277
4,523
permissive
[ { "docstring": "Constructor :param env: environment to sample from :param policy: policy to act in the environment (can also be an exploration strategy) :param num_envs: number of parallel samplers :param min_rollouts: minimum number of complete rollouts to sample. :param min_steps: minimum total number of step...
3
null
Implement the Python class `ParallelSampler` described below. Class description: Class for sampling from multiple environments in parallel Method signatures and docstrings: - def __init__(self, env, policy, num_envs: int, *, min_rollouts: int=None, min_steps: int=None, bernoulli_reset: bool=None, seed: int=None): Con...
Implement the Python class `ParallelSampler` described below. Class description: Class for sampling from multiple environments in parallel Method signatures and docstrings: - def __init__(self, env, policy, num_envs: int, *, min_rollouts: int=None, min_steps: int=None, bernoulli_reset: bool=None, seed: int=None): Con...
a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5
<|skeleton|> class ParallelSampler: """Class for sampling from multiple environments in parallel""" def __init__(self, env, policy, num_envs: int, *, min_rollouts: int=None, min_steps: int=None, bernoulli_reset: bool=None, seed: int=None): """Constructor :param env: environment to sample from :param po...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ParallelSampler: """Class for sampling from multiple environments in parallel""" def __init__(self, env, policy, num_envs: int, *, min_rollouts: int=None, min_steps: int=None, bernoulli_reset: bool=None, seed: int=None): """Constructor :param env: environment to sample from :param policy: policy ...
the_stack_v2_python_sparse
Pyrado/pyrado/sampling/parallel_sampler.py
jacarvalho/SimuRLacra
train
0
03d8b6ef9cd5e1ef1e2c94ecd528b286ebc3e9a6
[ "m = super(RecipeIngredientForm, self).save(commit=False)\ningredient_name = self.cleaned_data['ingredient_name']\nunit_name = self.cleaned_data['unit_name']\noptional = self.cleaned_data['optional']\ningredient = Ingredient.objects.get_or_create(name__iexact=ingredient_name, defaults={'name': ingredient_name, 'slu...
<|body_start_0|> m = super(RecipeIngredientForm, self).save(commit=False) ingredient_name = self.cleaned_data['ingredient_name'] unit_name = self.cleaned_data['unit_name'] optional = self.cleaned_data['optional'] ingredient = Ingredient.objects.get_or_create(name__iexact=ingredie...
A class that defines the form for submission of ingredients associated with a recipe.
RecipeIngredientForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RecipeIngredientForm: """A class that defines the form for submission of ingredients associated with a recipe.""" def save(self, commit=True): """An overwrite of the form save method that parses the ingredients, units and optional fields. Keyword arguments: self -- the RecipeIngredie...
stack_v2_sparse_classes_10k_train_008278
4,228
no_license
[ { "docstring": "An overwrite of the form save method that parses the ingredients, units and optional fields. Keyword arguments: self -- the RecipeIngredientForm instance commit -- whether the changes to the form should be committed", "name": "save", "signature": "def save(self, commit=True)" }, { ...
2
stack_v2_sparse_classes_30k_train_006164
Implement the Python class `RecipeIngredientForm` described below. Class description: A class that defines the form for submission of ingredients associated with a recipe. Method signatures and docstrings: - def save(self, commit=True): An overwrite of the form save method that parses the ingredients, units and optio...
Implement the Python class `RecipeIngredientForm` described below. Class description: A class that defines the form for submission of ingredients associated with a recipe. Method signatures and docstrings: - def save(self, commit=True): An overwrite of the form save method that parses the ingredients, units and optio...
51396b214a601f5a9cf80e1de3755ab5ebcf6d2e
<|skeleton|> class RecipeIngredientForm: """A class that defines the form for submission of ingredients associated with a recipe.""" def save(self, commit=True): """An overwrite of the form save method that parses the ingredients, units and optional fields. Keyword arguments: self -- the RecipeIngredie...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class RecipeIngredientForm: """A class that defines the form for submission of ingredients associated with a recipe.""" def save(self, commit=True): """An overwrite of the form save method that parses the ingredients, units and optional fields. Keyword arguments: self -- the RecipeIngredientForm instan...
the_stack_v2_python_sparse
recipes/forms.py
kgodey/Bendakai
train
6
de722b02ff25e868292b41a6612bee790b4a5636
[ "self.parent = parent\nself.name = name\nself._unix_name = UnixName(self.name)\nself._unix_name_used = False\nself.origin = origin\nself.simple_name = _StripNamespace(self.name, namespace)\nself.description = json.get('description', None)\nself.optional = json.get('optional', None)\nself.instance_of = json.get('isI...
<|body_start_0|> self.parent = parent self.name = name self._unix_name = UnixName(self.name) self._unix_name_used = False self.origin = origin self.simple_name = _StripNamespace(self.name, namespace) self.description = json.get('description', None) self.op...
A property of a type OR a parameter to a function. Properties: - |name| name of the property as in the json. This shouldn't change since it is the key used to access Value::Dict - |unix_name| the unix_style_name of the property. Used as variable name - |optional| a boolean representing whether the property is optional ...
Property
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Property: """A property of a type OR a parameter to a function. Properties: - |name| name of the property as in the json. This shouldn't change since it is the key used to access Value::Dict - |unix_name| the unix_style_name of the property. Used as variable name - |optional| a boolean representi...
stack_v2_sparse_classes_10k_train_008279
31,957
permissive
[ { "docstring": "Creates a Property from JSON.", "name": "__init__", "signature": "def __init__(self, parent, name, json, namespace, origin)" }, { "docstring": "Gets the property's unix_name. Raises AttributeError if not set.", "name": "GetUnixName", "signature": "def GetUnixName(self)" ...
3
stack_v2_sparse_classes_30k_train_000023
Implement the Python class `Property` described below. Class description: A property of a type OR a parameter to a function. Properties: - |name| name of the property as in the json. This shouldn't change since it is the key used to access Value::Dict - |unix_name| the unix_style_name of the property. Used as variable...
Implement the Python class `Property` described below. Class description: A property of a type OR a parameter to a function. Properties: - |name| name of the property as in the json. This shouldn't change since it is the key used to access Value::Dict - |unix_name| the unix_style_name of the property. Used as variable...
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
<|skeleton|> class Property: """A property of a type OR a parameter to a function. Properties: - |name| name of the property as in the json. This shouldn't change since it is the key used to access Value::Dict - |unix_name| the unix_style_name of the property. Used as variable name - |optional| a boolean representi...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Property: """A property of a type OR a parameter to a function. Properties: - |name| name of the property as in the json. This shouldn't change since it is the key used to access Value::Dict - |unix_name| the unix_style_name of the property. Used as variable name - |optional| a boolean representing whether th...
the_stack_v2_python_sparse
tools/json_schema_compiler/model.py
chromium/chromium
train
17,408
c0d1df093f133e1bbddcdee6f5fd57057ba28aa4
[ "super(SepConv, self).__init__()\nself.dconv = nn.Conv2d(in_channels, in_channels * filters, kernel_size, dilation=dilation, groups=in_channels)\nself.pconv = nn.Conv2d(in_channels * filters, out_channels, kernel_size=1)\nself.padding = dilation[0] * (kernel_size[0] - 1)", "x = F.pad(input, [0, 0, self.padding, 0...
<|body_start_0|> super(SepConv, self).__init__() self.dconv = nn.Conv2d(in_channels, in_channels * filters, kernel_size, dilation=dilation, groups=in_channels) self.pconv = nn.Conv2d(in_channels * filters, out_channels, kernel_size=1) self.padding = dilation[0] * (kernel_size[0] - 1) <|e...
SepConv
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SepConv: def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)): """:param kernel_size (time, frequency)""" <|body_0|> def forward(self, input): """input: [B, C, T, F]""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_10k_train_008280
14,384
permissive
[ { "docstring": ":param kernel_size (time, frequency)", "name": "__init__", "signature": "def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1))" }, { "docstring": "input: [B, C, T, F]", "name": "forward", "signature": "def forward(self, input)" } ]
2
null
Implement the Python class `SepConv` described below. Class description: Implement the SepConv class. Method signatures and docstrings: - def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)): :param kernel_size (time, frequency) - def forward(self, input): input: [B, C, T, F]
Implement the Python class `SepConv` described below. Class description: Implement the SepConv class. Method signatures and docstrings: - def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)): :param kernel_size (time, frequency) - def forward(self, input): input: [B, C, T, F] <...
8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6
<|skeleton|> class SepConv: def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)): """:param kernel_size (time, frequency)""" <|body_0|> def forward(self, input): """input: [B, C, T, F]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SepConv: def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)): """:param kernel_size (time, frequency)""" super(SepConv, self).__init__() self.dconv = nn.Conv2d(in_channels, in_channels * filters, kernel_size, dilation=dilation, groups=in_channels...
the_stack_v2_python_sparse
ai/modelscope/modelscope/models/audio/aec/layers/uni_deep_fsmn.py
alldatacenter/alldata
train
774
e2f870a282722fcbb33fd24ee9b269ef69147939
[ "self.dag_application_server_info_list = dag_application_server_info_list\nself.exchange_dag_protection_preference = exchange_dag_protection_preference\nself.guid = guid\nself.name = name", "if dictionary is None:\n return None\ndag_application_server_info_list = None\nif dictionary.get('dagApplicationServerIn...
<|body_start_0|> self.dag_application_server_info_list = dag_application_server_info_list self.exchange_dag_protection_preference = exchange_dag_protection_preference self.guid = guid self.name = name <|end_body_0|> <|body_start_1|> if dictionary is None: return None...
Implementation of the 'DagInfo' model. Specifies the information about the DAG(Database availability group). Attributes: dag_application_server_info_list (list of DagApplicationServerInfo): Specifies the status of all the Exchange Application Servers that are part of this DAG. exchange_dag_protection_preference (Exchan...
DagInfo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DagInfo: """Implementation of the 'DagInfo' model. Specifies the information about the DAG(Database availability group). Attributes: dag_application_server_info_list (list of DagApplicationServerInfo): Specifies the status of all the Exchange Application Servers that are part of this DAG. exchang...
stack_v2_sparse_classes_10k_train_008281
3,283
permissive
[ { "docstring": "Constructor for the DagInfo class", "name": "__init__", "signature": "def __init__(self, dag_application_server_info_list=None, exchange_dag_protection_preference=None, guid=None, name=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary ...
2
null
Implement the Python class `DagInfo` described below. Class description: Implementation of the 'DagInfo' model. Specifies the information about the DAG(Database availability group). Attributes: dag_application_server_info_list (list of DagApplicationServerInfo): Specifies the status of all the Exchange Application Ser...
Implement the Python class `DagInfo` described below. Class description: Implementation of the 'DagInfo' model. Specifies the information about the DAG(Database availability group). Attributes: dag_application_server_info_list (list of DagApplicationServerInfo): Specifies the status of all the Exchange Application Ser...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class DagInfo: """Implementation of the 'DagInfo' model. Specifies the information about the DAG(Database availability group). Attributes: dag_application_server_info_list (list of DagApplicationServerInfo): Specifies the status of all the Exchange Application Servers that are part of this DAG. exchang...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class DagInfo: """Implementation of the 'DagInfo' model. Specifies the information about the DAG(Database availability group). Attributes: dag_application_server_info_list (list of DagApplicationServerInfo): Specifies the status of all the Exchange Application Servers that are part of this DAG. exchange_dag_protect...
the_stack_v2_python_sparse
cohesity_management_sdk/models/dag_info.py
cohesity/management-sdk-python
train
24
aa046820e8fc249515cce130237f2fc992825129
[ "super(MyImageNet22K, self).__init__(root, *args, **kwargs)\nself.exclude_imagenet1k = exclude_imagenet1k\nself.shuffle_idxs = False\nself.size = size\nif exclude_imagenet1k:\n self.samples = [s for s in self.samples if not any([idx in s[0] for idx in self.imagenet1k_idxs])]", "path, target = self.samples[inde...
<|body_start_0|> super(MyImageNet22K, self).__init__(root, *args, **kwargs) self.exclude_imagenet1k = exclude_imagenet1k self.shuffle_idxs = False self.size = size if exclude_imagenet1k: self.samples = [s for s in self.samples if not any([idx in s[0] for idx in self.i...
MyImageNet22K
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyImageNet22K: def __init__(self, root: str, size: torch.Size, exclude_imagenet1k=True, *args, **kwargs): """Implements a torchvision style ImageNet22k dataset. The dataset needs to be downloaded manually and put in the according directory. Since the dataset is very large, it happens tha...
stack_v2_sparse_classes_10k_train_008282
13,359
permissive
[ { "docstring": "Implements a torchvision style ImageNet22k dataset. The dataset needs to be downloaded manually and put in the according directory. Since the dataset is very large, it happens that some of the image files are broken. In this case, a warning is logged during training and a black image is returned...
2
stack_v2_sparse_classes_30k_train_005675
Implement the Python class `MyImageNet22K` described below. Class description: Implement the MyImageNet22K class. Method signatures and docstrings: - def __init__(self, root: str, size: torch.Size, exclude_imagenet1k=True, *args, **kwargs): Implements a torchvision style ImageNet22k dataset. The dataset needs to be d...
Implement the Python class `MyImageNet22K` described below. Class description: Implement the MyImageNet22K class. Method signatures and docstrings: - def __init__(self, root: str, size: torch.Size, exclude_imagenet1k=True, *args, **kwargs): Implements a torchvision style ImageNet22k dataset. The dataset needs to be d...
7af3d8eadabee81ab8f7db5dea7f8389ef090213
<|skeleton|> class MyImageNet22K: def __init__(self, root: str, size: torch.Size, exclude_imagenet1k=True, *args, **kwargs): """Implements a torchvision style ImageNet22k dataset. The dataset needs to be downloaded manually and put in the according directory. Since the dataset is very large, it happens tha...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MyImageNet22K: def __init__(self, root: str, size: torch.Size, exclude_imagenet1k=True, *args, **kwargs): """Implements a torchvision style ImageNet22k dataset. The dataset needs to be downloaded manually and put in the according directory. Since the dataset is very large, it happens that some of the ...
the_stack_v2_python_sparse
python/fcdd/datasets/outlier_exposure/imagenet.py
hkhaledmohamed/fcdd
train
0
dc5e90251ee087fa66c612d57b10581085b11404
[ "if x < 0:\n return False\ny = self.reverse(x)\nreturn y == x", "if x is None:\n return None\nif x == 0:\n return 0\nx_str = str(x)\nif x_str.find('-') == -1:\n x_array = list(x_str)\n reversed_array = x_array\n reversed_array.reverse()\n i = 0\n while reversed_array[i] == '0':\n i ...
<|body_start_0|> if x < 0: return False y = self.reverse(x) return y == x <|end_body_0|> <|body_start_1|> if x is None: return None if x == 0: return 0 x_str = str(x) if x_str.find('-') == -1: x_array = list(x_str) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPalindrome(self, x): """:type x: int :rtype: bool""" <|body_0|> def reverse(self, x): """:type x: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if x < 0: return False y = self.reverse(x) ...
stack_v2_sparse_classes_10k_train_008283
2,674
no_license
[ { "docstring": ":type x: int :rtype: bool", "name": "isPalindrome", "signature": "def isPalindrome(self, x)" }, { "docstring": ":type x: int :rtype: int", "name": "reverse", "signature": "def reverse(self, x)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, x): :type x: int :rtype: bool - def reverse(self, x): :type x: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, x): :type x: int :rtype: bool - def reverse(self, x): :type x: int :rtype: int <|skeleton|> class Solution: def isPalindrome(self, x): """:ty...
71a02a2c6bc12e86119502c9c4a4b2047b9f3966
<|skeleton|> class Solution: def isPalindrome(self, x): """:type x: int :rtype: bool""" <|body_0|> def reverse(self, x): """:type x: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def isPalindrome(self, x): """:type x: int :rtype: bool""" if x < 0: return False y = self.reverse(x) return y == x def reverse(self, x): """:type x: int :rtype: int""" if x is None: return None if x == 0: ...
the_stack_v2_python_sparse
Math/9. Palindrome Number(easy).py
xilixjd/leetcode
train
1
76c2520b0dcf2244178ab216bd453ee86868cecc
[ "super().__init__()\nself.accuracy = torchmetrics.Accuracy()\nself.roc_auc = torchmetrics.AUROC(num_classes=2)\nself.auc_score = torchmetrics.AUC()\nself.precision = torchmetrics.Precision()\nself.recall = torchmetrics.Recall()\nself.f1 = torchmetrics.F1()\nself.hamming_distance = torchmetrics.HammingDistance()\nse...
<|body_start_0|> super().__init__() self.accuracy = torchmetrics.Accuracy() self.roc_auc = torchmetrics.AUROC(num_classes=2) self.auc_score = torchmetrics.AUC() self.precision = torchmetrics.Precision() self.recall = torchmetrics.Recall() self.f1 = torchmetrics.F1...
MetricLogger
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetricLogger: def __init__(self): """Initialize the metrics.""" <|body_0|> def update(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> None: """Update the metrics given the predictions and the ground truth.""" <|body_1|> def compute(self) -> dict: ...
stack_v2_sparse_classes_10k_train_008284
1,953
permissive
[ { "docstring": "Initialize the metrics.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Update the metrics given the predictions and the ground truth.", "name": "update", "signature": "def update(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> None" }, ...
3
stack_v2_sparse_classes_30k_train_000391
Implement the Python class `MetricLogger` described below. Class description: Implement the MetricLogger class. Method signatures and docstrings: - def __init__(self): Initialize the metrics. - def update(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> None: Update the metrics given the predictions and the groun...
Implement the Python class `MetricLogger` described below. Class description: Implement the MetricLogger class. Method signatures and docstrings: - def __init__(self): Initialize the metrics. - def update(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> None: Update the metrics given the predictions and the groun...
a5880c1e4051603d65672996b7c8ff204dabbe37
<|skeleton|> class MetricLogger: def __init__(self): """Initialize the metrics.""" <|body_0|> def update(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> None: """Update the metrics given the predictions and the ground truth.""" <|body_1|> def compute(self) -> dict: ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MetricLogger: def __init__(self): """Initialize the metrics.""" super().__init__() self.accuracy = torchmetrics.Accuracy() self.roc_auc = torchmetrics.AUROC(num_classes=2) self.auc_score = torchmetrics.AUC() self.precision = torchmetrics.Precision() self...
the_stack_v2_python_sparse
care_nl_ica/metrics/metric_logger.py
rpatrik96/nl-causal-representations
train
9
1c82d096d7c6bdea7d863c8d1db7ea065e8f127a
[ "raise ApiError(500, 1, 'vlan status is null')\nobj = {'vlan_arr': []}\nargs = Verify.dict(self.req_args, {'limit?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid limit')), 'index?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid index'))})\narr = vcmd.get_arr_simple('cdbctl read/cdb/...
<|body_start_0|> raise ApiError(500, 1, 'vlan status is null') obj = {'vlan_arr': []} args = Verify.dict(self.req_args, {'limit?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid limit')), 'index?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid index'))}) ar...
VlanApi
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VlanApi: def get(self): """get vlan array""" <|body_0|> def post(self): """add vlan""" <|body_1|> def put(self): """modify vlan name""" <|body_2|> def delete(self): """delete vlans""" <|body_3|> <|end_skeleton|> <|b...
stack_v2_sparse_classes_10k_train_008285
3,263
no_license
[ { "docstring": "get vlan array", "name": "get", "signature": "def get(self)" }, { "docstring": "add vlan", "name": "post", "signature": "def post(self)" }, { "docstring": "modify vlan name", "name": "put", "signature": "def put(self)" }, { "docstring": "delete vla...
4
stack_v2_sparse_classes_30k_train_006718
Implement the Python class `VlanApi` described below. Class description: Implement the VlanApi class. Method signatures and docstrings: - def get(self): get vlan array - def post(self): add vlan - def put(self): modify vlan name - def delete(self): delete vlans
Implement the Python class `VlanApi` described below. Class description: Implement the VlanApi class. Method signatures and docstrings: - def get(self): get vlan array - def post(self): add vlan - def put(self): modify vlan name - def delete(self): delete vlans <|skeleton|> class VlanApi: def get(self): ...
2fee6115caec25fd040188dda0cb922bfca1a55f
<|skeleton|> class VlanApi: def get(self): """get vlan array""" <|body_0|> def post(self): """add vlan""" <|body_1|> def put(self): """modify vlan name""" <|body_2|> def delete(self): """delete vlans""" <|body_3|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class VlanApi: def get(self): """get vlan array""" raise ApiError(500, 1, 'vlan status is null') obj = {'vlan_arr': []} args = Verify.dict(self.req_args, {'limit?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid limit')), 'index?': (lambda x: x.type('int') and x > 0, A...
the_stack_v2_python_sparse
osp_sai_2.1.8/system/apps/web/api_class/vlan.py
bonald/vim_cfg
train
0
dbc61411abf958bf9fcf1f49785c2ac5ac04d37c
[ "for state in connection_states:\n if state not in constants.TCPConnectionState.STATES:\n raise ValueError('Expected connection state not defined: %s' % state)\nip_address = ip_address or ''\nport = port or ''\ncmd = 'esxcli network ip connection list | grep %s:%s' % (ip_address, port)\nif keywords:\n ...
<|body_start_0|> for state in connection_states: if state not in constants.TCPConnectionState.STATES: raise ValueError('Expected connection state not defined: %s' % state) ip_address = ip_address or '' port = port or '' cmd = 'esxcli network ip connection list...
ESX55OSImpl
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ESX55OSImpl: def get_tcp_connection_count(cls, client_object, ip_address=None, port=None, connection_states=None, keywords=None, **kwargs): """Returns the tcp connection count using netstat command matching the given parameters. @type ip_address: string @param ip_address: Check connectio...
stack_v2_sparse_classes_10k_train_008286
3,893
no_license
[ { "docstring": "Returns the tcp connection count using netstat command matching the given parameters. @type ip_address: string @param ip_address: Check connection to this IP address. @type port: integer @param port: Check connection state to this port number. @type connection_states: list @param connection_stat...
3
null
Implement the Python class `ESX55OSImpl` described below. Class description: Implement the ESX55OSImpl class. Method signatures and docstrings: - def get_tcp_connection_count(cls, client_object, ip_address=None, port=None, connection_states=None, keywords=None, **kwargs): Returns the tcp connection count using netsta...
Implement the Python class `ESX55OSImpl` described below. Class description: Implement the ESX55OSImpl class. Method signatures and docstrings: - def get_tcp_connection_count(cls, client_object, ip_address=None, port=None, connection_states=None, keywords=None, **kwargs): Returns the tcp connection count using netsta...
5b55817c050b637e2747084290f6206d2e622938
<|skeleton|> class ESX55OSImpl: def get_tcp_connection_count(cls, client_object, ip_address=None, port=None, connection_states=None, keywords=None, **kwargs): """Returns the tcp connection count using netstat command matching the given parameters. @type ip_address: string @param ip_address: Check connectio...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ESX55OSImpl: def get_tcp_connection_count(cls, client_object, ip_address=None, port=None, connection_states=None, keywords=None, **kwargs): """Returns the tcp connection count using netstat command matching the given parameters. @type ip_address: string @param ip_address: Check connection to this IP a...
the_stack_v2_python_sparse
SystemTesting/pylib/vmware/vsphere/esx/cli/esx55_os_impl.py
Cloudxtreme/MyProject
train
0
e9f85e9444611e7bbef2d8078118f116066da014
[ "powerset = []\nself.generate_powerset(0, [], inputSet, powerset)\nreturn powerset", "if current_index == len(input_set):\n powerset.append(deepcopy(selected_so_far))\n return\n\"\\n Recurse WITH the item at 'currentIndex' in the powerset we\\n are working on.\\n \"\nselected_so_far.app...
<|body_start_0|> powerset = [] self.generate_powerset(0, [], inputSet, powerset) return powerset <|end_body_0|> <|body_start_1|> if current_index == len(input_set): powerset.append(deepcopy(selected_so_far)) return "\n Recurse WITH the item at 'cur...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def powerset(self, inputSet): """Interface ---- :type inputSet: list of int :rtype: list of list of int Approach ---- 1. Draw the recursion tree 2. Establish a policy and the associated logic to enforce at each stack frame 3. Establish constraints and backtracking conditions Co...
stack_v2_sparse_classes_10k_train_008287
2,563
no_license
[ { "docstring": "Interface ---- :type inputSet: list of int :rtype: list of list of int Approach ---- 1. Draw the recursion tree 2. Establish a policy and the associated logic to enforce at each stack frame 3. Establish constraints and backtracking conditions Complexity ---- Recurrence relation T(N) = 2T(N-1) + ...
2
stack_v2_sparse_classes_30k_train_002466
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def powerset(self, inputSet): Interface ---- :type inputSet: list of int :rtype: list of list of int Approach ---- 1. Draw the recursion tree 2. Establish a policy and the associ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def powerset(self, inputSet): Interface ---- :type inputSet: list of int :rtype: list of list of int Approach ---- 1. Draw the recursion tree 2. Establish a policy and the associ...
c0d49423885832b616ae3c7cd58e8f24c17cfd4d
<|skeleton|> class Solution: def powerset(self, inputSet): """Interface ---- :type inputSet: list of int :rtype: list of list of int Approach ---- 1. Draw the recursion tree 2. Establish a policy and the associated logic to enforce at each stack frame 3. Establish constraints and backtracking conditions Co...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def powerset(self, inputSet): """Interface ---- :type inputSet: list of int :rtype: list of list of int Approach ---- 1. Draw the recursion tree 2. Establish a policy and the associated logic to enforce at each stack frame 3. Establish constraints and backtracking conditions Complexity ---- ...
the_stack_v2_python_sparse
backtracking_algorithms/powerSet.py
miaviles/Data-Structures-Algorithms-Python
train
0
77e962aba1379118a851595e611258fb5586b7d8
[ "if not board or not board[0]:\n return\nprevious = [0] * len(board[0])\nsurround = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]\nfor i in range(len(board)):\n left, tmp_previous = (0, board[i].copy())\n for j in range(len(board[0])):\n sum_, tmp = (0, board[i][j])\n ...
<|body_start_0|> if not board or not board[0]: return previous = [0] * len(board[0]) surround = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] for i in range(len(board)): left, tmp_previous = (0, board[i].copy()) for j in range(...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def gameOfLife(self, board: List[List[int]]) -> None: """Do not return anything, modify board in-place instead.""" <|body_0|> def gameOfLife1(self, board: List[List[int]]) -> None: """Do not return anything, modify board in-place instead.""" <|body_...
stack_v2_sparse_classes_10k_train_008288
2,741
no_license
[ { "docstring": "Do not return anything, modify board in-place instead.", "name": "gameOfLife", "signature": "def gameOfLife(self, board: List[List[int]]) -> None" }, { "docstring": "Do not return anything, modify board in-place instead.", "name": "gameOfLife1", "signature": "def gameOfLi...
2
stack_v2_sparse_classes_30k_train_004016
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def gameOfLife(self, board: List[List[int]]) -> None: Do not return anything, modify board in-place instead. - def gameOfLife1(self, board: List[List[int]]) -> None: Do not retur...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def gameOfLife(self, board: List[List[int]]) -> None: Do not return anything, modify board in-place instead. - def gameOfLife1(self, board: List[List[int]]) -> None: Do not retur...
e2fecd266bfced6208694b19a2d81182b13dacd6
<|skeleton|> class Solution: def gameOfLife(self, board: List[List[int]]) -> None: """Do not return anything, modify board in-place instead.""" <|body_0|> def gameOfLife1(self, board: List[List[int]]) -> None: """Do not return anything, modify board in-place instead.""" <|body_...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def gameOfLife(self, board: List[List[int]]) -> None: """Do not return anything, modify board in-place instead.""" if not board or not board[0]: return previous = [0] * len(board[0]) surround = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0),...
the_stack_v2_python_sparse
gameOfLife.py
HuipengXu/leetcode
train
0
8f9b24eec01e3b2bedc2d29dec72bb56a49ab782
[ "self.entity_description = description\nself._build = None\nself._data = data\nself._repo_name = repo_name\nself._user = user\nself._branch = branch\nself._attr_name = f'{repo_name} {description.name}'", "attrs = {}\nif self._build and self._attr_native_value is not None:\n if self._user and self.entity_descri...
<|body_start_0|> self.entity_description = description self._build = None self._data = data self._repo_name = repo_name self._user = user self._branch = branch self._attr_name = f'{repo_name} {description.name}' <|end_body_0|> <|body_start_1|> attrs = {} ...
Representation of a Travis CI sensor.
TravisCISensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TravisCISensor: """Representation of a Travis CI sensor.""" def __init__(self, data, repo_name, user, branch, description: SensorEntityDescription) -> None: """Initialize the sensor.""" <|body_0|> def extra_state_attributes(self): """Return the state attributes."...
stack_v2_sparse_classes_10k_train_008289
5,862
permissive
[ { "docstring": "Initialize the sensor.", "name": "__init__", "signature": "def __init__(self, data, repo_name, user, branch, description: SensorEntityDescription) -> None" }, { "docstring": "Return the state attributes.", "name": "extra_state_attributes", "signature": "def extra_state_at...
3
stack_v2_sparse_classes_30k_train_003201
Implement the Python class `TravisCISensor` described below. Class description: Representation of a Travis CI sensor. Method signatures and docstrings: - def __init__(self, data, repo_name, user, branch, description: SensorEntityDescription) -> None: Initialize the sensor. - def extra_state_attributes(self): Return t...
Implement the Python class `TravisCISensor` described below. Class description: Representation of a Travis CI sensor. Method signatures and docstrings: - def __init__(self, data, repo_name, user, branch, description: SensorEntityDescription) -> None: Initialize the sensor. - def extra_state_attributes(self): Return t...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class TravisCISensor: """Representation of a Travis CI sensor.""" def __init__(self, data, repo_name, user, branch, description: SensorEntityDescription) -> None: """Initialize the sensor.""" <|body_0|> def extra_state_attributes(self): """Return the state attributes."...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TravisCISensor: """Representation of a Travis CI sensor.""" def __init__(self, data, repo_name, user, branch, description: SensorEntityDescription) -> None: """Initialize the sensor.""" self.entity_description = description self._build = None self._data = data self...
the_stack_v2_python_sparse
homeassistant/components/travisci/sensor.py
home-assistant/core
train
35,501
10b004d7e3063e1db2599848bc6c1de807c0cecc
[ "if obj is None:\n return getattr(self, 'model', None)\nreturn obj.__class__", "excluded_fields = super().get_exclude(request, obj=obj)\nif self.admin_integration_enabled:\n model_cls = self.get_model_cls(obj)\n if model_cls:\n excluded_fields = list({*model_cls.Moderation.excluded_fields, *exclud...
<|body_start_0|> if obj is None: return getattr(self, 'model', None) return obj.__class__ <|end_body_0|> <|body_start_1|> excluded_fields = super().get_exclude(request, obj=obj) if self.admin_integration_enabled: model_cls = self.get_model_cls(obj) if...
Admin for models requiring moderation.
ModeratedModelAdmin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModeratedModelAdmin: """Admin for models requiring moderation.""" def get_model_cls(self, obj: Optional['ModeratedModel']=None) -> Optional[type['ModeratedModel']]: """Return the class of the moderated model.""" <|body_0|> def get_exclude(self, request: 'HttpRequest', ob...
stack_v2_sparse_classes_10k_train_008290
6,185
no_license
[ { "docstring": "Return the class of the moderated model.", "name": "get_model_cls", "signature": "def get_model_cls(self, obj: Optional['ModeratedModel']=None) -> Optional[type['ModeratedModel']]" }, { "docstring": "Return the fields to be excluded from the admin form.", "name": "get_exclude...
5
stack_v2_sparse_classes_30k_test_000299
Implement the Python class `ModeratedModelAdmin` described below. Class description: Admin for models requiring moderation. Method signatures and docstrings: - def get_model_cls(self, obj: Optional['ModeratedModel']=None) -> Optional[type['ModeratedModel']]: Return the class of the moderated model. - def get_exclude(...
Implement the Python class `ModeratedModelAdmin` described below. Class description: Admin for models requiring moderation. Method signatures and docstrings: - def get_model_cls(self, obj: Optional['ModeratedModel']=None) -> Optional[type['ModeratedModel']]: Return the class of the moderated model. - def get_exclude(...
8bbdc8eec3622af22c17214051c34e36bea8e05a
<|skeleton|> class ModeratedModelAdmin: """Admin for models requiring moderation.""" def get_model_cls(self, obj: Optional['ModeratedModel']=None) -> Optional[type['ModeratedModel']]: """Return the class of the moderated model.""" <|body_0|> def get_exclude(self, request: 'HttpRequest', ob...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ModeratedModelAdmin: """Admin for models requiring moderation.""" def get_model_cls(self, obj: Optional['ModeratedModel']=None) -> Optional[type['ModeratedModel']]: """Return the class of the moderated model.""" if obj is None: return getattr(self, 'model', None) retur...
the_stack_v2_python_sparse
apps/moderation/admin/moderated_model/admin.py
abdulwahed-mansour/modularhistory
train
1
c38fd6ce2c3d7cb7414613c5b16789f4fe2d8031
[ "if len(nums) < 2:\n return len(nums)\n_nums, cnt, result = (sorted(nums), 1, 0)\nfor i in xrange(1, len(_nums)):\n if _nums[i] - _nums[i - 1] == 1:\n cnt += 1\n else:\n result = max(cnt, result)\n cnt = 1\nreturn max(result, cnt)", "nums = set(nums)\nif len(nums) < 2:\n return le...
<|body_start_0|> if len(nums) < 2: return len(nums) _nums, cnt, result = (sorted(nums), 1, 0) for i in xrange(1, len(_nums)): if _nums[i] - _nums[i - 1] == 1: cnt += 1 else: result = max(cnt, result) cnt = 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestConsecutive1(self, nums): """:type nums: List[int] :rtype: int 明显超时(NlogN)""" <|body_0|> def longestConsecutive2(self, nums): """:type nums: List[int] :rtype: int unionfind(N)""" <|body_1|> def longestConsecutive(self, nums): ...
stack_v2_sparse_classes_10k_train_008291
2,676
no_license
[ { "docstring": ":type nums: List[int] :rtype: int 明显超时(NlogN)", "name": "longestConsecutive1", "signature": "def longestConsecutive1(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int unionfind(N)", "name": "longestConsecutive2", "signature": "def longestConsecutive2(self,...
3
stack_v2_sparse_classes_30k_train_006033
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestConsecutive1(self, nums): :type nums: List[int] :rtype: int 明显超时(NlogN) - def longestConsecutive2(self, nums): :type nums: List[int] :rtype: int unionfind(N) - def lon...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestConsecutive1(self, nums): :type nums: List[int] :rtype: int 明显超时(NlogN) - def longestConsecutive2(self, nums): :type nums: List[int] :rtype: int unionfind(N) - def lon...
9687f8e743a8b6396fff192f22b5256d1025f86b
<|skeleton|> class Solution: def longestConsecutive1(self, nums): """:type nums: List[int] :rtype: int 明显超时(NlogN)""" <|body_0|> def longestConsecutive2(self, nums): """:type nums: List[int] :rtype: int unionfind(N)""" <|body_1|> def longestConsecutive(self, nums): ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def longestConsecutive1(self, nums): """:type nums: List[int] :rtype: int 明显超时(NlogN)""" if len(nums) < 2: return len(nums) _nums, cnt, result = (sorted(nums), 1, 0) for i in xrange(1, len(_nums)): if _nums[i] - _nums[i - 1] == 1: ...
the_stack_v2_python_sparse
2017/array/Longest_Consecutive_Sequence.py
buhuipao/LeetCode
train
5
e40f5025c78cf16e3e0fae8e3f3c588fc5fe2a36
[ "self.active_sessions = active_sessions\nself.file_path = file_path\nself.view_id = view_id\nself.view_name = view_name", "if dictionary is None:\n return None\nactive_sessions = None\nif dictionary.get('activeSessions') != None:\n active_sessions = list()\n for structure in dictionary.get('activeSession...
<|body_start_0|> self.active_sessions = active_sessions self.file_path = file_path self.view_id = view_id self.view_name = view_name <|end_body_0|> <|body_start_1|> if dictionary is None: return None active_sessions = None if dictionary.get('activeSes...
Implementation of the 'SmbActiveFilePath' model. Specifies a file path in an SMB view that has active sessions and opens. Attributes: active_sessions (list of SmbActiveSession): Specifies the sessions where the file is open. file_path (string): Specifies the filepath in the view. view_id (long|int): Specifies the id of...
SmbActiveFilePath
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SmbActiveFilePath: """Implementation of the 'SmbActiveFilePath' model. Specifies a file path in an SMB view that has active sessions and opens. Attributes: active_sessions (list of SmbActiveSession): Specifies the sessions where the file is open. file_path (string): Specifies the filepath in the ...
stack_v2_sparse_classes_10k_train_008292
2,539
permissive
[ { "docstring": "Constructor for the SmbActiveFilePath class", "name": "__init__", "signature": "def __init__(self, active_sessions=None, file_path=None, view_id=None, view_name=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictiona...
2
stack_v2_sparse_classes_30k_val_000226
Implement the Python class `SmbActiveFilePath` described below. Class description: Implementation of the 'SmbActiveFilePath' model. Specifies a file path in an SMB view that has active sessions and opens. Attributes: active_sessions (list of SmbActiveSession): Specifies the sessions where the file is open. file_path (...
Implement the Python class `SmbActiveFilePath` described below. Class description: Implementation of the 'SmbActiveFilePath' model. Specifies a file path in an SMB view that has active sessions and opens. Attributes: active_sessions (list of SmbActiveSession): Specifies the sessions where the file is open. file_path (...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class SmbActiveFilePath: """Implementation of the 'SmbActiveFilePath' model. Specifies a file path in an SMB view that has active sessions and opens. Attributes: active_sessions (list of SmbActiveSession): Specifies the sessions where the file is open. file_path (string): Specifies the filepath in the ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SmbActiveFilePath: """Implementation of the 'SmbActiveFilePath' model. Specifies a file path in an SMB view that has active sessions and opens. Attributes: active_sessions (list of SmbActiveSession): Specifies the sessions where the file is open. file_path (string): Specifies the filepath in the view. view_id...
the_stack_v2_python_sparse
cohesity_management_sdk/models/smb_active_file_path.py
cohesity/management-sdk-python
train
24
baaf9649b84c2f922dbe86dabe06cfcde8e925fc
[ "def preorder(node):\n if node is None:\n serial.append('#')\n else:\n serial.append(str(node.val))\n preorder(node.left)\n preorder(node.right)\nif root is None:\n return ''\nserial = []\npreorder(root)\nreturn ','.join(serial)", "if data == '':\n return None\nserial = dat...
<|body_start_0|> def preorder(node): if node is None: serial.append('#') else: serial.append(str(node.val)) preorder(node.left) preorder(node.right) if root is None: return '' serial = [] ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_10k_train_008293
1,764
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:...
e12025e754547d18d5bb50a9dbe5e725fd03fd9c
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" def preorder(node): if node is None: serial.append('#') else: serial.append(str(node.val)) preorder(node.left) ...
the_stack_v2_python_sparse
leetcode_review/297serialize_and_deserialize_BT.py
clovery410/mycode
train
1
2908fbce074f74864e6eb5ccc7583ff65c3eda16
[ "obj = cls()\ncrawler.signals.connect(obj.spider_error, signal=signals.spider_error)\nreturn obj", "if 'errors' not in spider.state:\n spider.state['errors'] = []\nspider.state['errors'].append({'exception': failure, 'sender': response})" ]
<|body_start_0|> obj = cls() crawler.signals.connect(obj.spider_error, signal=signals.spider_error) return obj <|end_body_0|> <|body_start_1|> if 'errors' not in spider.state: spider.state['errors'] = [] spider.state['errors'].append({'exception': failure, 'sender': ...
ErrorHandler
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ErrorHandler: def from_crawler(cls, crawler, client=None, dsn=None): """Hook in the signal for errors.""" <|body_0|> def spider_error(self, failure, response, spider, signal=None, sender=None, *args, **kwargs): """Register the error in the spider and continue.""" ...
stack_v2_sparse_classes_10k_train_008294
1,511
permissive
[ { "docstring": "Hook in the signal for errors.", "name": "from_crawler", "signature": "def from_crawler(cls, crawler, client=None, dsn=None)" }, { "docstring": "Register the error in the spider and continue.", "name": "spider_error", "signature": "def spider_error(self, failure, response...
2
stack_v2_sparse_classes_30k_train_004979
Implement the Python class `ErrorHandler` described below. Class description: Implement the ErrorHandler class. Method signatures and docstrings: - def from_crawler(cls, crawler, client=None, dsn=None): Hook in the signal for errors. - def spider_error(self, failure, response, spider, signal=None, sender=None, *args,...
Implement the Python class `ErrorHandler` described below. Class description: Implement the ErrorHandler class. Method signatures and docstrings: - def from_crawler(cls, crawler, client=None, dsn=None): Hook in the signal for errors. - def spider_error(self, failure, response, spider, signal=None, sender=None, *args,...
e645cc3dbfe74141c00f8e42e6fbc603e878af36
<|skeleton|> class ErrorHandler: def from_crawler(cls, crawler, client=None, dsn=None): """Hook in the signal for errors.""" <|body_0|> def spider_error(self, failure, response, spider, signal=None, sender=None, *args, **kwargs): """Register the error in the spider and continue.""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ErrorHandler: def from_crawler(cls, crawler, client=None, dsn=None): """Hook in the signal for errors.""" obj = cls() crawler.signals.connect(obj.spider_error, signal=signals.spider_error) return obj def spider_error(self, failure, response, spider, signal=None, sender=Non...
the_stack_v2_python_sparse
hepcrawl/extensions.py
inspirehep/hepcrawl
train
21
6b195ac6442a1965b29863fe210658327ae9ea5b
[ "def residual(x):\n y_, log_dy_dx = bijection(x)\n return (y_ - y, log_dy_dx)\nwith torch.no_grad():\n x, log_dx_dy = root_finder(residual, x0=y)\nctx.save_for_backward(x, *params)\nctx.bijection = bijection\nreturn (x, log_dx_dy)", "x, *params = ctx.saved_tensors\nwith torch.enable_grad():\n x = x.de...
<|body_start_0|> def residual(x): y_, log_dy_dx = bijection(x) return (y_ - y, log_dy_dx) with torch.no_grad(): x, log_dx_dy = root_finder(residual, x0=y) ctx.save_for_backward(x, *params) ctx.bijection = bijection return (x, log_dx_dy) <|end_b...
First-order-differentiation of an elementwise bijection under black-box inversion.
DifferentiableApproximateInverse
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DifferentiableApproximateInverse: """First-order-differentiation of an elementwise bijection under black-box inversion.""" def forward(ctx, root_finder, bijection, y, *params): """Inverse pass Parameters ---------- ctx : object context object to stash information for the backward cal...
stack_v2_sparse_classes_10k_train_008295
8,727
no_license
[ { "docstring": "Inverse pass Parameters ---------- ctx : object context object to stash information for the backward call root_finder : Callable Root finding method, which takes two parameters (residue, x0) bijection : Flow a flow object, whose forward function returns (y, dlogp) y : torch.Tensor the input to t...
2
stack_v2_sparse_classes_30k_train_004777
Implement the Python class `DifferentiableApproximateInverse` described below. Class description: First-order-differentiation of an elementwise bijection under black-box inversion. Method signatures and docstrings: - def forward(ctx, root_finder, bijection, y, *params): Inverse pass Parameters ---------- ctx : object...
Implement the Python class `DifferentiableApproximateInverse` described below. Class description: First-order-differentiation of an elementwise bijection under black-box inversion. Method signatures and docstrings: - def forward(ctx, root_finder, bijection, y, *params): Inverse pass Parameters ---------- ctx : object...
15835d43a5ec2d29f05d325d65ffd973a6c8a201
<|skeleton|> class DifferentiableApproximateInverse: """First-order-differentiation of an elementwise bijection under black-box inversion.""" def forward(ctx, root_finder, bijection, y, *params): """Inverse pass Parameters ---------- ctx : object context object to stash information for the backward cal...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class DifferentiableApproximateInverse: """First-order-differentiation of an elementwise bijection under black-box inversion.""" def forward(ctx, root_finder, bijection, y, *params): """Inverse pass Parameters ---------- ctx : object context object to stash information for the backward call root_finder...
the_stack_v2_python_sparse
bgflow/bgflow/nn/flow/root_finding/approx_inverse.py
noegroup/smooth_normalizing_flows
train
1
0886b848387c9429222689b57906509c38b56c28
[ "from readthedocs.projects.models import Project\nproject = Project.objects.get(slug=project_slug)\nbase_project = project.publisherproject_set.all().first()\nif not base_project or private:\n return super(ItaliaResolver, self).base_resolve_path(project_slug, filename, version_slug, language, private, single_ver...
<|body_start_0|> from readthedocs.projects.models import Project project = Project.objects.get(slug=project_slug) base_project = project.publisherproject_set.all().first() if not base_project or private: return super(ItaliaResolver, self).base_resolve_path(project_slug, filen...
Custom path resolver for built documentation. Resolves to public domain without use of subdomains or /doc/* paths. It also takes publisher into account
ItaliaResolver
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ItaliaResolver: """Custom path resolver for built documentation. Resolves to public domain without use of subdomains or /doc/* paths. It also takes publisher into account""" def base_resolve_path(self, project_slug, filename, version_slug=None, language=None, private=False, single_version=No...
stack_v2_sparse_classes_10k_train_008296
4,501
permissive
[ { "docstring": "Generates the URL for a document according to its project / publisher. :param project_slug: project (document) slug :param filename: filename :param version_slug: version slug :param language: language :param private: if document is private :param single_version: if document has single version :...
4
stack_v2_sparse_classes_30k_train_003287
Implement the Python class `ItaliaResolver` described below. Class description: Custom path resolver for built documentation. Resolves to public domain without use of subdomains or /doc/* paths. It also takes publisher into account Method signatures and docstrings: - def base_resolve_path(self, project_slug, filename...
Implement the Python class `ItaliaResolver` described below. Class description: Custom path resolver for built documentation. Resolves to public domain without use of subdomains or /doc/* paths. It also takes publisher into account Method signatures and docstrings: - def base_resolve_path(self, project_slug, filename...
649965d7589eb1d30efdc7906c3ee7dc5a9e3656
<|skeleton|> class ItaliaResolver: """Custom path resolver for built documentation. Resolves to public domain without use of subdomains or /doc/* paths. It also takes publisher into account""" def base_resolve_path(self, project_slug, filename, version_slug=None, language=None, private=False, single_version=No...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ItaliaResolver: """Custom path resolver for built documentation. Resolves to public domain without use of subdomains or /doc/* paths. It also takes publisher into account""" def base_resolve_path(self, project_slug, filename, version_slug=None, language=None, private=False, single_version=None, subprojec...
the_stack_v2_python_sparse
readthedocs/docsitalia/resolver.py
italia/docs.italia.it
train
19
02e50c1fdea9d978bdbe871b6aea8dd91bf72334
[ "if not T:\n return []\nif len(T) == 1:\n return [0]\nres = [0 for _ in range(len(T))]\ntem_list = [None for _ in range(len(T))]\nfor index, each in enumerate(T):\n tem_list[index] = set(range(each + 1, 101))\n if index != 0 and each > T[index - 1]:\n for i in range(index, -1, -1):\n i...
<|body_start_0|> if not T: return [] if len(T) == 1: return [0] res = [0 for _ in range(len(T))] tem_list = [None for _ in range(len(T))] for index, each in enumerate(T): tem_list[index] = set(range(each + 1, 101)) if index != 0 and...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def dailyTemperatures(self, T): """:type T: List[int] :rtype: List[int]""" <|body_0|> def dailyTemperatures2(self, T): """:type T: List[int] :rtype: List[int] 稍微进步点了, 吐血""" <|body_1|> def dailyTemperatures3(self, T): """:type T: List[in...
stack_v2_sparse_classes_10k_train_008297
2,144
no_license
[ { "docstring": ":type T: List[int] :rtype: List[int]", "name": "dailyTemperatures", "signature": "def dailyTemperatures(self, T)" }, { "docstring": ":type T: List[int] :rtype: List[int] 稍微进步点了, 吐血", "name": "dailyTemperatures2", "signature": "def dailyTemperatures2(self, T)" }, { ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def dailyTemperatures(self, T): :type T: List[int] :rtype: List[int] - def dailyTemperatures2(self, T): :type T: List[int] :rtype: List[int] 稍微进步点了, 吐血 - def dailyTemperatures3(s...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def dailyTemperatures(self, T): :type T: List[int] :rtype: List[int] - def dailyTemperatures2(self, T): :type T: List[int] :rtype: List[int] 稍微进步点了, 吐血 - def dailyTemperatures3(s...
4105e18050b15fc0409c75353ad31be17187dd34
<|skeleton|> class Solution: def dailyTemperatures(self, T): """:type T: List[int] :rtype: List[int]""" <|body_0|> def dailyTemperatures2(self, T): """:type T: List[int] :rtype: List[int] 稍微进步点了, 吐血""" <|body_1|> def dailyTemperatures3(self, T): """:type T: List[in...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def dailyTemperatures(self, T): """:type T: List[int] :rtype: List[int]""" if not T: return [] if len(T) == 1: return [0] res = [0 for _ in range(len(T))] tem_list = [None for _ in range(len(T))] for index, each in enumerate(T):...
the_stack_v2_python_sparse
dailyTemperatures.py
NeilWangziyu/Leetcode_py
train
2
8386cc3e6407247fb98fe8bd5e810d6c31436eb9
[ "self.name = name\nself.age = age\nPerson.Count += 1", "print('name is ', self.name)\nprint('age is ', self.age)\nprint('there are ' + str(Person.Count) + ' person in the class')" ]
<|body_start_0|> self.name = name self.age = age Person.Count += 1 <|end_body_0|> <|body_start_1|> print('name is ', self.name) print('age is ', self.age) print('there are ' + str(Person.Count) + ' person in the class') <|end_body_1|>
classdocs
Person
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Person: """classdocs""" def __init__(self, name, age): """Constructor @param: name the name of this person @param: age the age of this person""" <|body_0|> def detail(self): """the detail infomation of this person""" <|body_1|> <|end_skeleton|> <|body_s...
stack_v2_sparse_classes_10k_train_008298
889
no_license
[ { "docstring": "Constructor @param: name the name of this person @param: age the age of this person", "name": "__init__", "signature": "def __init__(self, name, age)" }, { "docstring": "the detail infomation of this person", "name": "detail", "signature": "def detail(self)" } ]
2
stack_v2_sparse_classes_30k_train_000130
Implement the Python class `Person` described below. Class description: classdocs Method signatures and docstrings: - def __init__(self, name, age): Constructor @param: name the name of this person @param: age the age of this person - def detail(self): the detail infomation of this person
Implement the Python class `Person` described below. Class description: classdocs Method signatures and docstrings: - def __init__(self, name, age): Constructor @param: name the name of this person @param: age the age of this person - def detail(self): the detail infomation of this person <|skeleton|> class Person: ...
c7dd6def7ec081b483c3a4cfe334d17c049224c2
<|skeleton|> class Person: """classdocs""" def __init__(self, name, age): """Constructor @param: name the name of this person @param: age the age of this person""" <|body_0|> def detail(self): """the detail infomation of this person""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Person: """classdocs""" def __init__(self, name, age): """Constructor @param: name the name of this person @param: age the age of this person""" self.name = name self.age = age Person.Count += 1 def detail(self): """the detail infomation of this person""" ...
the_stack_v2_python_sparse
offline-only/tkinter/jicheng.py
liucz25/FSGL
train
1
675bc42bd2bb86d97d8deea5c91a1ffe8b84fcdd
[ "super(GluonTSModel, self).__init__(model_data, image, role, entry_point, predictor_cls=predictor_cls, **kwargs)\nself.framework_version = framework_version\nself.model_server_workers = model_server_workers", "is_mms_version = parse_version(self.framework_version) >= parse_version(self._LOWEST_MMS_VERSION)\ndeplo...
<|body_start_0|> super(GluonTSModel, self).__init__(model_data, image, role, entry_point, predictor_cls=predictor_cls, **kwargs) self.framework_version = framework_version self.model_server_workers = model_server_workers <|end_body_0|> <|body_start_1|> is_mms_version = parse_version(sel...
An GluonTS SageMaker ``Model`` that can be deployed to a SageMaker ``Endpoint``.
GluonTSModel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GluonTSModel: """An GluonTS SageMaker ``Model`` that can be deployed to a SageMaker ``Endpoint``.""" def __init__(self, model_data, role, entry_point, image: str=None, framework_version: str=GLUONTS_VERSION, predictor_cls=GluonTSPredictor, model_server_workers: int=None, **kwargs): "...
stack_v2_sparse_classes_10k_train_008299
6,390
permissive
[ { "docstring": "Initialize a GluonTSModel. Parameters ---------- model_data: The S3 location of a SageMaker model data ``.tar.gz`` file. role: An AWS IAM role (either name or full ARN). The Amazon SageMaker training jobs and APIs that create Amazon SageMaker endpoints use this role to access training data and m...
2
null
Implement the Python class `GluonTSModel` described below. Class description: An GluonTS SageMaker ``Model`` that can be deployed to a SageMaker ``Endpoint``. Method signatures and docstrings: - def __init__(self, model_data, role, entry_point, image: str=None, framework_version: str=GLUONTS_VERSION, predictor_cls=Gl...
Implement the Python class `GluonTSModel` described below. Class description: An GluonTS SageMaker ``Model`` that can be deployed to a SageMaker ``Endpoint``. Method signatures and docstrings: - def __init__(self, model_data, role, entry_point, image: str=None, framework_version: str=GLUONTS_VERSION, predictor_cls=Gl...
df4256b0e67120db555c109a1bf6cfa2b3bd3cd8
<|skeleton|> class GluonTSModel: """An GluonTS SageMaker ``Model`` that can be deployed to a SageMaker ``Endpoint``.""" def __init__(self, model_data, role, entry_point, image: str=None, framework_version: str=GLUONTS_VERSION, predictor_cls=GluonTSPredictor, model_server_workers: int=None, **kwargs): "...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GluonTSModel: """An GluonTS SageMaker ``Model`` that can be deployed to a SageMaker ``Endpoint``.""" def __init__(self, model_data, role, entry_point, image: str=None, framework_version: str=GLUONTS_VERSION, predictor_cls=GluonTSPredictor, model_server_workers: int=None, **kwargs): """Initialize ...
the_stack_v2_python_sparse
src/gluonts/nursery/sagemaker_sdk/model.py
mbohlkeschneider/gluon-ts
train
54