blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
925c1ff84720a75dee80f58820382844fcb3c0d5 | [
"logic = NoticeLogic(self.auth, sid, aid)\nparams = ParamsParser(request.JSON)\nids = params.list('ids', desc='通知id列表')\nstatic = {}\nnotices = AssociationNotice.objects.get_many(ids=ids)\nfor notice in notices:\n logic.notice = notice\n if logic.notice.association_id != logic.association.id:\n _static... | <|body_start_0|>
logic = NoticeLogic(self.auth, sid, aid)
params = ParamsParser(request.JSON)
ids = params.list('ids', desc='通知id列表')
static = {}
notices = AssociationNotice.objects.get_many(ids=ids)
for notice in notices:
logic.notice = notice
if ... | NoticeRememberView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoticeRememberView:
def post(self, request, sid, aid):
"""批量记住通知 :param request: :param sid: :param aid: :return:"""
<|body_0|>
def get(self, request, sid, aid, nid):
"""记住通知 :param request: :param sid: :param aid: :param nid: :return:"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_009200 | 7,116 | no_license | [
{
"docstring": "批量记住通知 :param request: :param sid: :param aid: :return:",
"name": "post",
"signature": "def post(self, request, sid, aid)"
},
{
"docstring": "记住通知 :param request: :param sid: :param aid: :param nid: :return:",
"name": "get",
"signature": "def get(self, request, sid, aid, ... | 2 | stack_v2_sparse_classes_30k_train_053071 | Implement the Python class `NoticeRememberView` described below.
Class description:
Implement the NoticeRememberView class.
Method signatures and docstrings:
- def post(self, request, sid, aid): 批量记住通知 :param request: :param sid: :param aid: :return:
- def get(self, request, sid, aid, nid): 记住通知 :param request: :para... | Implement the Python class `NoticeRememberView` described below.
Class description:
Implement the NoticeRememberView class.
Method signatures and docstrings:
- def post(self, request, sid, aid): 批量记住通知 :param request: :param sid: :param aid: :return:
- def get(self, request, sid, aid, nid): 记住通知 :param request: :para... | a0553be3c259712de1fe5517b06317ad5756f79d | <|skeleton|>
class NoticeRememberView:
def post(self, request, sid, aid):
"""批量记住通知 :param request: :param sid: :param aid: :return:"""
<|body_0|>
def get(self, request, sid, aid, nid):
"""记住通知 :param request: :param sid: :param aid: :param nid: :return:"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NoticeRememberView:
def post(self, request, sid, aid):
"""批量记住通知 :param request: :param sid: :param aid: :return:"""
logic = NoticeLogic(self.auth, sid, aid)
params = ParamsParser(request.JSON)
ids = params.list('ids', desc='通知id列表')
static = {}
notices = Associ... | the_stack_v2_python_sparse | LittlePigHoHo/server/notice/views/info.py | shoogoome/hoho | train | 1 | |
1ebbfcb0a9d27f6dd8d5391a933ef9d3189bbcc1 | [
"self.reader = reader.Reader()\nid_handler = identifier.Identifier()\nself.machine_id = id_handler.get_id()\nself.connection = self.set_connection()",
"rabbit_connection = False\naddress = self.reader.get_c_value()[1]\nport = self.reader.get_c_value()[2]\ntry:\n rabbit_connection = rabbitmq.RabbitMQ(address, p... | <|body_start_0|>
self.reader = reader.Reader()
id_handler = identifier.Identifier()
self.machine_id = id_handler.get_id()
self.connection = self.set_connection()
<|end_body_0|>
<|body_start_1|>
rabbit_connection = False
address = self.reader.get_c_value()[1]
port... | Handles the sending of the packets formed from metric values and id to the rabbit mq server, based on the configured send time. | Packet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Packet:
"""Handles the sending of the packets formed from metric values and id to the rabbit mq server, based on the configured send time."""
def __init__(self):
"""Creates the dictionary containing the collected packet, unique id and the time when the object was sent. Uses the given... | stack_v2_sparse_classes_75kplus_train_009201 | 1,468 | no_license | [
{
"docstring": "Creates the dictionary containing the collected packet, unique id and the time when the object was sent. Uses the given port and address to connect to the rabbit queue and sends the packet dictionary.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Init... | 2 | stack_v2_sparse_classes_30k_train_031993 | Implement the Python class `Packet` described below.
Class description:
Handles the sending of the packets formed from metric values and id to the rabbit mq server, based on the configured send time.
Method signatures and docstrings:
- def __init__(self): Creates the dictionary containing the collected packet, unique... | Implement the Python class `Packet` described below.
Class description:
Handles the sending of the packets formed from metric values and id to the rabbit mq server, based on the configured send time.
Method signatures and docstrings:
- def __init__(self): Creates the dictionary containing the collected packet, unique... | db8b8cd05bd47ee99abcc8660453edf7fce1c7a1 | <|skeleton|>
class Packet:
"""Handles the sending of the packets formed from metric values and id to the rabbit mq server, based on the configured send time."""
def __init__(self):
"""Creates the dictionary containing the collected packet, unique id and the time when the object was sent. Uses the given... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Packet:
"""Handles the sending of the packets formed from metric values and id to the rabbit mq server, based on the configured send time."""
def __init__(self):
"""Creates the dictionary containing the collected packet, unique id and the time when the object was sent. Uses the given port and add... | the_stack_v2_python_sparse | client/packets.py | BabyCakes13/SMS | train | 0 |
c20b6ca58ce0a13a1ba70c53ee95c7a26c43fe8c | [
"pre = None\ncur = head\nwhile cur:\n tmp = cur.next\n cur.next = pre\n pre = cur\n cur = tmp\nreturn pre",
"p = head\nh = p\ntt = None\nhead = None\nwhile p is not None:\n for _ in range(k - 1):\n if p.next is None:\n if tt is not None:\n tt.next = h\n i... | <|body_start_0|>
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
<|end_body_0|>
<|body_start_1|>
p = head
h = p
tt = None
head = None
while p is not None... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pre = None
... | stack_v2_sparse_classes_75kplus_train_009202 | 1,323 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "reverseKGroup",
"signature": "def reverseKGroup(self, head, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008749 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
<|skeleton|>
class Solu... | d8ed762d1005975f0de4f07760c9671195621c88 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
def reverseKGroup(self, head, k):
... | the_stack_v2_python_sparse | reverse-nodes-in-k-group/solution.py | uxlsl/leetcode_practice | train | 0 | |
1eb54caaba7e8e04c959edd1ef4c167bf849fc3e | [
"if currency and currency == invoice_move.company_id.currency_id:\n currency_id = False\nelse:\n currency_id = currency.id\npayable_line = invoice_move.line_ids.filtered(_is_payable_line)\nassert len(payable_line) == 1\nconfig = get_account_config(self)\njournal = config.prepayment_journal_type_id\ndate = inv... | <|body_start_0|>
if currency and currency == invoice_move.company_id.currency_id:
currency_id = False
else:
currency_id = currency.id
payable_line = invoice_move.line_ids.filtered(_is_payable_line)
assert len(payable_line) == 1
config = get_account_config(... | AdvancedAccountMove | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdvancedAccountMove:
def _match_prepayment(self, invoice_move, pre_account, amount, currency=False):
"""Create a matching entry for a prepayment and reconciles it. `amount` is the amount to match expressed in `currency`. If `currency` is False, it defaults to the invoice's company curren... | stack_v2_sparse_classes_75kplus_train_009203 | 8,742 | no_license | [
{
"docstring": "Create a matching entry for a prepayment and reconciles it. `amount` is the amount to match expressed in `currency`. If `currency` is False, it defaults to the invoice's company currency.",
"name": "_match_prepayment",
"signature": "def _match_prepayment(self, invoice_move, pre_account, ... | 2 | stack_v2_sparse_classes_30k_train_012186 | Implement the Python class `AdvancedAccountMove` described below.
Class description:
Implement the AdvancedAccountMove class.
Method signatures and docstrings:
- def _match_prepayment(self, invoice_move, pre_account, amount, currency=False): Create a matching entry for a prepayment and reconciles it. `amount` is the ... | Implement the Python class `AdvancedAccountMove` described below.
Class description:
Implement the AdvancedAccountMove class.
Method signatures and docstrings:
- def _match_prepayment(self, invoice_move, pre_account, amount, currency=False): Create a matching entry for a prepayment and reconciles it. `amount` is the ... | 525cb116ea174643185a9af69d4be07bc60470ed | <|skeleton|>
class AdvancedAccountMove:
def _match_prepayment(self, invoice_move, pre_account, amount, currency=False):
"""Create a matching entry for a prepayment and reconciles it. `amount` is the amount to match expressed in `currency`. If `currency` is False, it defaults to the invoice's company curren... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdvancedAccountMove:
def _match_prepayment(self, invoice_move, pre_account, amount, currency=False):
"""Create a matching entry for a prepayment and reconciles it. `amount` is the amount to match expressed in `currency`. If `currency` is False, it defaults to the invoice's company currency."""
... | the_stack_v2_python_sparse | xopgi/xopgi_account_advancement/models/account_advancement.py | merchise/xopgi.account | train | 0 | |
fcbdbd19760df270c2fb64d69598a30eb75fbb71 | [
"if not parent:\n raise ValueError('Missing parent value.')\nsuper(BDEPathSpec, self).__init__(parent=parent, **kwargs)\nself.password = password\nself.recovery_password = recovery_password\nself.startup_key = startup_key",
"string_parts = []\nif self.password:\n string_parts.append(f'password: {self.passwo... | <|body_start_0|>
if not parent:
raise ValueError('Missing parent value.')
super(BDEPathSpec, self).__init__(parent=parent, **kwargs)
self.password = password
self.recovery_password = recovery_password
self.startup_key = startup_key
<|end_body_0|>
<|body_start_1|>
... | BDE path specification. Attributes: password (str): password. recovery_password (str): recovery password. startup_key (str): name of the startup key file. | BDEPathSpec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BDEPathSpec:
"""BDE path specification. Attributes: password (str): password. recovery_password (str): recovery password. startup_key (str): name of the startup key file."""
def __init__(self, password=None, parent=None, recovery_password=None, startup_key=None, **kwargs):
"""Initial... | stack_v2_sparse_classes_75kplus_train_009204 | 1,769 | permissive | [
{
"docstring": "Initializes a path specification. Note that the BDE path specification must have a parent. Args: password (Optional[str]): password. parent (Optional[PathSpec]): parent path specification. recovery_password (Optional[str]): recovery password. startup_key (Optional[str]): name of the startup key ... | 2 | null | Implement the Python class `BDEPathSpec` described below.
Class description:
BDE path specification. Attributes: password (str): password. recovery_password (str): recovery password. startup_key (str): name of the startup key file.
Method signatures and docstrings:
- def __init__(self, password=None, parent=None, rec... | Implement the Python class `BDEPathSpec` described below.
Class description:
BDE path specification. Attributes: password (str): password. recovery_password (str): recovery password. startup_key (str): name of the startup key file.
Method signatures and docstrings:
- def __init__(self, password=None, parent=None, rec... | 28756d910e951a22c5f0b2bcf5184f055a19d544 | <|skeleton|>
class BDEPathSpec:
"""BDE path specification. Attributes: password (str): password. recovery_password (str): recovery password. startup_key (str): name of the startup key file."""
def __init__(self, password=None, parent=None, recovery_password=None, startup_key=None, **kwargs):
"""Initial... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BDEPathSpec:
"""BDE path specification. Attributes: password (str): password. recovery_password (str): recovery password. startup_key (str): name of the startup key file."""
def __init__(self, password=None, parent=None, recovery_password=None, startup_key=None, **kwargs):
"""Initializes a path s... | the_stack_v2_python_sparse | dfvfs/path/bde_path_spec.py | log2timeline/dfvfs | train | 197 |
77ea59edc75bc37bbb84ebc9e8b4a6a458150b94 | [
"name = read_unicode_string(fp)\nclassID = read_length_and_key(fp)\noffset = read_fmt('I', fp)[0]\nreturn cls(name, classID, offset)",
"written = write_unicode_string(fp, self.name)\nwritten += write_length_and_key(fp, self.classID)\nwritten += write_fmt(fp, 'I', self.value)\nreturn written"
] | <|body_start_0|>
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
offset = read_fmt('I', fp)[0]
return cls(name, classID, offset)
<|end_body_0|>
<|body_start_1|>
written = write_unicode_string(fp, self.name)
written += write_length_and_key(fp, self.classI... | Offset structure. .. py:attribute:: value | Offset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Offset:
"""Offset structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp: file-like object"""
... | stack_v2_sparse_classes_75kplus_train_009205 | 19,890 | permissive | [
{
"docstring": "Read the element from a file-like object. :param fp: file-like object",
"name": "read",
"signature": "def read(cls, fp)"
},
{
"docstring": "Write the element to a file-like object. :param fp: file-like object",
"name": "write",
"signature": "def write(self, fp)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002000 | Implement the Python class `Offset` described below.
Class description:
Offset structure. .. py:attribute:: value
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like object. :param fp: file... | Implement the Python class `Offset` described below.
Class description:
Offset structure. .. py:attribute:: value
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like object. :param fp: file... | 0e3ac5b64061c7eb87c6eeacce4b9792d1f479b5 | <|skeleton|>
class Offset:
"""Offset structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp: file-like object"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Offset:
"""Offset structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
offset = read_fmt('I', fp)[0]
return cls(name, cl... | the_stack_v2_python_sparse | psd_tools/psd/descriptor.py | sfneal/psd-tools3 | train | 30 |
c649dd4010e281d60ac32eeaef491929a8cb4b9c | [
"super().__init__(config_entry, driver, info, entity_description, unit_of_measurement)\nself._primary_value = cast(ConfigurationValue, self.info.primary_value)\nproperty_key_name = self.info.primary_value.property_key_name\nself._attr_name = self.generate_name(alternate_value_name=self.info.primary_value.property_n... | <|body_start_0|>
super().__init__(config_entry, driver, info, entity_description, unit_of_measurement)
self._primary_value = cast(ConfigurationValue, self.info.primary_value)
property_key_name = self.info.primary_value.property_key_name
self._attr_name = self.generate_name(alternate_valu... | Representation of a Z-Wave config parameter sensor. | ZWaveConfigParameterSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZWaveConfigParameterSensor:
"""Representation of a Z-Wave config parameter sensor."""
def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo, entity_description: SensorEntityDescription, unit_of_measurement: str | None=None) -> None:
"""Initialize a ZW... | stack_v2_sparse_classes_75kplus_train_009206 | 37,746 | permissive | [
{
"docstring": "Initialize a ZWaveConfigParameterSensor entity.",
"name": "__init__",
"signature": "def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo, entity_description: SensorEntityDescription, unit_of_measurement: str | None=None) -> None"
},
{
"docstring"... | 3 | stack_v2_sparse_classes_30k_train_052088 | Implement the Python class `ZWaveConfigParameterSensor` described below.
Class description:
Representation of a Z-Wave config parameter sensor.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo, entity_description: SensorEntityDescription, unit_... | Implement the Python class `ZWaveConfigParameterSensor` described below.
Class description:
Representation of a Z-Wave config parameter sensor.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo, entity_description: SensorEntityDescription, unit_... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ZWaveConfigParameterSensor:
"""Representation of a Z-Wave config parameter sensor."""
def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo, entity_description: SensorEntityDescription, unit_of_measurement: str | None=None) -> None:
"""Initialize a ZW... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZWaveConfigParameterSensor:
"""Representation of a Z-Wave config parameter sensor."""
def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo, entity_description: SensorEntityDescription, unit_of_measurement: str | None=None) -> None:
"""Initialize a ZWaveConfigPara... | the_stack_v2_python_sparse | homeassistant/components/zwave_js/sensor.py | home-assistant/core | train | 35,501 |
e25ef507aad1c18b3728de1c2df6cc155fa4f82a | [
"super().__init__(**kwargs)\nself.net = net\nself.f0_residual = f0_residual\nself.dense_out = tfkl.Dense(2)\nself.norm = nn.Normalize('layer')",
"x = tf.concat([f0_midi, loudness], axis=-1)\nx = self.net(x)\nx = self.norm(x)\nx = self.dense_out(x)\nz_pitch = x[..., 0:1]\nz_vel = x[..., 1:2]\nif self.f0_residual:\... | <|body_start_0|>
super().__init__(**kwargs)
self.net = net
self.f0_residual = f0_residual
self.dense_out = tfkl.Dense(2)
self.norm = nn.Normalize('layer')
<|end_body_0|>
<|body_start_1|>
x = tf.concat([f0_midi, loudness], axis=-1)
x = self.net(x)
x = self... | Encodes f0 & loudness to MIDI representation. | MidiEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MidiEncoder:
"""Encodes f0 & loudness to MIDI representation."""
def __init__(self, net=None, f0_residual=True, **kwargs):
"""Constructor."""
<|body_0|>
def call(self, f0_midi, loudness) -> ['z_pitch', 'z_vel']:
"""Forward pass for the encoder. Args: f0_midi: Ten... | stack_v2_sparse_classes_75kplus_train_009207 | 15,113 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, net=None, f0_residual=True, **kwargs)"
},
{
"docstring": "Forward pass for the encoder. Args: f0_midi: Tensor containing an f0 curve in MIDI scale. [batch, time, 1] loudness: Tensor containing a loudness curve in... | 2 | stack_v2_sparse_classes_30k_train_021582 | Implement the Python class `MidiEncoder` described below.
Class description:
Encodes f0 & loudness to MIDI representation.
Method signatures and docstrings:
- def __init__(self, net=None, f0_residual=True, **kwargs): Constructor.
- def call(self, f0_midi, loudness) -> ['z_pitch', 'z_vel']: Forward pass for the encode... | Implement the Python class `MidiEncoder` described below.
Class description:
Encodes f0 & loudness to MIDI representation.
Method signatures and docstrings:
- def __init__(self, net=None, f0_residual=True, **kwargs): Constructor.
- def call(self, f0_midi, loudness) -> ['z_pitch', 'z_vel']: Forward pass for the encode... | 7e0a39420f3bd87d9efd54cf0d36f4e258311340 | <|skeleton|>
class MidiEncoder:
"""Encodes f0 & loudness to MIDI representation."""
def __init__(self, net=None, f0_residual=True, **kwargs):
"""Constructor."""
<|body_0|>
def call(self, f0_midi, loudness) -> ['z_pitch', 'z_vel']:
"""Forward pass for the encoder. Args: f0_midi: Ten... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MidiEncoder:
"""Encodes f0 & loudness to MIDI representation."""
def __init__(self, net=None, f0_residual=True, **kwargs):
"""Constructor."""
super().__init__(**kwargs)
self.net = net
self.f0_residual = f0_residual
self.dense_out = tfkl.Dense(2)
self.norm =... | the_stack_v2_python_sparse | ddsp/training/encoders.py | magenta/ddsp | train | 2,666 |
764d87469e90fc895cb74ad4131ac855430a9730 | [
"if clock is None:\n clock = time.clock\nself.current = clock()\nself.clock = clock",
"next = self.clock()\ndelta = next - self.current\nself.current = next\nreturn delta"
] | <|body_start_0|>
if clock is None:
clock = time.clock
self.current = clock()
self.clock = clock
<|end_body_0|>
<|body_start_1|>
next = self.clock()
delta = next - self.current
self.current = next
return delta
<|end_body_1|>
| A callable object that tracks the time elapsed between calls | Timer | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Timer:
"""A callable object that tracks the time elapsed between calls"""
def __init__(self, clock=None):
"""Create a timer based on the given clock function."""
<|body_0|>
def __call__(self):
"""Compute the time elapsed since the last call and reset the timer.""... | stack_v2_sparse_classes_75kplus_train_009208 | 1,584 | permissive | [
{
"docstring": "Create a timer based on the given clock function.",
"name": "__init__",
"signature": "def __init__(self, clock=None)"
},
{
"docstring": "Compute the time elapsed since the last call and reset the timer.",
"name": "__call__",
"signature": "def __call__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034055 | Implement the Python class `Timer` described below.
Class description:
A callable object that tracks the time elapsed between calls
Method signatures and docstrings:
- def __init__(self, clock=None): Create a timer based on the given clock function.
- def __call__(self): Compute the time elapsed since the last call a... | Implement the Python class `Timer` described below.
Class description:
A callable object that tracks the time elapsed between calls
Method signatures and docstrings:
- def __init__(self, clock=None): Create a timer based on the given clock function.
- def __call__(self): Compute the time elapsed since the last call a... | c7a147037b806058d18d9a200ffa4a14f3402d04 | <|skeleton|>
class Timer:
"""A callable object that tracks the time elapsed between calls"""
def __init__(self, clock=None):
"""Create a timer based on the given clock function."""
<|body_0|>
def __call__(self):
"""Compute the time elapsed since the last call and reset the timer.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Timer:
"""A callable object that tracks the time elapsed between calls"""
def __init__(self, clock=None):
"""Create a timer based on the given clock function."""
if clock is None:
clock = time.clock
self.current = clock()
self.clock = clock
def __call__(se... | the_stack_v2_python_sparse | util/time.py | gregr/old-and-miscellaneous | train | 2 |
07636030b01bfbee11d5d4ca6d398d5d7dcc4fe6 | [
"self.size = size\nself.square = []\nfor row in range(size):\n self.square.append([])\n for col in range(size):\n self.square[row].append(0)",
"row = self.size - 1\ncol = self.size // 2\npos = 1\nwhile pos <= self.size * self.size:\n self.square[row][col] = pos\n row += 1\n col += 1\n if ... | <|body_start_0|>
self.size = size
self.square = []
for row in range(size):
self.square.append([])
for col in range(size):
self.square[row].append(0)
<|end_body_0|>
<|body_start_1|>
row = self.size - 1
col = self.size // 2
pos = 1
... | a magic square is an n*n (where n is odd) grid of numbers where the sum of each row and column is equal | Magic_Square | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Magic_Square:
"""a magic square is an n*n (where n is odd) grid of numbers where the sum of each row and column is equal"""
def __init__(self, size):
"""initialize the square"""
<|body_0|>
def make_square(self):
"""build the square"""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus_train_009209 | 1,362 | no_license | [
{
"docstring": "initialize the square",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": "build the square",
"name": "make_square",
"signature": "def make_square(self)"
},
{
"docstring": "display the square",
"name": "print_square",
"signature... | 3 | stack_v2_sparse_classes_30k_train_021587 | Implement the Python class `Magic_Square` described below.
Class description:
a magic square is an n*n (where n is odd) grid of numbers where the sum of each row and column is equal
Method signatures and docstrings:
- def __init__(self, size): initialize the square
- def make_square(self): build the square
- def prin... | Implement the Python class `Magic_Square` described below.
Class description:
a magic square is an n*n (where n is odd) grid of numbers where the sum of each row and column is equal
Method signatures and docstrings:
- def __init__(self, size): initialize the square
- def make_square(self): build the square
- def prin... | 268cc79fb9b0d5b4a8c600ae56ff838a9dae54b0 | <|skeleton|>
class Magic_Square:
"""a magic square is an n*n (where n is odd) grid of numbers where the sum of each row and column is equal"""
def __init__(self, size):
"""initialize the square"""
<|body_0|>
def make_square(self):
"""build the square"""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Magic_Square:
"""a magic square is an n*n (where n is odd) grid of numbers where the sum of each row and column is equal"""
def __init__(self, size):
"""initialize the square"""
self.size = size
self.square = []
for row in range(size):
self.square.append([])
... | the_stack_v2_python_sparse | Python/MagicSquare.py | smarth55/Examples | train | 0 |
5a60d55d408bfb0329da3b0de1b835b729d6aea1 | [
"try:\n self.no_graphics = not showEnv\n self.envName = envName\n self.states = None\nexcept Exception as e:\n raise type(e)('lib.envs.envUnity.Env.__init__ - ERROR - ' + str(e)).with_traceback(sys.exc_info()[2])\nreturn",
"try:\n self.env = gym.make(self.envName)\n self.state = self.env.reset()... | <|body_start_0|>
try:
self.no_graphics = not showEnv
self.envName = envName
self.states = None
except Exception as e:
raise type(e)('lib.envs.envUnity.Env.__init__ - ERROR - ' + str(e)).with_traceback(sys.exc_info()[2])
return
<|end_body_0|>
<|bod... | A convinience function for generating episodes and memories This convinience class generates a context manager that can be used for generating a Gym environment. This is supposed to be a drop-in replacement for the Unity environment. This however differs from the Unity environment in that it needs the name of the envir... | Env | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Env:
"""A convinience function for generating episodes and memories This convinience class generates a context manager that can be used for generating a Gym environment. This is supposed to be a drop-in replacement for the Unity environment. This however differs from the Unity environment in that... | stack_v2_sparse_classes_75kplus_train_009210 | 15,876 | permissive | [
{
"docstring": "Initialize the environment This sets up the requirements that will later be used for generating the gym Environment. The gym environment can be used in a mode that hides the plotting of the actuual environment. This may result in a significant boost in speed. Arguments: envName {str} -- The name... | 6 | stack_v2_sparse_classes_30k_train_034082 | Implement the Python class `Env` described below.
Class description:
A convinience function for generating episodes and memories This convinience class generates a context manager that can be used for generating a Gym environment. This is supposed to be a drop-in replacement for the Unity environment. This however dif... | Implement the Python class `Env` described below.
Class description:
A convinience function for generating episodes and memories This convinience class generates a context manager that can be used for generating a Gym environment. This is supposed to be a drop-in replacement for the Unity environment. This however dif... | 80d19a39af29947db2fc73b0443b9c3bb66d6fc0 | <|skeleton|>
class Env:
"""A convinience function for generating episodes and memories This convinience class generates a context manager that can be used for generating a Gym environment. This is supposed to be a drop-in replacement for the Unity environment. This however differs from the Unity environment in that... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Env:
"""A convinience function for generating episodes and memories This convinience class generates a context manager that can be used for generating a Gym environment. This is supposed to be a drop-in replacement for the Unity environment. This however differs from the Unity environment in that it needs the... | the_stack_v2_python_sparse | src/lib/envs/envGym.py | sankhaMukherjee/RLalgos | train | 0 |
75c4dcf488eb72768747d15a9167208c5bf2b79d | [
"self.triangle = triangle\nself.branchmin = dict()\nreturn self.miniSub(0, 0)",
"if i == len(self.triangle) - 1:\n return self.triangle[i][j]\nelse:\n if (i, j) not in self.branchmin.keys():\n self.branchmin[i, j] = min(self.miniSub(i + 1, j), self.miniSub(i + 1, j + 1))\n return self.triangle[i][... | <|body_start_0|>
self.triangle = triangle
self.branchmin = dict()
return self.miniSub(0, 0)
<|end_body_0|>
<|body_start_1|>
if i == len(self.triangle) - 1:
return self.triangle[i][j]
else:
if (i, j) not in self.branchmin.keys():
self.branc... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
<|body_0|>
def miniSub(self, i, j):
"""input: position of the tip output:minimun of the triangle with tip i,j"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_009211 | 917 | no_license | [
{
"docstring": ":type triangle: List[List[int]] :rtype: int",
"name": "minimumTotal",
"signature": "def minimumTotal(self, triangle)"
},
{
"docstring": "input: position of the tip output:minimun of the triangle with tip i,j",
"name": "miniSub",
"signature": "def miniSub(self, i, j)"
}
... | 2 | stack_v2_sparse_classes_30k_train_009349 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotal(self, triangle): :type triangle: List[List[int]] :rtype: int
- def miniSub(self, i, j): input: position of the tip output:minimun of the triangle with tip i,j | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotal(self, triangle): :type triangle: List[List[int]] :rtype: int
- def miniSub(self, i, j): input: position of the tip output:minimun of the triangle with tip i,j
<... | e6114ab9ebd6b401a8b63266010bb1d75e23637f | <|skeleton|>
class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
<|body_0|>
def miniSub(self, i, j):
"""input: position of the tip output:minimun of the triangle with tip i,j"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
self.triangle = triangle
self.branchmin = dict()
return self.miniSub(0, 0)
def miniSub(self, i, j):
"""input: position of the tip output:minimun of the triangle with tip i... | the_stack_v2_python_sparse | 120_20180830.py | yusun-hci/LeetCodeDaily | train | 0 | |
1a664342f500697b4c538301d1d16c173a1eae16 | [
"self.service = service\nself.user = user\nself.host = host",
"authStr = heloStr = b''\nif self.user:\n authStr = b' auth=' + self.user.encode('xtext')\nif helo[0]:\n heloStr = b' helo=' + helo[0]\nfromUser = b'from ' + helo[0] + b' ([' + helo[1] + b']' + heloStr + authStr\nby = b'by ' + self.host + b' with... | <|body_start_0|>
self.service = service
self.user = user
self.host = host
<|end_body_0|>
<|body_start_1|>
authStr = heloStr = b''
if self.user:
authStr = b' auth=' + self.user.encode('xtext')
if helo[0]:
heloStr = b' helo=' + helo[0]
fromU... | A base class for message delivery using the domains of a mail service. @ivar service: See L{__init__} @ivar user: See L{__init__} @ivar host: See L{__init__} @type protocolName: L{bytes} @ivar protocolName: The protocol being used to deliver the mail. Sub-classes should set this appropriately. | DomainDeliveryBase | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DomainDeliveryBase:
"""A base class for message delivery using the domains of a mail service. @ivar service: See L{__init__} @ivar user: See L{__init__} @ivar host: See L{__init__} @type protocolName: L{bytes} @ivar protocolName: The protocol being used to deliver the mail. Sub-classes should set... | stack_v2_sparse_classes_75kplus_train_009212 | 12,420 | permissive | [
{
"docstring": "@type service: L{MailService} @param service: A mail service. @type user: L{bytes} or L{None} @param user: The authenticated SMTP user. @type host: L{bytes} @param host: The hostname.",
"name": "__init__",
"signature": "def __init__(self, service, user, host=smtp.DNSNAME)"
},
{
"... | 4 | null | Implement the Python class `DomainDeliveryBase` described below.
Class description:
A base class for message delivery using the domains of a mail service. @ivar service: See L{__init__} @ivar user: See L{__init__} @ivar host: See L{__init__} @type protocolName: L{bytes} @ivar protocolName: The protocol being used to d... | Implement the Python class `DomainDeliveryBase` described below.
Class description:
A base class for message delivery using the domains of a mail service. @ivar service: See L{__init__} @ivar user: See L{__init__} @ivar host: See L{__init__} @type protocolName: L{bytes} @ivar protocolName: The protocol being used to d... | 5cee0a8c4180a3108538b4e4ce945a18726595a6 | <|skeleton|>
class DomainDeliveryBase:
"""A base class for message delivery using the domains of a mail service. @ivar service: See L{__init__} @ivar user: See L{__init__} @ivar host: See L{__init__} @type protocolName: L{bytes} @ivar protocolName: The protocol being used to deliver the mail. Sub-classes should set... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DomainDeliveryBase:
"""A base class for message delivery using the domains of a mail service. @ivar service: See L{__init__} @ivar user: See L{__init__} @ivar host: See L{__init__} @type protocolName: L{bytes} @ivar protocolName: The protocol being used to deliver the mail. Sub-classes should set this appropr... | the_stack_v2_python_sparse | venv/Lib/site-packages/twisted/mail/protocols.py | zoelesv/Smathchat | train | 9 |
8497c76972bf4cbfa2652ab690f517e66d16eccd | [
"self.spiffe_id = spiffe_id\nself.audience = audience\nself.expiry = expiry\nself.claims = claims\nself.token = token",
"if not token:\n raise ArgumentError(INVALID_INPUT_ERROR.format('token cannot be empty'))\ntry:\n header_params = jwt.get_unverified_header(token)\n validator = JwtSvidValidator()\n ... | <|body_start_0|>
self.spiffe_id = spiffe_id
self.audience = audience
self.expiry = expiry
self.claims = claims
self.token = token
<|end_body_0|>
<|body_start_1|>
if not token:
raise ArgumentError(INVALID_INPUT_ERROR.format('token cannot be empty'))
tr... | Represents a SPIFFE JWT SVID as defined in the SPIFFE standard. See `SPIFFE JWT-SVID standard <https://github.com/spiffe/spiffe/blob/master/standards/JWT-SVID.md>` | JwtSvid | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JwtSvid:
"""Represents a SPIFFE JWT SVID as defined in the SPIFFE standard. See `SPIFFE JWT-SVID standard <https://github.com/spiffe/spiffe/blob/master/standards/JWT-SVID.md>`"""
def __init__(self, spiffe_id: SpiffeId, audience: List[str], expiry: int, claims: Dict[str, str], token: str) -> ... | stack_v2_sparse_classes_75kplus_train_009213 | 6,651 | permissive | [
{
"docstring": "Creates a JwtSvid instance. Args: spiffe_id: A valid SpiffeId instance. audience: The intended recipients of JWT-SVID as present in the 'aud' claims. expiry: Date and time in UTC specifying expiry date of the JwtSvid. claims: Key-value pairs with all the claims present in the token. token: Encod... | 3 | stack_v2_sparse_classes_30k_train_035345 | Implement the Python class `JwtSvid` described below.
Class description:
Represents a SPIFFE JWT SVID as defined in the SPIFFE standard. See `SPIFFE JWT-SVID standard <https://github.com/spiffe/spiffe/blob/master/standards/JWT-SVID.md>`
Method signatures and docstrings:
- def __init__(self, spiffe_id: SpiffeId, audie... | Implement the Python class `JwtSvid` described below.
Class description:
Represents a SPIFFE JWT SVID as defined in the SPIFFE standard. See `SPIFFE JWT-SVID standard <https://github.com/spiffe/spiffe/blob/master/standards/JWT-SVID.md>`
Method signatures and docstrings:
- def __init__(self, spiffe_id: SpiffeId, audie... | ab46e05171b9d804f2aec4c6c4f024a573047215 | <|skeleton|>
class JwtSvid:
"""Represents a SPIFFE JWT SVID as defined in the SPIFFE standard. See `SPIFFE JWT-SVID standard <https://github.com/spiffe/spiffe/blob/master/standards/JWT-SVID.md>`"""
def __init__(self, spiffe_id: SpiffeId, audience: List[str], expiry: int, claims: Dict[str, str], token: str) -> ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JwtSvid:
"""Represents a SPIFFE JWT SVID as defined in the SPIFFE standard. See `SPIFFE JWT-SVID standard <https://github.com/spiffe/spiffe/blob/master/standards/JWT-SVID.md>`"""
def __init__(self, spiffe_id: SpiffeId, audience: List[str], expiry: int, claims: Dict[str, str], token: str) -> None:
... | the_stack_v2_python_sparse | src/pyspiffe/svid/jwt_svid.py | amoore877/py-spiffe | train | 0 |
60da923d8eb80ac48a2cf486c278fe11eeb26b99 | [
"if data is not None:\n if type(data) != list:\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise ValueError('data must contain multiple values')\n mean = 0.0\n count = 0\n for element in data:\n if type(element) not in {int, float}:\n raise TypeError... | <|body_start_0|>
if data is not None:
if type(data) != list:
raise TypeError('data must be a list')
if len(data) < 2:
raise ValueError('data must contain multiple values')
mean = 0.0
count = 0
for element in data:
... | Class that represents an Exponential distribution. | Exponential | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exponential:
"""Class that represents an Exponential distribution."""
def __init__(self, data=None, lambtha=1.0):
"""Constructor of the class. Sets the instance attribute lambtha as float. data is a list of the data to be used to estimate the distribution. lambtha is the expected num... | stack_v2_sparse_classes_75kplus_train_009214 | 1,635 | no_license | [
{
"docstring": "Constructor of the class. Sets the instance attribute lambtha as float. data is a list of the data to be used to estimate the distribution. lambtha is the expected number of occurences in a given time frame.",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
... | 3 | stack_v2_sparse_classes_30k_train_022304 | Implement the Python class `Exponential` described below.
Class description:
Class that represents an Exponential distribution.
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Constructor of the class. Sets the instance attribute lambtha as float. data is a list of the data to be used ... | Implement the Python class `Exponential` described below.
Class description:
Class that represents an Exponential distribution.
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Constructor of the class. Sets the instance attribute lambtha as float. data is a list of the data to be used ... | 1e7cd1589e6e4896ee48a24b9ca85595e16e929d | <|skeleton|>
class Exponential:
"""Class that represents an Exponential distribution."""
def __init__(self, data=None, lambtha=1.0):
"""Constructor of the class. Sets the instance attribute lambtha as float. data is a list of the data to be used to estimate the distribution. lambtha is the expected num... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Exponential:
"""Class that represents an Exponential distribution."""
def __init__(self, data=None, lambtha=1.0):
"""Constructor of the class. Sets the instance attribute lambtha as float. data is a list of the data to be used to estimate the distribution. lambtha is the expected number of occure... | the_stack_v2_python_sparse | math/0x03-probability/exponential.py | Daransoto/holbertonschool-machine_learning | train | 0 |
f53e8d47c874f62e63b8b4e7a2f1b6c2e94f4df6 | [
"results = None\ntry:\n with datastore_services.get_ndb_context():\n results = exp_services.regenerate_missing_stats_for_exploration(exp_id)\nexcept Exception as e:\n logging.exception(e)\n return result.Err((exp_id, e))\nreturn result.Ok((exp_id, results))",
"unmigrated_exploration_models = self.... | <|body_start_0|>
results = None
try:
with datastore_services.get_ndb_context():
results = exp_services.regenerate_missing_stats_for_exploration(exp_id)
except Exception as e:
logging.exception(e)
return result.Err((exp_id, e))
return re... | Job that regenerates missing exploration stats models. | RegenerateMissingExplorationStatsModelsJob | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegenerateMissingExplorationStatsModelsJob:
"""Job that regenerates missing exploration stats models."""
def _regenerate_stats_models(exp_id: str, unused_exp_model: exp_models.ExplorationModel) -> result.Result[Tuple[str, exp_domain.Exploration], Tuple[str, Exception]]:
"""Regenerate... | stack_v2_sparse_classes_75kplus_train_009215 | 28,752 | permissive | [
{
"docstring": "Regenerates missing exploration stats models. Args: exp_id: str. The ID of the exploration. unused_exp_model: ExplorationModel. Exploration model. Returns: Result((str, Exploration), (str, Exception)). Result containing tuple that consists of exploration ID and either Exploration object or Excep... | 2 | stack_v2_sparse_classes_30k_train_041225 | Implement the Python class `RegenerateMissingExplorationStatsModelsJob` described below.
Class description:
Job that regenerates missing exploration stats models.
Method signatures and docstrings:
- def _regenerate_stats_models(exp_id: str, unused_exp_model: exp_models.ExplorationModel) -> result.Result[Tuple[str, ex... | Implement the Python class `RegenerateMissingExplorationStatsModelsJob` described below.
Class description:
Job that regenerates missing exploration stats models.
Method signatures and docstrings:
- def _regenerate_stats_models(exp_id: str, unused_exp_model: exp_models.ExplorationModel) -> result.Result[Tuple[str, ex... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class RegenerateMissingExplorationStatsModelsJob:
"""Job that regenerates missing exploration stats models."""
def _regenerate_stats_models(exp_id: str, unused_exp_model: exp_models.ExplorationModel) -> result.Result[Tuple[str, exp_domain.Exploration], Tuple[str, Exception]]:
"""Regenerate... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegenerateMissingExplorationStatsModelsJob:
"""Job that regenerates missing exploration stats models."""
def _regenerate_stats_models(exp_id: str, unused_exp_model: exp_models.ExplorationModel) -> result.Result[Tuple[str, exp_domain.Exploration], Tuple[str, Exception]]:
"""Regenerates missing exp... | the_stack_v2_python_sparse | core/jobs/batch_jobs/exp_migration_jobs.py | oppia/oppia | train | 6,172 |
7d8eb92601283deda10ca6263e7b8b7aefad5cbe | [
"Validate.required(raw_costs, 'raw_costs')\nValidate.required(demand, 'demand')\nif raw_costs.holding_cost == 0.0:\n return demand.quantity\nelse:\n numerator = 2 * raw_costs.ordering_cost * demand.quantity\n denominator = raw_costs.holding_cost\n return math.sqrt(numerator / denominator)",
"Validate.... | <|body_start_0|>
Validate.required(raw_costs, 'raw_costs')
Validate.required(demand, 'demand')
if raw_costs.holding_cost == 0.0:
return demand.quantity
else:
numerator = 2 * raw_costs.ordering_cost * demand.quantity
denominator = raw_costs.holding_cost... | EOQ | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EOQ:
def optimal_order_quantity(raw_costs, demand):
"""Calculate economic order quantity (optimal Q*) given raw costs and demand. Parameters ---------- raw_costs : RawCosts A `RawCosts` object, containing a set of raw cost values demand : Demand A `Demand` object, containing demand quant... | stack_v2_sparse_classes_75kplus_train_009216 | 3,268 | no_license | [
{
"docstring": "Calculate economic order quantity (optimal Q*) given raw costs and demand. Parameters ---------- raw_costs : RawCosts A `RawCosts` object, containing a set of raw cost values demand : Demand A `Demand` object, containing demand quantity and time frame Returns ------- optimal_order_quantity: floa... | 4 | stack_v2_sparse_classes_30k_train_023248 | Implement the Python class `EOQ` described below.
Class description:
Implement the EOQ class.
Method signatures and docstrings:
- def optimal_order_quantity(raw_costs, demand): Calculate economic order quantity (optimal Q*) given raw costs and demand. Parameters ---------- raw_costs : RawCosts A `RawCosts` object, co... | Implement the Python class `EOQ` described below.
Class description:
Implement the EOQ class.
Method signatures and docstrings:
- def optimal_order_quantity(raw_costs, demand): Calculate economic order quantity (optimal Q*) given raw costs and demand. Parameters ---------- raw_costs : RawCosts A `RawCosts` object, co... | 230b7bead81265dfee2e0e5c5819ae7a9c46acbc | <|skeleton|>
class EOQ:
def optimal_order_quantity(raw_costs, demand):
"""Calculate economic order quantity (optimal Q*) given raw costs and demand. Parameters ---------- raw_costs : RawCosts A `RawCosts` object, containing a set of raw cost values demand : Demand A `Demand` object, containing demand quant... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EOQ:
def optimal_order_quantity(raw_costs, demand):
"""Calculate economic order quantity (optimal Q*) given raw costs and demand. Parameters ---------- raw_costs : RawCosts A `RawCosts` object, containing a set of raw cost values demand : Demand A `Demand` object, containing demand quantity and time f... | the_stack_v2_python_sparse | eoq.py | rickhaffey/supply-chain-python | train | 2 | |
738d7672419a6c76c78f52a05a00b70abfc1979c | [
"session_option = onnxruntime.SessionOptions()\nsession_option.log_severity_level = 3\nsession_option.intra_op_num_threads = psutil.cpu_count(logical=True) // 2 - 1\nself.onnx_session = onnxruntime.InferenceSession(model_path, sess_options=session_option, providers=providers)\nself.providers = self.onnx_session.get... | <|body_start_0|>
session_option = onnxruntime.SessionOptions()
session_option.log_severity_level = 3
session_option.intra_op_num_threads = psutil.cpu_count(logical=True) // 2 - 1
self.onnx_session = onnxruntime.InferenceSession(model_path, sess_options=session_option, providers=providers... | RetinaFaceONNX | [
"AGPL-3.0-only",
"LicenseRef-scancode-proprietary-license",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetinaFaceONNX:
def __init__(self, model_path: Optional[str]='retinaface_mbn025_with_postprocess_480x640_max1000_th0.70.onnx', providers: Optional[List]=[('TensorrtExecutionProvider', {'trt_engine_cache_enable': True, 'trt_engine_cache_path': '.', 'trt_fp16_enable': True}), 'CUDAExecutionProvide... | stack_v2_sparse_classes_75kplus_train_009217 | 14,586 | permissive | [
{
"docstring": "RetinaFaceONNX Parameters ---------- model_path: Optional[str] ONNX file path providers: Optional[List] Name of onnx execution providers",
"name": "__init__",
"signature": "def __init__(self, model_path: Optional[str]='retinaface_mbn025_with_postprocess_480x640_max1000_th0.70.onnx', prov... | 3 | null | Implement the Python class `RetinaFaceONNX` described below.
Class description:
Implement the RetinaFaceONNX class.
Method signatures and docstrings:
- def __init__(self, model_path: Optional[str]='retinaface_mbn025_with_postprocess_480x640_max1000_th0.70.onnx', providers: Optional[List]=[('TensorrtExecutionProvider'... | Implement the Python class `RetinaFaceONNX` described below.
Class description:
Implement the RetinaFaceONNX class.
Method signatures and docstrings:
- def __init__(self, model_path: Optional[str]='retinaface_mbn025_with_postprocess_480x640_max1000_th0.70.onnx', providers: Optional[List]=[('TensorrtExecutionProvider'... | ff08e6e8ab095d98e96fc4a136ad5cbccc75fcf9 | <|skeleton|>
class RetinaFaceONNX:
def __init__(self, model_path: Optional[str]='retinaface_mbn025_with_postprocess_480x640_max1000_th0.70.onnx', providers: Optional[List]=[('TensorrtExecutionProvider', {'trt_engine_cache_enable': True, 'trt_engine_cache_path': '.', 'trt_fp16_enable': True}), 'CUDAExecutionProvide... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RetinaFaceONNX:
def __init__(self, model_path: Optional[str]='retinaface_mbn025_with_postprocess_480x640_max1000_th0.70.onnx', providers: Optional[List]=[('TensorrtExecutionProvider', {'trt_engine_cache_enable': True, 'trt_engine_cache_path': '.', 'trt_fp16_enable': True}), 'CUDAExecutionProvider', 'CPUExecut... | the_stack_v2_python_sparse | 398_L2CS-Net/demo/demo_L2CSNet_with_postprocess_onnx.py | PINTO0309/PINTO_model_zoo | train | 2,849 | |
4b0341f4952bf77825858b09db9c60a4693e64ad | [
"if key is not None:\n self.key = key\n self.conf = self.get_train_obj(key)",
"try:\n graph_id = str(graph_id)\n query_set = models.AUTO_ML_RULE.objects.all()\n query_set = serial.serialize('json', query_set)\n query_set = json.loads(query_set)\n ids = []\n for row in query_set:\n g... | <|body_start_0|>
if key is not None:
self.key = key
self.conf = self.get_train_obj(key)
<|end_body_0|>
<|body_start_1|>
try:
graph_id = str(graph_id)
query_set = models.AUTO_ML_RULE.objects.all()
query_set = serial.serialize('json', query_set)... | Auto ML related conf get/set common methos | AutoMlRule | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoMlRule:
"""Auto ML related conf get/set common methos"""
def __init__(self, key=None):
"""init key variable :param key: :return:"""
<|body_0|>
def get_graph_type_list(self, graph_id):
"""get view data for net config :return:"""
<|body_1|>
def get... | stack_v2_sparse_classes_75kplus_train_009218 | 3,528 | permissive | [
{
"docstring": "init key variable :param key: :return:",
"name": "__init__",
"signature": "def __init__(self, key=None)"
},
{
"docstring": "get view data for net config :return:",
"name": "get_graph_type_list",
"signature": "def get_graph_type_list(self, graph_id)"
},
{
"docstrin... | 5 | stack_v2_sparse_classes_30k_train_051188 | Implement the Python class `AutoMlRule` described below.
Class description:
Auto ML related conf get/set common methos
Method signatures and docstrings:
- def __init__(self, key=None): init key variable :param key: :return:
- def get_graph_type_list(self, graph_id): get view data for net config :return:
- def get_gra... | Implement the Python class `AutoMlRule` described below.
Class description:
Auto ML related conf get/set common methos
Method signatures and docstrings:
- def __init__(self, key=None): init key variable :param key: :return:
- def get_graph_type_list(self, graph_id): get view data for net config :return:
- def get_gra... | 6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f | <|skeleton|>
class AutoMlRule:
"""Auto ML related conf get/set common methos"""
def __init__(self, key=None):
"""init key variable :param key: :return:"""
<|body_0|>
def get_graph_type_list(self, graph_id):
"""get view data for net config :return:"""
<|body_1|>
def get... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutoMlRule:
"""Auto ML related conf get/set common methos"""
def __init__(self, key=None):
"""init key variable :param key: :return:"""
if key is not None:
self.key = key
self.conf = self.get_train_obj(key)
def get_graph_type_list(self, graph_id):
"""g... | the_stack_v2_python_sparse | master/automl/automl_rule.py | yurimkoo/tensormsa | train | 1 |
4b1517d47cd1141ad46e5227023a7078dc59f1c7 | [
"anzVersucheText = ''\ni = 0\nwhile i < p_anzVersuche and (not self.__loginOK):\n os.system(p_cl)\n print(anzVersucheText)\n u_lo = input('Login\\t: ')\n u_pw = input('Pass\\t: ')\n if u_lo in self.__loPwDict and self.__loPwDict[u_lo] == u_pw:\n self.__loginOK = True\n break\n i += 1... | <|body_start_0|>
anzVersucheText = ''
i = 0
while i < p_anzVersuche and (not self.__loginOK):
os.system(p_cl)
print(anzVersucheText)
u_lo = input('Login\t: ')
u_pw = input('Pass\t: ')
if u_lo in self.__loPwDict and self.__loPwDict[u_lo]... | Eine Klasse für eine Login Funktionalität | loKlasse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class loKlasse:
"""Eine Klasse für eine Login Funktionalität"""
def loginCheck(self, p_anzVersuche, p_cl):
"""Return: True bei Login erfolgreich False bei Login nicht erfolgreich"""
<|body_0|>
def loginListeSortiert(self, p_spaltenUeberschriftenRef, p_spaltenBreiteRef=30):
... | stack_v2_sparse_classes_75kplus_train_009219 | 4,716 | no_license | [
{
"docstring": "Return: True bei Login erfolgreich False bei Login nicht erfolgreich",
"name": "loginCheck",
"signature": "def loginCheck(self, p_anzVersuche, p_cl)"
},
{
"docstring": "Gibt eine formatierte Liste aller Logins mit Passwort nach Login sortiert zurück.",
"name": "loginListeSort... | 3 | stack_v2_sparse_classes_30k_train_011317 | Implement the Python class `loKlasse` described below.
Class description:
Eine Klasse für eine Login Funktionalität
Method signatures and docstrings:
- def loginCheck(self, p_anzVersuche, p_cl): Return: True bei Login erfolgreich False bei Login nicht erfolgreich
- def loginListeSortiert(self, p_spaltenUeberschriften... | Implement the Python class `loKlasse` described below.
Class description:
Eine Klasse für eine Login Funktionalität
Method signatures and docstrings:
- def loginCheck(self, p_anzVersuche, p_cl): Return: True bei Login erfolgreich False bei Login nicht erfolgreich
- def loginListeSortiert(self, p_spaltenUeberschriften... | 78c440bb44e5c628af9705dae53c827e1e0ae315 | <|skeleton|>
class loKlasse:
"""Eine Klasse für eine Login Funktionalität"""
def loginCheck(self, p_anzVersuche, p_cl):
"""Return: True bei Login erfolgreich False bei Login nicht erfolgreich"""
<|body_0|>
def loginListeSortiert(self, p_spaltenUeberschriftenRef, p_spaltenBreiteRef=30):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class loKlasse:
"""Eine Klasse für eine Login Funktionalität"""
def loginCheck(self, p_anzVersuche, p_cl):
"""Return: True bei Login erfolgreich False bei Login nicht erfolgreich"""
anzVersucheText = ''
i = 0
while i < p_anzVersuche and (not self.__loginOK):
os.syste... | the_stack_v2_python_sparse | schulung/06_2_Uebung/10_login_oop.py | sjuerges/python_schulung | train | 0 |
e5d279e2d19afd33a8c22701ffd0dbb1a0b33f7a | [
"if node is None:\n return None\noriginal = set()\noriginal.add(node)\nself.findNode(original, node)\npossibleNodes = dict()\nanswer = Node(node.val)\npossibleNodes[answer.val] = answer\nfor n in original:\n if n.val not in possibleNodes.keys():\n possibleNodes[n.val] = Node(n.val)\nfor n in original:\... | <|body_start_0|>
if node is None:
return None
original = set()
original.add(node)
self.findNode(original, node)
possibleNodes = dict()
answer = Node(node.val)
possibleNodes[answer.val] = answer
for n in original:
if n.val not in pos... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def cloneGraph(self, node):
""":type node: Node :rtype: Node"""
<|body_0|>
def findNode(self, original, node):
""":type original: set(Node) :node: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if node is None:
return Non... | stack_v2_sparse_classes_75kplus_train_009220 | 1,917 | permissive | [
{
"docstring": ":type node: Node :rtype: Node",
"name": "cloneGraph",
"signature": "def cloneGraph(self, node)"
},
{
"docstring": ":type original: set(Node) :node: Node",
"name": "findNode",
"signature": "def findNode(self, original, node)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def cloneGraph(self, node): :type node: Node :rtype: Node
- def findNode(self, original, node): :type original: set(Node) :node: Node | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def cloneGraph(self, node): :type node: Node :rtype: Node
- def findNode(self, original, node): :type original: set(Node) :node: Node
<|skeleton|>
class Solution:
def clone... | c60b332866caa28e1ae5e216cbfc2c6f869a751a | <|skeleton|>
class Solution:
def cloneGraph(self, node):
""":type node: Node :rtype: Node"""
<|body_0|>
def findNode(self, original, node):
""":type original: set(Node) :node: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def cloneGraph(self, node):
""":type node: Node :rtype: Node"""
if node is None:
return None
original = set()
original.add(node)
self.findNode(original, node)
possibleNodes = dict()
answer = Node(node.val)
possibleNodes[answ... | the_stack_v2_python_sparse | leetcode/medium/graph/test_clone_graph.py | yenbohuang/online-contest-python | train | 0 | |
ddfae3bb6791a60ccdcb0960b507b11eaed3ebd7 | [
"mask_list = []\ntry:\n lines = value.split('\\n')\n for line in lines:\n if 'MaskBTPParameters' in line:\n mask_strings = re.findall('append\\\\((.+)\\\\)', line.strip())\n for item in mask_strings:\n mask_list.append(eval(item.lower()))\nexcept:\n logging.excep... | <|body_start_0|>
mask_list = []
try:
lines = value.split('\n')
for line in lines:
if 'MaskBTPParameters' in line:
mask_strings = re.findall('append\\((.+)\\)', line.strip())
for item in mask_strings:
... | Simple form for a mask entry. A combination of banks, tubes, pixels can be specified. | MaskForm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskForm:
"""Simple form for a mask entry. A combination of banks, tubes, pixels can be specified."""
def to_tokens(cls, value):
"""Takes a block of Mantid script and extract the dictionary argument. The template should be like MaskBTPParameters({'Bank':'', 'Tube':'', 'Pixel':''}) :p... | stack_v2_sparse_classes_75kplus_train_009221 | 17,630 | permissive | [
{
"docstring": "Takes a block of Mantid script and extract the dictionary argument. The template should be like MaskBTPParameters({'Bank':'', 'Tube':'', 'Pixel':''}) :param value: string value for the code snippet",
"name": "to_tokens",
"signature": "def to_tokens(cls, value)"
},
{
"docstring": ... | 5 | null | Implement the Python class `MaskForm` described below.
Class description:
Simple form for a mask entry. A combination of banks, tubes, pixels can be specified.
Method signatures and docstrings:
- def to_tokens(cls, value): Takes a block of Mantid script and extract the dictionary argument. The template should be like... | Implement the Python class `MaskForm` described below.
Class description:
Simple form for a mask entry. A combination of banks, tubes, pixels can be specified.
Method signatures and docstrings:
- def to_tokens(cls, value): Takes a block of Mantid script and extract the dictionary argument. The template should be like... | ff55e4e1a0203a6966fc9dab6b49e0d6dd03d18d | <|skeleton|>
class MaskForm:
"""Simple form for a mask entry. A combination of banks, tubes, pixels can be specified."""
def to_tokens(cls, value):
"""Takes a block of Mantid script and extract the dictionary argument. The template should be like MaskBTPParameters({'Bank':'', 'Tube':'', 'Pixel':''}) :p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaskForm:
"""Simple form for a mask entry. A combination of banks, tubes, pixels can be specified."""
def to_tokens(cls, value):
"""Takes a block of Mantid script and extract the dictionary argument. The template should be like MaskBTPParameters({'Bank':'', 'Tube':'', 'Pixel':''}) :param value: s... | the_stack_v2_python_sparse | src/webmon_app/reporting/reduction/forms.py | neutrons/data_workflow | train | 4 |
ce525d11618e921d64bef77b8b8a15b9cdc45ed6 | [
"try:\n addr = self.filter(passport_id=passport_id, is_default=True).get(is_delete=False)\nexcept self.model.DoesNotExist:\n addr = None\nreturn addr",
"addr = self.get_default_address(passport_id=passport_id)\nif addr:\n is_default = False\nelse:\n is_default = True\naddr = self.create(passport_id=pa... | <|body_start_0|>
try:
addr = self.filter(passport_id=passport_id, is_default=True).get(is_delete=False)
except self.model.DoesNotExist:
addr = None
return addr
<|end_body_0|>
<|body_start_1|>
addr = self.get_default_address(passport_id=passport_id)
if add... | 地址模型管理器类 | AddressManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddressManager:
"""地址模型管理器类"""
def get_default_address(self, passport_id):
"""查询指定用户的默认收货地址"""
<|body_0|>
def add_one_address(self, passport_id, recipient_name, recipient_addr, zip_code, recipient_phone):
"""添加收货地址"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_009222 | 3,320 | no_license | [
{
"docstring": "查询指定用户的默认收货地址",
"name": "get_default_address",
"signature": "def get_default_address(self, passport_id)"
},
{
"docstring": "添加收货地址",
"name": "add_one_address",
"signature": "def add_one_address(self, passport_id, recipient_name, recipient_addr, zip_code, recipient_phone)"... | 2 | stack_v2_sparse_classes_30k_val_000389 | Implement the Python class `AddressManager` described below.
Class description:
地址模型管理器类
Method signatures and docstrings:
- def get_default_address(self, passport_id): 查询指定用户的默认收货地址
- def add_one_address(self, passport_id, recipient_name, recipient_addr, zip_code, recipient_phone): 添加收货地址 | Implement the Python class `AddressManager` described below.
Class description:
地址模型管理器类
Method signatures and docstrings:
- def get_default_address(self, passport_id): 查询指定用户的默认收货地址
- def add_one_address(self, passport_id, recipient_name, recipient_addr, zip_code, recipient_phone): 添加收货地址
<|skeleton|>
class Address... | fc7fc38268f3bfeaa6cdf4c7c1f5e53076efb27d | <|skeleton|>
class AddressManager:
"""地址模型管理器类"""
def get_default_address(self, passport_id):
"""查询指定用户的默认收货地址"""
<|body_0|>
def add_one_address(self, passport_id, recipient_name, recipient_addr, zip_code, recipient_phone):
"""添加收货地址"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddressManager:
"""地址模型管理器类"""
def get_default_address(self, passport_id):
"""查询指定用户的默认收货地址"""
try:
addr = self.filter(passport_id=passport_id, is_default=True).get(is_delete=False)
except self.model.DoesNotExist:
addr = None
return addr
def ad... | the_stack_v2_python_sparse | Book/users/models.py | wantaname/django | train | 15 |
379b5a449a63113f8ab2b79ca5a43985136983ae | [
"self.id = id\nself.access_token = access_token\nself.expires_in = expires_in\nself.refresh_token = refresh_token\nself.error = error\nself.user_name = user_name\nself.insurance_centre_name = insurance_centre_name\nself.insurance_centre_logo = insurance_centre_logo\nself.insurance_centre_favicon = insurance_centre_... | <|body_start_0|>
self.id = id
self.access_token = access_token
self.expires_in = expires_in
self.refresh_token = refresh_token
self.error = error
self.user_name = user_name
self.insurance_centre_name = insurance_centre_name
self.insurance_centre_logo = ins... | Implementation of the 'get Access Token User Info' model. TODO: type model description here. Attributes: id (string): TODO: type description here. access_token (string): TODO: type description here. expires_in (string): TODO: type description here. refresh_token (string): TODO: type description here. error (string): TO... | GetAccessTokenUserInfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetAccessTokenUserInfo:
"""Implementation of the 'get Access Token User Info' model. TODO: type model description here. Attributes: id (string): TODO: type description here. access_token (string): TODO: type description here. expires_in (string): TODO: type description here. refresh_token (string... | stack_v2_sparse_classes_75kplus_train_009223 | 6,632 | permissive | [
{
"docstring": "Constructor for the GetAccessTokenUserInfo class",
"name": "__init__",
"signature": "def __init__(self, id=None, access_token=None, expires_in=None, refresh_token=None, user_name=None, insurance_centre_name=None, insurance_centre_logo=None, licensed=None, email=None, insurance_centre_typ... | 2 | stack_v2_sparse_classes_30k_train_047286 | Implement the Python class `GetAccessTokenUserInfo` described below.
Class description:
Implementation of the 'get Access Token User Info' model. TODO: type model description here. Attributes: id (string): TODO: type description here. access_token (string): TODO: type description here. expires_in (string): TODO: type ... | Implement the Python class `GetAccessTokenUserInfo` described below.
Class description:
Implementation of the 'get Access Token User Info' model. TODO: type model description here. Attributes: id (string): TODO: type description here. access_token (string): TODO: type description here. expires_in (string): TODO: type ... | b574a76a8805b306a423229b572c36dae0159def | <|skeleton|>
class GetAccessTokenUserInfo:
"""Implementation of the 'get Access Token User Info' model. TODO: type model description here. Attributes: id (string): TODO: type description here. access_token (string): TODO: type description here. expires_in (string): TODO: type description here. refresh_token (string... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetAccessTokenUserInfo:
"""Implementation of the 'get Access Token User Info' model. TODO: type model description here. Attributes: id (string): TODO: type description here. access_token (string): TODO: type description here. expires_in (string): TODO: type description here. refresh_token (string): TODO: type... | the_stack_v2_python_sparse | easybimehlanding/models/get_access_token_user_info.py | kmelodi/EasyBimehLanding_Python | train | 0 |
32bb08eae13f268e63f69e11ac9a3e42bcc22f68 | [
"ser = GetDepositDetailsSerializer(data=request.query_params)\nif ser.is_valid(raise_exception=False):\n return send_200(data=ser.data, message='deposit details fetched')\nreturn send_400(status='FAILURE', data={'errors': ser.errors}, message=ser.extract_error_msg())",
"data = dict(request.data)\nser = CreateD... | <|body_start_0|>
ser = GetDepositDetailsSerializer(data=request.query_params)
if ser.is_valid(raise_exception=False):
return send_200(data=ser.data, message='deposit details fetched')
return send_400(status='FAILURE', data={'errors': ser.errors}, message=ser.extract_error_msg())
<|en... | DepositInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DepositInfo:
def get(self, request):
"""Get all deposits in a portfolio"""
<|body_0|>
def post(self, request):
"""Deposit to a portfolio"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ser = GetDepositDetailsSerializer(data=request.query_params)
... | stack_v2_sparse_classes_75kplus_train_009224 | 4,648 | no_license | [
{
"docstring": "Get all deposits in a portfolio",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Deposit to a portfolio",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027346 | Implement the Python class `DepositInfo` described below.
Class description:
Implement the DepositInfo class.
Method signatures and docstrings:
- def get(self, request): Get all deposits in a portfolio
- def post(self, request): Deposit to a portfolio | Implement the Python class `DepositInfo` described below.
Class description:
Implement the DepositInfo class.
Method signatures and docstrings:
- def get(self, request): Get all deposits in a portfolio
- def post(self, request): Deposit to a portfolio
<|skeleton|>
class DepositInfo:
def get(self, request):
... | 3a64de39af7c51f6702c0e84a9c034055d72780e | <|skeleton|>
class DepositInfo:
def get(self, request):
"""Get all deposits in a portfolio"""
<|body_0|>
def post(self, request):
"""Deposit to a portfolio"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DepositInfo:
def get(self, request):
"""Get all deposits in a portfolio"""
ser = GetDepositDetailsSerializer(data=request.query_params)
if ser.is_valid(raise_exception=False):
return send_200(data=ser.data, message='deposit details fetched')
return send_400(status='... | the_stack_v2_python_sparse | stashaway/api/deposit.py | ritzvik/sample-portfolio-manager | train | 0 | |
aeb3ab99d75b26bd66743ad4a6bee3666807a4ab | [
"tests = {'3': 3, '3 dozen': 36, '50 dozen kW': 600000, '1 / 10': 0.1, '1/2 kW': 500, '1/2 dozen kW': 6000, '0.005 MW': 5000}\nfor val, expected in tests.items():\n q = InvenTree.conversion.convert_physical_value(val, 'W')\n self.assertAlmostEqual(q, expected, 0.01)\n q = InvenTree.conversion.convert_physi... | <|body_start_0|>
tests = {'3': 3, '3 dozen': 36, '50 dozen kW': 600000, '1 / 10': 0.1, '1/2 kW': 500, '1/2 dozen kW': 6000, '0.005 MW': 5000}
for val, expected in tests.items():
q = InvenTree.conversion.convert_physical_value(val, 'W')
self.assertAlmostEqual(q, expected, 0.01)
... | Tests for conversion of physical units | ConversionTest | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConversionTest:
"""Tests for conversion of physical units"""
def test_base_units(self):
"""Test conversion to specified base units"""
<|body_0|>
def test_dimensionless_units(self):
"""Tests for 'dimensonless' unit quantities"""
<|body_1|>
def test_in... | stack_v2_sparse_classes_75kplus_train_009225 | 41,191 | permissive | [
{
"docstring": "Test conversion to specified base units",
"name": "test_base_units",
"signature": "def test_base_units(self)"
},
{
"docstring": "Tests for 'dimensonless' unit quantities",
"name": "test_dimensionless_units",
"signature": "def test_dimensionless_units(self)"
},
{
"... | 4 | stack_v2_sparse_classes_30k_train_043009 | Implement the Python class `ConversionTest` described below.
Class description:
Tests for conversion of physical units
Method signatures and docstrings:
- def test_base_units(self): Test conversion to specified base units
- def test_dimensionless_units(self): Tests for 'dimensonless' unit quantities
- def test_invali... | Implement the Python class `ConversionTest` described below.
Class description:
Tests for conversion of physical units
Method signatures and docstrings:
- def test_base_units(self): Test conversion to specified base units
- def test_dimensionless_units(self): Tests for 'dimensonless' unit quantities
- def test_invali... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class ConversionTest:
"""Tests for conversion of physical units"""
def test_base_units(self):
"""Test conversion to specified base units"""
<|body_0|>
def test_dimensionless_units(self):
"""Tests for 'dimensonless' unit quantities"""
<|body_1|>
def test_in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConversionTest:
"""Tests for conversion of physical units"""
def test_base_units(self):
"""Test conversion to specified base units"""
tests = {'3': 3, '3 dozen': 36, '50 dozen kW': 600000, '1 / 10': 0.1, '1/2 kW': 500, '1/2 dozen kW': 6000, '0.005 MW': 5000}
for val, expected in t... | the_stack_v2_python_sparse | InvenTree/InvenTree/tests.py | inventree/InvenTree | train | 3,077 |
092d7f1d4fbcb6c5d20129cfa6bed7e8e4c36b25 | [
"if n == 0:\n return []\n\ndef generate(l, r):\n res = []\n for i in range(l, r + 1):\n for ll in generate(l, i - 1):\n for rr in generate(i + 1, r):\n root = TreeNode(i)\n root.left = ll\n root.right = rr\n res += (root,)\n r... | <|body_start_0|>
if n == 0:
return []
def generate(l, r):
res = []
for i in range(l, r + 1):
for ll in generate(l, i - 1):
for rr in generate(i + 1, r):
root = TreeNode(i)
root.left =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
<|body_0|>
def generateTrees2(self, n):
""":type n: int :rtype: List[TreeNode]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 0:
return []
... | stack_v2_sparse_classes_75kplus_train_009226 | 1,507 | no_license | [
{
"docstring": ":type n: int :rtype: List[TreeNode]",
"name": "generateTrees",
"signature": "def generateTrees(self, n)"
},
{
"docstring": ":type n: int :rtype: List[TreeNode]",
"name": "generateTrees2",
"signature": "def generateTrees2(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021340 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateTrees(self, n): :type n: int :rtype: List[TreeNode]
- def generateTrees2(self, n): :type n: int :rtype: List[TreeNode] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateTrees(self, n): :type n: int :rtype: List[TreeNode]
- def generateTrees2(self, n): :type n: int :rtype: List[TreeNode]
<|skeleton|>
class Solution:
def generate... | 4105e18050b15fc0409c75353ad31be17187dd34 | <|skeleton|>
class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
<|body_0|>
def generateTrees2(self, n):
""":type n: int :rtype: List[TreeNode]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
if n == 0:
return []
def generate(l, r):
res = []
for i in range(l, r + 1):
for ll in generate(l, i - 1):
for rr in generate(i + 1, r... | the_stack_v2_python_sparse | generateTrees.py | NeilWangziyu/Leetcode_py | train | 2 | |
c4fe998291186c383b796494c24d8eb0f77027fa | [
"super(SpectralNormConv2D, self).__init__()\nself.filters = filters\nself.kernel_size = kernel_size\nself.stride = stride\nself.padding = padding.upper()\nself.iteration = iteration\nself.scope = scope",
"with tf.variable_scope(self.scope):\n w = tf.get_variable('kernel', shape=[self.kernel_size, self.kernel_s... | <|body_start_0|>
super(SpectralNormConv2D, self).__init__()
self.filters = filters
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding.upper()
self.iteration = iteration
self.scope = scope
<|end_body_0|>
<|body_start_1|>
with tf.var... | SpectralNormConv2D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpectralNormConv2D:
def __init__(self, filters, kernel_size=3, stride=1, padding='same', iteration=1, scope='sn_conv'):
"""Convolutional layer containing a wrapper to the spectral_norm() operation. Args: filters (int): number of filters kernel_size (int): kernel size for the convolutiona... | stack_v2_sparse_classes_75kplus_train_009227 | 5,370 | permissive | [
{
"docstring": "Convolutional layer containing a wrapper to the spectral_norm() operation. Args: filters (int): number of filters kernel_size (int): kernel size for the convolutional layer stride (int): stride for the convolutional layer padding (str): padding to apply to the convolved tensor iteration (int): p... | 2 | stack_v2_sparse_classes_30k_test_001353 | Implement the Python class `SpectralNormConv2D` described below.
Class description:
Implement the SpectralNormConv2D class.
Method signatures and docstrings:
- def __init__(self, filters, kernel_size=3, stride=1, padding='same', iteration=1, scope='sn_conv'): Convolutional layer containing a wrapper to the spectral_n... | Implement the Python class `SpectralNormConv2D` described below.
Class description:
Implement the SpectralNormConv2D class.
Method signatures and docstrings:
- def __init__(self, filters, kernel_size=3, stride=1, padding='same', iteration=1, scope='sn_conv'): Convolutional layer containing a wrapper to the spectral_n... | fc05d70d411d20147075392c14fced274c1bf6ee | <|skeleton|>
class SpectralNormConv2D:
def __init__(self, filters, kernel_size=3, stride=1, padding='same', iteration=1, scope='sn_conv'):
"""Convolutional layer containing a wrapper to the spectral_norm() operation. Args: filters (int): number of filters kernel_size (int): kernel size for the convolutiona... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpectralNormConv2D:
def __init__(self, filters, kernel_size=3, stride=1, padding='same', iteration=1, scope='sn_conv'):
"""Convolutional layer containing a wrapper to the spectral_norm() operation. Args: filters (int): number of filters kernel_size (int): kernel size for the convolutional layer stride... | the_stack_v2_python_sparse | idas/losses/models/layers/spectral_norm.py | gvalvano/multiscale-adversarial-attention-gates | train | 40 | |
3237fd9296bda93a3196eeecf039920b8a16a93c | [
"super().__init__(name=name)\nself.agent = agent\nself.env = env\nself.return_obs = return_obs\nself.return_action = return_action\nself.GymOutput = GymOutput(self.return_obs, self.return_action)",
"action = hk.get_state('action', shape=[], init=lambda *_: self.GymState(self.agent(raw_obs)))\nrw, obs = self.env(a... | <|body_start_0|>
super().__init__(name=name)
self.agent = agent
self.env = env
self.return_obs = return_obs
self.return_action = return_action
self.GymOutput = GymOutput(self.return_obs, self.return_action)
<|end_body_0|>
<|body_start_1|>
action = hk.get_state('a... | Gym feedback between an agent and a Gym environment. | GymFeedback | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GymFeedback:
"""Gym feedback between an agent and a Gym environment."""
def __init__(self, agent, env, return_obs=False, return_action=False, name=None):
"""Initialize module. Args: agent : Gym environment used to unroll the data and feed the agent. env : Gym environment used to unro... | stack_v2_sparse_classes_75kplus_train_009228 | 3,205 | permissive | [
{
"docstring": "Initialize module. Args: agent : Gym environment used to unroll the data and feed the agent. env : Gym environment used to unroll the data and feed the agent. return_obs : if true return environment observation return_action : if true return agent action name : name of the module",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_029271 | Implement the Python class `GymFeedback` described below.
Class description:
Gym feedback between an agent and a Gym environment.
Method signatures and docstrings:
- def __init__(self, agent, env, return_obs=False, return_action=False, name=None): Initialize module. Args: agent : Gym environment used to unroll the da... | Implement the Python class `GymFeedback` described below.
Class description:
Gym feedback between an agent and a Gym environment.
Method signatures and docstrings:
- def __init__(self, agent, env, return_obs=False, return_action=False, name=None): Initialize module. Args: agent : Gym environment used to unroll the da... | ab18e064f9fa1c95458978f501efb6cde9ab64d5 | <|skeleton|>
class GymFeedback:
"""Gym feedback between an agent and a Gym environment."""
def __init__(self, agent, env, return_obs=False, return_action=False, name=None):
"""Initialize module. Args: agent : Gym environment used to unroll the data and feed the agent. env : Gym environment used to unro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GymFeedback:
"""Gym feedback between an agent and a Gym environment."""
def __init__(self, agent, env, return_obs=False, return_action=False, name=None):
"""Initialize module. Args: agent : Gym environment used to unroll the data and feed the agent. env : Gym environment used to unroll the data a... | the_stack_v2_python_sparse | wax/modules/gym_feedback.py | zggl/wax-ml | train | 0 |
4457353920588e75b4c70e58a763ca350de6414f | [
"self.id = _id\nself.name = name\nself.sex = sex\nself.birt: Optional[Dict[str, str]] = birt\nself.alive = alive\nself.deat: Optional[bool, Dict[str, str]] = deat\nself.famc: List[str] = []\nself.fams: List[str] = []",
"today = date.today()\nbirthday = datetime.strptime(self.birt['date'], '%d %b %Y')\nage = today... | <|body_start_0|>
self.id = _id
self.name = name
self.sex = sex
self.birt: Optional[Dict[str, str]] = birt
self.alive = alive
self.deat: Optional[bool, Dict[str, str]] = deat
self.famc: List[str] = []
self.fams: List[str] = []
<|end_body_0|>
<|body_start_1... | holds an Individual record | Individual | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Individual:
"""holds an Individual record"""
def __init__(self, _id=None, name=None, sex=None, birt=None, alive=True, deat=False):
"""store Individual info"""
<|body_0|>
def age(self):
"""calculate age using the birth date"""
<|body_1|>
def info(self... | stack_v2_sparse_classes_75kplus_train_009229 | 4,191 | no_license | [
{
"docstring": "store Individual info",
"name": "__init__",
"signature": "def __init__(self, _id=None, name=None, sex=None, birt=None, alive=True, deat=False)"
},
{
"docstring": "calculate age using the birth date",
"name": "age",
"signature": "def age(self)"
},
{
"docstring": "r... | 3 | stack_v2_sparse_classes_30k_train_003733 | Implement the Python class `Individual` described below.
Class description:
holds an Individual record
Method signatures and docstrings:
- def __init__(self, _id=None, name=None, sex=None, birt=None, alive=True, deat=False): store Individual info
- def age(self): calculate age using the birth date
- def info(self): r... | Implement the Python class `Individual` described below.
Class description:
holds an Individual record
Method signatures and docstrings:
- def __init__(self, _id=None, name=None, sex=None, birt=None, alive=True, deat=False): store Individual info
- def age(self): calculate age using the birth date
- def info(self): r... | 7017c9ff6d45835bf07cf81b711eec2b80738ad7 | <|skeleton|>
class Individual:
"""holds an Individual record"""
def __init__(self, _id=None, name=None, sex=None, birt=None, alive=True, deat=False):
"""store Individual info"""
<|body_0|>
def age(self):
"""calculate age using the birth date"""
<|body_1|>
def info(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Individual:
"""holds an Individual record"""
def __init__(self, _id=None, name=None, sex=None, birt=None, alive=True, deat=False):
"""store Individual info"""
self.id = _id
self.name = name
self.sex = sex
self.birt: Optional[Dict[str, str]] = birt
self.aliv... | the_stack_v2_python_sparse | HW(Agile)/birthbrforemarriageofparents.py | janki1997/CS-555 | train | 0 |
eb494d5823a5f611c6ab624a0c1ca7851b88ce91 | [
"super().__init__(*args, **kwargs)\nendpoints = current_app.config.get('RECORDS_REST_ENDPOINTS', [])\ndocument_endpoint = endpoints.get(DOCUMENT_PID_TYPE, {})\nself.max_result_window = document_endpoint.get('max_result_window', RECORDS_REST_MAX_RESULT_WINDOW)",
"size_param = request.args.get('size', self.default_... | <|body_start_0|>
super().__init__(*args, **kwargs)
endpoints = current_app.config.get('RECORDS_REST_ENDPOINTS', [])
document_endpoint = endpoints.get(DOCUMENT_PID_TYPE, {})
self.max_result_window = document_endpoint.get('max_result_window', RECORDS_REST_MAX_RESULT_WINDOW)
<|end_body_0|>
... | Statistics view for the documents with the most loans. | MostLoanedDocumentsResource | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MostLoanedDocumentsResource:
"""Statistics view for the documents with the most loans."""
def __init__(self, *args, **kwargs):
"""Constructor."""
<|body_0|>
def _validate_bucket_size(self):
"""Validate bucket size parameter."""
<|body_1|>
def _valida... | stack_v2_sparse_classes_75kplus_train_009230 | 4,933 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Validate bucket size parameter.",
"name": "_validate_bucket_size",
"signature": "def _validate_bucket_size(self)"
},
{
"docstring": "Validate start date range ... | 4 | stack_v2_sparse_classes_30k_train_047314 | Implement the Python class `MostLoanedDocumentsResource` described below.
Class description:
Statistics view for the documents with the most loans.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructor.
- def _validate_bucket_size(self): Validate bucket size parameter.
- def _validate_s... | Implement the Python class `MostLoanedDocumentsResource` described below.
Class description:
Statistics view for the documents with the most loans.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructor.
- def _validate_bucket_size(self): Validate bucket size parameter.
- def _validate_s... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class MostLoanedDocumentsResource:
"""Statistics view for the documents with the most loans."""
def __init__(self, *args, **kwargs):
"""Constructor."""
<|body_0|>
def _validate_bucket_size(self):
"""Validate bucket size parameter."""
<|body_1|>
def _valida... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MostLoanedDocumentsResource:
"""Statistics view for the documents with the most loans."""
def __init__(self, *args, **kwargs):
"""Constructor."""
super().__init__(*args, **kwargs)
endpoints = current_app.config.get('RECORDS_REST_ENDPOINTS', [])
document_endpoint = endpoint... | the_stack_v2_python_sparse | invenio_app_ils/circulation/stats/views.py | inveniosoftware/invenio-app-ils | train | 64 |
264dda141f7fe79e24926e64483dfaf3fd91294c | [
"self.head = DLLNode(-1, -1)\nself.tail = DLLNode(-1, -1)\nself.head.next = self.tail\nself.tail.prev = self.head\nself.hashtable = {}\nself.capacity = capacity\nself.length = 0",
"if key in self.hashtable.keys():\n node = self.hashtable[key]\n node.prev.next = node.next\n node.next.prev = node.prev\n ... | <|body_start_0|>
self.head = DLLNode(-1, -1)
self.tail = DLLNode(-1, -1)
self.head.next = self.tail
self.tail.prev = self.head
self.hashtable = {}
self.capacity = capacity
self.length = 0
<|end_body_0|>
<|body_start_1|>
if key in self.hashtable.keys():
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_009231 | 1,684 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_016881 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 12c2afc900f98501a665eb8cbcdc05ee3ef429f4 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.head = DLLNode(-1, -1)
self.tail = DLLNode(-1, -1)
self.head.next = self.tail
self.tail.prev = self.head
self.hashtable = {}
self.capacity = capacity
self.length = 0
def ... | the_stack_v2_python_sparse | problems/leetcode/lruCache.py | vshypko/coding_challenges | train | 0 | |
41d20cd35e9631d277dae0697dec0164458843dd | [
"_sorted = [0] * len(_list)\nc_length = max(_list) + 1\nc_list = [0] * c_length\n' Populate c list from provided unsorted list'\nfor number in _list:\n c_list[number] += 1\nc_list = self.run_c_prime(c_list)\n' Populate sorted list'\nfor each in _list:\n _sorted[c_list[each] - 1] = each\n c_list[each] -= 1\... | <|body_start_0|>
_sorted = [0] * len(_list)
c_length = max(_list) + 1
c_list = [0] * c_length
' Populate c list from provided unsorted list'
for number in _list:
c_list[number] += 1
c_list = self.run_c_prime(c_list)
' Populate sorted list'
for ... | countSort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class countSort:
def run_sort(self, _list):
"""Sort list of positive integers using the countSort Algorithm"""
<|body_0|>
def run_c_prime(self, c_list):
"""Build C` list by summing the x and x-1 elements of the list"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_009232 | 1,107 | no_license | [
{
"docstring": "Sort list of positive integers using the countSort Algorithm",
"name": "run_sort",
"signature": "def run_sort(self, _list)"
},
{
"docstring": "Build C` list by summing the x and x-1 elements of the list",
"name": "run_c_prime",
"signature": "def run_c_prime(self, c_list)"... | 2 | stack_v2_sparse_classes_30k_train_023169 | Implement the Python class `countSort` described below.
Class description:
Implement the countSort class.
Method signatures and docstrings:
- def run_sort(self, _list): Sort list of positive integers using the countSort Algorithm
- def run_c_prime(self, c_list): Build C` list by summing the x and x-1 elements of the ... | Implement the Python class `countSort` described below.
Class description:
Implement the countSort class.
Method signatures and docstrings:
- def run_sort(self, _list): Sort list of positive integers using the countSort Algorithm
- def run_c_prime(self, c_list): Build C` list by summing the x and x-1 elements of the ... | ea03e60b111423fb2c88a2ea4034560ea7318d51 | <|skeleton|>
class countSort:
def run_sort(self, _list):
"""Sort list of positive integers using the countSort Algorithm"""
<|body_0|>
def run_c_prime(self, c_list):
"""Build C` list by summing the x and x-1 elements of the list"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class countSort:
def run_sort(self, _list):
"""Sort list of positive integers using the countSort Algorithm"""
_sorted = [0] * len(_list)
c_length = max(_list) + 1
c_list = [0] * c_length
' Populate c list from provided unsorted list'
for number in _list:
... | the_stack_v2_python_sparse | countSort/Python/countSort.py | johncanthony/sorts | train | 0 | |
b707840a3ac5ca9b4115b77edd1bcb1f8da9022d | [
"self.name = 'Ausputzer'\nTemplateFunction.__init__(self, task_config, general_config)\nself.__execute()",
"self.finish()\nself.logger.info('Lösche alle temporären SDE-Connectionfiles')\nfor v in self.general_config['connections'].values():\n for cf in v.connection_files:\n self.logger.info(cf)\n v.d... | <|body_start_0|>
self.name = 'Ausputzer'
TemplateFunction.__init__(self, task_config, general_config)
self.__execute()
<|end_body_0|>
<|body_start_1|>
self.finish()
self.logger.info('Lösche alle temporären SDE-Connectionfiles')
for v in self.general_config['connections']... | Diese Funktion führt am Ende eines Imports/Tasks bestimmte Aufräumarbeiten aus: - Connection-Files löschen - Logging herunterfahren | Ausputzer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ausputzer:
"""Diese Funktion führt am Ende eines Imports/Tasks bestimmte Aufräumarbeiten aus: - Connection-Files löschen - Logging herunterfahren"""
def __init__(self, task_config, general_config):
"""Constructor :param task_config: Vom Usecase initialisierte task_config (Dictionary)... | stack_v2_sparse_classes_75kplus_train_009233 | 1,615 | no_license | [
{
"docstring": "Constructor :param task_config: Vom Usecase initialisierte task_config (Dictionary)",
"name": "__init__",
"signature": "def __init__(self, task_config, general_config)"
},
{
"docstring": "Führt den eigentlichen Funktionsablauf aus",
"name": "__execute",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_028779 | Implement the Python class `Ausputzer` described below.
Class description:
Diese Funktion führt am Ende eines Imports/Tasks bestimmte Aufräumarbeiten aus: - Connection-Files löschen - Logging herunterfahren
Method signatures and docstrings:
- def __init__(self, task_config, general_config): Constructor :param task_co... | Implement the Python class `Ausputzer` described below.
Class description:
Diese Funktion führt am Ende eines Imports/Tasks bestimmte Aufräumarbeiten aus: - Connection-Files löschen - Logging herunterfahren
Method signatures and docstrings:
- def __init__(self, task_config, general_config): Constructor :param task_co... | 65c1cdc83a40a0343800a839c6f3cbe61ec37abc | <|skeleton|>
class Ausputzer:
"""Diese Funktion führt am Ende eines Imports/Tasks bestimmte Aufräumarbeiten aus: - Connection-Files löschen - Logging herunterfahren"""
def __init__(self, task_config, general_config):
"""Constructor :param task_config: Vom Usecase initialisierte task_config (Dictionary)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ausputzer:
"""Diese Funktion führt am Ende eines Imports/Tasks bestimmte Aufräumarbeiten aus: - Connection-Files löschen - Logging herunterfahren"""
def __init__(self, task_config, general_config):
"""Constructor :param task_config: Vom Usecase initialisierte task_config (Dictionary)"""
s... | the_stack_v2_python_sparse | src/iLader/functions/Ausputzer.py | AGIBE/iLader | train | 0 |
985be3ff5bd77b28230d49c34515b7defc5d4549 | [
"if not root:\n return '[]'\nqueue = collections.deque()\nqueue.append(root)\nres = []\nwhile queue:\n node = queue.popleft()\n if node:\n res.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\n else:\n res.append('null')\nreturn '[' + ','.join(res) +... | <|body_start_0|>
if not root:
return '[]'
queue = collections.deque()
queue.append(root)
res = []
while queue:
node = queue.popleft()
if node:
res.append(str(node.val))
queue.append(node.left)
que... | Codec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""将二叉树bfs遍历,并记录叶子节点"""
<|body_0|>
def deserialize(self, data):
"""根据bfs来复原二叉树"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return '[]'
queue = collections.deque()
queue.a... | stack_v2_sparse_classes_75kplus_train_009234 | 4,312 | permissive | [
{
"docstring": "将二叉树bfs遍历,并记录叶子节点",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "根据bfs来复原二叉树",
"name": "deserialize",
"signature": "def deserialize(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023018 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): 将二叉树bfs遍历,并记录叶子节点
- def deserialize(self, data): 根据bfs来复原二叉树 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): 将二叉树bfs遍历,并记录叶子节点
- def deserialize(self, data): 根据bfs来复原二叉树
<|skeleton|>
class Codec:
def serialize(self, root):
"""将二叉树bfs遍历,并记录叶子节点"""
... | b19233521c4e9a08cba6267eda743935e1fb06a6 | <|skeleton|>
class Codec:
def serialize(self, root):
"""将二叉树bfs遍历,并记录叶子节点"""
<|body_0|>
def deserialize(self, data):
"""根据bfs来复原二叉树"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""将二叉树bfs遍历,并记录叶子节点"""
if not root:
return '[]'
queue = collections.deque()
queue.append(root)
res = []
while queue:
node = queue.popleft()
if node:
res.append(str(node.val))
... | the_stack_v2_python_sparse | leetcode/offerIsComing/搜索与回溯算法/剑指 Offer 37. 序列化二叉树.py | wenhaoliang/leetcode | train | 0 | |
39efdf284bbfa8556a2146309c8b00e004e056ab | [
"self.device = device\nself.num_classes = num_classes\nself.batch_size = batch_size\nself.img_size = img_size\nself.dataframe = pd.read_csv(csv_path)\nself.depth = depth\ntrain_split, val_split, test_split = self.make_splits(val_percentage, test_num, shuffle_data)\nself.train_loader = self.get_dataloader(train_spli... | <|body_start_0|>
self.device = device
self.num_classes = num_classes
self.batch_size = batch_size
self.img_size = img_size
self.dataframe = pd.read_csv(csv_path)
self.depth = depth
train_split, val_split, test_split = self.make_splits(val_percentage, test_num, shu... | SegmentationAgent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegmentationAgent:
def __init__(self, val_percentage, test_num, num_classes, batch_size, img_size, csv_path, shuffle_data, learning_rate, depth, device):
"""A helper class to facilitate the training of the model"""
<|body_0|>
def make_splits(self, val_percentage=0.2, test_nu... | stack_v2_sparse_classes_75kplus_train_009235 | 3,720 | permissive | [
{
"docstring": "A helper class to facilitate the training of the model",
"name": "__init__",
"signature": "def __init__(self, val_percentage, test_num, num_classes, batch_size, img_size, csv_path, shuffle_data, learning_rate, depth, device)"
},
{
"docstring": "Split the data into train, validati... | 3 | stack_v2_sparse_classes_30k_val_001575 | Implement the Python class `SegmentationAgent` described below.
Class description:
Implement the SegmentationAgent class.
Method signatures and docstrings:
- def __init__(self, val_percentage, test_num, num_classes, batch_size, img_size, csv_path, shuffle_data, learning_rate, depth, device): A helper class to facilit... | Implement the Python class `SegmentationAgent` described below.
Class description:
Implement the SegmentationAgent class.
Method signatures and docstrings:
- def __init__(self, val_percentage, test_num, num_classes, batch_size, img_size, csv_path, shuffle_data, learning_rate, depth, device): A helper class to facilit... | a30e907e83fa5bbfb934d951b7c663b622104fcc | <|skeleton|>
class SegmentationAgent:
def __init__(self, val_percentage, test_num, num_classes, batch_size, img_size, csv_path, shuffle_data, learning_rate, depth, device):
"""A helper class to facilitate the training of the model"""
<|body_0|>
def make_splits(self, val_percentage=0.2, test_nu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SegmentationAgent:
def __init__(self, val_percentage, test_num, num_classes, batch_size, img_size, csv_path, shuffle_data, learning_rate, depth, device):
"""A helper class to facilitate the training of the model"""
self.device = device
self.num_classes = num_classes
self.batch_... | the_stack_v2_python_sparse | em/src/deep_segmentation/SegmentationAgent.py | tecdatalab/biostructure | train | 0 | |
20625469cafa2277557128136b04f4a20c578797 | [
"self.__parser = parser\nparser.add_argument('mapOrProtareFileName', help='The path to a map or protare file. If it is a map file then option \"--tid\" (and maybe \"--pid\") is required.')\nparser.add_argument('--pid', action='store', default=IDsModule.neutron, help='The PoPs id for the projectile. Only used if the... | <|body_start_0|>
self.__parser = parser
parser.add_argument('mapOrProtareFileName', help='The path to a map or protare file. If it is a map file then option "--tid" (and maybe "--pid") is required.')
parser.add_argument('--pid', action='store', default=IDsModule.neutron, help='The PoPs id for th... | SingleProtareArguments | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleProtareArguments:
def __init__(self, parser):
""":param parser: An argparse.ArgumentParser instance which will be updated with parameters for accessing a profile from a file."""
<|body_0|>
def protare(self, args, verbosity=0, lazyParsing=True):
"""Returns a pro... | stack_v2_sparse_classes_75kplus_train_009236 | 2,913 | permissive | [
{
"docstring": ":param parser: An argparse.ArgumentParser instance which will be updated with parameters for accessing a profile from a file.",
"name": "__init__",
"signature": "def __init__(self, parser)"
},
{
"docstring": "Returns a protare (i.e., \"reactionSuite\") instance that has been read... | 2 | stack_v2_sparse_classes_30k_train_039123 | Implement the Python class `SingleProtareArguments` described below.
Class description:
Implement the SingleProtareArguments class.
Method signatures and docstrings:
- def __init__(self, parser): :param parser: An argparse.ArgumentParser instance which will be updated with parameters for accessing a profile from a fi... | Implement the Python class `SingleProtareArguments` described below.
Class description:
Implement the SingleProtareArguments class.
Method signatures and docstrings:
- def __init__(self, parser): :param parser: An argparse.ArgumentParser instance which will be updated with parameters for accessing a profile from a fi... | 6ba80855ae47cb32c37f635d065b228fadb03412 | <|skeleton|>
class SingleProtareArguments:
def __init__(self, parser):
""":param parser: An argparse.ArgumentParser instance which will be updated with parameters for accessing a profile from a file."""
<|body_0|>
def protare(self, args, verbosity=0, lazyParsing=True):
"""Returns a pro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SingleProtareArguments:
def __init__(self, parser):
""":param parser: An argparse.ArgumentParser instance which will be updated with parameters for accessing a profile from a file."""
self.__parser = parser
parser.add_argument('mapOrProtareFileName', help='The path to a map or protare ... | the_stack_v2_python_sparse | LUPY/argumentsForScripts.py | LLNL/fudge | train | 21 | |
d5d848b66adf92824d83f6fb00f26c77dcb0bbac | [
"BaseBNNPrior.__init__(self, bnn_omega, components)\nself.params_to_exclude = []\nself.set_params_list(self.params_to_exclude)\nself.set_comps_qphi_to_e1e2()",
"kwargs = Dict()\nfor comp, param_name in self.params_to_realize:\n hyperparams = getattr(self, comp)[param_name].copy()\n kwargs[comp][param_name] ... | <|body_start_0|>
BaseBNNPrior.__init__(self, bnn_omega, components)
self.params_to_exclude = []
self.set_params_list(self.params_to_exclude)
self.set_comps_qphi_to_e1e2()
<|end_body_0|>
<|body_start_1|>
kwargs = Dict()
for comp, param_name in self.params_to_realize:
... | BNN prior with independent parameters Note ---- This BNNPrior is cosmology-agnostic. For a version that's useful for H0 inference, see `DiagonalCosmoBNNPrior`. | DiagonalBNNPrior | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiagonalBNNPrior:
"""BNN prior with independent parameters Note ---- This BNNPrior is cosmology-agnostic. For a version that's useful for H0 inference, see `DiagonalCosmoBNNPrior`."""
def __init__(self, bnn_omega, components):
"""Note ---- The dictionary attributes are copies of the ... | stack_v2_sparse_classes_75kplus_train_009237 | 2,765 | permissive | [
{
"docstring": "Note ---- The dictionary attributes are copies of the config corresponding to each component. The number of attributes depends on the number of components. Attributes ---------- components : list list of components, e.g. `lens_mass` lens_mass : dict profile type and parameters of the lens mass s... | 2 | stack_v2_sparse_classes_30k_train_046638 | Implement the Python class `DiagonalBNNPrior` described below.
Class description:
BNN prior with independent parameters Note ---- This BNNPrior is cosmology-agnostic. For a version that's useful for H0 inference, see `DiagonalCosmoBNNPrior`.
Method signatures and docstrings:
- def __init__(self, bnn_omega, components... | Implement the Python class `DiagonalBNNPrior` described below.
Class description:
BNN prior with independent parameters Note ---- This BNNPrior is cosmology-agnostic. For a version that's useful for H0 inference, see `DiagonalCosmoBNNPrior`.
Method signatures and docstrings:
- def __init__(self, bnn_omega, components... | 2a9a1b3eafbafef925bedab4b3137a3505a9b750 | <|skeleton|>
class DiagonalBNNPrior:
"""BNN prior with independent parameters Note ---- This BNNPrior is cosmology-agnostic. For a version that's useful for H0 inference, see `DiagonalCosmoBNNPrior`."""
def __init__(self, bnn_omega, components):
"""Note ---- The dictionary attributes are copies of the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiagonalBNNPrior:
"""BNN prior with independent parameters Note ---- This BNNPrior is cosmology-agnostic. For a version that's useful for H0 inference, see `DiagonalCosmoBNNPrior`."""
def __init__(self, bnn_omega, components):
"""Note ---- The dictionary attributes are copies of the config corres... | the_stack_v2_python_sparse | baobab/bnn_priors/diagonal_bnn_prior.py | jiwoncpark/baobab | train | 9 |
84fd418148ca146684f0f3cdfce5aec851176d04 | [
"self.commcell = commcell\nself.__xml = '\\n <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?><TMMsg_CreateTaskReq><taskInfo>\\n <task initiatedFrom=\"1\"ownerId=\"1\" ownerName=\"admin\" sequenceNumber=\"0\" taskType=\"1\"><taskFlags disabled=\"0\"/>\\n </task><appGroup/><subTasks ... | <|body_start_0|>
self.commcell = commcell
self.__xml = '\n <?xml version="1.0" encoding="UTF-8" standalone="no" ?><TMMsg_CreateTaskReq><taskInfo>\n <task initiatedFrom="1"ownerId="1" ownerName="admin" sequenceNumber="0" taskType="1"><taskFlags disabled="0"/>\n </task><appGroup/><sub... | Class for building a backup job summary report | Report | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Report:
"""Class for building a backup job summary report"""
def __init__(self, commcell):
"""Initialize the backup job summary report object"""
<|body_0|>
def set_format(self, format_type):
"""Sets the output format of a report Args: format_type (FormatType): Re... | stack_v2_sparse_classes_75kplus_train_009238 | 6,163 | permissive | [
{
"docstring": "Initialize the backup job summary report object",
"name": "__init__",
"signature": "def __init__(self, commcell)"
},
{
"docstring": "Sets the output format of a report Args: format_type (FormatType): Report format type",
"name": "set_format",
"signature": "def set_format(... | 4 | stack_v2_sparse_classes_30k_train_015932 | Implement the Python class `Report` described below.
Class description:
Class for building a backup job summary report
Method signatures and docstrings:
- def __init__(self, commcell): Initialize the backup job summary report object
- def set_format(self, format_type): Sets the output format of a report Args: format_... | Implement the Python class `Report` described below.
Class description:
Class for building a backup job summary report
Method signatures and docstrings:
- def __init__(self, commcell): Initialize the backup job summary report object
- def set_format(self, format_type): Sets the output format of a report Args: format_... | 6aa0beb426a95de877cd531602234515723ccc94 | <|skeleton|>
class Report:
"""Class for building a backup job summary report"""
def __init__(self, commcell):
"""Initialize the backup job summary report object"""
<|body_0|>
def set_format(self, format_type):
"""Sets the output format of a report Args: format_type (FormatType): Re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Report:
"""Class for building a backup job summary report"""
def __init__(self, commcell):
"""Initialize the backup job summary report object"""
self.commcell = commcell
self.__xml = '\n <?xml version="1.0" encoding="UTF-8" standalone="no" ?><TMMsg_CreateTaskReq><taskInfo>\... | the_stack_v2_python_sparse | cvpysdk/reports/backup_job_summary.py | jack1806/cvpysdk | train | 1 |
5f3a445898b096e21ec5b174ec7f46d36c60555a | [
"dfile_dct = {} if dfile_dct is None else dfile_dct\nassert isinstance(ddir, DataDir)\nself.dir = ddir\nself.file = types.SimpleNamespace()\nfor name, obj in dfile_dct.items():\n assert isinstance(name, str)\n assert isinstance(obj, DataFile)\n setattr(self.file, name, obj)",
"ddir = self.dir.stacked_ove... | <|body_start_0|>
dfile_dct = {} if dfile_dct is None else dfile_dct
assert isinstance(ddir, DataDir)
self.dir = ddir
self.file = types.SimpleNamespace()
for name, obj in dfile_dct.items():
assert isinstance(name, str)
assert isinstance(obj, DataFile)
... | a single-layered system of directories and files | DataLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataLayer:
"""a single-layered system of directories and files"""
def __init__(self, ddir, dfile_dct=None):
""":param ddir: a DataDir object :param dfiles: a sequence of pairs `(name, obj)` where `obj` is a DataFile instance that will be accessible as `obj.file.name`"""
<|bod... | stack_v2_sparse_classes_75kplus_train_009239 | 6,832 | permissive | [
{
"docstring": ":param ddir: a DataDir object :param dfiles: a sequence of pairs `(name, obj)` where `obj` is a DataFile instance that will be accessible as `obj.file.name`",
"name": "__init__",
"signature": "def __init__(self, ddir, dfile_dct=None)"
},
{
"docstring": "get a copy of this DataLay... | 2 | stack_v2_sparse_classes_30k_train_046234 | Implement the Python class `DataLayer` described below.
Class description:
a single-layered system of directories and files
Method signatures and docstrings:
- def __init__(self, ddir, dfile_dct=None): :param ddir: a DataDir object :param dfiles: a sequence of pairs `(name, obj)` where `obj` is a DataFile instance th... | Implement the Python class `DataLayer` described below.
Class description:
a single-layered system of directories and files
Method signatures and docstrings:
- def __init__(self, ddir, dfile_dct=None): :param ddir: a DataDir object :param dfiles: a sequence of pairs `(name, obj)` where `obj` is a DataFile instance th... | e52341a2b77b5e79b0e2cee73f48735d00fd6209 | <|skeleton|>
class DataLayer:
"""a single-layered system of directories and files"""
def __init__(self, ddir, dfile_dct=None):
""":param ddir: a DataDir object :param dfiles: a sequence of pairs `(name, obj)` where `obj` is a DataFile instance that will be accessible as `obj.file.name`"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataLayer:
"""a single-layered system of directories and files"""
def __init__(self, ddir, dfile_dct=None):
""":param ddir: a DataDir object :param dfiles: a sequence of pairs `(name, obj)` where `obj` is a DataFile instance that will be accessible as `obj.file.name`"""
dfile_dct = {} if ... | the_stack_v2_python_sparse | old_autodir/factory.py | avcopan/filesystem | train | 0 |
cd481317e2f86d7606eabad4513187d10cc982ec | [
"super(RepoAPI, self).get()\nproject_id = request.args.get('project_id', '')\nif action in self.actions:\n self_action = getattr(self, action.lower(), None)\n return self_action(project_id=project_id)\nelse:\n abort(404)",
"wi = Deployer(project_id=project_id)\ntag_list = wi.list_tag()\ntags = tag_list.s... | <|body_start_0|>
super(RepoAPI, self).get()
project_id = request.args.get('project_id', '')
if action in self.actions:
self_action = getattr(self, action.lower(), None)
return self_action(project_id=project_id)
else:
abort(404)
<|end_body_0|>
<|body_s... | RepoAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepoAPI:
def get(self, action, commit=None):
"""fetch project list or one item /project/<int:project_id> :return:"""
<|body_0|>
def tags(self, project_id=None):
"""fetch project list or one item /tag/ :return:"""
<|body_1|>
def branches(self, project_id=... | stack_v2_sparse_classes_75kplus_train_009240 | 1,793 | permissive | [
{
"docstring": "fetch project list or one item /project/<int:project_id> :return:",
"name": "get",
"signature": "def get(self, action, commit=None)"
},
{
"docstring": "fetch project list or one item /tag/ :return:",
"name": "tags",
"signature": "def tags(self, project_id=None)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_048852 | Implement the Python class `RepoAPI` described below.
Class description:
Implement the RepoAPI class.
Method signatures and docstrings:
- def get(self, action, commit=None): fetch project list or one item /project/<int:project_id> :return:
- def tags(self, project_id=None): fetch project list or one item /tag/ :retur... | Implement the Python class `RepoAPI` described below.
Class description:
Implement the RepoAPI class.
Method signatures and docstrings:
- def get(self, action, commit=None): fetch project list or one item /project/<int:project_id> :return:
- def tags(self, project_id=None): fetch project list or one item /tag/ :retur... | a306f8212a2671411125f61a850b5869d315e283 | <|skeleton|>
class RepoAPI:
def get(self, action, commit=None):
"""fetch project list or one item /project/<int:project_id> :return:"""
<|body_0|>
def tags(self, project_id=None):
"""fetch project list or one item /tag/ :return:"""
<|body_1|>
def branches(self, project_id=... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RepoAPI:
def get(self, action, commit=None):
"""fetch project list or one item /project/<int:project_id> :return:"""
super(RepoAPI, self).get()
project_id = request.args.get('project_id', '')
if action in self.actions:
self_action = getattr(self, action.lower(), Non... | the_stack_v2_python_sparse | walle/api/repo.py | fu648126437/walle-web | train | 2 | |
94fbe87c140bc01ba9c278daf7f6e1346d30728c | [
"super(DictViewerWindow, self).__init__()\nself.dialogs = list()\nself.screen = screen\ndict_view = DictView(dic, title, screen)\ndict_view.openContentAction.triggered.connect(lambda: self.open_new_window(dict_view))\nself.setCentralWidget(dict_view)\nself.setWindowTitle('Snapshot Viewer')\nscreen_geom = screen.siz... | <|body_start_0|>
super(DictViewerWindow, self).__init__()
self.dialogs = list()
self.screen = screen
dict_view = DictView(dic, title, screen)
dict_view.openContentAction.triggered.connect(lambda: self.open_new_window(dict_view))
self.setCentralWidget(dict_view)
se... | Main window to display the dictionary with all the features | DictViewerWindow | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DictViewerWindow:
"""Main window to display the dictionary with all the features"""
def __init__(self, dic: dict, title: str='', screen=None):
"""Initialization of the main window Args: dic(dict): Dictionary which is displayed in the main window title(str): Title which pops up in the... | stack_v2_sparse_classes_75kplus_train_009241 | 32,157 | permissive | [
{
"docstring": "Initialization of the main window Args: dic(dict): Dictionary which is displayed in the main window title(str): Title which pops up in the window",
"name": "__init__",
"signature": "def __init__(self, dic: dict, title: str='', screen=None)"
},
{
"docstring": "Opens a new window f... | 3 | stack_v2_sparse_classes_30k_train_021784 | Implement the Python class `DictViewerWindow` described below.
Class description:
Main window to display the dictionary with all the features
Method signatures and docstrings:
- def __init__(self, dic: dict, title: str='', screen=None): Initialization of the main window Args: dic(dict): Dictionary which is displayed ... | Implement the Python class `DictViewerWindow` described below.
Class description:
Main window to display the dictionary with all the features
Method signatures and docstrings:
- def __init__(self, dic: dict, title: str='', screen=None): Initialization of the main window Args: dic(dict): Dictionary which is displayed ... | bc6733d774fe31a23f4c7e73e5eb0beed8d30e7d | <|skeleton|>
class DictViewerWindow:
"""Main window to display the dictionary with all the features"""
def __init__(self, dic: dict, title: str='', screen=None):
"""Initialization of the main window Args: dic(dict): Dictionary which is displayed in the main window title(str): Title which pops up in the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DictViewerWindow:
"""Main window to display the dictionary with all the features"""
def __init__(self, dic: dict, title: str='', screen=None):
"""Initialization of the main window Args: dic(dict): Dictionary which is displayed in the main window title(str): Title which pops up in the window"""
... | the_stack_v2_python_sparse | pycqed/gui/dict_viewer.py | QudevETH/PycQED_py3 | train | 8 |
856f77729ec30a7942ed90236321017f1b7d9a0c | [
"self.M = num_models\nself.W1_model_prior = np.sqrt(prior_var) * rd.randn(self.M, hidden_dim, input_dim)\nself.W2_model_prior = np.sqrt(prior_var) * rd.randn(self.M, hidden_dim)\nself.W1 = np.copy(self.W1_model_prior)\nself.W2 = np.copy(self.W2_model_prior)\nself.actions = actions\nself.num_actions = len(actions)\n... | <|body_start_0|>
self.M = num_models
self.W1_model_prior = np.sqrt(prior_var) * rd.randn(self.M, hidden_dim, input_dim)
self.W2_model_prior = np.sqrt(prior_var) * rd.randn(self.M, hidden_dim)
self.W1 = np.copy(self.W1_model_prior)
self.W2 = np.copy(self.W2_model_prior)
se... | An ensemble sampling agent maintains an ensemble of neural nets, each fitted to a perturbed prior and perturbed observations. | TwoLayerNNEnsembleSampling | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoLayerNNEnsembleSampling:
"""An ensemble sampling agent maintains an ensemble of neural nets, each fitted to a perturbed prior and perturbed observations."""
def __init__(self, input_dim, hidden_dim, actions, time_horizon, prior_var, noise_var, num_models=10, learning_rate=0.1, num_gradien... | stack_v2_sparse_classes_75kplus_train_009242 | 13,684 | permissive | [
{
"docstring": "Ensemble sampling agent with two-layer neural network model. Args: input_dim: int dimension of input. hidden_dim: int size of hidden layer. actions: numpy array of valid actions (generated by environment). time_horizon: int size to pre-allocate data storage. prior_var: prior variance for random ... | 6 | stack_v2_sparse_classes_30k_train_017007 | Implement the Python class `TwoLayerNNEnsembleSampling` described below.
Class description:
An ensemble sampling agent maintains an ensemble of neural nets, each fitted to a perturbed prior and perturbed observations.
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, actions, time_horizon,... | Implement the Python class `TwoLayerNNEnsembleSampling` described below.
Class description:
An ensemble sampling agent maintains an ensemble of neural nets, each fitted to a perturbed prior and perturbed observations.
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, actions, time_horizon,... | 147ff28dc507172774693f225071f8e244e5994e | <|skeleton|>
class TwoLayerNNEnsembleSampling:
"""An ensemble sampling agent maintains an ensemble of neural nets, each fitted to a perturbed prior and perturbed observations."""
def __init__(self, input_dim, hidden_dim, actions, time_horizon, prior_var, noise_var, num_models=10, learning_rate=0.1, num_gradien... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwoLayerNNEnsembleSampling:
"""An ensemble sampling agent maintains an ensemble of neural nets, each fitted to a perturbed prior and perturbed observations."""
def __init__(self, input_dim, hidden_dim, actions, time_horizon, prior_var, noise_var, num_models=10, learning_rate=0.1, num_gradient_steps=1, ba... | the_stack_v2_python_sparse | src/ensemble_nn/agent_nn.py | AbhinavGopal/ts_tutorial | train | 0 |
c4c14ce7f685d3a09da2ae08d320c65c9aeb1d6a | [
"Frame.__init__(self, master)\nself.grid()\nself.create_widgets()",
"Label(self, text='Welcome to Order Up!').grid(row=0, column=0, columnspan=2, sticky=W)\nLabel(self, text='Please choose what you would like to eat.').grid(row=1, column=0, columnspan=2, sticky=W)\nLabel(self, text='******************************... | <|body_start_0|>
Frame.__init__(self, master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
Label(self, text='Welcome to Order Up!').grid(row=0, column=0, columnspan=2, sticky=W)
Label(self, text='Please choose what you would like to eat.').grid(row=1, column... | GUI application that creates a story based on user input. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""GUI application that creates a story based on user input."""
def __init__(self, master):
"""Initialize Frame"""
<|body_0|>
def create_widgets(self):
"""Create widgets to create the menu"""
<|body_1|>
def food_eaten(self):
"""f... | stack_v2_sparse_classes_75kplus_train_009243 | 4,026 | no_license | [
{
"docstring": "Initialize Frame",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "Create widgets to create the menu",
"name": "create_widgets",
"signature": "def create_widgets(self)"
},
{
"docstring": "fill text box list of foods eaten and total... | 3 | stack_v2_sparse_classes_30k_train_053185 | Implement the Python class `Application` described below.
Class description:
GUI application that creates a story based on user input.
Method signatures and docstrings:
- def __init__(self, master): Initialize Frame
- def create_widgets(self): Create widgets to create the menu
- def food_eaten(self): fill text box li... | Implement the Python class `Application` described below.
Class description:
GUI application that creates a story based on user input.
Method signatures and docstrings:
- def __init__(self, master): Initialize Frame
- def create_widgets(self): Create widgets to create the menu
- def food_eaten(self): fill text box li... | 272683aa0bfb68889e7dc272797549217f318dda | <|skeleton|>
class Application:
"""GUI application that creates a story based on user input."""
def __init__(self, master):
"""Initialize Frame"""
<|body_0|>
def create_widgets(self):
"""Create widgets to create the menu"""
<|body_1|>
def food_eaten(self):
"""f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Application:
"""GUI application that creates a story based on user input."""
def __init__(self, master):
"""Initialize Frame"""
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create widgets to create the menu"""
... | the_stack_v2_python_sparse | CSC_217/CSC_217_470_Assignment2/CIS_217_470_ASSIGNMENT2b_MENU.py | denisetra/SCHOOL | train | 0 |
4a566a17a251ee6f7b954408180f6f00046edef1 | [
"try:\n space = await get_data_from_req(self.request).spaces.get(space_id)\nexcept ResourceNotFoundError:\n raise NotFound\nreturn json_response(space)",
"try:\n space = await get_data_from_req(self.request).spaces.update(space_id, data)\nexcept ResourceNotFoundError:\n raise NotFound\nexcept Resource... | <|body_start_0|>
try:
space = await get_data_from_req(self.request).spaces.get(space_id)
except ResourceNotFoundError:
raise NotFound
return json_response(space)
<|end_body_0|>
<|body_start_1|>
try:
space = await get_data_from_req(self.request).spaces... | SpaceView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpaceView:
async def get(self, space_id: int, /) -> Union[r200[GetSpaceResponse], r404]:
"""Get a space. Fetches the complete representation of a space. Status Codes: 200: Successful operation 404: User not found"""
<|body_0|>
async def patch(self, space_id: int, /, data: Up... | stack_v2_sparse_classes_75kplus_train_009244 | 4,595 | permissive | [
{
"docstring": "Get a space. Fetches the complete representation of a space. Status Codes: 200: Successful operation 404: User not found",
"name": "get",
"signature": "async def get(self, space_id: int, /) -> Union[r200[GetSpaceResponse], r404]"
},
{
"docstring": "Update a space. Changes the nam... | 2 | stack_v2_sparse_classes_30k_train_049505 | Implement the Python class `SpaceView` described below.
Class description:
Implement the SpaceView class.
Method signatures and docstrings:
- async def get(self, space_id: int, /) -> Union[r200[GetSpaceResponse], r404]: Get a space. Fetches the complete representation of a space. Status Codes: 200: Successful operati... | Implement the Python class `SpaceView` described below.
Class description:
Implement the SpaceView class.
Method signatures and docstrings:
- async def get(self, space_id: int, /) -> Union[r200[GetSpaceResponse], r404]: Get a space. Fetches the complete representation of a space. Status Codes: 200: Successful operati... | 1d17d2ba570cf5487e7514bec29250a5b368bb0a | <|skeleton|>
class SpaceView:
async def get(self, space_id: int, /) -> Union[r200[GetSpaceResponse], r404]:
"""Get a space. Fetches the complete representation of a space. Status Codes: 200: Successful operation 404: User not found"""
<|body_0|>
async def patch(self, space_id: int, /, data: Up... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpaceView:
async def get(self, space_id: int, /) -> Union[r200[GetSpaceResponse], r404]:
"""Get a space. Fetches the complete representation of a space. Status Codes: 200: Successful operation 404: User not found"""
try:
space = await get_data_from_req(self.request).spaces.get(spac... | the_stack_v2_python_sparse | virtool/spaces/api.py | virtool/virtool | train | 45 | |
601037a7a7124a26b89eed98316d7bf0d7d5bb98 | [
"challenge_mgr.init()\nself.user = test_utils.setup_user(username='user', password='changeme')\ntest_utils.set_competition_round()\ntest_utils.enable_quest()\nchallenge_mgr.register_page_widget('home', 'home')\nchallenge_mgr.register_page_widget('profile', 'my_achievements')\nchallenge_mgr.register_page_widget('pro... | <|body_start_0|>
challenge_mgr.init()
self.user = test_utils.setup_user(username='user', password='changeme')
test_utils.set_competition_round()
test_utils.enable_quest()
challenge_mgr.register_page_widget('home', 'home')
challenge_mgr.register_page_widget('profile', 'my_... | Profile page test | MyAchievementsTestCase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyAchievementsTestCase:
"""Profile page test"""
def setUp(self):
"""setup"""
<|body_0|>
def testActivityAchievement(self):
"""Check that the user's activity achievements are loaded."""
<|body_1|>
def testCommitmentAchievement(self):
"""Check ... | stack_v2_sparse_classes_75kplus_train_009245 | 8,244 | permissive | [
{
"docstring": "setup",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Check that the user's activity achievements are loaded.",
"name": "testActivityAchievement",
"signature": "def testActivityAchievement(self)"
},
{
"docstring": "Check that the user's commit... | 6 | stack_v2_sparse_classes_30k_train_047882 | Implement the Python class `MyAchievementsTestCase` described below.
Class description:
Profile page test
Method signatures and docstrings:
- def setUp(self): setup
- def testActivityAchievement(self): Check that the user's activity achievements are loaded.
- def testCommitmentAchievement(self): Check that the user's... | Implement the Python class `MyAchievementsTestCase` described below.
Class description:
Profile page test
Method signatures and docstrings:
- def setUp(self): setup
- def testActivityAchievement(self): Check that the user's activity achievements are loaded.
- def testCommitmentAchievement(self): Check that the user's... | 4b7dd685012ec64758affe0ecee3103596d16aa7 | <|skeleton|>
class MyAchievementsTestCase:
"""Profile page test"""
def setUp(self):
"""setup"""
<|body_0|>
def testActivityAchievement(self):
"""Check that the user's activity achievements are loaded."""
<|body_1|>
def testCommitmentAchievement(self):
"""Check ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyAchievementsTestCase:
"""Profile page test"""
def setUp(self):
"""setup"""
challenge_mgr.init()
self.user = test_utils.setup_user(username='user', password='changeme')
test_utils.set_competition_round()
test_utils.enable_quest()
challenge_mgr.register_pag... | the_stack_v2_python_sparse | makahiki/apps/widgets/my_achievements/tests.py | justinslee/Wai-Not-Makahiki | train | 1 |
12d378d0e33bef40fdcb1f04633d7269ec21a134 | [
"serializer = SampleSerializer(data=request.data)\nserializer.is_valid(raise_exception=True)\nsample = serializer.save(user=request.user)\nreturn JsonResponse({'id': sample.id}, status=status.HTTP_201_CREATED)",
"sample = self.get_object()\nif sample.user.id == request.user.id:\n serializer = SampleSerializer(... | <|body_start_0|>
serializer = SampleSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
sample = serializer.save(user=request.user)
return JsonResponse({'id': sample.id}, status=status.HTTP_201_CREATED)
<|end_body_0|>
<|body_start_1|>
sample = self.get_object... | SampleView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleView:
def create(self, request, *args, **kwargs):
"""Overridden create method in order to assign the authenticated user and to return the newly created sample ID."""
<|body_0|>
def update(self, request, *args, **kwargs):
"""Overridden patch method in order to o... | stack_v2_sparse_classes_75kplus_train_009246 | 2,384 | no_license | [
{
"docstring": "Overridden create method in order to assign the authenticated user and to return the newly created sample ID.",
"name": "create",
"signature": "def create(self, request, *args, **kwargs)"
},
{
"docstring": "Overridden patch method in order to only allow the sample owner to update... | 3 | stack_v2_sparse_classes_30k_train_003124 | Implement the Python class `SampleView` described below.
Class description:
Implement the SampleView class.
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): Overridden create method in order to assign the authenticated user and to return the newly created sample ID.
- def update(self, r... | Implement the Python class `SampleView` described below.
Class description:
Implement the SampleView class.
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): Overridden create method in order to assign the authenticated user and to return the newly created sample ID.
- def update(self, r... | 94810e2e0bddd98ec9f3bd44c2f9f5f3f166bb08 | <|skeleton|>
class SampleView:
def create(self, request, *args, **kwargs):
"""Overridden create method in order to assign the authenticated user and to return the newly created sample ID."""
<|body_0|>
def update(self, request, *args, **kwargs):
"""Overridden patch method in order to o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SampleView:
def create(self, request, *args, **kwargs):
"""Overridden create method in order to assign the authenticated user and to return the newly created sample ID."""
serializer = SampleSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
sample = serial... | the_stack_v2_python_sparse | src/safm_api/views/sample.py | HE-Arc/social-audio-free-market | train | 4 | |
b09ae5239bae200fa6bfa9c44b3e63183a47b9ed | [
"self.create_file = True\nself.logfilename = logfilename\nif not self.logfilename.endswith('.csv'):\n self.logfilename += '.csv'",
"if self.create_file:\n dataframe.to_csv(self.logfilename, mode='w')\n self.create_file = False\nelse:\n dataframe.to_csv(self.logfilename, mode='a', header=False)"
] | <|body_start_0|>
self.create_file = True
self.logfilename = logfilename
if not self.logfilename.endswith('.csv'):
self.logfilename += '.csv'
<|end_body_0|>
<|body_start_1|>
if self.create_file:
dataframe.to_csv(self.logfilename, mode='w')
self.create_... | Handles creation and writing of a dataframe to a .csv file, possibly multiple times via appending. Used to log producer-consumer iteration, but could be used to log any dataframe. | IterationLog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IterationLog:
"""Handles creation and writing of a dataframe to a .csv file, possibly multiple times via appending. Used to log producer-consumer iteration, but could be used to log any dataframe."""
def __init__(self, logfilename):
"""Create IterationLog object Args: logfilename: na... | stack_v2_sparse_classes_75kplus_train_009247 | 5,083 | no_license | [
{
"docstring": "Create IterationLog object Args: logfilename: name of file to create, '.csv' extension added if not provided.",
"name": "__init__",
"signature": "def __init__(self, logfilename)"
},
{
"docstring": "Write dataframe to a .csv file, file is created on first write, subsequent writes ... | 2 | stack_v2_sparse_classes_30k_train_033314 | Implement the Python class `IterationLog` described below.
Class description:
Handles creation and writing of a dataframe to a .csv file, possibly multiple times via appending. Used to log producer-consumer iteration, but could be used to log any dataframe.
Method signatures and docstrings:
- def __init__(self, logfi... | Implement the Python class `IterationLog` described below.
Class description:
Handles creation and writing of a dataframe to a .csv file, possibly multiple times via appending. Used to log producer-consumer iteration, but could be used to log any dataframe.
Method signatures and docstrings:
- def __init__(self, logfi... | afe912c57383b9de90ef30820f7977c3367a30c4 | <|skeleton|>
class IterationLog:
"""Handles creation and writing of a dataframe to a .csv file, possibly multiple times via appending. Used to log producer-consumer iteration, but could be used to log any dataframe."""
def __init__(self, logfilename):
"""Create IterationLog object Args: logfilename: na... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IterationLog:
"""Handles creation and writing of a dataframe to a .csv file, possibly multiple times via appending. Used to log producer-consumer iteration, but could be used to log any dataframe."""
def __init__(self, logfilename):
"""Create IterationLog object Args: logfilename: name of file to... | the_stack_v2_python_sparse | omega_model/common/omega_log.py | USEPA/EPA_OMEGA_Model | train | 17 |
233c23a6263d0384d24c4fb8bbc04e491a28a53b | [
"test_jwt = create_mock_jwt(MOCK_RSA_PRIVATE_KEY_PEM, algorithm=OIDC_JWT_ALGORITHM, key_id='oidc_1234', audience=OIDC_VALID_AUDIENCE, issuer=OIDC_VALID_ISSUER)\npublic_key = get_public_key_for_jwt(test_jwt, OIDC_PUBLIC_KEY_URL)\nself.assertIsInstance(public_key, _RSAPublicKey)",
"test_jwt = create_mock_jwt(MOCK_R... | <|body_start_0|>
test_jwt = create_mock_jwt(MOCK_RSA_PRIVATE_KEY_PEM, algorithm=OIDC_JWT_ALGORITHM, key_id='oidc_1234', audience=OIDC_VALID_AUDIENCE, issuer=OIDC_VALID_ISSUER)
public_key = get_public_key_for_jwt(test_jwt, OIDC_PUBLIC_KEY_URL)
self.assertIsInstance(public_key, _RSAPublicKey)
<|en... | Tests for the functionality of the google_auth module. | TestGoogleCloudOpenIdConnect | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGoogleCloudOpenIdConnect:
"""Tests for the functionality of the google_auth module."""
def test_fetching_oidc_keys(self):
"""Test to fetch OpenID Connect formatted keys."""
<|body_0|>
def test_valid_oidc_jwt(self):
"""Test to validate a valid OpenID Connect J... | stack_v2_sparse_classes_75kplus_train_009248 | 16,971 | permissive | [
{
"docstring": "Test to fetch OpenID Connect formatted keys.",
"name": "test_fetching_oidc_keys",
"signature": "def test_fetching_oidc_keys(self)"
},
{
"docstring": "Test to validate a valid OpenID Connect JWT.",
"name": "test_valid_oidc_jwt",
"signature": "def test_valid_oidc_jwt(self)"... | 2 | stack_v2_sparse_classes_30k_train_002489 | Implement the Python class `TestGoogleCloudOpenIdConnect` described below.
Class description:
Tests for the functionality of the google_auth module.
Method signatures and docstrings:
- def test_fetching_oidc_keys(self): Test to fetch OpenID Connect formatted keys.
- def test_valid_oidc_jwt(self): Test to validate a v... | Implement the Python class `TestGoogleCloudOpenIdConnect` described below.
Class description:
Tests for the functionality of the google_auth module.
Method signatures and docstrings:
- def test_fetching_oidc_keys(self): Test to fetch OpenID Connect formatted keys.
- def test_valid_oidc_jwt(self): Test to validate a v... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class TestGoogleCloudOpenIdConnect:
"""Tests for the functionality of the google_auth module."""
def test_fetching_oidc_keys(self):
"""Test to fetch OpenID Connect formatted keys."""
<|body_0|>
def test_valid_oidc_jwt(self):
"""Test to validate a valid OpenID Connect J... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestGoogleCloudOpenIdConnect:
"""Tests for the functionality of the google_auth module."""
def test_fetching_oidc_keys(self):
"""Test to fetch OpenID Connect formatted keys."""
test_jwt = create_mock_jwt(MOCK_RSA_PRIVATE_KEY_PEM, algorithm=OIDC_JWT_ALGORITHM, key_id='oidc_1234', audience=... | the_stack_v2_python_sparse | timesketch/lib/google_auth_test.py | google/timesketch | train | 2,263 |
6916599dbd7682aba1d36df24ab9d5f4026c4825 | [
"cols = {'white': 1, 'whit': 1, 'whi': 1, 'wh': 1, 'w': 1, 'black': 2, 'blac': 2, 'bla': 2, 'bl': 2, 'b': 2}\ncol = 1\nreply = await message.get_reply_message()\ntxt = utils.get_args_raw(message)\nawait message.edit('подождем...')\nif txt in cols:\n col = cols[txt]\n txt = None\nif not txt:\n txt = 'я лоша... | <|body_start_0|>
cols = {'white': 1, 'whit': 1, 'whi': 1, 'wh': 1, 'w': 1, 'black': 2, 'blac': 2, 'bla': 2, 'bl': 2, 'b': 2}
col = 1
reply = await message.get_reply_message()
txt = utils.get_args_raw(message)
await message.edit('подождем...')
if txt in cols:
c... | TextOnPhotoMod | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextOnPhotoMod:
async def bottomcmd(self, message):
"""Используй: .bottom {реплай на картинку/стикер} <white/black>;ничего <текст>."""
<|body_0|>
async def topcmd(self, message):
"""Используй: .top {реплай на картинку/стикер} <white/black>;ничего <текст>."""
... | stack_v2_sparse_classes_75kplus_train_009249 | 4,912 | no_license | [
{
"docstring": "Используй: .bottom {реплай на картинку/стикер} <white/black>;ничего <текст>.",
"name": "bottomcmd",
"signature": "async def bottomcmd(self, message)"
},
{
"docstring": "Используй: .top {реплай на картинку/стикер} <white/black>;ничего <текст>.",
"name": "topcmd",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_043629 | Implement the Python class `TextOnPhotoMod` described below.
Class description:
Implement the TextOnPhotoMod class.
Method signatures and docstrings:
- async def bottomcmd(self, message): Используй: .bottom {реплай на картинку/стикер} <white/black>;ничего <текст>.
- async def topcmd(self, message): Используй: .top {р... | Implement the Python class `TextOnPhotoMod` described below.
Class description:
Implement the TextOnPhotoMod class.
Method signatures and docstrings:
- async def bottomcmd(self, message): Используй: .bottom {реплай на картинку/стикер} <white/black>;ничего <текст>.
- async def topcmd(self, message): Используй: .top {р... | a29db28872a452fcc48445279aff58e676dd0e3c | <|skeleton|>
class TextOnPhotoMod:
async def bottomcmd(self, message):
"""Используй: .bottom {реплай на картинку/стикер} <white/black>;ничего <текст>."""
<|body_0|>
async def topcmd(self, message):
"""Используй: .top {реплай на картинку/стикер} <white/black>;ничего <текст>."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextOnPhotoMod:
async def bottomcmd(self, message):
"""Используй: .bottom {реплай на картинку/стикер} <white/black>;ничего <текст>."""
cols = {'white': 1, 'whit': 1, 'whi': 1, 'wh': 1, 'w': 1, 'black': 2, 'blac': 2, 'bla': 2, 'bl': 2, 'b': 2}
col = 1
reply = await message.get_r... | the_stack_v2_python_sparse | textonphoto.py | Fl1yd/FTG-Modules | train | 6 | |
f238de8468e2bc5cc002eccfdc03383d5fac6138 | [
"dt1 = datetime.timedelta(days=0, minutes=0, seconds=0)\ndt2 = datetime.timedelta(days=0, minutes=0, seconds=0)\ndt3 = datetime.timedelta(days=0, minutes=1, seconds=15)\ndt4 = datetime.timedelta(days=10, minutes=1, seconds=15, microseconds=300)\nfake_dt5 = None\nfake_dt6 = 'fake'\nfake_dt7 = 18.52\nself.assertEqual... | <|body_start_0|>
dt1 = datetime.timedelta(days=0, minutes=0, seconds=0)
dt2 = datetime.timedelta(days=0, minutes=0, seconds=0)
dt3 = datetime.timedelta(days=0, minutes=1, seconds=15)
dt4 = datetime.timedelta(days=10, minutes=1, seconds=15, microseconds=300)
fake_dt5 = None
... | Contains unit tests for the check module. | TestChecks | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestChecks:
"""Contains unit tests for the check module."""
def test_sum_time_delta(self):
"""Test the sum_time_delta() function"""
<|body_0|>
def test_get_i_from_job_name(self):
"""Test the get_i_from_job_name() function"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_009250 | 2,038 | permissive | [
{
"docstring": "Test the sum_time_delta() function",
"name": "test_sum_time_delta",
"signature": "def test_sum_time_delta(self)"
},
{
"docstring": "Test the get_i_from_job_name() function",
"name": "test_get_i_from_job_name",
"signature": "def test_get_i_from_job_name(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047394 | Implement the Python class `TestChecks` described below.
Class description:
Contains unit tests for the check module.
Method signatures and docstrings:
- def test_sum_time_delta(self): Test the sum_time_delta() function
- def test_get_i_from_job_name(self): Test the get_i_from_job_name() function | Implement the Python class `TestChecks` described below.
Class description:
Contains unit tests for the check module.
Method signatures and docstrings:
- def test_sum_time_delta(self): Test the sum_time_delta() function
- def test_get_i_from_job_name(self): Test the get_i_from_job_name() function
<|skeleton|>
class ... | 617b2c5430e409271e241eda0de3dd673ec41835 | <|skeleton|>
class TestChecks:
"""Contains unit tests for the check module."""
def test_sum_time_delta(self):
"""Test the sum_time_delta() function"""
<|body_0|>
def test_get_i_from_job_name(self):
"""Test the get_i_from_job_name() function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestChecks:
"""Contains unit tests for the check module."""
def test_sum_time_delta(self):
"""Test the sum_time_delta() function"""
dt1 = datetime.timedelta(days=0, minutes=0, seconds=0)
dt2 = datetime.timedelta(days=0, minutes=0, seconds=0)
dt3 = datetime.timedelta(days=0... | the_stack_v2_python_sparse | arc/checks/common_test.py | ReactionMechanismGenerator/ARC | train | 40 |
7ae82d6f1e1feada24bc15be7ee4e90f3e0ffee4 | [
"super(Query, self).__init__(*args, **kwargs)\nif api_version is None:\n api_version = version.ec2_api\nself.params = {'Version': api_version, 'SignatureVersion': '2', 'Action': self.action, 'AWSAccessKeyId': self.creds.access_key}\nif other_params is None or 'Expires' not in other_params:\n self.params['Time... | <|body_start_0|>
super(Query, self).__init__(*args, **kwargs)
if api_version is None:
api_version = version.ec2_api
self.params = {'Version': api_version, 'SignatureVersion': '2', 'Action': self.action, 'AWSAccessKeyId': self.creds.access_key}
if other_params is None or 'Expi... | A query that may be submitted to EC2. | Query | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Query:
"""A query that may be submitted to EC2."""
def __init__(self, other_params=None, time_tuple=None, api_version=None, *args, **kwargs):
"""Create a Query to submit to EC2."""
<|body_0|>
def sign(self, hash_type='sha256'):
"""Sign this query using its built ... | stack_v2_sparse_classes_75kplus_train_009251 | 46,873 | permissive | [
{
"docstring": "Create a Query to submit to EC2.",
"name": "__init__",
"signature": "def __init__(self, other_params=None, time_tuple=None, api_version=None, *args, **kwargs)"
},
{
"docstring": "Sign this query using its built in credentials. @param hash_type: if the SignatureVersion is 2, speci... | 3 | stack_v2_sparse_classes_30k_train_004367 | Implement the Python class `Query` described below.
Class description:
A query that may be submitted to EC2.
Method signatures and docstrings:
- def __init__(self, other_params=None, time_tuple=None, api_version=None, *args, **kwargs): Create a Query to submit to EC2.
- def sign(self, hash_type='sha256'): Sign this q... | Implement the Python class `Query` described below.
Class description:
A query that may be submitted to EC2.
Method signatures and docstrings:
- def __init__(self, other_params=None, time_tuple=None, api_version=None, *args, **kwargs): Create a Query to submit to EC2.
- def sign(self, hash_type='sha256'): Sign this q... | f07134e4d1560c33a64cbe85a83aa7dfc1a4c56d | <|skeleton|>
class Query:
"""A query that may be submitted to EC2."""
def __init__(self, other_params=None, time_tuple=None, api_version=None, *args, **kwargs):
"""Create a Query to submit to EC2."""
<|body_0|>
def sign(self, hash_type='sha256'):
"""Sign this query using its built ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Query:
"""A query that may be submitted to EC2."""
def __init__(self, other_params=None, time_tuple=None, api_version=None, *args, **kwargs):
"""Create a Query to submit to EC2."""
super(Query, self).__init__(*args, **kwargs)
if api_version is None:
api_version = versi... | the_stack_v2_python_sparse | txaws/ec2/client.py | DomAmato/txaws | train | 1 |
d34fe4525b2687ea782db2ffb487ea1db1a6e8b9 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the Media File service. Service to manage media files. | MediaFileServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MediaFileServiceServicer:
"""Proto file describing the Media File service. Service to manage media files."""
def GetMediaFile(self, request, context):
"""Returns the requested media file in full detail."""
<|body_0|>
def MutateMediaFiles(self, request, context):
... | stack_v2_sparse_classes_75kplus_train_009252 | 5,357 | permissive | [
{
"docstring": "Returns the requested media file in full detail.",
"name": "GetMediaFile",
"signature": "def GetMediaFile(self, request, context)"
},
{
"docstring": "Creates media files. Operation statuses are returned.",
"name": "MutateMediaFiles",
"signature": "def MutateMediaFiles(sel... | 2 | stack_v2_sparse_classes_30k_train_013541 | Implement the Python class `MediaFileServiceServicer` described below.
Class description:
Proto file describing the Media File service. Service to manage media files.
Method signatures and docstrings:
- def GetMediaFile(self, request, context): Returns the requested media file in full detail.
- def MutateMediaFiles(s... | Implement the Python class `MediaFileServiceServicer` described below.
Class description:
Proto file describing the Media File service. Service to manage media files.
Method signatures and docstrings:
- def GetMediaFile(self, request, context): Returns the requested media file in full detail.
- def MutateMediaFiles(s... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class MediaFileServiceServicer:
"""Proto file describing the Media File service. Service to manage media files."""
def GetMediaFile(self, request, context):
"""Returns the requested media file in full detail."""
<|body_0|>
def MutateMediaFiles(self, request, context):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MediaFileServiceServicer:
"""Proto file describing the Media File service. Service to manage media files."""
def GetMediaFile(self, request, context):
"""Returns the requested media file in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method... | the_stack_v2_python_sparse | google/ads/google_ads/v5/proto/services/media_file_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
0886e1e64fb6be238afbb0c5245e002665bd2484 | [
"super(Application, self).__init__(master)\nself.grid()\nself.create_widgets()",
"bttnl = Button(self, text='I do nothing!')\nbttnl.grid()\nbttn2 = Button(self)\nbttn2.grid()\nbttn2.configure(text='Me too!')\nbttn3 = Button(self)\nbttn3.grid()\nbttn3['text'] = 'same here!'"
] | <|body_start_0|>
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
bttnl = Button(self, text='I do nothing!')
bttnl.grid()
bttn2 = Button(self)
bttn2.grid()
bttn2.configure(text='Me too!')
... | A GUI application with three buttons. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""A GUI application with three buttons."""
def __init__(self, master):
"""Initialize the Frame."""
<|body_0|>
def create_widgets(self):
"""Create three buttons that do nothing."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(... | stack_v2_sparse_classes_75kplus_train_009253 | 844 | no_license | [
{
"docstring": "Initialize the Frame.",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "Create three buttons that do nothing.",
"name": "create_widgets",
"signature": "def create_widgets(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022225 | Implement the Python class `Application` described below.
Class description:
A GUI application with three buttons.
Method signatures and docstrings:
- def __init__(self, master): Initialize the Frame.
- def create_widgets(self): Create three buttons that do nothing. | Implement the Python class `Application` described below.
Class description:
A GUI application with three buttons.
Method signatures and docstrings:
- def __init__(self, master): Initialize the Frame.
- def create_widgets(self): Create three buttons that do nothing.
<|skeleton|>
class Application:
"""A GUI appli... | 8d0194f641a77c86b17248481e5a18804e425b97 | <|skeleton|>
class Application:
"""A GUI application with three buttons."""
def __init__(self, master):
"""Initialize the Frame."""
<|body_0|>
def create_widgets(self):
"""Create three buttons that do nothing."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Application:
"""A GUI application with three buttons."""
def __init__(self, master):
"""Initialize the Frame."""
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create three buttons that do nothing."""
... | the_stack_v2_python_sparse | SimpleGUI/Lazybuttons2.py | DeepNoceans/PythonPrograms | train | 0 |
e67d0c0cedd5c4e94f8fdd9b1c99acad11dc40cc | [
"for inv in self:\n if inv.company_id.lines_invoice < 1:\n raise exceptions.except_orm(_('Error !'), _('Please set an invoice lines value in:\\nAdministration->Company->Configuration->Invoice lines'))\n if inv.type in ['out_invoice', 'out_refund']:\n if len(inv.invoice_line_ids) > inv.company_id... | <|body_start_0|>
for inv in self:
if inv.company_id.lines_invoice < 1:
raise exceptions.except_orm(_('Error !'), _('Please set an invoice lines value in:\nAdministration->Company->Configuration->Invoice lines'))
if inv.type in ['out_invoice', 'out_refund']:
... | AccountInvoice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountInvoice:
def split_invoice(self):
"""Split the invoice when the lines exceed the maximum set for the company"""
<|body_0|>
def action_date_assign(self):
"""Return assigned dat"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for inv in self:
... | stack_v2_sparse_classes_75kplus_train_009254 | 1,344 | no_license | [
{
"docstring": "Split the invoice when the lines exceed the maximum set for the company",
"name": "split_invoice",
"signature": "def split_invoice(self)"
},
{
"docstring": "Return assigned dat",
"name": "action_date_assign",
"signature": "def action_date_assign(self)"
}
] | 2 | null | Implement the Python class `AccountInvoice` described below.
Class description:
Implement the AccountInvoice class.
Method signatures and docstrings:
- def split_invoice(self): Split the invoice when the lines exceed the maximum set for the company
- def action_date_assign(self): Return assigned dat | Implement the Python class `AccountInvoice` described below.
Class description:
Implement the AccountInvoice class.
Method signatures and docstrings:
- def split_invoice(self): Split the invoice when the lines exceed the maximum set for the company
- def action_date_assign(self): Return assigned dat
<|skeleton|>
cla... | b95909d0689fc787185290565f0873040a6027cf | <|skeleton|>
class AccountInvoice:
def split_invoice(self):
"""Split the invoice when the lines exceed the maximum set for the company"""
<|body_0|>
def action_date_assign(self):
"""Return assigned dat"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountInvoice:
def split_invoice(self):
"""Split the invoice when the lines exceed the maximum set for the company"""
for inv in self:
if inv.company_id.lines_invoice < 1:
raise exceptions.except_orm(_('Error !'), _('Please set an invoice lines value in:\nAdministr... | the_stack_v2_python_sparse | localizacion_metromed/l10n_ve_split_invoice/model/invoice.py | Tysamncaweb/produccion2 | train | 1 | |
0f16216a72aa397bb1c5aba884a88e32d1ea36e9 | [
"kwargs.setdefault('primary', None)\nkwargs.setdefault('secondary', None)\nprimary = kwargs.pop('primary')\nsecondary = kwargs.pop('secondary')\nif primary or secondary:\n assert primary and secondary\n super().__init__(primary, secondary)\nelse:\n super().__init__(augeasparser.AugeasDirectiveNode(**kwargs... | <|body_start_0|>
kwargs.setdefault('primary', None)
kwargs.setdefault('secondary', None)
primary = kwargs.pop('primary')
secondary = kwargs.pop('secondary')
if primary or secondary:
assert primary and secondary
super().__init__(primary, secondary)
... | Dual parser implementation of DirectiveNode interface | DualDirectiveNode | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DualDirectiveNode:
"""Dual parser implementation of DirectiveNode interface"""
def __init__(self, **kwargs: Any) -> None:
"""This initialization implementation allows ordinary initialization of DirectiveNode objects as well as creating a DualDirectiveNode object using precreated or f... | stack_v2_sparse_classes_75kplus_train_009255 | 14,986 | permissive | [
{
"docstring": "This initialization implementation allows ordinary initialization of DirectiveNode objects as well as creating a DualDirectiveNode object using precreated or fetched DirectiveNode objects if provided as optional arguments primary and secondary. Parameters other than the following are from interf... | 2 | stack_v2_sparse_classes_30k_test_001965 | Implement the Python class `DualDirectiveNode` described below.
Class description:
Dual parser implementation of DirectiveNode interface
Method signatures and docstrings:
- def __init__(self, **kwargs: Any) -> None: This initialization implementation allows ordinary initialization of DirectiveNode objects as well as ... | Implement the Python class `DualDirectiveNode` described below.
Class description:
Dual parser implementation of DirectiveNode interface
Method signatures and docstrings:
- def __init__(self, **kwargs: Any) -> None: This initialization implementation allows ordinary initialization of DirectiveNode objects as well as ... | b1978ff18837e40d16eedf2090330af53d8ceaa5 | <|skeleton|>
class DualDirectiveNode:
"""Dual parser implementation of DirectiveNode interface"""
def __init__(self, **kwargs: Any) -> None:
"""This initialization implementation allows ordinary initialization of DirectiveNode objects as well as creating a DualDirectiveNode object using precreated or f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DualDirectiveNode:
"""Dual parser implementation of DirectiveNode interface"""
def __init__(self, **kwargs: Any) -> None:
"""This initialization implementation allows ordinary initialization of DirectiveNode objects as well as creating a DualDirectiveNode object using precreated or fetched Direct... | the_stack_v2_python_sparse | certbot-apache/certbot_apache/_internal/dualparser.py | certbot/certbot | train | 18,581 |
c29ccdf877bcfbaef3f3b56e610d7023f3ef410e | [
"self.scenarios = scenarios\nself.solver = solver\nif not random_state is None:\n np.random.seed(random_state)",
"scenario_results = {}\nfor scenario_name, scenario in self.scenarios.items():\n model = TransportExperiment(scenario=scenario, solver=self.solver)\n runner = MultipleReplicationRunner(model=m... | <|body_start_0|>
self.scenarios = scenarios
self.solver = solver
if not random_state is None:
np.random.seed(random_state)
<|end_body_0|>
<|body_start_1|>
scenario_results = {}
for scenario_name, scenario in self.scenarios.items():
model = TransportExperi... | Execute mulitple replicatins of multiple scenarios. | ScenarioManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScenarioManager:
"""Execute mulitple replicatins of multiple scenarios."""
def __init__(self, scenarios, solver, random_state=None):
"""ScenarioManager Parameters: scenarios: dict (str:Scenario) scenarios to run solver: object The VRP solver object random_state: int optional (default... | stack_v2_sparse_classes_75kplus_train_009256 | 18,047 | permissive | [
{
"docstring": "ScenarioManager Parameters: scenarios: dict (str:Scenario) scenarios to run solver: object The VRP solver object random_state: int optional (default = None) random seed. When None runs are not reproducible.",
"name": "__init__",
"signature": "def __init__(self, scenarios, solver, random_... | 2 | null | Implement the Python class `ScenarioManager` described below.
Class description:
Execute mulitple replicatins of multiple scenarios.
Method signatures and docstrings:
- def __init__(self, scenarios, solver, random_state=None): ScenarioManager Parameters: scenarios: dict (str:Scenario) scenarios to run solver: object ... | Implement the Python class `ScenarioManager` described below.
Class description:
Execute mulitple replicatins of multiple scenarios.
Method signatures and docstrings:
- def __init__(self, scenarios, solver, random_state=None): ScenarioManager Parameters: scenarios: dict (str:Scenario) scenarios to run solver: object ... | 62c6842fc14acee07aee12ac2f238cbd1c3881d6 | <|skeleton|>
class ScenarioManager:
"""Execute mulitple replicatins of multiple scenarios."""
def __init__(self, scenarios, solver, random_state=None):
"""ScenarioManager Parameters: scenarios: dict (str:Scenario) scenarios to run solver: object The VRP solver object random_state: int optional (default... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScenarioManager:
"""Execute mulitple replicatins of multiple scenarios."""
def __init__(self, scenarios, solver, random_state=None):
"""ScenarioManager Parameters: scenarios: dict (str:Scenario) scenarios to run solver: object The VRP solver object random_state: int optional (default = None) rand... | the_stack_v2_python_sparse | vrp/sim.py | MichaelAllen1966/2004_covid_dialysis | train | 0 |
dfec3e1e50c88a5c261ad10c3a3d86d935d092bf | [
"self.log = logging.getLogger(__name__)\nself.appinfo = {'app': app, 'email': email, 'project': project, 'repo': repo, 'provider': provider}\nself.appname = app\nself.pipeline_config = pipeline_config",
"self.appinfo['accounts'] = ['default']\nself.log.debug('Pipeline Config\\n%s', pformat(self.pipeline_config))\... | <|body_start_0|>
self.log = logging.getLogger(__name__)
self.appinfo = {'app': app, 'email': email, 'project': project, 'repo': repo, 'provider': provider}
self.appname = app
self.pipeline_config = pipeline_config
<|end_body_0|>
<|body_start_1|>
self.appinfo['accounts'] = ['defa... | Base App. | SpinnakerApp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpinnakerApp:
"""Base App."""
def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None):
"""Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json data. app (str): Application name. email (str): Email asso... | stack_v2_sparse_classes_75kplus_train_009257 | 3,461 | permissive | [
{
"docstring": "Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json data. app (str): Application name. email (str): Email associated with application. project (str): Git namespace or project group repo (str): Repository name",
"name": "__init__",
"signature": "d... | 5 | stack_v2_sparse_classes_30k_train_028510 | Implement the Python class `SpinnakerApp` described below.
Class description:
Base App.
Method signatures and docstrings:
- def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None): Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json d... | Implement the Python class `SpinnakerApp` described below.
Class description:
Base App.
Method signatures and docstrings:
- def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None): Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json d... | d88001ea0e33fcd09707b81b5c4ed40e5e21fb59 | <|skeleton|>
class SpinnakerApp:
"""Base App."""
def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None):
"""Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json data. app (str): Application name. email (str): Email asso... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpinnakerApp:
"""Base App."""
def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None):
"""Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json data. app (str): Application name. email (str): Email associated with a... | the_stack_v2_python_sparse | src/foremast/app/spinnaker_app.py | foremast/foremast | train | 151 |
c6c7aa10ff32199310dc9f68a426eb1b28c6b3c6 | [
"if bit == 256:\n digest = hashlib.sha256\nelif bit == 512:\n digest = hashlib.sha512\nelse:\n return ''\nsignature = hmac.new(bytes_secret, msg=bytes_data, digestmod=digest).hexdigest()\nreturn signature",
"if bit == 256:\n algorithm = Crypto.Hash.SHA256\nelif bit == 512:\n algorithm = Crypto.Hash... | <|body_start_0|>
if bit == 256:
digest = hashlib.sha256
elif bit == 512:
digest = hashlib.sha512
else:
return ''
signature = hmac.new(bytes_secret, msg=bytes_data, digestmod=digest).hexdigest()
return signature
<|end_body_0|>
<|body_start_1|>
... | CryptoKit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CryptoKit:
def hmac_sign(cls, bytes_data, bytes_secret, bit=256):
"""hmac签名"""
<|body_0|>
def rsa_sign(cls, plaintext, key, bit=256):
"""RSA 数字签名"""
<|body_1|>
def rsa_verify(cls, sign, plaintext, key, bit=256):
"""校验RSA 数字签名"""
<|body_2|... | stack_v2_sparse_classes_75kplus_train_009258 | 1,675 | no_license | [
{
"docstring": "hmac签名",
"name": "hmac_sign",
"signature": "def hmac_sign(cls, bytes_data, bytes_secret, bit=256)"
},
{
"docstring": "RSA 数字签名",
"name": "rsa_sign",
"signature": "def rsa_sign(cls, plaintext, key, bit=256)"
},
{
"docstring": "校验RSA 数字签名",
"name": "rsa_verify",... | 3 | stack_v2_sparse_classes_30k_train_054736 | Implement the Python class `CryptoKit` described below.
Class description:
Implement the CryptoKit class.
Method signatures and docstrings:
- def hmac_sign(cls, bytes_data, bytes_secret, bit=256): hmac签名
- def rsa_sign(cls, plaintext, key, bit=256): RSA 数字签名
- def rsa_verify(cls, sign, plaintext, key, bit=256): 校验RSA... | Implement the Python class `CryptoKit` described below.
Class description:
Implement the CryptoKit class.
Method signatures and docstrings:
- def hmac_sign(cls, bytes_data, bytes_secret, bit=256): hmac签名
- def rsa_sign(cls, plaintext, key, bit=256): RSA 数字签名
- def rsa_verify(cls, sign, plaintext, key, bit=256): 校验RSA... | ff36deb73e667de16a73b1666bbeaf28f993f944 | <|skeleton|>
class CryptoKit:
def hmac_sign(cls, bytes_data, bytes_secret, bit=256):
"""hmac签名"""
<|body_0|>
def rsa_sign(cls, plaintext, key, bit=256):
"""RSA 数字签名"""
<|body_1|>
def rsa_verify(cls, sign, plaintext, key, bit=256):
"""校验RSA 数字签名"""
<|body_2|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CryptoKit:
def hmac_sign(cls, bytes_data, bytes_secret, bit=256):
"""hmac签名"""
if bit == 256:
digest = hashlib.sha256
elif bit == 512:
digest = hashlib.sha512
else:
return ''
signature = hmac.new(bytes_secret, msg=bytes_data, digestmo... | the_stack_v2_python_sparse | backend/app/libs/crypto.py | LyanJin/check-pay | train | 0 | |
088ea1cda14d2afc9f641aa0f1c985ed8563d54c | [
"self.language = language\nself.language = self.language.replace('..', '')\nself.language = self.language.replace('/', '')\nlangfile = Lang.LANG_PATH + self.language + '.json'\nif not os.path.isfile(langfile):\n langfile = Lang.LANG_PATH + 'en.json'\n self.language = 'en'\ndata = open(langfile, encoding='utf-... | <|body_start_0|>
self.language = language
self.language = self.language.replace('..', '')
self.language = self.language.replace('/', '')
langfile = Lang.LANG_PATH + self.language + '.json'
if not os.path.isfile(langfile):
langfile = Lang.LANG_PATH + 'en.json'
... | Internationalization tool. Loads messages in a given language and keeps them as object attributes. Usage : - lang = Lang('en') - lang.message_key | Lang | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lang:
"""Internationalization tool. Loads messages in a given language and keeps them as object attributes. Usage : - lang = Lang('en') - lang.message_key"""
def __init__(self, language='en'):
"""Loads a lang file's content as class attributes. Tries to find given language, falls bac... | stack_v2_sparse_classes_75kplus_train_009259 | 2,141 | permissive | [
{
"docstring": "Loads a lang file's content as class attributes. Tries to find given language, falls back to english if needed. :param language: language to load (default : en) :type language: str :rtype: bool",
"name": "__init__",
"signature": "def __init__(self, language='en')"
},
{
"docstring... | 2 | stack_v2_sparse_classes_30k_train_022832 | Implement the Python class `Lang` described below.
Class description:
Internationalization tool. Loads messages in a given language and keeps them as object attributes. Usage : - lang = Lang('en') - lang.message_key
Method signatures and docstrings:
- def __init__(self, language='en'): Loads a lang file's content as ... | Implement the Python class `Lang` described below.
Class description:
Internationalization tool. Loads messages in a given language and keeps them as object attributes. Usage : - lang = Lang('en') - lang.message_key
Method signatures and docstrings:
- def __init__(self, language='en'): Loads a lang file's content as ... | bd998c25bae8e8635494ddf145c1fcd789959dc1 | <|skeleton|>
class Lang:
"""Internationalization tool. Loads messages in a given language and keeps them as object attributes. Usage : - lang = Lang('en') - lang.message_key"""
def __init__(self, language='en'):
"""Loads a lang file's content as class attributes. Tries to find given language, falls bac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Lang:
"""Internationalization tool. Loads messages in a given language and keeps them as object attributes. Usage : - lang = Lang('en') - lang.message_key"""
def __init__(self, language='en'):
"""Loads a lang file's content as class attributes. Tries to find given language, falls back to english ... | the_stack_v2_python_sparse | utils/lang.py | matteocargnelutti/jean-pierre | train | 47 |
9613db8215a2d71b09dec19ee65585d267b8acca | [
"super(Validation_Dataset, self).__init__()\nfiles = os.listdir(data_dir)\nself._files = [data_dir + '/' + file for file in files]\nself._batch_size = batch_size\nself.vocab = vocab",
"batch_size = self._batch_size\nfile_num = len(self._files) - 1\nselected_file_num = random.randint(0, file_num)\nselected_file = ... | <|body_start_0|>
super(Validation_Dataset, self).__init__()
files = os.listdir(data_dir)
self._files = [data_dir + '/' + file for file in files]
self._batch_size = batch_size
self.vocab = vocab
<|end_body_0|>
<|body_start_1|>
batch_size = self._batch_size
file_nu... | Validation_Dataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Validation_Dataset:
def __init__(self, data_dir, batch_size=32, vocab=None):
"""Args: data_dir: the data dir contain the validation datas vocab: Vocabulary obj"""
<|body_0|>
def get_batch(self):
"""only use 10 batch to validation the model, every epoch we random sele... | stack_v2_sparse_classes_75kplus_train_009260 | 2,235 | no_license | [
{
"docstring": "Args: data_dir: the data dir contain the validation datas vocab: Vocabulary obj",
"name": "__init__",
"signature": "def __init__(self, data_dir, batch_size=32, vocab=None)"
},
{
"docstring": "only use 10 batch to validation the model, every epoch we random select a file, and shuf... | 2 | stack_v2_sparse_classes_30k_train_047475 | Implement the Python class `Validation_Dataset` described below.
Class description:
Implement the Validation_Dataset class.
Method signatures and docstrings:
- def __init__(self, data_dir, batch_size=32, vocab=None): Args: data_dir: the data dir contain the validation datas vocab: Vocabulary obj
- def get_batch(self)... | Implement the Python class `Validation_Dataset` described below.
Class description:
Implement the Validation_Dataset class.
Method signatures and docstrings:
- def __init__(self, data_dir, batch_size=32, vocab=None): Args: data_dir: the data dir contain the validation datas vocab: Vocabulary obj
- def get_batch(self)... | 21bc34d51ff77da40ed657d3df92e4481a991a7b | <|skeleton|>
class Validation_Dataset:
def __init__(self, data_dir, batch_size=32, vocab=None):
"""Args: data_dir: the data dir contain the validation datas vocab: Vocabulary obj"""
<|body_0|>
def get_batch(self):
"""only use 10 batch to validation the model, every epoch we random sele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Validation_Dataset:
def __init__(self, data_dir, batch_size=32, vocab=None):
"""Args: data_dir: the data dir contain the validation datas vocab: Vocabulary obj"""
super(Validation_Dataset, self).__init__()
files = os.listdir(data_dir)
self._files = [data_dir + '/' + file for fi... | the_stack_v2_python_sparse | cn_cove/data/dev_dataset.py | dabaier/CNN_CBOW | train | 0 | |
10629a5bc786ff7bf58c5ff8c27ddcbe824853a8 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('kobesay', 'kobesay')\nrepo.dropCollection('regionincome')\nrepo.createCollection('regionincome')\nitems = {}\nincome2013 = repo.kobesay.income2013.find()\nincome2014 = repo.kobesay.income2014.find()\nfor... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('kobesay', 'kobesay')
repo.dropCollection('regionincome')
repo.createCollection('regionincome')
items = {}
income2013 = repo.kobesa... | trans_income | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class trans_income:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ... | stack_v2_sparse_classes_75kplus_train_009261 | 4,374 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_012508 | Implement the Python class `trans_income` described below.
Class description:
Implement the trans_income class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, end... | Implement the Python class `trans_income` described below.
Class description:
Implement the trans_income class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, end... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class trans_income:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class trans_income:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('kobesay', 'kobesay')
repo.drop... | the_stack_v2_python_sparse | kobesay/trans_income.py | lingyigu/course-2017-spr-proj | train | 0 | |
501a12258170832716a7e696b0f771bcbfa1ac28 | [
"self.output = output\nself._c_function = self._compile(entry_name, tree, entry_type)\nreturn self",
"duration = c_float()\nif self.output is not None:\n output = self.output\n self.output = None\nelse:\n output = np.zeros_like(args[0])\nargs += (output, byref(duration))\nself._c_function(*args)\nreturn ... | <|body_start_0|>
self.output = output
self._c_function = self._compile(entry_name, tree, entry_type)
return self
<|end_body_0|>
<|body_start_1|>
duration = c_float()
if self.output is not None:
output = self.output
self.output = None
else:
... | StencilFunction The standard concrete specialized function that is returned when using the C or OpenMP backend. | ConcreteStencil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConcreteStencil:
"""StencilFunction The standard concrete specialized function that is returned when using the C or OpenMP backend."""
def finalize(self, tree, entry_name, entry_type, output):
""":param tree: A project node containing any files to be compiled for this specialized fun... | stack_v2_sparse_classes_75kplus_train_009262 | 25,641 | no_license | [
{
"docstring": ":param tree: A project node containing any files to be compiled for this specialized function. :type tree: Project node :param entry_name: The name of the function that will be the entry point to the compiled project. :type: str :param entry_type: The type signature of the function described by ... | 2 | stack_v2_sparse_classes_30k_train_044883 | Implement the Python class `ConcreteStencil` described below.
Class description:
StencilFunction The standard concrete specialized function that is returned when using the C or OpenMP backend.
Method signatures and docstrings:
- def finalize(self, tree, entry_name, entry_type, output): :param tree: A project node con... | Implement the Python class `ConcreteStencil` described below.
Class description:
StencilFunction The standard concrete specialized function that is returned when using the C or OpenMP backend.
Method signatures and docstrings:
- def finalize(self, tree, entry_name, entry_type, output): :param tree: A project node con... | 87f5d5115587f3362c8ea097900d3d50a3485b1a | <|skeleton|>
class ConcreteStencil:
"""StencilFunction The standard concrete specialized function that is returned when using the C or OpenMP backend."""
def finalize(self, tree, entry_name, entry_type, output):
""":param tree: A project node containing any files to be compiled for this specialized fun... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConcreteStencil:
"""StencilFunction The standard concrete specialized function that is returned when using the C or OpenMP backend."""
def finalize(self, tree, entry_name, entry_type, output):
""":param tree: A project node containing any files to be compiled for this specialized function. :type ... | the_stack_v2_python_sparse | stencil_code/stencil_kernel.py | ucb-sejits/stencil_code | train | 3 |
10f15394a6ea5f215084f498f0332a3d8d2474a8 | [
"self.Wf = np.random.normal(size=(i + h, h))\nself.Wu = np.random.normal(size=(i + h, h))\nself.Wc = np.random.normal(size=(i + h, h))\nself.Wo = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bf = np.zeros((1, h))\nself.bu = np.zeros((1, h))\nself.bc = np.zeros((1, h))\nself.bo = ... | <|body_start_0|>
self.Wf = np.random.normal(size=(i + h, h))
self.Wu = np.random.normal(size=(i + h, h))
self.Wc = np.random.normal(size=(i + h, h))
self.Wo = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bf = np.zeros((1, h))
self... | structure of a LSTM cell | LSTMCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTMCell:
"""structure of a LSTM cell"""
def __init__(self, i, h, o):
"""* i is the dimensionality of the data * h is the dimensionality of the hidden state * o is the dimensionality of the outputs * Wf and bf are for the forget gate * Wu and bu are for the update gate * Wc and bc ar... | stack_v2_sparse_classes_75kplus_train_009263 | 2,684 | no_license | [
{
"docstring": "* i is the dimensionality of the data * h is the dimensionality of the hidden state * o is the dimensionality of the outputs * Wf and bf are for the forget gate * Wu and bu are for the update gate * Wc and bc are for the intermediate cell state * Wo and bo are for the output gate * Wy and by are... | 2 | stack_v2_sparse_classes_30k_train_046623 | Implement the Python class `LSTMCell` described below.
Class description:
structure of a LSTM cell
Method signatures and docstrings:
- def __init__(self, i, h, o): * i is the dimensionality of the data * h is the dimensionality of the hidden state * o is the dimensionality of the outputs * Wf and bf are for the forge... | Implement the Python class `LSTMCell` described below.
Class description:
structure of a LSTM cell
Method signatures and docstrings:
- def __init__(self, i, h, o): * i is the dimensionality of the data * h is the dimensionality of the hidden state * o is the dimensionality of the outputs * Wf and bf are for the forge... | 8ad4c2594ff78b345dbd92e9d54d2a143ac4071a | <|skeleton|>
class LSTMCell:
"""structure of a LSTM cell"""
def __init__(self, i, h, o):
"""* i is the dimensionality of the data * h is the dimensionality of the hidden state * o is the dimensionality of the outputs * Wf and bf are for the forget gate * Wu and bu are for the update gate * Wc and bc ar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LSTMCell:
"""structure of a LSTM cell"""
def __init__(self, i, h, o):
"""* i is the dimensionality of the data * h is the dimensionality of the hidden state * o is the dimensionality of the outputs * Wf and bf are for the forget gate * Wu and bu are for the update gate * Wc and bc are for the int... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/3-lstm_cell.py | jorgezafra94/holbertonschool-machine_learning | train | 1 |
9f53640abd3d57af76b055223b2130a284e044a2 | [
"self.element = element\nself.need_update = need_update\nself.callout = None",
"points = self._get_up_down_points(offset)\nself.callout = MyView.create_callout(view.Id, view.GetTypeId(), *points)\nif self.need_update:\n self._update(symbol_point=points, rotated=rotated)\nif template_view:\n self.callout.App... | <|body_start_0|>
self.element = element
self.need_update = need_update
self.callout = None
<|end_body_0|>
<|body_start_1|>
points = self._get_up_down_points(offset)
self.callout = MyView.create_callout(view.Id, view.GetTypeId(), *points)
if self.need_update:
... | MetaClass for Callout. Need overrides: - _calc_origin_and_orientation - _get_symbol_points _need_update determines whether to rotate and crop | MyCalloutCreator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyCalloutCreator:
"""MetaClass for Callout. Need overrides: - _calc_origin_and_orientation - _get_symbol_points _need_update determines whether to rotate and crop"""
def __init__(self, element, need_update=True):
"""Initialization of instance :param element: :type element: MyElementG... | stack_v2_sparse_classes_75kplus_train_009264 | 2,951 | permissive | [
{
"docstring": "Initialization of instance :param element: :type element: MyElementGeom",
"name": "__init__",
"signature": "def __init__(self, element, need_update=True)"
},
{
"docstring": "Create callout on given view, offset and rotate if it needed :param view: view on which the callout will b... | 5 | stack_v2_sparse_classes_30k_train_022314 | Implement the Python class `MyCalloutCreator` described below.
Class description:
MetaClass for Callout. Need overrides: - _calc_origin_and_orientation - _get_symbol_points _need_update determines whether to rotate and crop
Method signatures and docstrings:
- def __init__(self, element, need_update=True): Initializat... | Implement the Python class `MyCalloutCreator` described below.
Class description:
MetaClass for Callout. Need overrides: - _calc_origin_and_orientation - _get_symbol_points _need_update determines whether to rotate and crop
Method signatures and docstrings:
- def __init__(self, element, need_update=True): Initializat... | c4ea77428111d186fab55501243ad4319376482b | <|skeleton|>
class MyCalloutCreator:
"""MetaClass for Callout. Need overrides: - _calc_origin_and_orientation - _get_symbol_points _need_update determines whether to rotate and crop"""
def __init__(self, element, need_update=True):
"""Initialization of instance :param element: :type element: MyElementG... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyCalloutCreator:
"""MetaClass for Callout. Need overrides: - _calc_origin_and_orientation - _get_symbol_points _need_update determines whether to rotate and crop"""
def __init__(self, element, need_update=True):
"""Initialization of instance :param element: :type element: MyElementGeom"""
... | the_stack_v2_python_sparse | scripts/my_class/my_callout.py | appolimp/Dynamo_scripts | train | 1 |
b8ada245e20ca67d18c0332cf4d854bb7cca1d89 | [
"SYMBOL_SEPARATOR = ' '\nSYMBOL_NONE = 'X'\nif root == None:\n return ''\nqueue = Queue()\nqueue.put(root)\nans_str = ''\nwhile not queue.empty():\n cur_node = queue.get()\n ans_str += SYMBOL_SEPARATOR + (str(cur_node.val) if cur_node else SYMBOL_NONE)\n if cur_node:\n queue.put(cur_node.left)\n ... | <|body_start_0|>
SYMBOL_SEPARATOR = ' '
SYMBOL_NONE = 'X'
if root == None:
return ''
queue = Queue()
queue.put(root)
ans_str = ''
while not queue.empty():
cur_node = queue.get()
ans_str += SYMBOL_SEPARATOR + (str(cur_node.val) i... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_009265 | 3,349 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_037080 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | e31ec989daf70bb4cba69e35e351fc970e93dc34 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
SYMBOL_SEPARATOR = ' '
SYMBOL_NONE = 'X'
if root == None:
return ''
queue = Queue()
queue.put(root)
ans_str = ''
while not que... | the_stack_v2_python_sparse | Hard/#297_Serialize_and_Deserialize_Binary_Tree.py | AlphaGarden/LeetCodeProblems | train | 0 | |
d562dcaefec4053be49970f6baff9ddd09805ae9 | [
"self.assertTrue(can_access(self.member1_profile, None, constants.PUBLIC_ACCESS))\nself.assertTrue(can_access(self.member1_profile, self.registered1_profile, constants.PUBLIC_ACCESS))\nself.assertTrue(can_access(self.member1_profile, self.member2_profile, constants.PUBLIC_ACCESS))\nself.assertTrue(can_access(self.m... | <|body_start_0|>
self.assertTrue(can_access(self.member1_profile, None, constants.PUBLIC_ACCESS))
self.assertTrue(can_access(self.member1_profile, self.registered1_profile, constants.PUBLIC_ACCESS))
self.assertTrue(can_access(self.member1_profile, self.member2_profile, constants.PUBLIC_ACCESS))
... | Test the can_access method in access.py. Test different configurations of owner and viewer, and make sure the correct valid access levels are returned. | CanAccessTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanAccessTestCase:
"""Test the can_access method in access.py. Test different configurations of owner and viewer, and make sure the correct valid access levels are returned."""
def test_public(self):
"""Any combination of owner/viewer at the public level should be True."""
<|... | stack_v2_sparse_classes_75kplus_train_009266 | 10,516 | permissive | [
{
"docstring": "Any combination of owner/viewer at the public level should be True.",
"name": "test_public",
"signature": "def test_public(self)"
},
{
"docstring": "If the viewer is anonymous, this should return False.",
"name": "test_registered",
"signature": "def test_registered(self)"... | 5 | null | Implement the Python class `CanAccessTestCase` described below.
Class description:
Test the can_access method in access.py. Test different configurations of owner and viewer, and make sure the correct valid access levels are returned.
Method signatures and docstrings:
- def test_public(self): Any combination of owner... | Implement the Python class `CanAccessTestCase` described below.
Class description:
Test the can_access method in access.py. Test different configurations of owner and viewer, and make sure the correct valid access levels are returned.
Method signatures and docstrings:
- def test_public(self): Any combination of owner... | b26e4dd37b095247b15ae087639eedd1a2028247 | <|skeleton|>
class CanAccessTestCase:
"""Test the can_access method in access.py. Test different configurations of owner and viewer, and make sure the correct valid access levels are returned."""
def test_public(self):
"""Any combination of owner/viewer at the public level should be True."""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CanAccessTestCase:
"""Test the can_access method in access.py. Test different configurations of owner and viewer, and make sure the correct valid access levels are returned."""
def test_public(self):
"""Any combination of owner/viewer at the public level should be True."""
self.assertTrue... | the_stack_v2_python_sparse | HedyNet/profiles/tests.py | SeattleAttic/HedyNet | train | 0 |
49e7fcd30e41de7fa39978c059ee28b6f8b5f632 | [
"from django.utils.timezone import utc\nfrom django.http import HttpResponseRedirect\nif settings.SYSDOWNTIMEUTC and settings.SYSUPTIMEUTC:\n now = datetime.utcnow().replace(tzinfo=utc)\n if now > settings.SYSDOWNTIMEUTC and now < settings.SYSUPTIMEUTC:\n return HttpResponseRedirect(settings.SYSDOWNINF... | <|body_start_0|>
from django.utils.timezone import utc
from django.http import HttpResponseRedirect
if settings.SYSDOWNTIMEUTC and settings.SYSUPTIMEUTC:
now = datetime.utcnow().replace(tzinfo=utc)
if now > settings.SYSDOWNTIMEUTC and now < settings.SYSUPTIMEUTC:
... | GoingDown | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoingDown:
def process_request(self, request):
"""Redirects all requests to another url when the system is down"""
<|body_0|>
def process_template_response(self, request, response):
"""Warns users the system is going down at a given time"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_009267 | 2,101 | no_license | [
{
"docstring": "Redirects all requests to another url when the system is down",
"name": "process_request",
"signature": "def process_request(self, request)"
},
{
"docstring": "Warns users the system is going down at a given time",
"name": "process_template_response",
"signature": "def pr... | 2 | stack_v2_sparse_classes_30k_train_025857 | Implement the Python class `GoingDown` described below.
Class description:
Implement the GoingDown class.
Method signatures and docstrings:
- def process_request(self, request): Redirects all requests to another url when the system is down
- def process_template_response(self, request, response): Warns users the syst... | Implement the Python class `GoingDown` described below.
Class description:
Implement the GoingDown class.
Method signatures and docstrings:
- def process_request(self, request): Redirects all requests to another url when the system is down
- def process_template_response(self, request, response): Warns users the syst... | b5cb9e6d80867883cc2ff6bceda3a500db38c206 | <|skeleton|>
class GoingDown:
def process_request(self, request):
"""Redirects all requests to another url when the system is down"""
<|body_0|>
def process_template_response(self, request, response):
"""Warns users the system is going down at a given time"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoingDown:
def process_request(self, request):
"""Redirects all requests to another url when the system is down"""
from django.utils.timezone import utc
from django.http import HttpResponseRedirect
if settings.SYSDOWNTIMEUTC and settings.SYSUPTIMEUTC:
now = datetime... | the_stack_v2_python_sparse | roses/roses/middleware.py | shearichard/djangoroses | train | 0 | |
660cc7d201ffd14dfd1292863cfccb7ae88b2d25 | [
"res = []\n\ndef helper(root):\n if not root:\n return\n res.append(root.val)\n helper(root.left)\n helper(root.right)\nhelper(root)\nreturn res",
"if root is None:\n return []\nstack = [root]\nans = []\nwhile stack:\n tail = stack.pop()\n ans.append(tail.val)\n if tail.right:\n ... | <|body_start_0|>
res = []
def helper(root):
if not root:
return
res.append(root.val)
helper(root.left)
helper(root.right)
helper(root)
return res
<|end_body_0|>
<|body_start_1|>
if root is None:
return ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
"""递归"""
<|body_0|>
def preorderTraversal1(self, root: TreeNode) -> List[int]:
"""迭代"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
def helper(root):
... | stack_v2_sparse_classes_75kplus_train_009268 | 1,331 | no_license | [
{
"docstring": "递归",
"name": "preorderTraversal",
"signature": "def preorderTraversal(self, root: TreeNode) -> List[int]"
},
{
"docstring": "迭代",
"name": "preorderTraversal1",
"signature": "def preorderTraversal1(self, root: TreeNode) -> List[int]"
}
] | 2 | stack_v2_sparse_classes_30k_train_000476 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversal(self, root: TreeNode) -> List[int]: 递归
- def preorderTraversal1(self, root: TreeNode) -> List[int]: 迭代 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversal(self, root: TreeNode) -> List[int]: 递归
- def preorderTraversal1(self, root: TreeNode) -> List[int]: 迭代
<|skeleton|>
class Solution:
def preorderTraver... | 40726506802d2d60028fdce206696b1df2f63ece | <|skeleton|>
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
"""递归"""
<|body_0|>
def preorderTraversal1(self, root: TreeNode) -> List[int]:
"""迭代"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
"""递归"""
res = []
def helper(root):
if not root:
return
res.append(root.val)
helper(root.left)
helper(root.right)
helper(root)
return res... | the_stack_v2_python_sparse | 二刷+题解/树/preorderTraversal.py | 1oser5/LeetCode | train | 0 | |
dcf0451e0b8d608bdd8e6aa073e868fbf7eace6a | [
"count = 0\nif len(nums) == 0:\n return 0\npre = nums[0]\ni = 0\nwhile i < len(nums):\n if nums[i] == pre:\n count += 1\n if count > 2:\n nums.remove(pre)\n else:\n i += 1\n else:\n pre = nums[i]\n count = 1\n i += 1\nreturn i",
"i = 0\nfor ... | <|body_start_0|>
count = 0
if len(nums) == 0:
return 0
pre = nums[0]
i = 0
while i < len(nums):
if nums[i] == pre:
count += 1
if count > 2:
nums.remove(pre)
else:
i += ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeDuplicates0(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = 0
if len(nums) == ... | stack_v2_sparse_classes_75kplus_train_009269 | 982 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeDuplicates0",
"signature": "def removeDuplicates0(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026999 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicates0(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicates0(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def ... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeDuplicates0(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
count = 0
if len(nums) == 0:
return 0
pre = nums[0]
i = 0
while i < len(nums):
if nums[i] == pre:
count += 1
if count > 2:... | the_stack_v2_python_sparse | PythonCode/src/0080_Remove_Duplicates_from_Sorted_Array_II.py | oneyuan/CodeforFun | train | 0 | |
5ba6e3554063e263c24297241943151e3f6634c1 | [
"try:\n job = self.build_objects_async(build_table=build_table, delete_dataset_contents=delete_dataset_contents, delete_templates=delete_templates)\nexcept IngestionException as e:\n if self.raise_errors:\n raise e\n else:\n return IngestionStatus.from_exception(e)\nstatus = self.poll_for_job... | <|body_start_0|>
try:
job = self.build_objects_async(build_table=build_table, delete_dataset_contents=delete_dataset_contents, delete_templates=delete_templates)
except IngestionException as e:
if self.raise_errors:
raise e
else:
return... | [ALPHA] A job that uploads new information to the platform. Datasets are the basic unit of access control. A user with read access to a dataset can view every object in that dataset. A user with write access to a dataset can create, update, and delete objects in the dataset. Attributes ---------- uid: UUID Unique uuid4... | Ingestion | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ingestion:
"""[ALPHA] A job that uploads new information to the platform. Datasets are the basic unit of access control. A user with read access to a dataset can view every object in that dataset. A user with write access to a dataset can create, update, and delete objects in the dataset. Attribu... | stack_v2_sparse_classes_75kplus_train_009270 | 18,706 | permissive | [
{
"docstring": "[ALPHA] Perform a complete ingestion operation, from start to finish. Initiates an ingestion operation, polls the server to determine when the job has finished, and returns the outcome. Parameters ---------- build_table: bool Whether to build a table immediately after ingestion. Default : False ... | 4 | stack_v2_sparse_classes_30k_train_019175 | Implement the Python class `Ingestion` described below.
Class description:
[ALPHA] A job that uploads new information to the platform. Datasets are the basic unit of access control. A user with read access to a dataset can view every object in that dataset. A user with write access to a dataset can create, update, and... | Implement the Python class `Ingestion` described below.
Class description:
[ALPHA] A job that uploads new information to the platform. Datasets are the basic unit of access control. A user with read access to a dataset can view every object in that dataset. A user with write access to a dataset can create, update, and... | 43898bfc66edbe10fab00f614ee68c9ea20c4c52 | <|skeleton|>
class Ingestion:
"""[ALPHA] A job that uploads new information to the platform. Datasets are the basic unit of access control. A user with read access to a dataset can view every object in that dataset. A user with write access to a dataset can create, update, and delete objects in the dataset. Attribu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ingestion:
"""[ALPHA] A job that uploads new information to the platform. Datasets are the basic unit of access control. A user with read access to a dataset can view every object in that dataset. A user with write access to a dataset can create, update, and delete objects in the dataset. Attributes ---------... | the_stack_v2_python_sparse | src/citrine/resources/ingestion.py | CitrineInformatics/citrine-python | train | 30 |
7cf58d3906fd27930ab2a46116a517948ff7d12d | [
"tx_power_idx_to_tx_power: Dict = {}\nfor channel, info in hardware_config['tx_power_idx_to_tx_power'].items():\n tx_power_idx_to_tx_power[channel] = {}\n for mcs, tx_data in info.items():\n tx_power_idx_to_tx_power[channel][mcs] = {}\n for tx_power_idx, tx_power in tx_data.items():\n ... | <|body_start_0|>
tx_power_idx_to_tx_power: Dict = {}
for channel, info in hardware_config['tx_power_idx_to_tx_power'].items():
tx_power_idx_to_tx_power[channel] = {}
for mcs, tx_data in info.items():
tx_power_idx_to_tx_power[channel][mcs] = {}
for ... | HardwareConfig | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HardwareConfig:
def set_config(cls, hardware_config: Dict) -> None:
"""Set all hardware config params."""
<|body_0|>
def get_pwr_offset(cls, target_pwr_idx: Optional[int]=None, ref_pwr_idx: Optional[int]=None, channel: Optional[str]=None, mcs: Optional[str]=None) -> int:
... | stack_v2_sparse_classes_75kplus_train_009271 | 4,491 | permissive | [
{
"docstring": "Set all hardware config params.",
"name": "set_config",
"signature": "def set_config(cls, hardware_config: Dict) -> None"
},
{
"docstring": "Estimate inr offset on target power idx, given inr at reference power idx.",
"name": "get_pwr_offset",
"signature": "def get_pwr_of... | 3 | stack_v2_sparse_classes_30k_train_007090 | Implement the Python class `HardwareConfig` described below.
Class description:
Implement the HardwareConfig class.
Method signatures and docstrings:
- def set_config(cls, hardware_config: Dict) -> None: Set all hardware config params.
- def get_pwr_offset(cls, target_pwr_idx: Optional[int]=None, ref_pwr_idx: Optiona... | Implement the Python class `HardwareConfig` described below.
Class description:
Implement the HardwareConfig class.
Method signatures and docstrings:
- def set_config(cls, hardware_config: Dict) -> None: Set all hardware config params.
- def get_pwr_offset(cls, target_pwr_idx: Optional[int]=None, ref_pwr_idx: Optiona... | 93c0c4bef28c1ed15dc61e9fd340a9faef4902e3 | <|skeleton|>
class HardwareConfig:
def set_config(cls, hardware_config: Dict) -> None:
"""Set all hardware config params."""
<|body_0|>
def get_pwr_offset(cls, target_pwr_idx: Optional[int]=None, ref_pwr_idx: Optional[int]=None, channel: Optional[str]=None, mcs: Optional[str]=None) -> int:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HardwareConfig:
def set_config(cls, hardware_config: Dict) -> None:
"""Set all hardware config params."""
tx_power_idx_to_tx_power: Dict = {}
for channel, info in hardware_config['tx_power_idx_to_tx_power'].items():
tx_power_idx_to_tx_power[channel] = {}
for mcs... | the_stack_v2_python_sparse | scan_service/scan_service/utils/hardware_config.py | terragraph/tgnms | train | 15 | |
5cf6d21555c565c3783a98c4288b19590ee2ad20 | [
"super().__init__(results, best_results, options, group_dir, pp_locations, table_name)\nself.name = 'emissions'\nself.has_pp = True\nself.pp_filenames = [os.path.relpath(self.pp_locations[1], group_dir)]\nself.cbar_title = 'Problem-Specific Cell Shading: Relative Emissions'",
"rel_value = result.norm_emissions\na... | <|body_start_0|>
super().__init__(results, best_results, options, group_dir, pp_locations, table_name)
self.name = 'emissions'
self.has_pp = True
self.pp_filenames = [os.path.relpath(self.pp_locations[1], group_dir)]
self.cbar_title = 'Problem-Specific Cell Shading: Relative Emis... | The emissions (kg CO\\ :sub:`2`\\ eq) results are calculated from an average (over num_runs) using the `codecarbon <https://mlco2.github.io/codecarbon/index.html>`_ module. num_runs is set in :ref:`options`. Configuration for codecarbon is set in ``.codecarbon.config``. Please note that for tracking CPU power usage on ... | EmissionsTable | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmissionsTable:
"""The emissions (kg CO\\ :sub:`2`\\ eq) results are calculated from an average (over num_runs) using the `codecarbon <https://mlco2.github.io/codecarbon/index.html>`_ module. num_runs is set in :ref:`options`. Configuration for codecarbon is set in ``.codecarbon.config``. Please ... | stack_v2_sparse_classes_75kplus_train_009272 | 2,728 | permissive | [
{
"docstring": "Initialise the emissions table which shows the average emissions results :param results: Results grouped by row and category (for colouring) :type results: dict[str, dict[str, list[utils.fitbm_result.FittingResult]]] :param best_results: The best results from each row/category :type best_results... | 2 | null | Implement the Python class `EmissionsTable` described below.
Class description:
The emissions (kg CO\\ :sub:`2`\\ eq) results are calculated from an average (over num_runs) using the `codecarbon <https://mlco2.github.io/codecarbon/index.html>`_ module. num_runs is set in :ref:`options`. Configuration for codecarbon is... | Implement the Python class `EmissionsTable` described below.
Class description:
The emissions (kg CO\\ :sub:`2`\\ eq) results are calculated from an average (over num_runs) using the `codecarbon <https://mlco2.github.io/codecarbon/index.html>`_ module. num_runs is set in :ref:`options`. Configuration for codecarbon is... | 5ee7e66d963ebe9296c0a62c24b9616f6c65537e | <|skeleton|>
class EmissionsTable:
"""The emissions (kg CO\\ :sub:`2`\\ eq) results are calculated from an average (over num_runs) using the `codecarbon <https://mlco2.github.io/codecarbon/index.html>`_ module. num_runs is set in :ref:`options`. Configuration for codecarbon is set in ``.codecarbon.config``. Please ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmissionsTable:
"""The emissions (kg CO\\ :sub:`2`\\ eq) results are calculated from an average (over num_runs) using the `codecarbon <https://mlco2.github.io/codecarbon/index.html>`_ module. num_runs is set in :ref:`options`. Configuration for codecarbon is set in ``.codecarbon.config``. Please note that for... | the_stack_v2_python_sparse | fitbenchmarking/results_processing/emissions_table.py | fitbenchmarking/fitbenchmarking | train | 15 |
ee06e713d27fb5a06a055e5d2b5418d4f6890355 | [
"logs = get_logging_container()\nstdout, parsed_data, logs = self.parse_stdout_from_retrieved(logs)\nbase_exit_code = self.check_base_errors(logs)\nif base_exit_code:\n return self.exit(base_exit_code, logs)\nself.out('output_parameters', Dict(parsed_data))\nfor exit_code in self.get_error_map().values():\n i... | <|body_start_0|>
logs = get_logging_container()
stdout, parsed_data, logs = self.parse_stdout_from_retrieved(logs)
base_exit_code = self.check_base_errors(logs)
if base_exit_code:
return self.exit(base_exit_code, logs)
self.out('output_parameters', Dict(parsed_data))
... | ``Parser`` implementation for the ``OpenGridCalculation`` calculation job class. | OpenGridParser | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenGridParser:
"""``Parser`` implementation for the ``OpenGridCalculation`` calculation job class."""
def parse(self, **kwargs):
"""Parse the retrieved files of a completed ``OpenGridCalculation`` into output nodes."""
<|body_0|>
def parse_kpoints(stdout: str, logs: Att... | stack_v2_sparse_classes_75kplus_train_009273 | 2,749 | permissive | [
{
"docstring": "Parse the retrieved files of a completed ``OpenGridCalculation`` into output nodes.",
"name": "parse",
"signature": "def parse(self, **kwargs)"
},
{
"docstring": "Parse the ``stdout`` for the mesh and explicit list of kpoints.",
"name": "parse_kpoints",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_041151 | Implement the Python class `OpenGridParser` described below.
Class description:
``Parser`` implementation for the ``OpenGridCalculation`` calculation job class.
Method signatures and docstrings:
- def parse(self, **kwargs): Parse the retrieved files of a completed ``OpenGridCalculation`` into output nodes.
- def pars... | Implement the Python class `OpenGridParser` described below.
Class description:
``Parser`` implementation for the ``OpenGridCalculation`` calculation job class.
Method signatures and docstrings:
- def parse(self, **kwargs): Parse the retrieved files of a completed ``OpenGridCalculation`` into output nodes.
- def pars... | 7263f92ccabcfc9f828b9da5473e1aefbc4b8eca | <|skeleton|>
class OpenGridParser:
"""``Parser`` implementation for the ``OpenGridCalculation`` calculation job class."""
def parse(self, **kwargs):
"""Parse the retrieved files of a completed ``OpenGridCalculation`` into output nodes."""
<|body_0|>
def parse_kpoints(stdout: str, logs: Att... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpenGridParser:
"""``Parser`` implementation for the ``OpenGridCalculation`` calculation job class."""
def parse(self, **kwargs):
"""Parse the retrieved files of a completed ``OpenGridCalculation`` into output nodes."""
logs = get_logging_container()
stdout, parsed_data, logs = se... | the_stack_v2_python_sparse | src/aiida_quantumespresso/parsers/open_grid.py | aiidateam/aiida-quantumespresso | train | 56 |
969daaeee23c5722ffab9c5de7d252a1f116b3e3 | [
"super(MatchTensor, self).__init__()\nself.dictionary = dictionary\nself.embedding_index = embedding_index\nself.config = args\nself.num_directions = 2 if self.config.bidirection else 1\nself.embedding = EmbeddingLayer(len(self.dictionary), self.config)\nself.linear_projection = nn.Linear(self.config.emsize, self.c... | <|body_start_0|>
super(MatchTensor, self).__init__()
self.dictionary = dictionary
self.embedding_index = embedding_index
self.config = args
self.num_directions = 2 if self.config.bidirection else 1
self.embedding = EmbeddingLayer(len(self.dictionary), self.config)
... | Class that classifies question pair as duplicate or not. | MatchTensor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatchTensor:
"""Class that classifies question pair as duplicate or not."""
def __init__(self, dictionary, embedding_index, args):
""""Constructor of the class."""
<|body_0|>
def forward(self, batch_queries, query_len, batch_docs, doc_len):
"""Forward function of... | stack_v2_sparse_classes_75kplus_train_009274 | 6,081 | permissive | [
{
"docstring": "\"Constructor of the class.",
"name": "__init__",
"signature": "def __init__(self, dictionary, embedding_index, args)"
},
{
"docstring": "Forward function of the match tensor model. Return average loss for a batch of sessions. :param batch_queries: 2d tensor [batch_size x max_que... | 2 | null | Implement the Python class `MatchTensor` described below.
Class description:
Class that classifies question pair as duplicate or not.
Method signatures and docstrings:
- def __init__(self, dictionary, embedding_index, args): "Constructor of the class.
- def forward(self, batch_queries, query_len, batch_docs, doc_len)... | Implement the Python class `MatchTensor` described below.
Class description:
Class that classifies question pair as duplicate or not.
Method signatures and docstrings:
- def __init__(self, dictionary, embedding_index, args): "Constructor of the class.
- def forward(self, batch_queries, query_len, batch_docs, doc_len)... | 5bd241fb49f08fa4937539991e12e5a502d5a072 | <|skeleton|>
class MatchTensor:
"""Class that classifies question pair as duplicate or not."""
def __init__(self, dictionary, embedding_index, args):
""""Constructor of the class."""
<|body_0|>
def forward(self, batch_queries, query_len, batch_docs, doc_len):
"""Forward function of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MatchTensor:
"""Class that classifies question pair as duplicate or not."""
def __init__(self, dictionary, embedding_index, args):
""""Constructor of the class."""
super(MatchTensor, self).__init__()
self.dictionary = dictionary
self.embedding_index = embedding_index
... | the_stack_v2_python_sparse | ranking_baselines/MATCH_TENSOR/model.py | polaris79/mnsrf_ranking_suggestion | train | 0 |
56ba4a33a842cfedb21b752c31b4dfaeeca1e292 | [
"super(DeclarativeNameError, self).__init__(name)\nself.name = name\nself.filename = filename\nself.lineno = lineno\nself.block = block",
"text = '%s\\n\\n' % self.name\ntext += _format_source_error(self.filename, self.lineno, self.block)\ntext += \"\\n\\nNameError: global name '%s' is not defined\" % self.name\n... | <|body_start_0|>
super(DeclarativeNameError, self).__init__(name)
self.name = name
self.filename = filename
self.lineno = lineno
self.block = block
<|end_body_0|>
<|body_start_1|>
text = '%s\n\n' % self.name
text += _format_source_error(self.filename, self.lineno... | A NameError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed global lookups when building out the object tree. | DeclarativeNameError | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeclarativeNameError:
"""A NameError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed global lookups when building out the object tree."""
def __init__(self, name, filename, lineno, block):
"""I... | stack_v2_sparse_classes_75kplus_train_009275 | 4,784 | permissive | [
{
"docstring": "Initialize a DeclarativeNameError. Parameters ---------- name : str The name of global symbol which was not found. filename : str The filename where the lookup failed. lineno : int The line number of the error. block : str The name of the lexical block in which the lookup failed.",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_051195 | Implement the Python class `DeclarativeNameError` described below.
Class description:
A NameError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed global lookups when building out the object tree.
Method signatures and docstring... | Implement the Python class `DeclarativeNameError` described below.
Class description:
A NameError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed global lookups when building out the object tree.
Method signatures and docstring... | 424bba29219de58fe9e47196de6763de8b2009f2 | <|skeleton|>
class DeclarativeNameError:
"""A NameError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed global lookups when building out the object tree."""
def __init__(self, name, filename, lineno, block):
"""I... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeclarativeNameError:
"""A NameError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed global lookups when building out the object tree."""
def __init__(self, name, filename, lineno, block):
"""Initialize a D... | the_stack_v2_python_sparse | enaml/core/exceptions.py | enthought/enaml | train | 17 |
f34a29071aabec3b4f322d461488c8f4bf9b805c | [
"super(LeNet, self).__init__()\nself.class_num = class_num\nself.features = self._make_layers()\nself.classifier = self._classifer_layers()\nself.in_channels = 1",
"layers = []\nfor layer_type in self.cfg:\n if layer_type == 'M':\n layer = [nn.MaxPool3d(kernel_size=(1, self.pool_kernel_size, self.pool_k... | <|body_start_0|>
super(LeNet, self).__init__()
self.class_num = class_num
self.features = self._make_layers()
self.classifier = self._classifer_layers()
self.in_channels = 1
<|end_body_0|>
<|body_start_1|>
layers = []
for layer_type in self.cfg:
if la... | LeNet神经网络结构搭建, 分类前fc层改为GAP, 加入BN, 激活函数为ReLU, 欠拟合严重,加入NiN增加非线性 | LeNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LeNet:
"""LeNet神经网络结构搭建, 分类前fc层改为GAP, 加入BN, 激活函数为ReLU, 欠拟合严重,加入NiN增加非线性"""
def __init__(self, class_num):
"""网络初始化 param: class_num 目标分类数"""
<|body_0|>
def _make_layers(self):
"""建立特征提取部分网络 return LeNet_feature_net LeNet特征提取部分"""
<|body_1|>
def _clas... | stack_v2_sparse_classes_75kplus_train_009276 | 28,867 | no_license | [
{
"docstring": "网络初始化 param: class_num 目标分类数",
"name": "__init__",
"signature": "def __init__(self, class_num)"
},
{
"docstring": "建立特征提取部分网络 return LeNet_feature_net LeNet特征提取部分",
"name": "_make_layers",
"signature": "def _make_layers(self)"
},
{
"docstring": "建立分类部分网络 return Le... | 4 | stack_v2_sparse_classes_30k_train_011499 | Implement the Python class `LeNet` described below.
Class description:
LeNet神经网络结构搭建, 分类前fc层改为GAP, 加入BN, 激活函数为ReLU, 欠拟合严重,加入NiN增加非线性
Method signatures and docstrings:
- def __init__(self, class_num): 网络初始化 param: class_num 目标分类数
- def _make_layers(self): 建立特征提取部分网络 return LeNet_feature_net LeNet特征提取部分
- def _classife... | Implement the Python class `LeNet` described below.
Class description:
LeNet神经网络结构搭建, 分类前fc层改为GAP, 加入BN, 激活函数为ReLU, 欠拟合严重,加入NiN增加非线性
Method signatures and docstrings:
- def __init__(self, class_num): 网络初始化 param: class_num 目标分类数
- def _make_layers(self): 建立特征提取部分网络 return LeNet_feature_net LeNet特征提取部分
- def _classife... | 2a68fd854bc5b1806319dfc40e36e084f9c4c5d0 | <|skeleton|>
class LeNet:
"""LeNet神经网络结构搭建, 分类前fc层改为GAP, 加入BN, 激活函数为ReLU, 欠拟合严重,加入NiN增加非线性"""
def __init__(self, class_num):
"""网络初始化 param: class_num 目标分类数"""
<|body_0|>
def _make_layers(self):
"""建立特征提取部分网络 return LeNet_feature_net LeNet特征提取部分"""
<|body_1|>
def _clas... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LeNet:
"""LeNet神经网络结构搭建, 分类前fc层改为GAP, 加入BN, 激活函数为ReLU, 欠拟合严重,加入NiN增加非线性"""
def __init__(self, class_num):
"""网络初始化 param: class_num 目标分类数"""
super(LeNet, self).__init__()
self.class_num = class_num
self.features = self._make_layers()
self.classifier = self._classif... | the_stack_v2_python_sparse | code_keh/Pytorch_nets3d.py | ruichen9/3DCTLungDiseaseDiagnosis | train | 0 |
2df5df756ce58a338d527cf8296f173414b6e2d5 | [
"self.regex = {}\nif regex_src:\n self.regex[0] = regex_src\nif regex_trg:\n self.regex[1] = regex_trg\nif regex_all:\n for i, v in enumerate(regex_all):\n self.regex[i] = v",
"for i, sent in enumerate(sents):\n if type(sent) == list:\n sent = ' '.join(sent)\n if self.regex.get(i) is ... | <|body_start_0|>
self.regex = {}
if regex_src:
self.regex[0] = regex_src
if regex_trg:
self.regex[1] = regex_trg
if regex_all:
for i, v in enumerate(regex_all):
self.regex[i] = v
<|end_body_0|>
<|body_start_1|>
for i, sent in e... | Filters sentences via regular expressions. A sentence must match the expression to be kept. | SentenceFiltererMatchingRegex | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SentenceFiltererMatchingRegex:
"""Filters sentences via regular expressions. A sentence must match the expression to be kept."""
def __init__(self, regex_src: Optional[str], regex_trg: Optional[str], regex_all: Optional[Sequence[str]]) -> None:
"""Specifies the regular expressions to... | stack_v2_sparse_classes_75kplus_train_009277 | 32,168 | permissive | [
{
"docstring": "Specifies the regular expressions to filter the sentences that we'll be getting. Args: regex_src: regular expression for source language (language index 0) regex_trg: regular expression for target language (language index 1) regex_all: list of regular expressions for all languages in order",
... | 2 | stack_v2_sparse_classes_30k_train_005480 | Implement the Python class `SentenceFiltererMatchingRegex` described below.
Class description:
Filters sentences via regular expressions. A sentence must match the expression to be kept.
Method signatures and docstrings:
- def __init__(self, regex_src: Optional[str], regex_trg: Optional[str], regex_all: Optional[Sequ... | Implement the Python class `SentenceFiltererMatchingRegex` described below.
Class description:
Filters sentences via regular expressions. A sentence must match the expression to be kept.
Method signatures and docstrings:
- def __init__(self, regex_src: Optional[str], regex_trg: Optional[str], regex_all: Optional[Sequ... | b5e6985d3bedfac102312cab030a60594bc17baf | <|skeleton|>
class SentenceFiltererMatchingRegex:
"""Filters sentences via regular expressions. A sentence must match the expression to be kept."""
def __init__(self, regex_src: Optional[str], regex_trg: Optional[str], regex_all: Optional[Sequence[str]]) -> None:
"""Specifies the regular expressions to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SentenceFiltererMatchingRegex:
"""Filters sentences via regular expressions. A sentence must match the expression to be kept."""
def __init__(self, regex_src: Optional[str], regex_trg: Optional[str], regex_all: Optional[Sequence[str]]) -> None:
"""Specifies the regular expressions to filter the s... | the_stack_v2_python_sparse | xnmt/preproc.py | philip30/xnmt | train | 0 |
f72172eac2c6d21542d8b35978e52d69bbc8cf3e | [
"flask_config = config.flask_config[config.FLASK_ENV]\nlog_conf = flask_config.LOGGER_CONF\npath = os.path.join(config.BASEDIR, log_conf['path'])\nif not os.path.isdir(path):\n os.makedirs(path)\nlogger = logging.getLogger()\nlogger.setLevel(log_conf['level'])\nhandler = logging.StreamHandler()\nhandler.setForma... | <|body_start_0|>
flask_config = config.flask_config[config.FLASK_ENV]
log_conf = flask_config.LOGGER_CONF
path = os.path.join(config.BASEDIR, log_conf['path'])
if not os.path.isdir(path):
os.makedirs(path)
logger = logging.getLogger()
logger.setLevel(log_conf[... | FlaskApp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlaskApp:
def init_logger(cls):
"""日志配置 :return:"""
<|body_0|>
def init_extensions(cls, _app):
"""初始化第三方插件 :param _app: :return:"""
<|body_1|>
def create_app(cls, service_name, config_name):
"""根据config name创建不同环境下的app :param service_name: 服务名称就是... | stack_v2_sparse_classes_75kplus_train_009278 | 3,975 | no_license | [
{
"docstring": "日志配置 :return:",
"name": "init_logger",
"signature": "def init_logger(cls)"
},
{
"docstring": "初始化第三方插件 :param _app: :return:",
"name": "init_extensions",
"signature": "def init_extensions(cls, _app)"
},
{
"docstring": "根据config name创建不同环境下的app :param service_name:... | 3 | stack_v2_sparse_classes_30k_train_042519 | Implement the Python class `FlaskApp` described below.
Class description:
Implement the FlaskApp class.
Method signatures and docstrings:
- def init_logger(cls): 日志配置 :return:
- def init_extensions(cls, _app): 初始化第三方插件 :param _app: :return:
- def create_app(cls, service_name, config_name): 根据config name创建不同环境下的app :p... | Implement the Python class `FlaskApp` described below.
Class description:
Implement the FlaskApp class.
Method signatures and docstrings:
- def init_logger(cls): 日志配置 :return:
- def init_extensions(cls, _app): 初始化第三方插件 :param _app: :return:
- def create_app(cls, service_name, config_name): 根据config name创建不同环境下的app :p... | ff36deb73e667de16a73b1666bbeaf28f993f944 | <|skeleton|>
class FlaskApp:
def init_logger(cls):
"""日志配置 :return:"""
<|body_0|>
def init_extensions(cls, _app):
"""初始化第三方插件 :param _app: :return:"""
<|body_1|>
def create_app(cls, service_name, config_name):
"""根据config name创建不同环境下的app :param service_name: 服务名称就是... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FlaskApp:
def init_logger(cls):
"""日志配置 :return:"""
flask_config = config.flask_config[config.FLASK_ENV]
log_conf = flask_config.LOGGER_CONF
path = os.path.join(config.BASEDIR, log_conf['path'])
if not os.path.isdir(path):
os.makedirs(path)
logger = ... | the_stack_v2_python_sparse | backend/app/app.py | LyanJin/check-pay | train | 0 | |
6a4e4806df4e24c293067bd670cfa398d410dd91 | [
"xml.sax.handler.ContentHandler.__init__(self)\nself._objs = []\nself._being = None\nself._level = 0\nself._tag = None\nself._tile = []\nself._pointer = None\nself._forget_root = True\nself._no_content = no_content\nself._prepare_stringio()",
"if not self._no_content:\n self._xmlio = io.StringIO()\n self._x... | <|body_start_0|>
xml.sax.handler.ContentHandler.__init__(self)
self._objs = []
self._being = None
self._level = 0
self._tag = None
self._tile = []
self._pointer = None
self._forget_root = True
self._no_content = no_content
self._prepare_str... | Overloads functions about XML, it produces objects at the end we assume the file contains a list of objects. | XMLHandlerDict | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XMLHandlerDict:
"""Overloads functions about XML, it produces objects at the end we assume the file contains a list of objects."""
def __init__(self, no_content=False):
"""@param no_content avoid loading the content of every record"""
<|body_0|>
def _prepare_stringio(sel... | stack_v2_sparse_classes_75kplus_train_009279 | 7,250 | permissive | [
{
"docstring": "@param no_content avoid loading the content of every record",
"name": "__init__",
"signature": "def __init__(self, no_content=False)"
},
{
"docstring": "prepare the StringIO stream",
"name": "_prepare_stringio",
"signature": "def _prepare_stringio(self)"
},
{
"doc... | 5 | stack_v2_sparse_classes_30k_train_049196 | Implement the Python class `XMLHandlerDict` described below.
Class description:
Overloads functions about XML, it produces objects at the end we assume the file contains a list of objects.
Method signatures and docstrings:
- def __init__(self, no_content=False): @param no_content avoid loading the content of every re... | Implement the Python class `XMLHandlerDict` described below.
Class description:
Overloads functions about XML, it produces objects at the end we assume the file contains a list of objects.
Method signatures and docstrings:
- def __init__(self, no_content=False): @param no_content avoid loading the content of every re... | 68399f58ed258599e77f8bde45835169a0e9238d | <|skeleton|>
class XMLHandlerDict:
"""Overloads functions about XML, it produces objects at the end we assume the file contains a list of objects."""
def __init__(self, no_content=False):
"""@param no_content avoid loading the content of every record"""
<|body_0|>
def _prepare_stringio(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XMLHandlerDict:
"""Overloads functions about XML, it produces objects at the end we assume the file contains a list of objects."""
def __init__(self, no_content=False):
"""@param no_content avoid loading the content of every record"""
xml.sax.handler.ContentHandler.__init__(self)
... | the_stack_v2_python_sparse | src/pyrsslocal/xmlhelper/xml_tree.py | sdpython/pyrsslocal | train | 2 |
74065dc53c5d122f855c61c3e62fcf831918481f | [
"def caller(query_compiler, *args, **kwargs):\n \"\"\"Execute MapReduce function against passed query compiler.\"\"\"\n _axis = kwargs.get('axis') if axis is None else axis\n return query_compiler.__constructor__(query_compiler._modin_frame.map_reduce(cls.validate_axis(_axis), lambda x: map_function(x, *ar... | <|body_start_0|>
def caller(query_compiler, *args, **kwargs):
"""Execute MapReduce function against passed query compiler."""
_axis = kwargs.get('axis') if axis is None else axis
return query_compiler.__constructor__(query_compiler._modin_frame.map_reduce(cls.validate_axis(_a... | Builder class for MapReduce functions. | MapReduceFunction | [
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MapReduceFunction:
"""Builder class for MapReduce functions."""
def call(cls, map_function, reduce_function, axis=None):
"""Build MapReduce function. Parameters ---------- map_function : callable(pandas.DataFrame) -> pandas.DataFrame Source map function. reduce_function : callable(pa... | stack_v2_sparse_classes_75kplus_train_009280 | 3,073 | permissive | [
{
"docstring": "Build MapReduce function. Parameters ---------- map_function : callable(pandas.DataFrame) -> pandas.DataFrame Source map function. reduce_function : callable(pandas.DataFrame) -> pandas.Series Source reduce function. axis : int, optional Specifies axis to apply function along. Returns ------- ca... | 2 | stack_v2_sparse_classes_30k_train_020403 | Implement the Python class `MapReduceFunction` described below.
Class description:
Builder class for MapReduce functions.
Method signatures and docstrings:
- def call(cls, map_function, reduce_function, axis=None): Build MapReduce function. Parameters ---------- map_function : callable(pandas.DataFrame) -> pandas.Dat... | Implement the Python class `MapReduceFunction` described below.
Class description:
Builder class for MapReduce functions.
Method signatures and docstrings:
- def call(cls, map_function, reduce_function, axis=None): Build MapReduce function. Parameters ---------- map_function : callable(pandas.DataFrame) -> pandas.Dat... | b58663bd8f2c8802bb45d7bafa2cc65ae988f959 | <|skeleton|>
class MapReduceFunction:
"""Builder class for MapReduce functions."""
def call(cls, map_function, reduce_function, axis=None):
"""Build MapReduce function. Parameters ---------- map_function : callable(pandas.DataFrame) -> pandas.DataFrame Source map function. reduce_function : callable(pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MapReduceFunction:
"""Builder class for MapReduce functions."""
def call(cls, map_function, reduce_function, axis=None):
"""Build MapReduce function. Parameters ---------- map_function : callable(pandas.DataFrame) -> pandas.DataFrame Source map function. reduce_function : callable(pandas.DataFram... | the_stack_v2_python_sparse | modin/data_management/functions/mapreducefunction.py | wroldwiedbwe/modin | train | 0 |
6f85ed1ec543e071aad1ab3e4ab2621607adb285 | [
"self.location = None\nif not os.path.exists(location):\n raise FileNotFoundError('Could not find file at \"{}\"'.format(location))\nself.location = location",
"if self.location:\n with open(self.location, 'rb') as f:\n return hashlib.sha1(f.read()).hexdigest()\nelse:\n return hashlib.sha1(''.enco... | <|body_start_0|>
self.location = None
if not os.path.exists(location):
raise FileNotFoundError('Could not find file at "{}"'.format(location))
self.location = location
<|end_body_0|>
<|body_start_1|>
if self.location:
with open(self.location, 'rb') as f:
... | Create a audio_file object for - storing location - retrieving a unique hash - resampling for training - splitting into segments given an STM file | audio_file | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class audio_file:
"""Create a audio_file object for - storing location - retrieving a unique hash - resampling for training - splitting into segments given an STM file"""
def __init__(self, location=''):
"""Populate file location info"""
<|body_0|>
def hash(self):
"""R... | stack_v2_sparse_classes_75kplus_train_009281 | 4,746 | permissive | [
{
"docstring": "Populate file location info",
"name": "__init__",
"signature": "def __init__(self, location='')"
},
{
"docstring": "Returns a sha1 hash of the file",
"name": "hash",
"signature": "def hash(self)"
},
{
"docstring": "Converts to single channel (from channel 1) audio... | 4 | stack_v2_sparse_classes_30k_train_000172 | Implement the Python class `audio_file` described below.
Class description:
Create a audio_file object for - storing location - retrieving a unique hash - resampling for training - splitting into segments given an STM file
Method signatures and docstrings:
- def __init__(self, location=''): Populate file location inf... | Implement the Python class `audio_file` described below.
Class description:
Create a audio_file object for - storing location - retrieving a unique hash - resampling for training - splitting into segments given an STM file
Method signatures and docstrings:
- def __init__(self, location=''): Populate file location inf... | 2a6e1fba1ebb67b69fe005f3b9a5c2a82d8787d1 | <|skeleton|>
class audio_file:
"""Create a audio_file object for - storing location - retrieving a unique hash - resampling for training - splitting into segments given an STM file"""
def __init__(self, location=''):
"""Populate file location info"""
<|body_0|>
def hash(self):
"""R... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class audio_file:
"""Create a audio_file object for - storing location - retrieving a unique hash - resampling for training - splitting into segments given an STM file"""
def __init__(self, location=''):
"""Populate file location info"""
self.location = None
if not os.path.exists(locati... | the_stack_v2_python_sparse | asrtoolkit/data_structures/audio_file.py | finos/greenkey-asrtoolkit | train | 35 |
f42d522c7b847f447ad3707a8fec16c9ff32ea99 | [
"sm = get_storage_manager()\nwith sm.transaction():\n role = sm.get(models.Role, None, filters={'name': role_name})\n already_exists = models.Permission.query.filter_by(role=role, name=permission_name).first()\n if already_exists:\n raise manager_exceptions.ConflictError(f'{role_name} already has pe... | <|body_start_0|>
sm = get_storage_manager()
with sm.transaction():
role = sm.get(models.Role, None, filters={'name': role_name})
already_exists = models.Permission.query.filter_by(role=role, name=permission_name).first()
if already_exists:
raise manage... | PermissionsRoleId | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PermissionsRoleId:
def put(self, role_name, permission_name):
"""Allow role_name the permission permission_name"""
<|body_0|>
def delete(self, role_name, permission_name):
"""Disallow role_name the permission permission_name"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_009282 | 3,208 | permissive | [
{
"docstring": "Allow role_name the permission permission_name",
"name": "put",
"signature": "def put(self, role_name, permission_name)"
},
{
"docstring": "Disallow role_name the permission permission_name",
"name": "delete",
"signature": "def delete(self, role_name, permission_name)"
... | 2 | stack_v2_sparse_classes_30k_train_013407 | Implement the Python class `PermissionsRoleId` described below.
Class description:
Implement the PermissionsRoleId class.
Method signatures and docstrings:
- def put(self, role_name, permission_name): Allow role_name the permission permission_name
- def delete(self, role_name, permission_name): Disallow role_name the... | Implement the Python class `PermissionsRoleId` described below.
Class description:
Implement the PermissionsRoleId class.
Method signatures and docstrings:
- def put(self, role_name, permission_name): Allow role_name the permission permission_name
- def delete(self, role_name, permission_name): Disallow role_name the... | c0de6442e1d7653fad824d75e571802a74eee605 | <|skeleton|>
class PermissionsRoleId:
def put(self, role_name, permission_name):
"""Allow role_name the permission permission_name"""
<|body_0|>
def delete(self, role_name, permission_name):
"""Disallow role_name the permission permission_name"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PermissionsRoleId:
def put(self, role_name, permission_name):
"""Allow role_name the permission permission_name"""
sm = get_storage_manager()
with sm.transaction():
role = sm.get(models.Role, None, filters={'name': role_name})
already_exists = models.Permission.... | the_stack_v2_python_sparse | rest-service/manager_rest/rest/resources_v3_1/permissions.py | cloudify-cosmo/cloudify-manager | train | 146 | |
bddc953027593aedb9e9519b3f74892df84226cc | [
"if user.is_anonymous or user.is_client:\n return False\nif user.is_administrator:\n return False\nif user.is_manager:\n return False\nif user.is_advisor:\n return Image.objects.filter(pk=image.pk).accessible_by(user).exists()\nreturn self.admin_permission(user, image, *args)",
"if user.is_anonymous o... | <|body_start_0|>
if user.is_anonymous or user.is_client:
return False
if user.is_administrator:
return False
if user.is_manager:
return False
if user.is_advisor:
return Image.objects.filter(pk=image.pk).accessible_by(user).exists()
... | ImagePermissionLogic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImagePermissionLogic:
def view(self, user, image, *args):
"""Permissions for viewing Image"""
<|body_0|>
def create(self, user, image, *args):
"""Permissions for creating image"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if user.is_anonymous or ... | stack_v2_sparse_classes_75kplus_train_009283 | 1,151 | no_license | [
{
"docstring": "Permissions for viewing Image",
"name": "view",
"signature": "def view(self, user, image, *args)"
},
{
"docstring": "Permissions for creating image",
"name": "create",
"signature": "def create(self, user, image, *args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018232 | Implement the Python class `ImagePermissionLogic` described below.
Class description:
Implement the ImagePermissionLogic class.
Method signatures and docstrings:
- def view(self, user, image, *args): Permissions for viewing Image
- def create(self, user, image, *args): Permissions for creating image | Implement the Python class `ImagePermissionLogic` described below.
Class description:
Implement the ImagePermissionLogic class.
Method signatures and docstrings:
- def view(self, user, image, *args): Permissions for viewing Image
- def create(self, user, image, *args): Permissions for creating image
<|skeleton|>
cla... | 95d21cd6036a99c5f399b700a5426e9e2e17e878 | <|skeleton|>
class ImagePermissionLogic:
def view(self, user, image, *args):
"""Permissions for viewing Image"""
<|body_0|>
def create(self, user, image, *args):
"""Permissions for creating image"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImagePermissionLogic:
def view(self, user, image, *args):
"""Permissions for viewing Image"""
if user.is_anonymous or user.is_client:
return False
if user.is_administrator:
return False
if user.is_manager:
return False
if user.is_advi... | the_stack_v2_python_sparse | newsletters/perms/image_perm.py | alexandrenorman/mixeur | train | 0 | |
347c49c263a75290ac4e2e3b5e45637224617001 | [
"if bn.get_user(test_user.email):\n bn.delete_user(test_user.email)\nself.open(base_url + '/logout')\nself.open(base_url + '/register')\nself.type('#email', test_user.email)\nself.type('#name', test_user.name)\nself.type('#password', test_user.password)\nself.type('#password2', test_user.password)\nself.click('i... | <|body_start_0|>
if bn.get_user(test_user.email):
bn.delete_user(test_user.email)
self.open(base_url + '/logout')
self.open(base_url + '/register')
self.type('#email', test_user.email)
self.type('#name', test_user.name)
self.type('#password', test_user.passwor... | integrationTestSignupPost | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class integrationTestSignupPost:
def test_register(self):
"""This tests that the user register as a new user"""
<|body_0|>
def test_login(self):
"""This tests that the user can log in"""
<|body_1|>
def test_integration(self):
"""This tests that the use... | stack_v2_sparse_classes_75kplus_train_009284 | 3,723 | permissive | [
{
"docstring": "This tests that the user register as a new user",
"name": "test_register",
"signature": "def test_register(self)"
},
{
"docstring": "This tests that the user can log in",
"name": "test_login",
"signature": "def test_login(self)"
},
{
"docstring": "This tests that ... | 3 | stack_v2_sparse_classes_30k_train_030317 | Implement the Python class `integrationTestSignupPost` described below.
Class description:
Implement the integrationTestSignupPost class.
Method signatures and docstrings:
- def test_register(self): This tests that the user register as a new user
- def test_login(self): This tests that the user can log in
- def test_... | Implement the Python class `integrationTestSignupPost` described below.
Class description:
Implement the integrationTestSignupPost class.
Method signatures and docstrings:
- def test_register(self): This tests that the user register as a new user
- def test_login(self): This tests that the user can log in
- def test_... | 582e00a4c16016e545fedcbb14a745d125db94e0 | <|skeleton|>
class integrationTestSignupPost:
def test_register(self):
"""This tests that the user register as a new user"""
<|body_0|>
def test_login(self):
"""This tests that the user can log in"""
<|body_1|>
def test_integration(self):
"""This tests that the use... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class integrationTestSignupPost:
def test_register(self):
"""This tests that the user register as a new user"""
if bn.get_user(test_user.email):
bn.delete_user(test_user.email)
self.open(base_url + '/logout')
self.open(base_url + '/register')
self.type('#email', t... | the_stack_v2_python_sparse | qa327_test/integration/test_signup_post.py | GraemeBadley/QA-Project | train | 0 | |
7e72497d7fa22ff6596bb6ffbb3acbffb32f970e | [
"def partition(p, r):\n x = nums[r]\n i = p - 1\n for j in range(p, r):\n if nums[j] < x:\n i += 1\n nums[i], nums[j] = (nums[j], nums[i])\n nums[i + 1], nums[r] = (nums[r], nums[i + 1])\n return i + 1\n\ndef random_partition(p, r):\n ri = randint(p, r)\n nums[ri], ... | <|body_start_0|>
def partition(p, r):
x = nums[r]
i = p - 1
for j in range(p, r):
if nums[j] < x:
i += 1
nums[i], nums[j] = (nums[j], nums[i])
nums[i + 1], nums[r] = (nums[r], nums[i + 1])
return ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
"""Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int"""
<|body_0|>
def findKthLargestPQ(self, nums, k):
"""Algorithm: * Heap O(n lg k), kth largest element is the smallest one in the k-size min-he... | stack_v2_sparse_classes_75kplus_train_009285 | 2,164 | no_license | [
{
"docstring": "Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int",
"name": "findKthLargest",
"signature": "def findKthLargest(self, nums, k)"
},
{
"docstring": "Algorithm: * Heap O(n lg k), kth largest element is the smallest one in the k-size min-heap. :rtype: int",
... | 2 | stack_v2_sparse_classes_30k_train_032376 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int
- def findKthLargestPQ(self, nums, k): Algorithm: * Heap O(n lg k),... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int
- def findKthLargestPQ(self, nums, k): Algorithm: * Heap O(n lg k),... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
"""Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int"""
<|body_0|>
def findKthLargestPQ(self, nums, k):
"""Algorithm: * Heap O(n lg k), kth largest element is the smallest one in the k-size min-he... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findKthLargest(self, nums, k):
"""Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int"""
def partition(p, r):
x = nums[r]
i = p - 1
for j in range(p, r):
if nums[j] < x:
i += 1
... | the_stack_v2_python_sparse | K/KthLargestElementinanArray.py | bssrdf/pyleet | train | 2 | |
d45662f4dd4be5a127e11579b8d510877b610a82 | [
"self.ss = ss\nself.n_step = n_step\nself.interval = step_interval\nself.step_time = step_time\nself.saw_time = saw_time",
"lB = self.interval[0]\nuB = self.interval[1]\nstep_vector = [round(uniform(lB, uB), 1) for _ in range(self.n_step)]\nstep_vector[0] = self.ss\nu = np.zeros(shape=dim)\nj = 0\nramp_Step = sel... | <|body_start_0|>
self.ss = ss
self.n_step = n_step
self.interval = step_interval
self.step_time = step_time
self.saw_time = saw_time
<|end_body_0|>
<|body_start_1|>
lB = self.interval[0]
uB = self.interval[1]
step_vector = [round(uniform(lB, uB), 1) for _... | SawRandStep | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SawRandStep:
def __init__(self, step_time, saw_time, step_interval=None, n_step=None, ss=None):
"""Settings for a random step sequence Args: step_interval (list): Probability interval <a, b> step_time: Time to perform step change n_step (int): Number of steps"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus_train_009286 | 8,036 | no_license | [
{
"docstring": "Settings for a random step sequence Args: step_interval (list): Probability interval <a, b> step_time: Time to perform step change n_step (int): Number of steps",
"name": "__init__",
"signature": "def __init__(self, step_time, saw_time, step_interval=None, n_step=None, ss=None)"
},
{... | 2 | stack_v2_sparse_classes_30k_train_016916 | Implement the Python class `SawRandStep` described below.
Class description:
Implement the SawRandStep class.
Method signatures and docstrings:
- def __init__(self, step_time, saw_time, step_interval=None, n_step=None, ss=None): Settings for a random step sequence Args: step_interval (list): Probability interval <a, ... | Implement the Python class `SawRandStep` described below.
Class description:
Implement the SawRandStep class.
Method signatures and docstrings:
- def __init__(self, step_time, saw_time, step_interval=None, n_step=None, ss=None): Settings for a random step sequence Args: step_interval (list): Probability interval <a, ... | cf548475295f25407ba968546c2fc85c26f9343c | <|skeleton|>
class SawRandStep:
def __init__(self, step_time, saw_time, step_interval=None, n_step=None, ss=None):
"""Settings for a random step sequence Args: step_interval (list): Probability interval <a, b> step_time: Time to perform step change n_step (int): Number of steps"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SawRandStep:
def __init__(self, step_time, saw_time, step_interval=None, n_step=None, ss=None):
"""Settings for a random step sequence Args: step_interval (list): Probability interval <a, b> step_time: Time to perform step change n_step (int): Number of steps"""
self.ss = ss
self.n_ste... | the_stack_v2_python_sparse | SourceCode/simulation/signal.py | martin-bachorik/Master-Thesis-Project | train | 0 | |
d0f8094dff035bb43afe92b24365c26977d4d555 | [
"if not root:\n return 0\nreturn self.subroutine(root, 0)",
"if not node:\n return depth\nreturn min(self.subroutine(node.left, depth + 1), self.subroutine(node.right, depth + 1))"
] | <|body_start_0|>
if not root:
return 0
return self.subroutine(root, 0)
<|end_body_0|>
<|body_start_1|>
if not node:
return depth
return min(self.subroutine(node.left, depth + 1), self.subroutine(node.right, depth + 1))
<|end_body_1|>
| Leet111 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Leet111:
def min_depth(self, root):
"""Find the minimum depth of a tree. Args: root -- TreeNode. Returns: Minimum depth of a tree."""
<|body_0|>
def subroutine(self, node, depth):
"""Find the min depth of two subtrees of a node. Args: node -- TreeNode min_depth -- ke... | stack_v2_sparse_classes_75kplus_train_009287 | 1,036 | no_license | [
{
"docstring": "Find the minimum depth of a tree. Args: root -- TreeNode. Returns: Minimum depth of a tree.",
"name": "min_depth",
"signature": "def min_depth(self, root)"
},
{
"docstring": "Find the min depth of two subtrees of a node. Args: node -- TreeNode min_depth -- keeps track of max dept... | 2 | null | Implement the Python class `Leet111` described below.
Class description:
Implement the Leet111 class.
Method signatures and docstrings:
- def min_depth(self, root): Find the minimum depth of a tree. Args: root -- TreeNode. Returns: Minimum depth of a tree.
- def subroutine(self, node, depth): Find the min depth of tw... | Implement the Python class `Leet111` described below.
Class description:
Implement the Leet111 class.
Method signatures and docstrings:
- def min_depth(self, root): Find the minimum depth of a tree. Args: root -- TreeNode. Returns: Minimum depth of a tree.
- def subroutine(self, node, depth): Find the min depth of tw... | b0cfcfa1eff0101cf8e0e3fb9db55fb83f566f6f | <|skeleton|>
class Leet111:
def min_depth(self, root):
"""Find the minimum depth of a tree. Args: root -- TreeNode. Returns: Minimum depth of a tree."""
<|body_0|>
def subroutine(self, node, depth):
"""Find the min depth of two subtrees of a node. Args: node -- TreeNode min_depth -- ke... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Leet111:
def min_depth(self, root):
"""Find the minimum depth of a tree. Args: root -- TreeNode. Returns: Minimum depth of a tree."""
if not root:
return 0
return self.subroutine(root, 0)
def subroutine(self, node, depth):
"""Find the min depth of two subtrees ... | the_stack_v2_python_sparse | archive/algorithms-leetcode/leet111.py | riehseun/software-engineering | train | 0 | |
dc1ec111b09788ebc052c9a047f0a2923d43c4b7 | [
"if not root:\n return root\nroot.left, root.right = (self.mirrorTree(root.right), self.mirrorTree(root.left))\nreturn root",
"if not root:\n return root\nstack = [root]\nwhile stack:\n node = stack.pop()\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.r... | <|body_start_0|>
if not root:
return root
root.left, root.right = (self.mirrorTree(root.right), self.mirrorTree(root.left))
return root
<|end_body_0|>
<|body_start_1|>
if not root:
return root
stack = [root]
while stack:
node = stack.p... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
"""递归 时间复杂度:O(n) 空间复杂度:O(n) 最差的情况下,二叉树为链表结构,需要暂存左节点,而Python可以平行赋值,可省略"""
<|body_0|>
def mirrorTree_2(self, root: TreeNode) -> TreeNode:
"""非递归,使用辅助栈 时间复杂度:O(n) 空间复杂度:O(n) 最差的情况下,二叉树为链表结构,需要存一半的节点"""
... | stack_v2_sparse_classes_75kplus_train_009288 | 1,363 | no_license | [
{
"docstring": "递归 时间复杂度:O(n) 空间复杂度:O(n) 最差的情况下,二叉树为链表结构,需要暂存左节点,而Python可以平行赋值,可省略",
"name": "mirrorTree",
"signature": "def mirrorTree(self, root: TreeNode) -> TreeNode"
},
{
"docstring": "非递归,使用辅助栈 时间复杂度:O(n) 空间复杂度:O(n) 最差的情况下,二叉树为链表结构,需要存一半的节点",
"name": "mirrorTree_2",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_013820 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mirrorTree(self, root: TreeNode) -> TreeNode: 递归 时间复杂度:O(n) 空间复杂度:O(n) 最差的情况下,二叉树为链表结构,需要暂存左节点,而Python可以平行赋值,可省略
- def mirrorTree_2(self, root: TreeNode) -> TreeNode: 非递归,使用辅... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mirrorTree(self, root: TreeNode) -> TreeNode: 递归 时间复杂度:O(n) 空间复杂度:O(n) 最差的情况下,二叉树为链表结构,需要暂存左节点,而Python可以平行赋值,可省略
- def mirrorTree_2(self, root: TreeNode) -> TreeNode: 非递归,使用辅... | c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0 | <|skeleton|>
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
"""递归 时间复杂度:O(n) 空间复杂度:O(n) 最差的情况下,二叉树为链表结构,需要暂存左节点,而Python可以平行赋值,可省略"""
<|body_0|>
def mirrorTree_2(self, root: TreeNode) -> TreeNode:
"""非递归,使用辅助栈 时间复杂度:O(n) 空间复杂度:O(n) 最差的情况下,二叉树为链表结构,需要存一半的节点"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
"""递归 时间复杂度:O(n) 空间复杂度:O(n) 最差的情况下,二叉树为链表结构,需要暂存左节点,而Python可以平行赋值,可省略"""
if not root:
return root
root.left, root.right = (self.mirrorTree(root.right), self.mirrorTree(root.left))
return root
def mirro... | the_stack_v2_python_sparse | SwordOffer/SwordOffer_27.py | EachenKuang/LeetCode | train | 28 | |
fb03b8f9596d80fc944313d6d5bd695032b4dfa2 | [
"self.file_type = file_type\nself.full_path = full_path\nself.size_bytes = size_bytes",
"if dictionary is None:\n return None\nfile_type = dictionary.get('fileType')\nfull_path = dictionary.get('fullPath')\nsize_bytes = dictionary.get('sizeBytes')\nreturn cls(file_type, full_path, size_bytes)"
] | <|body_start_0|>
self.file_type = file_type
self.full_path = full_path
self.size_bytes = size_bytes
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
file_type = dictionary.get('fileType')
full_path = dictionary.get('fullPath')
size_b... | Implementation of the 'DbFileInfo' model. Specifies information about a database file. Attributes: file_type (FileTypeEnum): Specifies the format type of the file that SQL database stores the data. Specifies the format type of the file that SQL database stores the data. 'kRows' refers to a data file 'kLog' refers to a ... | DbFileInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DbFileInfo:
"""Implementation of the 'DbFileInfo' model. Specifies information about a database file. Attributes: file_type (FileTypeEnum): Specifies the format type of the file that SQL database stores the data. Specifies the format type of the file that SQL database stores the data. 'kRows' ref... | stack_v2_sparse_classes_75kplus_train_009289 | 2,285 | permissive | [
{
"docstring": "Constructor for the DbFileInfo class",
"name": "__init__",
"signature": "def __init__(self, file_type=None, full_path=None, size_bytes=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the o... | 2 | stack_v2_sparse_classes_30k_train_006087 | Implement the Python class `DbFileInfo` described below.
Class description:
Implementation of the 'DbFileInfo' model. Specifies information about a database file. Attributes: file_type (FileTypeEnum): Specifies the format type of the file that SQL database stores the data. Specifies the format type of the file that SQ... | Implement the Python class `DbFileInfo` described below.
Class description:
Implementation of the 'DbFileInfo' model. Specifies information about a database file. Attributes: file_type (FileTypeEnum): Specifies the format type of the file that SQL database stores the data. Specifies the format type of the file that SQ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class DbFileInfo:
"""Implementation of the 'DbFileInfo' model. Specifies information about a database file. Attributes: file_type (FileTypeEnum): Specifies the format type of the file that SQL database stores the data. Specifies the format type of the file that SQL database stores the data. 'kRows' ref... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DbFileInfo:
"""Implementation of the 'DbFileInfo' model. Specifies information about a database file. Attributes: file_type (FileTypeEnum): Specifies the format type of the file that SQL database stores the data. Specifies the format type of the file that SQL database stores the data. 'kRows' refers to a data... | the_stack_v2_python_sparse | cohesity_management_sdk/models/db_file_info.py | cohesity/management-sdk-python | train | 24 |
2f05dac46521ddd2d451a3e239a7f492db4201be | [
"if not root:\n return '[]'\nresult, de = ([], deque())\nde.append(root)\nwhile de:\n node = de.popleft()\n if node:\n result.append(str(node.val))\n de.append(node.left)\n de.append(node.right)\n else:\n result.append('null')\nreturn '[' + ','.join(result) + ']'",
"if data... | <|body_start_0|>
if not root:
return '[]'
result, de = ([], deque())
de.append(root)
while de:
node = de.popleft()
if node:
result.append(str(node.val))
de.append(node.left)
de.append(node.right)
... | Codec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_009290 | 2,157 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | b0ed7a36f47b66c04b908eb67f2146843a9c71a3 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '[]'
result, de = ([], deque())
de.append(root)
while de:
node = de.popleft()
if node:
res... | the_stack_v2_python_sparse | Codes/gracekoo/interview_61.py | asdf2014/algorithm | train | 270 | |
ff97b4f78d97d2ef13d21f60b8704045c1f5755c | [
"comment_query = self.sess.query(Comment).get(comment_id)\nif not comment_query:\n self.send_error(status_code=404, message='Not Found')\nresponse = {'id': comment_query.id, 'content': comment_query.content, 'problem_id': comment_query.problem_id, 'user_id': comment_query.user_id, 'created_date': iso_datetime(co... | <|body_start_0|>
comment_query = self.sess.query(Comment).get(comment_id)
if not comment_query:
self.send_error(status_code=404, message='Not Found')
response = {'id': comment_query.id, 'content': comment_query.content, 'problem_id': comment_query.problem_id, 'user_id': comment_query... | CommentHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentHandler:
def get(self, comment_id):
"""Returns comment by its id. Answer format: .. code-block: json { "modified_date": "2015-06-25T22:30:49.000Z", "modified_user_id": 1, "user_id": 2, "problem_id": 1, "content": "comment_0_content", "created_date": "2015-06-25T22:30:49.000Z", "id... | stack_v2_sparse_classes_75kplus_train_009291 | 4,646 | no_license | [
{
"docstring": "Returns comment by its id. Answer format: .. code-block: json { \"modified_date\": \"2015-06-25T22:30:49.000Z\", \"modified_user_id\": 1, \"user_id\": 2, \"problem_id\": 1, \"content\": \"comment_0_content\", \"created_date\": \"2015-06-25T22:30:49.000Z\", \"id\": 1 }",
"name": "get",
"s... | 3 | stack_v2_sparse_classes_30k_train_022013 | Implement the Python class `CommentHandler` described below.
Class description:
Implement the CommentHandler class.
Method signatures and docstrings:
- def get(self, comment_id): Returns comment by its id. Answer format: .. code-block: json { "modified_date": "2015-06-25T22:30:49.000Z", "modified_user_id": 1, "user_i... | Implement the Python class `CommentHandler` described below.
Class description:
Implement the CommentHandler class.
Method signatures and docstrings:
- def get(self, comment_id): Returns comment by its id. Answer format: .. code-block: json { "modified_date": "2015-06-25T22:30:49.000Z", "modified_user_id": 1, "user_i... | e911ce6bcaa73e15248586d40c95beeb1a05da47 | <|skeleton|>
class CommentHandler:
def get(self, comment_id):
"""Returns comment by its id. Answer format: .. code-block: json { "modified_date": "2015-06-25T22:30:49.000Z", "modified_user_id": 1, "user_id": 2, "problem_id": 1, "content": "comment_0_content", "created_date": "2015-06-25T22:30:49.000Z", "id... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommentHandler:
def get(self, comment_id):
"""Returns comment by its id. Answer format: .. code-block: json { "modified_date": "2015-06-25T22:30:49.000Z", "modified_user_id": 1, "user_id": 2, "problem_id": 1, "content": "comment_0_content", "created_date": "2015-06-25T22:30:49.000Z", "id": 1 }"""
... | the_stack_v2_python_sparse | ecomap/api/v1_0/handlers/comments.py | ITsvetkoFF/Kv-008 | train | 3 | |
8880157ee9fb7ee6556d28e23c128b8f8c09f201 | [
"assert reduction in ('none', 'mean', 'sum'), reduction\nsuper().__init__()\nself.temperature = temperature\nself.use_double_scores = use_double_scores\nself.reduction = reduction",
"nbest = k2.Nbest.from_lattice(lattice=lattice, num_paths=num_paths, use_double_scores=self.use_double_scores, nbest_scale=nbest_sca... | <|body_start_0|>
assert reduction in ('none', 'mean', 'sum'), reduction
super().__init__()
self.temperature = temperature
self.use_double_scores = use_double_scores
self.reduction = reduction
<|end_body_0|>
<|body_start_1|>
nbest = k2.Nbest.from_lattice(lattice=lattice, ... | Minimum Word Error Rate Loss compuration in k2. See equation 2 of https://arxiv.org/pdf/2106.02302.pdf about its definition. | MWERLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MWERLoss:
"""Minimum Word Error Rate Loss compuration in k2. See equation 2 of https://arxiv.org/pdf/2106.02302.pdf about its definition."""
def __init__(self, temperature: float=1.0, use_double_scores: bool=True, reduction: Literal['none', 'mean', 'sum']='sum'):
"""Args: temperature... | stack_v2_sparse_classes_75kplus_train_009292 | 7,465 | permissive | [
{
"docstring": "Args: temperature: For long utterances, the dynamic range of scores will be too large and the posteriors will be mostly 0 or 1. To prevent this it might be a good idea to have an extra argument that functions like a temperature. We scale the logprobs by before doing the normalization. use_double... | 2 | stack_v2_sparse_classes_30k_train_003687 | Implement the Python class `MWERLoss` described below.
Class description:
Minimum Word Error Rate Loss compuration in k2. See equation 2 of https://arxiv.org/pdf/2106.02302.pdf about its definition.
Method signatures and docstrings:
- def __init__(self, temperature: float=1.0, use_double_scores: bool=True, reduction:... | Implement the Python class `MWERLoss` described below.
Class description:
Minimum Word Error Rate Loss compuration in k2. See equation 2 of https://arxiv.org/pdf/2106.02302.pdf about its definition.
Method signatures and docstrings:
- def __init__(self, temperature: float=1.0, use_double_scores: bool=True, reduction:... | 2b2ac14b326d61d79d04e53fbd69b1ff6d630411 | <|skeleton|>
class MWERLoss:
"""Minimum Word Error Rate Loss compuration in k2. See equation 2 of https://arxiv.org/pdf/2106.02302.pdf about its definition."""
def __init__(self, temperature: float=1.0, use_double_scores: bool=True, reduction: Literal['none', 'mean', 'sum']='sum'):
"""Args: temperature... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MWERLoss:
"""Minimum Word Error Rate Loss compuration in k2. See equation 2 of https://arxiv.org/pdf/2106.02302.pdf about its definition."""
def __init__(self, temperature: float=1.0, use_double_scores: bool=True, reduction: Literal['none', 'mean', 'sum']='sum'):
"""Args: temperature: For long ut... | the_stack_v2_python_sparse | k2/python/k2/mwer_loss.py | k2-fsa/k2 | train | 851 |
7faaf211074a3346a71330ef0aaca4226624bf71 | [
"if model._meta.app_label == self.APP:\n return self.DB\nreturn None",
"if model._meta.app_label == self.APP:\n return self.DB\nreturn None",
"if obj1._meta.app_label == self.APP or obj2._meta.app_label == self.APP:\n return True\nreturn None",
"if db == self.DB:\n return model._meta.app_label == ... | <|body_start_0|>
if model._meta.app_label == self.APP:
return self.DB
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == self.APP:
return self.DB
return None
<|end_body_1|>
<|body_start_2|>
if obj1._meta.app_label == self.APP or obj2... | A router to control all database operations on models in the geonames application. | GeoNamesRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeoNamesRouter:
"""A router to control all database operations on models in the geonames application."""
def db_for_read(self, model, **hints):
"""Attempts to read geonames models go to geonames db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempt... | stack_v2_sparse_classes_75kplus_train_009293 | 1,196 | no_license | [
{
"docstring": "Attempts to read geonames models go to geonames db.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write geonames models go to geonames db.",
"name": "db_for_write",
"signature": "def db_for_write(self, model, ... | 4 | stack_v2_sparse_classes_30k_train_052152 | Implement the Python class `GeoNamesRouter` described below.
Class description:
A router to control all database operations on models in the geonames application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read geonames models go to geonames db.
- def db_for_write(self, mod... | Implement the Python class `GeoNamesRouter` described below.
Class description:
A router to control all database operations on models in the geonames application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read geonames models go to geonames db.
- def db_for_write(self, mod... | 681ef09e4044879840f7f0c8bccc836c3cffec3c | <|skeleton|>
class GeoNamesRouter:
"""A router to control all database operations on models in the geonames application."""
def db_for_read(self, model, **hints):
"""Attempts to read geonames models go to geonames db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GeoNamesRouter:
"""A router to control all database operations on models in the geonames application."""
def db_for_read(self, model, **hints):
"""Attempts to read geonames models go to geonames db."""
if model._meta.app_label == self.APP:
return self.DB
return None
... | the_stack_v2_python_sparse | apps/geonames/db_routers.py | RumorIO/healersource | train | 0 |
c14a9c2931a77babbafc7e38cf444e26f0d050ff | [
"self.k = k\nheapq.heapify(nums)\nself.heap = nums\nwhile len(self.heap) > k:\n heapq.heappop(self.heap)",
"if len(self.heap) < self.k:\n heapq.heappush(self.heap, val)\nelse:\n heapq.heappushpop(self.heap, val)\nreturn self.heap[0]"
] | <|body_start_0|>
self.k = k
heapq.heapify(nums)
self.heap = nums
while len(self.heap) > k:
heapq.heappop(self.heap)
<|end_body_0|>
<|body_start_1|>
if len(self.heap) < self.k:
heapq.heappush(self.heap, val)
else:
heapq.heappushpop(self... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
heapq.heapify(nums)
self.heap =... | stack_v2_sparse_classes_75kplus_train_009294 | 3,840 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048710 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 5195b032d8000a3d888e2d4068984011bebd3b84 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
heapq.heapify(nums)
self.heap = nums
while len(self.heap) > k:
heapq.heappop(self.heap)
def add(self, val):
""":type val: int :rtype: int"""
if ... | the_stack_v2_python_sparse | leetcode_python/Heap/kth_largest_element_in_a_stream.py | ChillOrb/CS_basics | train | 1 | |
df88988a47b2ecf8fc7e57e0f507b9bc2d8d86ba | [
"N = len(Profits)\n\ndef dfs(i, k, c):\n if k == 0 or i == N:\n return c\n ret = [dfs(i + 1, k, c)]\n if Capital[i] <= c:\n ret.append(dfs(i + 1, k - 1, c + Profits[i]))\n return max(ret)\nreturn dfs(0, k, W)",
"N = len(Profits)\nmemo = {k: W}\ncp = list(sorted(zip(Capital, Profits)))\nf... | <|body_start_0|>
N = len(Profits)
def dfs(i, k, c):
if k == 0 or i == N:
return c
ret = [dfs(i + 1, k, c)]
if Capital[i] <= c:
ret.append(dfs(i + 1, k - 1, c + Profits[i]))
return max(ret)
return dfs(0, k, W)
<|end_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int:
"""Nov 01, 2020 12:26"""
<|body_0|>
def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int:
"""Nov 01, 2020 13:05"""
... | stack_v2_sparse_classes_75kplus_train_009295 | 12,781 | no_license | [
{
"docstring": "Nov 01, 2020 12:26",
"name": "findMaximizedCapital",
"signature": "def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int"
},
{
"docstring": "Nov 01, 2020 13:05",
"name": "findMaximizedCapital",
"signature": "def findMaximizedCapital... | 4 | stack_v2_sparse_classes_30k_train_012685 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int: Nov 01, 2020 12:26
- def findMaximizedCapital(self, k: int, W: int, Profits: List[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int: Nov 01, 2020 12:26
- def findMaximizedCapital(self, k: int, W: int, Profits: List[i... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int:
"""Nov 01, 2020 12:26"""
<|body_0|>
def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int:
"""Nov 01, 2020 13:05"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int:
"""Nov 01, 2020 12:26"""
N = len(Profits)
def dfs(i, k, c):
if k == 0 or i == N:
return c
ret = [dfs(i + 1, k, c)]
if Capital[i]... | the_stack_v2_python_sparse | leetcode/solved/502_IPO/solution.py | sungminoh/algorithms | train | 0 | |
b46894a0d57f05cbcdfec7886a901b0ad884e63d | [
"LOG.warning('WARNING: Collector mappings are deprecated and will be removed in a future release')\nkwargs['service_id'] = kwargs.get('service') or ''\nauthorized_args = ['collector']\nurl = self.get_url('mappings', kwargs, authorized_args)\nreturn self.api_client.get(url).json()",
"LOG.warning('WARNING: Collecto... | <|body_start_0|>
LOG.warning('WARNING: Collector mappings are deprecated and will be removed in a future release')
kwargs['service_id'] = kwargs.get('service') or ''
authorized_args = ['collector']
url = self.get_url('mappings', kwargs, authorized_args)
return self.api_client.get... | Class used to handle /v1/collector/mappings endpoint | CollectorManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectorManager:
"""Class used to handle /v1/collector/mappings endpoint"""
def get_mapping(self, **kwargs):
"""Returns a service to collector mapping. If the service is not specified, returns a list of mappings for the given collector. :param service: Name of the service to filter ... | stack_v2_sparse_classes_75kplus_train_009296 | 4,374 | permissive | [
{
"docstring": "Returns a service to collector mapping. If the service is not specified, returns a list of mappings for the given collector. :param service: Name of the service to filter on. :type service: str :param collector: Name of the collector to filter on. :type collector: str",
"name": "get_mapping"... | 5 | stack_v2_sparse_classes_30k_val_001034 | Implement the Python class `CollectorManager` described below.
Class description:
Class used to handle /v1/collector/mappings endpoint
Method signatures and docstrings:
- def get_mapping(self, **kwargs): Returns a service to collector mapping. If the service is not specified, returns a list of mappings for the given ... | Implement the Python class `CollectorManager` described below.
Class description:
Class used to handle /v1/collector/mappings endpoint
Method signatures and docstrings:
- def get_mapping(self, **kwargs): Returns a service to collector mapping. If the service is not specified, returns a list of mappings for the given ... | 244f229af7cb95b82118da9a4873806942a895ef | <|skeleton|>
class CollectorManager:
"""Class used to handle /v1/collector/mappings endpoint"""
def get_mapping(self, **kwargs):
"""Returns a service to collector mapping. If the service is not specified, returns a list of mappings for the given collector. :param service: Name of the service to filter ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CollectorManager:
"""Class used to handle /v1/collector/mappings endpoint"""
def get_mapping(self, **kwargs):
"""Returns a service to collector mapping. If the service is not specified, returns a list of mappings for the given collector. :param service: Name of the service to filter on. :type ser... | the_stack_v2_python_sparse | cloudkittyclient/v1/collector.py | openstack/python-cloudkittyclient | train | 19 |
0b9cf3ee3faeb966bf88139dfcb45369ea3755f6 | [
"self.score = 0\nself.cards = []\nself.ac_used = False\nself.ad_used = False\nself.ah_used = False\nself.as_used = False",
"self.cards.append(card)\nif card.value in ['2', '3', '4', '5', '6', '7', '8', '9', '10']:\n self.score += int(card.value)\nif card.value in ['JACK', 'QUEEN', 'KING']:\n self.score += 1... | <|body_start_0|>
self.score = 0
self.cards = []
self.ac_used = False
self.ad_used = False
self.ah_used = False
self.as_used = False
<|end_body_0|>
<|body_start_1|>
self.cards.append(card)
if card.value in ['2', '3', '4', '5', '6', '7', '8', '9', '10']:
... | Simple class for holding hand information. | Hand | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hand:
"""Simple class for holding hand information."""
def __init__(self):
"""Create hand."""
<|body_0|>
def add_card(self, card: Card):
"""Add new card."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.score = 0
self.cards = []
... | stack_v2_sparse_classes_75kplus_train_009297 | 6,805 | no_license | [
{
"docstring": "Create hand.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add new card.",
"name": "add_card",
"signature": "def add_card(self, card: Card)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036246 | Implement the Python class `Hand` described below.
Class description:
Simple class for holding hand information.
Method signatures and docstrings:
- def __init__(self): Create hand.
- def add_card(self, card: Card): Add new card. | Implement the Python class `Hand` described below.
Class description:
Simple class for holding hand information.
Method signatures and docstrings:
- def __init__(self): Create hand.
- def add_card(self, card: Card): Add new card.
<|skeleton|>
class Hand:
"""Simple class for holding hand information."""
def ... | fff3109b23706f4b5550b531254dacf36f9e6ccb | <|skeleton|>
class Hand:
"""Simple class for holding hand information."""
def __init__(self):
"""Create hand."""
<|body_0|>
def add_card(self, card: Card):
"""Add new card."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Hand:
"""Simple class for holding hand information."""
def __init__(self):
"""Create hand."""
self.score = 0
self.cards = []
self.ac_used = False
self.ad_used = False
self.ah_used = False
self.as_used = False
def add_card(self, card: Card):
... | the_stack_v2_python_sparse | ex13_blackjack/blackjack.py | raitk3/Python | train | 0 |
2915fbe2b10d0d82ab5fc45293ef290bcbf680b9 | [
"print(f'Executing request {self.request}')\ninputSpec = self.request.get('input', [])\ndset: xa.Dataset = xa.open_dataset(inputSpec['uri'])\nvid = inputSpec['name']\nvariable: xa.DataArray = dset.data_vars[vid]\nresult_arrays = self.operate(vid, variable)\nresultDataset = xa.Dataset(result_arrays, dset.coords, dse... | <|body_start_0|>
print(f'Executing request {self.request}')
inputSpec = self.request.get('input', [])
dset: xa.Dataset = xa.open_dataset(inputSpec['uri'])
vid = inputSpec['name']
variable: xa.DataArray = dset.data_vars[vid]
result_arrays = self.operate(vid, variable)
... | This class is used to implement a single operation. | XaOpsExecutable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XaOpsExecutable:
"""This class is used to implement a single operation."""
def execute(self, **kwargs) -> TaskResult:
"""Executes the operation. Creates an Executable for each analytics operation The operation request is available as self.request. The operation inputs are available a... | stack_v2_sparse_classes_75kplus_train_009298 | 3,991 | no_license | [
{
"docstring": "Executes the operation. Creates an Executable for each analytics operation The operation request is available as self.request. The operation inputs are available as self.inputs. Returns: TaskResult: The result of the operation.",
"name": "execute",
"signature": "def execute(self, **kwarg... | 2 | stack_v2_sparse_classes_30k_train_024677 | Implement the Python class `XaOpsExecutable` described below.
Class description:
This class is used to implement a single operation.
Method signatures and docstrings:
- def execute(self, **kwargs) -> TaskResult: Executes the operation. Creates an Executable for each analytics operation The operation request is availa... | Implement the Python class `XaOpsExecutable` described below.
Class description:
This class is used to implement a single operation.
Method signatures and docstrings:
- def execute(self, **kwargs) -> TaskResult: Executes the operation. Creates an Executable for each analytics operation The operation request is availa... | 021629b7f6afe34b5d229e4cdbfef220319c5954 | <|skeleton|>
class XaOpsExecutable:
"""This class is used to implement a single operation."""
def execute(self, **kwargs) -> TaskResult:
"""Executes the operation. Creates an Executable for each analytics operation The operation request is available as self.request. The operation inputs are available a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XaOpsExecutable:
"""This class is used to implement a single operation."""
def execute(self, **kwargs) -> TaskResult:
"""Executes the operation. Creates an Executable for each analytics operation The operation request is available as self.request. The operation inputs are available as self.inputs... | the_stack_v2_python_sparse | pc2/handlers/module/samples/xarrayOps/endpoint.py | nasa-nccs-cds/pc2 | train | 0 |
744b85f377a0d84048fbf5c614a594194706623f | [
"processed = 0\nfor net in queryset:\n net.AddDomains(1)\n processed += 1\nself.message_user(request, '%s added.' % GetMessageBit(processed))",
"processed = 0\nfor net in queryset:\n net.AddDomains()\n processed += 1\nself.message_user(request, '%s processed.' % GetMessageBit(processed))",
"processe... | <|body_start_0|>
processed = 0
for net in queryset:
net.AddDomains(1)
processed += 1
self.message_user(request, '%s added.' % GetMessageBit(processed))
<|end_body_0|>
<|body_start_1|>
processed = 0
for net in queryset:
net.AddDomains()
... | NetAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetAdmin:
def AddDomains(self, request, queryset):
"""Добавляем в сеть один домен"""
<|body_0|>
def AddDomainsAll(self, request, queryset):
"""Добавляем в сеть один домен"""
<|body_1|>
def GenerateDoorways(self, request, queryset):
"""Генерируем ... | stack_v2_sparse_classes_75kplus_train_009299 | 29,849 | no_license | [
{
"docstring": "Добавляем в сеть один домен",
"name": "AddDomains",
"signature": "def AddDomains(self, request, queryset)"
},
{
"docstring": "Добавляем в сеть один домен",
"name": "AddDomainsAll",
"signature": "def AddDomainsAll(self, request, queryset)"
},
{
"docstring": "Генери... | 6 | stack_v2_sparse_classes_30k_train_019292 | Implement the Python class `NetAdmin` described below.
Class description:
Implement the NetAdmin class.
Method signatures and docstrings:
- def AddDomains(self, request, queryset): Добавляем в сеть один домен
- def AddDomainsAll(self, request, queryset): Добавляем в сеть один домен
- def GenerateDoorways(self, reques... | Implement the Python class `NetAdmin` described below.
Class description:
Implement the NetAdmin class.
Method signatures and docstrings:
- def AddDomains(self, request, queryset): Добавляем в сеть один домен
- def AddDomainsAll(self, request, queryset): Добавляем в сеть один домен
- def GenerateDoorways(self, reques... | d2771bf04aa187dda6d468883a5a167237589369 | <|skeleton|>
class NetAdmin:
def AddDomains(self, request, queryset):
"""Добавляем в сеть один домен"""
<|body_0|>
def AddDomainsAll(self, request, queryset):
"""Добавляем в сеть один домен"""
<|body_1|>
def GenerateDoorways(self, request, queryset):
"""Генерируем ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NetAdmin:
def AddDomains(self, request, queryset):
"""Добавляем в сеть один домен"""
processed = 0
for net in queryset:
net.AddDomains(1)
processed += 1
self.message_user(request, '%s added.' % GetMessageBit(processed))
def AddDomainsAll(self, reque... | the_stack_v2_python_sparse | doorsadmin/admin.py | cash2one/doorscenter | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.