blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
46301e88ca00c2414752ddb3e5c5785876cd697b
[ "self.name = name\nif labels is None:\n self.labels = []\nelse:\n self.labels = labels", "cell_labels = np.array([None for x in range(len(sca.cell_sample))])\nfor label in self.labels:\n indices = label.select_cells(sca)\n if len(indices) == 0:\n continue\n cell_labels[indices] = label.name\...
<|body_start_0|> self.name = name if labels is None: self.labels = [] else: self.labels = labels <|end_body_0|> <|body_start_1|> cell_labels = np.array([None for x in range(len(sca.cell_sample))]) for label in self.labels: indices = label.sele...
This class represents a custom color map
CustomColorMap
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomColorMap: """This class represents a custom color map""" def __init__(self, name, labels=None): """Args: name (str) labels (list of CustomLabel objects)""" <|body_0|> def label_cells(self, sca): """Labels the cells in the given SCAnalysis object.""" ...
stack_v2_sparse_classes_36k_train_006000
6,289
no_license
[ { "docstring": "Args: name (str) labels (list of CustomLabel objects)", "name": "__init__", "signature": "def __init__(self, name, labels=None)" }, { "docstring": "Labels the cells in the given SCAnalysis object.", "name": "label_cells", "signature": "def label_cells(self, sca)" }, {...
3
stack_v2_sparse_classes_30k_train_016905
Implement the Python class `CustomColorMap` described below. Class description: This class represents a custom color map Method signatures and docstrings: - def __init__(self, name, labels=None): Args: name (str) labels (list of CustomLabel objects) - def label_cells(self, sca): Labels the cells in the given SCAnalys...
Implement the Python class `CustomColorMap` described below. Class description: This class represents a custom color map Method signatures and docstrings: - def __init__(self, name, labels=None): Args: name (str) labels (list of CustomLabel objects) - def label_cells(self, sca): Labels the cells in the given SCAnalys...
a64425ca5bff57c3fe336e47fddf00fe2bbc1e75
<|skeleton|> class CustomColorMap: """This class represents a custom color map""" def __init__(self, name, labels=None): """Args: name (str) labels (list of CustomLabel objects)""" <|body_0|> def label_cells(self, sca): """Labels the cells in the given SCAnalysis object.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomColorMap: """This class represents a custom color map""" def __init__(self, name, labels=None): """Args: name (str) labels (list of CustomLabel objects)""" self.name = name if labels is None: self.labels = [] else: self.labels = labels de...
the_stack_v2_python_sparse
uncurl_analysis/custom_cell_selection.py
yjzhang/uncurl_analysis
train
1
057807310c3dcf027a2c3f41e04b0ad1a290aae2
[ "Document.__init__(self)\nsession.info('Exporting to NMF XML version 1.0')\nwith session._objslock:\n self.scenarioPlan = ScenarioPlan(self, session)\n if session.getstate() == coreapi.CORE_EVENT_RUNTIME_STATE:\n deployment = CoreDeploymentWriter(self, self.scenarioPlan, session)\n deployment.ad...
<|body_start_0|> Document.__init__(self) session.info('Exporting to NMF XML version 1.0') with session._objslock: self.scenarioPlan = ScenarioPlan(self, session) if session.getstate() == coreapi.CORE_EVENT_RUNTIME_STATE: deployment = CoreDeploymentWriter(s...
Utility class for writing a CoreSession to XML in the NMF scenPlan schema. The init method builds an xml.dom.minidom.Document, and the writexml() method saves the XML file.
CoreDocumentWriter1
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CoreDocumentWriter1: """Utility class for writing a CoreSession to XML in the NMF scenPlan schema. The init method builds an xml.dom.minidom.Document, and the writexml() method saves the XML file.""" def __init__(self, session): """Create an empty Scenario XML Document, then populate...
stack_v2_sparse_classes_36k_train_006001
37,675
permissive
[ { "docstring": "Create an empty Scenario XML Document, then populate it with objects from the given session.", "name": "__init__", "signature": "def __init__(self, session)" }, { "docstring": "Commit to file", "name": "writexml", "signature": "def writexml(self, filename)" } ]
2
null
Implement the Python class `CoreDocumentWriter1` described below. Class description: Utility class for writing a CoreSession to XML in the NMF scenPlan schema. The init method builds an xml.dom.minidom.Document, and the writexml() method saves the XML file. Method signatures and docstrings: - def __init__(self, sessi...
Implement the Python class `CoreDocumentWriter1` described below. Class description: Utility class for writing a CoreSession to XML in the NMF scenPlan schema. The init method builds an xml.dom.minidom.Document, and the writexml() method saves the XML file. Method signatures and docstrings: - def __init__(self, sessi...
9c246b0ae0e9182dcf61acc4faee41841d5cbd51
<|skeleton|> class CoreDocumentWriter1: """Utility class for writing a CoreSession to XML in the NMF scenPlan schema. The init method builds an xml.dom.minidom.Document, and the writexml() method saves the XML file.""" def __init__(self, session): """Create an empty Scenario XML Document, then populate...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CoreDocumentWriter1: """Utility class for writing a CoreSession to XML in the NMF scenPlan schema. The init method builds an xml.dom.minidom.Document, and the writexml() method saves the XML file.""" def __init__(self, session): """Create an empty Scenario XML Document, then populate it with obje...
the_stack_v2_python_sparse
coreemu-read-only/daemon/core/misc/xmlwriter1.py
ermin-sakic/common-open-research-emulator-CORE
train
3
6ce31067b4a0af641709930a01e204e3f0aa8ee2
[ "super().__init__()\nself.args = args\nself.q_params = nn.Parameter(self.args.q_delta * torch.randn(self.args.q_depth * self.args.n_qubits))\nself.qai = quant_arc_interface", "q_in = torch.tanh(input_features) * np.pi / 2.0\nq_in = q_in.to(self.args.device)\nq_out = torch.Tensor(0, self.args.target_class)\nq_out ...
<|body_start_0|> super().__init__() self.args = args self.q_params = nn.Parameter(self.args.q_delta * torch.randn(self.args.q_depth * self.args.n_qubits)) self.qai = quant_arc_interface <|end_body_0|> <|body_start_1|> q_in = torch.tanh(input_features) * np.pi / 2.0 q_in ...
Torch module implementing the *dressed* quantum net.
vqc_net
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class vqc_net: """Torch module implementing the *dressed* quantum net.""" def __init__(self, args, quant_arc_interface): """Definition of the *dressed* layout.""" <|body_0|> def forward(self, input_features): """Defining how tensors are supposed to move through the *dr...
stack_v2_sparse_classes_36k_train_006002
1,518
permissive
[ { "docstring": "Definition of the *dressed* layout.", "name": "__init__", "signature": "def __init__(self, args, quant_arc_interface)" }, { "docstring": "Defining how tensors are supposed to move through the *dressed* quantum net.", "name": "forward", "signature": "def forward(self, inpu...
2
stack_v2_sparse_classes_30k_train_000085
Implement the Python class `vqc_net` described below. Class description: Torch module implementing the *dressed* quantum net. Method signatures and docstrings: - def __init__(self, args, quant_arc_interface): Definition of the *dressed* layout. - def forward(self, input_features): Defining how tensors are supposed to...
Implement the Python class `vqc_net` described below. Class description: Torch module implementing the *dressed* quantum net. Method signatures and docstrings: - def __init__(self, args, quant_arc_interface): Definition of the *dressed* layout. - def forward(self, input_features): Defining how tensors are supposed to...
8126691b43bddc2b1a96f73ab35d04d1af200d7a
<|skeleton|> class vqc_net: """Torch module implementing the *dressed* quantum net.""" def __init__(self, args, quant_arc_interface): """Definition of the *dressed* layout.""" <|body_0|> def forward(self, input_features): """Defining how tensors are supposed to move through the *dr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class vqc_net: """Torch module implementing the *dressed* quantum net.""" def __init__(self, args, quant_arc_interface): """Definition of the *dressed* layout.""" super().__init__() self.args = args self.q_params = nn.Parameter(self.args.q_delta * torch.randn(self.args.q_depth *...
the_stack_v2_python_sparse
model/vqc_layers.py
zzh237/quanthmc
train
0
7f32d1a6f18eab2d7c3d505ed61740b43e6b7ca7
[ "import build.api\nimport company.api\nimport order.api\nimport part.api\nimport stock.api\nreturn {'build': build.api.BuildList, 'company': company.api.CompanyList, 'manufacturerpart': company.api.ManufacturerPartList, 'supplierpart': company.api.SupplierPartList, 'part': part.api.PartList, 'partcategory': part.ap...
<|body_start_0|> import build.api import company.api import order.api import part.api import stock.api return {'build': build.api.BuildList, 'company': company.api.CompanyList, 'manufacturerpart': company.api.ManufacturerPartList, 'supplierpart': company.api.SupplierPartL...
A general-purpose 'search' API endpoint Returns hits against a number of different models simultaneously, to consolidate multiple API requests into a single query. Is much more efficient and simplifies code!
APISearchView
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class APISearchView: """A general-purpose 'search' API endpoint Returns hits against a number of different models simultaneously, to consolidate multiple API requests into a single query. Is much more efficient and simplifies code!""" def get_result_types(self): """Construct a list of sear...
stack_v2_sparse_classes_36k_train_006003
11,757
permissive
[ { "docstring": "Construct a list of search types we can return", "name": "get_result_types", "signature": "def get_result_types(self)" }, { "docstring": "Perform search query against available models", "name": "post", "signature": "def post(self, request, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_020681
Implement the Python class `APISearchView` described below. Class description: A general-purpose 'search' API endpoint Returns hits against a number of different models simultaneously, to consolidate multiple API requests into a single query. Is much more efficient and simplifies code! Method signatures and docstring...
Implement the Python class `APISearchView` described below. Class description: A general-purpose 'search' API endpoint Returns hits against a number of different models simultaneously, to consolidate multiple API requests into a single query. Is much more efficient and simplifies code! Method signatures and docstring...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class APISearchView: """A general-purpose 'search' API endpoint Returns hits against a number of different models simultaneously, to consolidate multiple API requests into a single query. Is much more efficient and simplifies code!""" def get_result_types(self): """Construct a list of sear...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class APISearchView: """A general-purpose 'search' API endpoint Returns hits against a number of different models simultaneously, to consolidate multiple API requests into a single query. Is much more efficient and simplifies code!""" def get_result_types(self): """Construct a list of search types we c...
the_stack_v2_python_sparse
InvenTree/InvenTree/api.py
inventree/InvenTree
train
3,077
561c95ebb895cf6a7c18a8e926aa79f4602efd08
[ "def dp(i, j, memo):\n if i > j:\n return 0\n if i == j:\n return 1\n if (i, j) not in memo:\n ans = float('inf')\n for k in range(i, j):\n ans = min(ans, dp(i, k, memo) + dp(k + 1, j, memo) - int(s[i] == s[k + 1]))\n memo[i, j] = ans\n return memo[i, j]\nre...
<|body_start_0|> def dp(i, j, memo): if i > j: return 0 if i == j: return 1 if (i, j) not in memo: ans = float('inf') for k in range(i, j): ans = min(ans, dp(i, k, memo) + dp(k + 1, j, memo) -...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def strangePrinter(self, s: str) -> int: """top down""" <|body_0|> def strangePrinter(self, s: str) -> int: """bottom up""" <|body_1|> <|end_skeleton|> <|body_start_0|> def dp(i, j, memo): if i > j: return 0 ...
stack_v2_sparse_classes_36k_train_006004
2,222
no_license
[ { "docstring": "top down", "name": "strangePrinter", "signature": "def strangePrinter(self, s: str) -> int" }, { "docstring": "bottom up", "name": "strangePrinter", "signature": "def strangePrinter(self, s: str) -> int" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def strangePrinter(self, s: str) -> int: top down - def strangePrinter(self, s: str) -> int: bottom up
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def strangePrinter(self, s: str) -> int: top down - def strangePrinter(self, s: str) -> int: bottom up <|skeleton|> class Solution: def strangePrinter(self, s: str) -> int:...
6ff1941ff213a843013100ac7033e2d4f90fbd6a
<|skeleton|> class Solution: def strangePrinter(self, s: str) -> int: """top down""" <|body_0|> def strangePrinter(self, s: str) -> int: """bottom up""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def strangePrinter(self, s: str) -> int: """top down""" def dp(i, j, memo): if i > j: return 0 if i == j: return 1 if (i, j) not in memo: ans = float('inf') for k in range(i, j): ...
the_stack_v2_python_sparse
Leetcode 0664. Strange Printer.py
Chaoran-sjsu/leetcode
train
0
cec4325b3cb154ce77ab0b3e6d677ba17595c922
[ "if self.window.editors:\n self.enabled = True\nelse:\n self.enabled = False", "active_editor = self.window.active_editor\nif self.enabled and active_editor is not None:\n active_editor.save_as()" ]
<|body_start_0|> if self.window.editors: self.enabled = True else: self.enabled = False <|end_body_0|> <|body_start_1|> active_editor = self.window.active_editor if self.enabled and active_editor is not None: active_editor.save_as() <|end_body_1|>
Defines an action that save the contents of the current editor to a new name.
SaveAsAction
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SaveAsAction: """Defines an action that save the contents of the current editor to a new name.""" def _active_editor_changed_for_window(self): """Enables the action if the window has editors.""" <|body_0|> def perform(self, event): """Performs the action.""" ...
stack_v2_sparse_classes_36k_train_006005
3,865
permissive
[ { "docstring": "Enables the action if the window has editors.", "name": "_active_editor_changed_for_window", "signature": "def _active_editor_changed_for_window(self)" }, { "docstring": "Performs the action.", "name": "perform", "signature": "def perform(self, event)" } ]
2
null
Implement the Python class `SaveAsAction` described below. Class description: Defines an action that save the contents of the current editor to a new name. Method signatures and docstrings: - def _active_editor_changed_for_window(self): Enables the action if the window has editors. - def perform(self, event): Perform...
Implement the Python class `SaveAsAction` described below. Class description: Defines an action that save the contents of the current editor to a new name. Method signatures and docstrings: - def _active_editor_changed_for_window(self): Enables the action if the window has editors. - def perform(self, event): Perform...
e8fc0b2d6b9b08e60389fc4714a5cf51f628b57f
<|skeleton|> class SaveAsAction: """Defines an action that save the contents of the current editor to a new name.""" def _active_editor_changed_for_window(self): """Enables the action if the window has editors.""" <|body_0|> def perform(self, event): """Performs the action.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SaveAsAction: """Defines an action that save the contents of the current editor to a new name.""" def _active_editor_changed_for_window(self): """Enables the action if the window has editors.""" if self.window.editors: self.enabled = True else: self.enabled...
the_stack_v2_python_sparse
puddle/resource/action/save_as_action.py
rwl/puddle
train
2
ae70c7ecca3cafd5d6bdce7dae3694e56b4b5cd6
[ "import sys\nresult = [0] * len(nums)\nfor i in range(len(nums) - 2, -1, -1):\n if nums[i] == 0:\n result[i] = sys.maxint\n else:\n result[i] = min(result[i + 1:nums[i] + i + 1]) + 1\nreturn result[0]", "n, start, end, step = (len(nums), 0, 0, 0)\nwhile end < n - 1:\n step += 1\n maxend ...
<|body_start_0|> import sys result = [0] * len(nums) for i in range(len(nums) - 2, -1, -1): if nums[i] == 0: result[i] = sys.maxint else: result[i] = min(result[i + 1:nums[i] + i + 1]) + 1 return result[0] <|end_body_0|> <|body_sta...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def jump(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def jump2(self, nums): """https://discuss.leetcode.com/topic/18815/10-lines-c-16ms-python-bfs-solutions-with-explanations/2 This problem has a nice BFS structure. Let’s illustrate it u...
stack_v2_sparse_classes_36k_train_006006
2,401
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "jump", "signature": "def jump(self, nums)" }, { "docstring": "https://discuss.leetcode.com/topic/18815/10-lines-c-16ms-python-bfs-solutions-with-explanations/2 This problem has a nice BFS structure. Let’s illustrate it using the exampl...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def jump(self, nums): :type nums: List[int] :rtype: int - def jump2(self, nums): https://discuss.leetcode.com/topic/18815/10-lines-c-16ms-python-bfs-solutions-with-explanations/2...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def jump(self, nums): :type nums: List[int] :rtype: int - def jump2(self, nums): https://discuss.leetcode.com/topic/18815/10-lines-c-16ms-python-bfs-solutions-with-explanations/2...
2526f8c0dec7101123123740e146ee4081e979ee
<|skeleton|> class Solution: def jump(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def jump2(self, nums): """https://discuss.leetcode.com/topic/18815/10-lines-c-16ms-python-bfs-solutions-with-explanations/2 This problem has a nice BFS structure. Let’s illustrate it u...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def jump(self, nums): """:type nums: List[int] :rtype: int""" import sys result = [0] * len(nums) for i in range(len(nums) - 2, -1, -1): if nums[i] == 0: result[i] = sys.maxint else: result[i] = min(result[i + 1:...
the_stack_v2_python_sparse
045. Jump Game II.py
zhangpengGenedock/leetcode_python
train
1
728954c7c78b3d24462af871db4ae633d72135aa
[ "super(DiagnosticAuditListener, self).__init__()\nself._config = config\nconnection_string = self._config.get_logging_db_connection_string()\nengine = create_engine(connection_string)\nDiagnostic.__table__.create(bind=engine, checkfirst=True)", "if type(event) is DiagnosticEvent:\n connection_string = self._co...
<|body_start_0|> super(DiagnosticAuditListener, self).__init__() self._config = config connection_string = self._config.get_logging_db_connection_string() engine = create_engine(connection_string) Diagnostic.__table__.create(bind=engine, checkfirst=True) <|end_body_0|> <|body_st...
Implementation for the diagnostic listener that saves diagnostic logs to the database.
DiagnosticAuditListener
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DiagnosticAuditListener: """Implementation for the diagnostic listener that saves diagnostic logs to the database.""" def __init__(self, config: Configuration): """Constructor""" <|body_0|> def record_event(self, event: DiagnosticEvent): """method for handling au...
stack_v2_sparse_classes_36k_train_006007
3,486
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, config: Configuration)" }, { "docstring": "method for handling auditable events to be implemented by listeners. :param event: The event. :type event: :py:class:`lostservice.logging.diagnostic.AuditableEvent`", ...
2
stack_v2_sparse_classes_30k_test_000428
Implement the Python class `DiagnosticAuditListener` described below. Class description: Implementation for the diagnostic listener that saves diagnostic logs to the database. Method signatures and docstrings: - def __init__(self, config: Configuration): Constructor - def record_event(self, event: DiagnosticEvent): m...
Implement the Python class `DiagnosticAuditListener` described below. Class description: Implementation for the diagnostic listener that saves diagnostic logs to the database. Method signatures and docstrings: - def __init__(self, config: Configuration): Constructor - def record_event(self, event: DiagnosticEvent): m...
5a41d09a922f0b239893c99ae9a9626f020bf3f9
<|skeleton|> class DiagnosticAuditListener: """Implementation for the diagnostic listener that saves diagnostic logs to the database.""" def __init__(self, config: Configuration): """Constructor""" <|body_0|> def record_event(self, event: DiagnosticEvent): """method for handling au...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DiagnosticAuditListener: """Implementation for the diagnostic listener that saves diagnostic logs to the database.""" def __init__(self, config: Configuration): """Constructor""" super(DiagnosticAuditListener, self).__init__() self._config = config connection_string = self...
the_stack_v2_python_sparse
lostservice/logger/diagnosticsaudit.py
ravinash496/lostservice
train
1
0f61feb7419e0c6df1bf35a9b06e8bd84a19f9e5
[ "super(TorchVisionSSLDCL, self).__init__()\nself.model_function = get_object_from_path(config.cfg['model']['model_function_path'])\nself.pretrained = config.cfg['model']['pretrained']\nself.num_classes = config.cfg['model']['classes_count']\nself.prediction_type = config.cfg['model']['prediction_type']\njigsaw_size...
<|body_start_0|> super(TorchVisionSSLDCL, self).__init__() self.model_function = get_object_from_path(config.cfg['model']['model_function_path']) self.pretrained = config.cfg['model']['pretrained'] self.num_classes = config.cfg['model']['classes_count'] self.prediction_type = con...
The class adds the DCL-SSL task to the standard specified torchvision model.
TorchVisionSSLDCL
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TorchVisionSSLDCL: """The class adds the DCL-SSL task to the standard specified torchvision model.""" def __init__(self, config): """Constructor, The function parse the config and initialize the layers of the corresponding model. :param config: Configuration class object""" <...
stack_v2_sparse_classes_36k_train_006008
4,500
permissive
[ { "docstring": "Constructor, The function parse the config and initialize the layers of the corresponding model. :param config: Configuration class object", "name": "__init__", "signature": "def __init__(self, config)" }, { "docstring": "The function implements the forward pass of the model. :pa...
2
stack_v2_sparse_classes_30k_train_011206
Implement the Python class `TorchVisionSSLDCL` described below. Class description: The class adds the DCL-SSL task to the standard specified torchvision model. Method signatures and docstrings: - def __init__(self, config): Constructor, The function parse the config and initialize the layers of the corresponding mode...
Implement the Python class `TorchVisionSSLDCL` described below. Class description: The class adds the DCL-SSL task to the standard specified torchvision model. Method signatures and docstrings: - def __init__(self, config): Constructor, The function parse the config and initialize the layers of the corresponding mode...
9a4bf0a112b818caca8794868a903dc736839a43
<|skeleton|> class TorchVisionSSLDCL: """The class adds the DCL-SSL task to the standard specified torchvision model.""" def __init__(self, config): """Constructor, The function parse the config and initialize the layers of the corresponding model. :param config: Configuration class object""" <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TorchVisionSSLDCL: """The class adds the DCL-SSL task to the standard specified torchvision model.""" def __init__(self, config): """Constructor, The function parse the config and initialize the layers of the corresponding model. :param config: Configuration class object""" super(TorchVis...
the_stack_v2_python_sparse
model/torchvision_ssl_dcl.py
Niousha12/ssl_for_fgvc
train
0
3b94f443693a2e332147080ed39b32323363f3cd
[ "response = super(UploadedFileDetail, self).retrieve(request, *args, **kwargs)\ntemplate_data = {'upload_path': ''}\nreturn services.append_collection_template(response, template_data)", "user_file = self.get_object()\nrequest.data['fname'] = user_file.fname.file\nreturn super(UploadedFileDetail, self).update(req...
<|body_start_0|> response = super(UploadedFileDetail, self).retrieve(request, *args, **kwargs) template_data = {'upload_path': ''} return services.append_collection_template(response, template_data) <|end_body_0|> <|body_start_1|> user_file = self.get_object() request.data['fnam...
An uploaded file view.
UploadedFileDetail
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UploadedFileDetail: """An uploaded file view.""" def retrieve(self, request, *args, **kwargs): """Overriden to append a collection+json template.""" <|body_0|> def update(self, request, *args, **kwargs): """Overriden to include the current fname in the request.""...
stack_v2_sparse_classes_36k_train_006009
4,631
permissive
[ { "docstring": "Overriden to append a collection+json template.", "name": "retrieve", "signature": "def retrieve(self, request, *args, **kwargs)" }, { "docstring": "Overriden to include the current fname in the request.", "name": "update", "signature": "def update(self, request, *args, *...
4
null
Implement the Python class `UploadedFileDetail` described below. Class description: An uploaded file view. Method signatures and docstrings: - def retrieve(self, request, *args, **kwargs): Overriden to append a collection+json template. - def update(self, request, *args, **kwargs): Overriden to include the current fn...
Implement the Python class `UploadedFileDetail` described below. Class description: An uploaded file view. Method signatures and docstrings: - def retrieve(self, request, *args, **kwargs): Overriden to append a collection+json template. - def update(self, request, *args, **kwargs): Overriden to include the current fn...
20d3eedf20610af9182f6cca8db8f0b3546b5336
<|skeleton|> class UploadedFileDetail: """An uploaded file view.""" def retrieve(self, request, *args, **kwargs): """Overriden to append a collection+json template.""" <|body_0|> def update(self, request, *args, **kwargs): """Overriden to include the current fname in the request.""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UploadedFileDetail: """An uploaded file view.""" def retrieve(self, request, *args, **kwargs): """Overriden to append a collection+json template.""" response = super(UploadedFileDetail, self).retrieve(request, *args, **kwargs) template_data = {'upload_path': ''} return ser...
the_stack_v2_python_sparse
chris_backend/uploadedfiles/views.py
FNNDSC/ChRIS_ultron_backEnd
train
36
ce67b3fb4b8a39b74756164ff3b12d01115d18b1
[ "if detection is None:\n if imageWithFaceDetection is None:\n raise ValueError('image and boundingBox or detection must be not None')\n error, ags = self._coreEstimator.estimate(imageWithFaceDetection.image.coreImage, imageWithFaceDetection.boundingBox.coreEstimation)\nelse:\n error, ags = self._cor...
<|body_start_0|> if detection is None: if imageWithFaceDetection is None: raise ValueError('image and boundingBox or detection must be not None') error, ags = self._coreEstimator.estimate(imageWithFaceDetection.image.coreImage, imageWithFaceDetection.boundingBox.coreEstim...
Approximate garbage score estimator.
AGSEstimator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AGSEstimator: """Approximate garbage score estimator.""" def estimate(self, detection: Optional[FaceDetection]=None, imageWithFaceDetection: Optional[ImageWithFaceDetection]=None) -> float: """Estimate ags for single image/detection. Args: detection: face detection imageWithFaceDetec...
stack_v2_sparse_classes_36k_train_006010
2,508
permissive
[ { "docstring": "Estimate ags for single image/detection. Args: detection: face detection imageWithFaceDetection: image with face detection Returns: estimated ags, float in range[0,1] Raises: LunaSDKException: if estimation failed ValueError: if image and detection are None", "name": "estimate", "signatu...
2
stack_v2_sparse_classes_30k_train_016650
Implement the Python class `AGSEstimator` described below. Class description: Approximate garbage score estimator. Method signatures and docstrings: - def estimate(self, detection: Optional[FaceDetection]=None, imageWithFaceDetection: Optional[ImageWithFaceDetection]=None) -> float: Estimate ags for single image/dete...
Implement the Python class `AGSEstimator` described below. Class description: Approximate garbage score estimator. Method signatures and docstrings: - def estimate(self, detection: Optional[FaceDetection]=None, imageWithFaceDetection: Optional[ImageWithFaceDetection]=None) -> float: Estimate ags for single image/dete...
7a4bebc92ae7a96d8d9c18a024208308942f90cd
<|skeleton|> class AGSEstimator: """Approximate garbage score estimator.""" def estimate(self, detection: Optional[FaceDetection]=None, imageWithFaceDetection: Optional[ImageWithFaceDetection]=None) -> float: """Estimate ags for single image/detection. Args: detection: face detection imageWithFaceDetec...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AGSEstimator: """Approximate garbage score estimator.""" def estimate(self, detection: Optional[FaceDetection]=None, imageWithFaceDetection: Optional[ImageWithFaceDetection]=None) -> float: """Estimate ags for single image/detection. Args: detection: face detection imageWithFaceDetection: image w...
the_stack_v2_python_sparse
lunavl/sdk/estimators/face_estimators/ags.py
matemax/lunasdk
train
16
dcc10fed9f7619ff264c9026366aec95116d1125
[ "logs = None\nlogsDao = LogsDao()\ntry:\n logs = logsDao.add(args)\nexcept Exception as e:\n abort(500, e)\nreturn logs", "record = None\nlogsDao = LogsDao()\ntry:\n record = logsDao.edit(args)\nexcept Exception as e:\n abort(500, e)\nreturn record", "record = None\nlogsDao = LogsDao()\nid = args.ge...
<|body_start_0|> logs = None logsDao = LogsDao() try: logs = logsDao.add(args) except Exception as e: abort(500, e) return logs <|end_body_0|> <|body_start_1|> record = None logsDao = LogsDao() try: record = logsDao.edi...
UserLogsAPI
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserLogsAPI: def post(self, args): """add""" <|body_0|> def put(self, args): """edit""" <|body_1|> def get(self, args): """view""" <|body_2|> def delete(self, args): """del""" <|body_3|> <|end_skeleton|> <|body_star...
stack_v2_sparse_classes_36k_train_006011
5,130
permissive
[ { "docstring": "add", "name": "post", "signature": "def post(self, args)" }, { "docstring": "edit", "name": "put", "signature": "def put(self, args)" }, { "docstring": "view", "name": "get", "signature": "def get(self, args)" }, { "docstring": "del", "name": "...
4
stack_v2_sparse_classes_30k_train_008499
Implement the Python class `UserLogsAPI` described below. Class description: Implement the UserLogsAPI class. Method signatures and docstrings: - def post(self, args): add - def put(self, args): edit - def get(self, args): view - def delete(self, args): del
Implement the Python class `UserLogsAPI` described below. Class description: Implement the UserLogsAPI class. Method signatures and docstrings: - def post(self, args): add - def put(self, args): edit - def get(self, args): view - def delete(self, args): del <|skeleton|> class UserLogsAPI: def post(self, args): ...
0fb1b604185a8bd8b72c1d2d527fb94bbaf46a86
<|skeleton|> class UserLogsAPI: def post(self, args): """add""" <|body_0|> def put(self, args): """edit""" <|body_1|> def get(self, args): """view""" <|body_2|> def delete(self, args): """del""" <|body_3|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserLogsAPI: def post(self, args): """add""" logs = None logsDao = LogsDao() try: logs = logsDao.add(args) except Exception as e: abort(500, e) return logs def put(self, args): """edit""" record = None logsDao...
the_stack_v2_python_sparse
app/modules/logs/resource.py
daitouli/baoaiback
train
0
8f0bfc2691fb6555ef86be6d3891f0045f14df30
[ "edit = QLineEdit(parent)\ncompleter = QCompleter()\nedit.setCompleter(completer)\nmodel = QStringListModel()\ncompleter.setModel(model)\nself.setCompleterData(model)\nreturn edit", "categoryNames = []\nfor category in Categories.all():\n if category.name is not None:\n categoryNames.append(category.nam...
<|body_start_0|> edit = QLineEdit(parent) completer = QCompleter() edit.setCompleter(completer) model = QStringListModel() completer.setModel(model) self.setCompleterData(model) return edit <|end_body_0|> <|body_start_1|> categoryNames = [] for ca...
Transaction Category View Delegate
TransactionCategoryDelegate
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransactionCategoryDelegate: """Transaction Category View Delegate""" def createEditor(self, parent, option, index): """Should return a LineEdit with all the Category Names as AutoComplete values""" <|body_0|> def setCompleterData(self, model): """Set Completer D...
stack_v2_sparse_classes_36k_train_006012
902
no_license
[ { "docstring": "Should return a LineEdit with all the Category Names as AutoComplete values", "name": "createEditor", "signature": "def createEditor(self, parent, option, index)" }, { "docstring": "Set Completer Data to use Category data", "name": "setCompleterData", "signature": "def se...
2
null
Implement the Python class `TransactionCategoryDelegate` described below. Class description: Transaction Category View Delegate Method signatures and docstrings: - def createEditor(self, parent, option, index): Should return a LineEdit with all the Category Names as AutoComplete values - def setCompleterData(self, mo...
Implement the Python class `TransactionCategoryDelegate` described below. Class description: Transaction Category View Delegate Method signatures and docstrings: - def createEditor(self, parent, option, index): Should return a LineEdit with all the Category Names as AutoComplete values - def setCompleterData(self, mo...
57c909c8581bef3b66388038a1cf5edda426ecf9
<|skeleton|> class TransactionCategoryDelegate: """Transaction Category View Delegate""" def createEditor(self, parent, option, index): """Should return a LineEdit with all the Category Names as AutoComplete values""" <|body_0|> def setCompleterData(self, model): """Set Completer D...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TransactionCategoryDelegate: """Transaction Category View Delegate""" def createEditor(self, parent, option, index): """Should return a LineEdit with all the Category Names as AutoComplete values""" edit = QLineEdit(parent) completer = QCompleter() edit.setCompleter(comple...
the_stack_v2_python_sparse
src/Qt/GUI/Transaction/Table/Columns/Delegates/transaction_category_delegate.py
cloew/PersonalAccountingSoftware
train
0
7e2841e5b537b7703a023a97c95afe11eba68076
[ "self.open_tag = open_tag\nself.close_tag = close_tag\nself.content = [content]\nif kwargs:\n self.open_tag = open_tag.strip('>')\n for key in kwargs:\n self.open_tag += ' {}=\"{}\"'.format(key, kwargs[key])\n self.open_tag += '>'", "if hasattr(content, 'render') and self.content:\n self.conten...
<|body_start_0|> self.open_tag = open_tag self.close_tag = close_tag self.content = [content] if kwargs: self.open_tag = open_tag.strip('>') for key in kwargs: self.open_tag += ' {}="{}"'.format(key, kwargs[key]) self.open_tag += '>' <|...
Parent class for all html elements to be created.
Element
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Element: """Parent class for all html elements to be created.""" def __init__(self, open_tag='<html>', close_tag='</html>', content=None, **kwargs): """Constructor for Element objects. :param open_tag="<html>": set opening tag parameter to html should none be given :param close_tag="...
stack_v2_sparse_classes_36k_train_006013
7,157
no_license
[ { "docstring": "Constructor for Element objects. :param open_tag=\"<html>\": set opening tag parameter to html should none be given :param close_tag=\"</html>\": set closing tag parameter to html should none be given :param content=None: set content value to NoneType if no content associated", "name": "__in...
3
null
Implement the Python class `Element` described below. Class description: Parent class for all html elements to be created. Method signatures and docstrings: - def __init__(self, open_tag='<html>', close_tag='</html>', content=None, **kwargs): Constructor for Element objects. :param open_tag="<html>": set opening tag ...
Implement the Python class `Element` described below. Class description: Parent class for all html elements to be created. Method signatures and docstrings: - def __init__(self, open_tag='<html>', close_tag='</html>', content=None, **kwargs): Constructor for Element objects. :param open_tag="<html>": set opening tag ...
e298b1151dab639659d8dfa56f47bcb43dd3438f
<|skeleton|> class Element: """Parent class for all html elements to be created.""" def __init__(self, open_tag='<html>', close_tag='</html>', content=None, **kwargs): """Constructor for Element objects. :param open_tag="<html>": set opening tag parameter to html should none be given :param close_tag="...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Element: """Parent class for all html elements to be created.""" def __init__(self, open_tag='<html>', close_tag='</html>', content=None, **kwargs): """Constructor for Element objects. :param open_tag="<html>": set opening tag parameter to html should none be given :param close_tag="</html>": set...
the_stack_v2_python_sparse
students/ian_letourneau/Lesson07/html_render.py
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
train
13
76858d8ed3bf6b2c0d6a0bf1ea6101e5ef57a931
[ "self.datastore_id = datastore_id\nself.file_restore_info = file_restore_info\nself.name = name\nself.objects = objects\nself.protection_source_name = protection_source_name\nself.start_time_usecs = start_time_usecs\nself.mtype = mtype\nself.username = username", "if dictionary is None:\n return None\ndatastor...
<|body_start_0|> self.datastore_id = datastore_id self.file_restore_info = file_restore_info self.name = name self.objects = objects self.protection_source_name = protection_source_name self.start_time_usecs = start_time_usecs self.mtype = mtype self.usern...
Implementation of the 'RestoreSourceSummaryByObjectTypeElement' model. RestoreSourceSummaryByObjectTypeElement represents a recover/clone summary for a single object type. Attributes: datastore_id (long|int): Specifies the datastore where the object's files are recovered to. This field is populated when objects are rec...
RestoreSourceSummaryByObjectTypeElement
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RestoreSourceSummaryByObjectTypeElement: """Implementation of the 'RestoreSourceSummaryByObjectTypeElement' model. RestoreSourceSummaryByObjectTypeElement represents a recover/clone summary for a single object type. Attributes: datastore_id (long|int): Specifies the datastore where the object's f...
stack_v2_sparse_classes_36k_train_006014
6,343
permissive
[ { "docstring": "Constructor for the RestoreSourceSummaryByObjectTypeElement class", "name": "__init__", "signature": "def __init__(self, datastore_id=None, file_restore_info=None, name=None, objects=None, protection_source_name=None, start_time_usecs=None, mtype=None, username=None)" }, { "docst...
2
stack_v2_sparse_classes_30k_train_000582
Implement the Python class `RestoreSourceSummaryByObjectTypeElement` described below. Class description: Implementation of the 'RestoreSourceSummaryByObjectTypeElement' model. RestoreSourceSummaryByObjectTypeElement represents a recover/clone summary for a single object type. Attributes: datastore_id (long|int): Speci...
Implement the Python class `RestoreSourceSummaryByObjectTypeElement` described below. Class description: Implementation of the 'RestoreSourceSummaryByObjectTypeElement' model. RestoreSourceSummaryByObjectTypeElement represents a recover/clone summary for a single object type. Attributes: datastore_id (long|int): Speci...
0093194d125fc6746f55b8499da1270c64f473fc
<|skeleton|> class RestoreSourceSummaryByObjectTypeElement: """Implementation of the 'RestoreSourceSummaryByObjectTypeElement' model. RestoreSourceSummaryByObjectTypeElement represents a recover/clone summary for a single object type. Attributes: datastore_id (long|int): Specifies the datastore where the object's f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RestoreSourceSummaryByObjectTypeElement: """Implementation of the 'RestoreSourceSummaryByObjectTypeElement' model. RestoreSourceSummaryByObjectTypeElement represents a recover/clone summary for a single object type. Attributes: datastore_id (long|int): Specifies the datastore where the object's files are reco...
the_stack_v2_python_sparse
cohesity_management_sdk/models/restore_source_summary_by_object_type_element.py
hsantoyo2/management-sdk-python
train
0
8b237c6d702babcf3abc0ba3bd831ab06bde0d22
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn InferenceClassificationOverride()", "from .email_address import EmailAddress\nfrom .entity import Entity\nfrom .inference_classification_type import InferenceClassificationType\nfrom .email_address import EmailAddress\nfrom .entity imp...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return InferenceClassificationOverride() <|end_body_0|> <|body_start_1|> from .email_address import EmailAddress from .entity import Entity from .inference_classification_type import In...
InferenceClassificationOverride
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InferenceClassificationOverride: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InferenceClassificationOverride: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator...
stack_v2_sparse_classes_36k_train_006015
2,897
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: InferenceClassificationOverride", "name": "create_from_discriminator_value", "signature": "def create_from_d...
3
null
Implement the Python class `InferenceClassificationOverride` described below. Class description: Implement the InferenceClassificationOverride class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InferenceClassificationOverride: Creates a new instance...
Implement the Python class `InferenceClassificationOverride` described below. Class description: Implement the InferenceClassificationOverride class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InferenceClassificationOverride: Creates a new instance...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class InferenceClassificationOverride: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InferenceClassificationOverride: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InferenceClassificationOverride: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InferenceClassificationOverride: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and cre...
the_stack_v2_python_sparse
msgraph/generated/models/inference_classification_override.py
microsoftgraph/msgraph-sdk-python
train
135
fbbb0d6a9f0ee144b78aecc0f1a0cd0bad3c45ad
[ "data = self._current_data\nkwargs = super(ClusterSerializer, self).data_info()\nif kwargs and self._detail:\n pass\nreturn kwargs", "data = self._current_data\nhosts = data.host\nbest_host = None\nbest_perform = 0\nfor host in hosts:\n host_serializer = HostSystemSerializer(host).data\n free_mem_mb = ho...
<|body_start_0|> data = self._current_data kwargs = super(ClusterSerializer, self).data_info() if kwargs and self._detail: pass return kwargs <|end_body_0|> <|body_start_1|> data = self._current_data hosts = data.host best_host = None best_per...
集群数据处理
ClusterSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClusterSerializer: """集群数据处理""" def data_info(self): """* 返回字段 ** moid ** name""" <|body_0|> def best_host_of_mb(self): """内存最优主机""" <|body_1|> <|end_skeleton|> <|body_start_0|> data = self._current_data kwargs = super(ClusterSerializer,...
stack_v2_sparse_classes_36k_train_006016
12,928
no_license
[ { "docstring": "* 返回字段 ** moid ** name", "name": "data_info", "signature": "def data_info(self)" }, { "docstring": "内存最优主机", "name": "best_host_of_mb", "signature": "def best_host_of_mb(self)" } ]
2
stack_v2_sparse_classes_30k_test_000209
Implement the Python class `ClusterSerializer` described below. Class description: 集群数据处理 Method signatures and docstrings: - def data_info(self): * 返回字段 ** moid ** name - def best_host_of_mb(self): 内存最优主机
Implement the Python class `ClusterSerializer` described below. Class description: 集群数据处理 Method signatures and docstrings: - def data_info(self): * 返回字段 ** moid ** name - def best_host_of_mb(self): 内存最优主机 <|skeleton|> class ClusterSerializer: """集群数据处理""" def data_info(self): """* 返回字段 ** moid ** n...
639f11a91ee6e8b72883300cbf297ef4c0494d52
<|skeleton|> class ClusterSerializer: """集群数据处理""" def data_info(self): """* 返回字段 ** moid ** name""" <|body_0|> def best_host_of_mb(self): """内存最优主机""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClusterSerializer: """集群数据处理""" def data_info(self): """* 返回字段 ** moid ** name""" data = self._current_data kwargs = super(ClusterSerializer, self).data_info() if kwargs and self._detail: pass return kwargs def best_host_of_mb(self): """内存最...
the_stack_v2_python_sparse
ivmware/serializers.py
caijb007/itmsp
train
0
d535846de779f801a29130c99bd4f5bd2d82d873
[ "assert category in ERROR_CATEGORIES\nself.relpath = relpath\nself.category = category\nself.message = message\nself.fix_it = fix_it\nERROR_COUNTS[category] += 1\nif not FLAGS.counts:\n print(f'{relpath}: {shell.ShellEscapeCodes.YELLOW}{message}{shell.ShellEscapeCodes.END} [{category}]', file=sys.stderr)\n ...
<|body_start_0|> assert category in ERROR_CATEGORIES self.relpath = relpath self.category = category self.message = message self.fix_it = fix_it ERROR_COUNTS[category] += 1 if not FLAGS.counts: print(f'{relpath}: {shell.ShellEscapeCodes.YELLOW}{messag...
A linter error.
Error
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Error: """A linter error.""" def __init__(self, relpath: str, category: str, message: str, fix_it: str=None): """Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag was passed, the command is printed to stdout. All other out...
stack_v2_sparse_classes_36k_train_006017
16,624
permissive
[ { "docstring": "Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag was passed, the command is printed to stdout. All other output is to stderr.", "name": "__init__", "signature": "def __init__(self, relpath: str, category: str, message: str, f...
2
null
Implement the Python class `Error` described below. Class description: A linter error. Method signatures and docstrings: - def __init__(self, relpath: str, category: str, message: str, fix_it: str=None): Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag wa...
Implement the Python class `Error` described below. Class description: A linter error. Method signatures and docstrings: - def __init__(self, relpath: str, category: str, message: str, fix_it: str=None): Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag wa...
22fccacb63b261eade1e1a41ab52a5ea6c542e91
<|skeleton|> class Error: """A linter error.""" def __init__(self, relpath: str, category: str, message: str, fix_it: str=None): """Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag was passed, the command is printed to stdout. All other out...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Error: """A linter error.""" def __init__(self, relpath: str, category: str, message: str, fix_it: str=None): """Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag was passed, the command is printed to stdout. All other output is to std...
the_stack_v2_python_sparse
util/photolib/linters.py
50417/phd
train
1
82459b1f606a4525a12d66682100324516a9b64b
[ "if globals.G_TUNNEL_NUM > len(globals.G_TUNNEL_GROUP_INFO):\n self._TunnelGroupNumber = len(globals.G_TUNNEL_GROUP_INFO)\nelse:\n self._TunnelGroupNumber = globals.G_TUNNEL_NUM\nself._TunnelGroupInfo = globals.G_TUNNEL_GROUP_INFO\nself._TunnelGroupList = tunnelgrouplist\nself._TunnelWorkerQueue = tunnelworke...
<|body_start_0|> if globals.G_TUNNEL_NUM > len(globals.G_TUNNEL_GROUP_INFO): self._TunnelGroupNumber = len(globals.G_TUNNEL_GROUP_INFO) else: self._TunnelGroupNumber = globals.G_TUNNEL_NUM self._TunnelGroupInfo = globals.G_TUNNEL_GROUP_INFO self._TunnelGroupList =...
ListenService服务 监听本地连接,并读取数据存放到队列中
ListenService
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ListenService: """ListenService服务 监听本地连接,并读取数据存放到队列中""" def __init__(self, tunnelgrouplist, tunnelworkerqueue, tunnelworksmanager): """监听服务初始化""" <|body_0|> def start(self): """监听服务启动""" <|body_1|> def stop(self): """监听服务停止""" <|body_...
stack_v2_sparse_classes_36k_train_006018
4,968
no_license
[ { "docstring": "监听服务初始化", "name": "__init__", "signature": "def __init__(self, tunnelgrouplist, tunnelworkerqueue, tunnelworksmanager)" }, { "docstring": "监听服务启动", "name": "start", "signature": "def start(self)" }, { "docstring": "监听服务停止", "name": "stop", "signature": "de...
4
stack_v2_sparse_classes_30k_train_018941
Implement the Python class `ListenService` described below. Class description: ListenService服务 监听本地连接,并读取数据存放到队列中 Method signatures and docstrings: - def __init__(self, tunnelgrouplist, tunnelworkerqueue, tunnelworksmanager): 监听服务初始化 - def start(self): 监听服务启动 - def stop(self): 监听服务停止 - def generator(self, tunnelgroup...
Implement the Python class `ListenService` described below. Class description: ListenService服务 监听本地连接,并读取数据存放到队列中 Method signatures and docstrings: - def __init__(self, tunnelgrouplist, tunnelworkerqueue, tunnelworksmanager): 监听服务初始化 - def start(self): 监听服务启动 - def stop(self): 监听服务停止 - def generator(self, tunnelgroup...
c19d8c7ad189b84943abde6684d31f279fca4b21
<|skeleton|> class ListenService: """ListenService服务 监听本地连接,并读取数据存放到队列中""" def __init__(self, tunnelgrouplist, tunnelworkerqueue, tunnelworksmanager): """监听服务初始化""" <|body_0|> def start(self): """监听服务启动""" <|body_1|> def stop(self): """监听服务停止""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ListenService: """ListenService服务 监听本地连接,并读取数据存放到队列中""" def __init__(self, tunnelgrouplist, tunnelworkerqueue, tunnelworksmanager): """监听服务初始化""" if globals.G_TUNNEL_NUM > len(globals.G_TUNNEL_GROUP_INFO): self._TunnelGroupNumber = len(globals.G_TUNNEL_GROUP_INFO) else...
the_stack_v2_python_sparse
Client/ListenService.py
lixingke3650/OrTunnel
train
1
f17bc693587f8cf15c9c808117c8599155ca5f19
[ "self.erase_prob = erase_prob\nself.noise_type = noise_type\nself.use_keys = use_keys\nself.ignore_keys = ignore_keys\nself.num_patches = num_patches\nif not (isinstance(num_patches, tuple) or isinstance(num_patches, list)):\n self.num_patches = (num_patches, num_patches)\nself.patch_size = patch_size\nif len(pa...
<|body_start_0|> self.erase_prob = erase_prob self.noise_type = noise_type self.use_keys = use_keys self.ignore_keys = ignore_keys self.num_patches = num_patches if not (isinstance(num_patches, tuple) or isinstance(num_patches, list)): self.num_patches = (num_...
Randomly covers a rectangular patch on the second image with noise, to simulate a pseudo-occlusion. The noise_type may be the mean or random. This transform erases patches ONLY FROM THE SECOND IMAGE.
RandomPatchEraser
[ "Apache-2.0", "CC-BY-NC-SA-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomPatchEraser: """Randomly covers a rectangular patch on the second image with noise, to simulate a pseudo-occlusion. The noise_type may be the mean or random. This transform erases patches ONLY FROM THE SECOND IMAGE.""" def __init__(self, erase_prob: float=0.0, num_patches: Union[int, T...
stack_v2_sparse_classes_36k_train_006019
42,078
permissive
[ { "docstring": "Initialize RandomPatchEraser. Parameters ---------- erase_prob : float, default 0.0 Probability of applying the transformation. num_patches : Union[int, Tuple[int, int]], default 1 Number of occlusion patches to generate. If it is a tuple, the number will be uniformly sampled from the interval. ...
2
stack_v2_sparse_classes_30k_train_016742
Implement the Python class `RandomPatchEraser` described below. Class description: Randomly covers a rectangular patch on the second image with noise, to simulate a pseudo-occlusion. The noise_type may be the mean or random. This transform erases patches ONLY FROM THE SECOND IMAGE. Method signatures and docstrings: -...
Implement the Python class `RandomPatchEraser` described below. Class description: Randomly covers a rectangular patch on the second image with noise, to simulate a pseudo-occlusion. The noise_type may be the mean or random. This transform erases patches ONLY FROM THE SECOND IMAGE. Method signatures and docstrings: -...
d6582a0fd386517fdefbe2c347cef53150b5b1da
<|skeleton|> class RandomPatchEraser: """Randomly covers a rectangular patch on the second image with noise, to simulate a pseudo-occlusion. The noise_type may be the mean or random. This transform erases patches ONLY FROM THE SECOND IMAGE.""" def __init__(self, erase_prob: float=0.0, num_patches: Union[int, T...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomPatchEraser: """Randomly covers a rectangular patch on the second image with noise, to simulate a pseudo-occlusion. The noise_type may be the mean or random. This transform erases patches ONLY FROM THE SECOND IMAGE.""" def __init__(self, erase_prob: float=0.0, num_patches: Union[int, Tuple[int, int...
the_stack_v2_python_sparse
ptlflow/data/flow_transforms.py
hmorimitsu/ptlflow
train
140
e0e80121ce67196f4800a7c804d9437046661766
[ "__method_name = inspect.currentframe().f_code.co_name\ntry:\n sentinel_pattern = indicator.get('properties', {}).get('parsedPattern', None)\n if sentinel_pattern:\n sentinel_parsed_pattern_value = sentinel_pattern[0].get('patternTypeValues', None)\n if sentinel_parsed_pattern_value:\n ...
<|body_start_0|> __method_name = inspect.currentframe().f_code.co_name try: sentinel_pattern = indicator.get('properties', {}).get('parsedPattern', None) if sentinel_pattern: sentinel_parsed_pattern_value = sentinel_pattern[0].get('patternTypeValues', None) ...
To map field values of Sentinel and defender indicators.
SentinelToDefenderMapping
[ "MIT", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SentinelToDefenderMapping: """To map field values of Sentinel and defender indicators.""" def get_defender_indicator_value(self, indicator): """To convert sentinel indicator pattern to threat value.""" <|body_0|> def get_defender_indicator_type(self, indicator): ...
stack_v2_sparse_classes_36k_train_006020
7,343
permissive
[ { "docstring": "To convert sentinel indicator pattern to threat value.", "name": "get_defender_indicator_value", "signature": "def get_defender_indicator_value(self, indicator)" }, { "docstring": "To convert sentinel indicator type to defender accepted indicator type.", "name": "get_defender...
5
null
Implement the Python class `SentinelToDefenderMapping` described below. Class description: To map field values of Sentinel and defender indicators. Method signatures and docstrings: - def get_defender_indicator_value(self, indicator): To convert sentinel indicator pattern to threat value. - def get_defender_indicator...
Implement the Python class `SentinelToDefenderMapping` described below. Class description: To map field values of Sentinel and defender indicators. Method signatures and docstrings: - def get_defender_indicator_value(self, indicator): To convert sentinel indicator pattern to threat value. - def get_defender_indicator...
4536a3f6b9bdef902312b3d96f9c2e66b8bf52c1
<|skeleton|> class SentinelToDefenderMapping: """To map field values of Sentinel and defender indicators.""" def get_defender_indicator_value(self, indicator): """To convert sentinel indicator pattern to threat value.""" <|body_0|> def get_defender_indicator_type(self, indicator): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SentinelToDefenderMapping: """To map field values of Sentinel and defender indicators.""" def get_defender_indicator_value(self, indicator): """To convert sentinel indicator pattern to threat value.""" __method_name = inspect.currentframe().f_code.co_name try: sentinel...
the_stack_v2_python_sparse
Solutions/CofenseIntelligence/Data Connectors/CofenseIntelligenceDataConnector/SentinelToDefender/sentinel_to_defender_mapping.py
Azure/Azure-Sentinel
train
3,697
cf383b0a14facd053a7f82595112f8823ddf2042
[ "path = '/'.join([self.REQUEST_BASEURL, 'list']) + '?' + '&'.join(['src_rse={}'.format(src_rse), 'dst_rse={}'.format(dst_rse), 'request_states={}'.format(request_states)])\nurl = build_url(choice(self.list_hosts), path=path)\nr = self._send_request(url, type_='GET')\nif r.status_code == codes.ok:\n return self._...
<|body_start_0|> path = '/'.join([self.REQUEST_BASEURL, 'list']) + '?' + '&'.join(['src_rse={}'.format(src_rse), 'dst_rse={}'.format(dst_rse), 'request_states={}'.format(request_states)]) url = build_url(choice(self.list_hosts), path=path) r = self._send_request(url, type_='GET') if r.st...
RequestClient
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RequestClient: def list_requests(self, src_rse, dst_rse, request_states): """Return latest request details :return: request information :rtype: dict""" <|body_0|> def list_requests_history(self, src_rse, dst_rse, request_states, offset=0, limit=100): """Return histor...
stack_v2_sparse_classes_36k_train_006021
4,256
permissive
[ { "docstring": "Return latest request details :return: request information :rtype: dict", "name": "list_requests", "signature": "def list_requests(self, src_rse, dst_rse, request_states)" }, { "docstring": "Return historical request details :return: request information :rtype: dict", "name":...
4
stack_v2_sparse_classes_30k_train_004614
Implement the Python class `RequestClient` described below. Class description: Implement the RequestClient class. Method signatures and docstrings: - def list_requests(self, src_rse, dst_rse, request_states): Return latest request details :return: request information :rtype: dict - def list_requests_history(self, src...
Implement the Python class `RequestClient` described below. Class description: Implement the RequestClient class. Method signatures and docstrings: - def list_requests(self, src_rse, dst_rse, request_states): Return latest request details :return: request information :rtype: dict - def list_requests_history(self, src...
7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b
<|skeleton|> class RequestClient: def list_requests(self, src_rse, dst_rse, request_states): """Return latest request details :return: request information :rtype: dict""" <|body_0|> def list_requests_history(self, src_rse, dst_rse, request_states, offset=0, limit=100): """Return histor...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RequestClient: def list_requests(self, src_rse, dst_rse, request_states): """Return latest request details :return: request information :rtype: dict""" path = '/'.join([self.REQUEST_BASEURL, 'list']) + '?' + '&'.join(['src_rse={}'.format(src_rse), 'dst_rse={}'.format(dst_rse), 'request_states=...
the_stack_v2_python_sparse
lib/rucio/client/requestclient.py
rucio/rucio
train
232
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_36k_train_006022
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_train_007470
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_36k
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
558d56f7b12cc69848044feba82b7a4fb63f1586
[ "attrs = {'history': '2018-12-10Z: StaGE Decoupler', 'title': 'Temperature on UK 2 km Standard Grid', 'source': 'Met Office Unified Model'}\nself.cube = set_up_variable_cube(np.ones((11, 11), dtype=np.float32), spatial_grid='equalarea', standard_grid_metadata='uk_det', attributes=attrs)\nself.grid_spacing = np.diff...
<|body_start_0|> attrs = {'history': '2018-12-10Z: StaGE Decoupler', 'title': 'Temperature on UK 2 km Standard Grid', 'source': 'Met Office Unified Model'} self.cube = set_up_variable_cube(np.ones((11, 11), dtype=np.float32), spatial_grid='equalarea', standard_grid_metadata='uk_det', attributes=attrs) ...
Tests for the create_cube_with_halo function
Test_create_cube_with_halo
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test_create_cube_with_halo: """Tests for the create_cube_with_halo function""" def setUp(self): """Set up a realistic input cube with lots of metadata. Input cube grid is 1000x1000 km with points spaced 100 km apart.""" <|body_0|> def test_basic(self): """Test fu...
stack_v2_sparse_classes_36k_train_006023
25,212
permissive
[ { "docstring": "Set up a realistic input cube with lots of metadata. Input cube grid is 1000x1000 km with points spaced 100 km apart.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test function returns a cube with expected metadata", "name": "test_basic", "signatur...
3
null
Implement the Python class `Test_create_cube_with_halo` described below. Class description: Tests for the create_cube_with_halo function Method signatures and docstrings: - def setUp(self): Set up a realistic input cube with lots of metadata. Input cube grid is 1000x1000 km with points spaced 100 km apart. - def test...
Implement the Python class `Test_create_cube_with_halo` described below. Class description: Tests for the create_cube_with_halo function Method signatures and docstrings: - def setUp(self): Set up a realistic input cube with lots of metadata. Input cube grid is 1000x1000 km with points spaced 100 km apart. - def test...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class Test_create_cube_with_halo: """Tests for the create_cube_with_halo function""" def setUp(self): """Set up a realistic input cube with lots of metadata. Input cube grid is 1000x1000 km with points spaced 100 km apart.""" <|body_0|> def test_basic(self): """Test fu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Test_create_cube_with_halo: """Tests for the create_cube_with_halo function""" def setUp(self): """Set up a realistic input cube with lots of metadata. Input cube grid is 1000x1000 km with points spaced 100 km apart.""" attrs = {'history': '2018-12-10Z: StaGE Decoupler', 'title': 'Tempera...
the_stack_v2_python_sparse
improver_tests/utilities/test_pad_spatial.py
metoppv/improver
train
101
c7222a8ee0733ff066067678fac38469350e9325
[ "super().__init__(*args, **kwargs)\nself.dag_name = dag_name\nself.input_hook = hook_factory.get_input_hook(input_hook, **kwargs)\nself.output_hook = hook_factory.get_output_hook(output_hook, **kwargs)\nself.return_report = return_report\nself.enable_monitoring = enable_monitoring\nself.is_retry = is_retry\nif enab...
<|body_start_0|> super().__init__(*args, **kwargs) self.dag_name = dag_name self.input_hook = hook_factory.get_input_hook(input_hook, **kwargs) self.output_hook = hook_factory.get_output_hook(output_hook, **kwargs) self.return_report = return_report self.enable_monitoring...
Custom Operator to send data from an input hook to an output hook.
DataConnectorOperator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataConnectorOperator: """Custom Operator to send data from an input hook to an output hook.""" def __init__(self, *args, input_hook: hook_factory.InputHookType, output_hook: hook_factory.OutputHookType, dag_name: str, monitoring_dataset: str='', monitoring_table: str='', monitoring_bq_conn_...
stack_v2_sparse_classes_36k_train_006024
5,361
permissive
[ { "docstring": "Initiates the DataConnectorOperator. Args: *args: arguments for the operator. input_hook: The type of the input hook. output_hook: The type of the output hook. dag_name: The ID of the current running dag. monitoring_dataset: Dataset id of the monitoring table. monitoring_table: Table name of the...
2
stack_v2_sparse_classes_30k_train_000822
Implement the Python class `DataConnectorOperator` described below. Class description: Custom Operator to send data from an input hook to an output hook. Method signatures and docstrings: - def __init__(self, *args, input_hook: hook_factory.InputHookType, output_hook: hook_factory.OutputHookType, dag_name: str, monit...
Implement the Python class `DataConnectorOperator` described below. Class description: Custom Operator to send data from an input hook to an output hook. Method signatures and docstrings: - def __init__(self, *args, input_hook: hook_factory.InputHookType, output_hook: hook_factory.OutputHookType, dag_name: str, monit...
031f21680c8646c9d2d39d589c581a9bc9796424
<|skeleton|> class DataConnectorOperator: """Custom Operator to send data from an input hook to an output hook.""" def __init__(self, *args, input_hook: hook_factory.InputHookType, output_hook: hook_factory.OutputHookType, dag_name: str, monitoring_dataset: str='', monitoring_table: str='', monitoring_bq_conn_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataConnectorOperator: """Custom Operator to send data from an input hook to an output hook.""" def __init__(self, *args, input_hook: hook_factory.InputHookType, output_hook: hook_factory.OutputHookType, dag_name: str, monitoring_dataset: str='', monitoring_table: str='', monitoring_bq_conn_id: str='', r...
the_stack_v2_python_sparse
src/dags/dependencies/tcrm/operators/data_connector_operator.py
Ressmann/blockbuster
train
0
bb71b8685d372d2b027f616521e22eafb3cc930b
[ "self.setting = setting\nself.gameActive = False\nself.mainMenu = True\nself.mainGame = False\nself.mainAbout = False\nself.playMenu = False\nself.twoPlayer = False\nself.paused = False\nself.score = 0\nself.level = 1\nself.highScore = 0\nself.resetStats()", "self.shipsLeft = self.setting.shipLimit\nself.level = ...
<|body_start_0|> self.setting = setting self.gameActive = False self.mainMenu = True self.mainGame = False self.mainAbout = False self.playMenu = False self.twoPlayer = False self.paused = False self.score = 0 self.level = 1 self.hi...
Track stats for alien shooter
GameStats
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GameStats: """Track stats for alien shooter""" def __init__(self, setting): """initialize statistics""" <|body_0|> def resetStats(self): """initialize statistics that can change during the game""" <|body_1|> <|end_skeleton|> <|body_start_0|> sel...
stack_v2_sparse_classes_36k_train_006025
1,307
permissive
[ { "docstring": "initialize statistics", "name": "__init__", "signature": "def __init__(self, setting)" }, { "docstring": "initialize statistics that can change during the game", "name": "resetStats", "signature": "def resetStats(self)" } ]
2
stack_v2_sparse_classes_30k_train_014837
Implement the Python class `GameStats` described below. Class description: Track stats for alien shooter Method signatures and docstrings: - def __init__(self, setting): initialize statistics - def resetStats(self): initialize statistics that can change during the game
Implement the Python class `GameStats` described below. Class description: Track stats for alien shooter Method signatures and docstrings: - def __init__(self, setting): initialize statistics - def resetStats(self): initialize statistics that can change during the game <|skeleton|> class GameStats: """Track stat...
2fda9dc7722f2b1bfd7ea05f77bca20ed017cc2a
<|skeleton|> class GameStats: """Track stats for alien shooter""" def __init__(self, setting): """initialize statistics""" <|body_0|> def resetStats(self): """initialize statistics that can change during the game""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GameStats: """Track stats for alien shooter""" def __init__(self, setting): """initialize statistics""" self.setting = setting self.gameActive = False self.mainMenu = True self.mainGame = False self.mainAbout = False self.playMenu = False se...
the_stack_v2_python_sparse
gameStats.py
taaeyoon/SourceTree
train
0
daea475924763c804e66a0d0bfe22a5877b1df9e
[ "actions: List[int] = []\nis_wins: List[bool] = []\nfor x in range(BW):\n y, result = cls._action_result(s_ary, x)\n if result != MOVE_ILLEGAL:\n actions.append(y * BW + x)\n is_wins.append(result == MOVE_WIN)\nreturn (actions, is_wins)", "y = BH - 1\nwhile True:\n if y < 0 or (s_ary[CP, y,...
<|body_start_0|> actions: List[int] = [] is_wins: List[bool] = [] for x in range(BW): y, result = cls._action_result(s_ary, x) if result != MOVE_ILLEGAL: actions.append(y * BW + x) is_wins.append(result == MOVE_WIN) return (actions,...
ActionChecker
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ActionChecker: def get_action_candidates(cls, s_ary: np.array) -> Tuple[List[int], List[bool]]: """合法手およびその手で勝利するか否かを求める""" <|body_0|> def _action_result(cls, s_ary: np.array, x: int) -> Tuple[int, int]: """その局面でのxに対応するyおよび結果を求める""" <|body_1|> def _check...
stack_v2_sparse_classes_36k_train_006026
7,788
no_license
[ { "docstring": "合法手およびその手で勝利するか否かを求める", "name": "get_action_candidates", "signature": "def get_action_candidates(cls, s_ary: np.array) -> Tuple[List[int], List[bool]]" }, { "docstring": "その局面でのxに対応するyおよび結果を求める", "name": "_action_result", "signature": "def _action_result(cls, s_ary: np.ar...
3
stack_v2_sparse_classes_30k_train_014511
Implement the Python class `ActionChecker` described below. Class description: Implement the ActionChecker class. Method signatures and docstrings: - def get_action_candidates(cls, s_ary: np.array) -> Tuple[List[int], List[bool]]: 合法手およびその手で勝利するか否かを求める - def _action_result(cls, s_ary: np.array, x: int) -> Tuple[int, ...
Implement the Python class `ActionChecker` described below. Class description: Implement the ActionChecker class. Method signatures and docstrings: - def get_action_candidates(cls, s_ary: np.array) -> Tuple[List[int], List[bool]]: 合法手およびその手で勝利するか否かを求める - def _action_result(cls, s_ary: np.array, x: int) -> Tuple[int, ...
01e8fb7a5483f6cb209806f1097ce16573694b4d
<|skeleton|> class ActionChecker: def get_action_candidates(cls, s_ary: np.array) -> Tuple[List[int], List[bool]]: """合法手およびその手で勝利するか否かを求める""" <|body_0|> def _action_result(cls, s_ary: np.array, x: int) -> Tuple[int, int]: """その局面でのxに対応するyおよび結果を求める""" <|body_1|> def _check...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ActionChecker: def get_action_candidates(cls, s_ary: np.array) -> Tuple[List[int], List[bool]]: """合法手およびその手で勝利するか否かを求める""" actions: List[int] = [] is_wins: List[bool] = [] for x in range(BW): y, result = cls._action_result(s_ary, x) if result != MOVE_IL...
the_stack_v2_python_sparse
src/c4_zero/env/solver/solver.py
threecourse/rl-connect4-alpha-zero
train
0
85acf760cd341998f6f18081fa431b9145d18ffc
[ "self.token = {'access_token': Remark.access_token}\nname = {'openid': Remark.re, 'remark': 'lishouwu'}\nhost = cof.url + '/cgi-bin/user/info/updateremark'\nremarks = ApiDefine().remark(self.session, url=host, params=self.token, data=json.dumps(name))\nself.assertIn('ok', remarks.text)", "self.token = {'access_to...
<|body_start_0|> self.token = {'access_token': Remark.access_token} name = {'openid': Remark.re, 'remark': 'lishouwu'} host = cof.url + '/cgi-bin/user/info/updateremark' remarks = ApiDefine().remark(self.session, url=host, params=self.token, data=json.dumps(name)) self.assertIn('...
Remark
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Remark: def test_remarks(self): """修改用户列表""" <|body_0|> def test_f_remarks(self): """修改用户列表,错误token""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.token = {'access_token': Remark.access_token} name = {'openid': Remark.re, 'remark': 'li...
stack_v2_sparse_classes_36k_train_006027
1,400
no_license
[ { "docstring": "修改用户列表", "name": "test_remarks", "signature": "def test_remarks(self)" }, { "docstring": "修改用户列表,错误token", "name": "test_f_remarks", "signature": "def test_f_remarks(self)" } ]
2
null
Implement the Python class `Remark` described below. Class description: Implement the Remark class. Method signatures and docstrings: - def test_remarks(self): 修改用户列表 - def test_f_remarks(self): 修改用户列表,错误token
Implement the Python class `Remark` described below. Class description: Implement the Remark class. Method signatures and docstrings: - def test_remarks(self): 修改用户列表 - def test_f_remarks(self): 修改用户列表,错误token <|skeleton|> class Remark: def test_remarks(self): """修改用户列表""" <|body_0|> def te...
7b790f675419224bfdbe1542eddc5a638982e68a
<|skeleton|> class Remark: def test_remarks(self): """修改用户列表""" <|body_0|> def test_f_remarks(self): """修改用户列表,错误token""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Remark: def test_remarks(self): """修改用户列表""" self.token = {'access_token': Remark.access_token} name = {'openid': Remark.re, 'remark': 'lishouwu'} host = cof.url + '/cgi-bin/user/info/updateremark' remarks = ApiDefine().remark(self.session, url=host, params=self.token, ...
the_stack_v2_python_sparse
task/weixin_apitest/testcases/weixin_remarks.py
liousAlready/NewDream_learning
train
0
9b598f467b9969ec07bb85877170609f4431188a
[ "if N <= 1:\n return N\nif N == 2:\n return 1\nprev1 = 1\nprev2 = 1\nfor i in range(2, N + 1):\n prev1, prev2 = (prev1 + prev2, prev1)\nreturn prev1", "if N <= 1:\n return N\nreturn self.fib(N - 1) + self.fib(N - 2)" ]
<|body_start_0|> if N <= 1: return N if N == 2: return 1 prev1 = 1 prev2 = 1 for i in range(2, N + 1): prev1, prev2 = (prev1 + prev2, prev1) return prev1 <|end_body_0|> <|body_start_1|> if N <= 1: return N r...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def fib2(self, N: int) -> int: """递推 时间复杂度: O(N) 空间复杂度: O(1) Args: N: Returns:""" <|body_0|> def fib(self, N: int) -> int: """递归 时间复杂度 O(2^N) 空间复杂度 O(N) Args: N: Returns:""" <|body_1|> <|end_skeleton|> <|body_start_0|> if N <= 1: ...
stack_v2_sparse_classes_36k_train_006028
1,011
no_license
[ { "docstring": "递推 时间复杂度: O(N) 空间复杂度: O(1) Args: N: Returns:", "name": "fib2", "signature": "def fib2(self, N: int) -> int" }, { "docstring": "递归 时间复杂度 O(2^N) 空间复杂度 O(N) Args: N: Returns:", "name": "fib", "signature": "def fib(self, N: int) -> int" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def fib2(self, N: int) -> int: 递推 时间复杂度: O(N) 空间复杂度: O(1) Args: N: Returns: - def fib(self, N: int) -> int: 递归 时间复杂度 O(2^N) 空间复杂度 O(N) Args: N: Returns:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def fib2(self, N: int) -> int: 递推 时间复杂度: O(N) 空间复杂度: O(1) Args: N: Returns: - def fib(self, N: int) -> int: 递归 时间复杂度 O(2^N) 空间复杂度 O(N) Args: N: Returns: <|skeleton|> class Solut...
c0dd577481b46129d950354d567d332a4d091137
<|skeleton|> class Solution: def fib2(self, N: int) -> int: """递推 时间复杂度: O(N) 空间复杂度: O(1) Args: N: Returns:""" <|body_0|> def fib(self, N: int) -> int: """递归 时间复杂度 O(2^N) 空间复杂度 O(N) Args: N: Returns:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def fib2(self, N: int) -> int: """递推 时间复杂度: O(N) 空间复杂度: O(1) Args: N: Returns:""" if N <= 1: return N if N == 2: return 1 prev1 = 1 prev2 = 1 for i in range(2, N + 1): prev1, prev2 = (prev1 + prev2, prev1) re...
the_stack_v2_python_sparse
leetcode/509_斐波拉契数.py
tenqaz/crazy_arithmetic
train
0
fa3d86b057c416802ed490a7c7bf1603492b99f4
[ "self.n = height\nself.m = width\nself.dirs = {'L': [0, -1], 'U': [-1, 0], 'R': [0, 1], 'D': [1, 0]}\nself.food = collections.deque(food)\nself.snake_set = {(0, 0)}\nself.snake = collections.deque([(0, 0)])", "x, y = (self.snake[-1][0] + self.dirs[direction][0], self.snake[-1][1] + self.dirs[direction][1])\nif x ...
<|body_start_0|> self.n = height self.m = width self.dirs = {'L': [0, -1], 'U': [-1, 0], 'R': [0, 1], 'D': [1, 0]} self.food = collections.deque(food) self.snake_set = {(0, 0)} self.snake = collections.deque([(0, 0)]) <|end_body_0|> <|body_start_1|> x, y = (self....
SnakeGame
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): """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], t...
stack_v2_sparse_classes_36k_train_006029
1,784
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].", "name": "__init__", "signature": "def __init__(self, widt...
2
stack_v2_sparse_classes_30k_test_000917
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -...
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -...
59f70dc4466e15df591ba285317e4a1fe808ed60
<|skeleton|> class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): """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], t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): """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 a...
the_stack_v2_python_sparse
leet/Design/353_Design_Snake_Game.py
arsamigullin/problem_solving_python
train
0
d52ba227f6b54888b09eb610d738e5972616868b
[ "PROXY_PRIORITY_VALUES = []\nraw_priority_values = settings.proxies.pool.priority\nfor priority in raw_priority_values:\n multiplier = int(priority[0])\n metric = priority[1][0]\n params = []\n if len(priority[1]) > 1:\n params = priority[1][1:]\n value = self.get_metric(metric, *params)\n ...
<|body_start_0|> PROXY_PRIORITY_VALUES = [] raw_priority_values = settings.proxies.pool.priority for priority in raw_priority_values: multiplier = int(priority[0]) metric = priority[1][0] params = [] if len(priority[1]) > 1: params ...
ProxyMetrics
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProxyMetrics: def priority(self, count): """We do not need the confirmed fields since they already are factored in based on the separate queues. [!] IMPORTANT: ------------- Tuple comparison for priority in Python3 breaks if two tuples are the same, so we have to use a counter to guarant...
stack_v2_sparse_classes_36k_train_006030
13,482
no_license
[ { "docstring": "We do not need the confirmed fields since they already are factored in based on the separate queues. [!] IMPORTANT: ------------- Tuple comparison for priority in Python3 breaks if two tuples are the same, so we have to use a counter to guarantee that no two tuples are the same and priority will...
2
null
Implement the Python class `ProxyMetrics` described below. Class description: Implement the ProxyMetrics class. Method signatures and docstrings: - def priority(self, count): We do not need the confirmed fields since they already are factored in based on the separate queues. [!] IMPORTANT: ------------- Tuple compari...
Implement the Python class `ProxyMetrics` described below. Class description: Implement the ProxyMetrics class. Method signatures and docstrings: - def priority(self, count): We do not need the confirmed fields since they already are factored in based on the separate queues. [!] IMPORTANT: ------------- Tuple compari...
e27d6ab0da018495a4b54e41a15cc84dc0df14ab
<|skeleton|> class ProxyMetrics: def priority(self, count): """We do not need the confirmed fields since they already are factored in based on the separate queues. [!] IMPORTANT: ------------- Tuple comparison for priority in Python3 breaks if two tuples are the same, so we have to use a counter to guarant...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProxyMetrics: def priority(self, count): """We do not need the confirmed fields since they already are factored in based on the separate queues. [!] IMPORTANT: ------------- Tuple comparison for priority in Python3 breaks if two tuples are the same, so we have to use a counter to guarantee that no two...
the_stack_v2_python_sparse
instattack/core/models/mixins.py
nickmflorin/instagram-attack
train
9
16ff5689577916b7fa815c990dfc89d1d36b633f
[ "self.cleaned_data = super(DeleteWaypointForm, self).clean()\nwaypoint = Waypoint.objects.filter(pk=self.cleaned_data['id_waypoint'])\nif not waypoint:\n raise ValidationError('El punto de entrega no existe')\nreturn self.cleaned_data", "waypoint = Waypoint.objects.get(pk=self.cleaned_data['id_waypoint'])\nway...
<|body_start_0|> self.cleaned_data = super(DeleteWaypointForm, self).clean() waypoint = Waypoint.objects.filter(pk=self.cleaned_data['id_waypoint']) if not waypoint: raise ValidationError('El punto de entrega no existe') return self.cleaned_data <|end_body_0|> <|body_start_1...
Form that is used to soft-delete (deactivate) a WaypointModel as well as the related user.
DeleteWaypointForm
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeleteWaypointForm: """Form that is used to soft-delete (deactivate) a WaypointModel as well as the related user.""" def clean(self): """Override clean data to validate the id corresponds to a real Waypoint.""" <|body_0|> def save(self, *args, **kwargs): """Overr...
stack_v2_sparse_classes_36k_train_006031
8,251
permissive
[ { "docstring": "Override clean data to validate the id corresponds to a real Waypoint.", "name": "clean", "signature": "def clean(self)" }, { "docstring": "Override save to soft delete the waypoint.", "name": "save", "signature": "def save(self, *args, **kwargs)" } ]
2
null
Implement the Python class `DeleteWaypointForm` described below. Class description: Form that is used to soft-delete (deactivate) a WaypointModel as well as the related user. Method signatures and docstrings: - def clean(self): Override clean data to validate the id corresponds to a real Waypoint. - def save(self, *a...
Implement the Python class `DeleteWaypointForm` described below. Class description: Form that is used to soft-delete (deactivate) a WaypointModel as well as the related user. Method signatures and docstrings: - def clean(self): Override clean data to validate the id corresponds to a real Waypoint. - def save(self, *a...
0100435c5d5a5fd12133b376b305e8fa79ddb8f0
<|skeleton|> class DeleteWaypointForm: """Form that is used to soft-delete (deactivate) a WaypointModel as well as the related user.""" def clean(self): """Override clean data to validate the id corresponds to a real Waypoint.""" <|body_0|> def save(self, *args, **kwargs): """Overr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeleteWaypointForm: """Form that is used to soft-delete (deactivate) a WaypointModel as well as the related user.""" def clean(self): """Override clean data to validate the id corresponds to a real Waypoint.""" self.cleaned_data = super(DeleteWaypointForm, self).clean() waypoint =...
the_stack_v2_python_sparse
waypoints/forms.py
Oswaldinho24k/geo-csv
train
0
942f7e2ac06f33815a91e6f04e0527deb23a6d66
[ "expected_result = np.array([[0.0, 0.0, 0.1, 0.0, 0.0], [0.0, 0.0, 0.175, 0.0, 0.0], [0.05, 0.125, 0.3375, 0.125, 0.05], [0.025, 0.0625, 0.29375, 0.0625, 0.025], [0.0125, 0.03125, 0.196875, 0.03125, 0.0125]])\nresult = RecursiveFilter(edge_width=1)._recurse_forward(self.cube.data[0, :], self.smoothing_coefficients[...
<|body_start_0|> expected_result = np.array([[0.0, 0.0, 0.1, 0.0, 0.0], [0.0, 0.0, 0.175, 0.0, 0.0], [0.05, 0.125, 0.3375, 0.125, 0.05], [0.025, 0.0625, 0.29375, 0.0625, 0.025], [0.0125, 0.03125, 0.196875, 0.03125, 0.0125]]) result = RecursiveFilter(edge_width=1)._recurse_forward(self.cube.data[0, :], s...
Test the _recurse_forward method
Test__recurse_forward
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test__recurse_forward: """Test the _recurse_forward method""" def test_first_axis(self): """Test that the returned _recurse_forward array has the expected type and result.""" <|body_0|> def test_second_axis(self): """Test that the returned _recurse_forward array ...
stack_v2_sparse_classes_36k_train_006032
22,857
permissive
[ { "docstring": "Test that the returned _recurse_forward array has the expected type and result.", "name": "test_first_axis", "signature": "def test_first_axis(self)" }, { "docstring": "Test that the returned _recurse_forward array has the expected type and result.", "name": "test_second_axis...
2
null
Implement the Python class `Test__recurse_forward` described below. Class description: Test the _recurse_forward method Method signatures and docstrings: - def test_first_axis(self): Test that the returned _recurse_forward array has the expected type and result. - def test_second_axis(self): Test that the returned _r...
Implement the Python class `Test__recurse_forward` described below. Class description: Test the _recurse_forward method Method signatures and docstrings: - def test_first_axis(self): Test that the returned _recurse_forward array has the expected type and result. - def test_second_axis(self): Test that the returned _r...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class Test__recurse_forward: """Test the _recurse_forward method""" def test_first_axis(self): """Test that the returned _recurse_forward array has the expected type and result.""" <|body_0|> def test_second_axis(self): """Test that the returned _recurse_forward array ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Test__recurse_forward: """Test the _recurse_forward method""" def test_first_axis(self): """Test that the returned _recurse_forward array has the expected type and result.""" expected_result = np.array([[0.0, 0.0, 0.1, 0.0, 0.0], [0.0, 0.0, 0.175, 0.0, 0.0], [0.05, 0.125, 0.3375, 0.125, 0...
the_stack_v2_python_sparse
improver_tests/nbhood/recursive_filter/test_RecursiveFilter.py
metoppv/improver
train
101
ea1aa675ed0a8f74994ab7e1daec79ac202f0702
[ "super().__init__()\nself.generator = generator_cls(img_size, latent_dim, num_channels)\nself.discriminator = discriminator_cls(num_channels, img_size)\nself._latent_dim = latent_dim\nself.generator.apply(weights_init_normal)\nself.discriminator.apply(weights_init_normal)\nself.lambda_gp = lambda_gp", "if noise i...
<|body_start_0|> super().__init__() self.generator = generator_cls(img_size, latent_dim, num_channels) self.discriminator = discriminator_cls(num_channels, img_size) self._latent_dim = latent_dim self.generator.apply(weights_init_normal) self.discriminator.apply(weights_i...
Implementation of Generative Adversarial Networks following the convergence and stability guidance of ``On Convergence and Stability of GANs`` References ---------- `Paper <https://arxiv.org/abs/1705.07215>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained ne...
DRAGAN
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DRAGAN: """Implementation of Generative Adversarial Networks following the convergence and stability guidance of ``On Convergence and Stability of GANs`` References ---------- `Paper <https://arxiv.org/abs/1705.07215>`_ Warnings -------- This Network is designed for training only; if you want to ...
stack_v2_sparse_classes_36k_train_006033
5,304
permissive
[ { "docstring": "Parameters ---------- latent_dim : int size of the latent dimension num_channels : int number of channels for image generation and discrimination img_size : int number of pixels per image side lambda_gp : float weighting factor for gradient penalty generator_cls : class implementing the actual g...
2
stack_v2_sparse_classes_30k_train_003901
Implement the Python class `DRAGAN` described below. Class description: Implementation of Generative Adversarial Networks following the convergence and stability guidance of ``On Convergence and Stability of GANs`` References ---------- `Paper <https://arxiv.org/abs/1705.07215>`_ Warnings -------- This Network is desi...
Implement the Python class `DRAGAN` described below. Class description: Implementation of Generative Adversarial Networks following the convergence and stability guidance of ``On Convergence and Stability of GANs`` References ---------- `Paper <https://arxiv.org/abs/1705.07215>`_ Warnings -------- This Network is desi...
1078f5030b8aac2bf022daf5fa14d66f74c3c893
<|skeleton|> class DRAGAN: """Implementation of Generative Adversarial Networks following the convergence and stability guidance of ``On Convergence and Stability of GANs`` References ---------- `Paper <https://arxiv.org/abs/1705.07215>`_ Warnings -------- This Network is designed for training only; if you want to ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DRAGAN: """Implementation of Generative Adversarial Networks following the convergence and stability guidance of ``On Convergence and Stability of GANs`` References ---------- `Paper <https://arxiv.org/abs/1705.07215>`_ Warnings -------- This Network is designed for training only; if you want to predict from ...
the_stack_v2_python_sparse
dlutils/models/gans/dragan/dragan.py
justusschock/dl-utils
train
15
88f225d86c1b18605129320e5f8bcb6453145bfb
[ "super(EnterpriseCustomerIdentityProviderAdminForm, self).__init__(*args, **kwargs)\nidp_choices = utils.get_idp_choices()\nif idp_choices is not None:\n self.fields['provider_id'] = forms.TypedChoiceField(choices=idp_choices)", "super(EnterpriseCustomerIdentityProviderAdminForm, self).clean()\nprovider_id = s...
<|body_start_0|> super(EnterpriseCustomerIdentityProviderAdminForm, self).__init__(*args, **kwargs) idp_choices = utils.get_idp_choices() if idp_choices is not None: self.fields['provider_id'] = forms.TypedChoiceField(choices=idp_choices) <|end_body_0|> <|body_start_1|> supe...
Alternate form for the EnterpriseCustomerIdentityProvider admin page. This form fetches identity providers from lms third_party_auth app. If third_party_auth app is not avilable it displays provider_id as a CharField.
EnterpriseCustomerIdentityProviderAdminForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EnterpriseCustomerIdentityProviderAdminForm: """Alternate form for the EnterpriseCustomerIdentityProvider admin page. This form fetches identity providers from lms third_party_auth app. If third_party_auth app is not avilable it displays provider_id as a CharField.""" def __init__(self, *arg...
stack_v2_sparse_classes_36k_train_006034
14,734
no_license
[ { "docstring": "Initialize the form. Substitutes CharField with TypedChoiceField for the provider_id field.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Final validations of model fields. 1. Validate that selected site for enterprise customer matche...
2
stack_v2_sparse_classes_30k_train_001764
Implement the Python class `EnterpriseCustomerIdentityProviderAdminForm` described below. Class description: Alternate form for the EnterpriseCustomerIdentityProvider admin page. This form fetches identity providers from lms third_party_auth app. If third_party_auth app is not avilable it displays provider_id as a Cha...
Implement the Python class `EnterpriseCustomerIdentityProviderAdminForm` described below. Class description: Alternate form for the EnterpriseCustomerIdentityProvider admin page. This form fetches identity providers from lms third_party_auth app. If third_party_auth app is not avilable it displays provider_id as a Cha...
de3d1b297fa99d61cf32addb981cdfc55aec9891
<|skeleton|> class EnterpriseCustomerIdentityProviderAdminForm: """Alternate form for the EnterpriseCustomerIdentityProvider admin page. This form fetches identity providers from lms third_party_auth app. If third_party_auth app is not avilable it displays provider_id as a CharField.""" def __init__(self, *arg...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EnterpriseCustomerIdentityProviderAdminForm: """Alternate form for the EnterpriseCustomerIdentityProvider admin page. This form fetches identity providers from lms third_party_auth app. If third_party_auth app is not avilable it displays provider_id as a CharField.""" def __init__(self, *args, **kwargs):...
the_stack_v2_python_sparse
venvs/edxapp/lib/python2.7/site-packages/enterprise/admin/forms.py
UOMx/CITeS-VM-edxapp
train
0
e3f1e91a022165a526299378047d7249c65a6eaa
[ "username = request.GET.get('username', None)\nif username is not None:\n teacher = get_object_or_404(Teacher, user__username=username)\n serializer = TeacherSerializer(teacher)\n return JsonResponse({'teachers': [serializer.data]}, safe=False)\nelse:\n teachers = Teacher.objects.all()\n serializer =...
<|body_start_0|> username = request.GET.get('username', None) if username is not None: teacher = get_object_or_404(Teacher, user__username=username) serializer = TeacherSerializer(teacher) return JsonResponse({'teachers': [serializer.data]}, safe=False) else: ...
教师view
Teachers
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Teachers: """教师view""" def get(self, request): """查询教师""" <|body_0|> def post(self, request): """增加教师""" <|body_1|> def delete(self, request): """删除教师""" <|body_2|> <|end_skeleton|> <|body_start_0|> username = request.GET.ge...
stack_v2_sparse_classes_36k_train_006035
16,053
permissive
[ { "docstring": "查询教师", "name": "get", "signature": "def get(self, request)" }, { "docstring": "增加教师", "name": "post", "signature": "def post(self, request)" }, { "docstring": "删除教师", "name": "delete", "signature": "def delete(self, request)" } ]
3
stack_v2_sparse_classes_30k_train_011610
Implement the Python class `Teachers` described below. Class description: 教师view Method signatures and docstrings: - def get(self, request): 查询教师 - def post(self, request): 增加教师 - def delete(self, request): 删除教师
Implement the Python class `Teachers` described below. Class description: 教师view Method signatures and docstrings: - def get(self, request): 查询教师 - def post(self, request): 增加教师 - def delete(self, request): 删除教师 <|skeleton|> class Teachers: """教师view""" def get(self, request): """查询教师""" <|b...
7aaa1be773718de1beb3ce0080edca7c4114b7ad
<|skeleton|> class Teachers: """教师view""" def get(self, request): """查询教师""" <|body_0|> def post(self, request): """增加教师""" <|body_1|> def delete(self, request): """删除教师""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Teachers: """教师view""" def get(self, request): """查询教师""" username = request.GET.get('username', None) if username is not None: teacher = get_object_or_404(Teacher, user__username=username) serializer = TeacherSerializer(teacher) return JsonResp...
the_stack_v2_python_sparse
user/views.py
MIXISAMA/MIS-backend
train
0
eac14632447e396631a44ba81ee3f9ad8b6ba520
[ "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.
GradeOutServicer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GradeOutServicer: """Missing associated documentation comment in .proto file.""" def CreateGrade(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def ReadGrade(self, request, context): """Missing associated docume...
stack_v2_sparse_classes_36k_train_006036
9,091
no_license
[ { "docstring": "Missing associated documentation comment in .proto file.", "name": "CreateGrade", "signature": "def CreateGrade(self, request, context)" }, { "docstring": "Missing associated documentation comment in .proto file.", "name": "ReadGrade", "signature": "def ReadGrade(self, re...
5
stack_v2_sparse_classes_30k_train_015300
Implement the Python class `GradeOutServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def CreateGrade(self, request, context): Missing associated documentation comment in .proto file. - def ReadGrade(self, request, context): Miss...
Implement the Python class `GradeOutServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def CreateGrade(self, request, context): Missing associated documentation comment in .proto file. - def ReadGrade(self, request, context): Miss...
de7bc0fa1dc299473e2e63dab58c1d49fde7df2f
<|skeleton|> class GradeOutServicer: """Missing associated documentation comment in .proto file.""" def CreateGrade(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def ReadGrade(self, request, context): """Missing associated docume...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GradeOutServicer: """Missing associated documentation comment in .proto file.""" def CreateGrade(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
gateway/src/logic/protogen/outgoing/grade_out_pb2_grpc.py
Mutestock/mini-project-loner-edition
train
0
ee0e3ebf4d44f9a28a9b547bf8445d17a0153f74
[ "self.mol = mol\nself.mints = mints\nself.V_nuc = mol.nuclear_repulsion_energy()\nself.T = block_oei(mints.ao_kinetic())\nself.S = block_oei(mints.ao_overlap())\nself.V = block_oei(mints.ao_potential())\nG = block_tei(mints.ao_eri())\nself.g = G.transpose(0, 2, 1, 3) - G.transpose(0, 2, 3, 1)\nself.h = self.T + sel...
<|body_start_0|> self.mol = mol self.mints = mints self.V_nuc = mol.nuclear_repulsion_energy() self.T = block_oei(mints.ao_kinetic()) self.S = block_oei(mints.ao_overlap()) self.V = block_oei(mints.ao_potential()) G = block_tei(mints.ao_eri()) self.g = G.t...
Unrestricted Hartree-Fock class for obtaining the unrestricted Hartree-Fock energy
UHF
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UHF: """Unrestricted Hartree-Fock class for obtaining the unrestricted Hartree-Fock energy""" def __init__(self, mol, mints): """Initialize the uhf :param mol: a psi4 molecule object :param mints: a molecular integrals object (from MintsHelper)""" <|body_0|> def compute_...
stack_v2_sparse_classes_36k_train_006037
3,614
no_license
[ { "docstring": "Initialize the uhf :param mol: a psi4 molecule object :param mints: a molecular integrals object (from MintsHelper)", "name": "__init__", "signature": "def __init__(self, mol, mints)" }, { "docstring": "Compute the rhf energy :return: energy", "name": "compute_energy", "s...
3
null
Implement the Python class `UHF` described below. Class description: Unrestricted Hartree-Fock class for obtaining the unrestricted Hartree-Fock energy Method signatures and docstrings: - def __init__(self, mol, mints): Initialize the uhf :param mol: a psi4 molecule object :param mints: a molecular integrals object (...
Implement the Python class `UHF` described below. Class description: Unrestricted Hartree-Fock class for obtaining the unrestricted Hartree-Fock energy Method signatures and docstrings: - def __init__(self, mol, mints): Initialize the uhf :param mol: a psi4 molecule object :param mints: a molecular integrals object (...
2e8255ea548f13de6c492f649c4f2c4156f9995f
<|skeleton|> class UHF: """Unrestricted Hartree-Fock class for obtaining the unrestricted Hartree-Fock energy""" def __init__(self, mol, mints): """Initialize the uhf :param mol: a psi4 molecule object :param mints: a molecular integrals object (from MintsHelper)""" <|body_0|> def compute_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UHF: """Unrestricted Hartree-Fock class for obtaining the unrestricted Hartree-Fock energy""" def __init__(self, mol, mints): """Initialize the uhf :param mol: a psi4 molecule object :param mints: a molecular integrals object (from MintsHelper)""" self.mol = mol self.mints = mints...
the_stack_v2_python_sparse
5/jevandezande/module/uhf.py
CCQC/summer-program
train
35
26c33ec77c16085c7f7e677efaea8f76732eff79
[ "try:\n branch = Branch.objects.get(id=kwargs['branch_id'], repository_id=kwargs['repository_id'])\nexcept Branch.DoesNotExist:\n raise Http404\nsuper(BranchDetail, self).check_permissions(request, branch)\nreturn branch", "branch = self.get_object(request, branch_id=kwargs['branch_id'], repository_id=kwarg...
<|body_start_0|> try: branch = Branch.objects.get(id=kwargs['branch_id'], repository_id=kwargs['repository_id']) except Branch.DoesNotExist: raise Http404 super(BranchDetail, self).check_permissions(request, branch) return branch <|end_body_0|> <|body_start_1|> ...
This view handle all requests what comes on endpoint repositories/(?P<repository_id>[0-9]+)/branches/(?P<branch_id>[0-9]+)/$
BranchDetail
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BranchDetail: """This view handle all requests what comes on endpoint repositories/(?P<repository_id>[0-9]+)/branches/(?P<branch_id>[0-9]+)/$""" def get_object(self, request, *args, **kwargs) -> Branch: """Trying to find branch by branch and repository id in database and return them ...
stack_v2_sparse_classes_36k_train_006038
4,560
permissive
[ { "docstring": "Trying to find branch by branch and repository id in database and return them :param args: other parameters :param kwargs: dict parsed url variables {\"branch_id\": \"id\", \"repository_id\":\"id\"} :return: Branch object or DoesNotExist exception :raise Branch.DoesNotExist", "name": "get_ob...
3
stack_v2_sparse_classes_30k_train_001854
Implement the Python class `BranchDetail` described below. Class description: This view handle all requests what comes on endpoint repositories/(?P<repository_id>[0-9]+)/branches/(?P<branch_id>[0-9]+)/$ Method signatures and docstrings: - def get_object(self, request, *args, **kwargs) -> Branch: Trying to find branch...
Implement the Python class `BranchDetail` described below. Class description: This view handle all requests what comes on endpoint repositories/(?P<repository_id>[0-9]+)/branches/(?P<branch_id>[0-9]+)/$ Method signatures and docstrings: - def get_object(self, request, *args, **kwargs) -> Branch: Trying to find branch...
fdb911dfafbd2609b7f96561ab6780b4131a77bd
<|skeleton|> class BranchDetail: """This view handle all requests what comes on endpoint repositories/(?P<repository_id>[0-9]+)/branches/(?P<branch_id>[0-9]+)/$""" def get_object(self, request, *args, **kwargs) -> Branch: """Trying to find branch by branch and repository id in database and return them ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BranchDetail: """This view handle all requests what comes on endpoint repositories/(?P<repository_id>[0-9]+)/branches/(?P<branch_id>[0-9]+)/$""" def get_object(self, request, *args, **kwargs) -> Branch: """Trying to find branch by branch and repository id in database and return them :param args: ...
the_stack_v2_python_sparse
branches/views.py
Kh-011-WebUIPython/lit
train
4
da67d24e11a57c0e4929cdc9be7df4c233a96731
[ "ThreadSlave.__init__(self)\nmyThread = threading.currentThread()\nself.runningFeedersLock = myThread.runningFeedersLock\nself.runningFeeders = myThread.runningFeeders\nself.messageArgs = None", "ThreadSlave.initInThread(self)\nmyThread = threading.currentThread()\ndaofactory = DAOFactory(package='WMComponent.Fee...
<|body_start_0|> ThreadSlave.__init__(self) myThread = threading.currentThread() self.runningFeedersLock = myThread.runningFeedersLock self.runningFeeders = myThread.runningFeeders self.messageArgs = None <|end_body_0|> <|body_start_1|> ThreadSlave.initInThread(self) ...
The default slave for FeederManager messages
DefaultSlave
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DefaultSlave: """The default slave for FeederManager messages""" def __init__(self): """Initialise the slave""" <|body_0|> def initInThread(self): """Load shared queries""" <|body_1|> def __call__(self, parameters): """Unpickle event payload ...
stack_v2_sparse_classes_36k_train_006039
1,685
no_license
[ { "docstring": "Initialise the slave", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Load shared queries", "name": "initInThread", "signature": "def initInThread(self)" }, { "docstring": "Unpickle event payload if it is pickled", "name": "__call__",...
3
null
Implement the Python class `DefaultSlave` described below. Class description: The default slave for FeederManager messages Method signatures and docstrings: - def __init__(self): Initialise the slave - def initInThread(self): Load shared queries - def __call__(self, parameters): Unpickle event payload if it is pickle...
Implement the Python class `DefaultSlave` described below. Class description: The default slave for FeederManager messages Method signatures and docstrings: - def __init__(self): Initialise the slave - def initInThread(self): Load shared queries - def __call__(self, parameters): Unpickle event payload if it is pickle...
122f9332f2e944154dd0df68b6b3f2875427b032
<|skeleton|> class DefaultSlave: """The default slave for FeederManager messages""" def __init__(self): """Initialise the slave""" <|body_0|> def initInThread(self): """Load shared queries""" <|body_1|> def __call__(self, parameters): """Unpickle event payload ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DefaultSlave: """The default slave for FeederManager messages""" def __init__(self): """Initialise the slave""" ThreadSlave.__init__(self) myThread = threading.currentThread() self.runningFeedersLock = myThread.runningFeedersLock self.runningFeeders = myThread.runn...
the_stack_v2_python_sparse
src/python/WMComponent/FeederManager/Handler/DefaultSlave.py
cinquo/WMCore
train
1
79944e732c2d048d78c44fb00f8607203d9d7080
[ "self.site = page._link.site\nself.title = page._link.title\nself.loc_title = page._link.canonical_title()\nself.can_title = page._link.ns_title()\nself.outputlang = outputlang\nif outputlang is not None:\n if not hasattr(self, 'onsite'):\n self.onsite = pywikibot.Site(outputlang, self.site.family)\n t...
<|body_start_0|> self.site = page._link.site self.title = page._link.title self.loc_title = page._link.canonical_title() self.can_title = page._link.ns_title() self.outputlang = outputlang if outputlang is not None: if not hasattr(self, 'onsite'): ...
Structure with Page attributes exposed for formatting from cmd line.
Formatter
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Formatter: """Structure with Page attributes exposed for formatting from cmd line.""" def __init__(self, page, outputlang=None, default='******'): """Initializer. @param page: the page to be formatted. @type page: Page object. @param outputlang: language code in which namespace befor...
stack_v2_sparse_classes_36k_train_006040
9,907
permissive
[ { "docstring": "Initializer. @param page: the page to be formatted. @type page: Page object. @param outputlang: language code in which namespace before title should be translated. Page ns will be searched in Site(outputlang, page.site.family) and, if found, its custom name will be used in page.title(). @type ou...
2
stack_v2_sparse_classes_30k_train_000666
Implement the Python class `Formatter` described below. Class description: Structure with Page attributes exposed for formatting from cmd line. Method signatures and docstrings: - def __init__(self, page, outputlang=None, default='******'): Initializer. @param page: the page to be formatted. @type page: Page object. ...
Implement the Python class `Formatter` described below. Class description: Structure with Page attributes exposed for formatting from cmd line. Method signatures and docstrings: - def __init__(self, page, outputlang=None, default='******'): Initializer. @param page: the page to be formatted. @type page: Page object. ...
af470904ce62cedae63d285ca15146e9168a0ee6
<|skeleton|> class Formatter: """Structure with Page attributes exposed for formatting from cmd line.""" def __init__(self, page, outputlang=None, default='******'): """Initializer. @param page: the page to be formatted. @type page: Page object. @param outputlang: language code in which namespace befor...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Formatter: """Structure with Page attributes exposed for formatting from cmd line.""" def __init__(self, page, outputlang=None, default='******'): """Initializer. @param page: the page to be formatted. @type page: Page object. @param outputlang: language code in which namespace before title shoul...
the_stack_v2_python_sparse
scripts/listpages.py
anisayari/pywikibot
train
3
b9d676a34e4a83f592580247ecde07aa85750585
[ "params = dict(request.query_params)\nparams.update(dict(request.data))\nqueryset = kwargs.get('queryset', None)\nagg_field, group_fields, date_part = self.validate_request(params, queryset)\nif not params.get('show_null_groups', False) and (not params.get('show_nulls', False)):\n q_object = Q()\n for field i...
<|body_start_0|> params = dict(request.query_params) params.update(dict(request.data)) queryset = kwargs.get('queryset', None) agg_field, group_fields, date_part = self.validate_request(params, queryset) if not params.get('show_null_groups', False) and (not params.get('show_nulls...
Aggregate a queryset. Any pre-aggregation operations on the queryset (e.g. filtering) is already done (it's handled at the view level, in the get_queryset method).
AggregateQuerysetMixin
[ "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AggregateQuerysetMixin: """Aggregate a queryset. Any pre-aggregation operations on the queryset (e.g. filtering) is already done (it's handled at the view level, in the get_queryset method).""" def aggregate(self, request, *args, **kwargs): """Perform an aggregate function on a Djang...
stack_v2_sparse_classes_36k_train_006041
10,956
permissive
[ { "docstring": "Perform an aggregate function on a Django queryset with an optional group by field.", "name": "aggregate", "signature": "def aggregate(self, request, *args, **kwargs)" }, { "docstring": "F-expression of col, wrapped if needed with SQL function call Assumes that there's an SQL fun...
3
stack_v2_sparse_classes_30k_train_011196
Implement the Python class `AggregateQuerysetMixin` described below. Class description: Aggregate a queryset. Any pre-aggregation operations on the queryset (e.g. filtering) is already done (it's handled at the view level, in the get_queryset method). Method signatures and docstrings: - def aggregate(self, request, *...
Implement the Python class `AggregateQuerysetMixin` described below. Class description: Aggregate a queryset. Any pre-aggregation operations on the queryset (e.g. filtering) is already done (it's handled at the view level, in the get_queryset method). Method signatures and docstrings: - def aggregate(self, request, *...
38f920438697930ae3ac57bbcaae9034877d8fb7
<|skeleton|> class AggregateQuerysetMixin: """Aggregate a queryset. Any pre-aggregation operations on the queryset (e.g. filtering) is already done (it's handled at the view level, in the get_queryset method).""" def aggregate(self, request, *args, **kwargs): """Perform an aggregate function on a Djang...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AggregateQuerysetMixin: """Aggregate a queryset. Any pre-aggregation operations on the queryset (e.g. filtering) is already done (it's handled at the view level, in the get_queryset method).""" def aggregate(self, request, *args, **kwargs): """Perform an aggregate function on a Django queryset wi...
the_stack_v2_python_sparse
usaspending_api/common/mixins.py
fedspendingtransparency/usaspending-api
train
276
5dd58f907904443936d9e2b5a898853b4399a81d
[ "@functools.lru_cache()\ndef recur(m, n):\n if m == 1 and n == 1:\n return grid[0][0]\n elif m == 0 or n == 0:\n return float('inf')\n return grid[m - 1][n - 1] + min(recur(m - 1, n), recur(m, n - 1))\nreturn recur(len(grid), len(grid[0]))", "grid = [[float('inf')] + x for x in grid]\ngrid....
<|body_start_0|> @functools.lru_cache() def recur(m, n): if m == 1 and n == 1: return grid[0][0] elif m == 0 or n == 0: return float('inf') return grid[m - 1][n - 1] + min(recur(m - 1, n), recur(m, n - 1)) return recur(len(grid)...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minPathSum(self, grid: List[List[int]]) -> int: """递归思想, 这一题中,递归方法会慢很多; :param grid: :return:""" <|body_0|> def minPathSum_2(self, grid: List[List[int]]) -> int: """动态规划思想 :param grid: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_006042
1,164
no_license
[ { "docstring": "递归思想, 这一题中,递归方法会慢很多; :param grid: :return:", "name": "minPathSum", "signature": "def minPathSum(self, grid: List[List[int]]) -> int" }, { "docstring": "动态规划思想 :param grid: :return:", "name": "minPathSum_2", "signature": "def minPathSum_2(self, grid: List[List[int]]) -> in...
2
stack_v2_sparse_classes_30k_train_009505
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minPathSum(self, grid: List[List[int]]) -> int: 递归思想, 这一题中,递归方法会慢很多; :param grid: :return: - def minPathSum_2(self, grid: List[List[int]]) -> int: 动态规划思想 :param grid: :return...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minPathSum(self, grid: List[List[int]]) -> int: 递归思想, 这一题中,递归方法会慢很多; :param grid: :return: - def minPathSum_2(self, grid: List[List[int]]) -> int: 动态规划思想 :param grid: :return...
f2c162654a83c51495ebd161f42a1d0b69caf72d
<|skeleton|> class Solution: def minPathSum(self, grid: List[List[int]]) -> int: """递归思想, 这一题中,递归方法会慢很多; :param grid: :return:""" <|body_0|> def minPathSum_2(self, grid: List[List[int]]) -> int: """动态规划思想 :param grid: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minPathSum(self, grid: List[List[int]]) -> int: """递归思想, 这一题中,递归方法会慢很多; :param grid: :return:""" @functools.lru_cache() def recur(m, n): if m == 1 and n == 1: return grid[0][0] elif m == 0 or n == 0: return float('in...
the_stack_v2_python_sparse
64 minPathSum.py
ABenxj/leetcode
train
1
f70ed00cf128e878bbbcc66563038b1dfa630cde
[ "emails = clean_addresses(self.data['emails'])\nif not len(emails):\n raise ValidationError('No Valid Addresses Found')\nemail_string = [formataddr(entry) for entry in emails]\nreturn email_string", "is_staff = self.cleaned_data.get('is_staff', False)\nis_superuser = self.cleaned_data.get('is_superuser', False...
<|body_start_0|> emails = clean_addresses(self.data['emails']) if not len(emails): raise ValidationError('No Valid Addresses Found') email_string = [formataddr(entry) for entry in emails] return email_string <|end_body_0|> <|body_start_1|> is_staff = self.cleaned_dat...
Form for inviting a user.
InviteForm
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InviteForm: """Form for inviting a user.""" def clean_emails(self): """Clean up email field to only include symantically valid addresses""" <|body_0|> def save(self): """Save the form.""" <|body_1|> <|end_skeleton|> <|body_start_0|> emails = cle...
stack_v2_sparse_classes_36k_train_006043
8,878
permissive
[ { "docstring": "Clean up email field to only include symantically valid addresses", "name": "clean_emails", "signature": "def clean_emails(self)" }, { "docstring": "Save the form.", "name": "save", "signature": "def save(self)" } ]
2
stack_v2_sparse_classes_30k_train_005991
Implement the Python class `InviteForm` described below. Class description: Form for inviting a user. Method signatures and docstrings: - def clean_emails(self): Clean up email field to only include symantically valid addresses - def save(self): Save the form.
Implement the Python class `InviteForm` described below. Class description: Form for inviting a user. Method signatures and docstrings: - def clean_emails(self): Clean up email field to only include symantically valid addresses - def save(self): Save the form. <|skeleton|> class InviteForm: """Form for inviting ...
a56c0f89df82694bf5db32a04d8b092974791972
<|skeleton|> class InviteForm: """Form for inviting a user.""" def clean_emails(self): """Clean up email field to only include symantically valid addresses""" <|body_0|> def save(self): """Save the form.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InviteForm: """Form for inviting a user.""" def clean_emails(self): """Clean up email field to only include symantically valid addresses""" emails = clean_addresses(self.data['emails']) if not len(emails): raise ValidationError('No Valid Addresses Found') email...
the_stack_v2_python_sparse
open_connect/accounts/forms.py
ofa/connect
train
66
3a9f1d6cfcabd6edf49287abd5c0d48ce76d0036
[ "self.rasterpath = rasterpath\nself.num_chunks = num_chunks\nself.chunk_list = chunk_list\nself.metadata = metadata\nself.force_scv = force_scv\nreturn", "for chunk_obj in self.chunk_list:\n if chunk_obj.index == index:\n return chunk_obj\nelse:\n raise Exception('No chunk with chunk_id = {0}'.format...
<|body_start_0|> self.rasterpath = rasterpath self.num_chunks = num_chunks self.chunk_list = chunk_list self.metadata = metadata self.force_scv = force_scv return <|end_body_0|> <|body_start_1|> for chunk_obj in self.chunk_list: if chunk_obj.index == ...
Creates a chunk bundle object. it can be used to pass smaller pieces of raster data to complex functions and reduce memory consumption in those functions. Presently, chunks are not saved individually, but are always bundled to form the undivided raster image. This allows chunks to be passed individually and sequentiall...
chunk_bundle
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-us-govt-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class chunk_bundle: """Creates a chunk bundle object. it can be used to pass smaller pieces of raster data to complex functions and reduce memory consumption in those functions. Presently, chunks are not saved individually, but are always bundled to form the undivided raster image. This allows chunks t...
stack_v2_sparse_classes_36k_train_006044
5,063
permissive
[ { "docstring": "Creates a chunk bundle. Two probable use cases: 1) loading raster to split into smaller chunks with: inchunk = chunk_bundle(rasterpath, num_chunks = #) inchunk.load() 2) building new chunk_bundle with processed data, passing on old chunks metadata: outchunk = chunk_bundle(rasterpath, chunk_list ...
5
stack_v2_sparse_classes_30k_train_019697
Implement the Python class `chunk_bundle` described below. Class description: Creates a chunk bundle object. it can be used to pass smaller pieces of raster data to complex functions and reduce memory consumption in those functions. Presently, chunks are not saved individually, but are always bundled to form the undiv...
Implement the Python class `chunk_bundle` described below. Class description: Creates a chunk bundle object. it can be used to pass smaller pieces of raster data to complex functions and reduce memory consumption in those functions. Presently, chunks are not saved individually, but are always bundled to form the undiv...
372ba1481a155dca102612307a8e354dcf975eaa
<|skeleton|> class chunk_bundle: """Creates a chunk bundle object. it can be used to pass smaller pieces of raster data to complex functions and reduce memory consumption in those functions. Presently, chunks are not saved individually, but are always bundled to form the undivided raster image. This allows chunks t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class chunk_bundle: """Creates a chunk bundle object. it can be used to pass smaller pieces of raster data to complex functions and reduce memory consumption in those functions. Presently, chunks are not saved individually, but are always bundled to form the undivided raster image. This allows chunks to be passed i...
the_stack_v2_python_sparse
dnppy_install/chunking/chunking.py
lmakely/dnppy
train
0
d3ebd052df120a4f43fd5c4cbf7101889991661c
[ "proxy = mgmt_session.proxy(RwsdnalYang)\nsdn_account = RwsdnalYang.YangData_RwProject_Project_SdnAccounts_SdnAccountList(name=sdn_account_name, account_type=sdn_account_type)\nxpath = \"/rw-project:project[rw-project:name='default']/sdn-accounts/sdn-account-list[name=%s]\" % quoted_key(sdn_account_name)\nproxy.rep...
<|body_start_0|> proxy = mgmt_session.proxy(RwsdnalYang) sdn_account = RwsdnalYang.YangData_RwProject_Project_SdnAccounts_SdnAccountList(name=sdn_account_name, account_type=sdn_account_type) xpath = "/rw-project:project[rw-project:name='default']/sdn-accounts/sdn-account-list[name=%s]" % quoted_...
TestSdnSetup
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestSdnSetup: def test_create_odl_sdn_account(self, mgmt_session, sdn_account_name, sdn_account_type): """Configure sdn account Asserts: SDN name and accout type.""" <|body_0|> def test_create_openstack_sdn_account(self, mgmt_session, openstack_sdn_account_name, cloud_accoun...
stack_v2_sparse_classes_36k_train_006045
8,232
no_license
[ { "docstring": "Configure sdn account Asserts: SDN name and accout type.", "name": "test_create_odl_sdn_account", "signature": "def test_create_odl_sdn_account(self, mgmt_session, sdn_account_name, sdn_account_type)" }, { "docstring": "Configure sdn account Asserts: SDN name and account type.", ...
2
null
Implement the Python class `TestSdnSetup` described below. Class description: Implement the TestSdnSetup class. Method signatures and docstrings: - def test_create_odl_sdn_account(self, mgmt_session, sdn_account_name, sdn_account_type): Configure sdn account Asserts: SDN name and accout type. - def test_create_openst...
Implement the Python class `TestSdnSetup` described below. Class description: Implement the TestSdnSetup class. Method signatures and docstrings: - def test_create_odl_sdn_account(self, mgmt_session, sdn_account_name, sdn_account_type): Configure sdn account Asserts: SDN name and accout type. - def test_create_openst...
cdd0abe80a76d533d08a51c7970d8ded06624b7d
<|skeleton|> class TestSdnSetup: def test_create_odl_sdn_account(self, mgmt_session, sdn_account_name, sdn_account_type): """Configure sdn account Asserts: SDN name and accout type.""" <|body_0|> def test_create_openstack_sdn_account(self, mgmt_session, openstack_sdn_account_name, cloud_accoun...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestSdnSetup: def test_create_odl_sdn_account(self, mgmt_session, sdn_account_name, sdn_account_type): """Configure sdn account Asserts: SDN name and accout type.""" proxy = mgmt_session.proxy(RwsdnalYang) sdn_account = RwsdnalYang.YangData_RwProject_Project_SdnAccounts_SdnAccountList(...
the_stack_v2_python_sparse
osm/SO/rwlaunchpad/ra/pytest/test_launchpad.py
dennis-me/Pishahang
train
2
d83ec030afe80674ea238dddee10e37aba7083de
[ "self.__server_ip = ip\nself.__port = port\nself.__tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)", "endpoint = (self.__server_ip, self.__port)\ntry:\n self.__tcp.connect(endpoint)\n print('conexao realizada com sucesso!')\n self.__method()\nexcept Exception as e:\n print('Erro de conecacao c...
<|body_start_0|> self.__server_ip = ip self.__port = port self.__tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <|end_body_0|> <|body_start_1|> endpoint = (self.__server_ip, self.__port) try: self.__tcp.connect(endpoint) print('conexao realizada ...
Classe cliente
Cliente
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Cliente: """Classe cliente""" def __init__(self, ip, port): """costrutor da classe cliente Args: ip : ip do servidor port : [porta do servidor""" <|body_0|> def start(self): """Metodo de inicializacao do cliente""" <|body_1|> def __method(self): ...
stack_v2_sparse_classes_36k_train_006046
1,751
no_license
[ { "docstring": "costrutor da classe cliente Args: ip : ip do servidor port : [porta do servidor", "name": "__init__", "signature": "def __init__(self, ip, port)" }, { "docstring": "Metodo de inicializacao do cliente", "name": "start", "signature": "def start(self)" }, { "docstrin...
3
stack_v2_sparse_classes_30k_train_004650
Implement the Python class `Cliente` described below. Class description: Classe cliente Method signatures and docstrings: - def __init__(self, ip, port): costrutor da classe cliente Args: ip : ip do servidor port : [porta do servidor - def start(self): Metodo de inicializacao do cliente - def __method(self): metodod ...
Implement the Python class `Cliente` described below. Class description: Classe cliente Method signatures and docstrings: - def __init__(self, ip, port): costrutor da classe cliente Args: ip : ip do servidor port : [porta do servidor - def start(self): Metodo de inicializacao do cliente - def __method(self): metodod ...
c7208c4075dc250e348003226c13c47142c05c71
<|skeleton|> class Cliente: """Classe cliente""" def __init__(self, ip, port): """costrutor da classe cliente Args: ip : ip do servidor port : [porta do servidor""" <|body_0|> def start(self): """Metodo de inicializacao do cliente""" <|body_1|> def __method(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Cliente: """Classe cliente""" def __init__(self, ip, port): """costrutor da classe cliente Args: ip : ip do servidor port : [porta do servidor""" self.__server_ip = ip self.__port = port self.__tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def start(self): ...
the_stack_v2_python_sparse
semana_7/cliente/cliente.py
EduardFonseca/InformaticaIndustrial
train
0
2b8d87586eb6662c10256fc004b80eaafe221199
[ "super(PointNetEstimation, self).__init__()\nself.conv1 = nn.Conv1d(3, 128, 1)\nself.conv2 = nn.Conv1d(128, 128, 1)\nself.conv3 = nn.Conv1d(128, 256, 1)\nself.conv4 = nn.Conv1d(256, 512, 1)\nself.bn1 = nn.BatchNorm1d(128)\nself.bn2 = nn.BatchNorm1d(128)\nself.bn3 = nn.BatchNorm1d(256)\nself.bn4 = nn.BatchNorm1d(512...
<|body_start_0|> super(PointNetEstimation, self).__init__() self.conv1 = nn.Conv1d(3, 128, 1) self.conv2 = nn.Conv1d(128, 128, 1) self.conv3 = nn.Conv1d(128, 256, 1) self.conv4 = nn.Conv1d(256, 512, 1) self.bn1 = nn.BatchNorm1d(128) self.bn2 = nn.BatchNorm1d(128) ...
PointNetEstimation
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PointNetEstimation: def __init__(self, n_classes=3): """v1 Amodal 3D Box Estimation Pointnet :param n_classes:3 :param one_hot_vec:[bs,n_classes]""" <|body_0|> def forward(self, pts, one_hot_vec): """:param pts: [bs,3,m]: x,y,z after InstanceSeg :return: box_pred: [b...
stack_v2_sparse_classes_36k_train_006047
11,900
permissive
[ { "docstring": "v1 Amodal 3D Box Estimation Pointnet :param n_classes:3 :param one_hot_vec:[bs,n_classes]", "name": "__init__", "signature": "def __init__(self, n_classes=3)" }, { "docstring": ":param pts: [bs,3,m]: x,y,z after InstanceSeg :return: box_pred: [bs,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUS...
2
stack_v2_sparse_classes_30k_train_013098
Implement the Python class `PointNetEstimation` described below. Class description: Implement the PointNetEstimation class. Method signatures and docstrings: - def __init__(self, n_classes=3): v1 Amodal 3D Box Estimation Pointnet :param n_classes:3 :param one_hot_vec:[bs,n_classes] - def forward(self, pts, one_hot_ve...
Implement the Python class `PointNetEstimation` described below. Class description: Implement the PointNetEstimation class. Method signatures and docstrings: - def __init__(self, n_classes=3): v1 Amodal 3D Box Estimation Pointnet :param n_classes:3 :param one_hot_vec:[bs,n_classes] - def forward(self, pts, one_hot_ve...
64bcfa4b292dacc91f92f2542e11d489b1fa2c8a
<|skeleton|> class PointNetEstimation: def __init__(self, n_classes=3): """v1 Amodal 3D Box Estimation Pointnet :param n_classes:3 :param one_hot_vec:[bs,n_classes]""" <|body_0|> def forward(self, pts, one_hot_vec): """:param pts: [bs,3,m]: x,y,z after InstanceSeg :return: box_pred: [b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PointNetEstimation: def __init__(self, n_classes=3): """v1 Amodal 3D Box Estimation Pointnet :param n_classes:3 :param one_hot_vec:[bs,n_classes]""" super(PointNetEstimation, self).__init__() self.conv1 = nn.Conv1d(3, 128, 1) self.conv2 = nn.Conv1d(128, 128, 1) self.con...
the_stack_v2_python_sparse
frustum_pointnet/models/frustum_pointnets_v1_old.py
ayushjain1144/SeeingByMoving
train
24
a364a630388234178a62085f8ef09fd6a70e1615
[ "if not a:\n return list()\nn = len(a)\nm = len(a[0])\nt = list()\nfor x, c in enumerate(self.gen_diagonal_coord(n, m)):\n p = self.traverse_diagonal(c, m, a)\n if x % 2 == 0:\n t.extend(p)\n else:\n t.extend(reversed(p))\nreturn t", "for i in range(0, n, 1):\n yield (i, 0)\nfor j in ...
<|body_start_0|> if not a: return list() n = len(a) m = len(a[0]) t = list() for x, c in enumerate(self.gen_diagonal_coord(n, m)): p = self.traverse_diagonal(c, m, a) if x % 2 == 0: t.extend(p) else: ...
Iteration over elements in 2D array. Time complexity: O(n) - Iterate over all elements in 2D array Space complexity: O(n) - Collect all elements in 2D array
Solution
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """Iteration over elements in 2D array. Time complexity: O(n) - Iterate over all elements in 2D array Space complexity: O(n) - Collect all elements in 2D array""" def find_diagonal_order(self, a): """Traverses all elements of 2D array in alternating diagonal order. :param l...
stack_v2_sparse_classes_36k_train_006048
3,214
permissive
[ { "docstring": "Traverses all elements of 2D array in alternating diagonal order. :param list[list[int]] a: 2D array of integers :return: array of elements from input array in diagonal order :rtype: list[int]", "name": "find_diagonal_order", "signature": "def find_diagonal_order(self, a)" }, { "...
3
stack_v2_sparse_classes_30k_train_008109
Implement the Python class `Solution` described below. Class description: Iteration over elements in 2D array. Time complexity: O(n) - Iterate over all elements in 2D array Space complexity: O(n) - Collect all elements in 2D array Method signatures and docstrings: - def find_diagonal_order(self, a): Traverses all ele...
Implement the Python class `Solution` described below. Class description: Iteration over elements in 2D array. Time complexity: O(n) - Iterate over all elements in 2D array Space complexity: O(n) - Collect all elements in 2D array Method signatures and docstrings: - def find_diagonal_order(self, a): Traverses all ele...
69f90877c5466927e8b081c4268cbcda074813ec
<|skeleton|> class Solution: """Iteration over elements in 2D array. Time complexity: O(n) - Iterate over all elements in 2D array Space complexity: O(n) - Collect all elements in 2D array""" def find_diagonal_order(self, a): """Traverses all elements of 2D array in alternating diagonal order. :param l...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """Iteration over elements in 2D array. Time complexity: O(n) - Iterate over all elements in 2D array Space complexity: O(n) - Collect all elements in 2D array""" def find_diagonal_order(self, a): """Traverses all elements of 2D array in alternating diagonal order. :param list[list[int]...
the_stack_v2_python_sparse
0498_diagonal_traverse/python_source.py
arthurdysart/LeetCode
train
0
2c82dd33180a7442607e5cbedf8846bd72b37150
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('bmroach', 'bmroach')\nrepo.dropCollection('open_space')\nrepo.createCollection('open_space')\nurl = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/2868d370c55d4d458d4ae2224ef8cddd_7.geojson'\...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('bmroach', 'bmroach') repo.dropCollection('open_space') repo.createCollection('open_space') url = 'http://bostonopendata-boston.opendata.ar...
retrieve_open_space
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class retrieve_open_space: def execute(trial=False, log=False): """Retrieves open spaces in Boston as geoJSON""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everything happening in thi...
stack_v2_sparse_classes_36k_train_006049
3,753
no_license
[ { "docstring": "Retrieves open spaces in Boston as geoJSON", "name": "execute", "signature": "def execute(trial=False, log=False)" }, { "docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describing that...
2
stack_v2_sparse_classes_30k_train_003287
Implement the Python class `retrieve_open_space` described below. Class description: Implement the retrieve_open_space class. Method signatures and docstrings: - def execute(trial=False, log=False): Retrieves open spaces in Boston as geoJSON - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None...
Implement the Python class `retrieve_open_space` described below. Class description: Implement the retrieve_open_space class. Method signatures and docstrings: - def execute(trial=False, log=False): Retrieves open spaces in Boston as geoJSON - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None...
97e72731ffadbeae57d7a332decd58706e7c08de
<|skeleton|> class retrieve_open_space: def execute(trial=False, log=False): """Retrieves open spaces in Boston as geoJSON""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everything happening in thi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class retrieve_open_space: def execute(trial=False, log=False): """Retrieves open spaces in Boston as geoJSON""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('bmroach', 'bmroach') repo.dropCollection('open...
the_stack_v2_python_sparse
bmroach/retrieve_open_space.py
ROODAY/course-2017-fal-proj
train
3
4465bedab331f4fc1378cddb2d4933ed199d76f4
[ "super(CA_NET, self).__init__()\nself.t_dim = t_dim\nself.ef_dim = ef_dim\nself.fc = nn.Linear(self.t_dim, self.ef_dim * 4, bias=True)\nself.relu = nn.GLU(1)", "x = self.relu(self.fc(text_embedding))\nmu = x[:, :self.ef_dim]\nlogvar = x[:, self.ef_dim:]\nreturn (mu, logvar)", "std = logvar.mul(0.5).exp_()\neps ...
<|body_start_0|> super(CA_NET, self).__init__() self.t_dim = t_dim self.ef_dim = ef_dim self.fc = nn.Linear(self.t_dim, self.ef_dim * 4, bias=True) self.relu = nn.GLU(1) <|end_body_0|> <|body_start_1|> x = self.relu(self.fc(text_embedding)) mu = x[:, :self.ef_dim...
Conditioning Augmentation network. Args: - t_dim (int): text dimension - ef_dim (int): embedding dimension
CA_NET
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CA_NET: """Conditioning Augmentation network. Args: - t_dim (int): text dimension - ef_dim (int): embedding dimension""" def __init__(self, t_dim, ef_dim): """Initialize the conditioning augmentation.""" <|body_0|> def encode(self, text_embedding): """Encode the ...
stack_v2_sparse_classes_36k_train_006050
22,492
no_license
[ { "docstring": "Initialize the conditioning augmentation.", "name": "__init__", "signature": "def __init__(self, t_dim, ef_dim)" }, { "docstring": "Encode the text embedding.", "name": "encode", "signature": "def encode(self, text_embedding)" }, { "docstring": "Reparametrize the ...
4
stack_v2_sparse_classes_30k_train_014791
Implement the Python class `CA_NET` described below. Class description: Conditioning Augmentation network. Args: - t_dim (int): text dimension - ef_dim (int): embedding dimension Method signatures and docstrings: - def __init__(self, t_dim, ef_dim): Initialize the conditioning augmentation. - def encode(self, text_em...
Implement the Python class `CA_NET` described below. Class description: Conditioning Augmentation network. Args: - t_dim (int): text dimension - ef_dim (int): embedding dimension Method signatures and docstrings: - def __init__(self, t_dim, ef_dim): Initialize the conditioning augmentation. - def encode(self, text_em...
70d344d80425e7bbcc7984737dbe50a6638293c9
<|skeleton|> class CA_NET: """Conditioning Augmentation network. Args: - t_dim (int): text dimension - ef_dim (int): embedding dimension""" def __init__(self, t_dim, ef_dim): """Initialize the conditioning augmentation.""" <|body_0|> def encode(self, text_embedding): """Encode the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CA_NET: """Conditioning Augmentation network. Args: - t_dim (int): text dimension - ef_dim (int): embedding dimension""" def __init__(self, t_dim, ef_dim): """Initialize the conditioning augmentation.""" super(CA_NET, self).__init__() self.t_dim = t_dim self.ef_dim = ef_di...
the_stack_v2_python_sparse
TeleGAN/model.py
ails-lab/teleGAN
train
1
39a2bc0cae49bcb98a7c0d80823bdec07d8d8b0b
[ "left = 0\nright = len(nums) - 1\nwhile left < right - 1:\n mid = (left + right) / 2\n if nums[mid] > nums[mid + 1] and nums[mid] > nums[mid - 1]:\n return mid\n if nums[mid] < nums[mid + 1]:\n left = mid\n else:\n right = mid\nreturn left if nums[left] >= nums[right] else right", ...
<|body_start_0|> left = 0 right = len(nums) - 1 while left < right - 1: mid = (left + right) / 2 if nums[mid] > nums[mid + 1] and nums[mid] > nums[mid - 1]: return mid if nums[mid] < nums[mid + 1]: left = mid else: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findPeakElement(self, nums): """Lets say you have a mid number at index x, nums[x] if (num[x+1] > nums[x]), that means a peak element HAS to exist on the right half of that array, because (since every number is unique) 1. the numbers keep increasing on the right side, and t...
stack_v2_sparse_classes_36k_train_006051
1,862
no_license
[ { "docstring": "Lets say you have a mid number at index x, nums[x] if (num[x+1] > nums[x]), that means a peak element HAS to exist on the right half of that array, because (since every number is unique) 1. the numbers keep increasing on the right side, and the peak will be the last element. 2. the numbers stop ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findPeakElement(self, nums): Lets say you have a mid number at index x, nums[x] if (num[x+1] > nums[x]), that means a peak element HAS to exist on the right half of that arra...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findPeakElement(self, nums): Lets say you have a mid number at index x, nums[x] if (num[x+1] > nums[x]), that means a peak element HAS to exist on the right half of that arra...
8bb17099be02d997d554519be360ef4aa1c028e3
<|skeleton|> class Solution: def findPeakElement(self, nums): """Lets say you have a mid number at index x, nums[x] if (num[x+1] > nums[x]), that means a peak element HAS to exist on the right half of that array, because (since every number is unique) 1. the numbers keep increasing on the right side, and t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findPeakElement(self, nums): """Lets say you have a mid number at index x, nums[x] if (num[x+1] > nums[x]), that means a peak element HAS to exist on the right half of that array, because (since every number is unique) 1. the numbers keep increasing on the right side, and the peak will b...
the_stack_v2_python_sparse
Google/2. medium/162. Find Peak Element.py
yemao616/summer18
train
0
9f6612c20775ec9469ae89dd92f50276327e5a22
[ "super(PCC_Layer, self).__init__()\nself.alpha = alpha\nself.centroid = centroid", "z = emb.unsqueeze(1)\nu = self.centroid\nqij = (1.0 + torch.sum((z - u) ** 2, dim=2) / self.alpha) ** (-1)\nqij_normalize = qij.T / torch.sum(qij, dim=1)\nqij_normalize = qij_normalize.T\nreturn qij_normalize" ]
<|body_start_0|> super(PCC_Layer, self).__init__() self.alpha = alpha self.centroid = centroid <|end_body_0|> <|body_start_1|> z = emb.unsqueeze(1) u = self.centroid qij = (1.0 + torch.sum((z - u) ** 2, dim=2) / self.alpha) ** (-1) qij_normalize = qij.T / torch.s...
PCC_Layer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PCC_Layer: def __init__(self, centroid, alpha=1.0): """:param centroid: tensor, predefined centroid, shape: (n_class, emb_dim)""" <|body_0|> def forward(self, emb): """see paper `Unsupervised Deep Embedding for Clustering Analysis` qij = 1/(1+dist(zi, uj)^2), then no...
stack_v2_sparse_classes_36k_train_006052
2,727
no_license
[ { "docstring": ":param centroid: tensor, predefined centroid, shape: (n_class, emb_dim)", "name": "__init__", "signature": "def __init__(self, centroid, alpha=1.0)" }, { "docstring": "see paper `Unsupervised Deep Embedding for Clustering Analysis` qij = 1/(1+dist(zi, uj)^2), then normalize it. q...
2
null
Implement the Python class `PCC_Layer` described below. Class description: Implement the PCC_Layer class. Method signatures and docstrings: - def __init__(self, centroid, alpha=1.0): :param centroid: tensor, predefined centroid, shape: (n_class, emb_dim) - def forward(self, emb): see paper `Unsupervised Deep Embeddin...
Implement the Python class `PCC_Layer` described below. Class description: Implement the PCC_Layer class. Method signatures and docstrings: - def __init__(self, centroid, alpha=1.0): :param centroid: tensor, predefined centroid, shape: (n_class, emb_dim) - def forward(self, emb): see paper `Unsupervised Deep Embeddin...
4e5908eb4c230e80e7d49bdbd77e7ec73de327c6
<|skeleton|> class PCC_Layer: def __init__(self, centroid, alpha=1.0): """:param centroid: tensor, predefined centroid, shape: (n_class, emb_dim)""" <|body_0|> def forward(self, emb): """see paper `Unsupervised Deep Embedding for Clustering Analysis` qij = 1/(1+dist(zi, uj)^2), then no...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PCC_Layer: def __init__(self, centroid, alpha=1.0): """:param centroid: tensor, predefined centroid, shape: (n_class, emb_dim)""" super(PCC_Layer, self).__init__() self.alpha = alpha self.centroid = centroid def forward(self, emb): """see paper `Unsupervised Deep E...
the_stack_v2_python_sparse
network_torch/Dual_CSA.py
lusccc/Trajectory-Classification-using-Dual-CSA
train
10
01e855c7d9a293fd79de0a25505cf281760a14b2
[ "Turtle.__init__(self, shape='square', visible=False)\nself.penup()\nself.shapesize(n * 1.25, 0.75, 1)\nself.sety(12.5 * n)\nself.x = Peg.pos\nself.setx(self.x)\nself.showturtle()\nPeg.pos += 200", "disk.setx(self.x)\ndisk.sety(10 + len(self) * 25)\nself.append(disk)", "disk = self.pop()\ndisk.sety(300)\nreturn...
<|body_start_0|> Turtle.__init__(self, shape='square', visible=False) self.penup() self.shapesize(n * 1.25, 0.75, 1) self.sety(12.5 * n) self.x = Peg.pos self.setx(self.x) self.showturtle() Peg.pos += 200 <|end_body_0|> <|body_start_1|> disk.setx(...
Classe de pino da torre de Hanói, herda de Turtle e list ________________________________________________________ __init__(self, n) Inicializa um pino para n discos pop(self) Remove o disco de cima do pino e o retorna push(self, disk) coloca o disco no pino
Peg
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Peg: """Classe de pino da torre de Hanói, herda de Turtle e list ________________________________________________________ __init__(self, n) Inicializa um pino para n discos pop(self) Remove o disco de cima do pino e o retorna push(self, disk) coloca o disco no pino""" def __init__(self, n): ...
stack_v2_sparse_classes_36k_train_006053
2,822
no_license
[ { "docstring": "Inicializa um pino para n discos", "name": "__init__", "signature": "def __init__(self, n)" }, { "docstring": "Coloca disco em torno do pino", "name": "push", "signature": "def push(self, disk)" }, { "docstring": "Remove disco do topo do pino e o retorna", "na...
3
stack_v2_sparse_classes_30k_train_015896
Implement the Python class `Peg` described below. Class description: Classe de pino da torre de Hanói, herda de Turtle e list ________________________________________________________ __init__(self, n) Inicializa um pino para n discos pop(self) Remove o disco de cima do pino e o retorna push(self, disk) coloca o disco ...
Implement the Python class `Peg` described below. Class description: Classe de pino da torre de Hanói, herda de Turtle e list ________________________________________________________ __init__(self, n) Inicializa um pino para n discos pop(self) Remove o disco de cima do pino e o retorna push(self, disk) coloca o disco ...
5d4eec368be91c18f0ae5c17d342e6eb0f1c79be
<|skeleton|> class Peg: """Classe de pino da torre de Hanói, herda de Turtle e list ________________________________________________________ __init__(self, n) Inicializa um pino para n discos pop(self) Remove o disco de cima do pino e o retorna push(self, disk) coloca o disco no pino""" def __init__(self, n): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Peg: """Classe de pino da torre de Hanói, herda de Turtle e list ________________________________________________________ __init__(self, n) Inicializa um pino para n discos pop(self) Remove o disco de cima do pino e o retorna push(self, disk) coloca o disco no pino""" def __init__(self, n): """In...
the_stack_v2_python_sparse
Semana3/turtle_hanoi.py
ju-c-lopes/Univesp_Algoritmos_II
train
0
fd245947dd9512226f8e90622a907d9a1a639817
[ "self._z_nodes = z_nodes.astype(np.float64)\nself._redshifts = redshifts.astype(np.float64)\nself._values = values.astype(np.float64)", "bounds = []\nfor i in range(len(p0)):\n bounds.append([min_val, max_val])\nres = scipy.optimize.minimize(self, p0, method='L-BFGS-B', bounds=bounds, jac=False, options={'maxf...
<|body_start_0|> self._z_nodes = z_nodes.astype(np.float64) self._redshifts = redshifts.astype(np.float64) self._values = values.astype(np.float64) <|end_body_0|> <|body_start_1|> bounds = [] for i in range(len(p0)): bounds.append([min_val, max_val]) res = sc...
Class to fit a spline to the median value as a function of redshift. This can be the color or magnitude or any quantity.
MedZFitter
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MedZFitter: """Class to fit a spline to the median value as a function of redshift. This can be the color or magnitude or any quantity.""" def __init__(self, z_nodes, redshifts, values): """Instantiate a MedZFitter object Parameters ---------- z_nodes: `np.array` Float array for reds...
stack_v2_sparse_classes_36k_train_006054
45,530
permissive
[ { "docstring": "Instantiate a MedZFitter object Parameters ---------- z_nodes: `np.array` Float array for redshift nodes redshifts: `np.array` Float array of input redshifts to fit values: `np.array` Float array of color values to fit", "name": "__init__", "signature": "def __init__(self, z_nodes, redsh...
3
stack_v2_sparse_classes_30k_train_017443
Implement the Python class `MedZFitter` described below. Class description: Class to fit a spline to the median value as a function of redshift. This can be the color or magnitude or any quantity. Method signatures and docstrings: - def __init__(self, z_nodes, redshifts, values): Instantiate a MedZFitter object Param...
Implement the Python class `MedZFitter` described below. Class description: Class to fit a spline to the median value as a function of redshift. This can be the color or magnitude or any quantity. Method signatures and docstrings: - def __init__(self, z_nodes, redshifts, values): Instantiate a MedZFitter object Param...
d3a8b432c2f3a20aa518a7781c0f2aa315624855
<|skeleton|> class MedZFitter: """Class to fit a spline to the median value as a function of redshift. This can be the color or magnitude or any quantity.""" def __init__(self, z_nodes, redshifts, values): """Instantiate a MedZFitter object Parameters ---------- z_nodes: `np.array` Float array for reds...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MedZFitter: """Class to fit a spline to the median value as a function of redshift. This can be the color or magnitude or any quantity.""" def __init__(self, z_nodes, redshifts, values): """Instantiate a MedZFitter object Parameters ---------- z_nodes: `np.array` Float array for redshift nodes re...
the_stack_v2_python_sparse
redmapper/fitters.py
erykoff/redmapper
train
20
f7b92c135c678cae08d786fe7507e3ed2b784744
[ "with self.Session() as session:\n if filter_id is not None:\n f = session.scalars(Filter.select(session.user_or_token, options=[joinedload(Filter.stream)]).where(Filter.id == filter_id)).first()\n if f is None:\n return self.error(f'Cannot find a filter with ID: {filter_id}.')\n ...
<|body_start_0|> with self.Session() as session: if filter_id is not None: f = session.scalars(Filter.select(session.user_or_token, options=[joinedload(Filter.stream)]).where(Filter.id == filter_id)).first() if f is None: return self.error(f'Cannot...
FilterHandler
[ "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FilterHandler: def get(self, filter_id=None): """--- single: description: Retrieve a filter tags: - filters parameters: - in: path name: filter_id required: true schema: type: integer responses: 200: content: application/json: schema: SingleFilter 400: content: application/json: schema: ...
stack_v2_sparse_classes_36k_train_006055
5,485
permissive
[ { "docstring": "--- single: description: Retrieve a filter tags: - filters parameters: - in: path name: filter_id required: true schema: type: integer responses: 200: content: application/json: schema: SingleFilter 400: content: application/json: schema: Error multiple: description: Retrieve all filters tags: -...
4
stack_v2_sparse_classes_30k_train_000880
Implement the Python class `FilterHandler` described below. Class description: Implement the FilterHandler class. Method signatures and docstrings: - def get(self, filter_id=None): --- single: description: Retrieve a filter tags: - filters parameters: - in: path name: filter_id required: true schema: type: integer re...
Implement the Python class `FilterHandler` described below. Class description: Implement the FilterHandler class. Method signatures and docstrings: - def get(self, filter_id=None): --- single: description: Retrieve a filter tags: - filters parameters: - in: path name: filter_id required: true schema: type: integer re...
161d3532ba3ba059446addcdac58ca96f39e9636
<|skeleton|> class FilterHandler: def get(self, filter_id=None): """--- single: description: Retrieve a filter tags: - filters parameters: - in: path name: filter_id required: true schema: type: integer responses: 200: content: application/json: schema: SingleFilter 400: content: application/json: schema: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FilterHandler: def get(self, filter_id=None): """--- single: description: Retrieve a filter tags: - filters parameters: - in: path name: filter_id required: true schema: type: integer responses: 200: content: application/json: schema: SingleFilter 400: content: application/json: schema: Error multiple...
the_stack_v2_python_sparse
skyportal/handlers/api/filter.py
skyportal/skyportal
train
80
03edf1a97d3ec2e95b7a9500a951150bf5cbaf95
[ "input_json = request.data\noutput_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [input_json['AvailabilityDetails'], input_json['AuthenticationDetails'], input_json['SessionDetails'], None]))\ntry:\n json_params = input_json['APIParams']\n json_params['profile_...
<|body_start_0|> input_json = request.data output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [input_json['AvailabilityDetails'], input_json['AuthenticationDetails'], input_json['SessionDetails'], None])) try: json_params = input_jso...
This API will create a notification
PopulateMyNotificationsAPI
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PopulateMyNotificationsAPI: """This API will create a notification""" def post(self, request): """Post function to crete a notification""" <|body_0|> def populate_my_notifications_json(self, request): """This API will create a notification :param request: { 'prof...
stack_v2_sparse_classes_36k_train_006056
3,021
no_license
[ { "docstring": "Post function to crete a notification", "name": "post", "signature": "def post(self, request)" }, { "docstring": "This API will create a notification :param request: { 'profile_id':277 } :return", "name": "populate_my_notifications_json", "signature": "def populate_my_not...
2
stack_v2_sparse_classes_30k_test_000554
Implement the Python class `PopulateMyNotificationsAPI` described below. Class description: This API will create a notification Method signatures and docstrings: - def post(self, request): Post function to crete a notification - def populate_my_notifications_json(self, request): This API will create a notification :p...
Implement the Python class `PopulateMyNotificationsAPI` described below. Class description: This API will create a notification Method signatures and docstrings: - def post(self, request): Post function to crete a notification - def populate_my_notifications_json(self, request): This API will create a notification :p...
36eb9931f330e64902354c6fc471be2adf4b7049
<|skeleton|> class PopulateMyNotificationsAPI: """This API will create a notification""" def post(self, request): """Post function to crete a notification""" <|body_0|> def populate_my_notifications_json(self, request): """This API will create a notification :param request: { 'prof...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PopulateMyNotificationsAPI: """This API will create a notification""" def post(self, request): """Post function to crete a notification""" input_json = request.data output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [input_json['A...
the_stack_v2_python_sparse
Generic/common/notifications_new/api/populate_my_notifications/views_populate_my_notifications.py
archiemb303/common_backend_django
train
0
4cd2442be7be6778bc5050fdc35655dd0eb1d010
[ "if len(lists) == 0:\n return\nhead = ListNode(0)\nnew_list = head\nK = len(lists)\nres = lists[0]\nfor i in range(1, K):\n res = self.mergeTwoLists(res, lists[i])\nreturn res", "new_head = ListNode(0)\nnew_list = new_head\nwhile l1 and l2:\n if l1.val < l2.val:\n new_head.next = l1\n l1 = ...
<|body_start_0|> if len(lists) == 0: return head = ListNode(0) new_list = head K = len(lists) res = lists[0] for i in range(1, K): res = self.mergeTwoLists(res, lists[i]) return res <|end_body_0|> <|body_start_1|> new_head = ListNo...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def mergeKLists(self, lists): """:type lists: List[ListNode] :rtype: ListNode""" <|body_0|> def mergeTwoLists(self, l1, l2): """:type l1: ListNode :type l2: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(l...
stack_v2_sparse_classes_36k_train_006057
1,105
permissive
[ { "docstring": ":type lists: List[ListNode] :rtype: ListNode", "name": "mergeKLists", "signature": "def mergeKLists(self, lists)" }, { "docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode", "name": "mergeTwoLists", "signature": "def mergeTwoLists(self, l1, l2)" } ]
2
stack_v2_sparse_classes_30k_train_016759
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode - def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode - def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode <|skeleton|>...
e00ebc7d83583ffd26c53f48efdd27ebc76a9623
<|skeleton|> class Solution: def mergeKLists(self, lists): """:type lists: List[ListNode] :rtype: ListNode""" <|body_0|> def mergeTwoLists(self, l1, l2): """:type l1: ListNode :type l2: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def mergeKLists(self, lists): """:type lists: List[ListNode] :rtype: ListNode""" if len(lists) == 0: return head = ListNode(0) new_list = head K = len(lists) res = lists[0] for i in range(1, K): res = self.mergeTwoLists(...
the_stack_v2_python_sparse
23_Merge-K-Sorted-Lists.py
Coalin/Daily-LeetCode-Exercise
train
4
a3a777a18022111b81a565503bf9a2246dd90bbb
[ "super().__init__()\nif weights is not None and (not np.isclose(weights.sum(), 1)):\n raise ValueError('Weights must sum to 1.')\nself.weights = weights", "if self.weights is None:\n m = scores.shape[-1]\n self.weights = torch.ones(m, device=scores.device) / m\nreturn scores @ self.weights" ]
<|body_start_0|> super().__init__() if weights is not None and (not np.isclose(weights.sum(), 1)): raise ValueError('Weights must sum to 1.') self.weights = weights <|end_body_0|> <|body_start_1|> if self.weights is None: m = scores.shape[-1] self.wei...
AverageAggregator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AverageAggregator: def __init__(self, weights: Optional[torch.Tensor]=None): """Averages the scores of the detectors in an ensemble. Parameters ---------- weights Optional parameter to weight the scores. If `weights` is left ``None`` then will be set to a vector of ones. Raises ------ Va...
stack_v2_sparse_classes_36k_train_006058
9,337
permissive
[ { "docstring": "Averages the scores of the detectors in an ensemble. Parameters ---------- weights Optional parameter to weight the scores. If `weights` is left ``None`` then will be set to a vector of ones. Raises ------ ValueError If `weights` does not sum to ``1``.", "name": "__init__", "signature": ...
2
stack_v2_sparse_classes_30k_train_013021
Implement the Python class `AverageAggregator` described below. Class description: Implement the AverageAggregator class. Method signatures and docstrings: - def __init__(self, weights: Optional[torch.Tensor]=None): Averages the scores of the detectors in an ensemble. Parameters ---------- weights Optional parameter ...
Implement the Python class `AverageAggregator` described below. Class description: Implement the AverageAggregator class. Method signatures and docstrings: - def __init__(self, weights: Optional[torch.Tensor]=None): Averages the scores of the detectors in an ensemble. Parameters ---------- weights Optional parameter ...
4a1b4f74a8590117965421e86c2295bff0f33e89
<|skeleton|> class AverageAggregator: def __init__(self, weights: Optional[torch.Tensor]=None): """Averages the scores of the detectors in an ensemble. Parameters ---------- weights Optional parameter to weight the scores. If `weights` is left ``None`` then will be set to a vector of ones. Raises ------ Va...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AverageAggregator: def __init__(self, weights: Optional[torch.Tensor]=None): """Averages the scores of the detectors in an ensemble. Parameters ---------- weights Optional parameter to weight the scores. If `weights` is left ``None`` then will be set to a vector of ones. Raises ------ ValueError If `w...
the_stack_v2_python_sparse
alibi_detect/od/pytorch/ensemble.py
SeldonIO/alibi-detect
train
1,922
297d24bc2ac40c285d60abb20a14071b3e94fe10
[ "if not email:\n raise ValueError('The given email must be set')\nemail = self.normalize_email(email)\nuser = self.model(email=email, **extra_fields)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "extra_fields.setdefault('is_staff', False)\nextra_fields.setdefault('is_superuser', False...
<|body_start_0|> if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user <|end_body_0|> <|body_start_1|>...
Define a model manager for User model with no username field.
ParticipantManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParticipantManager: """Define a model manager for User model with no username field.""" def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" <|body_0|> def create_user(self, email, password=None, **extra...
stack_v2_sparse_classes_36k_train_006059
3,675
no_license
[ { "docstring": "Create and save a User with the given email and password.", "name": "_create_user", "signature": "def _create_user(self, email, password, **extra_fields)" }, { "docstring": "Create and save a regular User with the given email and password.", "name": "create_user", "signat...
3
stack_v2_sparse_classes_30k_train_012911
Implement the Python class `ParticipantManager` described below. Class description: Define a model manager for User model with no username field. Method signatures and docstrings: - def _create_user(self, email, password, **extra_fields): Create and save a User with the given email and password. - def create_user(sel...
Implement the Python class `ParticipantManager` described below. Class description: Define a model manager for User model with no username field. Method signatures and docstrings: - def _create_user(self, email, password, **extra_fields): Create and save a User with the given email and password. - def create_user(sel...
a57b9fe5b73e58e703f15b6f3c55a9dde8102496
<|skeleton|> class ParticipantManager: """Define a model manager for User model with no username field.""" def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" <|body_0|> def create_user(self, email, password=None, **extra...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ParticipantManager: """Define a model manager for User model with no username field.""" def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') ...
the_stack_v2_python_sparse
meetings/models.py
gsoosk/Jalas-Backend
train
0
9be28398bae2e72073be7df5197abfc079264fe9
[ "k = k % len(nums)\nfor i in range(len(nums) - k):\n nums.append(nums[0])\n nums.pop(0)\nreturn nums", "k = k % len(nums)\nfor _ in range(k):\n nums.insert(0, nums.pop())\nreturn nums", "k = k % len(nums)\nnums[:] = nums[-k:] + nums[:-k]\nreturn nums" ]
<|body_start_0|> k = k % len(nums) for i in range(len(nums) - k): nums.append(nums[0]) nums.pop(0) return nums <|end_body_0|> <|body_start_1|> k = k % len(nums) for _ in range(k): nums.insert(0, nums.pop()) return nums <|end_body_1|> ...
Solution
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rotate(self, nums: list, k: int) -> None: """Do not return anything, modify nums in-place instead.""" <|body_0|> def rotate2(self, nums: list, k: int) -> None: """Do not return anything, modify nums in-place instead.""" <|body_1|> def rotat...
stack_v2_sparse_classes_36k_train_006060
1,053
permissive
[ { "docstring": "Do not return anything, modify nums in-place instead.", "name": "rotate", "signature": "def rotate(self, nums: list, k: int) -> None" }, { "docstring": "Do not return anything, modify nums in-place instead.", "name": "rotate2", "signature": "def rotate2(self, nums: list, ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, nums: list, k: int) -> None: Do not return anything, modify nums in-place instead. - def rotate2(self, nums: list, k: int) -> None: Do not return anything, modif...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, nums: list, k: int) -> None: Do not return anything, modify nums in-place instead. - def rotate2(self, nums: list, k: int) -> None: Do not return anything, modif...
e32439a76968d67f99881b6d07fb16e21c979c9e
<|skeleton|> class Solution: def rotate(self, nums: list, k: int) -> None: """Do not return anything, modify nums in-place instead.""" <|body_0|> def rotate2(self, nums: list, k: int) -> None: """Do not return anything, modify nums in-place instead.""" <|body_1|> def rotat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def rotate(self, nums: list, k: int) -> None: """Do not return anything, modify nums in-place instead.""" k = k % len(nums) for i in range(len(nums) - k): nums.append(nums[0]) nums.pop(0) return nums def rotate2(self, nums: list, k: int) -...
the_stack_v2_python_sparse
python/189.py
HymEric/LeetCode
train
2
73e052d3dbc62d41812b3604abf98d9540c48977
[ "Strategy.__init__(self)\nself._spread_size_indicator = SpreadSize(minimum_return, market_fee)\nself.default_position = default_position\nself.current_position = default_position\nself._first_time_unprofitable = True\nwith localcontext() as context:\n context.prec = 8\n self.undercut_market_by = Decimal(under...
<|body_start_0|> Strategy.__init__(self) self._spread_size_indicator = SpreadSize(minimum_return, market_fee) self.default_position = default_position self.current_position = default_position self._first_time_unprofitable = True with localcontext() as context: ...
SpreadSizeStrategy
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpreadSizeStrategy: def __init__(self, default_position, undercut_market_by=0.01, minimum_return=1.005, market_fee=0.005): """default_position is whether the Strategy should hold the minor currency (sell, False) or the major currency (buy / True) after scalping the market. For example, i...
stack_v2_sparse_classes_36k_train_006061
4,149
no_license
[ { "docstring": "default_position is whether the Strategy should hold the minor currency (sell, False) or the major currency (buy / True) after scalping the market. For example, in a USD-CAD market True would mean CAD is held after scalping and False would mean USD is held after scalping. It is assumed that the ...
2
stack_v2_sparse_classes_30k_train_016997
Implement the Python class `SpreadSizeStrategy` described below. Class description: Implement the SpreadSizeStrategy class. Method signatures and docstrings: - def __init__(self, default_position, undercut_market_by=0.01, minimum_return=1.005, market_fee=0.005): default_position is whether the Strategy should hold th...
Implement the Python class `SpreadSizeStrategy` described below. Class description: Implement the SpreadSizeStrategy class. Method signatures and docstrings: - def __init__(self, default_position, undercut_market_by=0.01, minimum_return=1.005, market_fee=0.005): default_position is whether the Strategy should hold th...
e0e08d1811d84a90cd62d762c6444e54de0c3da4
<|skeleton|> class SpreadSizeStrategy: def __init__(self, default_position, undercut_market_by=0.01, minimum_return=1.005, market_fee=0.005): """default_position is whether the Strategy should hold the minor currency (sell, False) or the major currency (buy / True) after scalping the market. For example, i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpreadSizeStrategy: def __init__(self, default_position, undercut_market_by=0.01, minimum_return=1.005, market_fee=0.005): """default_position is whether the Strategy should hold the minor currency (sell, False) or the major currency (buy / True) after scalping the market. For example, in a USD-CAD ma...
the_stack_v2_python_sparse
cryptotrader/tradesignals/strategies/spread_size_strategy.py
SPLT12/cryptocurrency-trader
train
0
73e2e2d32a970b297706cefd49903747f9c9867d
[ "super().__init__(filterFineData, universeSettings)\nself.NumberOfSymbolsCoarse = 500\nself.NumberOfSymbolsFine = 20\nself.NumberOfSymbolsInPortfolio = 10\nself.lastMonth = -1\nself.dollarVolumeBySymbol = {}", "month = algorithm.Time.month\nif month == self.lastMonth:\n return Universe.Unchanged\nself.lastMont...
<|body_start_0|> super().__init__(filterFineData, universeSettings) self.NumberOfSymbolsCoarse = 500 self.NumberOfSymbolsFine = 20 self.NumberOfSymbolsInPortfolio = 10 self.lastMonth = -1 self.dollarVolumeBySymbol = {} <|end_body_0|> <|body_start_1|> month = algo...
Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm. From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Value to EBITDA (EV/EBITDA) and Return on Assets (ROA).
GreenBlattMagicFormulaUniverseSelectionModel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GreenBlattMagicFormulaUniverseSelectionModel: """Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm. From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Value to EBITDA (EV/EBITDA) and Return on ...
stack_v2_sparse_classes_36k_train_006062
9,868
permissive
[ { "docstring": "Initializes a new default instance of the MagicFormulaUniverseSelectionModel", "name": "__init__", "signature": "def __init__(self, filterFineData=True, universeSettings=None)" }, { "docstring": "Performs coarse selection for constituents. The stocks must have fundamental data", ...
3
stack_v2_sparse_classes_30k_train_017342
Implement the Python class `GreenBlattMagicFormulaUniverseSelectionModel` described below. Class description: Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm. From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Val...
Implement the Python class `GreenBlattMagicFormulaUniverseSelectionModel` described below. Class description: Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm. From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Val...
b33dd3bc140e14b883f39ecf848a793cf7292277
<|skeleton|> class GreenBlattMagicFormulaUniverseSelectionModel: """Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm. From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Value to EBITDA (EV/EBITDA) and Return on ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GreenBlattMagicFormulaUniverseSelectionModel: """Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm. From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Value to EBITDA (EV/EBITDA) and Return on Assets (ROA)....
the_stack_v2_python_sparse
Algorithm.Python/Alphas/GreenblattMagicFormulaAlpha.py
Capnode/Algoloop
train
87
82d177ae8f7f7354f839b0adefe649a66694de7f
[ "import numpy as np\nif sina is not None:\n cosa = cosa + 1j * sina\nreturn np.angle(cosa) % (2 * np.pi)", "import numpy as np\nfrom jizhipy.Array import Asarray\nfrom jizhipy.Basic import Raise\nangle, axis = (npfmt(angle1), int(axis))\nif axis < 0:\n axis += len(angle.shape)\nif axis > len(angle.shape):\n...
<|body_start_0|> import numpy as np if sina is not None: cosa = cosa + 1j * sina return np.angle(cosa) % (2 * np.pi) <|end_body_0|> <|body_start_1|> import numpy as np from jizhipy.Array import Asarray from jizhipy.Basic import Raise angle, axis = (np...
Angle
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Angle: def Angle(self, cosa, sina=None): """return the phase (case 1) cosa = A*np.cos(a) sina = A*np.sin(a) return a (case 2) cosa = np.complex (real + 1j*imag) sina = None""" <|body_0|> def AngleMean(self, angle1, angle2=None, axis=0): """return: angle.mean(axis) an...
stack_v2_sparse_classes_36k_train_006063
1,967
no_license
[ { "docstring": "return the phase (case 1) cosa = A*np.cos(a) sina = A*np.sin(a) return a (case 2) cosa = np.complex (real + 1j*imag) sina = None", "name": "Angle", "signature": "def Angle(self, cosa, sina=None)" }, { "docstring": "return: angle.mean(axis) angle1: [rad] Any shape array angle2: (1...
3
stack_v2_sparse_classes_30k_train_017177
Implement the Python class `Angle` described below. Class description: Implement the Angle class. Method signatures and docstrings: - def Angle(self, cosa, sina=None): return the phase (case 1) cosa = A*np.cos(a) sina = A*np.sin(a) return a (case 2) cosa = np.complex (real + 1j*imag) sina = None - def AngleMean(self,...
Implement the Python class `Angle` described below. Class description: Implement the Angle class. Method signatures and docstrings: - def Angle(self, cosa, sina=None): return the phase (case 1) cosa = A*np.cos(a) sina = A*np.sin(a) return a (case 2) cosa = np.complex (real + 1j*imag) sina = None - def AngleMean(self,...
b49777105a76b5ae03555a9f93f116454c8245a9
<|skeleton|> class Angle: def Angle(self, cosa, sina=None): """return the phase (case 1) cosa = A*np.cos(a) sina = A*np.sin(a) return a (case 2) cosa = np.complex (real + 1j*imag) sina = None""" <|body_0|> def AngleMean(self, angle1, angle2=None, axis=0): """return: angle.mean(axis) an...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Angle: def Angle(self, cosa, sina=None): """return the phase (case 1) cosa = A*np.cos(a) sina = A*np.sin(a) return a (case 2) cosa = np.complex (real + 1j*imag) sina = None""" import numpy as np if sina is not None: cosa = cosa + 1j * sina return np.angle(cosa) % (2...
the_stack_v2_python_sparse
Basic/Angle.py
jizhi/jizhipy
train
1
ada8ccf58df8e113b632e5dda96b142d18234d1e
[ "self.k = k\nself.nums = nums\nheapq.heapify(self.nums)\nwhile len(self.nums) > k:\n heapq.heappop(self.nums)", "if len(self.nums) < self.k:\n heapq.heappush(self.nums, val)\nelif val > self.nums[0]:\n heapq.heapreplace(self.nums, val)\nreturn self.nums[0]" ]
<|body_start_0|> self.k = k self.nums = nums heapq.heapify(self.nums) while len(self.nums) > k: heapq.heappop(self.nums) <|end_body_0|> <|body_start_1|> if len(self.nums) < self.k: heapq.heappush(self.nums, val) elif val > self.nums[0]: ...
KthLargest1
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KthLargest1: def __init__(self, k, nums): """:type k: int :type nums: List[int]""" <|body_0|> def add(self, val): """:type val: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.k = k self.nums = nums heapq.heapify...
stack_v2_sparse_classes_36k_train_006064
1,362
no_license
[ { "docstring": ":type k: int :type nums: List[int]", "name": "__init__", "signature": "def __init__(self, k, nums)" }, { "docstring": ":type val: int :rtype: int", "name": "add", "signature": "def add(self, val)" } ]
2
stack_v2_sparse_classes_30k_train_011197
Implement the Python class `KthLargest1` described below. Class description: Implement the KthLargest1 class. Method signatures and docstrings: - def __init__(self, k, nums): :type k: int :type nums: List[int] - def add(self, val): :type val: int :rtype: int
Implement the Python class `KthLargest1` described below. Class description: Implement the KthLargest1 class. Method signatures and docstrings: - def __init__(self, k, nums): :type k: int :type nums: List[int] - def add(self, val): :type val: int :rtype: int <|skeleton|> class KthLargest1: def __init__(self, k,...
d4a33dc28a6d3f99d5179fdb6a83b2ab8c5a0beb
<|skeleton|> class KthLargest1: def __init__(self, k, nums): """:type k: int :type nums: List[int]""" <|body_0|> def add(self, val): """:type val: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KthLargest1: def __init__(self, k, nums): """:type k: int :type nums: List[int]""" self.k = k self.nums = nums heapq.heapify(self.nums) while len(self.nums) > k: heapq.heappop(self.nums) def add(self, val): """:type val: int :rtype: int""" ...
the_stack_v2_python_sparse
leetcode/703_kth_largest_num.py
294150302hxq/python_learn
train
0
9fde606ade16252bad5d05584853b2c887c4def4
[ "endpoint = '/models/{}/features-importances/download'.format(self._id)\nresponse = client.request(endpoint=endpoint, method=requests.get, message_prefix='Fetch feature importance')\ndf_feat_importance = zip_to_pandas(response)\nreturn df_feat_importance.sort_values(by='importance', ascending=False)", "logger.deb...
<|body_start_0|> endpoint = '/models/{}/features-importances/download'.format(self._id) response = client.request(endpoint=endpoint, method=requests.get, message_prefix='Fetch feature importance') df_feat_importance = zip_to_pandas(response) return df_feat_importance.sort_values(by='impo...
ClassicModel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClassicModel: def feature_importance(self) -> pd.DataFrame: """Return a dataframe of feature importances for the given model features, with their corresponding scores (sorted by descending feature importance scores). Returns: ``pd.DataFrame``: Dataframe of feature importances Raises: Pre...
stack_v2_sparse_classes_36k_train_006065
22,476
permissive
[ { "docstring": "Return a dataframe of feature importances for the given model features, with their corresponding scores (sorted by descending feature importance scores). Returns: ``pd.DataFrame``: Dataframe of feature importances Raises: PrevisionException: Any error while fetching data from the platform or par...
4
stack_v2_sparse_classes_30k_train_019300
Implement the Python class `ClassicModel` described below. Class description: Implement the ClassicModel class. Method signatures and docstrings: - def feature_importance(self) -> pd.DataFrame: Return a dataframe of feature importances for the given model features, with their corresponding scores (sorted by descendin...
Implement the Python class `ClassicModel` described below. Class description: Implement the ClassicModel class. Method signatures and docstrings: - def feature_importance(self) -> pd.DataFrame: Return a dataframe of feature importances for the given model features, with their corresponding scores (sorted by descendin...
0860c931e2b466ac4be910350890085111ae32ce
<|skeleton|> class ClassicModel: def feature_importance(self) -> pd.DataFrame: """Return a dataframe of feature importances for the given model features, with their corresponding scores (sorted by descending feature importance scores). Returns: ``pd.DataFrame``: Dataframe of feature importances Raises: Pre...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClassicModel: def feature_importance(self) -> pd.DataFrame: """Return a dataframe of feature importances for the given model features, with their corresponding scores (sorted by descending feature importance scores). Returns: ``pd.DataFrame``: Dataframe of feature importances Raises: PrevisionExceptio...
the_stack_v2_python_sparse
previsionio/model.py
FrancoisA-prevision/prevision-python
train
0
14f229d21cf6ef1b3df5017db0273fd6874a0179
[ "result = []\nif not root:\n return result\nqueue = collections.deque([root])\nwhile queue:\n root = queue.pop()\n result.append('#')\n if root:\n result.append(str(root.val))\n queue.appendleft(root.left)\n queue.appendleft(root.right)\nreturn ''.join(result[1:])", "index = 0\nif...
<|body_start_0|> result = [] if not root: return result queue = collections.deque([root]) while queue: root = queue.pop() result.append('#') if root: result.append(str(root.val)) queue.appendleft(root.left) ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_006066
3,899
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_val_000238
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:...
d953abe2c9680f636563e76287d2f907e90ced63
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" result = [] if not root: return result queue = collections.deque([root]) while queue: root = queue.pop() result.append('#') ...
the_stack_v2_python_sparse
Python_leetcode/297_serialize_and_deserialize.py
xiangcao/Leetcode
train
0
d8bbe49eaa15dda5785235839a66a1ab96be2b34
[ "def search(left, right):\n while left >= 0 and right < len(s) and (s[left] == s[right]):\n if left == 0:\n cuts[right] = 0\n else:\n cuts[right] = min(cuts[right], cuts[left - 1] + 1)\n left -= 1\n right += 1\ncuts = [x for x in range(len(s))]\nfor i in range(le...
<|body_start_0|> def search(left, right): while left >= 0 and right < len(s) and (s[left] == s[right]): if left == 0: cuts[right] = 0 else: cuts[right] = min(cuts[right], cuts[left - 1] + 1) left -= 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minCut(self, s): """:type s: str :rtype: int""" <|body_0|> def minCut_v2(self, s): """:type s: str :rtype: int""" <|body_1|> def minCut_TLE(self, s): """:type s: str :rtype: int""" <|body_2|> <|end_skeleton|> <|body_start_...
stack_v2_sparse_classes_36k_train_006067
3,592
no_license
[ { "docstring": ":type s: str :rtype: int", "name": "minCut", "signature": "def minCut(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "minCut_v2", "signature": "def minCut_v2(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "minCut_TLE", "si...
3
stack_v2_sparse_classes_30k_test_001164
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minCut(self, s): :type s: str :rtype: int - def minCut_v2(self, s): :type s: str :rtype: int - def minCut_TLE(self, s): :type s: str :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minCut(self, s): :type s: str :rtype: int - def minCut_v2(self, s): :type s: str :rtype: int - def minCut_TLE(self, s): :type s: str :rtype: int <|skeleton|> class Solution:...
e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59
<|skeleton|> class Solution: def minCut(self, s): """:type s: str :rtype: int""" <|body_0|> def minCut_v2(self, s): """:type s: str :rtype: int""" <|body_1|> def minCut_TLE(self, s): """:type s: str :rtype: int""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minCut(self, s): """:type s: str :rtype: int""" def search(left, right): while left >= 0 and right < len(s) and (s[left] == s[right]): if left == 0: cuts[right] = 0 else: cuts[right] = min(cuts[ri...
the_stack_v2_python_sparse
src/lt_132.py
oxhead/CodingYourWay
train
0
ca939a619343cbcd5044ff5497207ae832849471
[ "self.name = name\nself.sequence = sequence\nself.metadata = {} if metadata is None else metadata", "ind = sequence.find(self.sequence)\nstrand = 1\nif ind == -1:\n ind = sequence.find(reverse_complement(self.sequence))\n if ind == -1:\n return None\n else:\n ind = len(sequence) - ind - len...
<|body_start_0|> self.name = name self.sequence = sequence self.metadata = {} if metadata is None else metadata <|end_body_0|> <|body_start_1|> ind = sequence.find(self.sequence) strand = 1 if ind == -1: ind = sequence.find(reverse_complement(self.sequence)) ...
Class representing a sequencing primer Parameters ---------- name Name (label) of the primer sequence An ATGC string metadata A dictionnary {field, value}
Primer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Primer: """Class representing a sequencing primer Parameters ---------- name Name (label) of the primer sequence An ATGC string metadata A dictionnary {field, value}""" def __init__(self, name=None, sequence=None, metadata=None): """Initialize""" <|body_0|> def find_loca...
stack_v2_sparse_classes_36k_train_006068
8,770
no_license
[ { "docstring": "Initialize", "name": "__init__", "signature": "def __init__(self, name=None, sequence=None, metadata=None)" }, { "docstring": "Return the (start, end, strand) of the primer in the sequence. The convention is that always (start < end), the strand indicates the direction of the hom...
2
stack_v2_sparse_classes_30k_train_008056
Implement the Python class `Primer` described below. Class description: Class representing a sequencing primer Parameters ---------- name Name (label) of the primer sequence An ATGC string metadata A dictionnary {field, value} Method signatures and docstrings: - def __init__(self, name=None, sequence=None, metadata=N...
Implement the Python class `Primer` described below. Class description: Class representing a sequencing primer Parameters ---------- name Name (label) of the primer sequence An ATGC string metadata A dictionnary {field, value} Method signatures and docstrings: - def __init__(self, name=None, sequence=None, metadata=N...
cf957678ae4be24d6eddaae82754767ab06b905e
<|skeleton|> class Primer: """Class representing a sequencing primer Parameters ---------- name Name (label) of the primer sequence An ATGC string metadata A dictionnary {field, value}""" def __init__(self, name=None, sequence=None, metadata=None): """Initialize""" <|body_0|> def find_loca...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Primer: """Class representing a sequencing primer Parameters ---------- name Name (label) of the primer sequence An ATGC string metadata A dictionnary {field, value}""" def __init__(self, name=None, sequence=None, metadata=None): """Initialize""" self.name = name self.sequence = s...
the_stack_v2_python_sparse
biomek/function/annealing.py
frba/biomek
train
1
9b9f18f543b5a9b3dc35b7683c7ff351bbc727f5
[ "super(GripperPositionDetector, self).__init__(robot_name=robot_name, tf_buffer=tf_buffer)\nself._topic = joint_topic\nself.timeout = rospy.Duration(2)\nself.wrench_sub = self.create_subscriber(self._topic, JointState, self._joint_callback, queue_size=1)\nself.current_position = None\nself.store_position = False\ns...
<|body_start_0|> super(GripperPositionDetector, self).__init__(robot_name=robot_name, tf_buffer=tf_buffer) self._topic = joint_topic self.timeout = rospy.Duration(2) self.wrench_sub = self.create_subscriber(self._topic, JointState, self._joint_callback, queue_size=1) self.current...
GripperPositionDetector
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GripperPositionDetector: def __init__(self, robot_name: str, tf_buffer: str, joint_topic: str) -> None: """Class for getting the position of the hand motor joint (how much the gripper is open or closed) Values go from 1 (open) to -1 (closed) :param robot_name: Name of the robot :param tf...
stack_v2_sparse_classes_36k_train_006069
2,238
no_license
[ { "docstring": "Class for getting the position of the hand motor joint (how much the gripper is open or closed) Values go from 1 (open) to -1 (closed) :param robot_name: Name of the robot :param tf_buffer: tf2_ros.Buffer for use in RobotPart :param joint_topic: Topic to use for measurement", "name": "__init...
3
null
Implement the Python class `GripperPositionDetector` described below. Class description: Implement the GripperPositionDetector class. Method signatures and docstrings: - def __init__(self, robot_name: str, tf_buffer: str, joint_topic: str) -> None: Class for getting the position of the hand motor joint (how much the ...
Implement the Python class `GripperPositionDetector` described below. Class description: Implement the GripperPositionDetector class. Method signatures and docstrings: - def __init__(self, robot_name: str, tf_buffer: str, joint_topic: str) -> None: Class for getting the position of the hand motor joint (how much the ...
092a354315b9b2c08e32cdc049791d82dfd47745
<|skeleton|> class GripperPositionDetector: def __init__(self, robot_name: str, tf_buffer: str, joint_topic: str) -> None: """Class for getting the position of the hand motor joint (how much the gripper is open or closed) Values go from 1 (open) to -1 (closed) :param robot_name: Name of the robot :param tf...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GripperPositionDetector: def __init__(self, robot_name: str, tf_buffer: str, joint_topic: str) -> None: """Class for getting the position of the hand motor joint (how much the gripper is open or closed) Values go from 1 (open) to -1 (closed) :param robot_name: Name of the robot :param tf_buffer: tf2_r...
the_stack_v2_python_sparse
robot_skills/src/robot_skills/arm/gripper_position_detector.py
tue-robotics/tue_robocup
train
39
bc04c695a5d736ea33cb4d4dd5ab497c4f46238f
[ "if [v for v in pattern if v > 10]:\n raise Exception('Maximum 10 views per ddoc allowed')\nif len(pattern) > 10:\n raise Exception('Maximum 10 design documents allowed')\nddocs = dict()\nfor number_of_views in pattern:\n ddoc_name = next(self.ddocs)\n ddocs[ddoc_name] = {'views': {}}\n for index_of_...
<|body_start_0|> if [v for v in pattern if v > 10]: raise Exception('Maximum 10 views per ddoc allowed') if len(pattern) > 10: raise Exception('Maximum 10 design documents allowed') ddocs = dict() for number_of_views in pattern: ddoc_name = next(self.d...
ViewGen
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ViewGen: def generate_ddocs(self, pattern=None, options=None): """Generate dictionary with design documents and views. Pattern looks like: [8, 8, 8] -- 8 ddocs (8 views, 8 views, 8 views) [2, 2, 4] -- 3 ddocs (2 views, 2 views, 4 views) [8] -- 1 ddoc (8 views) [1, 1, 1, 1] -- 4 ddocs (1 ...
stack_v2_sparse_classes_36k_train_006070
6,494
permissive
[ { "docstring": "Generate dictionary with design documents and views. Pattern looks like: [8, 8, 8] -- 8 ddocs (8 views, 8 views, 8 views) [2, 2, 4] -- 3 ddocs (2 views, 2 views, 4 views) [8] -- 1 ddoc (8 views) [1, 1, 1, 1] -- 4 ddocs (1 view per ddoc)", "name": "generate_ddocs", "signature": "def gener...
3
stack_v2_sparse_classes_30k_train_016589
Implement the Python class `ViewGen` described below. Class description: Implement the ViewGen class. Method signatures and docstrings: - def generate_ddocs(self, pattern=None, options=None): Generate dictionary with design documents and views. Pattern looks like: [8, 8, 8] -- 8 ddocs (8 views, 8 views, 8 views) [2, ...
Implement the Python class `ViewGen` described below. Class description: Implement the ViewGen class. Method signatures and docstrings: - def generate_ddocs(self, pattern=None, options=None): Generate dictionary with design documents and views. Pattern looks like: [8, 8, 8] -- 8 ddocs (8 views, 8 views, 8 views) [2, ...
9d8220a0925327bddf0e10887e22b57c5d6adb37
<|skeleton|> class ViewGen: def generate_ddocs(self, pattern=None, options=None): """Generate dictionary with design documents and views. Pattern looks like: [8, 8, 8] -- 8 ddocs (8 views, 8 views, 8 views) [2, 2, 4] -- 3 ddocs (2 views, 2 views, 4 views) [8] -- 1 ddoc (8 views) [1, 1, 1, 1] -- 4 ddocs (1 ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ViewGen: def generate_ddocs(self, pattern=None, options=None): """Generate dictionary with design documents and views. Pattern looks like: [8, 8, 8] -- 8 ddocs (8 views, 8 views, 8 views) [2, 2, 4] -- 3 ddocs (2 views, 2 views, 4 views) [8] -- 1 ddoc (8 views) [1, 1, 1, 1] -- 4 ddocs (1 view per ddoc)...
the_stack_v2_python_sparse
pytests/performance/viewgen.py
couchbase/testrunner
train
18
790d03b54f8aeffadcf587f0f79de7a2b2e9b81e
[ "parser.display_info.AddFormat(vmware_constants.VMWARE_CLUSTERS_FORMAT)\nflags.AddClusterResourceArg(parser, 'to update', True)\nbase.ASYNC_FLAG.AddToParser(parser)\nflags.AddValidationOnly(parser)\nflags.AddAllowMissingUpdateCluster(parser)\nflags.AddDescription(parser)\nflags.AddVersion(parser)\nflags.AddVmwareCo...
<|body_start_0|> parser.display_info.AddFormat(vmware_constants.VMWARE_CLUSTERS_FORMAT) flags.AddClusterResourceArg(parser, 'to update', True) base.ASYNC_FLAG.AddToParser(parser) flags.AddValidationOnly(parser) flags.AddAllowMissingUpdateCluster(parser) flags.AddDescripti...
Update an Anthos cluster on VMware.
UpdateBeta
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UpdateBeta: """Update an Anthos cluster on VMware.""" def Args(parser: parser_arguments.ArgumentInterceptor): """Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to.""" <|body_0|> def Run(self, args): """Run...
stack_v2_sparse_classes_36k_train_006071
6,033
permissive
[ { "docstring": "Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to.", "name": "Args", "signature": "def Args(parser: parser_arguments.ArgumentInterceptor)" }, { "docstring": "Runs the update command. Args: args: The arguments received from...
2
null
Implement the Python class `UpdateBeta` described below. Class description: Update an Anthos cluster on VMware. Method signatures and docstrings: - def Args(parser: parser_arguments.ArgumentInterceptor): Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to. - def...
Implement the Python class `UpdateBeta` described below. Class description: Update an Anthos cluster on VMware. Method signatures and docstrings: - def Args(parser: parser_arguments.ArgumentInterceptor): Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to. - def...
392abf004b16203030e6efd2f0af24db7c8d669e
<|skeleton|> class UpdateBeta: """Update an Anthos cluster on VMware.""" def Args(parser: parser_arguments.ArgumentInterceptor): """Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to.""" <|body_0|> def Run(self, args): """Run...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UpdateBeta: """Update an Anthos cluster on VMware.""" def Args(parser: parser_arguments.ArgumentInterceptor): """Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to.""" parser.display_info.AddFormat(vmware_constants.VMWARE_CLUSTERS_F...
the_stack_v2_python_sparse
lib/surface/container/vmware/clusters/update.py
google-cloud-sdk-unofficial/google-cloud-sdk
train
9
453df5d56509724e346bede1f95801d911a90861
[ "if not root:\n return\nl = self.invertTree(root.left)\nr = self.invertTree(root.right)\nroot.left = r\nroot.right = l\nreturn root", "if root:\n self.invertTree(root.left)\n self.invertTree(root.right)\n root.left, root.right = (root.right, root.left)\nreturn root" ]
<|body_start_0|> if not root: return l = self.invertTree(root.left) r = self.invertTree(root.right) root.left = r root.right = l return root <|end_body_0|> <|body_start_1|> if root: self.invertTree(root.left) self.invertTree(ro...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: """Nov 05, 2021 13:16""" <|body_0|> def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: """Mar 20, 2023 23:41""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_006072
1,710
no_license
[ { "docstring": "Nov 05, 2021 13:16", "name": "invertTree", "signature": "def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]" }, { "docstring": "Mar 20, 2023 23:41", "name": "invertTree", "signature": "def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]"...
2
stack_v2_sparse_classes_30k_train_005082
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: Nov 05, 2021 13:16 - def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: Mar 20, 2023 23:4...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: Nov 05, 2021 13:16 - def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: Mar 20, 2023 23:4...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: """Nov 05, 2021 13:16""" <|body_0|> def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: """Mar 20, 2023 23:41""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: """Nov 05, 2021 13:16""" if not root: return l = self.invertTree(root.left) r = self.invertTree(root.right) root.left = r root.right = l return root def inve...
the_stack_v2_python_sparse
leetcode/solved/226_Invert_Binary_Tree/solution.py
sungminoh/algorithms
train
0
af654de217ccde843a7cbc4b733baef5a304df93
[ "auth = tw.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\nauth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)\napi = tw.API(auth)\nself.extractor = api\nreturn", "tweets = self.extractor.user_timeline(screen_name=user, count=200, tweet_mode='extended')\nprint('Number of tweets extracted: {}.\\n'.format(len(tweets)))...
<|body_start_0|> auth = tw.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET) api = tw.API(auth) self.extractor = api return <|end_body_0|> <|body_start_1|> tweets = self.extractor.user_timeline(screen_name=user, count=200, twe...
TweetsExtractor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TweetsExtractor: def __init__(self): """Constructor function to setup the Twitter's API with our access keys provided.""" <|body_0|> def extract(self, user): """Function to extract latest 200 tweets from a user provided.""" <|body_1|> <|end_skeleton|> <|bod...
stack_v2_sparse_classes_36k_train_006073
2,119
no_license
[ { "docstring": "Constructor function to setup the Twitter's API with our access keys provided.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Function to extract latest 200 tweets from a user provided.", "name": "extract", "signature": "def extract(self, user)...
2
null
Implement the Python class `TweetsExtractor` described below. Class description: Implement the TweetsExtractor class. Method signatures and docstrings: - def __init__(self): Constructor function to setup the Twitter's API with our access keys provided. - def extract(self, user): Function to extract latest 200 tweets ...
Implement the Python class `TweetsExtractor` described below. Class description: Implement the TweetsExtractor class. Method signatures and docstrings: - def __init__(self): Constructor function to setup the Twitter's API with our access keys provided. - def extract(self, user): Function to extract latest 200 tweets ...
02b77652d0901e6e06cb9b1e7cb3e59c675445c2
<|skeleton|> class TweetsExtractor: def __init__(self): """Constructor function to setup the Twitter's API with our access keys provided.""" <|body_0|> def extract(self, user): """Function to extract latest 200 tweets from a user provided.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TweetsExtractor: def __init__(self): """Constructor function to setup the Twitter's API with our access keys provided.""" auth = tw.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET) api = tw.API(auth) self.extractor = api ...
the_stack_v2_python_sparse
47/RodolfoFerro/scripts/extractor.py
pybites/challenges
train
764
92ded508134e88b411bac6c1ce170937a24aa1ec
[ "self.kernel_type = kernel_type\nself.dim = dim\nself.lamb = lamb\nself.gamma = gamma\nif clf == 'knn':\n self.clf = KNeighborsClassifier(n_neighbors=1)\nelif clf == 'svm':\n self.clf = svm.SVC(C=1, gamma='auto', kernel='rbf', decision_function_shape='ovr')\nprint('kernel_type:[{}], dimension:[{}], classifier...
<|body_start_0|> self.kernel_type = kernel_type self.dim = dim self.lamb = lamb self.gamma = gamma if clf == 'knn': self.clf = KNeighborsClassifier(n_neighbors=1) elif clf == 'svm': self.clf = svm.SVC(C=1, gamma='auto', kernel='rbf', decision_funct...
TCA
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TCA: def __init__(self, kernel_type='primal', dim=30, lamb=1, gamma=1, clf='knn'): """Init func :param kernel_type: kernel, values: 'primal' | 'linear' | 'rbf' :param dim: dimension after transfer :param lamb: lambda value in equation :param gamma: kernel bandwidth for rbf kernel""" ...
stack_v2_sparse_classes_36k_train_006074
10,474
no_license
[ { "docstring": "Init func :param kernel_type: kernel, values: 'primal' | 'linear' | 'rbf' :param dim: dimension after transfer :param lamb: lambda value in equation :param gamma: kernel bandwidth for rbf kernel", "name": "__init__", "signature": "def __init__(self, kernel_type='primal', dim=30, lamb=1, ...
3
stack_v2_sparse_classes_30k_train_013992
Implement the Python class `TCA` described below. Class description: Implement the TCA class. Method signatures and docstrings: - def __init__(self, kernel_type='primal', dim=30, lamb=1, gamma=1, clf='knn'): Init func :param kernel_type: kernel, values: 'primal' | 'linear' | 'rbf' :param dim: dimension after transfer...
Implement the Python class `TCA` described below. Class description: Implement the TCA class. Method signatures and docstrings: - def __init__(self, kernel_type='primal', dim=30, lamb=1, gamma=1, clf='knn'): Init func :param kernel_type: kernel, values: 'primal' | 'linear' | 'rbf' :param dim: dimension after transfer...
ea0ff8204cd6649892704c90909eb08e8102fc11
<|skeleton|> class TCA: def __init__(self, kernel_type='primal', dim=30, lamb=1, gamma=1, clf='knn'): """Init func :param kernel_type: kernel, values: 'primal' | 'linear' | 'rbf' :param dim: dimension after transfer :param lamb: lambda value in equation :param gamma: kernel bandwidth for rbf kernel""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TCA: def __init__(self, kernel_type='primal', dim=30, lamb=1, gamma=1, clf='knn'): """Init func :param kernel_type: kernel, values: 'primal' | 'linear' | 'rbf' :param dim: dimension after transfer :param lamb: lambda value in equation :param gamma: kernel bandwidth for rbf kernel""" self.kerne...
the_stack_v2_python_sparse
Comparison_model/venv/Include/TCA.py
yephm/DASMN
train
0
d1f6321444eebb293c4c5b7e242eeb6170c23217
[ "time = timezone.now() + datetime.timedelta(days=30)\nfuture_question = Question(pub_date=time)\nself.assertIs(future_question.was_published_recently(), False)", "time = timezone.now() - datetime.timedelta(days=2)\npast_question = Question(pub_date=time)\nself.assertIs(past_question.was_published_recently(), Fals...
<|body_start_0|> time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) <|end_body_0|> <|body_start_1|> time = timezone.now() - datetime.timedelta(days=2) past_question = Questi...
QuestionMethodTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QuestionMethodTests: def test_was_published_recently_with_future_question(self): """was_published_recently() should return False for questions whose pub_date is in the future.""" <|body_0|> def test_was_published_recently_with_old_question(self): """was_published_rec...
stack_v2_sparse_classes_36k_train_006075
7,438
no_license
[ { "docstring": "was_published_recently() should return False for questions whose pub_date is in the future.", "name": "test_was_published_recently_with_future_question", "signature": "def test_was_published_recently_with_future_question(self)" }, { "docstring": "was_published_recently() should r...
3
stack_v2_sparse_classes_30k_train_008153
Implement the Python class `QuestionMethodTests` described below. Class description: Implement the QuestionMethodTests class. Method signatures and docstrings: - def test_was_published_recently_with_future_question(self): was_published_recently() should return False for questions whose pub_date is in the future. - de...
Implement the Python class `QuestionMethodTests` described below. Class description: Implement the QuestionMethodTests class. Method signatures and docstrings: - def test_was_published_recently_with_future_question(self): was_published_recently() should return False for questions whose pub_date is in the future. - de...
a7e7fc72abe357172f5aa49b03c5b9298d92d6e8
<|skeleton|> class QuestionMethodTests: def test_was_published_recently_with_future_question(self): """was_published_recently() should return False for questions whose pub_date is in the future.""" <|body_0|> def test_was_published_recently_with_old_question(self): """was_published_rec...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QuestionMethodTests: def test_was_published_recently_with_future_question(self): """was_published_recently() should return False for questions whose pub_date is in the future.""" time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self....
the_stack_v2_python_sparse
firstdjango/polls/tests.py
thewritingstew/lpthw
train
0
b6778c6aa65d4e23a684bd278a51c00b4fe8e3c4
[ "post_body = json.dumps({'OS-KSADM:service': kwargs})\nresp, body = self.post('/OS-KSADM/services', post_body)\nself.expected_success(200, resp.status)\nbody = json.loads(body)\nreturn rest_client.ResponseBody(resp, body)", "url = '/OS-KSADM/services/%s' % service_id\nresp, body = self.get(url)\nself.expected_suc...
<|body_start_0|> post_body = json.dumps({'OS-KSADM:service': kwargs}) resp, body = self.post('/OS-KSADM/services', post_body) self.expected_success(200, resp.status) body = json.loads(body) return rest_client.ResponseBody(resp, body) <|end_body_0|> <|body_start_1|> url =...
ServicesClient
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServicesClient: def create_service(self, **kwargs): """Create a service. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v2-ext/#create-service-admin-extension""" <|body_0|> def show_service(sel...
stack_v2_sparse_classes_36k_train_006076
2,419
permissive
[ { "docstring": "Create a service. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v2-ext/#create-service-admin-extension", "name": "create_service", "signature": "def create_service(self, **kwargs)" }, { "docstring"...
4
null
Implement the Python class `ServicesClient` described below. Class description: Implement the ServicesClient class. Method signatures and docstrings: - def create_service(self, **kwargs): Create a service. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/...
Implement the Python class `ServicesClient` described below. Class description: Implement the ServicesClient class. Method signatures and docstrings: - def create_service(self, **kwargs): Create a service. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/...
3932a799e620a20d7abf7b89e21b520683a1809b
<|skeleton|> class ServicesClient: def create_service(self, **kwargs): """Create a service. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v2-ext/#create-service-admin-extension""" <|body_0|> def show_service(sel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ServicesClient: def create_service(self, **kwargs): """Create a service. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v2-ext/#create-service-admin-extension""" post_body = json.dumps({'OS-KSADM:service': kwargs...
the_stack_v2_python_sparse
tempest/lib/services/identity/v2/services_client.py
openstack/tempest
train
270
a653bb09a47780f0cb6911ed039f330ccc90b336
[ "self.link = L\nif L is None:\n self.head = None\n self.tail = None\n return\nif not len(L[:1]):\n self.head = None\n self.tail = None\n return\nnode = Node(L[0])\nself.head = node\nfor e in L[1:]:\n node.next_node = Node(e)\n node.next_node.previous_node = node\n node = node.next_node\ns...
<|body_start_0|> self.link = L if L is None: self.head = None self.tail = None return if not len(L[:1]): self.head = None self.tail = None return node = Node(L[0]) self.head = node for e in L[1:]: ...
DoublyLinkedList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DoublyLinkedList: def __init__(self, L=None): """Creates an empty list or a list built from a subscriptable object. >>> DoublyLinkedList().print_from_head_to_tail() >>> DoublyLinkedList().print_from_tail_to_head() >>> DoublyLinkedList([]).print_from_head_to_tail() >>> DoublyLinkedList([]...
stack_v2_sparse_classes_36k_train_006077
4,348
no_license
[ { "docstring": "Creates an empty list or a list built from a subscriptable object. >>> DoublyLinkedList().print_from_head_to_tail() >>> DoublyLinkedList().print_from_tail_to_head() >>> DoublyLinkedList([]).print_from_head_to_tail() >>> DoublyLinkedList([]).print_from_tail_to_head() >>> DoublyLinkedList((0,)).pr...
4
stack_v2_sparse_classes_30k_train_015199
Implement the Python class `DoublyLinkedList` described below. Class description: Implement the DoublyLinkedList class. Method signatures and docstrings: - def __init__(self, L=None): Creates an empty list or a list built from a subscriptable object. >>> DoublyLinkedList().print_from_head_to_tail() >>> DoublyLinkedLi...
Implement the Python class `DoublyLinkedList` described below. Class description: Implement the DoublyLinkedList class. Method signatures and docstrings: - def __init__(self, L=None): Creates an empty list or a list built from a subscriptable object. >>> DoublyLinkedList().print_from_head_to_tail() >>> DoublyLinkedLi...
4d0d4a2d719745528bf84ed0dfb88a43f858be7e
<|skeleton|> class DoublyLinkedList: def __init__(self, L=None): """Creates an empty list or a list built from a subscriptable object. >>> DoublyLinkedList().print_from_head_to_tail() >>> DoublyLinkedList().print_from_tail_to_head() >>> DoublyLinkedList([]).print_from_head_to_tail() >>> DoublyLinkedList([]...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DoublyLinkedList: def __init__(self, L=None): """Creates an empty list or a list built from a subscriptable object. >>> DoublyLinkedList().print_from_head_to_tail() >>> DoublyLinkedList().print_from_tail_to_head() >>> DoublyLinkedList([]).print_from_head_to_tail() >>> DoublyLinkedList([]).print_from_t...
the_stack_v2_python_sparse
Sample_Exam_Questions_2/sample_5.py
gakkistyle/comp9021
train
14
6d2de5513d705d907b408c7d549fff9ea2b0635a
[ "if not isinstance(actions, dict):\n raise ValueError('actions.yaml is not a valid actions configuration')\nfor action in actions:\n if keyword.iskeyword(action):\n raise ValueError(f\"'{action}' is a reserved keyword and cannot be used as an action name\")\n if cls._action_name_regex.match(action) ...
<|body_start_0|> if not isinstance(actions, dict): raise ValueError('actions.yaml is not a valid actions configuration') for action in actions: if keyword.iskeyword(action): raise ValueError(f"'{action}' is a reserved keyword and cannot be used as an action name")...
Juju actions for charms. See also: https://juju.is/docs/sdk/actions
JujuActions
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JujuActions: """Juju actions for charms. See also: https://juju.is/docs/sdk/actions""" def validate_actions(cls, actions, values): """Verify actions names and descriptions.""" <|body_0|> def validate_each_action(cls, action, values): """Verify actions names and d...
stack_v2_sparse_classes_36k_train_006078
2,092
permissive
[ { "docstring": "Verify actions names and descriptions.", "name": "validate_actions", "signature": "def validate_actions(cls, actions, values)" }, { "docstring": "Verify actions names and descriptions.", "name": "validate_each_action", "signature": "def validate_each_action(cls, action, v...
2
stack_v2_sparse_classes_30k_train_014880
Implement the Python class `JujuActions` described below. Class description: Juju actions for charms. See also: https://juju.is/docs/sdk/actions Method signatures and docstrings: - def validate_actions(cls, actions, values): Verify actions names and descriptions. - def validate_each_action(cls, action, values): Verif...
Implement the Python class `JujuActions` described below. Class description: Juju actions for charms. See also: https://juju.is/docs/sdk/actions Method signatures and docstrings: - def validate_actions(cls, actions, values): Verify actions names and descriptions. - def validate_each_action(cls, action, values): Verif...
6f49f8334888947955d133cde6dc0fea10edb74c
<|skeleton|> class JujuActions: """Juju actions for charms. See also: https://juju.is/docs/sdk/actions""" def validate_actions(cls, actions, values): """Verify actions names and descriptions.""" <|body_0|> def validate_each_action(cls, action, values): """Verify actions names and d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JujuActions: """Juju actions for charms. See also: https://juju.is/docs/sdk/actions""" def validate_actions(cls, actions, values): """Verify actions names and descriptions.""" if not isinstance(actions, dict): raise ValueError('actions.yaml is not a valid actions configuration...
the_stack_v2_python_sparse
charmcraft/models/actions.py
canonical/charmcraft
train
56
0126f64812040aae7c9392b31cee9eae8dc1bc8e
[ "self.azdeg = azdeg\nself.altdeg = altdeg\nself.hsv_min_val = hsv_min_val\nself.hsv_max_val = hsv_max_val\nself.hsv_min_sat = hsv_min_sat\nself.hsv_max_sat = hsv_max_sat", "if minval == None:\n minval = data.min()\nnormdata = (data - minval) / (data.max() - minval)\nrgb0 = cmap(normdata)\nrgb1 = self.shade_rgb...
<|body_start_0|> self.azdeg = azdeg self.altdeg = altdeg self.hsv_min_val = hsv_min_val self.hsv_max_val = hsv_max_val self.hsv_min_sat = hsv_min_sat self.hsv_max_sat = hsv_max_sat <|end_body_0|> <|body_start_1|> if minval == None: minval = data.min()...
Create a light source coming from the specified azimuth and elevation. Angles are in degrees, with the azimuth measured clockwise from north and elevation up from the zero plane of the surface. The :meth:`shade` is used to produce rgb values for a shaded relief image given a data array. Original in matplotlib.colors, m...
LightSource
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LightSource: """Create a light source coming from the specified azimuth and elevation. Angles are in degrees, with the azimuth measured clockwise from north and elevation up from the zero plane of the surface. The :meth:`shade` is used to produce rgb values for a shaded relief image given a data ...
stack_v2_sparse_classes_36k_train_006079
5,066
no_license
[ { "docstring": "Specify the azimuth (measured clockwise from south) and altitude (measured up from the plane of the surface) of the light source in degrees. The color of the resulting image will be darkened by moving the (s,v) values (in hsv colorspace) toward (hsv_min_sat, hsv_min_val) in the shaded regions, o...
3
stack_v2_sparse_classes_30k_train_006728
Implement the Python class `LightSource` described below. Class description: Create a light source coming from the specified azimuth and elevation. Angles are in degrees, with the azimuth measured clockwise from north and elevation up from the zero plane of the surface. The :meth:`shade` is used to produce rgb values ...
Implement the Python class `LightSource` described below. Class description: Create a light source coming from the specified azimuth and elevation. Angles are in degrees, with the azimuth measured clockwise from north and elevation up from the zero plane of the surface. The :meth:`shade` is used to produce rgb values ...
6e39008842de8a0fb4a9879b53b8a67339b37aff
<|skeleton|> class LightSource: """Create a light source coming from the specified azimuth and elevation. Angles are in degrees, with the azimuth measured clockwise from north and elevation up from the zero plane of the surface. The :meth:`shade` is used to produce rgb values for a shaded relief image given a data ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LightSource: """Create a light source coming from the specified azimuth and elevation. Angles are in degrees, with the azimuth measured clockwise from north and elevation up from the zero plane of the surface. The :meth:`shade` is used to produce rgb values for a shaded relief image given a data array. Origin...
the_stack_v2_python_sparse
python/lib/myLightSource.py
gutmann/scripted_sufferin_succotash
train
2
306bb63a9a9736adeca689c32d7a154dbca7bea1
[ "min_price = prices[0]\nmax_profit = 0\nprofits = []\nfor price in prices:\n min_price = min(price, min_price)\n max_profit = max(max_profit, price - min_price)\n profits.append(max_profit)\ncurr_max_price = 0\nmax_profit = 0\nfor i in range(len(prices) - 1, 0, -1):\n curr_max_price = max(curr_max_price...
<|body_start_0|> min_price = prices[0] max_profit = 0 profits = [] for price in prices: min_price = min(price, min_price) max_profit = max(max_profit, price - min_price) profits.append(max_profit) curr_max_price = 0 max_profit = 0 ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit(self, prices: List[int]) -> int: """https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/39743/Python-DP-solution-120ms Runtime: 1383 ms, faster than 44.21% Memory Usage: 27.8 MB, less than 87.46% 1 <= prices.length <= 10**5 0 <= prices[i] <= ...
stack_v2_sparse_classes_36k_train_006080
2,529
permissive
[ { "docstring": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/39743/Python-DP-solution-120ms Runtime: 1383 ms, faster than 44.21% Memory Usage: 27.8 MB, less than 87.46% 1 <= prices.length <= 10**5 0 <= prices[i] <= 10**5 :param prices: :return:", "name": "maxProfit", "signat...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices: List[int]) -> int: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/39743/Python-DP-solution-120ms Runtime: 1383 ms, faster t...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices: List[int]) -> int: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/39743/Python-DP-solution-120ms Runtime: 1383 ms, faster t...
4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5
<|skeleton|> class Solution: def maxProfit(self, prices: List[int]) -> int: """https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/39743/Python-DP-solution-120ms Runtime: 1383 ms, faster than 44.21% Memory Usage: 27.8 MB, less than 87.46% 1 <= prices.length <= 10**5 0 <= prices[i] <= ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit(self, prices: List[int]) -> int: """https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/39743/Python-DP-solution-120ms Runtime: 1383 ms, faster than 44.21% Memory Usage: 27.8 MB, less than 87.46% 1 <= prices.length <= 10**5 0 <= prices[i] <= 10**5 :param p...
the_stack_v2_python_sparse
src/123-BestTimetoBuyandSellStockIII.py
Jiezhi/myleetcode
train
1
11a50ac987686c78d1b2bfb67de1ea896bb36e8a
[ "if not root:\n return None\nparent, left, right = (root, root.left, root.right)\nif left:\n ret = self.upsideDownBinaryTree(left)\n left.left = right\n left.right = parent\n return ret\nreturn root", "if not root:\n return None\nstack = []\nnode, left, right = (root, None, None)\nwhile node.lef...
<|body_start_0|> if not root: return None parent, left, right = (root, root.left, root.right) if left: ret = self.upsideDownBinaryTree(left) left.left = right left.right = parent return ret return root <|end_body_0|> <|body_sta...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def upsideDownBinaryTree(self, root): """解法一:将左子树递归颠倒,然后原来的左孩子的左右孩子指针分别指向原来的右兄弟和原来的根节点 这个题目可以这样做的关键是树的任何一个右孩子都没有枝节,基本就是一个梳子的形状,所以不用递归右子树""" <|body_0|> def upsideDownBinaryTree1(self, root): """解法二:迭代方法,借助stack做中序遍历""" <|body_1|> <|end_skeleton|> <...
stack_v2_sparse_classes_36k_train_006081
1,660
no_license
[ { "docstring": "解法一:将左子树递归颠倒,然后原来的左孩子的左右孩子指针分别指向原来的右兄弟和原来的根节点 这个题目可以这样做的关键是树的任何一个右孩子都没有枝节,基本就是一个梳子的形状,所以不用递归右子树", "name": "upsideDownBinaryTree", "signature": "def upsideDownBinaryTree(self, root)" }, { "docstring": "解法二:迭代方法,借助stack做中序遍历", "name": "upsideDownBinaryTree1", "signature": "...
2
stack_v2_sparse_classes_30k_train_013091
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def upsideDownBinaryTree(self, root): 解法一:将左子树递归颠倒,然后原来的左孩子的左右孩子指针分别指向原来的右兄弟和原来的根节点 这个题目可以这样做的关键是树的任何一个右孩子都没有枝节,基本就是一个梳子的形状,所以不用递归右子树 - def upsideDownBinaryTree1(self, root): 解法二...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def upsideDownBinaryTree(self, root): 解法一:将左子树递归颠倒,然后原来的左孩子的左右孩子指针分别指向原来的右兄弟和原来的根节点 这个题目可以这样做的关键是树的任何一个右孩子都没有枝节,基本就是一个梳子的形状,所以不用递归右子树 - def upsideDownBinaryTree1(self, root): 解法二...
54191d08bc42e5b1d403246a7486fca69d9ae30b
<|skeleton|> class Solution: def upsideDownBinaryTree(self, root): """解法一:将左子树递归颠倒,然后原来的左孩子的左右孩子指针分别指向原来的右兄弟和原来的根节点 这个题目可以这样做的关键是树的任何一个右孩子都没有枝节,基本就是一个梳子的形状,所以不用递归右子树""" <|body_0|> def upsideDownBinaryTree1(self, root): """解法二:迭代方法,借助stack做中序遍历""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def upsideDownBinaryTree(self, root): """解法一:将左子树递归颠倒,然后原来的左孩子的左右孩子指针分别指向原来的右兄弟和原来的根节点 这个题目可以这样做的关键是树的任何一个右孩子都没有枝节,基本就是一个梳子的形状,所以不用递归右子树""" if not root: return None parent, left, right = (root, root.left, root.right) if left: ret = self.upsideD...
the_stack_v2_python_sparse
algo/156_Binary_Tree_Upside_Down/Q156.py
dionwang88/lc1
train
0
4b4e7277606bf97672736ffe0a2e2cdb68e1f5fc
[ "self.strike = kwargs['strike']\nself.rate = kwargs['rate']\nself.dividend = kwargs['dividend']\nself.maturity = kwargs['maturity']\nself.volatility = kwargs['volatility']\nself.cp = kwargs['cp']\nself.date_type = kwargs['date_type']\nself.nominal_num = kwargs['nominal_num']\nself.factor_name = '{}:strike_{}'.forma...
<|body_start_0|> self.strike = kwargs['strike'] self.rate = kwargs['rate'] self.dividend = kwargs['dividend'] self.maturity = kwargs['maturity'] self.volatility = kwargs['volatility'] self.cp = kwargs['cp'] self.date_type = kwargs['date_type'] self.nominal...
示例正向对冲买入择时类,混入BuyCallMixin,即向上突破触发买入event, 适用于看涨期权
AbuFactorBuyEuroOptionHedge
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AbuFactorBuyEuroOptionHedge: """示例正向对冲买入择时类,混入BuyCallMixin,即向上突破触发买入event, 适用于看涨期权""" def _init_self(self, **kwargs): """kwargs中必须包含: 期权各参数""" <|body_0|> def fit_day(self, today, holding_cnt): """针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动的交易日金融时间序列数据 :param h...
stack_v2_sparse_classes_36k_train_006082
3,898
no_license
[ { "docstring": "kwargs中必须包含: 期权各参数", "name": "_init_self", "signature": "def _init_self(self, **kwargs)" }, { "docstring": "针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动的交易日金融时间序列数据 :param holding_cnt: 交易发生之前的持仓量 :return:", "name": "fit_day", "signature": "def fit_day(self, today, holdi...
2
stack_v2_sparse_classes_30k_train_017830
Implement the Python class `AbuFactorBuyEuroOptionHedge` described below. Class description: 示例正向对冲买入择时类,混入BuyCallMixin,即向上突破触发买入event, 适用于看涨期权 Method signatures and docstrings: - def _init_self(self, **kwargs): kwargs中必须包含: 期权各参数 - def fit_day(self, today, holding_cnt): 针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动...
Implement the Python class `AbuFactorBuyEuroOptionHedge` described below. Class description: 示例正向对冲买入择时类,混入BuyCallMixin,即向上突破触发买入event, 适用于看涨期权 Method signatures and docstrings: - def _init_self(self, **kwargs): kwargs中必须包含: 期权各参数 - def fit_day(self, today, holding_cnt): 针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动...
6f9dabecb17b65a02a370134e178722c169b2cd2
<|skeleton|> class AbuFactorBuyEuroOptionHedge: """示例正向对冲买入择时类,混入BuyCallMixin,即向上突破触发买入event, 适用于看涨期权""" def _init_self(self, **kwargs): """kwargs中必须包含: 期权各参数""" <|body_0|> def fit_day(self, today, holding_cnt): """针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动的交易日金融时间序列数据 :param h...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AbuFactorBuyEuroOptionHedge: """示例正向对冲买入择时类,混入BuyCallMixin,即向上突破触发买入event, 适用于看涨期权""" def _init_self(self, **kwargs): """kwargs中必须包含: 期权各参数""" self.strike = kwargs['strike'] self.rate = kwargs['rate'] self.dividend = kwargs['dividend'] self.maturity = kwargs['matur...
the_stack_v2_python_sparse
abupy/FactorBuyBu/ABuFactorBuyEuroOptionHedge.py
Leo70kg/Backtesting
train
1
d834640f05fce79682538d143639c783972b6f2b
[ "if set(s) & set(''.join(wordDict)) != set(s):\n return (False, {})\ndic_head, table, max_len = ({}, [0] * len(s) + [1], max(map(len, wordDict)))\nfor word in wordDict:\n if word[0] not in dic_head:\n dic_head[word[0]] = set([word])\n else:\n dic_head[word[0]].add(word)\nfor i in range(len(s)...
<|body_start_0|> if set(s) & set(''.join(wordDict)) != set(s): return (False, {}) dic_head, table, max_len = ({}, [0] * len(s) + [1], max(map(len, wordDict))) for word in wordDict: if word[0] not in dic_head: dic_head[word[0]] = set([word]) els...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def wordBreak1(self, s, wordDict): """:type s: str :type wordDict: List[str] :rtype: bool""" <|body_0|> def wordBreak(self, s, wordDict): """:type s: str :type wordDict: List[str] :rtype: List[str]""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_006083
1,679
no_license
[ { "docstring": ":type s: str :type wordDict: List[str] :rtype: bool", "name": "wordBreak1", "signature": "def wordBreak1(self, s, wordDict)" }, { "docstring": ":type s: str :type wordDict: List[str] :rtype: List[str]", "name": "wordBreak", "signature": "def wordBreak(self, s, wordDict)" ...
2
stack_v2_sparse_classes_30k_train_020519
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def wordBreak1(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool - def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: List[str...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def wordBreak1(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool - def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: List[str...
c767e3794455c5105ca34714a3e15101f4962f4d
<|skeleton|> class Solution: def wordBreak1(self, s, wordDict): """:type s: str :type wordDict: List[str] :rtype: bool""" <|body_0|> def wordBreak(self, s, wordDict): """:type s: str :type wordDict: List[str] :rtype: List[str]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def wordBreak1(self, s, wordDict): """:type s: str :type wordDict: List[str] :rtype: bool""" if set(s) & set(''.join(wordDict)) != set(s): return (False, {}) dic_head, table, max_len = ({}, [0] * len(s) + [1], max(map(len, wordDict))) for word in wordDict:...
the_stack_v2_python_sparse
140/WordBreakII.py
basto11/leetcode
train
0
38375e40dce2429d177981b42b4f75f67b1ee96c
[ "Block.__init__(self, scenario, args)\nif self.language is None:\n raise LoadingException('Language must be defined!')", "ttree = zone.ttree\natree = zone.create_atree()\nself.copy_subtree(ttree, atree)", "for tnode in troot.get_children(ordered=1):\n lemma = tnode.t_lemma or ''\n lemma = re.sub('_s[ei...
<|body_start_0|> Block.__init__(self, scenario, args) if self.language is None: raise LoadingException('Language must be defined!') <|end_body_0|> <|body_start_1|> ttree = zone.ttree atree = zone.create_atree() self.copy_subtree(ttree, atree) <|end_body_1|> <|body_s...
This block creates an a-tree based on a t-tree in the same zone. Arguments: language: the language of the target zone selector: the selector of the target zone
CopyTTree
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CopyTTree: """This block creates an a-tree based on a t-tree in the same zone. Arguments: language: the language of the target zone selector: the selector of the target zone""" def __init__(self, scenario, args): """Constructor, checking the argument values""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_006084
2,289
permissive
[ { "docstring": "Constructor, checking the argument values", "name": "__init__", "signature": "def __init__(self, scenario, args)" }, { "docstring": "Starting tree copy", "name": "process_zone", "signature": "def process_zone(self, zone)" }, { "docstring": "Deep-copy a subtree, cr...
3
null
Implement the Python class `CopyTTree` described below. Class description: This block creates an a-tree based on a t-tree in the same zone. Arguments: language: the language of the target zone selector: the selector of the target zone Method signatures and docstrings: - def __init__(self, scenario, args): Constructor...
Implement the Python class `CopyTTree` described below. Class description: This block creates an a-tree based on a t-tree in the same zone. Arguments: language: the language of the target zone selector: the selector of the target zone Method signatures and docstrings: - def __init__(self, scenario, args): Constructor...
73af644ec35c8a1cd0c37cd478c2afc1db717e0b
<|skeleton|> class CopyTTree: """This block creates an a-tree based on a t-tree in the same zone. Arguments: language: the language of the target zone selector: the selector of the target zone""" def __init__(self, scenario, args): """Constructor, checking the argument values""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CopyTTree: """This block creates an a-tree based on a t-tree in the same zone. Arguments: language: the language of the target zone selector: the selector of the target zone""" def __init__(self, scenario, args): """Constructor, checking the argument values""" Block.__init__(self, scenari...
the_stack_v2_python_sparse
alex/components/nlg/tectotpl/block/t2a/copyttree.py
oplatek/alex
train
0
7fbfb585c88985c884158b8557b9908ca5c21ec3
[ "def dfs(cur_node):\n if not cur_node:\n return 'None,'\n to_return = str(cur_node.val) + ','\n left_sub_tree = dfs(cur_node.left)\n right_sub_tree = dfs(cur_node.right)\n return to_return + left_sub_tree + right_sub_tree\nreturn dfs(root)", "def rdeserialize(l):\n \"\"\" 이게 핵심... !\"\"\"...
<|body_start_0|> def dfs(cur_node): if not cur_node: return 'None,' to_return = str(cur_node.val) + ',' left_sub_tree = dfs(cur_node.left) right_sub_tree = dfs(cur_node.right) return to_return + left_sub_tree + right_sub_tree re...
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): """From Official answer key...""" <|body_1|> <|end_skeleton|> <|body_start_0|> def dfs(cur_node): ...
stack_v2_sparse_classes_36k_train_006085
4,141
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "From Official answer key...", "name": "deserialize", "signature": "def deserialize(self, data)" } ]
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): From Official answer key...
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): From Official answer key... <|skeleton|> class Codec: ...
a5635356953df472e71d49c8db3b493ac59b860f
<|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): """From Official answer key...""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" def dfs(cur_node): if not cur_node: return 'None,' to_return = str(cur_node.val) + ',' left_sub_tree = dfs(cur_node.left) ...
the_stack_v2_python_sparse
python/q297.py
ksparkje/leetcode-practice
train
1
72de027ad380186edcd59b98e76f4f1eb3effbe9
[ "self.action_n = env.action_space.n\nself.obs_low = env.observation_space.low\nself.obs_scale = env.observation_space.high - env.observation_space.low\nself.encoder = TileCoder(layers, features)\nself.w = np.zeros(features)\nself.feature_list = []\nself.trajectory = []\nself.gamma = gamma\nself.learning_rate = lear...
<|body_start_0|> self.action_n = env.action_space.n self.obs_low = env.observation_space.low self.obs_scale = env.observation_space.high - env.observation_space.low self.encoder = TileCoder(layers, features) self.w = np.zeros(features) self.feature_list = [] self....
回合更新策略梯度算法寻找最优策略
VPGAgent
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VPGAgent: """回合更新策略梯度算法寻找最优策略""" def __init__(self, env, layers=8, features=1893, gamma=1.0, learning_rate=0.03, epsilon=0.001, baseline=True): """学习函数 env 环境 layers 要用到几层砖瓦编码 features 砖瓦编码应该得到多少特征 总特征数 8*8 + (8+1) * (8+1) * (8-1) gamma 收益衰减速率 learning_rate 学习速率 epsilon 执行探索策略概率""" ...
stack_v2_sparse_classes_36k_train_006086
22,277
no_license
[ { "docstring": "学习函数 env 环境 layers 要用到几层砖瓦编码 features 砖瓦编码应该得到多少特征 总特征数 8*8 + (8+1) * (8+1) * (8-1) gamma 收益衰减速率 learning_rate 学习速率 epsilon 执行探索策略概率", "name": "__init__", "signature": "def __init__(self, env, layers=8, features=1893, gamma=1.0, learning_rate=0.03, epsilon=0.001, baseline=True)" }, {...
3
stack_v2_sparse_classes_30k_val_000935
Implement the Python class `VPGAgent` described below. Class description: 回合更新策略梯度算法寻找最优策略 Method signatures and docstrings: - def __init__(self, env, layers=8, features=1893, gamma=1.0, learning_rate=0.03, epsilon=0.001, baseline=True): 学习函数 env 环境 layers 要用到几层砖瓦编码 features 砖瓦编码应该得到多少特征 总特征数 8*8 + (8+1) * (8+1) * (8...
Implement the Python class `VPGAgent` described below. Class description: 回合更新策略梯度算法寻找最优策略 Method signatures and docstrings: - def __init__(self, env, layers=8, features=1893, gamma=1.0, learning_rate=0.03, epsilon=0.001, baseline=True): 学习函数 env 环境 layers 要用到几层砖瓦编码 features 砖瓦编码应该得到多少特征 总特征数 8*8 + (8+1) * (8+1) * (8...
e6526e9e38fcb5be91b46cb40715c15242198a0b
<|skeleton|> class VPGAgent: """回合更新策略梯度算法寻找最优策略""" def __init__(self, env, layers=8, features=1893, gamma=1.0, learning_rate=0.03, epsilon=0.001, baseline=True): """学习函数 env 环境 layers 要用到几层砖瓦编码 features 砖瓦编码应该得到多少特征 总特征数 8*8 + (8+1) * (8+1) * (8-1) gamma 收益衰减速率 learning_rate 学习速率 epsilon 执行探索策略概率""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VPGAgent: """回合更新策略梯度算法寻找最优策略""" def __init__(self, env, layers=8, features=1893, gamma=1.0, learning_rate=0.03, epsilon=0.001, baseline=True): """学习函数 env 环境 layers 要用到几层砖瓦编码 features 砖瓦编码应该得到多少特征 总特征数 8*8 + (8+1) * (8+1) * (8-1) gamma 收益衰减速率 learning_rate 学习速率 epsilon 执行探索策略概率""" self.a...
the_stack_v2_python_sparse
mountain_car/function_approx.py
lwzswufe/gym_learning
train
0
295aec760f5d3f0cc015b0597f71a1c1eec88a59
[ "sd = np.square(inputs - x)\nmses = np.mean(sd, axis=tuple(range(1, sd.ndim)))\nindex = np.argmin(mses)\nif mses[index] > 0:\n raise ValueError('Could not find a precomputed adversarial for this input')\nreturn outputs[index]", "assert candidate_inputs.shape == candidate_outputs.shape\nx = a.unperturbed\nadver...
<|body_start_0|> sd = np.square(inputs - x) mses = np.mean(sd, axis=tuple(range(1, sd.ndim))) index = np.argmin(mses) if mses[index] > 0: raise ValueError('Could not find a precomputed adversarial for this input') return outputs[index] <|end_body_0|> <|body_start_1|>...
Attacks a model using precomputed adversarial candidates.
PrecomputedAdversarialsAttack
[ "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PrecomputedAdversarialsAttack: """Attacks a model using precomputed adversarial candidates.""" def _get_output(self, a, x, inputs, outputs): """Looks up the precomputed adversarial for a given input.""" <|body_0|> def as_generator(self, a, candidate_inputs, candidate_out...
stack_v2_sparse_classes_36k_train_006087
1,928
permissive
[ { "docstring": "Looks up the precomputed adversarial for a given input.", "name": "_get_output", "signature": "def _get_output(self, a, x, inputs, outputs)" }, { "docstring": "Attacks a model using precomputed adversarial candidates. Parameters ---------- input_or_adv : `numpy.ndarray` or :class...
2
null
Implement the Python class `PrecomputedAdversarialsAttack` described below. Class description: Attacks a model using precomputed adversarial candidates. Method signatures and docstrings: - def _get_output(self, a, x, inputs, outputs): Looks up the precomputed adversarial for a given input. - def as_generator(self, a,...
Implement the Python class `PrecomputedAdversarialsAttack` described below. Class description: Attacks a model using precomputed adversarial candidates. Method signatures and docstrings: - def _get_output(self, a, x, inputs, outputs): Looks up the precomputed adversarial for a given input. - def as_generator(self, a,...
81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a
<|skeleton|> class PrecomputedAdversarialsAttack: """Attacks a model using precomputed adversarial candidates.""" def _get_output(self, a, x, inputs, outputs): """Looks up the precomputed adversarial for a given input.""" <|body_0|> def as_generator(self, a, candidate_inputs, candidate_out...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PrecomputedAdversarialsAttack: """Attacks a model using precomputed adversarial candidates.""" def _get_output(self, a, x, inputs, outputs): """Looks up the precomputed adversarial for a given input.""" sd = np.square(inputs - x) mses = np.mean(sd, axis=tuple(range(1, sd.ndim))) ...
the_stack_v2_python_sparse
cnns/foolbox/foolbox_2_3_0/attacks/precomputed.py
adam-dziedzic/bandlimited-cnns
train
17
6ebc981c8923efdf2ca411d525d43343bedb2764
[ "super(RNNDecoder, self).__init__()\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform')\nself.F = tf.keras.layers.Dense(vocab)", "context, _ = SelfAttention(s_prev.shape[1])(s_prev, h...
<|body_start_0|> super(RNNDecoder, self).__init__() self.embedding = tf.keras.layers.Embedding(vocab, embedding) self.gru = tf.keras.layers.GRU(units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform') self.F = tf.keras.layers.Dense(vocab) <|end_body_0|> <...
to decode for machine translation
RNNDecoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RNNDecoder: """to decode for machine translation""" def __init__(self, vocab, embedding, units, batch): """constructor @untis: int representing the number of hidden units in the allignement model * sets the following public instance attributes @embedding: keras Embedding layer that c...
stack_v2_sparse_classes_36k_train_006088
2,304
no_license
[ { "docstring": "constructor @untis: int representing the number of hidden units in the allignement model * sets the following public instance attributes @embedding: keras Embedding layer that converts words from the vocabulary into embedding vector @gru: keras GRU layer with units as units @F: Dense layer with ...
2
stack_v2_sparse_classes_30k_train_021134
Implement the Python class `RNNDecoder` described below. Class description: to decode for machine translation Method signatures and docstrings: - def __init__(self, vocab, embedding, units, batch): constructor @untis: int representing the number of hidden units in the allignement model * sets the following public ins...
Implement the Python class `RNNDecoder` described below. Class description: to decode for machine translation Method signatures and docstrings: - def __init__(self, vocab, embedding, units, batch): constructor @untis: int representing the number of hidden units in the allignement model * sets the following public ins...
e20b284d5f1841952104d7d9a0274cff80eb304d
<|skeleton|> class RNNDecoder: """to decode for machine translation""" def __init__(self, vocab, embedding, units, batch): """constructor @untis: int representing the number of hidden units in the allignement model * sets the following public instance attributes @embedding: keras Embedding layer that c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RNNDecoder: """to decode for machine translation""" def __init__(self, vocab, embedding, units, batch): """constructor @untis: int representing the number of hidden units in the allignement model * sets the following public instance attributes @embedding: keras Embedding layer that converts words...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/2-rnn_decoder.py
jgadelugo/holbertonschool-machine_learning
train
1
d28575762b6e8e8c7851bc0f116c6bf04d856577
[ "max_val = float('-inf')\nsum = 0\nfor i, num in enumerate(nums, 1):\n sum += num\n if i > k:\n sum -= nums[i - k - 1]\n if i >= k:\n max_val = max(max_val, sum)\nreturn float(max_val) / k", "sum_list = [0]\nfor num in nums:\n sum_list.append(sum_list[-1] + num)\nmax_val = max((sum_list[...
<|body_start_0|> max_val = float('-inf') sum = 0 for i, num in enumerate(nums, 1): sum += num if i > k: sum -= nums[i - k - 1] if i >= k: max_val = max(max_val, sum) return float(max_val) / k <|end_body_0|> <|body_start...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findMaxAverage(self, nums, k): """:type nums: List[int] :type k: int :rtype: float""" <|body_0|> def findMaxAverage(self, nums, k): """:type nums: List[int] :type k: int :rtype: float""" <|body_1|> <|end_skeleton|> <|body_start_0|> max...
stack_v2_sparse_classes_36k_train_006089
1,398
no_license
[ { "docstring": ":type nums: List[int] :type k: int :rtype: float", "name": "findMaxAverage", "signature": "def findMaxAverage(self, nums, k)" }, { "docstring": ":type nums: List[int] :type k: int :rtype: float", "name": "findMaxAverage", "signature": "def findMaxAverage(self, nums, k)" ...
2
stack_v2_sparse_classes_30k_train_008070
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findMaxAverage(self, nums, k): :type nums: List[int] :type k: int :rtype: float - def findMaxAverage(self, nums, k): :type nums: List[int] :type k: int :rtype: float
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findMaxAverage(self, nums, k): :type nums: List[int] :type k: int :rtype: float - def findMaxAverage(self, nums, k): :type nums: List[int] :type k: int :rtype: float <|skele...
f0fe37f489a8dc9867b774bfa22a8d73c322cb79
<|skeleton|> class Solution: def findMaxAverage(self, nums, k): """:type nums: List[int] :type k: int :rtype: float""" <|body_0|> def findMaxAverage(self, nums, k): """:type nums: List[int] :type k: int :rtype: float""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findMaxAverage(self, nums, k): """:type nums: List[int] :type k: int :rtype: float""" max_val = float('-inf') sum = 0 for i, num in enumerate(nums, 1): sum += num if i > k: sum -= nums[i - k - 1] if i >= k: ...
the_stack_v2_python_sparse
dp/643_Maximum_Average_Subarray_I.py
AsterWang/leecode
train
0
59cb629ba2c0377424c24dad821472ceb67d22e2
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn NetworkConnection()", "from .connection_direction import ConnectionDirection\nfrom .connection_status import ConnectionStatus\nfrom .security_network_protocol import SecurityNetworkProtocol\nfrom .connection_direction import Connection...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return NetworkConnection() <|end_body_0|> <|body_start_1|> from .connection_direction import ConnectionDirection from .connection_status import ConnectionStatus from .security_network_p...
NetworkConnection
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NetworkConnection: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object...
stack_v2_sparse_classes_36k_train_006090
9,109
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: NetworkConnection", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_v...
3
stack_v2_sparse_classes_30k_train_006894
Implement the Python class `NetworkConnection` described below. Class description: Implement the NetworkConnection class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection: Creates a new instance of the appropriate class based on discrim...
Implement the Python class `NetworkConnection` described below. Class description: Implement the NetworkConnection class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection: Creates a new instance of the appropriate class based on discrim...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class NetworkConnection: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NetworkConnection: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Netw...
the_stack_v2_python_sparse
msgraph/generated/models/network_connection.py
microsoftgraph/msgraph-sdk-python
train
135
a70986140e73e6933c8e6e586eb79065fbc2430d
[ "start_url = 'https://ip.jiangxianli.com/?page={}&country=%E4%B8%AD%E5%9B%BD'\npage_count = 10\nurls = [start_url.format(page) for page in range(1, page_count + 1)]\ntime.sleep(3)\nfor url in urls:\n try:\n print('Crawing', url)\n html = requests.get(url).content.decode('utf8')\n if html:\n ...
<|body_start_0|> start_url = 'https://ip.jiangxianli.com/?page={}&country=%E4%B8%AD%E5%9B%BD' page_count = 10 urls = [start_url.format(page) for page in range(1, page_count + 1)] time.sleep(3) for url in urls: try: print('Crawing', url) ...
代理爬取
Crawler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Crawler: """代理爬取""" def crawl_jiangxianli(self): """ip.jiangxianli.com网站代理爬取""" <|body_0|> def crawl_kuaidaili(self): """https://www.kuaidaili.com/free/inha/1/ 快代理网站爬取""" <|body_1|> def crawl_ip66(self): """http://www.66ip.cn/""" <|bo...
stack_v2_sparse_classes_36k_train_006091
5,528
no_license
[ { "docstring": "ip.jiangxianli.com网站代理爬取", "name": "crawl_jiangxianli", "signature": "def crawl_jiangxianli(self)" }, { "docstring": "https://www.kuaidaili.com/free/inha/1/ 快代理网站爬取", "name": "crawl_kuaidaili", "signature": "def crawl_kuaidaili(self)" }, { "docstring": "http://www...
4
null
Implement the Python class `Crawler` described below. Class description: 代理爬取 Method signatures and docstrings: - def crawl_jiangxianli(self): ip.jiangxianli.com网站代理爬取 - def crawl_kuaidaili(self): https://www.kuaidaili.com/free/inha/1/ 快代理网站爬取 - def crawl_ip66(self): http://www.66ip.cn/ - def get_proxies(self, callba...
Implement the Python class `Crawler` described below. Class description: 代理爬取 Method signatures and docstrings: - def crawl_jiangxianli(self): ip.jiangxianli.com网站代理爬取 - def crawl_kuaidaili(self): https://www.kuaidaili.com/free/inha/1/ 快代理网站爬取 - def crawl_ip66(self): http://www.66ip.cn/ - def get_proxies(self, callba...
f49a93c1cab5716d4dafecb7479a3be2a4af91ad
<|skeleton|> class Crawler: """代理爬取""" def crawl_jiangxianli(self): """ip.jiangxianli.com网站代理爬取""" <|body_0|> def crawl_kuaidaili(self): """https://www.kuaidaili.com/free/inha/1/ 快代理网站爬取""" <|body_1|> def crawl_ip66(self): """http://www.66ip.cn/""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Crawler: """代理爬取""" def crawl_jiangxianli(self): """ip.jiangxianli.com网站代理爬取""" start_url = 'https://ip.jiangxianli.com/?page={}&country=%E4%B8%AD%E5%9B%BD' page_count = 10 urls = [start_url.format(page) for page in range(1, page_count + 1)] time.sleep(3) f...
the_stack_v2_python_sparse
Sec_9/9.2/crawler.py
WiconWang/spider_project
train
0
12785624fc17e46206298c852a59b171e80949af
[ "if fmtr is None:\n pass\nself.formatter = fmtr", "tid = threading.current_thread().ident()\ntime_stamp = helper_time.get_time_millionsec()\nnew_msg = '[%s] [%s] [%d] [%s] %s' % (time_stamp, lvl.name, tid, loggername, msg)\nif exc is not None:\n new_msg = new_msg + '\\r\\nex:%s' % exc.args\nreturn new_msg" ...
<|body_start_0|> if fmtr is None: pass self.formatter = fmtr <|end_body_0|> <|body_start_1|> tid = threading.current_thread().ident() time_stamp = helper_time.get_time_millionsec() new_msg = '[%s] [%s] [%d] [%s] %s' % (time_stamp, lvl.name, tid, loggername, msg) ...
The settings for log message formatting. The 'fmtr' should be a method that returns a string
MsLogMessageConfig
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MsLogMessageConfig: """The settings for log message formatting. The 'fmtr' should be a method that returns a string""" def __init__(self, fmtr=None): """The 'fmtr' should be a method that returns a string fmtr: A method that returns string""" <|body_0|> def __default_for...
stack_v2_sparse_classes_36k_train_006092
5,666
permissive
[ { "docstring": "The 'fmtr' should be a method that returns a string fmtr: A method that returns string", "name": "__init__", "signature": "def __init__(self, fmtr=None)" }, { "docstring": "msg: The log message. exc: The Exception object(if exists) 格式符 说明 %a 星期的英文单词的缩写:如星期一, 则返回 Mon %A 星期的英文单词的全拼...
2
null
Implement the Python class `MsLogMessageConfig` described below. Class description: The settings for log message formatting. The 'fmtr' should be a method that returns a string Method signatures and docstrings: - def __init__(self, fmtr=None): The 'fmtr' should be a method that returns a string fmtr: A method that re...
Implement the Python class `MsLogMessageConfig` described below. Class description: The settings for log message formatting. The 'fmtr' should be a method that returns a string Method signatures and docstrings: - def __init__(self, fmtr=None): The 'fmtr' should be a method that returns a string fmtr: A method that re...
8f05a6b91fc205960edd57f9076facec04f49a1a
<|skeleton|> class MsLogMessageConfig: """The settings for log message formatting. The 'fmtr' should be a method that returns a string""" def __init__(self, fmtr=None): """The 'fmtr' should be a method that returns a string fmtr: A method that returns string""" <|body_0|> def __default_for...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MsLogMessageConfig: """The settings for log message formatting. The 'fmtr' should be a method that returns a string""" def __init__(self, fmtr=None): """The 'fmtr' should be a method that returns a string fmtr: A method that returns string""" if fmtr is None: pass self...
the_stack_v2_python_sparse
savecode/pythonpackages/commonbaby/mslog/mslogconfig.py
cbbbbbbbb/sspywork
train
0
45523495bc3da9db151001805a1b8bcced3de2da
[ "mn = float('inf')\n\ndef dfs(d, i, cur):\n nonlocal mn\n if d == len(triangle):\n mn = min(mn, cur)\n return\n cur += triangle[d][i]\n dfs(d + 1, i, cur)\n dfs(d + 1, i + 1, cur)\ndfs(0, 0, 0)\nreturn mn", "@lru_cache(None)\ndef dp(d, i):\n if d == 0:\n assert i == 0\n ...
<|body_start_0|> mn = float('inf') def dfs(d, i, cur): nonlocal mn if d == len(triangle): mn = min(mn, cur) return cur += triangle[d][i] dfs(d + 1, i, cur) dfs(d + 1, i + 1, cur) dfs(0, 0, 0) ret...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: """Bruteforce dfs Time complexity: O(n!) Space complexity: O(n) # callstack""" <|body_0|> def minimumTotal(self, triangle: List[List[int]]) -> int: """Recursive DP Time complexity: O(n^2) Space compl...
stack_v2_sparse_classes_36k_train_006093
3,847
no_license
[ { "docstring": "Bruteforce dfs Time complexity: O(n!) Space complexity: O(n) # callstack", "name": "minimumTotal", "signature": "def minimumTotal(self, triangle: List[List[int]]) -> int" }, { "docstring": "Recursive DP Time complexity: O(n^2) Space complexity: O(n^2)", "name": "minimumTotal"...
5
stack_v2_sparse_classes_30k_test_000955
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumTotal(self, triangle: List[List[int]]) -> int: Bruteforce dfs Time complexity: O(n!) Space complexity: O(n) # callstack - def minimumTotal(self, triangle: List[List[in...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumTotal(self, triangle: List[List[int]]) -> int: Bruteforce dfs Time complexity: O(n!) Space complexity: O(n) # callstack - def minimumTotal(self, triangle: List[List[in...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: """Bruteforce dfs Time complexity: O(n!) Space complexity: O(n) # callstack""" <|body_0|> def minimumTotal(self, triangle: List[List[int]]) -> int: """Recursive DP Time complexity: O(n^2) Space compl...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: """Bruteforce dfs Time complexity: O(n!) Space complexity: O(n) # callstack""" mn = float('inf') def dfs(d, i, cur): nonlocal mn if d == len(triangle): mn = min(mn, cur) ...
the_stack_v2_python_sparse
leetcode/solved/120_Triangle/solution.py
sungminoh/algorithms
train
0
96e610726135a19eb6f822ee8ce941396166ac3a
[ "if not isinstance(process_num, int):\n raise ValueError('AKG kernel compiling process number must be of type int, but got {} with type {}'.format(process_num, type(wait_time)))\nif not isinstance(wait_time, int):\n raise ValueError('AKG kernel compiling wait time must be of type int, but got {} with type {}'...
<|body_start_0|> if not isinstance(process_num, int): raise ValueError('AKG kernel compiling process number must be of type int, but got {} with type {}'.format(process_num, type(wait_time))) if not isinstance(wait_time, int): raise ValueError('AKG kernel compiling wait time must...
akg kernel parallel process
AkgProcess
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "MPL-1.0", "OpenSSL", "LGPL-3.0-only", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause-Open-MPI", "MIT", "MPL-2.0-no-copyleft-exception", "NTP", "BSD-3-Clause", "GPL-1.0-or-later", "0BSD", "MPL-2.0", "LicenseRef-scancode-f...
stack_v2_sparse_python_classes_v1
<|skeleton|> class AkgProcess: """akg kernel parallel process""" def __init__(self, process_num, wait_time, platform): """Args: process_num: int. processes number wait_time: int. max time the function blocked""" <|body_0|> def compile(self, attrs=None): """compile kernel by multi p...
stack_v2_sparse_classes_36k_train_006094
7,760
permissive
[ { "docstring": "Args: process_num: int. processes number wait_time: int. max time the function blocked", "name": "__init__", "signature": "def __init__(self, process_num, wait_time, platform)" }, { "docstring": "compile kernel by multi processes Return: True for all compile success, False for so...
3
stack_v2_sparse_classes_30k_train_012900
Implement the Python class `AkgProcess` described below. Class description: akg kernel parallel process Method signatures and docstrings: - def __init__(self, process_num, wait_time, platform): Args: process_num: int. processes number wait_time: int. max time the function blocked - def compile(self, attrs=None): comp...
Implement the Python class `AkgProcess` described below. Class description: akg kernel parallel process Method signatures and docstrings: - def __init__(self, process_num, wait_time, platform): Args: process_num: int. processes number wait_time: int. max time the function blocked - def compile(self, attrs=None): comp...
54acb15d435533c815ee1bd9f6dc0b56b4d4cf83
<|skeleton|> class AkgProcess: """akg kernel parallel process""" def __init__(self, process_num, wait_time, platform): """Args: process_num: int. processes number wait_time: int. max time the function blocked""" <|body_0|> def compile(self, attrs=None): """compile kernel by multi p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AkgProcess: """akg kernel parallel process""" def __init__(self, process_num, wait_time, platform): """Args: process_num: int. processes number wait_time: int. max time the function blocked""" if not isinstance(process_num, int): raise ValueError('AKG kernel compiling process ...
the_stack_v2_python_sparse
mindspore/python/mindspore/_extends/parallel_compile/akg_compiler/akg_process.py
mindspore-ai/mindspore
train
4,178
387debdfcbfb6cbd032b5f4d00345a5d893ff4aa
[ "threading.Thread.__init__(self)\nself.threadName = name\nself.people = people", "print('开始线程: ' + self.threadName)\nchiHuoGuo(self.people)\nprint('qq交流群:226296743')\nprint('结束线程: ' + self.name)" ]
<|body_start_0|> threading.Thread.__init__(self) self.threadName = name self.people = people <|end_body_0|> <|body_start_1|> print('开始线程: ' + self.threadName) chiHuoGuo(self.people) print('qq交流群:226296743') print('结束线程: ' + self.name) <|end_body_1|>
myThread
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class myThread: def __init__(self, people, name): """重写threading.Thread初始化内容""" <|body_0|> def run(self): """重写run方法""" <|body_1|> <|end_skeleton|> <|body_start_0|> threading.Thread.__init__(self) self.threadName = name self.people = peopl...
stack_v2_sparse_classes_36k_train_006095
5,122
permissive
[ { "docstring": "重写threading.Thread初始化内容", "name": "__init__", "signature": "def __init__(self, people, name)" }, { "docstring": "重写run方法", "name": "run", "signature": "def run(self)" } ]
2
stack_v2_sparse_classes_30k_train_007503
Implement the Python class `myThread` described below. Class description: Implement the myThread class. Method signatures and docstrings: - def __init__(self, people, name): 重写threading.Thread初始化内容 - def run(self): 重写run方法
Implement the Python class `myThread` described below. Class description: Implement the myThread class. Method signatures and docstrings: - def __init__(self, people, name): 重写threading.Thread初始化内容 - def run(self): 重写run方法 <|skeleton|> class myThread: def __init__(self, people, name): """重写threading.Thr...
e046cdd35bd63e9430416ea6954b1aaef4bc50d5
<|skeleton|> class myThread: def __init__(self, people, name): """重写threading.Thread初始化内容""" <|body_0|> def run(self): """重写run方法""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class myThread: def __init__(self, people, name): """重写threading.Thread初始化内容""" threading.Thread.__init__(self) self.threadName = name self.people = people def run(self): """重写run方法""" print('开始线程: ' + self.threadName) chiHuoGuo(self.people) print...
the_stack_v2_python_sparse
第一期/北京-菜鸟渣渣/Fast_Learning_python3/thread/thread_join&setDeamon.py
beidou9313/deeptest
train
0
c979fb8409696f1d1e25d2716c8f6b0404e5ad1f
[ "from .wrapper import NCNNWrapper\nif deploy_cfg:\n backend_config = get_backend_config(deploy_cfg)\n use_vulkan = backend_config.get('use_vulkan', False)\nelse:\n use_vulkan = False\nreturn NCNNWrapper(param_file=backend_files[0], bin_file=backend_files[1], output_names=output_names, use_vulkan=use_vulkan...
<|body_start_0|> from .wrapper import NCNNWrapper if deploy_cfg: backend_config = get_backend_config(deploy_cfg) use_vulkan = backend_config.get('use_vulkan', False) else: use_vulkan = False return NCNNWrapper(param_file=backend_files[0], bin_file=back...
NCNNManager
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NCNNManager: def build_wrapper(cls, backend_files: Sequence[str], device: str='cpu', input_names: Optional[Sequence[str]]=None, output_names: Optional[Sequence[str]]=None, deploy_cfg: Optional[Any]=None, **kwargs): """Build the wrapper for the backend model. Args: backend_files (Sequence...
stack_v2_sparse_classes_36k_train_006096
5,173
permissive
[ { "docstring": "Build the wrapper for the backend model. Args: backend_files (Sequence[str]): Backend files. device (str, optional): The device info. Defaults to 'cpu'. input_names (Optional[Sequence[str]], optional): input names. Defaults to None. output_names (Optional[Sequence[str]], optional): output names....
5
stack_v2_sparse_classes_30k_train_017549
Implement the Python class `NCNNManager` described below. Class description: Implement the NCNNManager class. Method signatures and docstrings: - def build_wrapper(cls, backend_files: Sequence[str], device: str='cpu', input_names: Optional[Sequence[str]]=None, output_names: Optional[Sequence[str]]=None, deploy_cfg: O...
Implement the Python class `NCNNManager` described below. Class description: Implement the NCNNManager class. Method signatures and docstrings: - def build_wrapper(cls, backend_files: Sequence[str], device: str='cpu', input_names: Optional[Sequence[str]]=None, output_names: Optional[Sequence[str]]=None, deploy_cfg: O...
5479c8774f5b88d7ed9d399d4e305cb42cc2e73a
<|skeleton|> class NCNNManager: def build_wrapper(cls, backend_files: Sequence[str], device: str='cpu', input_names: Optional[Sequence[str]]=None, output_names: Optional[Sequence[str]]=None, deploy_cfg: Optional[Any]=None, **kwargs): """Build the wrapper for the backend model. Args: backend_files (Sequence...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NCNNManager: def build_wrapper(cls, backend_files: Sequence[str], device: str='cpu', input_names: Optional[Sequence[str]]=None, output_names: Optional[Sequence[str]]=None, deploy_cfg: Optional[Any]=None, **kwargs): """Build the wrapper for the backend model. Args: backend_files (Sequence[str]): Backen...
the_stack_v2_python_sparse
mmdeploy/backend/ncnn/backend_manager.py
open-mmlab/mmdeploy
train
2,164
04b7bf40bd026bd05b05434303f1fdb39d00ddf6
[ "paddle.set_device('cpu')\npaddle.seed(2020)\npaddle.framework.random._manual_program_seed(2020)\nffn_fc1_act = 'relu'\n[batch_size, d_model, n_head, dim_feedforward, dropout, attn_dropout, act_dropout, sequence_length] = generate_basic_params(mode='encoder_layer')\nsrc = np.random.rand(batch_size, sequence_length,...
<|body_start_0|> paddle.set_device('cpu') paddle.seed(2020) paddle.framework.random._manual_program_seed(2020) ffn_fc1_act = 'relu' [batch_size, d_model, n_head, dim_feedforward, dropout, attn_dropout, act_dropout, sequence_length] = generate_basic_params(mode='encoder_layer') ...
test
Test
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test: """test""" def test_transformer_encoder_layer(self): """test_transformer_encoder_layer""" <|body_0|> def test_main(self): """test""" <|body_1|> <|end_skeleton|> <|body_start_0|> paddle.set_device('cpu') paddle.seed(2020) pa...
stack_v2_sparse_classes_36k_train_006097
2,699
no_license
[ { "docstring": "test_transformer_encoder_layer", "name": "test_transformer_encoder_layer", "signature": "def test_transformer_encoder_layer(self)" }, { "docstring": "test", "name": "test_main", "signature": "def test_main(self)" } ]
2
null
Implement the Python class `Test` described below. Class description: test Method signatures and docstrings: - def test_transformer_encoder_layer(self): test_transformer_encoder_layer - def test_main(self): test
Implement the Python class `Test` described below. Class description: test Method signatures and docstrings: - def test_transformer_encoder_layer(self): test_transformer_encoder_layer - def test_main(self): test <|skeleton|> class Test: """test""" def test_transformer_encoder_layer(self): """test_tr...
bd3790ce72a2a26611b5eda3901651b5a809348f
<|skeleton|> class Test: """test""" def test_transformer_encoder_layer(self): """test_transformer_encoder_layer""" <|body_0|> def test_main(self): """test""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Test: """test""" def test_transformer_encoder_layer(self): """test_transformer_encoder_layer""" paddle.set_device('cpu') paddle.seed(2020) paddle.framework.random._manual_program_seed(2020) ffn_fc1_act = 'relu' [batch_size, d_model, n_head, dim_feedforward,...
the_stack_v2_python_sparse
framework/api/nn/test_TransformerEncoderLayer.py
PaddlePaddle/PaddleTest
train
42
64a5f112c5691a5790b0e304e8ab9318df9d7f05
[ "checkout = zeit.cms.checkout.interfaces.ICheckoutManager(self.context)\nif checkout.canCheckout:\n return _('View')\nreturn _('Edit contents')", "selected = self.request.getURL().endswith('@@edit.html')\nselected = selected or self.request.getURL().endswith('@@view.html')\nreturn selected" ]
<|body_start_0|> checkout = zeit.cms.checkout.interfaces.ICheckoutManager(self.context) if checkout.canCheckout: return _('View') return _('Edit contents') <|end_body_0|> <|body_start_1|> selected = self.request.getURL().endswith('@@edit.html') selected = selected or...
EditContentsMenuItem
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EditContentsMenuItem: def title(self): """Changes wheter item is checked out or checked in""" <|body_0|> def selected(self): """We are selected when no other item is selected.""" <|body_1|> <|end_skeleton|> <|body_start_0|> checkout = zeit.cms.check...
stack_v2_sparse_classes_36k_train_006098
831
permissive
[ { "docstring": "Changes wheter item is checked out or checked in", "name": "title", "signature": "def title(self)" }, { "docstring": "We are selected when no other item is selected.", "name": "selected", "signature": "def selected(self)" } ]
2
null
Implement the Python class `EditContentsMenuItem` described below. Class description: Implement the EditContentsMenuItem class. Method signatures and docstrings: - def title(self): Changes wheter item is checked out or checked in - def selected(self): We are selected when no other item is selected.
Implement the Python class `EditContentsMenuItem` described below. Class description: Implement the EditContentsMenuItem class. Method signatures and docstrings: - def title(self): Changes wheter item is checked out or checked in - def selected(self): We are selected when no other item is selected. <|skeleton|> clas...
3cc213b873d527127aa6f0dd3c79a542299a8a0e
<|skeleton|> class EditContentsMenuItem: def title(self): """Changes wheter item is checked out or checked in""" <|body_0|> def selected(self): """We are selected when no other item is selected.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EditContentsMenuItem: def title(self): """Changes wheter item is checked out or checked in""" checkout = zeit.cms.checkout.interfaces.ICheckoutManager(self.context) if checkout.canCheckout: return _('View') return _('Edit contents') def selected(self): ...
the_stack_v2_python_sparse
core/src/zeit/content/article/browser/menu.py
louika/vivi
train
0
dd2684e1dc89d205bdedf6166a3db20446c0fb81
[ "if start == end:\n return\nfor i in range(int((end - start + 1) / 2)):\n nums[start + i], nums[end - i] = (nums[end - i], nums[start + i])", "for i in range(len(nums) - 1, 0, -1):\n if nums[i - 1] < nums[i]:\n self.reverse_sublist(nums, i, len(nums) - 1)\n for j in range(i, len(nums)):\n ...
<|body_start_0|> if start == end: return for i in range(int((end - start + 1) / 2)): nums[start + i], nums[end - i] = (nums[end - i], nums[start + i]) <|end_body_0|> <|body_start_1|> for i in range(len(nums) - 1, 0, -1): if nums[i - 1] < nums[i]: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverse_sublist(self, nums, start, end): """Reverse order of sublist from start to end (both inclusive indices).""" <|body_0|> def nextPermutation(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body...
stack_v2_sparse_classes_36k_train_006099
1,113
no_license
[ { "docstring": "Reverse order of sublist from start to end (both inclusive indices).", "name": "reverse_sublist", "signature": "def reverse_sublist(self, nums, start, end)" }, { "docstring": "Do not return anything, modify nums in-place instead.", "name": "nextPermutation", "signature": ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse_sublist(self, nums, start, end): Reverse order of sublist from start to end (both inclusive indices). - def nextPermutation(self, nums: List[int]) -> None: Do not ret...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse_sublist(self, nums, start, end): Reverse order of sublist from start to end (both inclusive indices). - def nextPermutation(self, nums: List[int]) -> None: Do not ret...
de2b8bbc7cd744bb28ff9dcfe1d1cdc388c3fe8d
<|skeleton|> class Solution: def reverse_sublist(self, nums, start, end): """Reverse order of sublist from start to end (both inclusive indices).""" <|body_0|> def nextPermutation(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def reverse_sublist(self, nums, start, end): """Reverse order of sublist from start to end (both inclusive indices).""" if start == end: return for i in range(int((end - start + 1) / 2)): nums[start + i], nums[end - i] = (nums[end - i], nums[start + i]...
the_stack_v2_python_sparse
solutions/31.py
Anshul1196/leetcode
train
0