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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f5f0966e6a5072378b68d6c5cf544f63a355dc2c | [
"super(Span_Pos_CLS_StartPrior, self).__init__()\nself.sequence_encoder = sequence_encoder\nself.soft_label = soft_label\nself.num_labels = len(tag2id)\nself.tag2id = tag2id\nself.id2tag = {}\nfor tag, tid in tag2id.items():\n self.id2tag[tid] = tag\nif use_lstm:\n self.bilstm = nn.LSTM(input_size=sequence_en... | <|body_start_0|>
super(Span_Pos_CLS_StartPrior, self).__init__()
self.sequence_encoder = sequence_encoder
self.soft_label = soft_label
self.num_labels = len(tag2id)
self.tag2id = tag2id
self.id2tag = {}
for tag, tid in tag2id.items():
self.id2tag[tid] ... | Span_Pos_CLS_StartPrior | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Span_Pos_CLS_StartPrior:
def __init__(self, sequence_encoder, tag2id, use_lstm=False, compress_seq=False, soft_label=False, dropout_rate=0.1):
"""Args: sequence_encoder (nn.Module): encoder of sequence tag2id (dict): map from tag to id use_lstm (bool, optional): whether add lstm layer. D... | stack_v2_sparse_classes_36k_train_006300 | 14,475 | permissive | [
{
"docstring": "Args: sequence_encoder (nn.Module): encoder of sequence tag2id (dict): map from tag to id use_lstm (bool, optional): whether add lstm layer. Defaults to False. compress_seq (bool, optional): whether compress sequence for lstm. Defaults to True. soft_label (bool, optional): use one hot if soft_la... | 3 | stack_v2_sparse_classes_30k_train_017020 | Implement the Python class `Span_Pos_CLS_StartPrior` described below.
Class description:
Implement the Span_Pos_CLS_StartPrior class.
Method signatures and docstrings:
- def __init__(self, sequence_encoder, tag2id, use_lstm=False, compress_seq=False, soft_label=False, dropout_rate=0.1): Args: sequence_encoder (nn.Mod... | Implement the Python class `Span_Pos_CLS_StartPrior` described below.
Class description:
Implement the Span_Pos_CLS_StartPrior class.
Method signatures and docstrings:
- def __init__(self, sequence_encoder, tag2id, use_lstm=False, compress_seq=False, soft_label=False, dropout_rate=0.1): Args: sequence_encoder (nn.Mod... | b4c049fd30db39b67984edfadc49b4354d52be83 | <|skeleton|>
class Span_Pos_CLS_StartPrior:
def __init__(self, sequence_encoder, tag2id, use_lstm=False, compress_seq=False, soft_label=False, dropout_rate=0.1):
"""Args: sequence_encoder (nn.Module): encoder of sequence tag2id (dict): map from tag to id use_lstm (bool, optional): whether add lstm layer. D... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Span_Pos_CLS_StartPrior:
def __init__(self, sequence_encoder, tag2id, use_lstm=False, compress_seq=False, soft_label=False, dropout_rate=0.1):
"""Args: sequence_encoder (nn.Module): encoder of sequence tag2id (dict): map from tag to id use_lstm (bool, optional): whether add lstm layer. Defaults to Fal... | the_stack_v2_python_sparse | pasaie/pasaner/model/span_cls.py | tracy-talent/AIPolicy | train | 0 | |
22089c86863e4aa7cfdaa8d9b72b83b2e5cfea1a | [
"if cls._driver is None:\n if browser_name == 'Chrome':\n cls._driver = webdriver.Chrome(driverPath['Chrome'])\n elif browser_name == 'Firefox':\n cls._driver = webdriver.Firefox(driverPath['Firefox'])\n cls._driver.maximize_window()\n cls._driver.get(DOMAIN)\n cls.__login()\nreturn cls... | <|body_start_0|>
if cls._driver is None:
if browser_name == 'Chrome':
cls._driver = webdriver.Chrome(driverPath['Chrome'])
elif browser_name == 'Firefox':
cls._driver = webdriver.Firefox(driverPath['Firefox'])
cls._driver.maximize_window()
... | Driver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Driver:
def get_driver(cls, browser_name='Chrome'):
"""创建浏览器驱动对象,并将其作为返回值返回 如果,浏览器驱动对象不存在,则创建浏览器驱动对象,并将其作为返回值返回 如果,浏览器驱动对象存在,直接将其作为返回值返回即可 :param browser_name:希望创建的浏览器类型 :return:"""
<|body_0|>
def __login(cls):
"""私有方法,只能在类的内部使用 类外部无法使用,子类无法继承 解决登录问题,只希望在浏览器驱动对象被创建的时... | stack_v2_sparse_classes_36k_train_006301 | 1,850 | no_license | [
{
"docstring": "创建浏览器驱动对象,并将其作为返回值返回 如果,浏览器驱动对象不存在,则创建浏览器驱动对象,并将其作为返回值返回 如果,浏览器驱动对象存在,直接将其作为返回值返回即可 :param browser_name:希望创建的浏览器类型 :return:",
"name": "get_driver",
"signature": "def get_driver(cls, browser_name='Chrome')"
},
{
"docstring": "私有方法,只能在类的内部使用 类外部无法使用,子类无法继承 解决登录问题,只希望在浏览器驱动对象被创建的时候执... | 2 | stack_v2_sparse_classes_30k_train_014970 | Implement the Python class `Driver` described below.
Class description:
Implement the Driver class.
Method signatures and docstrings:
- def get_driver(cls, browser_name='Chrome'): 创建浏览器驱动对象,并将其作为返回值返回 如果,浏览器驱动对象不存在,则创建浏览器驱动对象,并将其作为返回值返回 如果,浏览器驱动对象存在,直接将其作为返回值返回即可 :param browser_name:希望创建的浏览器类型 :return:
- def __login(... | Implement the Python class `Driver` described below.
Class description:
Implement the Driver class.
Method signatures and docstrings:
- def get_driver(cls, browser_name='Chrome'): 创建浏览器驱动对象,并将其作为返回值返回 如果,浏览器驱动对象不存在,则创建浏览器驱动对象,并将其作为返回值返回 如果,浏览器驱动对象存在,直接将其作为返回值返回即可 :param browser_name:希望创建的浏览器类型 :return:
- def __login(... | 8065956de0cfb675e083ac692b243988d9e8d4b7 | <|skeleton|>
class Driver:
def get_driver(cls, browser_name='Chrome'):
"""创建浏览器驱动对象,并将其作为返回值返回 如果,浏览器驱动对象不存在,则创建浏览器驱动对象,并将其作为返回值返回 如果,浏览器驱动对象存在,直接将其作为返回值返回即可 :param browser_name:希望创建的浏览器类型 :return:"""
<|body_0|>
def __login(cls):
"""私有方法,只能在类的内部使用 类外部无法使用,子类无法继承 解决登录问题,只希望在浏览器驱动对象被创建的时... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Driver:
def get_driver(cls, browser_name='Chrome'):
"""创建浏览器驱动对象,并将其作为返回值返回 如果,浏览器驱动对象不存在,则创建浏览器驱动对象,并将其作为返回值返回 如果,浏览器驱动对象存在,直接将其作为返回值返回即可 :param browser_name:希望创建的浏览器类型 :return:"""
if cls._driver is None:
if browser_name == 'Chrome':
cls._driver = webdriver.Chrome(... | the_stack_v2_python_sparse | shanghaiyouyou/WebUiStudy/day7/po模式实战/utils/myDriver.py | kakashi-01/python-0504 | train | 0 | |
6f2301e3e6bd43e8a82926349a880ca4b23fdc3b | [
"mocker.patch.object(demisto, 'command', return_value='xdr-iocs-enable')\nmocker.patch.object(demisto, 'args', return_value={'indicator': '11.11.11.11'})\nmocker.patch('XDR_iocs.Client.http_request', return_value={})\noutputs = mocker.patch('XDR_iocs.return_outputs')\nenable_ioc = mocker.patch('XDR_iocs.prepare_ena... | <|body_start_0|>
mocker.patch.object(demisto, 'command', return_value='xdr-iocs-enable')
mocker.patch.object(demisto, 'args', return_value={'indicator': '11.11.11.11'})
mocker.patch('XDR_iocs.Client.http_request', return_value={})
outputs = mocker.patch('XDR_iocs.return_outputs')
... | TestIOCSCommand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestIOCSCommand:
def test_iocs_command_with_enable(self, mocker):
"""Given: - enable command Then: - Verify enable command is called."""
<|body_0|>
def test_iocs_command_with_disable(self, mocker):
"""Given: - disable command Then: - Verify disable command is called.... | stack_v2_sparse_classes_36k_train_006302 | 41,271 | permissive | [
{
"docstring": "Given: - enable command Then: - Verify enable command is called.",
"name": "test_iocs_command_with_enable",
"signature": "def test_iocs_command_with_enable(self, mocker)"
},
{
"docstring": "Given: - disable command Then: - Verify disable command is called.",
"name": "test_ioc... | 2 | stack_v2_sparse_classes_30k_train_021540 | Implement the Python class `TestIOCSCommand` described below.
Class description:
Implement the TestIOCSCommand class.
Method signatures and docstrings:
- def test_iocs_command_with_enable(self, mocker): Given: - enable command Then: - Verify enable command is called.
- def test_iocs_command_with_disable(self, mocker)... | Implement the Python class `TestIOCSCommand` described below.
Class description:
Implement the TestIOCSCommand class.
Method signatures and docstrings:
- def test_iocs_command_with_enable(self, mocker): Given: - enable command Then: - Verify enable command is called.
- def test_iocs_command_with_disable(self, mocker)... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestIOCSCommand:
def test_iocs_command_with_enable(self, mocker):
"""Given: - enable command Then: - Verify enable command is called."""
<|body_0|>
def test_iocs_command_with_disable(self, mocker):
"""Given: - disable command Then: - Verify disable command is called.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestIOCSCommand:
def test_iocs_command_with_enable(self, mocker):
"""Given: - enable command Then: - Verify enable command is called."""
mocker.patch.object(demisto, 'command', return_value='xdr-iocs-enable')
mocker.patch.object(demisto, 'args', return_value={'indicator': '11.11.11.11'... | the_stack_v2_python_sparse | Packs/CortexXDR/Integrations/XDR_iocs/XDR_iocs_test.py | demisto/content | train | 1,023 | |
5a9eb79dc648b6e9effabc4c424931a0d6465e77 | [
"n = len(A)\nif n <= 2:\n return True\nfor i in xrange(2, n):\n a = A[i] - A[i - 1]\n b = A[i - 1] - A[i - 2]\n if a * b < 0:\n return False\n elif a * b == 0 and a + b != 0:\n return False\nreturn True",
"n = len(A)\nif n <= 2:\n return True\nflag = 0\n\ndef sgn(x):\n return x ... | <|body_start_0|>
n = len(A)
if n <= 2:
return True
for i in xrange(2, n):
a = A[i] - A[i - 1]
b = A[i - 1] - A[i - 2]
if a * b < 0:
return False
elif a * b == 0 and a + b != 0:
return False
return... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isMonotonicWA(self, A):
""":type A: List[int] :rtype: bool"""
<|body_0|>
def isMonotonic(self, A):
""":type A: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(A)
if n <= 2:
return True... | stack_v2_sparse_classes_36k_train_006303 | 1,038 | no_license | [
{
"docstring": ":type A: List[int] :rtype: bool",
"name": "isMonotonicWA",
"signature": "def isMonotonicWA(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: bool",
"name": "isMonotonic",
"signature": "def isMonotonic(self, A)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMonotonicWA(self, A): :type A: List[int] :rtype: bool
- def isMonotonic(self, A): :type A: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMonotonicWA(self, A): :type A: List[int] :rtype: bool
- def isMonotonic(self, A): :type A: List[int] :rtype: bool
<|skeleton|>
class Solution:
def isMonotonicWA(self,... | 02ebe56cd92b9f4baeee132c5077892590018650 | <|skeleton|>
class Solution:
def isMonotonicWA(self, A):
""":type A: List[int] :rtype: bool"""
<|body_0|>
def isMonotonic(self, A):
""":type A: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isMonotonicWA(self, A):
""":type A: List[int] :rtype: bool"""
n = len(A)
if n <= 2:
return True
for i in xrange(2, n):
a = A[i] - A[i - 1]
b = A[i - 1] - A[i - 2]
if a * b < 0:
return False
... | the_stack_v2_python_sparse | python/leetcode.896.py | CalvinNeo/LeetCode | train | 3 | |
c43308a27aa0505f58171ab6b5bc60d950beccd9 | [
"language = Language() if language is None else language\ntraits.DatasetABC.__init__(self, self, language=language, device=device)\ntraits.Query.__init__(self, self)\ntraits.TransitionMatrix.__init__(self, self)\ntraits.Transform.__init__(self, parent=self, buffer_size=buffer_size, min_len=min_len, max_len=max_len,... | <|body_start_0|>
language = Language() if language is None else language
traits.DatasetABC.__init__(self, self, language=language, device=device)
traits.Query.__init__(self, self)
traits.TransitionMatrix.__init__(self, self)
traits.Transform.__init__(self, parent=self, buffer_siz... | Dataset used in training. This has some lazy operations due to dask usage. | Dataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""Dataset used in training. This has some lazy operations due to dask usage."""
def __init__(self, sentences: List[List[str]], language: Optional[Language], skip: Sequence[str]=(), buffer_size: int=int(10000.0), max_len: int=None, min_len: int=1, device: str='cpu', chunk_size: Unio... | stack_v2_sparse_classes_36k_train_006304 | 11,796 | permissive | [
{
"docstring": "Parameters ---------- sentences : list[list[str]] [[\"hello\", \"world!\"], [\"get\", \"down!\"]] language : sequence.data.utils.Language Required. Should be the language fitted for training. skip : list[str] Words to skip. buffer_size : int Size of chunks prepared by lazy generator. Only used d... | 2 | stack_v2_sparse_classes_30k_train_017920 | Implement the Python class `Dataset` described below.
Class description:
Dataset used in training. This has some lazy operations due to dask usage.
Method signatures and docstrings:
- def __init__(self, sentences: List[List[str]], language: Optional[Language], skip: Sequence[str]=(), buffer_size: int=int(10000.0), ma... | Implement the Python class `Dataset` described below.
Class description:
Dataset used in training. This has some lazy operations due to dask usage.
Method signatures and docstrings:
- def __init__(self, sentences: List[List[str]], language: Optional[Language], skip: Sequence[str]=(), buffer_size: int=int(10000.0), ma... | 79c669d0636521db2697e5fa583628d1920cc6c1 | <|skeleton|>
class Dataset:
"""Dataset used in training. This has some lazy operations due to dask usage."""
def __init__(self, sentences: List[List[str]], language: Optional[Language], skip: Sequence[str]=(), buffer_size: int=int(10000.0), max_len: int=None, min_len: int=1, device: str='cpu', chunk_size: Unio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dataset:
"""Dataset used in training. This has some lazy operations due to dask usage."""
def __init__(self, sentences: List[List[str]], language: Optional[Language], skip: Sequence[str]=(), buffer_size: int=int(10000.0), max_len: int=None, min_len: int=1, device: str='cpu', chunk_size: Union[int, str]='... | the_stack_v2_python_sparse | sequence/data/utils.py | ritchie46/sequence | train | 9 |
c1b088ab9fb2e11bb3f95198d8f112d2be020e8d | [
"super().__init__(classifier=classifier, regressor=regressor, coder=coder)\nself.logger = None\nself.fg_bg_sampler = sampler",
"box_logits, box_deltas = (prediction['box_logits'], prediction['box_deltas'])\nlosses = {}\nsampled_pos_inds, sampled_neg_inds = self.select_indices(target_labels, box_logits)\nsampled_i... | <|body_start_0|>
super().__init__(classifier=classifier, regressor=regressor, coder=coder)
self.logger = None
self.fg_bg_sampler = sampler
<|end_body_0|>
<|body_start_1|>
box_logits, box_deltas = (prediction['box_logits'], prediction['box_deltas'])
losses = {}
sampled_po... | DetectionHeadHNM | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DetectionHeadHNM:
def __init__(self, classifier: Classifier, regressor: Regressor, coder: BoxCoderND, sampler: AbstractSampler, log_num_anchors: Optional[str]='mllogger'):
"""Detection head with classifier and regression module. Uses hard negative example mining to compute loss Args: cla... | stack_v2_sparse_classes_36k_train_006305 | 21,997 | permissive | [
{
"docstring": "Detection head with classifier and regression module. Uses hard negative example mining to compute loss Args: classifier: classifier module regressor: regression module sampler (AbstractSampler): sampler for select positive and negative examples log_num_anchors (str): name of logger to use; if N... | 3 | stack_v2_sparse_classes_30k_train_003717 | Implement the Python class `DetectionHeadHNM` described below.
Class description:
Implement the DetectionHeadHNM class.
Method signatures and docstrings:
- def __init__(self, classifier: Classifier, regressor: Regressor, coder: BoxCoderND, sampler: AbstractSampler, log_num_anchors: Optional[str]='mllogger'): Detectio... | Implement the Python class `DetectionHeadHNM` described below.
Class description:
Implement the DetectionHeadHNM class.
Method signatures and docstrings:
- def __init__(self, classifier: Classifier, regressor: Regressor, coder: BoxCoderND, sampler: AbstractSampler, log_num_anchors: Optional[str]='mllogger'): Detectio... | 4f41faa7536dcef8fca7b647dcdca25360e5b58a | <|skeleton|>
class DetectionHeadHNM:
def __init__(self, classifier: Classifier, regressor: Regressor, coder: BoxCoderND, sampler: AbstractSampler, log_num_anchors: Optional[str]='mllogger'):
"""Detection head with classifier and regression module. Uses hard negative example mining to compute loss Args: cla... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DetectionHeadHNM:
def __init__(self, classifier: Classifier, regressor: Regressor, coder: BoxCoderND, sampler: AbstractSampler, log_num_anchors: Optional[str]='mllogger'):
"""Detection head with classifier and regression module. Uses hard negative example mining to compute loss Args: classifier: class... | the_stack_v2_python_sparse | nndet/arch/heads/comb.py | dboun/nnDetection | train | 1 | |
38481d6316a0f892011ed1c8ac82536246d50d2d | [
"super().__init__(connections, dev_cfg)\nself.log.info('Configuring LogicOr %s', self.name)\nself.log.debug('%s has following configured connections: \\n%s', self.name, yaml.dump(self.comm))\nself.log.debug('%s configured values: \\n%s', self.name, yaml.dump(self.values))\nverify_connections_layout(self.comm, self.... | <|body_start_0|>
super().__init__(connections, dev_cfg)
self.log.info('Configuring LogicOr %s', self.name)
self.log.debug('%s has following configured connections: \n%s', self.name, yaml.dump(self.comm))
self.log.debug('%s configured values: \n%s', self.name, yaml.dump(self.values))
... | Logical OR gate, can receive from multiple sensors and will trigger all configured receivers | LogicOr | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogicOr:
"""Logical OR gate, can receive from multiple sensors and will trigger all configured receivers"""
def __init__(self, connections, dev_cfg):
"""Initializes the Actuator by storing the passed in arguments as data members and registers 'InputSrc' and 'EnableSrc' with the given... | stack_v2_sparse_classes_36k_train_006306 | 9,274 | permissive | [
{
"docstring": "Initializes the Actuator by storing the passed in arguments as data members and registers 'InputSrc' and 'EnableSrc' with the given connections Arguments: - connections: List of the connections - dev_cfg: lambda that returns value for the passed in key \"Values\": Alternative values to publish i... | 2 | stack_v2_sparse_classes_30k_train_020563 | Implement the Python class `LogicOr` described below.
Class description:
Logical OR gate, can receive from multiple sensors and will trigger all configured receivers
Method signatures and docstrings:
- def __init__(self, connections, dev_cfg): Initializes the Actuator by storing the passed in arguments as data member... | Implement the Python class `LogicOr` described below.
Class description:
Logical OR gate, can receive from multiple sensors and will trigger all configured receivers
Method signatures and docstrings:
- def __init__(self, connections, dev_cfg): Initializes the Actuator by storing the passed in arguments as data member... | 6f8888ddef413fb8d58ef0ebc8fe89144c914a22 | <|skeleton|>
class LogicOr:
"""Logical OR gate, can receive from multiple sensors and will trigger all configured receivers"""
def __init__(self, connections, dev_cfg):
"""Initializes the Actuator by storing the passed in arguments as data members and registers 'InputSrc' and 'EnableSrc' with the given... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogicOr:
"""Logical OR gate, can receive from multiple sensors and will trigger all configured receivers"""
def __init__(self, connections, dev_cfg):
"""Initializes the Actuator by storing the passed in arguments as data members and registers 'InputSrc' and 'EnableSrc' with the given connections ... | the_stack_v2_python_sparse | local/local_logic.py | rkoshak/sensorReporter | train | 104 |
e09f1eee9a266cab57aaa4b880ec242aa9755aa5 | [
"interval = self.bot.configuration.prestige_wait_when_ready_interval\nif interval > 0:\n self.logger.info('Scheduling prestige to take place in %(interval)s second(s)...' % {'interval': interval})\n self.bot.cancel_scheduled_plugin(tags=['prestige', 'prestige_close_to_max'])\n self.bot.schedule_plugin(plug... | <|body_start_0|>
interval = self.bot.configuration.prestige_wait_when_ready_interval
if interval > 0:
self.logger.info('Scheduling prestige to take place in %(interval)s second(s)...' % {'interval': interval})
self.bot.cancel_scheduled_plugin(tags=['prestige', 'prestige_close_to_... | Perform a prestige in game if the "close to max" threshold has been reached. Close to max can be determined two ways: 1. The "event" icon is available for the event that is currently running. 2. The "skills" page "Prestige To Reset" icon is available in game. Once either of these are met, the close to max has been reac... | PrestigeCloseToMax | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrestigeCloseToMax:
"""Perform a prestige in game if the "close to max" threshold has been reached. Close to max can be determined two ways: 1. The "event" icon is available for the event that is currently running. 2. The "skills" page "Prestige To Reset" icon is available in game. Once either of... | stack_v2_sparse_classes_36k_train_006307 | 7,177 | no_license | [
{
"docstring": "Execute, or schedule a prestige based on the current configured interval.",
"name": "_prestige_execute_or_schedule",
"signature": "def _prestige_execute_or_schedule(self)"
},
{
"docstring": "Perform a prestige in game when the user has reached the stage required that represents t... | 2 | stack_v2_sparse_classes_30k_train_019994 | Implement the Python class `PrestigeCloseToMax` described below.
Class description:
Perform a prestige in game if the "close to max" threshold has been reached. Close to max can be determined two ways: 1. The "event" icon is available for the event that is currently running. 2. The "skills" page "Prestige To Reset" ic... | Implement the Python class `PrestigeCloseToMax` described below.
Class description:
Perform a prestige in game if the "close to max" threshold has been reached. Close to max can be determined two ways: 1. The "event" icon is available for the event that is currently running. 2. The "skills" page "Prestige To Reset" ic... | b8695acead575228c281459ba1397557f9a47149 | <|skeleton|>
class PrestigeCloseToMax:
"""Perform a prestige in game if the "close to max" threshold has been reached. Close to max can be determined two ways: 1. The "event" icon is available for the event that is currently running. 2. The "skills" page "Prestige To Reset" icon is available in game. Once either of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrestigeCloseToMax:
"""Perform a prestige in game if the "close to max" threshold has been reached. Close to max can be determined two ways: 1. The "event" icon is available for the event that is currently running. 2. The "skills" page "Prestige To Reset" icon is available in game. Once either of these are me... | the_stack_v2_python_sparse | bot/plugins/prestige/prestige_close_to_max.py | DevonJerothe/tap-titans-bot | train | 0 |
077c7468449eda0adca737f4d0f98f2856763ca7 | [
"self.v_count = 0\nself.adj_matrix = []\nif start_edges is not None:\n v_count = 0\n for u, v, _ in start_edges:\n v_count = max(v_count, u, v)\n for _ in range(v_count + 1):\n self.add_vertex()\n for u, v, weight in start_edges:\n self.add_edge(u, v, weight)",
"if self.v_count ==... | <|body_start_0|>
self.v_count = 0
self.adj_matrix = []
if start_edges is not None:
v_count = 0
for u, v, _ in start_edges:
v_count = max(v_count, u, v)
for _ in range(v_count + 1):
self.add_vertex()
for u, v, weight ... | Implements weighted graph to test MST algorithms. Copied from my CS261 Directed Graph assignment. | Graph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Graph:
"""Implements weighted graph to test MST algorithms. Copied from my CS261 Directed Graph assignment."""
def __init__(self, start_edges=None):
"""Store graph info as adjacency matrix DO NOT CHANGE THIS METHOD IN ANY WAY"""
<|body_0|>
def __str__(self):
"""R... | stack_v2_sparse_classes_36k_train_006308 | 6,160 | no_license | [
{
"docstring": "Store graph info as adjacency matrix DO NOT CHANGE THIS METHOD IN ANY WAY",
"name": "__init__",
"signature": "def __init__(self, start_edges=None)"
},
{
"docstring": "Return content of the graph in human-readable form DO NOT CHANGE THIS METHOD IN ANY WAY",
"name": "__str__",
... | 6 | stack_v2_sparse_classes_30k_train_006816 | Implement the Python class `Graph` described below.
Class description:
Implements weighted graph to test MST algorithms. Copied from my CS261 Directed Graph assignment.
Method signatures and docstrings:
- def __init__(self, start_edges=None): Store graph info as adjacency matrix DO NOT CHANGE THIS METHOD IN ANY WAY
-... | Implement the Python class `Graph` described below.
Class description:
Implements weighted graph to test MST algorithms. Copied from my CS261 Directed Graph assignment.
Method signatures and docstrings:
- def __init__(self, start_edges=None): Store graph info as adjacency matrix DO NOT CHANGE THIS METHOD IN ANY WAY
-... | dc1aae03fb6198a9a07c28f437123737161b1e49 | <|skeleton|>
class Graph:
"""Implements weighted graph to test MST algorithms. Copied from my CS261 Directed Graph assignment."""
def __init__(self, start_edges=None):
"""Store graph info as adjacency matrix DO NOT CHANGE THIS METHOD IN ANY WAY"""
<|body_0|>
def __str__(self):
"""R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Graph:
"""Implements weighted graph to test MST algorithms. Copied from my CS261 Directed Graph assignment."""
def __init__(self, start_edges=None):
"""Store graph info as adjacency matrix DO NOT CHANGE THIS METHOD IN ANY WAY"""
self.v_count = 0
self.adj_matrix = []
if sta... | the_stack_v2_python_sparse | MST.py | teejayjan/CS325 | train | 0 |
b8deee1fb01644fdb36261082ac94d13bd47897c | [
"for ch in letters:\n if ch > target:\n return ch\nreturn letters[0]",
"n = len(letters)\nif n == 0:\n return None\nlow = 0\nhigh = n - 1\nresult = 0\nwhile low <= high:\n mid = low + (high - low) // 2\n if letters[mid] > target:\n result = mid\n high = mid - 1\n else:\n ... | <|body_start_0|>
for ch in letters:
if ch > target:
return ch
return letters[0]
<|end_body_0|>
<|body_start_1|>
n = len(letters)
if n == 0:
return None
low = 0
high = n - 1
result = 0
while low <= high:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextGreatestLetter(self, letters, target):
""":type letters: List[str] :type target: str :rtype: str"""
<|body_0|>
def nextGreatestLetter2(self, letters, target):
""":type letters: List[str] :type target: str :rtype: str"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_006309 | 1,215 | no_license | [
{
"docstring": ":type letters: List[str] :type target: str :rtype: str",
"name": "nextGreatestLetter",
"signature": "def nextGreatestLetter(self, letters, target)"
},
{
"docstring": ":type letters: List[str] :type target: str :rtype: str",
"name": "nextGreatestLetter2",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_002921 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreatestLetter(self, letters, target): :type letters: List[str] :type target: str :rtype: str
- def nextGreatestLetter2(self, letters, target): :type letters: List[str] :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreatestLetter(self, letters, target): :type letters: List[str] :type target: str :rtype: str
- def nextGreatestLetter2(self, letters, target): :type letters: List[str] :... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def nextGreatestLetter(self, letters, target):
""":type letters: List[str] :type target: str :rtype: str"""
<|body_0|>
def nextGreatestLetter2(self, letters, target):
""":type letters: List[str] :type target: str :rtype: str"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nextGreatestLetter(self, letters, target):
""":type letters: List[str] :type target: str :rtype: str"""
for ch in letters:
if ch > target:
return ch
return letters[0]
def nextGreatestLetter2(self, letters, target):
""":type letters... | the_stack_v2_python_sparse | 8. BINARY SEARCH/744_find_smallest_letter_greater_than _target/solution.py | kimmyoo/python_leetcode | train | 1 | |
08f3bb8027661b65d1a2eeb71b31ae3301ad6f75 | [
"result = ['']\nfor i, c in enumerate(s):\n if c not in {'(', ')'}:\n result[-1] += c\n elif c == '(':\n result.append('')\n elif c == ')':\n popped = result.pop()\n result[-1] += popped[::-1]\nreturn result[0]",
"sign = 0\nnormal_stack = []\nreverse_stack = []\nfor i, c in en... | <|body_start_0|>
result = ['']
for i, c in enumerate(s):
if c not in {'(', ')'}:
result[-1] += c
elif c == '(':
result.append('')
elif c == ')':
popped = result.pop()
result[-1] += popped[::-1]
re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseParentheses(self, s: str) -> str:
"""20190928 执行用时 :40 ms, 在所有 Python3 提交中击败了95.30% 的用户 内存消耗 :13.9 MB, 在所有 Python3 提交中击败了100.00%的用户 如此写法, 真的太舒服了!"""
<|body_0|>
def reverseParentheses_old(self, s: str) -> str:
"""20190915 60 ms 14 MB Python3 很复杂的解... | stack_v2_sparse_classes_36k_train_006310 | 2,778 | no_license | [
{
"docstring": "20190928 执行用时 :40 ms, 在所有 Python3 提交中击败了95.30% 的用户 内存消耗 :13.9 MB, 在所有 Python3 提交中击败了100.00%的用户 如此写法, 真的太舒服了!",
"name": "reverseParentheses",
"signature": "def reverseParentheses(self, s: str) -> str"
},
{
"docstring": "20190915 60 ms 14 MB Python3 很复杂的解法",
"name": "reversePar... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseParentheses(self, s: str) -> str: 20190928 执行用时 :40 ms, 在所有 Python3 提交中击败了95.30% 的用户 内存消耗 :13.9 MB, 在所有 Python3 提交中击败了100.00%的用户 如此写法, 真的太舒服了!
- def reverseParentheses... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseParentheses(self, s: str) -> str: 20190928 执行用时 :40 ms, 在所有 Python3 提交中击败了95.30% 的用户 内存消耗 :13.9 MB, 在所有 Python3 提交中击败了100.00%的用户 如此写法, 真的太舒服了!
- def reverseParentheses... | 99a3abf1774933af73a8405f9b59e5e64906bca4 | <|skeleton|>
class Solution:
def reverseParentheses(self, s: str) -> str:
"""20190928 执行用时 :40 ms, 在所有 Python3 提交中击败了95.30% 的用户 内存消耗 :13.9 MB, 在所有 Python3 提交中击败了100.00%的用户 如此写法, 真的太舒服了!"""
<|body_0|>
def reverseParentheses_old(self, s: str) -> str:
"""20190915 60 ms 14 MB Python3 很复杂的解... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseParentheses(self, s: str) -> str:
"""20190928 执行用时 :40 ms, 在所有 Python3 提交中击败了95.30% 的用户 内存消耗 :13.9 MB, 在所有 Python3 提交中击败了100.00%的用户 如此写法, 真的太舒服了!"""
result = ['']
for i, c in enumerate(s):
if c not in {'(', ')'}:
result[-1] += c
... | the_stack_v2_python_sparse | leetcode/周赛/154/反转每对括号间的子串.py | iamkissg/leetcode | train | 0 | |
32b4da610a035b3dda6c527e6a8db38b06863744 | [
"Parametre.__init__(self, 'placer', 'in')\nself.schema = '(<nombre>) <nom_objet>'\nself.aide_courte = 'place des marchandises en cale'\nself.aide_longue = \"Cette commande vous permet de placer certaines marchandises en cale. Vous devez disposez des marchandises sur vous. Notez que le terme marchandise est utilisé ... | <|body_start_0|>
Parametre.__init__(self, 'placer', 'in')
self.schema = '(<nombre>) <nom_objet>'
self.aide_courte = 'place des marchandises en cale'
self.aide_longue = "Cette commande vous permet de placer certaines marchandises en cale. Vous devez disposez des marchandises sur vous. Not... | Commande 'cale placer'. | PrmPlacer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmPlacer:
"""Commande 'cale placer'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def ajouter(self):
"""Méthode appelée lors de l'ajout de la commande à l'interpréteur"""
<|body_1|>
def interpreter(self, personnage, dic_masques)... | stack_v2_sparse_classes_36k_train_006311 | 4,092 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Méthode appelée lors de l'ajout de la commande à l'interpréteur",
"name": "ajouter",
"signature": "def ajouter(self)"
},
{
"docstring": "Interprétation du paramètr... | 3 | null | Implement the Python class `PrmPlacer` described below.
Class description:
Commande 'cale placer'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def ajouter(self): Méthode appelée lors de l'ajout de la commande à l'interpréteur
- def interpreter(self, personnage, dic_masques): In... | Implement the Python class `PrmPlacer` described below.
Class description:
Commande 'cale placer'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def ajouter(self): Méthode appelée lors de l'ajout de la commande à l'interpréteur
- def interpreter(self, personnage, dic_masques): In... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmPlacer:
"""Commande 'cale placer'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def ajouter(self):
"""Méthode appelée lors de l'ajout de la commande à l'interpréteur"""
<|body_1|>
def interpreter(self, personnage, dic_masques)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmPlacer:
"""Commande 'cale placer'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'placer', 'in')
self.schema = '(<nombre>) <nom_objet>'
self.aide_courte = 'place des marchandises en cale'
self.aide_longue = "Cette commande vous ... | the_stack_v2_python_sparse | src/secondaires/navigation/commandes/cale/placer.py | vincent-lg/tsunami | train | 5 |
b817d36fa230efc334acda923e1884f139e48f18 | [
"super(SelfAttention, self).__init__()\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)\nself.W = tf.keras.layers.Dense(units)",
"query = tf.expand_dims(s_prev, 1)\ntfadd = tf.math.add(self.W(query), self.U(hidden_states))\nscore = self.V(tf.nn.tanh(tfadd))\nweigh = tf.nn.softmax(score, a... | <|body_start_0|>
super(SelfAttention, self).__init__()
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
self.W = tf.keras.layers.Dense(units)
<|end_body_0|>
<|body_start_1|>
query = tf.expand_dims(s_prev, 1)
tfadd = tf.math.add(self.W(query), self.... | class RNNEncoder class that inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation based on this paper: https://arxiv.org/pdf/1409.0473.pdf Args: tf ([type]): [description] | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""class RNNEncoder class that inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation based on this paper: https://arxiv.org/pdf/1409.0473.pdf Args: tf ([type]): [description]"""
def __init__(self, units):
"""[Class constructor] ... | stack_v2_sparse_classes_36k_train_006312 | 2,066 | no_license | [
{
"docstring": "[Class constructor] Args: units ([int]): [number of hidden units in the RNN cell] Sets the following public instance attributes: W: A Dense layer with units units, to be applied to the previous decoder hidden state U: A Dense layer with units units, to be applied to the encoder hidden states V: ... | 2 | stack_v2_sparse_classes_30k_val_000576 | Implement the Python class `SelfAttention` described below.
Class description:
class RNNEncoder class that inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation based on this paper: https://arxiv.org/pdf/1409.0473.pdf Args: tf ([type]): [description]
Method signatures and docs... | Implement the Python class `SelfAttention` described below.
Class description:
class RNNEncoder class that inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation based on this paper: https://arxiv.org/pdf/1409.0473.pdf Args: tf ([type]): [description]
Method signatures and docs... | eb47cd4d12e2f0627bb5e5af28cc0802ff13d0d9 | <|skeleton|>
class SelfAttention:
"""class RNNEncoder class that inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation based on this paper: https://arxiv.org/pdf/1409.0473.pdf Args: tf ([type]): [description]"""
def __init__(self, units):
"""[Class constructor] ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttention:
"""class RNNEncoder class that inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation based on this paper: https://arxiv.org/pdf/1409.0473.pdf Args: tf ([type]): [description]"""
def __init__(self, units):
"""[Class constructor] Args: units (... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | rodrigocruz13/holbertonschool-machine_learning | train | 4 |
de83447ea09faceb22852cf86615187b2f79bf05 | [
"del name\nif value:\n queryset = queryset.filter(company_id=value).order_by('-is_top', '-pk')\nreturn queryset",
"del name\nif value:\n return queryset.filter(owner_id=self.request.user.pk)\nreturn queryset.exclude(owner_id=self.request.user.pk)"
] | <|body_start_0|>
del name
if value:
queryset = queryset.filter(company_id=value).order_by('-is_top', '-pk')
return queryset
<|end_body_0|>
<|body_start_1|>
del name
if value:
return queryset.filter(owner_id=self.request.user.pk)
return queryset.ex... | Interview filterset. | InterviewFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterviewFilter:
"""Interview filterset."""
def _company(queryset, name, value):
"""Filter and order by company. :param queryset: Reviews queryset :param name: filter name :param value: filter value :return: queryset"""
<|body_0|>
def _is_mine(self, queryset, name, value... | stack_v2_sparse_classes_36k_train_006313 | 2,436 | no_license | [
{
"docstring": "Filter and order by company. :param queryset: Reviews queryset :param name: filter name :param value: filter value :return: queryset",
"name": "_company",
"signature": "def _company(queryset, name, value)"
},
{
"docstring": "Filter by owner. :param queryset: Reviews queryset :par... | 2 | null | Implement the Python class `InterviewFilter` described below.
Class description:
Interview filterset.
Method signatures and docstrings:
- def _company(queryset, name, value): Filter and order by company. :param queryset: Reviews queryset :param name: filter name :param value: filter value :return: queryset
- def _is_... | Implement the Python class `InterviewFilter` described below.
Class description:
Interview filterset.
Method signatures and docstrings:
- def _company(queryset, name, value): Filter and order by company. :param queryset: Reviews queryset :param name: filter name :param value: filter value :return: queryset
- def _is_... | 713b9d84ac70d964d46f189ab1f9c7b944b9684b | <|skeleton|>
class InterviewFilter:
"""Interview filterset."""
def _company(queryset, name, value):
"""Filter and order by company. :param queryset: Reviews queryset :param name: filter name :param value: filter value :return: queryset"""
<|body_0|>
def _is_mine(self, queryset, name, value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InterviewFilter:
"""Interview filterset."""
def _company(queryset, name, value):
"""Filter and order by company. :param queryset: Reviews queryset :param name: filter name :param value: filter value :return: queryset"""
del name
if value:
queryset = queryset.filter(com... | the_stack_v2_python_sparse | jobadvisor/reviews/filters.py | ewgen19892/jobadvisor | train | 0 |
1bf84b801499c9aa38fef04e6b10b35a813a4de4 | [
"n = len(pairs)\npairs = sorted(pairs)\nprint(pairs)\nif not n:\n return 0\nif n == 1:\n return 1\ndp = [1] * n\nfor i in range(n):\n for j in range(i):\n if pairs[i][0] > pairs[j][-1]:\n dp[i] = max(dp[i], dp[j] + 1)\nreturn max(dp)",
"link = {}\nfor start, end in pairs:\n link[end]... | <|body_start_0|>
n = len(pairs)
pairs = sorted(pairs)
print(pairs)
if not n:
return 0
if n == 1:
return 1
dp = [1] * n
for i in range(n):
for j in range(i):
if pairs[i][0] > pairs[j][-1]:
dp[i... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLongestChain(self, pairs) -> int:
"""可以通过动态规划来求解 不过超时了。。好尴尬 :param pairs: :return:"""
<|body_0|>
def findLongestChain2(self, pairs) -> int:
"""贪心算法来解决 思路是:排序后 :param pairs: :return:"""
<|body_1|>
def findLongestChain3(self, pairs) -> in... | stack_v2_sparse_classes_36k_train_006314 | 2,522 | permissive | [
{
"docstring": "可以通过动态规划来求解 不过超时了。。好尴尬 :param pairs: :return:",
"name": "findLongestChain",
"signature": "def findLongestChain(self, pairs) -> int"
},
{
"docstring": "贪心算法来解决 思路是:排序后 :param pairs: :return:",
"name": "findLongestChain2",
"signature": "def findLongestChain2(self, pairs) ->... | 3 | stack_v2_sparse_classes_30k_train_007682 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLongestChain(self, pairs) -> int: 可以通过动态规划来求解 不过超时了。。好尴尬 :param pairs: :return:
- def findLongestChain2(self, pairs) -> int: 贪心算法来解决 思路是:排序后 :param pairs: :return:
- def ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLongestChain(self, pairs) -> int: 可以通过动态规划来求解 不过超时了。。好尴尬 :param pairs: :return:
- def findLongestChain2(self, pairs) -> int: 贪心算法来解决 思路是:排序后 :param pairs: :return:
- def ... | 41f4b8b557cf15cbd602f187f6550184b3a108ec | <|skeleton|>
class Solution:
def findLongestChain(self, pairs) -> int:
"""可以通过动态规划来求解 不过超时了。。好尴尬 :param pairs: :return:"""
<|body_0|>
def findLongestChain2(self, pairs) -> int:
"""贪心算法来解决 思路是:排序后 :param pairs: :return:"""
<|body_1|>
def findLongestChain3(self, pairs) -> in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findLongestChain(self, pairs) -> int:
"""可以通过动态规划来求解 不过超时了。。好尴尬 :param pairs: :return:"""
n = len(pairs)
pairs = sorted(pairs)
print(pairs)
if not n:
return 0
if n == 1:
return 1
dp = [1] * n
for i in range(n... | the_stack_v2_python_sparse | leetcode/646. 最长数对链.py | zhongmb/suanfa | train | 0 | |
50d2d7513af61a00e7d9971fb3a8bff6ab45661d | [
"self.m = MPRester(api_key)\nself.dff = None\nself.ids = None",
"print('Will fetch %s inorganic compounds from Materials Project' % len(mp_ids))\n\ndef grouper(iterable, n, fillvalue=None):\n \"\"\"\"\n Split requests into fixed number groups\n eg: grouper('ABCDEFG', 3, 'x') --> ABC DEF G... | <|body_start_0|>
self.m = MPRester(api_key)
self.dff = None
self.ids = None
<|end_body_0|>
<|body_start_1|>
print('Will fetch %s inorganic compounds from Materials Project' % len(mp_ids))
def grouper(iterable, n, fillvalue=None):
""""
Split reque... | API for pymatgen database, access pymatgen to get data. Examples -------- >>> mpa = MpAccess("Di28ZMunseR8vr57") # change yourself key. >>> ids = mpa.get_ids({"elements": {"$in": ["Al","O"]},'nelements': {"$lt": 2, "$gte": 1}}) number 29 >>> df = mpa.data_fetcher(mp_ids=ids, mp_props=['material_id', "cif"]) Will fetch ... | MpAccess | [
"LGPL-3.0-only",
"LGPL-2.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MpAccess:
"""API for pymatgen database, access pymatgen to get data. Examples -------- >>> mpa = MpAccess("Di28ZMunseR8vr57") # change yourself key. >>> ids = mpa.get_ids({"elements": {"$in": ["Al","O"]},'nelements': {"$lt": 2, "$gte": 1}}) number 29 >>> df = mpa.data_fetcher(mp_ids=ids, mp_props... | stack_v2_sparse_classes_36k_train_006315 | 6,563 | permissive | [
{
"docstring": "Parameters ---------- api_key:str: pymatgen key.",
"name": "__init__",
"signature": "def __init__(self, api_key: str='Di28ZMunseR8vr46')"
},
{
"docstring": "Fetch file from pymatgen. prop_name=['band_gap','density',\"icsd_ids\"'volume','material_id','pretty_formula','elements',\"... | 5 | stack_v2_sparse_classes_30k_train_012048 | Implement the Python class `MpAccess` described below.
Class description:
API for pymatgen database, access pymatgen to get data. Examples -------- >>> mpa = MpAccess("Di28ZMunseR8vr57") # change yourself key. >>> ids = mpa.get_ids({"elements": {"$in": ["Al","O"]},'nelements': {"$lt": 2, "$gte": 1}}) number 29 >>> df ... | Implement the Python class `MpAccess` described below.
Class description:
API for pymatgen database, access pymatgen to get data. Examples -------- >>> mpa = MpAccess("Di28ZMunseR8vr57") # change yourself key. >>> ids = mpa.get_ids({"elements": {"$in": ["Al","O"]},'nelements': {"$lt": 2, "$gte": 1}}) number 29 >>> df ... | 47eea268d59fb036c4db0387fd845e53c7991178 | <|skeleton|>
class MpAccess:
"""API for pymatgen database, access pymatgen to get data. Examples -------- >>> mpa = MpAccess("Di28ZMunseR8vr57") # change yourself key. >>> ids = mpa.get_ids({"elements": {"$in": ["Al","O"]},'nelements': {"$lt": 2, "$gte": 1}}) number 29 >>> df = mpa.data_fetcher(mp_ids=ids, mp_props... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MpAccess:
"""API for pymatgen database, access pymatgen to get data. Examples -------- >>> mpa = MpAccess("Di28ZMunseR8vr57") # change yourself key. >>> ids = mpa.get_ids({"elements": {"$in": ["Al","O"]},'nelements': {"$lt": 2, "$gte": 1}}) number 29 >>> df = mpa.data_fetcher(mp_ids=ids, mp_props=['material_i... | the_stack_v2_python_sparse | featurebox/data/mp_access.py | boliqq07/featurebox | train | 1 |
29a204a74dcdd3cbcb42fb6096d4c2a3fbf54f9d | [
"page = CataloguePage(browser, LINK)\npage.open()\nproducts = page.load_products()\nproduct = random.choice(products)\nproduct_title = product.title\nproduct.add_to_basket()\nproduct_title = re.sub('\\\\.\\\\.\\\\.$', '', product_title).strip()\nassert page.is_text_present_at(BasePageLocators.SUCCESS_MESSAGE, Catal... | <|body_start_0|>
page = CataloguePage(browser, LINK)
page.open()
products = page.load_products()
product = random.choice(products)
product_title = product.title
product.add_to_basket()
product_title = re.sub('\\.\\.\\.$', '', product_title).strip()
assert ... | Тесты каталога | TestCataloguePage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCataloguePage:
"""Тесты каталога"""
def test_add_to_basket_confirmed(self, browser):
"""Тест проверяет, что при добавлении пользователем товара в корзину будет отображено сообщение об успехе добавления"""
<|body_0|>
def test_add_to_basket_updated_price(self, browser)... | stack_v2_sparse_classes_36k_train_006316 | 2,582 | no_license | [
{
"docstring": "Тест проверяет, что при добавлении пользователем товара в корзину будет отображено сообщение об успехе добавления",
"name": "test_add_to_basket_confirmed",
"signature": "def test_add_to_basket_confirmed(self, browser)"
},
{
"docstring": "Тест проверяет, что при добавлении пользов... | 2 | stack_v2_sparse_classes_30k_train_017275 | Implement the Python class `TestCataloguePage` described below.
Class description:
Тесты каталога
Method signatures and docstrings:
- def test_add_to_basket_confirmed(self, browser): Тест проверяет, что при добавлении пользователем товара в корзину будет отображено сообщение об успехе добавления
- def test_add_to_bas... | Implement the Python class `TestCataloguePage` described below.
Class description:
Тесты каталога
Method signatures and docstrings:
- def test_add_to_basket_confirmed(self, browser): Тест проверяет, что при добавлении пользователем товара в корзину будет отображено сообщение об успехе добавления
- def test_add_to_bas... | fb7ed1b83c37302b303cc829d6e5caa99aa43649 | <|skeleton|>
class TestCataloguePage:
"""Тесты каталога"""
def test_add_to_basket_confirmed(self, browser):
"""Тест проверяет, что при добавлении пользователем товара в корзину будет отображено сообщение об успехе добавления"""
<|body_0|>
def test_add_to_basket_updated_price(self, browser)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCataloguePage:
"""Тесты каталога"""
def test_add_to_basket_confirmed(self, browser):
"""Тест проверяет, что при добавлении пользователем товара в корзину будет отображено сообщение об успехе добавления"""
page = CataloguePage(browser, LINK)
page.open()
products = page.... | the_stack_v2_python_sparse | final/test_catalogue_page.py | qnikst/stepik_lessons | train | 1 |
e05cad1cab749d9a8a861a820eefac67bf0cca81 | [
"batch = batch.to(self.device)\ntokens_bos, _ = batch.tokens_bos\npred = self.hparams.model(tokens_bos)\nreturn pred",
"batch = batch.to(self.device)\ntokens_eos, tokens_len = batch.tokens_eos\nloss = self.hparams.compute_cost(predictions, tokens_eos, length=tokens_len)\nreturn loss",
"predictions = self.comput... | <|body_start_0|>
batch = batch.to(self.device)
tokens_bos, _ = batch.tokens_bos
pred = self.hparams.model(tokens_bos)
return pred
<|end_body_0|>
<|body_start_1|>
batch = batch.to(self.device)
tokens_eos, tokens_len = batch.tokens_eos
loss = self.hparams.compute_c... | Class that manages the training loop. See speechbrain.core.Brain. | LM | [
"Apache-2.0",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-permissive",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LM:
"""Class that manages the training loop. See speechbrain.core.Brain."""
def compute_forward(self, batch, stage):
"""Predicts the next word given the previous ones. Arguments --------- batch : PaddedBatch This batch object contains all the relevant tensors for computation. stage :... | stack_v2_sparse_classes_36k_train_006317 | 9,669 | permissive | [
{
"docstring": "Predicts the next word given the previous ones. Arguments --------- batch : PaddedBatch This batch object contains all the relevant tensors for computation. stage : sb.Stage One of sb.Stage.TRAIN, sb.Stage.VALID, or sb.Stage.TEST. Returns ------- predictions : torch.Tensor A tensor containing th... | 4 | null | Implement the Python class `LM` described below.
Class description:
Class that manages the training loop. See speechbrain.core.Brain.
Method signatures and docstrings:
- def compute_forward(self, batch, stage): Predicts the next word given the previous ones. Arguments --------- batch : PaddedBatch This batch object c... | Implement the Python class `LM` described below.
Class description:
Class that manages the training loop. See speechbrain.core.Brain.
Method signatures and docstrings:
- def compute_forward(self, batch, stage): Predicts the next word given the previous ones. Arguments --------- batch : PaddedBatch This batch object c... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class LM:
"""Class that manages the training loop. See speechbrain.core.Brain."""
def compute_forward(self, batch, stage):
"""Predicts the next word given the previous ones. Arguments --------- batch : PaddedBatch This batch object contains all the relevant tensors for computation. stage :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LM:
"""Class that manages the training loop. See speechbrain.core.Brain."""
def compute_forward(self, batch, stage):
"""Predicts the next word given the previous ones. Arguments --------- batch : PaddedBatch This batch object contains all the relevant tensors for computation. stage : sb.Stage One... | the_stack_v2_python_sparse | PyTorch/dev/perf/speechbrain-tdnn/templates/speech_recognition/LM/train.py | Ascend/ModelZoo-PyTorch | train | 23 |
c32648503f99a51d2d61b172c5e290c30cfee946 | [
"if self.dbconn.version < 90300:\n return\nfor trig in self.fetch():\n trig.enabled = self.enable_modes[trig.enabled]\n self[trig.key()] = trig",
"for key in intriggers:\n if not key.startswith('event trigger '):\n raise KeyError('Unrecognized object type: %s' % key)\n trg = key[14:]\n in... | <|body_start_0|>
if self.dbconn.version < 90300:
return
for trig in self.fetch():
trig.enabled = self.enable_modes[trig.enabled]
self[trig.key()] = trig
<|end_body_0|>
<|body_start_1|>
for key in intriggers:
if not key.startswith('event trigger ')... | The collection of event triggers in a database | EventTriggerDict | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventTriggerDict:
"""The collection of event triggers in a database"""
def _from_catalog(self):
"""Initialize the dictionary of triggers by querying the catalogs"""
<|body_0|>
def from_map(self, intriggers, newdb):
"""Initalize the dictionary of triggers by conve... | stack_v2_sparse_classes_36k_train_006318 | 3,974 | permissive | [
{
"docstring": "Initialize the dictionary of triggers by querying the catalogs",
"name": "_from_catalog",
"signature": "def _from_catalog(self)"
},
{
"docstring": "Initalize the dictionary of triggers by converting the input map :param intriggers: YAML map defining the event triggers :param newd... | 3 | stack_v2_sparse_classes_30k_train_003522 | Implement the Python class `EventTriggerDict` described below.
Class description:
The collection of event triggers in a database
Method signatures and docstrings:
- def _from_catalog(self): Initialize the dictionary of triggers by querying the catalogs
- def from_map(self, intriggers, newdb): Initalize the dictionary... | Implement the Python class `EventTriggerDict` described below.
Class description:
The collection of event triggers in a database
Method signatures and docstrings:
- def _from_catalog(self): Initialize the dictionary of triggers by querying the catalogs
- def from_map(self, intriggers, newdb): Initalize the dictionary... | 0133f3bc522890e0564d27de6791824acb4d2773 | <|skeleton|>
class EventTriggerDict:
"""The collection of event triggers in a database"""
def _from_catalog(self):
"""Initialize the dictionary of triggers by querying the catalogs"""
<|body_0|>
def from_map(self, intriggers, newdb):
"""Initalize the dictionary of triggers by conve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventTriggerDict:
"""The collection of event triggers in a database"""
def _from_catalog(self):
"""Initialize the dictionary of triggers by querying the catalogs"""
if self.dbconn.version < 90300:
return
for trig in self.fetch():
trig.enabled = self.enable_... | the_stack_v2_python_sparse | pyrseas/dbobject/eventtrig.py | vayerx/Pyrseas | train | 1 |
872fdb7d5a9fd2488e5b10608ef5513dc4c3e6f9 | [
"raw = cls.validate_payload(payload)\ntry:\n raw_float = cast(float, struct.unpack('>f', bytes(raw))[0])\nexcept struct.error:\n raise ConversionError(f'Could not parse {cls.__name__}', raw=raw)\ntry:\n return round(raw_float, 7 - ceil(log10(abs(raw_float))))\nexcept (ValueError, OverflowError):\n retur... | <|body_start_0|>
raw = cls.validate_payload(payload)
try:
raw_float = cast(float, struct.unpack('>f', bytes(raw))[0])
except struct.error:
raise ConversionError(f'Could not parse {cls.__name__}', raw=raw)
try:
return round(raw_float, 7 - ceil(log10(abs... | Abstraction for KNX 4 Octet Floating Point Numbers, with a maximum usable range as specified in IEEE 754. The largest positive finite float literal is 3.40282347e+38f. The smallest positive finite non-zero literal of type float is 1.40239846e-45f. The negative minimum finite float literal is -3.40282347e+38f. No value ... | DPT4ByteFloat | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DPT4ByteFloat:
"""Abstraction for KNX 4 Octet Floating Point Numbers, with a maximum usable range as specified in IEEE 754. The largest positive finite float literal is 3.40282347e+38f. The smallest positive finite non-zero literal of type float is 1.40239846e-45f. The negative minimum finite flo... | stack_v2_sparse_classes_36k_train_006319 | 17,660 | permissive | [
{
"docstring": "Parse/deserialize from KNX/IP raw data (big endian).",
"name": "from_knx",
"signature": "def from_knx(cls, payload: DPTArray | DPTBinary) -> float"
},
{
"docstring": "Serialize to KNX/IP raw data.",
"name": "to_knx",
"signature": "def to_knx(cls, value: float) -> DPTArray... | 2 | null | Implement the Python class `DPT4ByteFloat` described below.
Class description:
Abstraction for KNX 4 Octet Floating Point Numbers, with a maximum usable range as specified in IEEE 754. The largest positive finite float literal is 3.40282347e+38f. The smallest positive finite non-zero literal of type float is 1.4023984... | Implement the Python class `DPT4ByteFloat` described below.
Class description:
Abstraction for KNX 4 Octet Floating Point Numbers, with a maximum usable range as specified in IEEE 754. The largest positive finite float literal is 3.40282347e+38f. The smallest positive finite non-zero literal of type float is 1.4023984... | 48d4e31365c15e632b275f0d129cd9f2b2b5717d | <|skeleton|>
class DPT4ByteFloat:
"""Abstraction for KNX 4 Octet Floating Point Numbers, with a maximum usable range as specified in IEEE 754. The largest positive finite float literal is 3.40282347e+38f. The smallest positive finite non-zero literal of type float is 1.40239846e-45f. The negative minimum finite flo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DPT4ByteFloat:
"""Abstraction for KNX 4 Octet Floating Point Numbers, with a maximum usable range as specified in IEEE 754. The largest positive finite float literal is 3.40282347e+38f. The smallest positive finite non-zero literal of type float is 1.40239846e-45f. The negative minimum finite float literal is... | the_stack_v2_python_sparse | xknx/dpt/dpt_4byte_float.py | XKNX/xknx | train | 248 |
ff96c3524e079cd32615941b74aa292f28242ee3 | [
"self.pdf = pdf\nself.ranges = ranges\nif ranges is not None:\n self.d = len(ranges)\nreturn",
"result = None\ni = 0\nwhile result is None or len(result) < N:\n assert not (ranges is None and self.ranges is None), 'Unspecified range'\n if ranges is None:\n ranges = self.ranges\n self.d = len(ra... | <|body_start_0|>
self.pdf = pdf
self.ranges = ranges
if ranges is not None:
self.d = len(ranges)
return
<|end_body_0|>
<|body_start_1|>
result = None
i = 0
while result is None or len(result) < N:
assert not (ranges is None and self.ranges... | Rejection sampler This sampler generates sample form a provided proobability distribution using the rejection routine. It generates a unifrm density of points wthin a specified range, and selects points who are greater than a generated random number. Given a parameter space :math:`\\mathbf \\theta` and a probability de... | RejectionSamplerUniform | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RejectionSamplerUniform:
"""Rejection sampler This sampler generates sample form a provided proobability distribution using the rejection routine. It generates a unifrm density of points wthin a specified range, and selects points who are greater than a generated random number. Given a parameter ... | stack_v2_sparse_classes_36k_train_006320 | 3,930 | permissive | [
{
"docstring": "Initialize the Rejection sampler ... Parameters ---------- pdf : function A function that should take an :math:`(N,d)` nd-array and return a uarray :math:`(N,)`. The input to the function is thus a set of :math:`N` vectors, each of length :math:`d`. This function should return :math:`N` values, ... | 2 | stack_v2_sparse_classes_30k_train_018278 | Implement the Python class `RejectionSamplerUniform` described below.
Class description:
Rejection sampler This sampler generates sample form a provided proobability distribution using the rejection routine. It generates a unifrm density of points wthin a specified range, and selects points who are greater than a gene... | Implement the Python class `RejectionSamplerUniform` described below.
Class description:
Rejection sampler This sampler generates sample form a provided proobability distribution using the rejection routine. It generates a unifrm density of points wthin a specified range, and selects points who are greater than a gene... | adf76196506633e761f2df46a087fa80e5f1d35c | <|skeleton|>
class RejectionSamplerUniform:
"""Rejection sampler This sampler generates sample form a provided proobability distribution using the rejection routine. It generates a unifrm density of points wthin a specified range, and selects points who are greater than a generated random number. Given a parameter ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RejectionSamplerUniform:
"""Rejection sampler This sampler generates sample form a provided proobability distribution using the rejection routine. It generates a unifrm density of points wthin a specified range, and selects points who are greater than a generated random number. Given a parameter space :math:`... | the_stack_v2_python_sparse | src/lib/density/sampling/RejectionSampling.py | sankhaMukherjee/densityNN | train | 0 |
8fcbeecd123fec46ddf01cd121c7407624b27954 | [
"request_user = User.get_by_id(token_auth.current_user())\nif request_user.role != 1:\n return ({'Error': 'Only admin users can create organisations.', 'SubCode': 'OnlyAdminAccess'}, 403)\ntry:\n organisation_dto = NewOrganisationDTO(request.get_json())\n if request_user.username not in organisation_dto.ma... | <|body_start_0|>
request_user = User.get_by_id(token_auth.current_user())
if request_user.role != 1:
return ({'Error': 'Only admin users can create organisations.', 'SubCode': 'OnlyAdminAccess'}, 403)
try:
organisation_dto = NewOrganisationDTO(request.get_json())
... | OrganisationsRestAPI | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganisationsRestAPI:
def post(self):
"""Creates a new organisation --- tags: - organisations produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - in: body name:... | stack_v2_sparse_classes_36k_train_006321 | 15,215 | permissive | [
{
"docstring": "Creates a new organisation --- tags: - organisations produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - in: body name: body required: true description: JSON object for... | 4 | stack_v2_sparse_classes_30k_train_008723 | Implement the Python class `OrganisationsRestAPI` described below.
Class description:
Implement the OrganisationsRestAPI class.
Method signatures and docstrings:
- def post(self): Creates a new organisation --- tags: - organisations produces: - application/json parameters: - in: header name: Authorization description... | Implement the Python class `OrganisationsRestAPI` described below.
Class description:
Implement the OrganisationsRestAPI class.
Method signatures and docstrings:
- def post(self): Creates a new organisation --- tags: - organisations produces: - application/json parameters: - in: header name: Authorization description... | 45bf3937c74902226096aee5b49e7abea62df524 | <|skeleton|>
class OrganisationsRestAPI:
def post(self):
"""Creates a new organisation --- tags: - organisations produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - in: body name:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrganisationsRestAPI:
def post(self):
"""Creates a new organisation --- tags: - organisations produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - in: body name: body required... | the_stack_v2_python_sparse | backend/api/organisations/resources.py | hotosm/tasking-manager | train | 526 | |
2fa417d4d0364590e2fedc09ccc1400d746d34ad | [
"self.batch_size = batch_size\nself.beam_size = beam_size\nself.EOS_ID = EOS_ID\nself.back_pointers = []\nself.token_ids = []\nself.scores = []",
"B = self.batch_size\nK = self.beam_size\ndevice = self.token_ids[0].device\nmax_unroll = len(self.back_pointers)\nscore = self.scores[-1].clone()\nn_eos_found = [0] * ... | <|body_start_0|>
self.batch_size = batch_size
self.beam_size = beam_size
self.EOS_ID = EOS_ID
self.back_pointers = []
self.token_ids = []
self.scores = []
<|end_body_0|>
<|body_start_1|>
B = self.batch_size
K = self.beam_size
device = self.token_i... | Beam | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Beam:
def __init__(self, batch_size, beam_size, EOS_ID=3):
"""Beam class for beam search"""
<|body_0|>
def backtrack(self):
"""Backtracks over batch to generate optimal k-sequences back_pointer [B, K] token_id [B, K] attention [B, K, source_L] Returns: prediction ([B... | stack_v2_sparse_classes_36k_train_006322 | 49,575 | no_license | [
{
"docstring": "Beam class for beam search",
"name": "__init__",
"signature": "def __init__(self, batch_size, beam_size, EOS_ID=3)"
},
{
"docstring": "Backtracks over batch to generate optimal k-sequences back_pointer [B, K] token_id [B, K] attention [B, K, source_L] Returns: prediction ([B, K, ... | 2 | null | Implement the Python class `Beam` described below.
Class description:
Implement the Beam class.
Method signatures and docstrings:
- def __init__(self, batch_size, beam_size, EOS_ID=3): Beam class for beam search
- def backtrack(self): Backtracks over batch to generate optimal k-sequences back_pointer [B, K] token_id ... | Implement the Python class `Beam` described below.
Class description:
Implement the Beam class.
Method signatures and docstrings:
- def __init__(self, batch_size, beam_size, EOS_ID=3): Beam class for beam search
- def backtrack(self): Backtracks over batch to generate optimal k-sequences back_pointer [B, K] token_id ... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Beam:
def __init__(self, batch_size, beam_size, EOS_ID=3):
"""Beam class for beam search"""
<|body_0|>
def backtrack(self):
"""Backtracks over batch to generate optimal k-sequences back_pointer [B, K] token_id [B, K] attention [B, K, source_L] Returns: prediction ([B... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Beam:
def __init__(self, batch_size, beam_size, EOS_ID=3):
"""Beam class for beam search"""
self.batch_size = batch_size
self.beam_size = beam_size
self.EOS_ID = EOS_ID
self.back_pointers = []
self.token_ids = []
self.scores = []
def backtrack(self)... | the_stack_v2_python_sparse | generated/test_clovaai_FocusSeq2Seq.py | jansel/pytorch-jit-paritybench | train | 35 | |
06fd9e8576d04e83186079f5b18937b6f6a4c8b0 | [
"is_fit_call = isinstance(node.func, ast.Attribute) and node.func.attr == 'fit'\nif is_fit_call:\n for kw in node.keywords:\n if kw.arg == 'run_tensorboard_locally':\n return True\nreturn False",
"for kw in node.keywords:\n if kw.arg == 'run_tensorboard_locally':\n node.keywords.rem... | <|body_start_0|>
is_fit_call = isinstance(node.func, ast.Attribute) and node.func.attr == 'fit'
if is_fit_call:
for kw in node.keywords:
if kw.arg == 'run_tensorboard_locally':
return True
return False
<|end_body_0|>
<|body_start_1|>
for k... | A class for removing the ``run_tensorboard_locally`` parameter from ``fit()``. | TensorBoardParameterRemover | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TensorBoardParameterRemover:
"""A class for removing the ``run_tensorboard_locally`` parameter from ``fit()``."""
def node_should_be_modified(self, node):
"""Checks ``ast.Call`` node and returns boolean. If the ``ast.Call`` node invokes a function named "fit" and contains a keyword a... | stack_v2_sparse_classes_36k_train_006323 | 8,776 | permissive | [
{
"docstring": "Checks ``ast.Call`` node and returns boolean. If the ``ast.Call`` node invokes a function named \"fit\" and contains a keyword argument named \"run_tensorboard_locally\" returns boolean. Args: node (ast.Call): a node that represents a function call. For more, see https://docs.python.org/3/librar... | 2 | stack_v2_sparse_classes_30k_train_007678 | Implement the Python class `TensorBoardParameterRemover` described below.
Class description:
A class for removing the ``run_tensorboard_locally`` parameter from ``fit()``.
Method signatures and docstrings:
- def node_should_be_modified(self, node): Checks ``ast.Call`` node and returns boolean. If the ``ast.Call`` nod... | Implement the Python class `TensorBoardParameterRemover` described below.
Class description:
A class for removing the ``run_tensorboard_locally`` parameter from ``fit()``.
Method signatures and docstrings:
- def node_should_be_modified(self, node): Checks ``ast.Call`` node and returns boolean. If the ``ast.Call`` nod... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class TensorBoardParameterRemover:
"""A class for removing the ``run_tensorboard_locally`` parameter from ``fit()``."""
def node_should_be_modified(self, node):
"""Checks ``ast.Call`` node and returns boolean. If the ``ast.Call`` node invokes a function named "fit" and contains a keyword a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TensorBoardParameterRemover:
"""A class for removing the ``run_tensorboard_locally`` parameter from ``fit()``."""
def node_should_be_modified(self, node):
"""Checks ``ast.Call`` node and returns boolean. If the ``ast.Call`` node invokes a function named "fit" and contains a keyword argument named... | the_stack_v2_python_sparse | src/sagemaker/cli/compatibility/v2/modifiers/tf_legacy_mode.py | aws/sagemaker-python-sdk | train | 2,050 |
008fd01e24115e77b6f93e255232261e66da16cf | [
"super().__init__()\nassert kernel_size % 2 == 1, 'Kernel size must be odd number.'\nassert len(upsample_scales) == len(upsample_kernel_sizes)\nassert len(resblock_dilations) == len(resblock_kernel_sizes)\nself.num_upsamples = len(upsample_kernel_sizes)\nself.num_blocks = len(resblock_kernel_sizes)\nself.input_conv... | <|body_start_0|>
super().__init__()
assert kernel_size % 2 == 1, 'Kernel size must be odd number.'
assert len(upsample_scales) == len(upsample_kernel_sizes)
assert len(resblock_dilations) == len(resblock_kernel_sizes)
self.num_upsamples = len(upsample_kernel_sizes)
self.n... | Avocodo generator module. | AvocodoGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AvocodoGenerator:
"""Avocodo generator module."""
def __init__(self, in_channels: int=80, out_channels: int=1, channels: int=512, global_channels: int=-1, kernel_size: int=7, upsample_scales: List[int]=[8, 8, 2, 2], upsample_kernel_sizes: List[int]=[16, 16, 4, 4], resblock_kernel_sizes: List... | stack_v2_sparse_classes_36k_train_006324 | 29,046 | permissive | [
{
"docstring": "Initialize AvocodoGenerator module. Args: in_channels (int): Number of input channels. out_channels (int): Number of output channels. channels (int): Number of hidden representation channels. global_channels (int): Number of global conditioning channels. kernel_size (int): Kernel size of initial... | 5 | stack_v2_sparse_classes_30k_train_016201 | Implement the Python class `AvocodoGenerator` described below.
Class description:
Avocodo generator module.
Method signatures and docstrings:
- def __init__(self, in_channels: int=80, out_channels: int=1, channels: int=512, global_channels: int=-1, kernel_size: int=7, upsample_scales: List[int]=[8, 8, 2, 2], upsample... | Implement the Python class `AvocodoGenerator` described below.
Class description:
Avocodo generator module.
Method signatures and docstrings:
- def __init__(self, in_channels: int=80, out_channels: int=1, channels: int=512, global_channels: int=-1, kernel_size: int=7, upsample_scales: List[int]=[8, 8, 2, 2], upsample... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class AvocodoGenerator:
"""Avocodo generator module."""
def __init__(self, in_channels: int=80, out_channels: int=1, channels: int=512, global_channels: int=-1, kernel_size: int=7, upsample_scales: List[int]=[8, 8, 2, 2], upsample_kernel_sizes: List[int]=[16, 16, 4, 4], resblock_kernel_sizes: List... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AvocodoGenerator:
"""Avocodo generator module."""
def __init__(self, in_channels: int=80, out_channels: int=1, channels: int=512, global_channels: int=-1, kernel_size: int=7, upsample_scales: List[int]=[8, 8, 2, 2], upsample_kernel_sizes: List[int]=[16, 16, 4, 4], resblock_kernel_sizes: List[int]=[3, 7, ... | the_stack_v2_python_sparse | espnet2/gan_svs/avocodo/avocodo.py | espnet/espnet | train | 7,242 |
828dbb37ef0e139c616567fbff25f6d9e0e420af | [
"try:\n send_health_message(KAFKA_SERVER, HEALTHTOPIC, SERVICENAME)\nexcept Exception as error:\n LogMessage(str(error), LogMessage.LogTyp.ERROR, SERVICENAME).log()",
"try:\n report = json.loads(report.value.decode('UTF-8'))\n misp_connection = PyMISP(MISP_SERVER, MISP_TOKEN, MISP_CERT_VERIFY)\n ha... | <|body_start_0|>
try:
send_health_message(KAFKA_SERVER, HEALTHTOPIC, SERVICENAME)
except Exception as error:
LogMessage(str(error), LogMessage.LogTyp.ERROR, SERVICENAME).log()
<|end_body_0|>
<|body_start_1|>
try:
report = json.loads(report.value.decode('UTF-8... | Reporter will be a class representing the reporter-service. | Reporter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reporter:
"""Reporter will be a class representing the reporter-service."""
def healthpush():
"""healthpush will send a health message to KAFKA."""
<|body_0|>
def push_misp_report(report):
"""push_misp_report will send the misp report to the misp-platfrom."""
... | stack_v2_sparse_classes_36k_train_006325 | 3,082 | permissive | [
{
"docstring": "healthpush will send a health message to KAFKA.",
"name": "healthpush",
"signature": "def healthpush()"
},
{
"docstring": "push_misp_report will send the misp report to the misp-platfrom.",
"name": "push_misp_report",
"signature": "def push_misp_report(report)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_013816 | Implement the Python class `Reporter` described below.
Class description:
Reporter will be a class representing the reporter-service.
Method signatures and docstrings:
- def healthpush(): healthpush will send a health message to KAFKA.
- def push_misp_report(report): push_misp_report will send the misp report to the ... | Implement the Python class `Reporter` described below.
Class description:
Reporter will be a class representing the reporter-service.
Method signatures and docstrings:
- def healthpush(): healthpush will send a health message to KAFKA.
- def push_misp_report(report): push_misp_report will send the misp report to the ... | cdad9966ab2aef495d0dca51a06cf567dd38a315 | <|skeleton|>
class Reporter:
"""Reporter will be a class representing the reporter-service."""
def healthpush():
"""healthpush will send a health message to KAFKA."""
<|body_0|>
def push_misp_report(report):
"""push_misp_report will send the misp report to the misp-platfrom."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Reporter:
"""Reporter will be a class representing the reporter-service."""
def healthpush():
"""healthpush will send a health message to KAFKA."""
try:
send_health_message(KAFKA_SERVER, HEALTHTOPIC, SERVICENAME)
except Exception as error:
LogMessage(str(er... | the_stack_v2_python_sparse | iocreporter/core/server.py | hm-seclab/YAFRA | train | 32 |
0301f45a5eb322a6c9c32836d1e140e874837d3e | [
"dp = [False] * len(s)\nfor i in range(len(s)):\n for w in wordDict:\n if len(w) <= i + 1 and (dp[i - len(w)] or i - len(w) == -1) and (s[i - len(w) + 1:i + 1] == w):\n dp[i] = True\nreturn dp[-1]",
"starts = [0]\nword_set = set(wordDict)\nfor i in range(len(s)):\n if any((s[j:i + 1] in wo... | <|body_start_0|>
dp = [False] * len(s)
for i in range(len(s)):
for w in wordDict:
if len(w) <= i + 1 and (dp[i - len(w)] or i - len(w) == -1) and (s[i - len(w) + 1:i + 1] == w):
dp[i] = True
return dp[-1]
<|end_body_0|>
<|body_start_1|>
st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak(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: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_006326 | 820 | no_license | [
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
},
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(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: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(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: bool
<|s... | 24aaca7585c59255a86474c1f8088bd5b81ebf51 | <|skeleton|>
class Solution:
def wordBreak(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: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
dp = [False] * len(s)
for i in range(len(s)):
for w in wordDict:
if len(w) <= i + 1 and (dp[i - len(w)] or i - len(w) == -1) and (s[i - len(w) + 1:i + 1] ==... | the_stack_v2_python_sparse | Dynamic Programming/139. Word Break.py | burnmg/LC_algorithms_practice | train | 0 | |
0c7c692536dc5e58d65661314e16b826ad56779f | [
"kw = super(CallCreateView, self).get_form_kwargs()\nkw.update({'organization': self.request.user.organization})\nreturn kw",
"self.object = call = form.save(commit=False)\ncall.owner = self.request.user\ncall.organization = self.request.user.organization\ncall.save()\nform.save_m2m()\nreturn redirect(self.get_su... | <|body_start_0|>
kw = super(CallCreateView, self).get_form_kwargs()
kw.update({'organization': self.request.user.organization})
return kw
<|end_body_0|>
<|body_start_1|>
self.object = call = form.save(commit=False)
call.owner = self.request.user
call.organization = self.... | Create a call. | CallCreateView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CallCreateView:
"""Create a call."""
def get_form_kwargs(self):
"""Pass current user organization to the form."""
<|body_0|>
def form_valid(self, form):
"""Save -- but first save some details."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
kw =... | stack_v2_sparse_classes_36k_train_006327 | 28,644 | permissive | [
{
"docstring": "Pass current user organization to the form.",
"name": "get_form_kwargs",
"signature": "def get_form_kwargs(self)"
},
{
"docstring": "Save -- but first save some details.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002440 | Implement the Python class `CallCreateView` described below.
Class description:
Create a call.
Method signatures and docstrings:
- def get_form_kwargs(self): Pass current user organization to the form.
- def form_valid(self, form): Save -- but first save some details. | Implement the Python class `CallCreateView` described below.
Class description:
Create a call.
Method signatures and docstrings:
- def get_form_kwargs(self): Pass current user organization to the form.
- def form_valid(self, form): Save -- but first save some details.
<|skeleton|>
class CallCreateView:
"""Create... | dc6bc79d450f7e2bdf59cfbcd306d05a736e4db9 | <|skeleton|>
class CallCreateView:
"""Create a call."""
def get_form_kwargs(self):
"""Pass current user organization to the form."""
<|body_0|>
def form_valid(self, form):
"""Save -- but first save some details."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CallCreateView:
"""Create a call."""
def get_form_kwargs(self):
"""Pass current user organization to the form."""
kw = super(CallCreateView, self).get_form_kwargs()
kw.update({'organization': self.request.user.organization})
return kw
def form_valid(self, form):
... | the_stack_v2_python_sparse | project/editorial/views/contractors.py | ProjectFacet/facet | train | 25 |
f9410bd8d9ef2133f617705d76e55814618524b0 | [
"self.password = password\nself.server_name = server_name\nself.target = target\nself.user_name = user_name",
"if dictionary is None:\n return None\npassword = dictionary.get('password')\nserver_name = dictionary.get('serverName')\ntarget = dictionary.get('target')\nuser_name = dictionary.get('userName')\nretu... | <|body_start_0|>
self.password = password
self.server_name = server_name
self.target = target
self.user_name = user_name
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
password = dictionary.get('password')
server_name = dictionary.... | Implementation of the 'HostInfo' model. Specifies the list of all hosts on which the certificate is deployed. Attributes: password (string): Specifies the password of the host to establish SSH connection. The certificate is copied to the host after generating the certificate on the cluster. server_name (string): Specif... | HostInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostInfo:
"""Implementation of the 'HostInfo' model. Specifies the list of all hosts on which the certificate is deployed. Attributes: password (string): Specifies the password of the host to establish SSH connection. The certificate is copied to the host after generating the certificate on the c... | stack_v2_sparse_classes_36k_train_006328 | 2,260 | permissive | [
{
"docstring": "Constructor for the HostInfo class",
"name": "__init__",
"signature": "def __init__(self, password=None, server_name=None, target=None, user_name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representati... | 2 | null | Implement the Python class `HostInfo` described below.
Class description:
Implementation of the 'HostInfo' model. Specifies the list of all hosts on which the certificate is deployed. Attributes: password (string): Specifies the password of the host to establish SSH connection. The certificate is copied to the host af... | Implement the Python class `HostInfo` described below.
Class description:
Implementation of the 'HostInfo' model. Specifies the list of all hosts on which the certificate is deployed. Attributes: password (string): Specifies the password of the host to establish SSH connection. The certificate is copied to the host af... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class HostInfo:
"""Implementation of the 'HostInfo' model. Specifies the list of all hosts on which the certificate is deployed. Attributes: password (string): Specifies the password of the host to establish SSH connection. The certificate is copied to the host after generating the certificate on the c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HostInfo:
"""Implementation of the 'HostInfo' model. Specifies the list of all hosts on which the certificate is deployed. Attributes: password (string): Specifies the password of the host to establish SSH connection. The certificate is copied to the host after generating the certificate on the cluster. serve... | the_stack_v2_python_sparse | cohesity_management_sdk/models/host_info.py | cohesity/management-sdk-python | train | 24 |
d7d6b242415b75a4065d2b25681a7c2ba4d35d41 | [
"if not root:\n return\nif self.isDescendantOf(p, q):\n return p\nif self.isDescendantOf(q, p):\n return q\nif self.isDescendantOf(root.left, p) and self.isDescendantOf(root.right, q) or (self.isDescendantOf(root.left, q) and self.isDescendantOf(root.right, p)):\n return root\nelse:\n return self.low... | <|body_start_0|>
if not root:
return
if self.isDescendantOf(p, q):
return p
if self.isDescendantOf(q, p):
return q
if self.isDescendantOf(root.left, p) and self.isDescendantOf(root.right, q) or (self.isDescendantOf(root.left, q) and self.isDescendantOf... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|body_0|>
def isDescendantOf(self, x, y):
"""Check if y is a descendant of x"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_006329 | 2,297 | no_license | [
{
"docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root, p, q)"
},
{
"docstring": "Check if y is a descendant of x",
"name": "isDescendantOf",
"signature": "def isDescend... | 2 | stack_v2_sparse_classes_30k_train_009166 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode
- def isDescendantOf(self, x, y): Check if y is a descendant... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode
- def isDescendantOf(self, x, y): Check if y is a descendant... | 8e740b858bcc4d268861535203b76ee186754cdb | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|body_0|>
def isDescendantOf(self, x, y):
"""Check if y is a descendant of x"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
if not root:
return
if self.isDescendantOf(p, q):
return p
if self.isDescendantOf(q, p):
return q
if... | the_stack_v2_python_sparse | LowestCommonAncestorofaBinaryTree.py | SeavantUUz/LC_learning | train | 1 | |
2c5d4f26b0db6eb58a2972fc4e3d48fd8bbb6ce4 | [
"sub_command = 'list_dags' if airflow_version < (2, 0, 0) else 'dags list'\ncommand = f'CLOUDSDK_API_ENDPOINT_OVERRIDES_COMPOSER={sdk_endpoint} gcloud composer environments run {environment} --project={project_name} --location={location} {sub_command}'\ncommand_output = DAG._run_shell_command_locally_once(command=c... | <|body_start_0|>
sub_command = 'list_dags' if airflow_version < (2, 0, 0) else 'dags list'
command = f'CLOUDSDK_API_ENDPOINT_OVERRIDES_COMPOSER={sdk_endpoint} gcloud composer environments run {environment} --project={project_name} --location={location} {sub_command}'
command_output = DAG._run_sh... | Provides necessary utils for Composer DAGs. | DAG | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DAG:
"""Provides necessary utils for Composer DAGs."""
def get_list_of_dags(project_name: str, environment: str, location: str, sdk_endpoint: str, airflow_version: tuple[int]) -> list[str]:
"""Retrieves the list of dags for particular project."""
<|body_0|>
def _run_shel... | stack_v2_sparse_classes_36k_train_006330 | 8,678 | permissive | [
{
"docstring": "Retrieves the list of dags for particular project.",
"name": "get_list_of_dags",
"signature": "def get_list_of_dags(project_name: str, environment: str, location: str, sdk_endpoint: str, airflow_version: tuple[int]) -> list[str]"
},
{
"docstring": "Executes shell command and retu... | 5 | null | Implement the Python class `DAG` described below.
Class description:
Provides necessary utils for Composer DAGs.
Method signatures and docstrings:
- def get_list_of_dags(project_name: str, environment: str, location: str, sdk_endpoint: str, airflow_version: tuple[int]) -> list[str]: Retrieves the list of dags for par... | Implement the Python class `DAG` described below.
Class description:
Provides necessary utils for Composer DAGs.
Method signatures and docstrings:
- def get_list_of_dags(project_name: str, environment: str, location: str, sdk_endpoint: str, airflow_version: tuple[int]) -> list[str]: Retrieves the list of dags for par... | 44e819e713c3885e38c99c16dc73b7d7478acfe8 | <|skeleton|>
class DAG:
"""Provides necessary utils for Composer DAGs."""
def get_list_of_dags(project_name: str, environment: str, location: str, sdk_endpoint: str, airflow_version: tuple[int]) -> list[str]:
"""Retrieves the list of dags for particular project."""
<|body_0|>
def _run_shel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DAG:
"""Provides necessary utils for Composer DAGs."""
def get_list_of_dags(project_name: str, environment: str, location: str, sdk_endpoint: str, airflow_version: tuple[int]) -> list[str]:
"""Retrieves the list of dags for particular project."""
sub_command = 'list_dags' if airflow_versi... | the_stack_v2_python_sparse | composer/tools/composer_dags.py | GoogleCloudPlatform/python-docs-samples | train | 7,035 |
2936fb2c028ea411143d858668ee976c4550edae | [
"if not isinstance(self.db.run_date, datetime):\n self.db.run_date = datetime.now() + timedelta(days=7)\nremaining = self.db.run_date - datetime.now()\nreturn remaining",
"rounding_check = timedelta(minutes=5)\nif self.time_remaining < rounding_check:\n return True\nelse:\n return False"
] | <|body_start_0|>
if not isinstance(self.db.run_date, datetime):
self.db.run_date = datetime.now() + timedelta(days=7)
remaining = self.db.run_date - datetime.now()
return remaining
<|end_body_0|>
<|body_start_1|>
rounding_check = timedelta(minutes=5)
if self.time_rem... | Mixin for checking remaining time | RunDateMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunDateMixin:
"""Mixin for checking remaining time"""
def time_remaining(self):
"""Returns the time the update is scheduled to run.AccountTransaction Returns: remaining (Timedelta): remaining time before weekly update will process"""
<|body_0|>
def check_event(self):
... | stack_v2_sparse_classes_36k_train_006331 | 1,073 | permissive | [
{
"docstring": "Returns the time the update is scheduled to run.AccountTransaction Returns: remaining (Timedelta): remaining time before weekly update will process",
"name": "time_remaining",
"signature": "def time_remaining(self)"
},
{
"docstring": "Determine if enough time has passed. Return t... | 2 | stack_v2_sparse_classes_30k_train_017420 | Implement the Python class `RunDateMixin` described below.
Class description:
Mixin for checking remaining time
Method signatures and docstrings:
- def time_remaining(self): Returns the time the update is scheduled to run.AccountTransaction Returns: remaining (Timedelta): remaining time before weekly update will proc... | Implement the Python class `RunDateMixin` described below.
Class description:
Mixin for checking remaining time
Method signatures and docstrings:
- def time_remaining(self): Returns the time the update is scheduled to run.AccountTransaction Returns: remaining (Timedelta): remaining time before weekly update will proc... | 363a1f14fd1a640580a4bf4486a1afe776757557 | <|skeleton|>
class RunDateMixin:
"""Mixin for checking remaining time"""
def time_remaining(self):
"""Returns the time the update is scheduled to run.AccountTransaction Returns: remaining (Timedelta): remaining time before weekly update will process"""
<|body_0|>
def check_event(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunDateMixin:
"""Mixin for checking remaining time"""
def time_remaining(self):
"""Returns the time the update is scheduled to run.AccountTransaction Returns: remaining (Timedelta): remaining time before weekly update will process"""
if not isinstance(self.db.run_date, datetime):
... | the_stack_v2_python_sparse | typeclasses/scripts/script_mixins.py | Arx-Game/arxcode | train | 52 |
b3848755c624fb80b6eb08a9726e88cf6710d559 | [
"super().__init__(join('trainers', trainer.name.lower() + '_b.png'), position, anim_sequence_pos)\nself._nFrames = 1\nself._framesPerSecond = 1\nself._initial_position = position",
"self.setPosition(self.getPosition() + Vector2(2, 0))\nif self.getPosition().x > self._initial_position.x + 4:\n if self.getPositi... | <|body_start_0|>
super().__init__(join('trainers', trainer.name.lower() + '_b.png'), position, anim_sequence_pos)
self._nFrames = 1
self._framesPerSecond = 1
self._initial_position = position
<|end_body_0|>
<|body_start_1|>
self.setPosition(self.getPosition() + Vector2(2, 0))
... | EnemyDrop | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnemyDrop:
def __init__(self, position, anim_sequence_pos, trainer):
""""This is enemies equivalent of a TrainerToss. The enemy simply moves right off the screen"""
<|body_0|>
def update(self, ticks):
"""Player moves two pixels per update method. Returns the index of... | stack_v2_sparse_classes_36k_train_006332 | 1,110 | no_license | [
{
"docstring": "\"This is enemies equivalent of a TrainerToss. The enemy simply moves right off the screen",
"name": "__init__",
"signature": "def __init__(self, position, anim_sequence_pos, trainer)"
},
{
"docstring": "Player moves two pixels per update method. Returns the index of the next Ani... | 2 | stack_v2_sparse_classes_30k_train_021069 | Implement the Python class `EnemyDrop` described below.
Class description:
Implement the EnemyDrop class.
Method signatures and docstrings:
- def __init__(self, position, anim_sequence_pos, trainer): "This is enemies equivalent of a TrainerToss. The enemy simply moves right off the screen
- def update(self, ticks): P... | Implement the Python class `EnemyDrop` described below.
Class description:
Implement the EnemyDrop class.
Method signatures and docstrings:
- def __init__(self, position, anim_sequence_pos, trainer): "This is enemies equivalent of a TrainerToss. The enemy simply moves right off the screen
- def update(self, ticks): P... | 6718fdb6555d87f0b7b331c10d64a604431f8e81 | <|skeleton|>
class EnemyDrop:
def __init__(self, position, anim_sequence_pos, trainer):
""""This is enemies equivalent of a TrainerToss. The enemy simply moves right off the screen"""
<|body_0|>
def update(self, ticks):
"""Player moves two pixels per update method. Returns the index of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnemyDrop:
def __init__(self, position, anim_sequence_pos, trainer):
""""This is enemies equivalent of a TrainerToss. The enemy simply moves right off the screen"""
super().__init__(join('trainers', trainer.name.lower() + '_b.png'), position, anim_sequence_pos)
self._nFrames = 1
... | the_stack_v2_python_sparse | pokered/modules/animations/enemy_drop.py | surranc20/pokered | train | 44 | |
5ee18fa9af9efb894d2f8996ef864f1a2ec12e80 | [
"self.power_spectrum = power_spectrum\nself.delta_f = delta_f\nself.zero_padding = zero_padding\nif any(self.power_spectrum < self.eps):\n if not suppress_small_elements_warning:\n logging.warning('Some elements of power spectrum are too small, setting to zero')\n self.power_spectrum[self.power_spectru... | <|body_start_0|>
self.power_spectrum = power_spectrum
self.delta_f = delta_f
self.zero_padding = zero_padding
if any(self.power_spectrum < self.eps):
if not suppress_small_elements_warning:
logging.warning('Some elements of power spectrum are too small, settin... | SpectralFactorization | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpectralFactorization:
def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False):
"""Calculate the minimum-phase causal wavelet of a given power spectrum. In other words: Given the power transmission spectrum S(f) = |h(f)|² of a system with ... | stack_v2_sparse_classes_36k_train_006333 | 3,853 | permissive | [
{
"docstring": "Calculate the minimum-phase causal wavelet of a given power spectrum. In other words: Given the power transmission spectrum S(f) = |h(f)|² of a system with transfer function h(f), reconstruct the phase of h(f) so that h(t) = 0 for t < 0. The answer is only unique up to an all-pass component; the... | 2 | stack_v2_sparse_classes_30k_train_001774 | Implement the Python class `SpectralFactorization` described below.
Class description:
Implement the SpectralFactorization class.
Method signatures and docstrings:
- def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False): Calculate the minimum-phase causal wavelet of ... | Implement the Python class `SpectralFactorization` described below.
Class description:
Implement the SpectralFactorization class.
Method signatures and docstrings:
- def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False): Calculate the minimum-phase causal wavelet of ... | 4fc56396ad603bbe61e6d548f66b818d51a3301b | <|skeleton|>
class SpectralFactorization:
def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False):
"""Calculate the minimum-phase causal wavelet of a given power spectrum. In other words: Given the power transmission spectrum S(f) = |h(f)|² of a system with ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpectralFactorization:
def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False):
"""Calculate the minimum-phase causal wavelet of a given power spectrum. In other words: Given the power transmission spectrum S(f) = |h(f)|² of a system with transfer funct... | the_stack_v2_python_sparse | pycqed/analysis/tools/spectralfac.py | DiCarloLab-Delft/PycQED_py3 | train | 72 | |
53059386cbd0f6d9cb1cb2ca895b4584b20685ff | [
"self.path = os.getcwd()\nself.metadata = metadata\nself.license = license\nself.options = options\nself.playbooks = AnsibleGenerator._fetch_all_playbooks(self.path)\nplaybooks_name = [playbook['file'] for playbook in self.playbooks]\nAnsibleGenerator.LOGGER.debug('Playbooks found: %s', playbooks_name)\nself.metada... | <|body_start_0|>
self.path = os.getcwd()
self.metadata = metadata
self.license = license
self.options = options
self.playbooks = AnsibleGenerator._fetch_all_playbooks(self.path)
playbooks_name = [playbook['file'] for playbook in self.playbooks]
AnsibleGenerator.LO... | AnsibleGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnsibleGenerator:
def __init__(self, metadata, license=None, options=None):
"""Creates the object to generate the ansible charm from templates. Usage should be: 1) Create the object. 2) Run the generate method. :param metadata: metadata information about the charm being generated. :param... | stack_v2_sparse_classes_36k_train_006334 | 6,707 | permissive | [
{
"docstring": "Creates the object to generate the ansible charm from templates. Usage should be: 1) Create the object. 2) Run the generate method. :param metadata: metadata information about the charm being generated. :param license: information license to included in the charm being generated. :param options:... | 6 | null | Implement the Python class `AnsibleGenerator` described below.
Class description:
Implement the AnsibleGenerator class.
Method signatures and docstrings:
- def __init__(self, metadata, license=None, options=None): Creates the object to generate the ansible charm from templates. Usage should be: 1) Create the object. ... | Implement the Python class `AnsibleGenerator` described below.
Class description:
Implement the AnsibleGenerator class.
Method signatures and docstrings:
- def __init__(self, metadata, license=None, options=None): Creates the object to generate the ansible charm from templates. Usage should be: 1) Create the object. ... | b5973c2a4477354bb17a56fe39559f277a3a994a | <|skeleton|>
class AnsibleGenerator:
def __init__(self, metadata, license=None, options=None):
"""Creates the object to generate the ansible charm from templates. Usage should be: 1) Create the object. 2) Run the generate method. :param metadata: metadata information about the charm being generated. :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnsibleGenerator:
def __init__(self, metadata, license=None, options=None):
"""Creates the object to generate the ansible charm from templates. Usage should be: 1) Create the object. 2) Run the generate method. :param metadata: metadata information about the charm being generated. :param license: info... | the_stack_v2_python_sparse | descriptor-packages/tools/charm-generator/generator/generators/ansible_generator.py | ayoubbargueoui1996/osm-devops | train | 0 | |
677fd147dd5ebb7a59f95037746c0758ce61c110 | [
"user = self.model(email=email, **kwargs)\nuser.set_password(password)\nuser.save()\nreturn user",
"user = self.model(email=email, is_staff=True, is_superuser=True, **kwargs)\nuser.set_password(password)\nuser.save()\nreturn user"
] | <|body_start_0|>
user = self.model(email=email, **kwargs)
user.set_password(password)
user.save()
return user
<|end_body_0|>
<|body_start_1|>
user = self.model(email=email, is_staff=True, is_superuser=True, **kwargs)
user.set_password(password)
user.save()
... | Manager para controlar el modelo de usuarios que se creo, esto es requerido por AbstractBaseUser de django | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
"""Manager para controlar el modelo de usuarios que se creo, esto es requerido por AbstractBaseUser de django"""
def create_user(self, email, password=None, **kwargs):
""":param email: email del usuario :param password: contraseña (si se requiere) :param kwargs: p... | stack_v2_sparse_classes_36k_train_006335 | 1,068 | no_license | [
{
"docstring": ":param email: email del usuario :param password: contraseña (si se requiere) :param kwargs: parametros adicionales :return: usuario creado",
"name": "create_user",
"signature": "def create_user(self, email, password=None, **kwargs)"
},
{
"docstring": "Método para crear un superus... | 2 | stack_v2_sparse_classes_30k_train_011592 | Implement the Python class `UserProfileManager` described below.
Class description:
Manager para controlar el modelo de usuarios que se creo, esto es requerido por AbstractBaseUser de django
Method signatures and docstrings:
- def create_user(self, email, password=None, **kwargs): :param email: email del usuario :par... | Implement the Python class `UserProfileManager` described below.
Class description:
Manager para controlar el modelo de usuarios que se creo, esto es requerido por AbstractBaseUser de django
Method signatures and docstrings:
- def create_user(self, email, password=None, **kwargs): :param email: email del usuario :par... | cab11691d958df504c95884673916d0419e92b56 | <|skeleton|>
class UserProfileManager:
"""Manager para controlar el modelo de usuarios que se creo, esto es requerido por AbstractBaseUser de django"""
def create_user(self, email, password=None, **kwargs):
""":param email: email del usuario :param password: contraseña (si se requiere) :param kwargs: p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileManager:
"""Manager para controlar el modelo de usuarios que se creo, esto es requerido por AbstractBaseUser de django"""
def create_user(self, email, password=None, **kwargs):
""":param email: email del usuario :param password: contraseña (si se requiere) :param kwargs: parametros adi... | the_stack_v2_python_sparse | django_vue_multitenant/users/managers.py | kevincardonag/django-vue | train | 0 |
5d7d5d7acb30597d90f54b6474d6e5e367cd7d7a | [
"response_mock = Mock()\nresponse_mock.json.return_value = payload\nreturn response_mock",
"with patch('utils.requests') as mock_requests:\n mock_requests.get.return_value = self.response(payload)\n self.assertEqual(get_json(url), expected)\n assert mock_requests.get.call_count == 1"
] | <|body_start_0|>
response_mock = Mock()
response_mock.json.return_value = payload
return response_mock
<|end_body_0|>
<|body_start_1|>
with patch('utils.requests') as mock_requests:
mock_requests.get.return_value = self.response(payload)
self.assertEqual(get_json... | [summary] Args: unittest ([type]): [description] | TestGetJson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGetJson:
"""[summary] Args: unittest ([type]): [description]"""
def response(self, payload):
"""[summary]"""
<|body_0|>
def test_get_json(self, url, payload, expected):
"""[summary]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
response_mo... | stack_v2_sparse_classes_36k_train_006336 | 3,221 | no_license | [
{
"docstring": "[summary]",
"name": "response",
"signature": "def response(self, payload)"
},
{
"docstring": "[summary]",
"name": "test_get_json",
"signature": "def test_get_json(self, url, payload, expected)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012957 | Implement the Python class `TestGetJson` described below.
Class description:
[summary] Args: unittest ([type]): [description]
Method signatures and docstrings:
- def response(self, payload): [summary]
- def test_get_json(self, url, payload, expected): [summary] | Implement the Python class `TestGetJson` described below.
Class description:
[summary] Args: unittest ([type]): [description]
Method signatures and docstrings:
- def response(self, payload): [summary]
- def test_get_json(self, url, payload, expected): [summary]
<|skeleton|>
class TestGetJson:
"""[summary] Args: ... | 94cae2ce3aa4cd72fc5907bd0148694054a9e60f | <|skeleton|>
class TestGetJson:
"""[summary] Args: unittest ([type]): [description]"""
def response(self, payload):
"""[summary]"""
<|body_0|>
def test_get_json(self, url, payload, expected):
"""[summary]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestGetJson:
"""[summary] Args: unittest ([type]): [description]"""
def response(self, payload):
"""[summary]"""
response_mock = Mock()
response_mock.json.return_value = payload
return response_mock
def test_get_json(self, url, payload, expected):
"""[summary]... | the_stack_v2_python_sparse | 0x09-Unittests_and_integration_tests/test_utils.py | nakadorx/holbertonschool-web_back_end | train | 0 |
8b030049f7f1d747ce6afe82a09d31c5eb156c20 | [
"if 'host' not in kwargs:\n raise TobyException(\"'host' is mandatory\", host_obj=self)\nif kwargs.get('connect_mode', '').lower() == 'console':\n kwargs['strict'] = True\nkwargs['os'] = kwargs.get('os', 'BROCADE')\nself._kwargs = kwargs\nself.connected = False\nself.mode = 'user'\nself.prompt = '>\\\\s+'\nsu... | <|body_start_0|>
if 'host' not in kwargs:
raise TobyException("'host' is mandatory", host_obj=self)
if kwargs.get('connect_mode', '').lower() == 'console':
kwargs['strict'] = True
kwargs['os'] = kwargs.get('os', 'BROCADE')
self._kwargs = kwargs
self.connec... | Generic Brocade class for common operations | Brocade | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Brocade:
"""Generic Brocade class for common operations"""
def __init__(self, *args, **kwargs):
"""Base class for Brocade devices :param host: **REQUIRED** host-name or IP address of target device :param os: *OPTIONAL* Operating System of device. Default is BROCADE :param user: *OPTI... | stack_v2_sparse_classes_36k_train_006337 | 5,819 | no_license | [
{
"docstring": "Base class for Brocade devices :param host: **REQUIRED** host-name or IP address of target device :param os: *OPTIONAL* Operating System of device. Default is BROCADE :param user: *OPTIONAL* Login user name. If not provided will be derived from Toby framework defaults. :param password: *OPTIONAL... | 5 | stack_v2_sparse_classes_30k_train_008865 | Implement the Python class `Brocade` described below.
Class description:
Generic Brocade class for common operations
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Base class for Brocade devices :param host: **REQUIRED** host-name or IP address of target device :param os: *OPTIONAL* Operatin... | Implement the Python class `Brocade` described below.
Class description:
Generic Brocade class for common operations
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Base class for Brocade devices :param host: **REQUIRED** host-name or IP address of target device :param os: *OPTIONAL* Operatin... | 3966c63d48557b0b94303896eed7a767593a4832 | <|skeleton|>
class Brocade:
"""Generic Brocade class for common operations"""
def __init__(self, *args, **kwargs):
"""Base class for Brocade devices :param host: **REQUIRED** host-name or IP address of target device :param os: *OPTIONAL* Operating System of device. Default is BROCADE :param user: *OPTI... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Brocade:
"""Generic Brocade class for common operations"""
def __init__(self, *args, **kwargs):
"""Base class for Brocade devices :param host: **REQUIRED** host-name or IP address of target device :param os: *OPTIONAL* Operating System of device. Default is BROCADE :param user: *OPTIONAL* Login u... | the_stack_v2_python_sparse | NITA/lib/jnpr/toby/hldcl/brocade/brocade.py | fengyun4623/file | train | 0 |
facb40a87e67d960d6d730fa88dee8c724b7d27e | [
"dice = randint(1, 6)\nif self.house.food <= 10:\n self.shopping()\nelif self.house.cat_food <= 10:\n self.shop_food_the_cat()\nelif self.fullness <= 20:\n self.eat()\nelif self.house.mud > 100:\n self.clean_house()\nelif dice == 1:\n self.clean_house()\nelif dice == 2:\n self.eat()\nelif dice == ... | <|body_start_0|>
dice = randint(1, 6)
if self.house.food <= 10:
self.shopping()
elif self.house.cat_food <= 10:
self.shop_food_the_cat()
elif self.fullness <= 20:
self.eat()
elif self.house.mud > 100:
self.clean_house()
elif... | класс жена | Wife | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wife:
"""класс жена"""
def act(self):
"""метод активности человека"""
<|body_0|>
def shopping(self):
"""метод поход в магазин"""
<|body_1|>
def shop_food_the_cat(self):
"""метод поход в магазин за едой для кота"""
<|body_2|>
def ... | stack_v2_sparse_classes_36k_train_006338 | 13,031 | no_license | [
{
"docstring": "метод активности человека",
"name": "act",
"signature": "def act(self)"
},
{
"docstring": "метод поход в магазин",
"name": "shopping",
"signature": "def shopping(self)"
},
{
"docstring": "метод поход в магазин за едой для кота",
"name": "shop_food_the_cat",
... | 5 | stack_v2_sparse_classes_30k_train_010679 | Implement the Python class `Wife` described below.
Class description:
класс жена
Method signatures and docstrings:
- def act(self): метод активности человека
- def shopping(self): метод поход в магазин
- def shop_food_the_cat(self): метод поход в магазин за едой для кота
- def buy_fur_coat(self): метод поход за шубой... | Implement the Python class `Wife` described below.
Class description:
класс жена
Method signatures and docstrings:
- def act(self): метод активности человека
- def shopping(self): метод поход в магазин
- def shop_food_the_cat(self): метод поход в магазин за едой для кота
- def buy_fur_coat(self): метод поход за шубой... | dd9edc250511941163034d9368a54db69b986fb0 | <|skeleton|>
class Wife:
"""класс жена"""
def act(self):
"""метод активности человека"""
<|body_0|>
def shopping(self):
"""метод поход в магазин"""
<|body_1|>
def shop_food_the_cat(self):
"""метод поход в магазин за едой для кота"""
<|body_2|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Wife:
"""класс жена"""
def act(self):
"""метод активности человека"""
dice = randint(1, 6)
if self.house.food <= 10:
self.shopping()
elif self.house.cat_food <= 10:
self.shop_food_the_cat()
elif self.fullness <= 20:
self.eat()
... | the_stack_v2_python_sparse | lesson_008/family_experiment.py | Fusy123/python_base | train | 0 |
b2bffcdfd97fda73918f9e1664140d0ee868882b | [
"def Serialize_Helper(root, string):\n if root == None:\n string += 'None,'\n else:\n string += root.val\n string = Serialize_Helper(root.left, string)\n string = Serialize_Helper(root.right, string)\n return string\nreturn Serialize_Helper(root, '')",
"string_to_list = data.s... | <|body_start_0|>
def Serialize_Helper(root, string):
if root == None:
string += 'None,'
else:
string += root.val
string = Serialize_Helper(root.left, string)
string = Serialize_Helper(root.right, string)
return s... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :return type: 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_train_006339 | 1,320 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :return type: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def dese... | 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 :return type: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :... | 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 :return type: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :... | a9b2de06306f3929a82ef4e6613c972e9a2c2200 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :return type: 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 :return type: str"""
def Serialize_Helper(root, string):
if root == None:
string += 'None,'
else:
string += root.val
string = Ser... | the_stack_v2_python_sparse | Array_Manipulations/Serialize_Deseralize_Binary_Tree.py | anantvir/Leetcode-Problems | train | 1 | |
c6d1edbffdfaa2b7b4e3f7aa576fee5e8b4c197b | [
"self.data_name = dataset_name\nself.normal_data: np.ndarray = healthy_data\nself.anomaly_data: np.ndarray = broken_data\nself.Y: np.ndarray = data_labels\nscaler = Preprocessing(scaler=DEFAULT_SCALER)\nself.normal_data = scaler.scale_data(data=self.normal_data)\nself.anomaly_data = scaler.scale_data(data=self.anom... | <|body_start_0|>
self.data_name = dataset_name
self.normal_data: np.ndarray = healthy_data
self.anomaly_data: np.ndarray = broken_data
self.Y: np.ndarray = data_labels
scaler = Preprocessing(scaler=DEFAULT_SCALER)
self.normal_data = scaler.scale_data(data=self.normal_data... | AbstractMlModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractMlModel:
def __init__(self, healthy_data: np.ndarray, broken_data: np.ndarray, data_labels: np.ndarray, dataset_name: str) -> None:
"""Abstract machine learning model for anomaly detection. Init the dataset, dataset shapes and pre-processing. :param healthy_data: Healthy data arr... | stack_v2_sparse_classes_36k_train_006340 | 2,912 | no_license | [
{
"docstring": "Abstract machine learning model for anomaly detection. Init the dataset, dataset shapes and pre-processing. :param healthy_data: Healthy data array :param broken_data: Data with anomalies array :param data_labels: Data labels array :param dataset_name: Unique dataset name for models",
"name"... | 3 | null | Implement the Python class `AbstractMlModel` described below.
Class description:
Implement the AbstractMlModel class.
Method signatures and docstrings:
- def __init__(self, healthy_data: np.ndarray, broken_data: np.ndarray, data_labels: np.ndarray, dataset_name: str) -> None: Abstract machine learning model for anoma... | Implement the Python class `AbstractMlModel` described below.
Class description:
Implement the AbstractMlModel class.
Method signatures and docstrings:
- def __init__(self, healthy_data: np.ndarray, broken_data: np.ndarray, data_labels: np.ndarray, dataset_name: str) -> None: Abstract machine learning model for anoma... | 322a27511eb5a270ad88b4e83e30c44bc8943369 | <|skeleton|>
class AbstractMlModel:
def __init__(self, healthy_data: np.ndarray, broken_data: np.ndarray, data_labels: np.ndarray, dataset_name: str) -> None:
"""Abstract machine learning model for anomaly detection. Init the dataset, dataset shapes and pre-processing. :param healthy_data: Healthy data arr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbstractMlModel:
def __init__(self, healthy_data: np.ndarray, broken_data: np.ndarray, data_labels: np.ndarray, dataset_name: str) -> None:
"""Abstract machine learning model for anomaly detection. Init the dataset, dataset shapes and pre-processing. :param healthy_data: Healthy data array :param brok... | the_stack_v2_python_sparse | PYTHON/AnomalyDetection/Models/MachineLearningModels/AbstractMlModel.py | dwisniewski1993/Machine-Learning | train | 4 | |
792bc9bd840a9fa56f57decf7e106d8c351e4614 | [
"w = AboutBox(None)\nyield w\nw.close()",
"assert isinstance(widget, QtWidgets.QWidget)\nassert widget.windowTitle() == 'About'\nassert widget.cmdOK.text() == 'OK'\nassert 'SasView' in widget.label_2.text()",
"version = widget.lblVersion\nassert isinstance(version, QtWidgets.QLabel)\nassert str(version.text()) ... | <|body_start_0|>
w = AboutBox(None)
yield w
w.close()
<|end_body_0|>
<|body_start_1|>
assert isinstance(widget, QtWidgets.QWidget)
assert widget.windowTitle() == 'About'
assert widget.cmdOK.text() == 'OK'
assert 'SasView' in widget.label_2.text()
<|end_body_1|>
... | Test the AboutBox | AboutBoxTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AboutBoxTest:
"""Test the AboutBox"""
def widget(self, qapp):
"""Create/Destroy the AboutBox"""
<|body_0|>
def testDefaults(self, widget):
"""Test the GUI in its default state"""
<|body_1|>
def testVersion(self, widget):
"""Assure the version... | stack_v2_sparse_classes_36k_train_006341 | 3,001 | permissive | [
{
"docstring": "Create/Destroy the AboutBox",
"name": "widget",
"signature": "def widget(self, qapp)"
},
{
"docstring": "Test the GUI in its default state",
"name": "testDefaults",
"signature": "def testDefaults(self, widget)"
},
{
"docstring": "Assure the version number is as ex... | 5 | stack_v2_sparse_classes_30k_train_004896 | Implement the Python class `AboutBoxTest` described below.
Class description:
Test the AboutBox
Method signatures and docstrings:
- def widget(self, qapp): Create/Destroy the AboutBox
- def testDefaults(self, widget): Test the GUI in its default state
- def testVersion(self, widget): Assure the version number is as e... | Implement the Python class `AboutBoxTest` described below.
Class description:
Test the AboutBox
Method signatures and docstrings:
- def widget(self, qapp): Create/Destroy the AboutBox
- def testDefaults(self, widget): Test the GUI in its default state
- def testVersion(self, widget): Assure the version number is as e... | 55b1e9f6db58e33729f2a93b7dd1d8bf255b46f7 | <|skeleton|>
class AboutBoxTest:
"""Test the AboutBox"""
def widget(self, qapp):
"""Create/Destroy the AboutBox"""
<|body_0|>
def testDefaults(self, widget):
"""Test the GUI in its default state"""
<|body_1|>
def testVersion(self, widget):
"""Assure the version... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AboutBoxTest:
"""Test the AboutBox"""
def widget(self, qapp):
"""Create/Destroy the AboutBox"""
w = AboutBox(None)
yield w
w.close()
def testDefaults(self, widget):
"""Test the GUI in its default state"""
assert isinstance(widget, QtWidgets.QWidget)
... | the_stack_v2_python_sparse | src/sas/qtgui/MainWindow/UnitTesting/AboutBoxTest.py | SasView/sasview | train | 48 |
ba28ecd2c4f99542cfa2330745801482f67ad76f | [
"item = Inventory('1234', 'Book', '$100', '$75')\nself.assertEqual('1234', item.product_code)\nself.assertEqual('Book', item.description)\nself.assertEqual('$100', item.market_price)\nself.assertEqual('$75', item.rental_price)",
"item = Inventory('1234', 'Book', '$100', '$75')\nitem_info = item.return_as_dictiona... | <|body_start_0|>
item = Inventory('1234', 'Book', '$100', '$75')
self.assertEqual('1234', item.product_code)
self.assertEqual('Book', item.description)
self.assertEqual('$100', item.market_price)
self.assertEqual('$75', item.rental_price)
<|end_body_0|>
<|body_start_1|>
... | Unit tests the Inventory class | InventoryTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InventoryTest:
"""Unit tests the Inventory class"""
def test_add_item(self):
"""creates an object of the inventory class"""
<|body_0|>
def test_return_dict(self):
"""calls the return_as_dictionary function on the inventory class"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_006342 | 10,292 | no_license | [
{
"docstring": "creates an object of the inventory class",
"name": "test_add_item",
"signature": "def test_add_item(self)"
},
{
"docstring": "calls the return_as_dictionary function on the inventory class",
"name": "test_return_dict",
"signature": "def test_return_dict(self)"
}
] | 2 | null | Implement the Python class `InventoryTest` described below.
Class description:
Unit tests the Inventory class
Method signatures and docstrings:
- def test_add_item(self): creates an object of the inventory class
- def test_return_dict(self): calls the return_as_dictionary function on the inventory class | Implement the Python class `InventoryTest` described below.
Class description:
Unit tests the Inventory class
Method signatures and docstrings:
- def test_add_item(self): creates an object of the inventory class
- def test_return_dict(self): calls the return_as_dictionary function on the inventory class
<|skeleton|>... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class InventoryTest:
"""Unit tests the Inventory class"""
def test_add_item(self):
"""creates an object of the inventory class"""
<|body_0|>
def test_return_dict(self):
"""calls the return_as_dictionary function on the inventory class"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InventoryTest:
"""Unit tests the Inventory class"""
def test_add_item(self):
"""creates an object of the inventory class"""
item = Inventory('1234', 'Book', '$100', '$75')
self.assertEqual('1234', item.product_code)
self.assertEqual('Book', item.description)
self.a... | the_stack_v2_python_sparse | students/David_Baylor/lesson01/Assignment/test_unit.py | JavaRod/SP_Python220B_2019 | train | 1 |
44e2ba43726040ee56c6fbf0798041758def5295 | [
"self.new_item = {}\nself.purchase_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\nself.items_list = ['initial']",
"new_item = Item()\nself.new_item = new_item.ItemDescription(item_sku, item_name, item_price, taxable)\nupdated_order = self.items_list.append(self.new_item)\nreturn updated_order"
] | <|body_start_0|>
self.new_item = {}
self.purchase_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.items_list = ['initial']
<|end_body_0|>
<|body_start_1|>
new_item = Item()
self.new_item = new_item.ItemDescription(item_sku, item_name, item_price, taxable)
... | CustomerOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerOrder:
def __init__(self):
"""Instantiate Order object"""
<|body_0|>
def AddItem(self, item_sku, item_name, item_price, taxable):
"""Create item description"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.new_item = {}
self.purc... | stack_v2_sparse_classes_36k_train_006343 | 1,220 | no_license | [
{
"docstring": "Instantiate Order object",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create item description",
"name": "AddItem",
"signature": "def AddItem(self, item_sku, item_name, item_price, taxable)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000458 | Implement the Python class `CustomerOrder` described below.
Class description:
Implement the CustomerOrder class.
Method signatures and docstrings:
- def __init__(self): Instantiate Order object
- def AddItem(self, item_sku, item_name, item_price, taxable): Create item description | Implement the Python class `CustomerOrder` described below.
Class description:
Implement the CustomerOrder class.
Method signatures and docstrings:
- def __init__(self): Instantiate Order object
- def AddItem(self, item_sku, item_name, item_price, taxable): Create item description
<|skeleton|>
class CustomerOrder:
... | b3886baac5cacae48251f98ec749b75da9e5b310 | <|skeleton|>
class CustomerOrder:
def __init__(self):
"""Instantiate Order object"""
<|body_0|>
def AddItem(self, item_sku, item_name, item_price, taxable):
"""Create item description"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomerOrder:
def __init__(self):
"""Instantiate Order object"""
self.new_item = {}
self.purchase_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.items_list = ['initial']
def AddItem(self, item_sku, item_name, item_price, taxable):
"""Create item... | the_stack_v2_python_sparse | Class_2018-12-18/Class_Order_New.py | YuliyaKoldayeva/AR_VR_Specialist_Program_Python | train | 0 | |
593463b05855cb3ebffac5c7ec4c9ca85eaba891 | [
"super().__init__()\nself._name = name\nself._queue = queue\nself.data_incoming = True",
"while self.data_incoming or len(self._queue):\n if not self._queue:\n logging.info('Consumer %d is sleeping since queue is empty', self._name)\n time.sleep(0.75)\n print(self._queue.get())\n time.sleep... | <|body_start_0|>
super().__init__()
self._name = name
self._queue = queue
self.data_incoming = True
<|end_body_0|>
<|body_start_1|>
while self.data_incoming or len(self._queue):
if not self._queue:
logging.info('Consumer %d is sleeping since queue is ... | The ConsumerThread is responsible for consuming data from the queue and printing it out to the console. | ConsumerThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsumerThread:
"""The ConsumerThread is responsible for consuming data from the queue and printing it out to the console."""
def __init__(self, queue: CityOverheadTimeQueue, name: int):
"""Initializes the ConsumerThread with the same queue as the one the producer has. It also implem... | stack_v2_sparse_classes_36k_train_006344 | 5,647 | no_license | [
{
"docstring": "Initializes the ConsumerThread with the same queue as the one the producer has. It also implements a data_incoming boolean attribute that is set to True. This attribute should change to False after the producer thread has joined the main thread and finished processing all the cities. :param queu... | 2 | stack_v2_sparse_classes_30k_train_009788 | Implement the Python class `ConsumerThread` described below.
Class description:
The ConsumerThread is responsible for consuming data from the queue and printing it out to the console.
Method signatures and docstrings:
- def __init__(self, queue: CityOverheadTimeQueue, name: int): Initializes the ConsumerThread with t... | Implement the Python class `ConsumerThread` described below.
Class description:
The ConsumerThread is responsible for consuming data from the queue and printing it out to the console.
Method signatures and docstrings:
- def __init__(self, queue: CityOverheadTimeQueue, name: int): Initializes the ConsumerThread with t... | 5fbc92a7ddd9103076a7095124b5ae108b002f03 | <|skeleton|>
class ConsumerThread:
"""The ConsumerThread is responsible for consuming data from the queue and printing it out to the console."""
def __init__(self, queue: CityOverheadTimeQueue, name: int):
"""Initializes the ConsumerThread with the same queue as the one the producer has. It also implem... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConsumerThread:
"""The ConsumerThread is responsible for consuming data from the queue and printing it out to the console."""
def __init__(self, queue: CityOverheadTimeQueue, name: int):
"""Initializes the ConsumerThread with the same queue as the one the producer has. It also implements a data_i... | the_stack_v2_python_sparse | Labs/Lab10/producer_consumer.py | pyopoly/3522_A00699267 | train | 0 |
e36b7e862c814d70c8af98a661a656d0da942d0f | [
"self.open = price\nself.close = price\nself.high = price\nself.low = price\nself.mode = mode\nself.pre_mode = pre_mode\nself.datatime = dt",
"if price > self.high:\n self.high = price\n self.close = price\n return\nif price < self.low:\n self.low = price\n self.close = price\n return\nself.clos... | <|body_start_0|>
self.open = price
self.close = price
self.high = price
self.low = price
self.mode = mode
self.pre_mode = pre_mode
self.datatime = dt
<|end_body_0|>
<|body_start_1|>
if price > self.high:
self.high = price
self.clos... | CTA 周期 | CtaPeriod | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CtaPeriod:
"""CTA 周期"""
def __init__(self, mode, price, pre_mode=PERIOD_INIT, dt=datetime.now()):
"""初始化函数"""
<|body_0|>
def onPrice(self, price):
"""更新周期的价格"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.open = price
self.close = ... | stack_v2_sparse_classes_36k_train_006345 | 1,333 | permissive | [
{
"docstring": "初始化函数",
"name": "__init__",
"signature": "def __init__(self, mode, price, pre_mode=PERIOD_INIT, dt=datetime.now())"
},
{
"docstring": "更新周期的价格",
"name": "onPrice",
"signature": "def onPrice(self, price)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001758 | Implement the Python class `CtaPeriod` described below.
Class description:
CTA 周期
Method signatures and docstrings:
- def __init__(self, mode, price, pre_mode=PERIOD_INIT, dt=datetime.now()): 初始化函数
- def onPrice(self, price): 更新周期的价格 | Implement the Python class `CtaPeriod` described below.
Class description:
CTA 周期
Method signatures and docstrings:
- def __init__(self, mode, price, pre_mode=PERIOD_INIT, dt=datetime.now()): 初始化函数
- def onPrice(self, price): 更新周期的价格
<|skeleton|>
class CtaPeriod:
"""CTA 周期"""
def __init__(self, mode, price,... | d7eed63cd39b1639058474cb724a8f64adbf6f97 | <|skeleton|>
class CtaPeriod:
"""CTA 周期"""
def __init__(self, mode, price, pre_mode=PERIOD_INIT, dt=datetime.now()):
"""初始化函数"""
<|body_0|>
def onPrice(self, price):
"""更新周期的价格"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CtaPeriod:
"""CTA 周期"""
def __init__(self, mode, price, pre_mode=PERIOD_INIT, dt=datetime.now()):
"""初始化函数"""
self.open = price
self.close = price
self.high = price
self.low = price
self.mode = mode
self.pre_mode = pre_mode
self.datatime = d... | the_stack_v2_python_sparse | vnpy/trader/app/ctaStrategy/ctaPeriod.py | iefuzzer/vnpy_crypto | train | 3 |
4e3e9e8730cfd84c5ebcbb0e960f2edca827b38f | [
"super(STSeqLabel, self).__init__()\nself.enc = StarTransEnc(embed=embed, hidden_size=hidden_size, num_layers=num_layers, num_head=num_head, head_dim=head_dim, max_len=max_len, emb_dropout=emb_dropout, dropout=dropout)\nself.cls = _Cls(hidden_size, num_cls, cls_hidden_size)",
"mask = seq_len_to_mask(seq_len)\nnod... | <|body_start_0|>
super(STSeqLabel, self).__init__()
self.enc = StarTransEnc(embed=embed, hidden_size=hidden_size, num_layers=num_layers, num_head=num_head, head_dim=head_dim, max_len=max_len, emb_dropout=emb_dropout, dropout=dropout)
self.cls = _Cls(hidden_size, num_cls, cls_hidden_size)
<|end_b... | 用于序列标注的Star-Transformer模型 | STSeqLabel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class STSeqLabel:
"""用于序列标注的Star-Transformer模型"""
def __init__(self, embed, num_cls, hidden_size=300, num_layers=4, num_head=8, head_dim=32, max_len=512, cls_hidden_size=600, emb_dropout=0.1, dropout=0.1):
""":param embed: 单词词典, 可以是 tuple, 包括(num_embedings, embedding_dim), 即 embedding的大小和每... | stack_v2_sparse_classes_36k_train_006346 | 11,601 | permissive | [
{
"docstring": ":param embed: 单词词典, 可以是 tuple, 包括(num_embedings, embedding_dim), 即 embedding的大小和每个词的维度. 也可以传入 nn.Embedding 对象, 此时就以传入的对象作为embedding :param num_cls: 输出类别个数 :param hidden_size: 模型中特征维度. Default: 300 :param num_layers: 模型层数. Default: 4 :param num_head: 模型中multi-head的head个数. Default: 8 :param head_d... | 3 | stack_v2_sparse_classes_30k_train_000956 | Implement the Python class `STSeqLabel` described below.
Class description:
用于序列标注的Star-Transformer模型
Method signatures and docstrings:
- def __init__(self, embed, num_cls, hidden_size=300, num_layers=4, num_head=8, head_dim=32, max_len=512, cls_hidden_size=600, emb_dropout=0.1, dropout=0.1): :param embed: 单词词典, 可以是 ... | Implement the Python class `STSeqLabel` described below.
Class description:
用于序列标注的Star-Transformer模型
Method signatures and docstrings:
- def __init__(self, embed, num_cls, hidden_size=300, num_layers=4, num_head=8, head_dim=32, max_len=512, cls_hidden_size=600, emb_dropout=0.1, dropout=0.1): :param embed: 单词词典, 可以是 ... | dffc7a06cdbff2671a3ca73d2398159d91a4a7db | <|skeleton|>
class STSeqLabel:
"""用于序列标注的Star-Transformer模型"""
def __init__(self, embed, num_cls, hidden_size=300, num_layers=4, num_head=8, head_dim=32, max_len=512, cls_hidden_size=600, emb_dropout=0.1, dropout=0.1):
""":param embed: 单词词典, 可以是 tuple, 包括(num_embedings, embedding_dim), 即 embedding的大小和每... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class STSeqLabel:
"""用于序列标注的Star-Transformer模型"""
def __init__(self, embed, num_cls, hidden_size=300, num_layers=4, num_head=8, head_dim=32, max_len=512, cls_hidden_size=600, emb_dropout=0.1, dropout=0.1):
""":param embed: 单词词典, 可以是 tuple, 包括(num_embedings, embedding_dim), 即 embedding的大小和每个词的维度. 也可以传入 ... | the_stack_v2_python_sparse | phenobert/utils/fastNLP/models/star_transformer.py | TianlabTech/PhenoBERT | train | 2 |
c851c9a22e38ca3d9fd3456fe4318a535643a750 | [
"for order in self.browse(cr, uid, ids, context=context):\n if not order.order_line:\n raise osv.except_osv(_('Error !'), _('You can not confirm the order without order lines.'))\n x = 0\n for line in order.order_line:\n if line.product_id.asset == True:\n x += 1\n if x > 0 and... | <|body_start_0|>
for order in self.browse(cr, uid, ids, context=context):
if not order.order_line:
raise osv.except_osv(_('Error !'), _('You can not confirm the order without order lines.'))
x = 0
for line in order.order_line:
if line.product_... | exchange_order | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class exchange_order:
def action_confirm_order(self, cr, uid, ids, context=None):
"""wf_service Changes order state to confirm. @return: True"""
<|body_0|>
def _prepare_order_picking(self, cr, uid, order, context=None):
"""Prepare the dict of values to create the new picki... | stack_v2_sparse_classes_36k_train_006347 | 14,719 | no_license | [
{
"docstring": "wf_service Changes order state to confirm. @return: True",
"name": "action_confirm_order",
"signature": "def action_confirm_order(self, cr, uid, ids, context=None)"
},
{
"docstring": "Prepare the dict of values to create the new picking for a exchange order. This method may be ov... | 2 | stack_v2_sparse_classes_30k_val_000511 | Implement the Python class `exchange_order` described below.
Class description:
Implement the exchange_order class.
Method signatures and docstrings:
- def action_confirm_order(self, cr, uid, ids, context=None): wf_service Changes order state to confirm. @return: True
- def _prepare_order_picking(self, cr, uid, order... | Implement the Python class `exchange_order` described below.
Class description:
Implement the exchange_order class.
Method signatures and docstrings:
- def action_confirm_order(self, cr, uid, ids, context=None): wf_service Changes order state to confirm. @return: True
- def _prepare_order_picking(self, cr, uid, order... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class exchange_order:
def action_confirm_order(self, cr, uid, ids, context=None):
"""wf_service Changes order state to confirm. @return: True"""
<|body_0|>
def _prepare_order_picking(self, cr, uid, order, context=None):
"""Prepare the dict of values to create the new picki... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class exchange_order:
def action_confirm_order(self, cr, uid, ids, context=None):
"""wf_service Changes order state to confirm. @return: True"""
for order in self.browse(cr, uid, ids, context=context):
if not order.order_line:
raise osv.except_osv(_('Error !'), _('You can... | the_stack_v2_python_sparse | v_7/NISS/shamil_v3/account_asset_custody_niss/stock.py | musabahmed/baba | train | 0 | |
968640ba38d60861290f3be920d73f2ccc6f1c13 | [
"assert isinstance(widths, int) or len(headings) == len(widths), 'Widths must match up to headings!'\nassert formatters is None or len(formatters) == len(headings), 'Must have same number of formatters as headings!'\nself.headings = headings\nself.symbol = symbol\nself.pad = pad\nif isinstance(widths, int):\n se... | <|body_start_0|>
assert isinstance(widths, int) or len(headings) == len(widths), 'Widths must match up to headings!'
assert formatters is None or len(formatters) == len(headings), 'Must have same number of formatters as headings!'
self.headings = headings
self.symbol = symbol
sel... | Table with header and columns. Nothing fancy. Class meant for simple column printing, e.g., printing updates for each iteration of an iterative algorithm. Attributes ========== headings : list List of strings giving column labels. symbol : str Character to use as separator between header and table rows. pad : int Numbe... | Table | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Table:
"""Table with header and columns. Nothing fancy. Class meant for simple column printing, e.g., printing updates for each iteration of an iterative algorithm. Attributes ========== headings : list List of strings giving column labels. symbol : str Character to use as separator between heade... | stack_v2_sparse_classes_36k_train_006348 | 3,278 | no_license | [
{
"docstring": "Initialize the table object. headings : list List of strings to use as headings for columns. widths : list or int List of widths for each column. formatters : list, optional List of format options to use for each column. pad : int, optional Space between columns symbol : str, optional Character ... | 3 | stack_v2_sparse_classes_30k_train_006532 | Implement the Python class `Table` described below.
Class description:
Table with header and columns. Nothing fancy. Class meant for simple column printing, e.g., printing updates for each iteration of an iterative algorithm. Attributes ========== headings : list List of strings giving column labels. symbol : str Char... | Implement the Python class `Table` described below.
Class description:
Table with header and columns. Nothing fancy. Class meant for simple column printing, e.g., printing updates for each iteration of an iterative algorithm. Attributes ========== headings : list List of strings giving column labels. symbol : str Char... | 08cb43dcf53fd6fddd3304e3514a608842310a34 | <|skeleton|>
class Table:
"""Table with header and columns. Nothing fancy. Class meant for simple column printing, e.g., printing updates for each iteration of an iterative algorithm. Attributes ========== headings : list List of strings giving column labels. symbol : str Character to use as separator between heade... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Table:
"""Table with header and columns. Nothing fancy. Class meant for simple column printing, e.g., printing updates for each iteration of an iterative algorithm. Attributes ========== headings : list List of strings giving column labels. symbol : str Character to use as separator between header and table r... | the_stack_v2_python_sparse | mr_utils/utils/printtable.py | zongjg/mr_utils | train | 0 |
a82b954550123140dc0dab113db482e303d3ecf6 | [
"self.maxEpochs = maxEpochs\nself.initAlpha = initAlpha\nself.power = power\npass",
"decay = (1 - epoch / float(self.maxEpochs)) ** self.power\nalpha = self.initAlpha * decay\nreturn float(alpha)"
] | <|body_start_0|>
self.maxEpochs = maxEpochs
self.initAlpha = initAlpha
self.power = power
pass
<|end_body_0|>
<|body_start_1|>
decay = (1 - epoch / float(self.maxEpochs)) ** self.power
alpha = self.initAlpha * decay
return float(alpha)
<|end_body_1|>
| PolynomialDecay | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PolynomialDecay:
def __init__(self, maxEpochs=100, initAlpha=0.01, power=1.0):
"""- initialize polynomial learning rate decay schedule with 3 args" - maxEpochs = # of training epochs; - initAlpha = initial learning rate; - power = power/exponent of the polynomial; linear if power=1.0, qu... | stack_v2_sparse_classes_36k_train_006349 | 2,358 | no_license | [
{
"docstring": "- initialize polynomial learning rate decay schedule with 3 args\" - maxEpochs = # of training epochs; - initAlpha = initial learning rate; - power = power/exponent of the polynomial; linear if power=1.0, quadratic if power=2.0, etc.",
"name": "__init__",
"signature": "def __init__(self,... | 2 | stack_v2_sparse_classes_30k_train_001487 | Implement the Python class `PolynomialDecay` described below.
Class description:
Implement the PolynomialDecay class.
Method signatures and docstrings:
- def __init__(self, maxEpochs=100, initAlpha=0.01, power=1.0): - initialize polynomial learning rate decay schedule with 3 args" - maxEpochs = # of training epochs; ... | Implement the Python class `PolynomialDecay` described below.
Class description:
Implement the PolynomialDecay class.
Method signatures and docstrings:
- def __init__(self, maxEpochs=100, initAlpha=0.01, power=1.0): - initialize polynomial learning rate decay schedule with 3 args" - maxEpochs = # of training epochs; ... | ebf5edb4d71f81dd9d8478c6251e97c097d189c3 | <|skeleton|>
class PolynomialDecay:
def __init__(self, maxEpochs=100, initAlpha=0.01, power=1.0):
"""- initialize polynomial learning rate decay schedule with 3 args" - maxEpochs = # of training epochs; - initAlpha = initial learning rate; - power = power/exponent of the polynomial; linear if power=1.0, qu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PolynomialDecay:
def __init__(self, maxEpochs=100, initAlpha=0.01, power=1.0):
"""- initialize polynomial learning rate decay schedule with 3 args" - maxEpochs = # of training epochs; - initAlpha = initial learning rate; - power = power/exponent of the polynomial; linear if power=1.0, quadratic if pow... | the_stack_v2_python_sparse | callbacks/learning_rate_scheduler.py | zlyin/Orca | train | 0 | |
6b6a689efc66fc7cb29bf730efd4bc836301da4b | [
"super().define(spec)\nspec.input('parent_folder', valid_type=orm.RemoteData, help='Output folder of a completed `PwCalculation`')\nspec.output('output_parameters', valid_type=orm.Dict, help='The `output_parameters` output node of the successful calculation.`')\nspec.output('eps', valid_type=orm.ArrayData, help='Th... | <|body_start_0|>
super().define(spec)
spec.input('parent_folder', valid_type=orm.RemoteData, help='Output folder of a completed `PwCalculation`')
spec.output('output_parameters', valid_type=orm.Dict, help='The `output_parameters` output node of the successful calculation.`')
spec.output(... | `CalcJob` implementation for the pw2gw.x code of Quantum ESPRESSO. | Pw2gwCalculation | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pw2gwCalculation:
"""`CalcJob` implementation for the pw2gw.x code of Quantum ESPRESSO."""
def define(cls, spec):
"""Define the process specification."""
<|body_0|>
def prepare_for_submission(self, folder):
"""Prepare the calculation job for submission by transfo... | stack_v2_sparse_classes_36k_train_006350 | 3,008 | permissive | [
{
"docstring": "Define the process specification.",
"name": "define",
"signature": "def define(cls, spec)"
},
{
"docstring": "Prepare the calculation job for submission by transforming input nodes into input files. In addition to the input files being written to the sandbox folder, a `CalcInfo` ... | 2 | stack_v2_sparse_classes_30k_train_012141 | Implement the Python class `Pw2gwCalculation` described below.
Class description:
`CalcJob` implementation for the pw2gw.x code of Quantum ESPRESSO.
Method signatures and docstrings:
- def define(cls, spec): Define the process specification.
- def prepare_for_submission(self, folder): Prepare the calculation job for ... | Implement the Python class `Pw2gwCalculation` described below.
Class description:
`CalcJob` implementation for the pw2gw.x code of Quantum ESPRESSO.
Method signatures and docstrings:
- def define(cls, spec): Define the process specification.
- def prepare_for_submission(self, folder): Prepare the calculation job for ... | 7263f92ccabcfc9f828b9da5473e1aefbc4b8eca | <|skeleton|>
class Pw2gwCalculation:
"""`CalcJob` implementation for the pw2gw.x code of Quantum ESPRESSO."""
def define(cls, spec):
"""Define the process specification."""
<|body_0|>
def prepare_for_submission(self, folder):
"""Prepare the calculation job for submission by transfo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pw2gwCalculation:
"""`CalcJob` implementation for the pw2gw.x code of Quantum ESPRESSO."""
def define(cls, spec):
"""Define the process specification."""
super().define(spec)
spec.input('parent_folder', valid_type=orm.RemoteData, help='Output folder of a completed `PwCalculation`'... | the_stack_v2_python_sparse | src/aiida_quantumespresso/calculations/pw2gw.py | aiidateam/aiida-quantumespresso | train | 56 |
a489b6ab06ffbb09b996c38f32380bf6d98d4ffc | [
"keys_to_remove = ['alpha', 'ori_alpha']\nfor key in keys_to_remove:\n for pipeline in list(self.cfg.test_pipeline):\n if 'key' in pipeline and key == pipeline['key']:\n self.cfg.test_pipeline.remove(pipeline)\n if 'keys' in pipeline and key in pipeline['keys']:\n pipeline['ke... | <|body_start_0|>
keys_to_remove = ['alpha', 'ori_alpha']
for key in keys_to_remove:
for pipeline in list(self.cfg.test_pipeline):
if 'key' in pipeline and key == pipeline['key']:
self.cfg.test_pipeline.remove(pipeline)
if 'keys' in pipeline... | inferencer that predicts with matting models. | MattingInferencer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MattingInferencer:
"""inferencer that predicts with matting models."""
def preprocess(self, img: InputsType, trimap: InputsType) -> Dict:
"""Process the inputs into a model-feedable format. Args: img(InputsType): Image to be processed by models. mask(InputsType): Mask corresponding t... | stack_v2_sparse_classes_36k_train_006351 | 3,627 | permissive | [
{
"docstring": "Process the inputs into a model-feedable format. Args: img(InputsType): Image to be processed by models. mask(InputsType): Mask corresponding to the input image. Returns: results(Dict): Results of preprocess.",
"name": "preprocess",
"signature": "def preprocess(self, img: InputsType, tri... | 4 | null | Implement the Python class `MattingInferencer` described below.
Class description:
inferencer that predicts with matting models.
Method signatures and docstrings:
- def preprocess(self, img: InputsType, trimap: InputsType) -> Dict: Process the inputs into a model-feedable format. Args: img(InputsType): Image to be pr... | Implement the Python class `MattingInferencer` described below.
Class description:
inferencer that predicts with matting models.
Method signatures and docstrings:
- def preprocess(self, img: InputsType, trimap: InputsType) -> Dict: Process the inputs into a model-feedable format. Args: img(InputsType): Image to be pr... | a382f143c0fd20d227e1e5524831ba26a568190d | <|skeleton|>
class MattingInferencer:
"""inferencer that predicts with matting models."""
def preprocess(self, img: InputsType, trimap: InputsType) -> Dict:
"""Process the inputs into a model-feedable format. Args: img(InputsType): Image to be processed by models. mask(InputsType): Mask corresponding t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MattingInferencer:
"""inferencer that predicts with matting models."""
def preprocess(self, img: InputsType, trimap: InputsType) -> Dict:
"""Process the inputs into a model-feedable format. Args: img(InputsType): Image to be processed by models. mask(InputsType): Mask corresponding to the input i... | the_stack_v2_python_sparse | mmagic/apis/inferencers/matting_inferencer.py | open-mmlab/mmagic | train | 1,370 |
35ffea7707574db758e73a8b1c25347fb2b8ea60 | [
"super(_ECELoss, self).__init__()\nbin_bounds = torch.linspace(0, 1, n_bins + 1)\nself.bin_lowers = bin_bounds[:-1]\nself.bin_uppers = bin_bounds[1:]",
"probs = F.softmax(logits / t, dim=1)\nconf, pred = torch.max(probs, 1)\nacc = pred.eq(labels)\nece = torch.zeros(1, device=logits.device)\nfor bin_lower, bin_upp... | <|body_start_0|>
super(_ECELoss, self).__init__()
bin_bounds = torch.linspace(0, 1, n_bins + 1)
self.bin_lowers = bin_bounds[:-1]
self.bin_uppers = bin_bounds[1:]
<|end_body_0|>
<|body_start_1|>
probs = F.softmax(logits / t, dim=1)
conf, pred = torch.max(probs, 1)
... | The Expected Calibration Error of a model. In each bin, compute the confidence gap: bin_gap = | avg_confidence_in_bin - accuracy_in_bin | Return a weighted average of the gaps, based on the number of samples in each bin. Reference: Naeini et al. "Obtaining Well Calibrated Probabilities Using Bayesian Binning." (2015) | _ECELoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ECELoss:
"""The Expected Calibration Error of a model. In each bin, compute the confidence gap: bin_gap = | avg_confidence_in_bin - accuracy_in_bin | Return a weighted average of the gaps, based on the number of samples in each bin. Reference: Naeini et al. "Obtaining Well Calibrated Probabiliti... | stack_v2_sparse_classes_36k_train_006352 | 11,010 | permissive | [
{
"docstring": "Args: n_bins: number of confidence interval bins (int)",
"name": "__init__",
"signature": "def __init__(self, n_bins=15)"
},
{
"docstring": "Args: logits: network output logits (not softmax probabilities) labels: ground truth labels t: temperature parameter Returns: ece value",
... | 2 | null | Implement the Python class `_ECELoss` described below.
Class description:
The Expected Calibration Error of a model. In each bin, compute the confidence gap: bin_gap = | avg_confidence_in_bin - accuracy_in_bin | Return a weighted average of the gaps, based on the number of samples in each bin. Reference: Naeini et al.... | Implement the Python class `_ECELoss` described below.
Class description:
The Expected Calibration Error of a model. In each bin, compute the confidence gap: bin_gap = | avg_confidence_in_bin - accuracy_in_bin | Return a weighted average of the gaps, based on the number of samples in each bin. Reference: Naeini et al.... | 4101cd742dacac6ce82ce0606f1c34480cf9e681 | <|skeleton|>
class _ECELoss:
"""The Expected Calibration Error of a model. In each bin, compute the confidence gap: bin_gap = | avg_confidence_in_bin - accuracy_in_bin | Return a weighted average of the gaps, based on the number of samples in each bin. Reference: Naeini et al. "Obtaining Well Calibrated Probabiliti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _ECELoss:
"""The Expected Calibration Error of a model. In each bin, compute the confidence gap: bin_gap = | avg_confidence_in_bin - accuracy_in_bin | Return a weighted average of the gaps, based on the number of samples in each bin. Reference: Naeini et al. "Obtaining Well Calibrated Probabilities Using Baye... | the_stack_v2_python_sparse | icenet/deep/losstools.py | mieskolainen/icenet | train | 1 |
a15b5e89dfdd0b20142621c03b5083e3b40953b7 | [
"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... | SessionManager | SessionManagerServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionManagerServicer:
"""SessionManager"""
def GetCookies(self, request, context):
"""GetCookies"""
<|body_0|>
def SetCookies(self, request, context):
"""SetCookies"""
<|body_1|>
def ClearCookies(self, request, context):
"""ClearCookies"""
... | stack_v2_sparse_classes_36k_train_006353 | 6,532 | no_license | [
{
"docstring": "GetCookies",
"name": "GetCookies",
"signature": "def GetCookies(self, request, context)"
},
{
"docstring": "SetCookies",
"name": "SetCookies",
"signature": "def SetCookies(self, request, context)"
},
{
"docstring": "ClearCookies",
"name": "ClearCookies",
"... | 3 | stack_v2_sparse_classes_30k_train_008839 | Implement the Python class `SessionManagerServicer` described below.
Class description:
SessionManager
Method signatures and docstrings:
- def GetCookies(self, request, context): GetCookies
- def SetCookies(self, request, context): SetCookies
- def ClearCookies(self, request, context): ClearCookies | Implement the Python class `SessionManagerServicer` described below.
Class description:
SessionManager
Method signatures and docstrings:
- def GetCookies(self, request, context): GetCookies
- def SetCookies(self, request, context): SetCookies
- def ClearCookies(self, request, context): ClearCookies
<|skeleton|>
clas... | dd8239ef668ebeb21f75753860faf6f08f71c95f | <|skeleton|>
class SessionManagerServicer:
"""SessionManager"""
def GetCookies(self, request, context):
"""GetCookies"""
<|body_0|>
def SetCookies(self, request, context):
"""SetCookies"""
<|body_1|>
def ClearCookies(self, request, context):
"""ClearCookies"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionManagerServicer:
"""SessionManager"""
def GetCookies(self, request, context):
"""GetCookies"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def SetCookies(sel... | the_stack_v2_python_sparse | src/chameleon/smelter/v1/crawl/session/service_pb2_grpc.py | Rinal-Dev02/VoilaCrawler3 | train | 0 |
a62603223a5b094fab78054ad5e96eb2c276dda1 | [
"if self.request.user.groups.filter(name=WELLS_EDIT_ROLE).exists():\n qs = Well.objects.all()\nelse:\n qs = Well.objects.all().exclude(well_publication_status='Unpublished')\nreturn qs",
"qs = self.get_queryset()\nlocations = self.filter_queryset(qs)\ncount = locations.count()\nif count > MAX_LOCATION_COUNT... | <|body_start_0|>
if self.request.user.groups.filter(name=WELLS_EDIT_ROLE).exists():
qs = Well.objects.all()
else:
qs = Well.objects.all().exclude(well_publication_status='Unpublished')
return qs
<|end_body_0|>
<|body_start_1|>
qs = self.get_queryset()
loc... | returns well locations for a given search get: returns a list of wells with locations only | WellLocationListAPIViewV1 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WellLocationListAPIViewV1:
"""returns well locations for a given search get: returns a list of wells with locations only"""
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permissions"""
<|body_0|>
def get(self, request, **kwargs):
""... | stack_v2_sparse_classes_36k_train_006354 | 32,335 | permissive | [
{
"docstring": "Excludes Unpublished wells for users without edit permissions",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "cancels request if too many wells are found",
"name": "get",
"signature": "def get(self, request, **kwargs)"
}
] | 2 | null | Implement the Python class `WellLocationListAPIViewV1` described below.
Class description:
returns well locations for a given search get: returns a list of wells with locations only
Method signatures and docstrings:
- def get_queryset(self): Excludes Unpublished wells for users without edit permissions
- def get(self... | Implement the Python class `WellLocationListAPIViewV1` described below.
Class description:
returns well locations for a given search get: returns a list of wells with locations only
Method signatures and docstrings:
- def get_queryset(self): Excludes Unpublished wells for users without edit permissions
- def get(self... | 6be3701a8e0085d0c6fa199b2672b7f9f1266a03 | <|skeleton|>
class WellLocationListAPIViewV1:
"""returns well locations for a given search get: returns a list of wells with locations only"""
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permissions"""
<|body_0|>
def get(self, request, **kwargs):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WellLocationListAPIViewV1:
"""returns well locations for a given search get: returns a list of wells with locations only"""
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permissions"""
if self.request.user.groups.filter(name=WELLS_EDIT_ROLE).exists():
... | the_stack_v2_python_sparse | app/backend/wells/views.py | bcgov/gwells | train | 39 |
72f8ba893736985521e157cf42d768137923168e | [
"if nnmodel is None:\n nnmodel = _construct_nn_model(input_size, hidden_size, n_layers, modeltype).to(torch.double)\nmodel = DFTXC(xcstr, nnmodel).to(device)\nself.xc = xcstr\nloss: Loss = L2Loss()\noutput_types = ['loss', 'predict']\nself.mode = mode\nsuper(XCModel, self).__init__(model, loss=loss, output_types... | <|body_start_0|>
if nnmodel is None:
nnmodel = _construct_nn_model(input_size, hidden_size, n_layers, modeltype).to(torch.double)
model = DFTXC(xcstr, nnmodel).to(device)
self.xc = xcstr
loss: Loss = L2Loss()
output_types = ['loss', 'predict']
self.mode = mode... | This class is used to initialize and run Differentiable Quantum Chemistry (i.e, DFT) calculations, using an exchange correlation functional that has been replaced by a neural network. This model is based on the paper "Learning the exchange-correlation functional from nature with fully differentiable density functional ... | XCModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XCModel:
"""This class is used to initialize and run Differentiable Quantum Chemistry (i.e, DFT) calculations, using an exchange correlation functional that has been replaced by a neural network. This model is based on the paper "Learning the exchange-correlation functional from nature with fully... | stack_v2_sparse_classes_36k_train_006355 | 9,553 | permissive | [
{
"docstring": "Parameters ---------- xcstr: str The choice of xc to use. nnmodel: torch.nn.Module the PyTorch model implementing the calculation input_size: int size of neural network input hidden_size: int size of the hidden layers ; the number of hidden layers is fixed in the default method. n_layers: int nu... | 2 | null | Implement the Python class `XCModel` described below.
Class description:
This class is used to initialize and run Differentiable Quantum Chemistry (i.e, DFT) calculations, using an exchange correlation functional that has been replaced by a neural network. This model is based on the paper "Learning the exchange-correl... | Implement the Python class `XCModel` described below.
Class description:
This class is used to initialize and run Differentiable Quantum Chemistry (i.e, DFT) calculations, using an exchange correlation functional that has been replaced by a neural network. This model is based on the paper "Learning the exchange-correl... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class XCModel:
"""This class is used to initialize and run Differentiable Quantum Chemistry (i.e, DFT) calculations, using an exchange correlation functional that has been replaced by a neural network. This model is based on the paper "Learning the exchange-correlation functional from nature with fully... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XCModel:
"""This class is used to initialize and run Differentiable Quantum Chemistry (i.e, DFT) calculations, using an exchange correlation functional that has been replaced by a neural network. This model is based on the paper "Learning the exchange-correlation functional from nature with fully differentiab... | the_stack_v2_python_sparse | deepchem/models/dft/dftxc.py | deepchem/deepchem | train | 4,876 |
c6e51edcf31c4b12d599fd9fa6f510140475f9fe | [
"super(pcsaft, self).__init__()\nself.eoslibinit_init_pcsaft = getattr(self.tp, self.get_export_name('eoslibinit', 'init_pcsaft'))\nself.s_get_kij = getattr(self.tp, self.get_export_name('saft_interface', 'pc_saft_get_kij'))\nself.s_set_kij = getattr(self.tp, self.get_export_name('saft_interface', 'pc_saft_set_kij_... | <|body_start_0|>
super(pcsaft, self).__init__()
self.eoslibinit_init_pcsaft = getattr(self.tp, self.get_export_name('eoslibinit', 'init_pcsaft'))
self.s_get_kij = getattr(self.tp, self.get_export_name('saft_interface', 'pc_saft_get_kij'))
self.s_set_kij = getattr(self.tp, self.get_export... | Interface to cubic | pcsaft | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pcsaft:
"""Interface to cubic"""
def __init__(self):
"""Initialize cubic specific function pointers"""
<|body_0|>
def init(self, comps, parameter_reference='Default'):
"""Initialize PC-SAFT model in thermopack Args: comps (str): Comma separated list of component ... | stack_v2_sparse_classes_36k_train_006356 | 3,488 | permissive | [
{
"docstring": "Initialize cubic specific function pointers",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Initialize PC-SAFT model in thermopack Args: comps (str): Comma separated list of component names parameter_reference (str, optional): Which parameters to use?. ... | 4 | stack_v2_sparse_classes_30k_test_000845 | Implement the Python class `pcsaft` described below.
Class description:
Interface to cubic
Method signatures and docstrings:
- def __init__(self): Initialize cubic specific function pointers
- def init(self, comps, parameter_reference='Default'): Initialize PC-SAFT model in thermopack Args: comps (str): Comma separat... | Implement the Python class `pcsaft` described below.
Class description:
Interface to cubic
Method signatures and docstrings:
- def __init__(self): Initialize cubic specific function pointers
- def init(self, comps, parameter_reference='Default'): Initialize PC-SAFT model in thermopack Args: comps (str): Comma separat... | dcec37ba9b38acd9a65dbb011483a16c2439706a | <|skeleton|>
class pcsaft:
"""Interface to cubic"""
def __init__(self):
"""Initialize cubic specific function pointers"""
<|body_0|>
def init(self, comps, parameter_reference='Default'):
"""Initialize PC-SAFT model in thermopack Args: comps (str): Comma separated list of component ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class pcsaft:
"""Interface to cubic"""
def __init__(self):
"""Initialize cubic specific function pointers"""
super(pcsaft, self).__init__()
self.eoslibinit_init_pcsaft = getattr(self.tp, self.get_export_name('eoslibinit', 'init_pcsaft'))
self.s_get_kij = getattr(self.tp, self.ge... | the_stack_v2_python_sparse | addon/pycThermopack/pyctp/pcsaft.py | ibell/thermopack | train | 3 |
fee56a9e7d36e28fdf15a818f94fe47cf8fcf4e5 | [
"self.jar_name = jar_name\nself.jar_path = jar_path\nself.jar_relative_path = jar_relative_path\nself.save_entities = save_entities",
"if dictionary is None:\n return None\njar_name = dictionary.get('jarName')\njar_path = dictionary.get('jarPath')\njar_relative_path = dictionary.get('jarRelativePath')\nsave_en... | <|body_start_0|>
self.jar_name = jar_name
self.jar_path = jar_path
self.jar_relative_path = jar_relative_path
self.save_entities = save_entities
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
jar_name = dictionary.get('jarName')
ja... | Implementation of the 'AnalyseJarArg' model. API to analyse a JAR file. This JAR may contain multiple mappers/reducers. Jar will be analysed and list of all mappers/reducers found in the jar will be returned. Attributes: jar_name (string): Name of the JAR to be analysed. jar_path (string): Path of the jar file. jar_rel... | AnalyseJarArg | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalyseJarArg:
"""Implementation of the 'AnalyseJarArg' model. API to analyse a JAR file. This JAR may contain multiple mappers/reducers. Jar will be analysed and list of all mappers/reducers found in the jar will be returned. Attributes: jar_name (string): Name of the JAR to be analysed. jar_pat... | stack_v2_sparse_classes_36k_train_006357 | 2,254 | permissive | [
{
"docstring": "Constructor for the AnalyseJarArg class",
"name": "__init__",
"signature": "def __init__(self, jar_name=None, jar_path=None, jar_relative_path=None, save_entities=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictio... | 2 | null | Implement the Python class `AnalyseJarArg` described below.
Class description:
Implementation of the 'AnalyseJarArg' model. API to analyse a JAR file. This JAR may contain multiple mappers/reducers. Jar will be analysed and list of all mappers/reducers found in the jar will be returned. Attributes: jar_name (string): ... | Implement the Python class `AnalyseJarArg` described below.
Class description:
Implementation of the 'AnalyseJarArg' model. API to analyse a JAR file. This JAR may contain multiple mappers/reducers. Jar will be analysed and list of all mappers/reducers found in the jar will be returned. Attributes: jar_name (string): ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class AnalyseJarArg:
"""Implementation of the 'AnalyseJarArg' model. API to analyse a JAR file. This JAR may contain multiple mappers/reducers. Jar will be analysed and list of all mappers/reducers found in the jar will be returned. Attributes: jar_name (string): Name of the JAR to be analysed. jar_pat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnalyseJarArg:
"""Implementation of the 'AnalyseJarArg' model. API to analyse a JAR file. This JAR may contain multiple mappers/reducers. Jar will be analysed and list of all mappers/reducers found in the jar will be returned. Attributes: jar_name (string): Name of the JAR to be analysed. jar_path (string): P... | the_stack_v2_python_sparse | cohesity_management_sdk/models/analyse_jar_arg.py | cohesity/management-sdk-python | train | 24 |
b225aef7d1ef536c468427e982daa0d4378d61ac | [
"Company = tables.Company\nCustomer = tables.Customer\nPlan = tables.Plan\nSubscription = tables.Subscription\nquery = self.session.query(Subscription)\nif isinstance(context, Plan):\n query = query.filter(Subscription.plan == context)\nelif isinstance(context, Customer):\n query = query.filter(Subscription.c... | <|body_start_0|>
Company = tables.Company
Customer = tables.Customer
Plan = tables.Plan
Subscription = tables.Subscription
query = self.session.query(Subscription)
if isinstance(context, Plan):
query = query.filter(Subscription.plan == context)
elif is... | SubscriptionModel | [
"MIT",
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscriptionModel:
def list_by_context(self, context):
"""List subscriptions by a given context"""
<|body_0|>
def create(self, customer, plan, funding_instrument_uri=None, started_at=None, external_id=None, appears_on_statement_as=None, amount=None):
"""Create a subs... | stack_v2_sparse_classes_36k_train_006358 | 7,280 | permissive | [
{
"docstring": "List subscriptions by a given context",
"name": "list_by_context",
"signature": "def list_by_context(self, context)"
},
{
"docstring": "Create a subscription and return its id",
"name": "create",
"signature": "def create(self, customer, plan, funding_instrument_uri=None, ... | 5 | null | Implement the Python class `SubscriptionModel` described below.
Class description:
Implement the SubscriptionModel class.
Method signatures and docstrings:
- def list_by_context(self, context): List subscriptions by a given context
- def create(self, customer, plan, funding_instrument_uri=None, started_at=None, exter... | Implement the Python class `SubscriptionModel` described below.
Class description:
Implement the SubscriptionModel class.
Method signatures and docstrings:
- def list_by_context(self, context): List subscriptions by a given context
- def create(self, customer, plan, funding_instrument_uri=None, started_at=None, exter... | a723c3aca18f817829ae088f469fabc5bea9d538 | <|skeleton|>
class SubscriptionModel:
def list_by_context(self, context):
"""List subscriptions by a given context"""
<|body_0|>
def create(self, customer, plan, funding_instrument_uri=None, started_at=None, external_id=None, appears_on_statement_as=None, amount=None):
"""Create a subs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubscriptionModel:
def list_by_context(self, context):
"""List subscriptions by a given context"""
Company = tables.Company
Customer = tables.Customer
Plan = tables.Plan
Subscription = tables.Subscription
query = self.session.query(Subscription)
if isins... | the_stack_v2_python_sparse | billy/models/subscription.py | grang5/billy | train | 0 | |
166e01d59ab41b7a1bc0e3e1ebd2ff273e943c2d | [
"\"\"\"\n 我的想法:\n Merge graph, 然後判斷此graph的toposort 是否唯一.\n\n a digraph has a unique topological ordering if and only if there is a\n (directed edge) between each pair of consecutive vertices in the\n topological order (i.e., the digraph has a Hamiltonian path).\n\n https://... | <|body_start_0|>
"""
我的想法:
Merge graph, 然後判斷此graph的toposort 是否唯一.
a digraph has a unique topological ordering if and only if there is a
(directed edge) between each pair of consecutive vertices in the
topological order (i.e., the d... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sequenceReconstruction(self, org, seqs):
""":type org: List[int] :type seqs: List[List[int]] :rtype: bool"""
<|body_0|>
def rewrite(self, org, seqs):
""":type org: List[int] :type seqs: List[List[int]] :rtype: bool"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_006359 | 3,721 | no_license | [
{
"docstring": ":type org: List[int] :type seqs: List[List[int]] :rtype: bool",
"name": "sequenceReconstruction",
"signature": "def sequenceReconstruction(self, org, seqs)"
},
{
"docstring": ":type org: List[int] :type seqs: List[List[int]] :rtype: bool",
"name": "rewrite",
"signature": ... | 2 | stack_v2_sparse_classes_30k_test_001028 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sequenceReconstruction(self, org, seqs): :type org: List[int] :type seqs: List[List[int]] :rtype: bool
- def rewrite(self, org, seqs): :type org: List[int] :type seqs: List[L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sequenceReconstruction(self, org, seqs): :type org: List[int] :type seqs: List[List[int]] :rtype: bool
- def rewrite(self, org, seqs): :type org: List[int] :type seqs: List[L... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def sequenceReconstruction(self, org, seqs):
""":type org: List[int] :type seqs: List[List[int]] :rtype: bool"""
<|body_0|>
def rewrite(self, org, seqs):
""":type org: List[int] :type seqs: List[List[int]] :rtype: bool"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sequenceReconstruction(self, org, seqs):
""":type org: List[int] :type seqs: List[List[int]] :rtype: bool"""
"""
我的想法:
Merge graph, 然後判斷此graph的toposort 是否唯一.
a digraph has a unique topological ordering if and only if there is a
... | the_stack_v2_python_sparse | graph/444_Sequence_Reconstruction.py | vsdrun/lc_public | train | 6 | |
b3f00a684cf1bf77cbdc3d085cd070125890186a | [
"data = self.cleaned_data['unlock_conditions']\nutils.validate_form_predicates(data)\nreturn data",
"data = self.cleaned_data['completion_conditions']\nutils.validate_form_predicates(data)\nreturn data"
] | <|body_start_0|>
data = self.cleaned_data['unlock_conditions']
utils.validate_form_predicates(data)
return data
<|end_body_0|>
<|body_start_1|>
data = self.cleaned_data['completion_conditions']
utils.validate_form_predicates(data)
return data
<|end_body_1|>
| admin form | QuestAdminForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestAdminForm:
"""admin form"""
def clean_unlock_conditions(self):
"""Validates the unlock conditions of the quest."""
<|body_0|>
def clean_completion_conditions(self):
"""Validates the unlock conditions of the quest."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_006360 | 1,146 | no_license | [
{
"docstring": "Validates the unlock conditions of the quest.",
"name": "clean_unlock_conditions",
"signature": "def clean_unlock_conditions(self)"
},
{
"docstring": "Validates the unlock conditions of the quest.",
"name": "clean_completion_conditions",
"signature": "def clean_completion... | 2 | null | Implement the Python class `QuestAdminForm` described below.
Class description:
admin form
Method signatures and docstrings:
- def clean_unlock_conditions(self): Validates the unlock conditions of the quest.
- def clean_completion_conditions(self): Validates the unlock conditions of the quest. | Implement the Python class `QuestAdminForm` described below.
Class description:
admin form
Method signatures and docstrings:
- def clean_unlock_conditions(self): Validates the unlock conditions of the quest.
- def clean_completion_conditions(self): Validates the unlock conditions of the quest.
<|skeleton|>
class Que... | dc27c9125e068eaf19cb1f179f8eb0ee6e914021 | <|skeleton|>
class QuestAdminForm:
"""admin form"""
def clean_unlock_conditions(self):
"""Validates the unlock conditions of the quest."""
<|body_0|>
def clean_completion_conditions(self):
"""Validates the unlock conditions of the quest."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestAdminForm:
"""admin form"""
def clean_unlock_conditions(self):
"""Validates the unlock conditions of the quest."""
data = self.cleaned_data['unlock_conditions']
utils.validate_form_predicates(data)
return data
def clean_completion_conditions(self):
"""Val... | the_stack_v2_python_sparse | makahiki/apps/widgets/quests/admin.py | gregorylburgess/makahiki | train | 0 |
9b26d6fbd196081dc66411ec59b0eba1117f9344 | [
"request = Request.query.filter_by(id=request_id).first()\nif not request:\n return abort(404, 'request_id not found')\nif request.user_id != g.user.id:\n return abort(401, 'Not have permisions !!!')\nitems = RequestBids.query.filter_by(request_id=request_id).all()\ndata = [item.to_json() for item in items]\n... | <|body_start_0|>
request = Request.query.filter_by(id=request_id).first()
if not request:
return abort(404, 'request_id not found')
if request.user_id != g.user.id:
return abort(401, 'Not have permisions !!!')
items = RequestBids.query.filter_by(request_id=request... | RequestsBidAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestsBidAPI:
def get(self, request_id):
"""get bids for request_id"""
<|body_0|>
def post(self, request_id):
"""post bid for request_id"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
request = Request.query.filter_by(id=request_id).first()
... | stack_v2_sparse_classes_36k_train_006361 | 4,039 | no_license | [
{
"docstring": "get bids for request_id",
"name": "get",
"signature": "def get(self, request_id)"
},
{
"docstring": "post bid for request_id",
"name": "post",
"signature": "def post(self, request_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006405 | Implement the Python class `RequestsBidAPI` described below.
Class description:
Implement the RequestsBidAPI class.
Method signatures and docstrings:
- def get(self, request_id): get bids for request_id
- def post(self, request_id): post bid for request_id | Implement the Python class `RequestsBidAPI` described below.
Class description:
Implement the RequestsBidAPI class.
Method signatures and docstrings:
- def get(self, request_id): get bids for request_id
- def post(self, request_id): post bid for request_id
<|skeleton|>
class RequestsBidAPI:
def get(self, reques... | 1c7d812e214590e0f4759e6c5be411bd64f8e3c4 | <|skeleton|>
class RequestsBidAPI:
def get(self, request_id):
"""get bids for request_id"""
<|body_0|>
def post(self, request_id):
"""post bid for request_id"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestsBidAPI:
def get(self, request_id):
"""get bids for request_id"""
request = Request.query.filter_by(id=request_id).first()
if not request:
return abort(404, 'request_id not found')
if request.user_id != g.user.id:
return abort(401, 'Not have permi... | the_stack_v2_python_sparse | apis/bids.py | ajutor-app/backend | train | 0 | |
731c11f79da3d7e938699e38ec2de56a54c0e750 | [
"ssn = self.cleaned_data['patient_social_security_number']\nif 0 == len(ssn):\n return ssn\nif not re.search('^\\\\d{9}$', ssn):\n raise forms.ValidationError('Must be a series of nine digits.')\nreturn ssn",
"num = self.cleaned_data['patient_phone_number']\nif not re.search('^\\\\d*$', num):\n raise for... | <|body_start_0|>
ssn = self.cleaned_data['patient_social_security_number']
if 0 == len(ssn):
return ssn
if not re.search('^\\d{9}$', ssn):
raise forms.ValidationError('Must be a series of nine digits.')
return ssn
<|end_body_0|>
<|body_start_1|>
num = sel... | A form which can be used to search for a ``Person`` object. | PatientSearchForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatientSearchForm:
"""A form which can be used to search for a ``Person`` object."""
def clean_patient_social_security_number(self):
"""Ensures that ``self.social_security_number`` is valid."""
<|body_0|>
def clean_patient_phone_number(self):
"""Ensures that ``se... | stack_v2_sparse_classes_36k_train_006362 | 6,850 | no_license | [
{
"docstring": "Ensures that ``self.social_security_number`` is valid.",
"name": "clean_patient_social_security_number",
"signature": "def clean_patient_social_security_number(self)"
},
{
"docstring": "Ensures that ``self.patient_phone_number`` is valid.",
"name": "clean_patient_phone_number... | 2 | stack_v2_sparse_classes_30k_train_014820 | Implement the Python class `PatientSearchForm` described below.
Class description:
A form which can be used to search for a ``Person`` object.
Method signatures and docstrings:
- def clean_patient_social_security_number(self): Ensures that ``self.social_security_number`` is valid.
- def clean_patient_phone_number(sel... | Implement the Python class `PatientSearchForm` described below.
Class description:
A form which can be used to search for a ``Person`` object.
Method signatures and docstrings:
- def clean_patient_social_security_number(self): Ensures that ``self.social_security_number`` is valid.
- def clean_patient_phone_number(sel... | 385eb9205d2fa6d0a26cfe8b699b499d712a0290 | <|skeleton|>
class PatientSearchForm:
"""A form which can be used to search for a ``Person`` object."""
def clean_patient_social_security_number(self):
"""Ensures that ``self.social_security_number`` is valid."""
<|body_0|>
def clean_patient_phone_number(self):
"""Ensures that ``se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PatientSearchForm:
"""A form which can be used to search for a ``Person`` object."""
def clean_patient_social_security_number(self):
"""Ensures that ``self.social_security_number`` is valid."""
ssn = self.cleaned_data['patient_social_security_number']
if 0 == len(ssn):
... | the_stack_v2_python_sparse | web/django/generic_project/mhs/models.py | Tianlap/impedimenta | train | 0 |
04bfd76893f6614a9426446a522c34e66c922464 | [
"self.availableOptions.update({'undelete': False})\nsuper(DeletionRobot, self).__init__(generator=generator, **kwargs)\nself.summary = summary",
"self.current_page = page\nif self.getOption('undelete'):\n page.undelete(self.summary)\nelif page.exists():\n page.delete(self.summary, not self.getOption('always... | <|body_start_0|>
self.availableOptions.update({'undelete': False})
super(DeletionRobot, self).__init__(generator=generator, **kwargs)
self.summary = summary
<|end_body_0|>
<|body_start_1|>
self.current_page = page
if self.getOption('undelete'):
page.undelete(self.sum... | This robot allows deletion of pages en masse. | DeletionRobot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeletionRobot:
"""This robot allows deletion of pages en masse."""
def __init__(self, generator, summary, **kwargs):
"""Constructor. @param generator: the pages to work on @type generator: iterable @param summary: the reason for the (un)deletion @type summary: unicode"""
<|bo... | stack_v2_sparse_classes_36k_train_006363 | 4,824 | permissive | [
{
"docstring": "Constructor. @param generator: the pages to work on @type generator: iterable @param summary: the reason for the (un)deletion @type summary: unicode",
"name": "__init__",
"signature": "def __init__(self, generator, summary, **kwargs)"
},
{
"docstring": "Delete one page from the g... | 2 | stack_v2_sparse_classes_30k_train_006210 | Implement the Python class `DeletionRobot` described below.
Class description:
This robot allows deletion of pages en masse.
Method signatures and docstrings:
- def __init__(self, generator, summary, **kwargs): Constructor. @param generator: the pages to work on @type generator: iterable @param summary: the reason fo... | Implement the Python class `DeletionRobot` described below.
Class description:
This robot allows deletion of pages en masse.
Method signatures and docstrings:
- def __init__(self, generator, summary, **kwargs): Constructor. @param generator: the pages to work on @type generator: iterable @param summary: the reason fo... | 2461ccc6d24153790a1b1c0378348f99997c4eca | <|skeleton|>
class DeletionRobot:
"""This robot allows deletion of pages en masse."""
def __init__(self, generator, summary, **kwargs):
"""Constructor. @param generator: the pages to work on @type generator: iterable @param summary: the reason for the (un)deletion @type summary: unicode"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeletionRobot:
"""This robot allows deletion of pages en masse."""
def __init__(self, generator, summary, **kwargs):
"""Constructor. @param generator: the pages to work on @type generator: iterable @param summary: the reason for the (un)deletion @type summary: unicode"""
self.availableOpt... | the_stack_v2_python_sparse | scripts/delete.py | speedydeletion/pywikibot | train | 1 |
341f3d0af4bfbe5bd52a39a782d76a4cc4f16da4 | [
"with open('../../extra-files/molecule.xyz', 'r') as file1:\n mol1 = Molecule(file1.read())\nself.assertEqual(mol1.units, 'Angstrom', 'checking units')\nself.assertEqual(mol1.natom, 3, 'checking natom')\nself.assertEqual(mol1.labels, ['O', 'H', 'H'], 'checking labels')\nself.assertEqual(mol1.masses, [15.99491461... | <|body_start_0|>
with open('../../extra-files/molecule.xyz', 'r') as file1:
mol1 = Molecule(file1.read())
self.assertEqual(mol1.units, 'Angstrom', 'checking units')
self.assertEqual(mol1.natom, 3, 'checking natom')
self.assertEqual(mol1.labels, ['O', 'H', 'H'], 'checking labe... | Tests for Molecule class in 'molecule.py' | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
"""Tests for Molecule class in 'molecule.py'"""
def test_self_variables(self):
"""Are the self variables (units, natom, masses, charges, geom) from the xyz file initialized correctly?"""
<|body_0|>
def test_copy_function(self):
"""Does the copy function cor... | stack_v2_sparse_classes_36k_train_006364 | 3,835 | no_license | [
{
"docstring": "Are the self variables (units, natom, masses, charges, geom) from the xyz file initialized correctly?",
"name": "test_self_variables",
"signature": "def test_self_variables(self)"
},
{
"docstring": "Does the copy function correctly initialize all variables of a new molecule? Also... | 5 | stack_v2_sparse_classes_30k_train_008783 | Implement the Python class `Test` described below.
Class description:
Tests for Molecule class in 'molecule.py'
Method signatures and docstrings:
- def test_self_variables(self): Are the self variables (units, natom, masses, charges, geom) from the xyz file initialized correctly?
- def test_copy_function(self): Does ... | Implement the Python class `Test` described below.
Class description:
Tests for Molecule class in 'molecule.py'
Method signatures and docstrings:
- def test_self_variables(self): Are the self variables (units, natom, masses, charges, geom) from the xyz file initialized correctly?
- def test_copy_function(self): Does ... | 2e8255ea548f13de6c492f649c4f2c4156f9995f | <|skeleton|>
class Test:
"""Tests for Molecule class in 'molecule.py'"""
def test_self_variables(self):
"""Are the self variables (units, natom, masses, charges, geom) from the xyz file initialized correctly?"""
<|body_0|>
def test_copy_function(self):
"""Does the copy function cor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
"""Tests for Molecule class in 'molecule.py'"""
def test_self_variables(self):
"""Are the self variables (units, natom, masses, charges, geom) from the xyz file initialized correctly?"""
with open('../../extra-files/molecule.xyz', 'r') as file1:
mol1 = Molecule(file1.rea... | the_stack_v2_python_sparse | 0/zachglick/test.py | CCQC/summer-program | train | 35 |
e93a7df706497b100a922b579631ee71f34cca5a | [
"if not root:\n return []\nstack, res = ([root], [])\nwhile stack:\n root = stack.pop()\n if root:\n res.append(root.val)\n if root.right:\n stack.append(root.right)\n if root.left:\n stack.append(root.left)\nreturn res",
"if not root:\n return []\nstack, res = ([], [])\nnod... | <|body_start_0|>
if not root:
return []
stack, res = ([root], [])
while stack:
root = stack.pop()
if root:
res.append(root.val)
if root.right:
stack.append(root.right)
if root.left:
stack.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def Preorder_Traversal(self, root):
"""前序遍历"""
<|body_0|>
def Midorder_Traversal(self, root):
"""中序遍历"""
<|body_1|>
def Postorder_Traversal(self, root):
"""后序遍历 非递归"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
if no... | stack_v2_sparse_classes_36k_train_006365 | 5,982 | no_license | [
{
"docstring": "前序遍历",
"name": "Preorder_Traversal",
"signature": "def Preorder_Traversal(self, root)"
},
{
"docstring": "中序遍历",
"name": "Midorder_Traversal",
"signature": "def Midorder_Traversal(self, root)"
},
{
"docstring": "后序遍历 非递归",
"name": "Postorder_Traversal",
"s... | 3 | stack_v2_sparse_classes_30k_train_021250 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def Preorder_Traversal(self, root): 前序遍历
- def Midorder_Traversal(self, root): 中序遍历
- def Postorder_Traversal(self, root): 后序遍历 非递归 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def Preorder_Traversal(self, root): 前序遍历
- def Midorder_Traversal(self, root): 中序遍历
- def Postorder_Traversal(self, root): 后序遍历 非递归
<|skeleton|>
class Solution:
def Preorde... | fc0ccfdf9e0825c14535aae328a1e532544e552a | <|skeleton|>
class Solution:
def Preorder_Traversal(self, root):
"""前序遍历"""
<|body_0|>
def Midorder_Traversal(self, root):
"""中序遍历"""
<|body_1|>
def Postorder_Traversal(self, root):
"""后序遍历 非递归"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def Preorder_Traversal(self, root):
"""前序遍历"""
if not root:
return []
stack, res = ([root], [])
while stack:
root = stack.pop()
if root:
res.append(root.val)
if root.right:
stack.append(ro... | the_stack_v2_python_sparse | my_Binary_tree_traversal.py | ZLZhangLi/my_write | train | 0 | |
1155b519a9a3255c0864d4760cad13aafd5602c2 | [
"if '_xml_ns' in kwargs:\n self._xml_ns = kwargs['_xml_ns']\nif '_xml_ns_key' in kwargs:\n self._xml_ns_key = kwargs['_xml_ns_key']\nself.index = index\nsuper(LSVertexType, self).__init__(Line=Line, Sample=Sample, **kwargs)",
"if array is None:\n return None\nif isinstance(array, (numpy.ndarray, list, tu... | <|body_start_0|>
if '_xml_ns' in kwargs:
self._xml_ns = kwargs['_xml_ns']
if '_xml_ns_key' in kwargs:
self._xml_ns_key = kwargs['_xml_ns_key']
self.index = index
super(LSVertexType, self).__init__(Line=Line, Sample=Sample, **kwargs)
<|end_body_0|>
<|body_start_1|... | An array element of LSType. | LSVertexType | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSVertexType:
"""An array element of LSType."""
def __init__(self, Line=None, Sample=None, index=None, **kwargs):
"""Parameters ---------- Line : float Sample : float index : int kwargs"""
<|body_0|>
def from_array(cls, array, index=1):
"""Create from an array ty... | stack_v2_sparse_classes_36k_train_006366 | 10,131 | permissive | [
{
"docstring": "Parameters ---------- Line : float Sample : float index : int kwargs",
"name": "__init__",
"signature": "def __init__(self, Line=None, Sample=None, index=None, **kwargs)"
},
{
"docstring": "Create from an array type entry. Parameters ---------- array: numpy.ndarray|list|tuple ass... | 2 | stack_v2_sparse_classes_30k_train_019718 | Implement the Python class `LSVertexType` described below.
Class description:
An array element of LSType.
Method signatures and docstrings:
- def __init__(self, Line=None, Sample=None, index=None, **kwargs): Parameters ---------- Line : float Sample : float index : int kwargs
- def from_array(cls, array, index=1): Cr... | Implement the Python class `LSVertexType` described below.
Class description:
An array element of LSType.
Method signatures and docstrings:
- def __init__(self, Line=None, Sample=None, index=None, **kwargs): Parameters ---------- Line : float Sample : float index : int kwargs
- def from_array(cls, array, index=1): Cr... | de1b1886f161a83b6c89aadc7a2c7cfc4892ef81 | <|skeleton|>
class LSVertexType:
"""An array element of LSType."""
def __init__(self, Line=None, Sample=None, index=None, **kwargs):
"""Parameters ---------- Line : float Sample : float index : int kwargs"""
<|body_0|>
def from_array(cls, array, index=1):
"""Create from an array ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LSVertexType:
"""An array element of LSType."""
def __init__(self, Line=None, Sample=None, index=None, **kwargs):
"""Parameters ---------- Line : float Sample : float index : int kwargs"""
if '_xml_ns' in kwargs:
self._xml_ns = kwargs['_xml_ns']
if '_xml_ns_key' in kwa... | the_stack_v2_python_sparse | sarpy/io/phase_history/cphd1_elements/blocks.py | ngageoint/sarpy | train | 192 |
c951f73f96301454fc411c406e052661ab7cd6d3 | [
"if model._meta.app_label == 'sample':\n return 'sample_db'\nreturn None",
"if model._meta.app_label == 'sample':\n return 'sample_db'\nreturn None",
"if obj1._meta.app_label == 'sample' or obj2._meta.app_label == 'sample':\n return True\nreturn None",
"if app_label == 'sample':\n return db == 'sa... | <|body_start_0|>
if model._meta.app_label == 'sample':
return 'sample_db'
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == 'sample':
return 'sample_db'
return None
<|end_body_1|>
<|body_start_2|>
if obj1._meta.app_label == 'sample'... | A router to control all database operations on models in the sample application. | MyAppRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyAppRouter:
"""A router to control all database operations on models in the sample application."""
def db_for_read(self, model, **hints):
"""Attempts to read sample models go to sample_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to writ... | stack_v2_sparse_classes_36k_train_006367 | 1,189 | no_license | [
{
"docstring": "Attempts to read sample models go to sample_db.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write sample models go to sample_db.",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hints)... | 4 | null | Implement the Python class `MyAppRouter` described below.
Class description:
A router to control all database operations on models in the sample application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read sample models go to sample_db.
- def db_for_write(self, model, **hin... | Implement the Python class `MyAppRouter` described below.
Class description:
A router to control all database operations on models in the sample application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read sample models go to sample_db.
- def db_for_write(self, model, **hin... | 5cb51fcf14458e456be3b04d2c545121ba605b91 | <|skeleton|>
class MyAppRouter:
"""A router to control all database operations on models in the sample application."""
def db_for_read(self, model, **hints):
"""Attempts to read sample models go to sample_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to writ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyAppRouter:
"""A router to control all database operations on models in the sample application."""
def db_for_read(self, model, **hints):
"""Attempts to read sample models go to sample_db."""
if model._meta.app_label == 'sample':
return 'sample_db'
return None
de... | the_stack_v2_python_sparse | MiniProjects/genApps/AppsEngines/sample/routers.py | bikash9449/craZyeXp | train | 2 |
75658ea67f44c79ba97ea1c742866fe35d048692 | [
"assert start > 0.0\nassert factor >= 1.0\nassert limit is None or limit >= 0.0\nself._start = start\nself._factor = factor\nself._limit = limit\nself._next = start",
"current = self._next\nif self._limit is None or self._next < self._limit:\n self._next = min(self._limit, self._next * self._factor)\nreturn cu... | <|body_start_0|>
assert start > 0.0
assert factor >= 1.0
assert limit is None or limit >= 0.0
self._start = start
self._factor = factor
self._limit = limit
self._next = start
<|end_body_0|>
<|body_start_1|>
current = self._next
if self._limit is N... | Calculator for increasing delays. | _RetryDelayCalculator | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _RetryDelayCalculator:
"""Calculator for increasing delays."""
def __init__(self, start, factor, limit):
"""Initializes this class. @type start: float @param start: Initial delay @type factor: float @param factor: Factor for delay increase @type limit: float or None @param limit: Upp... | stack_v2_sparse_classes_36k_train_006368 | 8,282 | permissive | [
{
"docstring": "Initializes this class. @type start: float @param start: Initial delay @type factor: float @param factor: Factor for delay increase @type limit: float or None @param limit: Upper limit for delay or None for no limit",
"name": "__init__",
"signature": "def __init__(self, start, factor, li... | 2 | stack_v2_sparse_classes_30k_train_011636 | Implement the Python class `_RetryDelayCalculator` described below.
Class description:
Calculator for increasing delays.
Method signatures and docstrings:
- def __init__(self, start, factor, limit): Initializes this class. @type start: float @param start: Initial delay @type factor: float @param factor: Factor for de... | Implement the Python class `_RetryDelayCalculator` described below.
Class description:
Calculator for increasing delays.
Method signatures and docstrings:
- def __init__(self, start, factor, limit): Initializes this class. @type start: float @param start: Initial delay @type factor: float @param factor: Factor for de... | 456ea285a7583183c2c8e5bcffe9006ec8a9d658 | <|skeleton|>
class _RetryDelayCalculator:
"""Calculator for increasing delays."""
def __init__(self, start, factor, limit):
"""Initializes this class. @type start: float @param start: Initial delay @type factor: float @param factor: Factor for delay increase @type limit: float or None @param limit: Upp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _RetryDelayCalculator:
"""Calculator for increasing delays."""
def __init__(self, start, factor, limit):
"""Initializes this class. @type start: float @param start: Initial delay @type factor: float @param factor: Factor for delay increase @type limit: float or None @param limit: Upper limit for ... | the_stack_v2_python_sparse | lib/utils/retry.py | ganeti/ganeti | train | 465 |
3244bf8ea0d56d10eea595fbe67aa8ccbe21fafd | [
"super(CollisionTest, self).__init__(name, actor, 0, None, optional, terminate_on_failure)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nworld = self.actor.get_world()\nblueprint = world.get_blueprint_library().find('sensor.other.collision')\nself._collision_sensor = world.spawn_actor(blueprint, ca... | <|body_start_0|>
super(CollisionTest, self).__init__(name, actor, 0, None, optional, terminate_on_failure)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
world = self.actor.get_world()
blueprint = world.get_blueprint_library().find('sensor.other.collision')
self._co... | This class contains an atomic test for collisions. Important parameters: - actor: CARLA actor to be used for this test - terminate_on_failure [optional]: If True, the complete scenario will terminate upon failure of this test - optional [optional]: If True, the result is not considered for an overall pass/fail result | CollisionTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollisionTest:
"""This class contains an atomic test for collisions. Important parameters: - actor: CARLA actor to be used for this test - terminate_on_failure [optional]: If True, the complete scenario will terminate upon failure of this test - optional [optional]: If True, the result is not con... | stack_v2_sparse_classes_36k_train_006369 | 44,616 | permissive | [
{
"docstring": "Construction with sensor setup",
"name": "__init__",
"signature": "def __init__(self, actor, optional=False, name='CheckCollisions', terminate_on_failure=False)"
},
{
"docstring": "Check collision count",
"name": "update",
"signature": "def update(self)"
},
{
"doc... | 4 | null | Implement the Python class `CollisionTest` described below.
Class description:
This class contains an atomic test for collisions. Important parameters: - actor: CARLA actor to be used for this test - terminate_on_failure [optional]: If True, the complete scenario will terminate upon failure of this test - optional [op... | Implement the Python class `CollisionTest` described below.
Class description:
This class contains an atomic test for collisions. Important parameters: - actor: CARLA actor to be used for this test - terminate_on_failure [optional]: If True, the complete scenario will terminate upon failure of this test - optional [op... | 8ab0894b92e1f994802a218002021ee075c405bf | <|skeleton|>
class CollisionTest:
"""This class contains an atomic test for collisions. Important parameters: - actor: CARLA actor to be used for this test - terminate_on_failure [optional]: If True, the complete scenario will terminate upon failure of this test - optional [optional]: If True, the result is not con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CollisionTest:
"""This class contains an atomic test for collisions. Important parameters: - actor: CARLA actor to be used for this test - terminate_on_failure [optional]: If True, the complete scenario will terminate upon failure of this test - optional [optional]: If True, the result is not considered for a... | the_stack_v2_python_sparse | carla_rllib/carla_rllib-prak_evaluator-carla_rllib-prak_evaluator/carla_rllib/prak_evaluator/srunner/scenarioconfigs/scenariomanager/scenarioatomics/atomic_criteria.py | TinaMenke/Deep-Reinforcement-Learning | train | 9 |
61a95ba036525853d05519c90d4f4611661258ba | [
"if tree_a is None and tree_b is None:\n return True\nelif tree_a is None:\n return False\nelif tree_b is None:\n return False\nelif tree_a.val != tree_b.val:\n return False\nelse:\n return self.is_mirror(tree_a.left, tree_b.right) and self.is_mirror(tree_a.right, tree_b.left)",
"if root is None:\n... | <|body_start_0|>
if tree_a is None and tree_b is None:
return True
elif tree_a is None:
return False
elif tree_b is None:
return False
elif tree_a.val != tree_b.val:
return False
else:
return self.is_mirror(tree_a.left, ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def is_mirror(self, tree_a, tree_b):
""">>> s = Solution() >>> two, three, four = TreeNode(2), TreeNode(3), TreeNode(4) >>> two.left, two.right = three, four >>> another_two, another_three, another_four = TreeNode(2), TreeNode(3), TreeNode(4) >>> another_two.left, another_two.r... | stack_v2_sparse_classes_36k_train_006370 | 1,400 | no_license | [
{
"docstring": ">>> s = Solution() >>> two, three, four = TreeNode(2), TreeNode(3), TreeNode(4) >>> two.left, two.right = three, four >>> another_two, another_three, another_four = TreeNode(2), TreeNode(3), TreeNode(4) >>> another_two.left, another_two.right = another_four, another_three >>> s.is_mirror(three, ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_mirror(self, tree_a, tree_b): >>> s = Solution() >>> two, three, four = TreeNode(2), TreeNode(3), TreeNode(4) >>> two.left, two.right = three, four >>> another_two, anothe... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_mirror(self, tree_a, tree_b): >>> s = Solution() >>> two, three, four = TreeNode(2), TreeNode(3), TreeNode(4) >>> two.left, two.right = three, four >>> another_two, anothe... | 3b13a02f9c8273f9794a57b948d2655792707f37 | <|skeleton|>
class Solution:
def is_mirror(self, tree_a, tree_b):
""">>> s = Solution() >>> two, three, four = TreeNode(2), TreeNode(3), TreeNode(4) >>> two.left, two.right = three, four >>> another_two, another_three, another_four = TreeNode(2), TreeNode(3), TreeNode(4) >>> another_two.left, another_two.r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def is_mirror(self, tree_a, tree_b):
""">>> s = Solution() >>> two, three, four = TreeNode(2), TreeNode(3), TreeNode(4) >>> two.left, two.right = three, four >>> another_two, another_three, another_four = TreeNode(2), TreeNode(3), TreeNode(4) >>> another_two.left, another_two.right = another... | the_stack_v2_python_sparse | symmetric_tree.py | gsy/leetcode | train | 1 | |
ea64eb63ac04835be326792af604086b89b9ac9c | [
"form = WithdrawForm(self.body_data())\nif not form.is_valid():\n print(form.errors)\n return self.json(ResultCode.CODE_40003.value, None, ResultMsg.MSG_40003.value)\nif not check_player_gold(self.request.player.token, form.data['value']):\n return self.json(ResultCode.CODE_40005.value, None, ResultMsg.MSG... | <|body_start_0|>
form = WithdrawForm(self.body_data())
if not form.is_valid():
print(form.errors)
return self.json(ResultCode.CODE_40003.value, None, ResultMsg.MSG_40003.value)
if not check_player_gold(self.request.player.token, form.data['value']):
return sel... | ClientWithdrawController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientWithdrawController:
def add(self):
"""@api {post} /three/finance/withdraw/add 提现申请 @apiVersion 1.0.0 @apiName withdraw_add @apiGroup Finance @apiParam (参数) {Number} value 兑换金额 @apiSuccessExample {json} 返回样例: { "code": 20000, "message": "Succeed", "data": {} }"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_006371 | 2,941 | no_license | [
{
"docstring": "@api {post} /three/finance/withdraw/add 提现申请 @apiVersion 1.0.0 @apiName withdraw_add @apiGroup Finance @apiParam (参数) {Number} value 兑换金额 @apiSuccessExample {json} 返回样例: { \"code\": 20000, \"message\": \"Succeed\", \"data\": {} }",
"name": "add",
"signature": "def add(self)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_020508 | Implement the Python class `ClientWithdrawController` described below.
Class description:
Implement the ClientWithdrawController class.
Method signatures and docstrings:
- def add(self): @api {post} /three/finance/withdraw/add 提现申请 @apiVersion 1.0.0 @apiName withdraw_add @apiGroup Finance @apiParam (参数) {Number} valu... | Implement the Python class `ClientWithdrawController` described below.
Class description:
Implement the ClientWithdrawController class.
Method signatures and docstrings:
- def add(self): @api {post} /three/finance/withdraw/add 提现申请 @apiVersion 1.0.0 @apiName withdraw_add @apiGroup Finance @apiParam (参数) {Number} valu... | a4cb2794d9a9c1ecfaa324a6ad0787a80db2c8ee | <|skeleton|>
class ClientWithdrawController:
def add(self):
"""@api {post} /three/finance/withdraw/add 提现申请 @apiVersion 1.0.0 @apiName withdraw_add @apiGroup Finance @apiParam (参数) {Number} value 兑换金额 @apiSuccessExample {json} 返回样例: { "code": 20000, "message": "Succeed", "data": {} }"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClientWithdrawController:
def add(self):
"""@api {post} /three/finance/withdraw/add 提现申请 @apiVersion 1.0.0 @apiName withdraw_add @apiGroup Finance @apiParam (参数) {Number} value 兑换金额 @apiSuccessExample {json} 返回样例: { "code": 20000, "message": "Succeed", "data": {} }"""
form = WithdrawForm(self.... | the_stack_v2_python_sparse | finance/api/client_withdraw.py | ydtg1993/shaibao-server-python | train | 0 | |
82bb39dbb7391161dd61f37312a2e56b4923b0f9 | [
"is_cloud_admin = self.helper.is_user_cloud_admin()\napps_user_is_admin_on = self.helper.get_owned_apps()\napp_name = self.request.get('appid')\nif not is_cloud_admin and app_name not in apps_user_is_admin_on:\n response = json.dumps({'error': True, 'message': 'Not authorized'})\n self.response.out.write(resp... | <|body_start_0|>
is_cloud_admin = self.helper.is_user_cloud_admin()
apps_user_is_admin_on = self.helper.get_owned_apps()
app_name = self.request.get('appid')
if not is_cloud_admin and app_name not in apps_user_is_admin_on:
response = json.dumps({'error': True, 'message': 'Not... | Class that returns request statistics in JSON relating to the number of requests an application gets per second. | RequestsStats | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestsStats:
"""Class that returns request statistics in JSON relating to the number of requests an application gets per second."""
def get(self):
"""Handler for GET request for the requests statistics."""
<|body_0|>
def fetch_request_info(app_id):
"""Fetches r... | stack_v2_sparse_classes_36k_train_006372 | 37,207 | permissive | [
{
"docstring": "Handler for GET request for the requests statistics.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Fetches request per second information from the datastore for a given application. Args: app_id: A str, the application identifier. Returns: A list of dictionarie... | 2 | stack_v2_sparse_classes_30k_train_021386 | Implement the Python class `RequestsStats` described below.
Class description:
Class that returns request statistics in JSON relating to the number of requests an application gets per second.
Method signatures and docstrings:
- def get(self): Handler for GET request for the requests statistics.
- def fetch_request_in... | Implement the Python class `RequestsStats` described below.
Class description:
Class that returns request statistics in JSON relating to the number of requests an application gets per second.
Method signatures and docstrings:
- def get(self): Handler for GET request for the requests statistics.
- def fetch_request_in... | aa36e8dfaa295d53bec616ed07f91ec8c02fa4e1 | <|skeleton|>
class RequestsStats:
"""Class that returns request statistics in JSON relating to the number of requests an application gets per second."""
def get(self):
"""Handler for GET request for the requests statistics."""
<|body_0|>
def fetch_request_info(app_id):
"""Fetches r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestsStats:
"""Class that returns request statistics in JSON relating to the number of requests an application gets per second."""
def get(self):
"""Handler for GET request for the requests statistics."""
is_cloud_admin = self.helper.is_user_cloud_admin()
apps_user_is_admin_on ... | the_stack_v2_python_sparse | AppDashboard/dashboard.py | shatterednirvana/appscale | train | 6 |
5df396206a05756d8a3349cdc1529a610f7b748b | [
"if values:\n queryset = LessonPlan.objects.order_by('book')\nreturn queryset",
"if values:\n books = values.split(',')\n queryset = LessonPlan.objects.filter(book__in=books)\nreturn queryset"
] | <|body_start_0|>
if values:
queryset = LessonPlan.objects.order_by('book')
return queryset
<|end_body_0|>
<|body_start_1|>
if values:
books = values.split(',')
queryset = LessonPlan.objects.filter(book__in=books)
return queryset
<|end_body_1|>
| LessonPlanFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LessonPlanFilter:
def filter_get_all(self, queryset, name, values):
"""Filtering all locations. :param queryset: :param name: - :param values: example - True, False :return:"""
<|body_0|>
def filter_book(self, queryset, name, values):
"""Filtering all locations. :par... | stack_v2_sparse_classes_36k_train_006373 | 25,200 | no_license | [
{
"docstring": "Filtering all locations. :param queryset: :param name: - :param values: example - True, False :return:",
"name": "filter_get_all",
"signature": "def filter_get_all(self, queryset, name, values)"
},
{
"docstring": "Filtering all locations. :param queryset: :param name: - :param va... | 2 | null | Implement the Python class `LessonPlanFilter` described below.
Class description:
Implement the LessonPlanFilter class.
Method signatures and docstrings:
- def filter_get_all(self, queryset, name, values): Filtering all locations. :param queryset: :param name: - :param values: example - True, False :return:
- def fil... | Implement the Python class `LessonPlanFilter` described below.
Class description:
Implement the LessonPlanFilter class.
Method signatures and docstrings:
- def filter_get_all(self, queryset, name, values): Filtering all locations. :param queryset: :param name: - :param values: example - True, False :return:
- def fil... | 3dab33b61f50c254d7c6d53add2b776a7e211cbb | <|skeleton|>
class LessonPlanFilter:
def filter_get_all(self, queryset, name, values):
"""Filtering all locations. :param queryset: :param name: - :param values: example - True, False :return:"""
<|body_0|>
def filter_book(self, queryset, name, values):
"""Filtering all locations. :par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LessonPlanFilter:
def filter_get_all(self, queryset, name, values):
"""Filtering all locations. :param queryset: :param name: - :param values: example - True, False :return:"""
if values:
queryset = LessonPlan.objects.order_by('book')
return queryset
def filter_book(se... | the_stack_v2_python_sparse | classapp/filters.py | promaster171019/Beacon | train | 0 | |
51090fa6641f4d07d527782c325f98819873d476 | [
"for t in self.rotationTests:\n point = Geometry.rotate(t[0][0], t[0][1], t[0][2], t[0][3], t[0][4])\n self.assertEqual(point, t[1])",
"for t in self.translationTests:\n point = Geometry.translate(t[0][0], t[0][1], t[0][2], t[0][3])\n self.assertEqual(point, t[1])",
"for t in self.scalingTests:\n ... | <|body_start_0|>
for t in self.rotationTests:
point = Geometry.rotate(t[0][0], t[0][1], t[0][2], t[0][3], t[0][4])
self.assertEqual(point, t[1])
<|end_body_0|>
<|body_start_1|>
for t in self.translationTests:
point = Geometry.translate(t[0][0], t[0][1], t[0][2], t[0]... | testGeometry | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class testGeometry:
def testRotation(self):
"""testing rotation primitive"""
<|body_0|>
def testTranslation(self):
"""testing translation primitive"""
<|body_1|>
def testScaling(self):
"""testing scaling primitive"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_006374 | 27,361 | no_license | [
{
"docstring": "testing rotation primitive",
"name": "testRotation",
"signature": "def testRotation(self)"
},
{
"docstring": "testing translation primitive",
"name": "testTranslation",
"signature": "def testTranslation(self)"
},
{
"docstring": "testing scaling primitive",
"na... | 3 | stack_v2_sparse_classes_30k_train_001145 | Implement the Python class `testGeometry` described below.
Class description:
Implement the testGeometry class.
Method signatures and docstrings:
- def testRotation(self): testing rotation primitive
- def testTranslation(self): testing translation primitive
- def testScaling(self): testing scaling primitive | Implement the Python class `testGeometry` described below.
Class description:
Implement the testGeometry class.
Method signatures and docstrings:
- def testRotation(self): testing rotation primitive
- def testTranslation(self): testing translation primitive
- def testScaling(self): testing scaling primitive
<|skelet... | d900f58f0ddc1891831b298d9b37fbe98193719d | <|skeleton|>
class testGeometry:
def testRotation(self):
"""testing rotation primitive"""
<|body_0|>
def testTranslation(self):
"""testing translation primitive"""
<|body_1|>
def testScaling(self):
"""testing scaling primitive"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class testGeometry:
def testRotation(self):
"""testing rotation primitive"""
for t in self.rotationTests:
point = Geometry.rotate(t[0][0], t[0][1], t[0][2], t[0][3], t[0][4])
self.assertEqual(point, t[1])
def testTranslation(self):
"""testing translation primitiv... | the_stack_v2_python_sparse | Assignment4/atom3/Kernel/GraphicEditor/testGraphics.py | pombreda/comp304 | train | 1 | |
d33e9b7374796119e3493f15c463e931585469cb | [
"for feature, value in vm.features.items():\n if not feature.startswith('service.'):\n continue\n service = feature[len('service.'):]\n vm.untrusted_qdb.write('/vanir-service/{}'.format(service), str(int(bool(value))))\nvm.untrusted_qdb.write('/vanir-service/meminfo-writer', '1' if vm.maxmem > 0 els... | <|body_start_0|>
for feature, value in vm.features.items():
if not feature.startswith('service.'):
continue
service = feature[len('service.'):]
vm.untrusted_qdb.write('/vanir-service/{}'.format(service), str(int(bool(value))))
vm.untrusted_qdb.write('/... | This extension export features with 'service.' prefix to VanirDB in /vanir-service/ tree. | ServicesExtension | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServicesExtension:
"""This extension export features with 'service.' prefix to VanirDB in /vanir-service/ tree."""
def on_domain_qdb_create(self, vm, event):
"""Actually export features"""
<|body_0|>
def on_domain_feature_set(self, vm, event, feature, value, oldvalue=Non... | stack_v2_sparse_classes_36k_train_006375 | 4,598 | permissive | [
{
"docstring": "Actually export features",
"name": "on_domain_qdb_create",
"signature": "def on_domain_qdb_create(self, vm, event)"
},
{
"docstring": "Update /vanir-service/ VanirDB tree in runtime",
"name": "on_domain_feature_set",
"signature": "def on_domain_feature_set(self, vm, event... | 5 | stack_v2_sparse_classes_30k_train_003094 | Implement the Python class `ServicesExtension` described below.
Class description:
This extension export features with 'service.' prefix to VanirDB in /vanir-service/ tree.
Method signatures and docstrings:
- def on_domain_qdb_create(self, vm, event): Actually export features
- def on_domain_feature_set(self, vm, eve... | Implement the Python class `ServicesExtension` described below.
Class description:
This extension export features with 'service.' prefix to VanirDB in /vanir-service/ tree.
Method signatures and docstrings:
- def on_domain_qdb_create(self, vm, event): Actually export features
- def on_domain_feature_set(self, vm, eve... | e6cb3e4e391e583e98d548292b5f272320d38cc4 | <|skeleton|>
class ServicesExtension:
"""This extension export features with 'service.' prefix to VanirDB in /vanir-service/ tree."""
def on_domain_qdb_create(self, vm, event):
"""Actually export features"""
<|body_0|>
def on_domain_feature_set(self, vm, event, feature, value, oldvalue=Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServicesExtension:
"""This extension export features with 'service.' prefix to VanirDB in /vanir-service/ tree."""
def on_domain_qdb_create(self, vm, event):
"""Actually export features"""
for feature, value in vm.features.items():
if not feature.startswith('service.'):
... | the_stack_v2_python_sparse | vanir/ext/services.py | VanirLab/VOS | train | 0 |
e0a53901534e449ecc180b8056d3ab5d78a028ac | [
"ds = data_util.get_color_mnist_dataset(split='test', batch_size=100, shuffle=False, drop_remainder=False, buffer_size=1000)\ndata_dict = data_util.get_ds_data(ds)\nself.assertEqual(data_dict['inputs'].shape, (10000, 32, 32, 3))\nself.assertEqual(data_dict['labels'].shape, (10000,))",
"inputs = np.ones((100, 5), ... | <|body_start_0|>
ds = data_util.get_color_mnist_dataset(split='test', batch_size=100, shuffle=False, drop_remainder=False, buffer_size=1000)
data_dict = data_util.get_ds_data(ds)
self.assertEqual(data_dict['inputs'].shape, (10000, 32, 32, 3))
self.assertEqual(data_dict['labels'].shape, (... | Tests data util functions. | TestDataUtilFunctions | [
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDataUtilFunctions:
"""Tests data util functions."""
def test_get_ds_data(self):
"""Tests get_ds_data function."""
<|body_0|>
def test_construct_dataset(self):
"""Tests construct_dataset function."""
<|body_1|>
def test_construct_sub_dataset(self)... | stack_v2_sparse_classes_36k_train_006376 | 6,224 | permissive | [
{
"docstring": "Tests get_ds_data function.",
"name": "test_get_ds_data",
"signature": "def test_get_ds_data(self)"
},
{
"docstring": "Tests construct_dataset function.",
"name": "test_construct_dataset",
"signature": "def test_construct_dataset(self)"
},
{
"docstring": "Tests co... | 3 | null | Implement the Python class `TestDataUtilFunctions` described below.
Class description:
Tests data util functions.
Method signatures and docstrings:
- def test_get_ds_data(self): Tests get_ds_data function.
- def test_construct_dataset(self): Tests construct_dataset function.
- def test_construct_sub_dataset(self): Te... | Implement the Python class `TestDataUtilFunctions` described below.
Class description:
Tests data util functions.
Method signatures and docstrings:
- def test_get_ds_data(self): Tests get_ds_data function.
- def test_construct_dataset(self): Tests construct_dataset function.
- def test_construct_sub_dataset(self): Te... | c1ae273841592fce4c993bf35cdd0a6424e73da4 | <|skeleton|>
class TestDataUtilFunctions:
"""Tests data util functions."""
def test_get_ds_data(self):
"""Tests get_ds_data function."""
<|body_0|>
def test_construct_dataset(self):
"""Tests construct_dataset function."""
<|body_1|>
def test_construct_sub_dataset(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDataUtilFunctions:
"""Tests data util functions."""
def test_get_ds_data(self):
"""Tests get_ds_data function."""
ds = data_util.get_color_mnist_dataset(split='test', batch_size=100, shuffle=False, drop_remainder=False, buffer_size=1000)
data_dict = data_util.get_ds_data(ds)
... | the_stack_v2_python_sparse | active_selective_prediction/utils/data_util_test.py | ishine/google-research | train | 0 |
61facdd6002d4a64240f621f884ef31cfb6d8596 | [
"if s == '':\n return 1\nif s[0] == '0':\n return 0\nways = 0\nif int(s[0]) != 0:\n ways += self._numDecodings(s[1:])\nif len(s) >= 2 and 1 <= int(s[0:2]) <= 26:\n ways += self._numDecodings(s[2:])\nreturn ways",
"if s == '':\n return 0\nreturn self._numDecodings(s)"
] | <|body_start_0|>
if s == '':
return 1
if s[0] == '0':
return 0
ways = 0
if int(s[0]) != 0:
ways += self._numDecodings(s[1:])
if len(s) >= 2 and 1 <= int(s[0:2]) <= 26:
ways += self._numDecodings(s[2:])
return ways
<|end_body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _numDecodings(self, s):
""":type s:str :rtype: int"""
<|body_0|>
def numDecodings(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if s == '':
return 1
if s[0] == '0':
... | stack_v2_sparse_classes_36k_train_006377 | 875 | no_license | [
{
"docstring": ":type s:str :rtype: int",
"name": "_numDecodings",
"signature": "def _numDecodings(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "numDecodings",
"signature": "def numDecodings(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009892 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _numDecodings(self, s): :type s:str :rtype: int
- def numDecodings(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 _numDecodings(self, s): :type s:str :rtype: int
- def numDecodings(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def _numDecodings(self, s):
"... | cd3900a7d91d1d94d308bc7a65533b8262781ee9 | <|skeleton|>
class Solution:
def _numDecodings(self, s):
""":type s:str :rtype: int"""
<|body_0|>
def numDecodings(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _numDecodings(self, s):
""":type s:str :rtype: int"""
if s == '':
return 1
if s[0] == '0':
return 0
ways = 0
if int(s[0]) != 0:
ways += self._numDecodings(s[1:])
if len(s) >= 2 and 1 <= int(s[0:2]) <= 26:
... | the_stack_v2_python_sparse | lc0091_DecodeWays/lc0091.py | cgi0911/LeetCodePractice | train | 0 | |
1b6f047e9ae92ee4b46bf17206fa5402cbab9305 | [
"self.signup('healer')\nresponse = self.rest_client.get(reverse('provider_setup_intro'))\nself.assertEqual(response.status_code, 200)\nresponse = self.rest_client.get(reverse('notes'))\nself.assertEqual(response.status_code, 302)",
"self.signup()\nresponse = self.rest_client.get(reverse('provider_setup_intro'))\n... | <|body_start_0|>
self.signup('healer')
response = self.rest_client.get(reverse('provider_setup_intro'))
self.assertEqual(response.status_code, 200)
response = self.rest_client.get(reverse('notes'))
self.assertEqual(response.status_code, 302)
<|end_body_0|>
<|body_start_1|>
... | SignupAccessTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignupAccessTest:
def test_healer_not_confirmed(self):
"""Only setup should be available for healers without confirmed emails on signup."""
<|body_0|>
def test_client_not_confirmed(self):
"""Clients should not login on signup if email is not confirmed."""
<|b... | stack_v2_sparse_classes_36k_train_006378 | 38,593 | no_license | [
{
"docstring": "Only setup should be available for healers without confirmed emails on signup.",
"name": "test_healer_not_confirmed",
"signature": "def test_healer_not_confirmed(self)"
},
{
"docstring": "Clients should not login on signup if email is not confirmed.",
"name": "test_client_not... | 2 | stack_v2_sparse_classes_30k_train_017500 | Implement the Python class `SignupAccessTest` described below.
Class description:
Implement the SignupAccessTest class.
Method signatures and docstrings:
- def test_healer_not_confirmed(self): Only setup should be available for healers without confirmed emails on signup.
- def test_client_not_confirmed(self): Clients... | Implement the Python class `SignupAccessTest` described below.
Class description:
Implement the SignupAccessTest class.
Method signatures and docstrings:
- def test_healer_not_confirmed(self): Only setup should be available for healers without confirmed emails on signup.
- def test_client_not_confirmed(self): Clients... | 681ef09e4044879840f7f0c8bccc836c3cffec3c | <|skeleton|>
class SignupAccessTest:
def test_healer_not_confirmed(self):
"""Only setup should be available for healers without confirmed emails on signup."""
<|body_0|>
def test_client_not_confirmed(self):
"""Clients should not login on signup if email is not confirmed."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignupAccessTest:
def test_healer_not_confirmed(self):
"""Only setup should be available for healers without confirmed emails on signup."""
self.signup('healer')
response = self.rest_client.get(reverse('provider_setup_intro'))
self.assertEqual(response.status_code, 200)
... | the_stack_v2_python_sparse | apps/account_hs/tests.py | RumorIO/healersource | train | 0 | |
f728758cfd23df13524a06782773f452d9dceaf2 | [
"url = info['url'] + '/BalanceActivity/Index'\nself.get_url(url)\ntime.sleep(2)\nself.click_element(WebYueBaoLocator.program_link)\ntime.sleep(2)\nself.find_element(WebYueBaoLocator.get_yuebao_program_loc(ac_name)).click()\ntime.sleep(1)\ndata = self.web_crawler_table_data(WebYueBaoLocator.table_loc)\nreturn data",... | <|body_start_0|>
url = info['url'] + '/BalanceActivity/Index'
self.get_url(url)
time.sleep(2)
self.click_element(WebYueBaoLocator.program_link)
time.sleep(2)
self.find_element(WebYueBaoLocator.get_yuebao_program_loc(ac_name)).click()
time.sleep(1)
data = s... | WebYueBao | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebYueBao:
def get_web_yuebao_testdata(self, ac_name, info):
""":return: 爬虫data"""
<|body_0|>
def min_amount_test(self, data):
"""小于最低金额test :return:"""
<|body_1|>
def max_amount_test(self, data):
"""超过最大选限额 :param data: :return:"""
<|bod... | stack_v2_sparse_classes_36k_train_006379 | 3,323 | no_license | [
{
"docstring": ":return: 爬虫data",
"name": "get_web_yuebao_testdata",
"signature": "def get_web_yuebao_testdata(self, ac_name, info)"
},
{
"docstring": "小于最低金额test :return:",
"name": "min_amount_test",
"signature": "def min_amount_test(self, data)"
},
{
"docstring": "超过最大选限额 :para... | 4 | null | Implement the Python class `WebYueBao` described below.
Class description:
Implement the WebYueBao class.
Method signatures and docstrings:
- def get_web_yuebao_testdata(self, ac_name, info): :return: 爬虫data
- def min_amount_test(self, data): 小于最低金额test :return:
- def max_amount_test(self, data): 超过最大选限额 :param data:... | Implement the Python class `WebYueBao` described below.
Class description:
Implement the WebYueBao class.
Method signatures and docstrings:
- def get_web_yuebao_testdata(self, ac_name, info): :return: 爬虫data
- def min_amount_test(self, data): 小于最低金额test :return:
- def max_amount_test(self, data): 超过最大选限额 :param data:... | 7e95a399140567ff601205f8d83babbe56279ab6 | <|skeleton|>
class WebYueBao:
def get_web_yuebao_testdata(self, ac_name, info):
""":return: 爬虫data"""
<|body_0|>
def min_amount_test(self, data):
"""小于最低金额test :return:"""
<|body_1|>
def max_amount_test(self, data):
"""超过最大选限额 :param data: :return:"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WebYueBao:
def get_web_yuebao_testdata(self, ac_name, info):
""":return: 爬虫data"""
url = info['url'] + '/BalanceActivity/Index'
self.get_url(url)
time.sleep(2)
self.click_element(WebYueBaoLocator.program_link)
time.sleep(2)
self.find_element(WebYueBaoLoc... | the_stack_v2_python_sparse | HC_At_Test/PO/pageaction/web_yuebao_action.py | fan966/LX_AT_TEST | train | 0 | |
f0843a41c841e4aa253e69e52108f76f2b915e5e | [
"viewManage.go_to_newtopic_page()\ntopicAction.add_topic('share', 'hello world', 'hello world')\ntitle_text = topicpage.title_text\nassert title_text == 'hello world'\ncontent_text = topicpage.content_text\nassert content_text == 'hello world'",
"viewManage.go_to_home_page()\nviewManage.go_to_user_center('testuse... | <|body_start_0|>
viewManage.go_to_newtopic_page()
topicAction.add_topic('share', 'hello world', 'hello world')
title_text = topicpage.title_text
assert title_text == 'hello world'
content_text = topicpage.content_text
assert content_text == 'hello world'
<|end_body_0|>
<... | TestTmp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTmp:
def test_newtopic(self):
"""测试创建话题 :return:"""
<|body_0|>
def test_updatetopic(self):
"""更新话题 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
viewManage.go_to_newtopic_page()
topicAction.add_topic('share', 'hello world', 'h... | stack_v2_sparse_classes_36k_train_006380 | 2,373 | no_license | [
{
"docstring": "测试创建话题 :return:",
"name": "test_newtopic",
"signature": "def test_newtopic(self)"
},
{
"docstring": "更新话题 :return:",
"name": "test_updatetopic",
"signature": "def test_updatetopic(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001508 | Implement the Python class `TestTmp` described below.
Class description:
Implement the TestTmp class.
Method signatures and docstrings:
- def test_newtopic(self): 测试创建话题 :return:
- def test_updatetopic(self): 更新话题 :return: | Implement the Python class `TestTmp` described below.
Class description:
Implement the TestTmp class.
Method signatures and docstrings:
- def test_newtopic(self): 测试创建话题 :return:
- def test_updatetopic(self): 更新话题 :return:
<|skeleton|>
class TestTmp:
def test_newtopic(self):
"""测试创建话题 :return:"""
... | 1b039bb5cf4b92b63a947dcb9f10531cbf847b66 | <|skeleton|>
class TestTmp:
def test_newtopic(self):
"""测试创建话题 :return:"""
<|body_0|>
def test_updatetopic(self):
"""更新话题 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestTmp:
def test_newtopic(self):
"""测试创建话题 :return:"""
viewManage.go_to_newtopic_page()
topicAction.add_topic('share', 'hello world', 'hello world')
title_text = topicpage.title_text
assert title_text == 'hello world'
content_text = topicpage.content_text
... | the_stack_v2_python_sparse | test_project/testcase/test_topics.py | jack-fjh/pytest_demo | train | 0 | |
3a84142477fa07677ab55d6c043d02e59ff16b57 | [
"if font_sizes is None:\n font_sizes = [28, 32, 34, 38, 42]\nself.dst = dst\nself.font_sizes = font_sizes\nself.image_w = image_w\nself.image_h = image_h\nself.line_len = line_len\nself.path_to_fonts = path_to_fonts\nself.path_to_texts = path_to_texts\nos.makedirs(os.path.join(dst, 'images'), exist_ok=True)\nos.... | <|body_start_0|>
if font_sizes is None:
font_sizes = [28, 32, 34, 38, 42]
self.dst = dst
self.font_sizes = font_sizes
self.image_w = image_w
self.image_h = image_h
self.line_len = line_len
self.path_to_fonts = path_to_fonts
self.path_to_texts =... | This class must create threads for all set of options | ImageFactoryForSSD | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageFactoryForSSD:
"""This class must create threads for all set of options"""
def __init__(self, image_w, image_h, line_len, dst, font_sizes=None, path_to_fonts='example/fonts', path_to_texts='example/text'):
""":param image_w: width of output image :param image_h: height of output... | stack_v2_sparse_classes_36k_train_006381 | 11,348 | no_license | [
{
"docstring": ":param image_w: width of output image :param image_h: height of output image :param line_len: max count of chars in image :param dst: path than image would be saves",
"name": "__init__",
"signature": "def __init__(self, image_w, image_h, line_len, dst, font_sizes=None, path_to_fonts='exa... | 3 | null | Implement the Python class `ImageFactoryForSSD` described below.
Class description:
This class must create threads for all set of options
Method signatures and docstrings:
- def __init__(self, image_w, image_h, line_len, dst, font_sizes=None, path_to_fonts='example/fonts', path_to_texts='example/text'): :param image_... | Implement the Python class `ImageFactoryForSSD` described below.
Class description:
This class must create threads for all set of options
Method signatures and docstrings:
- def __init__(self, image_w, image_h, line_len, dst, font_sizes=None, path_to_fonts='example/fonts', path_to_texts='example/text'): :param image_... | 40ac67fcc393b103f26ae9bae863d53050b89417 | <|skeleton|>
class ImageFactoryForSSD:
"""This class must create threads for all set of options"""
def __init__(self, image_w, image_h, line_len, dst, font_sizes=None, path_to_fonts='example/fonts', path_to_texts='example/text'):
""":param image_w: width of output image :param image_h: height of output... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageFactoryForSSD:
"""This class must create threads for all set of options"""
def __init__(self, image_w, image_h, line_len, dst, font_sizes=None, path_to_fonts='example/fonts', path_to_texts='example/text'):
""":param image_w: width of output image :param image_h: height of output image :param... | the_stack_v2_python_sparse | makiflow/generators/image_generator_for_ssd.py | Banayaki/MakiFlow | train | 0 |
b884b9757a3ec9e61e31ddcd4e78bc5faa139013 | [
"index1 = 0\nindex2 = 0\nremain1 = m\nremain2 = n\nwhile remain1 > 0 and remain2 > 0:\n if nums1[index1] > nums2[index2]:\n nums1[index1], nums2[index2] = (nums2[index2], nums1[index1])\n cur_index = index2\n while cur_index + 1 < n and nums2[cur_index] > nums2[cur_index + 1]:\n n... | <|body_start_0|>
index1 = 0
index2 = 0
remain1 = m
remain2 = n
while remain1 > 0 and remain2 > 0:
if nums1[index1] > nums2[index2]:
nums1[index1], nums2[index2] = (nums2[index2], nums1[index1])
cur_index = index2
while c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergev1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, mo... | stack_v2_sparse_classes_36k_train_006382 | 3,307 | no_license | [
{
"docstring": "Do not return anything, modify nums1 in-place instead.",
"name": "mergev1",
"signature": "def mergev1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None"
},
{
"docstring": "Do not return anything, modify nums1 in-place instead.",
"name": "merge",
"signature... | 2 | stack_v2_sparse_classes_30k_train_015294 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergev1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: Do not return anything, modify nums1 in-place instead.
- def merge(self, nums1: List[int], m: int, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergev1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: Do not return anything, modify nums1 in-place instead.
- def merge(self, nums1: List[int], m: int, ... | 4be6ebd7f75b0047999536a2b47a123bfd70cc6d | <|skeleton|>
class Solution:
def mergev1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, mo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergev1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, modify nums1 in-place instead."""
index1 = 0
index2 = 0
remain1 = m
remain2 = n
while remain1 > 0 and remain2 > 0:
if nums1[index1] > ... | the_stack_v2_python_sparse | python/sort_merge.py | yuanlang/algorithm-practise | train | 0 | |
4cffeb0d276b0d2a7af1024b43a3109c2962d901 | [
"json_state = json.loads(state_string)\nself.tick = json_state['tick']\nself.is_finished = json_state['isFinished']\nself.bombs = [Bomb(bomb_json) for bomb_json in json_state['bombs'].values()]\nself.bonuses = [Bonus(bonus_json) for bonus_json in json_state['bonuses'].values()]\nself.bounds = Bounds(json_state['wid... | <|body_start_0|>
json_state = json.loads(state_string)
self.tick = json_state['tick']
self.is_finished = json_state['isFinished']
self.bombs = [Bomb(bomb_json) for bomb_json in json_state['bombs'].values()]
self.bonuses = [Bonus(bonus_json) for bonus_json in json_state['bonuses']... | The complete game representation. Game Attributes: tiles: Represents the map in a numpy array. You can access any Tile with state.tiles[x, y] tick: The current game tick is_finished: whether or not the game is finished players: A list with all players in the game bombs: A list with all bombs in the game bonuses: A list... | State | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class State:
"""The complete game representation. Game Attributes: tiles: Represents the map in a numpy array. You can access any Tile with state.tiles[x, y] tick: The current game tick is_finished: whether or not the game is finished players: A list with all players in the game bombs: A list with all ... | stack_v2_sparse_classes_36k_train_006383 | 2,465 | permissive | [
{
"docstring": ":param state_string: A json string representing the state :param current_player_id: The id of the current player",
"name": "__init__",
"signature": "def __init__(self, state_string, current_player_id)"
},
{
"docstring": "A numpy array is not JSON serializable so we force it to a ... | 2 | stack_v2_sparse_classes_30k_train_009933 | Implement the Python class `State` described below.
Class description:
The complete game representation. Game Attributes: tiles: Represents the map in a numpy array. You can access any Tile with state.tiles[x, y] tick: The current game tick is_finished: whether or not the game is finished players: A list with all play... | Implement the Python class `State` described below.
Class description:
The complete game representation. Game Attributes: tiles: Represents the map in a numpy array. You can access any Tile with state.tiles[x, y] tick: The current game tick is_finished: whether or not the game is finished players: A list with all play... | 2d7bc38575031e1d5595d9a7070655115db9899b | <|skeleton|>
class State:
"""The complete game representation. Game Attributes: tiles: Represents the map in a numpy array. You can access any Tile with state.tiles[x, y] tick: The current game tick is_finished: whether or not the game is finished players: A list with all players in the game bombs: A list with all ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class State:
"""The complete game representation. Game Attributes: tiles: Represents the map in a numpy array. You can access any Tile with state.tiles[x, y] tick: The current game tick is_finished: whether or not the game is finished players: A list with all players in the game bombs: A list with all bombs in the ... | the_stack_v2_python_sparse | bot/models/state.py | Guillaume-Docquier/bomberjam-bot | train | 0 |
3b7f66843cd27a87ccaa35e7919fe1ded606c37b | [
"from ibc.client import InteractiveBrokersClient\nself.client: InteractiveBrokersClient = ib_client\nself.session: InteractiveBrokersSession = ib_session\nif self.client.accounts._has_portfolio_been_called:\n self._has_servers_been_called = True\nelse:\n print('Calling Accounts Endpoint, so we can pull data.'... | <|body_start_0|>
from ibc.client import InteractiveBrokersClient
self.client: InteractiveBrokersClient = ib_client
self.session: InteractiveBrokersSession = ib_session
if self.client.accounts._has_portfolio_been_called:
self._has_servers_been_called = True
else:
... | MarketData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MarketData:
def __init__(self, ib_client, ib_session: InteractiveBrokersSession) -> None:
"""Initializes the `MarketData` client. ### Parameters ---- ib_client : object The `InteractiveBrokersClient` Python Client. ib_session : InteractiveBrokersSession The IB session handler."""
... | stack_v2_sparse_classes_36k_train_006384 | 4,341 | permissive | [
{
"docstring": "Initializes the `MarketData` client. ### Parameters ---- ib_client : object The `InteractiveBrokersClient` Python Client. ib_session : InteractiveBrokersSession The IB session handler.",
"name": "__init__",
"signature": "def __init__(self, ib_client, ib_session: InteractiveBrokersSession... | 3 | null | Implement the Python class `MarketData` described below.
Class description:
Implement the MarketData class.
Method signatures and docstrings:
- def __init__(self, ib_client, ib_session: InteractiveBrokersSession) -> None: Initializes the `MarketData` client. ### Parameters ---- ib_client : object The `InteractiveBrok... | Implement the Python class `MarketData` described below.
Class description:
Implement the MarketData class.
Method signatures and docstrings:
- def __init__(self, ib_client, ib_session: InteractiveBrokersSession) -> None: Initializes the `MarketData` client. ### Parameters ---- ib_client : object The `InteractiveBrok... | a5b02ea914d6cd7683aff30cd38547e6150dc374 | <|skeleton|>
class MarketData:
def __init__(self, ib_client, ib_session: InteractiveBrokersSession) -> None:
"""Initializes the `MarketData` client. ### Parameters ---- ib_client : object The `InteractiveBrokersClient` Python Client. ib_session : InteractiveBrokersSession The IB session handler."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MarketData:
def __init__(self, ib_client, ib_session: InteractiveBrokersSession) -> None:
"""Initializes the `MarketData` client. ### Parameters ---- ib_client : object The `InteractiveBrokersClient` Python Client. ib_session : InteractiveBrokersSession The IB session handler."""
from ibc.clie... | the_stack_v2_python_sparse | ibc/rest/market_data.py | xuelee85/interactive-brokers-api | train | 0 | |
dcb3401a9110b7c3383f2bb9d596bd8f0e54e97d | [
"set_from_file_parser = generate_subparser(subparser, 'set-from-file', description=cls.description, help=cls.description, subcommand=True)\nset_from_file_parser.add_argument('--file', '-f', default=OUTPUTS_FILE, help='Path to the json file, relative to the current working directory')\nset_from_file_parser.add_argum... | <|body_start_0|>
set_from_file_parser = generate_subparser(subparser, 'set-from-file', description=cls.description, help=cls.description, subcommand=True)
set_from_file_parser.add_argument('--file', '-f', default=OUTPUTS_FILE, help='Path to the json file, relative to the current working directory')
... | OutputSetFromFileSubCommand | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutputSetFromFileSubCommand:
def setup_subparser(cls, subparser):
"""Setup: manage.py output set-from-file [options] Args: outputs (list): List of available output services"""
<|body_0|>
def handler(cls, options, config):
"""Configure multiple outputs for multiple se... | stack_v2_sparse_classes_36k_train_006385 | 19,044 | permissive | [
{
"docstring": "Setup: manage.py output set-from-file [options] Args: outputs (list): List of available output services",
"name": "setup_subparser",
"signature": "def setup_subparser(cls, subparser)"
},
{
"docstring": "Configure multiple outputs for multiple services Args: options (argparse.Name... | 3 | stack_v2_sparse_classes_30k_val_000193 | Implement the Python class `OutputSetFromFileSubCommand` described below.
Class description:
Implement the OutputSetFromFileSubCommand class.
Method signatures and docstrings:
- def setup_subparser(cls, subparser): Setup: manage.py output set-from-file [options] Args: outputs (list): List of available output services... | Implement the Python class `OutputSetFromFileSubCommand` described below.
Class description:
Implement the OutputSetFromFileSubCommand class.
Method signatures and docstrings:
- def setup_subparser(cls, subparser): Setup: manage.py output set-from-file [options] Args: outputs (list): List of available output services... | 75ba140d2e1aa6e903313d88326920adcb8bff45 | <|skeleton|>
class OutputSetFromFileSubCommand:
def setup_subparser(cls, subparser):
"""Setup: manage.py output set-from-file [options] Args: outputs (list): List of available output services"""
<|body_0|>
def handler(cls, options, config):
"""Configure multiple outputs for multiple se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutputSetFromFileSubCommand:
def setup_subparser(cls, subparser):
"""Setup: manage.py output set-from-file [options] Args: outputs (list): List of available output services"""
set_from_file_parser = generate_subparser(subparser, 'set-from-file', description=cls.description, help=cls.descriptio... | the_stack_v2_python_sparse | streamalert_cli/outputs/handler.py | avmi/streamalert | train | 0 | |
c32d095a167e07f80dab1d517246515fb238d896 | [
"action = self.request.get('action')\nif action == 'view_plans':\n page = self.request.get('p')\n order = self.request.get('order')\n self.viewPlans(page, order)\nelse:\n self.viewPlans('1', '')",
"template_data = Controller().loadPlans(page, order)\nmessage = self.request.get('m')\nif message == '' o... | <|body_start_0|>
action = self.request.get('action')
if action == 'view_plans':
page = self.request.get('p')
order = self.request.get('order')
self.viewPlans(page, order)
else:
self.viewPlans('1', '')
<|end_body_0|>
<|body_start_1|>
templa... | View | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
def get(self):
"""Handles GET requests"""
<|body_0|>
def viewPlans(self, page, order):
"""Loads a number of plans into a Plan list, and renders it to the HTML @param page: The current page from the pagination index. @param order: The order defined by the user t... | stack_v2_sparse_classes_36k_train_006386 | 5,552 | no_license | [
{
"docstring": "Handles GET requests",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Loads a number of plans into a Plan list, and renders it to the HTML @param page: The current page from the pagination index. @param order: The order defined by the user to show the plans.",
... | 2 | stack_v2_sparse_classes_30k_train_007423 | Implement the Python class `View` described below.
Class description:
Implement the View class.
Method signatures and docstrings:
- def get(self): Handles GET requests
- def viewPlans(self, page, order): Loads a number of plans into a Plan list, and renders it to the HTML @param page: The current page from the pagina... | Implement the Python class `View` described below.
Class description:
Implement the View class.
Method signatures and docstrings:
- def get(self): Handles GET requests
- def viewPlans(self, page, order): Loads a number of plans into a Plan list, and renders it to the HTML @param page: The current page from the pagina... | 95cc24e41590853cf0d2d35e6bf2ba1bd0701d48 | <|skeleton|>
class View:
def get(self):
"""Handles GET requests"""
<|body_0|>
def viewPlans(self, page, order):
"""Loads a number of plans into a Plan list, and renders it to the HTML @param page: The current page from the pagination index. @param order: The order defined by the user t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class View:
def get(self):
"""Handles GET requests"""
action = self.request.get('action')
if action == 'view_plans':
page = self.request.get('p')
order = self.request.get('order')
self.viewPlans(page, order)
else:
self.viewPlans('1', ''... | the_stack_v2_python_sparse | python/src/plan.py | cjlallana/gae-course-application | train | 0 | |
023776c9402f0f5915c2378c604e27879993da21 | [
"self.description = description\nself.domain = domain\nself.name = name\nself.nfs_access = nfs_access\nself.nfs_squash = nfs_squash",
"if dictionary is None:\n return None\ndescription = dictionary.get('description')\ndomain = dictionary.get('domain')\nname = dictionary.get('name')\nnfs_access = dictionary.get... | <|body_start_0|>
self.description = description
self.domain = domain
self.name = name
self.nfs_access = nfs_access
self.nfs_squash = nfs_squash
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
description = dictionary.get('descriptio... | Implementation of the 'NisNetgroup' model. Defines an NIS Netgroup. Attributes: description (string): Description of the netgroup. domain (string): Specifies the domain of the netgroup. name (string): Specifies the name of the netgroup. nfs_access (NfsAccessEnum): Specifies whether clients from this netgroup can mount ... | NisNetgroup | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NisNetgroup:
"""Implementation of the 'NisNetgroup' model. Defines an NIS Netgroup. Attributes: description (string): Description of the netgroup. domain (string): Specifies the domain of the netgroup. name (string): Specifies the name of the netgroup. nfs_access (NfsAccessEnum): Specifies whethe... | stack_v2_sparse_classes_36k_train_006387 | 2,471 | permissive | [
{
"docstring": "Constructor for the NisNetgroup class",
"name": "__init__",
"signature": "def __init__(self, description=None, domain=None, name=None, nfs_access=None, nfs_squash=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictio... | 2 | stack_v2_sparse_classes_30k_train_019898 | Implement the Python class `NisNetgroup` described below.
Class description:
Implementation of the 'NisNetgroup' model. Defines an NIS Netgroup. Attributes: description (string): Description of the netgroup. domain (string): Specifies the domain of the netgroup. name (string): Specifies the name of the netgroup. nfs_a... | Implement the Python class `NisNetgroup` described below.
Class description:
Implementation of the 'NisNetgroup' model. Defines an NIS Netgroup. Attributes: description (string): Description of the netgroup. domain (string): Specifies the domain of the netgroup. name (string): Specifies the name of the netgroup. nfs_a... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NisNetgroup:
"""Implementation of the 'NisNetgroup' model. Defines an NIS Netgroup. Attributes: description (string): Description of the netgroup. domain (string): Specifies the domain of the netgroup. name (string): Specifies the name of the netgroup. nfs_access (NfsAccessEnum): Specifies whethe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NisNetgroup:
"""Implementation of the 'NisNetgroup' model. Defines an NIS Netgroup. Attributes: description (string): Description of the netgroup. domain (string): Specifies the domain of the netgroup. name (string): Specifies the name of the netgroup. nfs_access (NfsAccessEnum): Specifies whether clients fro... | the_stack_v2_python_sparse | cohesity_management_sdk/models/nis_netgroup.py | cohesity/management-sdk-python | train | 24 |
fae9adb24fb62d04683dc0a59a4da54cffd3579e | [
"pygame.init()\nself.screen = pygame.display.set_mode((600, 400))\npygame.display.set_caption('Blue Sky')\nself.bg_color = (0, 0, 255)",
"while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n self.screen.fill(self.bg_color)\n pygame.display.flip()... | <|body_start_0|>
pygame.init()
self.screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption('Blue Sky')
self.bg_color = (0, 0, 255)
<|end_body_0|>
<|body_start_1|>
while True:
for event in pygame.event.get():
if event.type == pygame.QU... | Make a Pygame window with a blue background. | BlueSky | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlueSky:
"""Make a Pygame window with a blue background."""
def __init__(self):
"""Initialize game window."""
<|body_0|>
def run_game(self):
"""Start main loop for the game."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pygame.init()
s... | stack_v2_sparse_classes_36k_train_006388 | 996 | no_license | [
{
"docstring": "Initialize game window.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Start main loop for the game.",
"name": "run_game",
"signature": "def run_game(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006844 | Implement the Python class `BlueSky` described below.
Class description:
Make a Pygame window with a blue background.
Method signatures and docstrings:
- def __init__(self): Initialize game window.
- def run_game(self): Start main loop for the game. | Implement the Python class `BlueSky` described below.
Class description:
Make a Pygame window with a blue background.
Method signatures and docstrings:
- def __init__(self): Initialize game window.
- def run_game(self): Start main loop for the game.
<|skeleton|>
class BlueSky:
"""Make a Pygame window with a blue... | de8b257c1d69eb2a71dd95114f5f7adf58e00a53 | <|skeleton|>
class BlueSky:
"""Make a Pygame window with a blue background."""
def __init__(self):
"""Initialize game window."""
<|body_0|>
def run_game(self):
"""Start main loop for the game."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlueSky:
"""Make a Pygame window with a blue background."""
def __init__(self):
"""Initialize game window."""
pygame.init()
self.screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption('Blue Sky')
self.bg_color = (0, 0, 255)
def run_game(self):... | the_stack_v2_python_sparse | ch12_tryityourslef/blue_sky.py | thewchan/python_crash_course | train | 0 |
662423ab416d826e04f11ca0e33e718f6e0c9e1a | [
"self.sum = w[0:]\nif len(w) <= 0:\n return\nfor i in range(1, len(w)):\n self.sum[i] = self.sum[i - 1] + w[i]\nprint(self.sum)",
"import numpy as np\nrnd = np.random.randint(0, self.sum[-1])\nlow = 0\nhigh = len(self.sum) - 1\nwhile low < high:\n mid = low + (high - low) / 2\n if self.sum[mid] <= rnd... | <|body_start_0|>
self.sum = w[0:]
if len(w) <= 0:
return
for i in range(1, len(w)):
self.sum[i] = self.sum[i - 1] + w[i]
print(self.sum)
<|end_body_0|>
<|body_start_1|>
import numpy as np
rnd = np.random.randint(0, self.sum[-1])
low = 0
... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sum = w[0:]
if len(w) <= 0:
return
for i in range(1, len(w)):
... | stack_v2_sparse_classes_36k_train_006389 | 1,927 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015480 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution1:
def __init__(self, w):
""":type w: List[int]"""
... | 176cc1db3291843fb068f06d0180766dd8c3122c | <|skeleton|>
class Solution1:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution1:
def __init__(self, w):
""":type w: List[int]"""
self.sum = w[0:]
if len(w) <= 0:
return
for i in range(1, len(w)):
self.sum[i] = self.sum[i - 1] + w[i]
print(self.sum)
def pickIndex(self):
""":rtype: int"""
import ... | the_stack_v2_python_sparse | 2019/sampling/random_pick_with_weight_528.py | yehongyu/acode | train | 0 | |
c4556e2a68038e7946401ca5de43fdbd809a4b32 | [
"T = current.T\ncss_base = self.css_base\nattr = self.attr\ncss = attr.get('class')\nattr['_class'] = '%s %s' % (css, css_base) if css else css_base\ninput_class = '%s-%s' % (css_base, 'input')\ninput_labels = self.input_labels\ninput_elements = DIV(_class='range-filter')\nie_append = input_elements.append\n_id = a... | <|body_start_0|>
T = current.T
css_base = self.css_base
attr = self.attr
css = attr.get('class')
attr['_class'] = '%s %s' % (css, css_base) if css else css_base
input_class = '%s-%s' % (css_base, 'input')
input_labels = self.input_labels
input_elements = D... | Numerical Range Filter Widget Keyword Args: label: label for the widget comment: comment for the widget hidden: render widget initially hidden (="advanced" option) | RangeFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RangeFilter:
"""Numerical Range Filter Widget Keyword Args: label: label for the widget comment: comment for the widget hidden: render widget initially hidden (="advanced" option)"""
def widget(self, resource, values):
"""Render this widget as HTML helper object(s) Args: resource: th... | stack_v2_sparse_classes_36k_train_006390 | 13,916 | permissive | [
{
"docstring": "Render this widget as HTML helper object(s) Args: resource: the resource values: the search values from the URL query",
"name": "widget",
"signature": "def widget(self, resource, values)"
},
{
"docstring": "Overrides FilterWidget.data_element(), constructs multiple hidden INPUTs ... | 4 | null | Implement the Python class `RangeFilter` described below.
Class description:
Numerical Range Filter Widget Keyword Args: label: label for the widget comment: comment for the widget hidden: render widget initially hidden (="advanced" option)
Method signatures and docstrings:
- def widget(self, resource, values): Rende... | Implement the Python class `RangeFilter` described below.
Class description:
Numerical Range Filter Widget Keyword Args: label: label for the widget comment: comment for the widget hidden: render widget initially hidden (="advanced" option)
Method signatures and docstrings:
- def widget(self, resource, values): Rende... | 7ec4b959d009daf26d5ca6ce91dd9c3c0bd978d6 | <|skeleton|>
class RangeFilter:
"""Numerical Range Filter Widget Keyword Args: label: label for the widget comment: comment for the widget hidden: render widget initially hidden (="advanced" option)"""
def widget(self, resource, values):
"""Render this widget as HTML helper object(s) Args: resource: th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RangeFilter:
"""Numerical Range Filter Widget Keyword Args: label: label for the widget comment: comment for the widget hidden: render widget initially hidden (="advanced" option)"""
def widget(self, resource, values):
"""Render this widget as HTML helper object(s) Args: resource: the resource va... | the_stack_v2_python_sparse | modules/core/filters/valuerange.py | nursix/drkcm | train | 3 |
6d1ade42cf95114240d6495ed1d3a3f63324b763 | [
"form.save()\nusername = form.cleaned_data.get('username')\npassword = form.cleaned_data.get('password1')\nuser = authenticate(username=username, password=password)\nlogin(self.request, user)\nreturn redirect(self.success_url)",
"if self.request.user.is_authenticated:\n redirect_to = settings.LOGIN_REDIRECT_UR... | <|body_start_0|>
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=password)
login(self.request, user)
return redirect(self.success_url)
<|end_body_0|>
<|body_start_1|>
... | SignupView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignupView:
def form_valid(self, form):
"""Además de crear el usuario, iniciamos sesión con el usuario recién creado"""
<|body_0|>
def dispatch(self, request, *args, **kwargs):
"""Si el usuario ya está autenticado, lo redirecciona a la página de redirección configura... | stack_v2_sparse_classes_36k_train_006391 | 1,545 | permissive | [
{
"docstring": "Además de crear el usuario, iniciamos sesión con el usuario recién creado",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Si el usuario ya está autenticado, lo redirecciona a la página de redirección configurada para ir tras el login",
"na... | 2 | stack_v2_sparse_classes_30k_train_014835 | Implement the Python class `SignupView` described below.
Class description:
Implement the SignupView class.
Method signatures and docstrings:
- def form_valid(self, form): Además de crear el usuario, iniciamos sesión con el usuario recién creado
- def dispatch(self, request, *args, **kwargs): Si el usuario ya está au... | Implement the Python class `SignupView` described below.
Class description:
Implement the SignupView class.
Method signatures and docstrings:
- def form_valid(self, form): Además de crear el usuario, iniciamos sesión con el usuario recién creado
- def dispatch(self, request, *args, **kwargs): Si el usuario ya está au... | 5b065b84e91ebb92d0d2af3aab4cf754a3a3b51c | <|skeleton|>
class SignupView:
def form_valid(self, form):
"""Además de crear el usuario, iniciamos sesión con el usuario recién creado"""
<|body_0|>
def dispatch(self, request, *args, **kwargs):
"""Si el usuario ya está autenticado, lo redirecciona a la página de redirección configura... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignupView:
def form_valid(self, form):
"""Además de crear el usuario, iniciamos sesión con el usuario recién creado"""
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password... | the_stack_v2_python_sparse | src/users/views.py | tonybolanyo/wordplease | train | 0 | |
d9d143c05516988af8c916776de2ac5cf840a97f | [
"self.ecal_train = ecal_train\nself.hcal_train = hcal_train\nself.true_train = true_train\nif lim == -1:\n lim = max(ecal_train) + max(hcal_train)\nself.lim = lim\nself.numberPart = len(self.ecal_train)\nif len(self.hcal_train) != self.numberPart or len(self.true_train) != self.numberPart or len(self.hcal_train)... | <|body_start_0|>
self.ecal_train = ecal_train
self.hcal_train = hcal_train
self.true_train = true_train
if lim == -1:
lim = max(ecal_train) + max(hcal_train)
self.lim = lim
self.numberPart = len(self.ecal_train)
if len(self.hcal_train) != self.numberPa... | Mother Class to calibrate the true energy of a particle thanks to training datas. All claibrations have to inherit from this class. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value to train the calibration true_train : array ecal value to train the calibration lim... | Calibration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Calibration:
"""Mother Class to calibrate the true energy of a particle thanks to training datas. All claibrations have to inherit from this class. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value to train the calibration true_train : array ... | stack_v2_sparse_classes_36k_train_006392 | 4,045 | no_license | [
{
"docstring": "Constructor of the class Parameters ---------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value to train the calibration true_train : array ecal value to train the calibration lim : float if ecal + hcal > lim, the calibrated energy ecalib = math.nan if lim = -... | 4 | stack_v2_sparse_classes_30k_train_015549 | Implement the Python class `Calibration` described below.
Class description:
Mother Class to calibrate the true energy of a particle thanks to training datas. All claibrations have to inherit from this class. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value to tr... | Implement the Python class `Calibration` described below.
Class description:
Mother Class to calibrate the true energy of a particle thanks to training datas. All claibrations have to inherit from this class. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value to tr... | 53dbbd2e68986602c29008338d6c9cc96edc6d77 | <|skeleton|>
class Calibration:
"""Mother Class to calibrate the true energy of a particle thanks to training datas. All claibrations have to inherit from this class. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value to train the calibration true_train : array ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Calibration:
"""Mother Class to calibrate the true energy of a particle thanks to training datas. All claibrations have to inherit from this class. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value to train the calibration true_train : array ecal value to... | the_stack_v2_python_sparse | pfcalibration/Calibration.py | sniang/particle_flow_calibration | train | 3 |
a20f593fad0904572b3e6da8c97ac357915ce720 | [
"self._url = urlparse.urlparse(url)\nself.protocol = self._url.scheme\nself.timeout = timeout\nself.hostname = self._url.hostname\nself.port = self._url.port\nself.path = self._url.path\nself.query = self._url.query\nself.username = getattr(self._url, 'username', None)\nself.password = getattr(self._url, 'password'... | <|body_start_0|>
self._url = urlparse.urlparse(url)
self.protocol = self._url.scheme
self.timeout = timeout
self.hostname = self._url.hostname
self.port = self._url.port
self.path = self._url.path
self.query = self._url.query
self.username = getattr(self._... | Remote session handling to fetch XML interface content. | RemoteInterfaceSession | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteInterfaceSession:
"""Remote session handling to fetch XML interface content."""
def __init__(self, url, timeout=10):
"""Initialize a new remote session on ``url``. Raise an error if ``timeout` in seconds is reached. >>> session = RemoteInterfaceSession( "http://insalert.app.cor... | stack_v2_sparse_classes_36k_train_006393 | 6,030 | permissive | [
{
"docstring": "Initialize a new remote session on ``url``. Raise an error if ``timeout` in seconds is reached. >>> session = RemoteInterfaceSession( \"http://insalert.app.corp:80/insequence/Alert_USMSMSQL0001.xml\") >>> session.protocol 'http' >>> session.hostname 'insalert.app.corp' >>> session.port 80 >>> se... | 3 | stack_v2_sparse_classes_30k_train_016262 | Implement the Python class `RemoteInterfaceSession` described below.
Class description:
Remote session handling to fetch XML interface content.
Method signatures and docstrings:
- def __init__(self, url, timeout=10): Initialize a new remote session on ``url``. Raise an error if ``timeout` in seconds is reached. >>> s... | Implement the Python class `RemoteInterfaceSession` described below.
Class description:
Remote session handling to fetch XML interface content.
Method signatures and docstrings:
- def __init__(self, url, timeout=10): Initialize a new remote session on ``url``. Raise an error if ``timeout` in seconds is reached. >>> s... | 4a66d26f9d2982609489eaa0f57d6afb16aca37c | <|skeleton|>
class RemoteInterfaceSession:
"""Remote session handling to fetch XML interface content."""
def __init__(self, url, timeout=10):
"""Initialize a new remote session on ``url``. Raise an error if ``timeout` in seconds is reached. >>> session = RemoteInterfaceSession( "http://insalert.app.cor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RemoteInterfaceSession:
"""Remote session handling to fetch XML interface content."""
def __init__(self, url, timeout=10):
"""Initialize a new remote session on ``url``. Raise an error if ``timeout` in seconds is reached. >>> session = RemoteInterfaceSession( "http://insalert.app.corp:80/insequen... | the_stack_v2_python_sparse | plugin/plugins/jit/src/jit/session.py | crazy-canux/zplugin | train | 0 |
3775d1779fedc61c5ce12242becca5ce2182afb5 | [
"self.n_samples = n_samples\nself.ref_mask_feature = self._parse_features(ref_mask_feature, default_feature_type=FeatureType.MASK_TIMELESS)\nself.ref_labels = list(ref_labels)\nself.sample_features = self._parse_features(sample_features, new_names=True, rename_function='{}_SAMPLED'.format)\nself.return_new_eopatch ... | <|body_start_0|>
self.n_samples = n_samples
self.ref_mask_feature = self._parse_features(ref_mask_feature, default_feature_type=FeatureType.MASK_TIMELESS)
self.ref_labels = list(ref_labels)
self.sample_features = self._parse_features(sample_features, new_names=True, rename_function='{}_S... | Task for spatially sampling points from a time-series. This task performs random spatial sampling of a time-series based on a label mask. The user specifies the number of points to be sampled, the name of the `DATA` time-series, the name of the label raster image, and the name of the output sample features and sampled ... | PointSamplingTask | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointSamplingTask:
"""Task for spatially sampling points from a time-series. This task performs random spatial sampling of a time-series based on a label mask. The user specifies the number of points to be sampled, the name of the `DATA` time-series, the name of the label raster image, and the na... | stack_v2_sparse_classes_36k_train_006394 | 17,294 | permissive | [
{
"docstring": "Initialise sampling task. The data to be sampled is supposed to be a time-series stored in `DATA` type of the eopatch, while the raster image is supposed to be stored in `MASK_TIMELESS`. The output sampled features are stored in `DATA` and have shape T x N_SAMPLES x 1 x D, where T is the number ... | 2 | stack_v2_sparse_classes_30k_train_021464 | Implement the Python class `PointSamplingTask` described below.
Class description:
Task for spatially sampling points from a time-series. This task performs random spatial sampling of a time-series based on a label mask. The user specifies the number of points to be sampled, the name of the `DATA` time-series, the nam... | Implement the Python class `PointSamplingTask` described below.
Class description:
Task for spatially sampling points from a time-series. This task performs random spatial sampling of a time-series based on a label mask. The user specifies the number of points to be sampled, the name of the `DATA` time-series, the nam... | 148189e2b92e06059b87f223b596255ccafac86d | <|skeleton|>
class PointSamplingTask:
"""Task for spatially sampling points from a time-series. This task performs random spatial sampling of a time-series based on a label mask. The user specifies the number of points to be sampled, the name of the `DATA` time-series, the name of the label raster image, and the na... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PointSamplingTask:
"""Task for spatially sampling points from a time-series. This task performs random spatial sampling of a time-series based on a label mask. The user specifies the number of points to be sampled, the name of the `DATA` time-series, the name of the label raster image, and the name of the out... | the_stack_v2_python_sparse | geometry/eolearn/geometry/sampling.py | wouellette/eo-learn | train | 2 |
1407b79bae11296126d3315dc6cad2c635fed338 | [
"try:\n trajectory = self._node.outputs.output_trajectory\nexcept exceptions.NotExistent as exc:\n raise ValueError(f'{self._node} does not have the `output_trajectory` output node') from exc\ntry:\n scf_accuracy = trajectory.get_array('scf_accuracy')\nexcept KeyError as exc:\n raise ValueError(f'{traje... | <|body_start_0|>
try:
trajectory = self._node.outputs.output_trajectory
except exceptions.NotExistent as exc:
raise ValueError(f'{self._node} does not have the `output_trajectory` output node') from exc
try:
scf_accuracy = trajectory.get_array('scf_accuracy')
... | Calculation tools for `PwCalculation`. Methods implemented here are available on any `CalcJobNode` produced by the `PwCalculation class through the `tools` attribute. | PwCalculationTools | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PwCalculationTools:
"""Calculation tools for `PwCalculation`. Methods implemented here are available on any `CalcJobNode` produced by the `PwCalculation class through the `tools` attribute."""
def get_scf_accuracy(self, index=0):
"""Return the array of SCF accuracy values for a given... | stack_v2_sparse_classes_36k_train_006395 | 4,288 | permissive | [
{
"docstring": "Return the array of SCF accuracy values for a given SCF cycle. :param index: the zero-based index of the desired SCF cycle :return: a list of SCF accuracy values of a certain SCF cycle. :raises ValueError: if the node does not have the `output_trajectory` output :raises ValueError: if `output_tr... | 2 | stack_v2_sparse_classes_30k_train_011443 | Implement the Python class `PwCalculationTools` described below.
Class description:
Calculation tools for `PwCalculation`. Methods implemented here are available on any `CalcJobNode` produced by the `PwCalculation class through the `tools` attribute.
Method signatures and docstrings:
- def get_scf_accuracy(self, inde... | Implement the Python class `PwCalculationTools` described below.
Class description:
Calculation tools for `PwCalculation`. Methods implemented here are available on any `CalcJobNode` produced by the `PwCalculation class through the `tools` attribute.
Method signatures and docstrings:
- def get_scf_accuracy(self, inde... | 7263f92ccabcfc9f828b9da5473e1aefbc4b8eca | <|skeleton|>
class PwCalculationTools:
"""Calculation tools for `PwCalculation`. Methods implemented here are available on any `CalcJobNode` produced by the `PwCalculation class through the `tools` attribute."""
def get_scf_accuracy(self, index=0):
"""Return the array of SCF accuracy values for a given... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PwCalculationTools:
"""Calculation tools for `PwCalculation`. Methods implemented here are available on any `CalcJobNode` produced by the `PwCalculation class through the `tools` attribute."""
def get_scf_accuracy(self, index=0):
"""Return the array of SCF accuracy values for a given SCF cycle. :... | the_stack_v2_python_sparse | src/aiida_quantumespresso/tools/calculations/pw.py | aiidateam/aiida-quantumespresso | train | 56 |
670d56f84a4535cf9256c0b05751fa048c304f51 | [
"mes = {'message': 'success'}\nrole_name = kwargs.get('role_name', '')\ndb = orm_module.get_client()\nconn = orm_module.get_conn(table_name=cls.get_table_name(), db_client=db)\nwrite_concern = WriteConcern(w=1, j=True)\nwith db.start_session(causal_consistency=True) as ses:\n with ses.start_transaction(write_con... | <|body_start_0|>
mes = {'message': 'success'}
role_name = kwargs.get('role_name', '')
db = orm_module.get_client()
conn = orm_module.get_conn(table_name=cls.get_table_name(), db_client=db)
write_concern = WriteConcern(w=1, j=True)
with db.start_session(causal_consistency=... | 管理员的角色/权限组 | AdminRole | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminRole:
"""管理员的角色/权限组"""
def add(cls, **kwargs) -> dict:
"""添加角色 :param kwargs: :return:"""
<|body_0|>
def all_rules(cls) -> list:
"""查询所有的rule,不包括root :return:"""
<|body_1|>
def paging_info(cls, filter_dict: dict, page_index: int=1, page_size: in... | stack_v2_sparse_classes_36k_train_006396 | 13,255 | no_license | [
{
"docstring": "添加角色 :param kwargs: :return:",
"name": "add",
"signature": "def add(cls, **kwargs) -> dict"
},
{
"docstring": "查询所有的rule,不包括root :return:",
"name": "all_rules",
"signature": "def all_rules(cls) -> list"
},
{
"docstring": "分页查看角色信息 :param filter_dict: 过滤器,由用户的权限生成 ... | 3 | stack_v2_sparse_classes_30k_train_011019 | Implement the Python class `AdminRole` described below.
Class description:
管理员的角色/权限组
Method signatures and docstrings:
- def add(cls, **kwargs) -> dict: 添加角色 :param kwargs: :return:
- def all_rules(cls) -> list: 查询所有的rule,不包括root :return:
- def paging_info(cls, filter_dict: dict, page_index: int=1, page_size: int=10... | Implement the Python class `AdminRole` described below.
Class description:
管理员的角色/权限组
Method signatures and docstrings:
- def add(cls, **kwargs) -> dict: 添加角色 :param kwargs: :return:
- def all_rules(cls) -> list: 查询所有的rule,不包括root :return:
- def paging_info(cls, filter_dict: dict, page_index: int=1, page_size: int=10... | 3a2bdfd1598bfcdfe56386ec0c46fcede772cbfe | <|skeleton|>
class AdminRole:
"""管理员的角色/权限组"""
def add(cls, **kwargs) -> dict:
"""添加角色 :param kwargs: :return:"""
<|body_0|>
def all_rules(cls) -> list:
"""查询所有的rule,不包括root :return:"""
<|body_1|>
def paging_info(cls, filter_dict: dict, page_index: int=1, page_size: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdminRole:
"""管理员的角色/权限组"""
def add(cls, **kwargs) -> dict:
"""添加角色 :param kwargs: :return:"""
mes = {'message': 'success'}
role_name = kwargs.get('role_name', '')
db = orm_module.get_client()
conn = orm_module.get_conn(table_name=cls.get_table_name(), db_client=db... | the_stack_v2_python_sparse | Webchat_Server/module/admin_module.py | SYYDSN/py_projects | train | 0 |
884ac4685cc142b0ea1226e6d8f48b32c7fa6687 | [
"cnt = 0\nfor i in range(L, R + 1):\n if self.is_prime(str(bin(i)).count('1')):\n cnt += 1\nreturn cnt",
"if all((n % i for i in range(2, n))) and n > 1:\n return True\nelse:\n return False"
] | <|body_start_0|>
cnt = 0
for i in range(L, R + 1):
if self.is_prime(str(bin(i)).count('1')):
cnt += 1
return cnt
<|end_body_0|>
<|body_start_1|>
if all((n % i for i in range(2, n))) and n > 1:
return True
else:
return False
<|e... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countPrimeSetBits(self, L, R):
""":type L: int :type R: int :rtype: int"""
<|body_0|>
def is_prime(self, n):
"""Check whether n is a prime number"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cnt = 0
for i in range(L, R + 1):... | stack_v2_sparse_classes_36k_train_006397 | 525 | no_license | [
{
"docstring": ":type L: int :type R: int :rtype: int",
"name": "countPrimeSetBits",
"signature": "def countPrimeSetBits(self, L, R)"
},
{
"docstring": "Check whether n is a prime number",
"name": "is_prime",
"signature": "def is_prime(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008638 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimeSetBits(self, L, R): :type L: int :type R: int :rtype: int
- def is_prime(self, n): Check whether n is a prime number | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimeSetBits(self, L, R): :type L: int :type R: int :rtype: int
- def is_prime(self, n): Check whether n is a prime number
<|skeleton|>
class Solution:
def countPr... | 388a371cdd1f78a9bc181520088d65dd7e507801 | <|skeleton|>
class Solution:
def countPrimeSetBits(self, L, R):
""":type L: int :type R: int :rtype: int"""
<|body_0|>
def is_prime(self, n):
"""Check whether n is a prime number"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countPrimeSetBits(self, L, R):
""":type L: int :type R: int :rtype: int"""
cnt = 0
for i in range(L, R + 1):
if self.is_prime(str(bin(i)).count('1')):
cnt += 1
return cnt
def is_prime(self, n):
"""Check whether n is a prime... | the_stack_v2_python_sparse | primeNumberOfSetBits_762.py | qiliu6767/leetcode | train | 0 | |
3539d4764d13a5ec7a453f1a199694057ec9d3c9 | [
"Block.__init__(self, parent, idevice)\nself.flashElement = FlashElement(idevice.flash)\nself.textElement = TextAreaElement(idevice.text)",
"log.debug('process ' + repr(request.args))\nBlock.process(self, request)\nif u'action' not in request.args or request.args[u'action'][0] != u'delete':\n self.flashElement... | <|body_start_0|>
Block.__init__(self, parent, idevice)
self.flashElement = FlashElement(idevice.flash)
self.textElement = TextAreaElement(idevice.text)
<|end_body_0|>
<|body_start_1|>
log.debug('process ' + repr(request.args))
Block.process(self, request)
if u'action' no... | FlashWithTextBlock can render and process FlashWithTextIdevices as XHTML | FlashWithTextBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlashWithTextBlock:
"""FlashWithTextBlock can render and process FlashWithTextIdevices as XHTML"""
def __init__(self, parent, idevice):
"""Initialize"""
<|body_0|>
def process(self, request):
"""Process the request arguments from the web server to see if any appl... | stack_v2_sparse_classes_36k_train_006398 | 4,333 | no_license | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self, parent, idevice)"
},
{
"docstring": "Process the request arguments from the web server to see if any apply to this block",
"name": "process",
"signature": "def process(self, request)"
},
{
"docstrin... | 5 | null | Implement the Python class `FlashWithTextBlock` described below.
Class description:
FlashWithTextBlock can render and process FlashWithTextIdevices as XHTML
Method signatures and docstrings:
- def __init__(self, parent, idevice): Initialize
- def process(self, request): Process the request arguments from the web serv... | Implement the Python class `FlashWithTextBlock` described below.
Class description:
FlashWithTextBlock can render and process FlashWithTextIdevices as XHTML
Method signatures and docstrings:
- def __init__(self, parent, idevice): Initialize
- def process(self, request): Process the request arguments from the web serv... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class FlashWithTextBlock:
"""FlashWithTextBlock can render and process FlashWithTextIdevices as XHTML"""
def __init__(self, parent, idevice):
"""Initialize"""
<|body_0|>
def process(self, request):
"""Process the request arguments from the web server to see if any appl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlashWithTextBlock:
"""FlashWithTextBlock can render and process FlashWithTextIdevices as XHTML"""
def __init__(self, parent, idevice):
"""Initialize"""
Block.__init__(self, parent, idevice)
self.flashElement = FlashElement(idevice.flash)
self.textElement = TextAreaElement... | the_stack_v2_python_sparse | eXe/rev2283-2409/left-trunk-2409/exe/webui/flashwithtextblock.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
0f20663fb8a4f3211c50cd95f80e4dba755a240f | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email), name=name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, password=password, name=name)\nuser.is_admin = True\nuser.is_staff = True... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), name=name)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.c... | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_36k_train_006399 | 7,149 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, name, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name": "c... | 2 | stack_v2_sparse_classes_30k_train_000156 | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | 4d497a6261de17cc2fc058cea50e127e885e5095 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), na... | the_stack_v2_python_sparse | Project4_FortressMachine/KindFortressMachine/web/models.py | phully/PythonHomeWork | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.