blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
91f0b1ad868614320f65d62713e4db67ec6b3fda | [
"self.defect = defect\ntry:\n bv = BVAnalyzer()\n struct_valences = bv.get_valences(self.defect.bulk_structure)\n site_index = self.defect.bulk_structure.get_sites_in_sphere(self.defect.site.coords, 0.1, include_index=True)[0][2]\n def_site_valence = struct_valences[site_index]\nexcept Exception:\n d... | <|body_start_0|>
self.defect = defect
try:
bv = BVAnalyzer()
struct_valences = bv.get_valences(self.defect.bulk_structure)
site_index = self.defect.bulk_structure.get_sites_in_sphere(self.defect.site.coords, 0.1, include_index=True)[0][2]
def_site_valence ... | Does an extremely simple/limited charge generation scheme (only one charge generated) for vacancies: use bond valence method to assign oxidation states and consider negative of the vacant site's oxidation state as single charge to try for antisites and subs: use bond valence method to assign oxidation states and consid... | SimpleChargeGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleChargeGenerator:
"""Does an extremely simple/limited charge generation scheme (only one charge generated) for vacancies: use bond valence method to assign oxidation states and consider negative of the vacant site's oxidation state as single charge to try for antisites and subs: use bond val... | stack_v2_sparse_classes_36k_train_030100 | 10,935 | permissive | [
{
"docstring": "Args: defect(Defect): pymatgen Defect object",
"name": "__init__",
"signature": "def __init__(self, defect)"
},
{
"docstring": "Returns the next defect type with the correct charge appended raises StopIteration",
"name": "__next__",
"signature": "def __next__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018987 | Implement the Python class `SimpleChargeGenerator` described below.
Class description:
Does an extremely simple/limited charge generation scheme (only one charge generated) for vacancies: use bond valence method to assign oxidation states and consider negative of the vacant site's oxidation state as single charge to t... | Implement the Python class `SimpleChargeGenerator` described below.
Class description:
Does an extremely simple/limited charge generation scheme (only one charge generated) for vacancies: use bond valence method to assign oxidation states and consider negative of the vacant site's oxidation state as single charge to t... | 62ecae1c7382a41861e3a5d9b9c8dd1207472409 | <|skeleton|>
class SimpleChargeGenerator:
"""Does an extremely simple/limited charge generation scheme (only one charge generated) for vacancies: use bond valence method to assign oxidation states and consider negative of the vacant site's oxidation state as single charge to try for antisites and subs: use bond val... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleChargeGenerator:
"""Does an extremely simple/limited charge generation scheme (only one charge generated) for vacancies: use bond valence method to assign oxidation states and consider negative of the vacant site's oxidation state as single charge to try for antisites and subs: use bond valence method t... | the_stack_v2_python_sparse | pymatgen/analysis/defects/generators.py | montoyjh/pymatgen | train | 2 |
ad72a87f07082451f004ec6c9896b74118c61712 | [
"super().__init__(*args, **kwargs)\nself.buyable_items = db.DBSession.query(db.Item).join(db.ItemCategory).filter(db.Item.price.isnot(None)).order_by(db.ItemCategory.order, db.Item.order, db.Item.name).all()\nself.item.choices = [(item.identifier, '+') for item in self.buyable_items]",
"items = zip(self.buyable_i... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.buyable_items = db.DBSession.query(db.Item).join(db.ItemCategory).filter(db.Item.price.isnot(None)).order_by(db.ItemCategory.order, db.Item.order, db.Item.name).all()
self.item.choices = [(item.identifier, '+') for item in self.buyable_item... | A form for choosing an item to add to the cart. | BuyItemsForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuyItemsForm:
"""A form for choosing an item to add to the cart."""
def __init__(self, *args, **kwargs):
"""Do usual form setup, then query all the buyable items, keep the results, and set item choices."""
<|body_0|>
def categorized_items(self):
"""Return items w... | stack_v2_sparse_classes_36k_train_030101 | 15,939 | no_license | [
{
"docstring": "Do usual form setup, then query all the buyable items, keep the results, and set item choices.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Return items with their buttons, grouped by category.",
"name": "categorized_items",
... | 2 | stack_v2_sparse_classes_30k_train_014229 | Implement the Python class `BuyItemsForm` described below.
Class description:
A form for choosing an item to add to the cart.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Do usual form setup, then query all the buyable items, keep the results, and set item choices.
- def categorized_items(... | Implement the Python class `BuyItemsForm` described below.
Class description:
A form for choosing an item to add to the cart.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Do usual form setup, then query all the buyable items, keep the results, and set item choices.
- def categorized_items(... | 872c0b21ed8d45a4c88d51969d3531b8b7913e71 | <|skeleton|>
class BuyItemsForm:
"""A form for choosing an item to add to the cart."""
def __init__(self, *args, **kwargs):
"""Do usual form setup, then query all the buyable items, keep the results, and set item choices."""
<|body_0|>
def categorized_items(self):
"""Return items w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BuyItemsForm:
"""A form for choosing an item to add to the cart."""
def __init__(self, *args, **kwargs):
"""Do usual form setup, then query all the buyable items, keep the results, and set item choices."""
super().__init__(*args, **kwargs)
self.buyable_items = db.DBSession.query(d... | the_stack_v2_python_sparse | asb/views/item.py | CatTrinket/tcod-asb | train | 1 |
ba2bd529d3e4425256781d82a3c8411239bfcb69 | [
"self.screen_l = 1200\nself.screen_w = 800\nself.bg_color = (255, 255, 255)\nself.bullet_w = 3\nself.bullet_h = 14\nself.bullet_color = (30, 60, 30)\nself.bullets_max = 10\nself.drop_speed = 10\nself.max_lives = 2\nself.speed_increase = 1.1\nself.init_dynamic_settings()\nself.score_scale = 1.5",
"self.ship_speed ... | <|body_start_0|>
self.screen_l = 1200
self.screen_w = 800
self.bg_color = (255, 255, 255)
self.bullet_w = 3
self.bullet_h = 14
self.bullet_color = (30, 60, 30)
self.bullets_max = 10
self.drop_speed = 10
self.max_lives = 2
self.speed_increas... | Stores Alien Invasion settings | Settings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""Stores Alien Invasion settings"""
def __init__(self):
"""Initializes game settings"""
<|body_0|>
def init_dynamic_settings(self):
"""Initializes dynamic settings"""
<|body_1|>
def increase_speed(self):
"""Increases speed of game ... | stack_v2_sparse_classes_36k_train_030102 | 975 | no_license | [
{
"docstring": "Initializes game settings",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Initializes dynamic settings",
"name": "init_dynamic_settings",
"signature": "def init_dynamic_settings(self)"
},
{
"docstring": "Increases speed of game per level... | 3 | stack_v2_sparse_classes_30k_train_010724 | Implement the Python class `Settings` described below.
Class description:
Stores Alien Invasion settings
Method signatures and docstrings:
- def __init__(self): Initializes game settings
- def init_dynamic_settings(self): Initializes dynamic settings
- def increase_speed(self): Increases speed of game per level | Implement the Python class `Settings` described below.
Class description:
Stores Alien Invasion settings
Method signatures and docstrings:
- def __init__(self): Initializes game settings
- def init_dynamic_settings(self): Initializes dynamic settings
- def increase_speed(self): Increases speed of game per level
<|sk... | e36fed32771509fd4ce1baec2f7fec9999fcfdf3 | <|skeleton|>
class Settings:
"""Stores Alien Invasion settings"""
def __init__(self):
"""Initializes game settings"""
<|body_0|>
def init_dynamic_settings(self):
"""Initializes dynamic settings"""
<|body_1|>
def increase_speed(self):
"""Increases speed of game ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Settings:
"""Stores Alien Invasion settings"""
def __init__(self):
"""Initializes game settings"""
self.screen_l = 1200
self.screen_w = 800
self.bg_color = (255, 255, 255)
self.bullet_w = 3
self.bullet_h = 14
self.bullet_color = (30, 60, 30)
... | the_stack_v2_python_sparse | settings.py | AlexLinGit/Space-Invaders | train | 0 |
f80f2dfe0c9fe305c4cbe9075e027b947422f23a | [
"if not root:\n return []\nqueue = deque([root])\nresult = []\nwhile queue:\n curr = queue.popleft()\n result.append(curr.val) if curr else result.append(curr)\n if not curr:\n continue\n queue.append(curr.left)\n queue.append(curr.right)\nreturn result",
"if not data:\n return None\ni... | <|body_start_0|>
if not root:
return []
queue = deque([root])
result = []
while queue:
curr = queue.popleft()
result.append(curr.val) if curr else result.append(curr)
if not curr:
continue
queue.append(curr.left)... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_030103 | 1,591 | 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 | stack_v2_sparse_classes_30k_train_008120 | 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:... | 8d120162657a1e29c3e821b51ac4121300fc7a12 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
queue = deque([root])
result = []
while queue:
curr = queue.popleft()
result.append(curr.val) if curr e... | the_stack_v2_python_sparse | LeetCode/Tree/297. Serialize and Deserialize Binary Tree.py | thehanemperor/LeetCode | train | 0 | |
249d32ca9d5fc5effb78d57324bfb8dafa3b0883 | [
"if isinstance(obj, str):\n Validator.__validate_encoded_gfa_field(obj, datatype, fieldname)\nelse:\n Validator.__validate_decoded_gfa_field(obj, datatype, fieldname)",
"if isinstance(obj, gfapy.FieldArray):\n return obj._validate_gfa_field(datatype, fieldname=fieldname)\nmod = gfapy.Field.FIELD_MODULE.g... | <|body_start_0|>
if isinstance(obj, str):
Validator.__validate_encoded_gfa_field(obj, datatype, fieldname)
else:
Validator.__validate_decoded_gfa_field(obj, datatype, fieldname)
<|end_body_0|>
<|body_start_1|>
if isinstance(obj, gfapy.FieldArray):
return obj.... | Validator | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Validator:
def _validate_gfa_field(obj, datatype, fieldname=None):
"""Validate the content of a field of a Line instance. Parameters: obj: the value to be validated. It can be either a string (in which case the encoded validation method is used) or any other kind of Python object (in whi... | stack_v2_sparse_classes_36k_train_030104 | 3,428 | permissive | [
{
"docstring": "Validate the content of a field of a Line instance. Parameters: obj: the value to be validated. It can be either a string (in which case the encoded validation method is used) or any other kind of Python object (in which case the decoded validation method is used). datatype (str) : the name of t... | 3 | stack_v2_sparse_classes_30k_train_008082 | Implement the Python class `Validator` described below.
Class description:
Implement the Validator class.
Method signatures and docstrings:
- def _validate_gfa_field(obj, datatype, fieldname=None): Validate the content of a field of a Line instance. Parameters: obj: the value to be validated. It can be either a strin... | Implement the Python class `Validator` described below.
Class description:
Implement the Validator class.
Method signatures and docstrings:
- def _validate_gfa_field(obj, datatype, fieldname=None): Validate the content of a field of a Line instance. Parameters: obj: the value to be validated. It can be either a strin... | 12b31daac26ab137b6ee4a29b4f14554ba962dcb | <|skeleton|>
class Validator:
def _validate_gfa_field(obj, datatype, fieldname=None):
"""Validate the content of a field of a Line instance. Parameters: obj: the value to be validated. It can be either a string (in which case the encoded validation method is used) or any other kind of Python object (in whi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Validator:
def _validate_gfa_field(obj, datatype, fieldname=None):
"""Validate the content of a field of a Line instance. Parameters: obj: the value to be validated. It can be either a string (in which case the encoded validation method is used) or any other kind of Python object (in which case the de... | the_stack_v2_python_sparse | gfapy/field/validator.py | ggonnella/gfapy | train | 63 | |
576e29ce512c06803f4c1e80f68da8ee0d44ddf7 | [
"if obj.location:\n return round(obj.location.y, 7)\nelse:\n return None",
"if obj.location:\n return round(obj.location.x, 7)\nelse:\n return None",
"result = super(GeneralInformationSerializer, self).to_representation(instance)\nresult.update(self.quantity('ground_surface_elevation', instance.grou... | <|body_start_0|>
if obj.location:
return round(obj.location.y, 7)
else:
return None
<|end_body_0|>
<|body_start_1|>
if obj.location:
return round(obj.location.x, 7)
else:
return None
<|end_body_1|>
<|body_start_2|>
result = super(... | GeneralInformationSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneralInformationSerializer:
def get_latitude(self, obj):
"""Return latitude of well :param obj: :type obj: Well"""
<|body_0|>
def get_longitude(self, obj):
"""Return longitude of well :param obj: :type obj: Well"""
<|body_1|>
def to_representation(self... | stack_v2_sparse_classes_36k_train_030105 | 4,719 | no_license | [
{
"docstring": "Return latitude of well :param obj: :type obj: Well",
"name": "get_latitude",
"signature": "def get_latitude(self, obj)"
},
{
"docstring": "Return longitude of well :param obj: :type obj: Well",
"name": "get_longitude",
"signature": "def get_longitude(self, obj)"
},
{... | 3 | null | Implement the Python class `GeneralInformationSerializer` described below.
Class description:
Implement the GeneralInformationSerializer class.
Method signatures and docstrings:
- def get_latitude(self, obj): Return latitude of well :param obj: :type obj: Well
- def get_longitude(self, obj): Return longitude of well ... | Implement the Python class `GeneralInformationSerializer` described below.
Class description:
Implement the GeneralInformationSerializer class.
Method signatures and docstrings:
- def get_latitude(self, obj): Return latitude of well :param obj: :type obj: Well
- def get_longitude(self, obj): Return longitude of well ... | fc036f9f8346dee2d40287d08375a6c2af0a1a12 | <|skeleton|>
class GeneralInformationSerializer:
def get_latitude(self, obj):
"""Return latitude of well :param obj: :type obj: Well"""
<|body_0|>
def get_longitude(self, obj):
"""Return longitude of well :param obj: :type obj: Well"""
<|body_1|>
def to_representation(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneralInformationSerializer:
def get_latitude(self, obj):
"""Return latitude of well :param obj: :type obj: Well"""
if obj.location:
return round(obj.location.y, 7)
else:
return None
def get_longitude(self, obj):
"""Return longitude of well :param ... | the_stack_v2_python_sparse | serializer/well/well_information.py | Alexia-Water/IGRAC-WellAndMonitoringDatabase | train | 0 | |
e224a152dc85476613c0c8d14cb0e6817bc57bbe | [
"super(PReLU, self).__init__()\nassert isinstance(channel, int) and channel > 0, 'channel should be bigger than 0'\nif isinstance(w, (float, np.float32)):\n tmp = np.empty((channel,), dtype=np.float32)\n tmp.fill(w)\n w = Tensor(tmp, dtype=mstype.float32)\nelif isinstance(w, list):\n if len(w) != channe... | <|body_start_0|>
super(PReLU, self).__init__()
assert isinstance(channel, int) and channel > 0, 'channel should be bigger than 0'
if isinstance(w, (float, np.float32)):
tmp = np.empty((channel,), dtype=np.float32)
tmp.fill(w)
w = Tensor(tmp, dtype=mstype.float... | prelu cell | PReLU | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PReLU:
"""prelu cell"""
def __init__(self, channel=1, w=0.25):
"""Initialize PReLU."""
<|body_0|>
def construct(self, x):
"""construct"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(PReLU, self).__init__()
assert isinstance(channe... | stack_v2_sparse_classes_36k_train_030106 | 7,848 | permissive | [
{
"docstring": "Initialize PReLU.",
"name": "__init__",
"signature": "def __init__(self, channel=1, w=0.25)"
},
{
"docstring": "construct",
"name": "construct",
"signature": "def construct(self, x)"
}
] | 2 | null | Implement the Python class `PReLU` described below.
Class description:
prelu cell
Method signatures and docstrings:
- def __init__(self, channel=1, w=0.25): Initialize PReLU.
- def construct(self, x): construct | Implement the Python class `PReLU` described below.
Class description:
prelu cell
Method signatures and docstrings:
- def __init__(self, channel=1, w=0.25): Initialize PReLU.
- def construct(self, x): construct
<|skeleton|>
class PReLU:
"""prelu cell"""
def __init__(self, channel=1, w=0.25):
"""Init... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class PReLU:
"""prelu cell"""
def __init__(self, channel=1, w=0.25):
"""Initialize PReLU."""
<|body_0|>
def construct(self, x):
"""construct"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PReLU:
"""prelu cell"""
def __init__(self, channel=1, w=0.25):
"""Initialize PReLU."""
super(PReLU, self).__init__()
assert isinstance(channel, int) and channel > 0, 'channel should be bigger than 0'
if isinstance(w, (float, np.float32)):
tmp = np.empty((channe... | the_stack_v2_python_sparse | research/cv/FDA-BNN/src/resnet.py | mindspore-ai/models | train | 301 |
2f581623e699f61794ce8bebce58ac1b5fd32d1b | [
"if not root:\n return ''\nstack, res = ([root], '')\nwhile stack:\n node = stack.pop()\n if node:\n tmp = str(node.val) + '!'\n stack.append(node.right)\n stack.append(node.left)\n else:\n tmp = '#!'\n res += tmp\nreturn res[:-1]",
"if not data:\n return None\nstore ... | <|body_start_0|>
if not root:
return ''
stack, res = ([root], '')
while stack:
node = stack.pop()
if node:
tmp = str(node.val) + '!'
stack.append(node.right)
stack.append(node.left)
else:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_030107 | 2,501 | 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_014028 | 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:... | 507ed2efeff7818ca9cf53a8ee7fb80d3c530d67 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
stack, res = ([root], '')
while stack:
node = stack.pop()
if node:
tmp = str(node.val) + '!'
... | the_stack_v2_python_sparse | Leetcode/Tree/#449-Serialize and Deserialize BST/main.py | qizongjun/Algorithms-1 | train | 0 | |
af1d526de3ecbbb2f75433b126a11d4a22780fb8 | [
"s = []\nret = 0\nfor i, h in enumerate(height):\n while s and h > height[s[-1]]:\n pop_idx = s.pop()\n r = i - 1\n if len(s) == 0:\n break\n l = s[-1] + 1\n dis = r - l + 1\n delt_height = min(h, height[l - 1]) - height[pop_idx]\n ret += delt_height * ... | <|body_start_0|>
s = []
ret = 0
for i, h in enumerate(height):
while s and h > height[s[-1]]:
pop_idx = s.pop()
r = i - 1
if len(s) == 0:
break
l = s[-1] + 1
dis = r - l + 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def trap(self, height: List[int]) -> int:
"""使单调减栈,求出左右第一个大于当前元素的边界,如果存在左右边界, 则填充左右边界中较小的"""
<|body_0|>
def trap_all_2(self, height: List[int]) -> int:
"""穷举,优化max步骤"""
<|body_1|>
def trap_all(self, height: List[int]) -> int:
"""对每个元素,找... | stack_v2_sparse_classes_36k_train_030108 | 1,891 | no_license | [
{
"docstring": "使单调减栈,求出左右第一个大于当前元素的边界,如果存在左右边界, 则填充左右边界中较小的",
"name": "trap",
"signature": "def trap(self, height: List[int]) -> int"
},
{
"docstring": "穷举,优化max步骤",
"name": "trap_all_2",
"signature": "def trap_all_2(self, height: List[int]) -> int"
},
{
"docstring": "对每个元素,找左右最... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height: List[int]) -> int: 使单调减栈,求出左右第一个大于当前元素的边界,如果存在左右边界, 则填充左右边界中较小的
- def trap_all_2(self, height: List[int]) -> int: 穷举,优化max步骤
- def trap_all(self, height: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height: List[int]) -> int: 使单调减栈,求出左右第一个大于当前元素的边界,如果存在左右边界, 则填充左右边界中较小的
- def trap_all_2(self, height: List[int]) -> int: 穷举,优化max步骤
- def trap_all(self, height: L... | e5b680db40de95f8f4b47e9b399942369c2081d9 | <|skeleton|>
class Solution:
def trap(self, height: List[int]) -> int:
"""使单调减栈,求出左右第一个大于当前元素的边界,如果存在左右边界, 则填充左右边界中较小的"""
<|body_0|>
def trap_all_2(self, height: List[int]) -> int:
"""穷举,优化max步骤"""
<|body_1|>
def trap_all(self, height: List[int]) -> int:
"""对每个元素,找... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def trap(self, height: List[int]) -> int:
"""使单调减栈,求出左右第一个大于当前元素的边界,如果存在左右边界, 则填充左右边界中较小的"""
s = []
ret = 0
for i, h in enumerate(height):
while s and h > height[s[-1]]:
pop_idx = s.pop()
r = i - 1
if len(s) ... | the_stack_v2_python_sparse | leetcode/queue_stack/42.py | YutingYao/leetcode-3 | train | 0 | |
223c69b485bcd70616dabd8f692e5139309db714 | [
"k = []\ndic = {}\nfor i in range(len(nums)):\n if nums[i] in dic:\n if nums[i] * 2 == target:\n return [dic[nums[i]], i]\n else:\n dic[nums[i]] = i\n k.append(target - nums[i])\nfor j in range(len(k)):\n if k[j] in dic:\n if k[j] != nums[j]:\n return [j, dic[k... | <|body_start_0|>
k = []
dic = {}
for i in range(len(nums)):
if nums[i] in dic:
if nums[i] * 2 == target:
return [dic[nums[i]], i]
else:
dic[nums[i]] = i
k.append(target - nums[i])
for j in range(len(k... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum0(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_030109 | 917 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum0",
"signature": "def twoSum0(self, nums, target)"
}... | 2 | stack_v2_sparse_classes_30k_train_000475 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum0(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum0(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum0(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
k = []
dic = {}
for i in range(len(nums)):
if nums[i] in dic:
if nums[i] * 2 == target:
return [dic[nums[i]], i]
... | the_stack_v2_python_sparse | PythonCode/src/0001_Two_Sum.py | oneyuan/CodeforFun | train | 0 | |
9997d1e3dd9c17a54158d1f3cb1f224be1a25654 | [
"self.chunkArray = []\nfor i in range(self.chunksHigh):\n pos = []\n for j in range(self.chunksWide):\n pos.append((i, j))\n self.chunkArray.append(chunk_row.Chunk_Row(pos))",
"for c in self.chunkArray:\n if not c.filled:\n height = image.shape[0] / self.chunksHigh\n width = image... | <|body_start_0|>
self.chunkArray = []
for i in range(self.chunksHigh):
pos = []
for j in range(self.chunksWide):
pos.append((i, j))
self.chunkArray.append(chunk_row.Chunk_Row(pos))
<|end_body_0|>
<|body_start_1|>
for c in self.chunkArray:
... | Horizontal mode fills the image with chunk rows and draws from the top to the bottom | Mode_Horizontal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mode_Horizontal:
"""Horizontal mode fills the image with chunk rows and draws from the top to the bottom"""
def _createChunkArray(self):
"""Uses the current state of the class to create a fresh chunk array filled with chunk rows"""
<|body_0|>
def fillNextChunk(self, imag... | stack_v2_sparse_classes_36k_train_030110 | 1,534 | no_license | [
{
"docstring": "Uses the current state of the class to create a fresh chunk array filled with chunk rows",
"name": "_createChunkArray",
"signature": "def _createChunkArray(self)"
},
{
"docstring": "Take the current chunk array and fill a chunk row if it needs to be done Arguments: image - A pica... | 2 | stack_v2_sparse_classes_30k_train_009147 | Implement the Python class `Mode_Horizontal` described below.
Class description:
Horizontal mode fills the image with chunk rows and draws from the top to the bottom
Method signatures and docstrings:
- def _createChunkArray(self): Uses the current state of the class to create a fresh chunk array filled with chunk row... | Implement the Python class `Mode_Horizontal` described below.
Class description:
Horizontal mode fills the image with chunk rows and draws from the top to the bottom
Method signatures and docstrings:
- def _createChunkArray(self): Uses the current state of the class to create a fresh chunk array filled with chunk row... | b87c1d826485695565f7f4ff22fb3b78db4f43d0 | <|skeleton|>
class Mode_Horizontal:
"""Horizontal mode fills the image with chunk rows and draws from the top to the bottom"""
def _createChunkArray(self):
"""Uses the current state of the class to create a fresh chunk array filled with chunk rows"""
<|body_0|>
def fillNextChunk(self, imag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mode_Horizontal:
"""Horizontal mode fills the image with chunk rows and draws from the top to the bottom"""
def _createChunkArray(self):
"""Uses the current state of the class to create a fresh chunk array filled with chunk rows"""
self.chunkArray = []
for i in range(self.chunksHi... | the_stack_v2_python_sparse | Python/mode_horizontal.py | SNAP-SAPIENT/plotting-time-and-space | train | 0 |
c5c2238404de988be843562786c303721e91daba | [
"if not isinstance(objs, list):\n objs = [objs]\nfor item in objs:\n fname = cls._parse_filename(filename=item.name, ext=item.settings['prefix'])\n with open(fname, 'wb') as f:\n pickle.dump({item.name: item}, f)",
"if project is None:\n project = Project()\np = cls._parse_filename(filename)\nw... | <|body_start_0|>
if not isinstance(objs, list):
objs = [objs]
for item in objs:
fname = cls._parse_filename(filename=item.name, ext=item.settings['prefix'])
with open(fname, 'wb') as f:
pickle.dump({item.name: item}, f)
<|end_body_0|>
<|body_start_1|>... | This class contains methods used for saving and loading OpenPNM Workspaces, Projects, and objects as Pickles. Notes ----- The methods in this class use the ``pickle`` module from the standard library. Aside from the security issues, these files can only be loaded by the exact same OpenPNM version used to save them. The... | Pickle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pickle:
"""This class contains methods used for saving and loading OpenPNM Workspaces, Projects, and objects as Pickles. Notes ----- The methods in this class use the ``pickle`` module from the standard library. Aside from the security issues, these files can only be loaded by the exact same Open... | stack_v2_sparse_classes_36k_train_030111 | 7,584 | permissive | [
{
"docstring": "Saves an OpenPNM object or list of objects to a file of set of files Parameters ---------- objs : Base or list of objects The object(s) to be saved",
"name": "save_object_to_file",
"signature": "def save_object_to_file(cls, objs)"
},
{
"docstring": "Loads an OpenPNM object from a... | 6 | stack_v2_sparse_classes_30k_train_015163 | Implement the Python class `Pickle` described below.
Class description:
This class contains methods used for saving and loading OpenPNM Workspaces, Projects, and objects as Pickles. Notes ----- The methods in this class use the ``pickle`` module from the standard library. Aside from the security issues, these files ca... | Implement the Python class `Pickle` described below.
Class description:
This class contains methods used for saving and loading OpenPNM Workspaces, Projects, and objects as Pickles. Notes ----- The methods in this class use the ``pickle`` module from the standard library. Aside from the security issues, these files ca... | 5ddd7f7317dd9c6d82e6db5256ec1800dd6eef5d | <|skeleton|>
class Pickle:
"""This class contains methods used for saving and loading OpenPNM Workspaces, Projects, and objects as Pickles. Notes ----- The methods in this class use the ``pickle`` module from the standard library. Aside from the security issues, these files can only be loaded by the exact same Open... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pickle:
"""This class contains methods used for saving and loading OpenPNM Workspaces, Projects, and objects as Pickles. Notes ----- The methods in this class use the ``pickle`` module from the standard library. Aside from the security issues, these files can only be loaded by the exact same OpenPNM version u... | the_stack_v2_python_sparse | openpnm/io/_pickle.py | ma-sadeghi/OpenPNM | train | 1 |
48952d62128d5d3a356559c9652117994504e586 | [
"super(login_required, self).__init__(**kwargs)\nself.ignore_login_fail = ignore_login_fail\nself.setGroupContext = setGroupContext\nself.login_redirect = login_redirect",
"super(login_required, self).on_logged_in(request, conn)\nself.prepare_session(request)\nif self.setGroupContext:\n if request.session.get(... | <|body_start_0|>
super(login_required, self).__init__(**kwargs)
self.ignore_login_fail = ignore_login_fail
self.setGroupContext = setGroupContext
self.login_redirect = login_redirect
<|end_body_0|>
<|body_start_1|>
super(login_required, self).on_logged_in(request, conn)
... | webclient specific extension of the OMERO.web login_required() decorator. | login_required | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class login_required:
"""webclient specific extension of the OMERO.web login_required() decorator."""
def __init__(self, ignore_login_fail=False, setGroupContext=False, login_redirect=None, **kwargs):
"""Initialises the decorator."""
<|body_0|>
def on_logged_in(self, request, ... | stack_v2_sparse_classes_36k_train_030112 | 6,360 | no_license | [
{
"docstring": "Initialises the decorator.",
"name": "__init__",
"signature": "def __init__(self, ignore_login_fail=False, setGroupContext=False, login_redirect=None, **kwargs)"
},
{
"docstring": "Called whenever the users is successfully logged in.",
"name": "on_logged_in",
"signature":... | 4 | null | Implement the Python class `login_required` described below.
Class description:
webclient specific extension of the OMERO.web login_required() decorator.
Method signatures and docstrings:
- def __init__(self, ignore_login_fail=False, setGroupContext=False, login_redirect=None, **kwargs): Initialises the decorator.
- ... | Implement the Python class `login_required` described below.
Class description:
webclient specific extension of the OMERO.web login_required() decorator.
Method signatures and docstrings:
- def __init__(self, ignore_login_fail=False, setGroupContext=False, login_redirect=None, **kwargs): Initialises the decorator.
- ... | 8c064a34b91127806848f4992d1e4767574863cf | <|skeleton|>
class login_required:
"""webclient specific extension of the OMERO.web login_required() decorator."""
def __init__(self, ignore_login_fail=False, setGroupContext=False, login_redirect=None, **kwargs):
"""Initialises the decorator."""
<|body_0|>
def on_logged_in(self, request, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class login_required:
"""webclient specific extension of the OMERO.web login_required() decorator."""
def __init__(self, ignore_login_fail=False, setGroupContext=False, login_redirect=None, **kwargs):
"""Initialises the decorator."""
super(login_required, self).__init__(**kwargs)
self.i... | the_stack_v2_python_sparse | tissuelab/omero/gateway_ome500_ice351/omeroweb/webclient/decorators.py | VirtualPlants/tissuelab | train | 2 |
25c036cc32c8bedbc6d71b2b789caa09aaca083f | [
"intervals.sort(key=lambda interval: interval.start)\nresult, prev = (0, 0)\nfor i in xrange(1, len(intervals)):\n if intervals[i].start < intervals[prev].end:\n if intervals[i].end < intervals[prev].end:\n prev = i\n result += 1\n else:\n prev = i\nreturn result",
"if not in... | <|body_start_0|>
intervals.sort(key=lambda interval: interval.start)
result, prev = (0, 0)
for i in xrange(1, len(intervals)):
if intervals[i].start < intervals[prev].end:
if intervals[i].end < intervals[prev].end:
prev = i
result +... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def eraseOverlapIntervals(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
<|body_0|>
def eraseOverlapIntervals2(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_030113 | 4,693 | permissive | [
{
"docstring": ":type intervals: List[Interval] :rtype: int",
"name": "eraseOverlapIntervals",
"signature": "def eraseOverlapIntervals(self, intervals)"
},
{
"docstring": ":type intervals: List[Interval] :rtype: int",
"name": "eraseOverlapIntervals2",
"signature": "def eraseOverlapInterv... | 2 | stack_v2_sparse_classes_30k_train_015515 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def eraseOverlapIntervals(self, intervals): :type intervals: List[Interval] :rtype: int
- def eraseOverlapIntervals2(self, intervals): :type intervals: List[Interval] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def eraseOverlapIntervals(self, intervals): :type intervals: List[Interval] :rtype: int
- def eraseOverlapIntervals2(self, intervals): :type intervals: List[Interval] :rtype: int... | 0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c | <|skeleton|>
class Solution:
def eraseOverlapIntervals(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
<|body_0|>
def eraseOverlapIntervals2(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def eraseOverlapIntervals(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
intervals.sort(key=lambda interval: interval.start)
result, prev = (0, 0)
for i in xrange(1, len(intervals)):
if intervals[i].start < intervals[prev].end:
... | the_stack_v2_python_sparse | cs15211/Non-overlappingIntervals.py | JulyKikuAkita/PythonPrac | train | 1 | |
64a23c081038a7d6e11e263dc1ee8549f1d23fd8 | [
"super().__init__()\nself._accept_input = accept_input\nself._default_measure = default_measure\nself._in_place = in_place",
"try:\n return BasicEngine.is_available(self, cmd)\nexcept LastEngineException:\n return True",
"if self.is_last_engine and cmd.gate == Measure:\n if get_control_count(cmd) != 0:... | <|body_start_0|>
super().__init__()
self._accept_input = accept_input
self._default_measure = default_measure
self._in_place = in_place
<|end_body_0|>
<|body_start_1|>
try:
return BasicEngine.is_available(self, cmd)
except LastEngineException:
ret... | Compiler engine that prints command to the standard output. CommandPrinter is a compiler engine which prints commands to stdout prior to sending them on to the next compiler engine. | CommandPrinter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandPrinter:
"""Compiler engine that prints command to the standard output. CommandPrinter is a compiler engine which prints commands to stdout prior to sending them on to the next compiler engine."""
def __init__(self, accept_input=True, default_measure=False, in_place=False):
""... | stack_v2_sparse_classes_36k_train_030114 | 4,917 | permissive | [
{
"docstring": "Initialize a CommandPrinter. Args: accept_input (bool): If accept_input is true, the printer queries the user to input measurement results if the CommandPrinter is the last engine. Otherwise, all measurements yield default_measure. default_measure (bool): Default measurement result (if accept_in... | 4 | stack_v2_sparse_classes_30k_train_019384 | Implement the Python class `CommandPrinter` described below.
Class description:
Compiler engine that prints command to the standard output. CommandPrinter is a compiler engine which prints commands to stdout prior to sending them on to the next compiler engine.
Method signatures and docstrings:
- def __init__(self, a... | Implement the Python class `CommandPrinter` described below.
Class description:
Compiler engine that prints command to the standard output. CommandPrinter is a compiler engine which prints commands to stdout prior to sending them on to the next compiler engine.
Method signatures and docstrings:
- def __init__(self, a... | 67c660ca18725d23ab0b261a45e34873b6a58d03 | <|skeleton|>
class CommandPrinter:
"""Compiler engine that prints command to the standard output. CommandPrinter is a compiler engine which prints commands to stdout prior to sending them on to the next compiler engine."""
def __init__(self, accept_input=True, default_measure=False, in_place=False):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommandPrinter:
"""Compiler engine that prints command to the standard output. CommandPrinter is a compiler engine which prints commands to stdout prior to sending them on to the next compiler engine."""
def __init__(self, accept_input=True, default_measure=False, in_place=False):
"""Initialize a... | the_stack_v2_python_sparse | projectq/backends/_printer.py | ProjectQ-Framework/ProjectQ | train | 886 |
2d43ee9133a47b53caef7d151d3fb3622d3d8ba1 | [
"bt_test = bluetoothlistener.BluetoothListenerEngineer()\nself.short_bt = bt_test.catch_bluetooth()\nself.long_bt = bt_test.listen_bluetooth(10)\nprint('Test suite: {}'.format(type(self).__name__))\nprint('This test may take up to 30 seconds to complete - Stand by....')",
"self.assertEqual(type(self.short_bt), li... | <|body_start_0|>
bt_test = bluetoothlistener.BluetoothListenerEngineer()
self.short_bt = bt_test.catch_bluetooth()
self.long_bt = bt_test.listen_bluetooth(10)
print('Test suite: {}'.format(type(self).__name__))
print('This test may take up to 30 seconds to complete - Stand by....... | Primary testing class for :mod:`bluetoothlistener` | TestBluetooth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBluetooth:
"""Primary testing class for :mod:`bluetoothlistener`"""
def setUp(self):
"""Setup the bluetooth module to test on."""
<|body_0|>
def test_bt_short(self):
"""Validate the short listen bluetooth return"""
<|body_1|>
def test_bt_long(sel... | stack_v2_sparse_classes_36k_train_030115 | 23,291 | no_license | [
{
"docstring": "Setup the bluetooth module to test on.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Validate the short listen bluetooth return",
"name": "test_bt_short",
"signature": "def test_bt_short(self)"
},
{
"docstring": "Validate the long listen blu... | 3 | null | Implement the Python class `TestBluetooth` described below.
Class description:
Primary testing class for :mod:`bluetoothlistener`
Method signatures and docstrings:
- def setUp(self): Setup the bluetooth module to test on.
- def test_bt_short(self): Validate the short listen bluetooth return
- def test_bt_long(self): ... | Implement the Python class `TestBluetooth` described below.
Class description:
Primary testing class for :mod:`bluetoothlistener`
Method signatures and docstrings:
- def setUp(self): Setup the bluetooth module to test on.
- def test_bt_short(self): Validate the short listen bluetooth return
- def test_bt_long(self): ... | 8f68cc2a6ca568e803a6bfea49a452a5b0c1a2cf | <|skeleton|>
class TestBluetooth:
"""Primary testing class for :mod:`bluetoothlistener`"""
def setUp(self):
"""Setup the bluetooth module to test on."""
<|body_0|>
def test_bt_short(self):
"""Validate the short listen bluetooth return"""
<|body_1|>
def test_bt_long(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestBluetooth:
"""Primary testing class for :mod:`bluetoothlistener`"""
def setUp(self):
"""Setup the bluetooth module to test on."""
bt_test = bluetoothlistener.BluetoothListenerEngineer()
self.short_bt = bt_test.catch_bluetooth()
self.long_bt = bt_test.listen_bluetooth(1... | the_stack_v2_python_sparse | AgentPi/agenttesting.py | JiewenGuan/Iot-Carshare | train | 0 |
54581552b7ca7416920e3e8caf13da8e89da3d02 | [
"self.zoneType = zoneType\nself.filter = filter\nself.thenEffects = thenEffects",
"zone = context.loadZone(self.zoneType)\npossibleCards = self.filter.evaluate(context)\nevent = CardsEvent(possibleCards, zone, context)\ncoroutine = PerformEffects(self.thenEffects, event.context)\nresponse = (yield coroutine.next(... | <|body_start_0|>
self.zoneType = zoneType
self.filter = filter
self.thenEffects = thenEffects
<|end_body_0|>
<|body_start_1|>
zone = context.loadZone(self.zoneType)
possibleCards = self.filter.evaluate(context)
event = CardsEvent(possibleCards, zone, context)
cor... | Represents an effect to pick cards from a zone and an optional filter | Filter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Filter:
"""Represents an effect to pick cards from a zone and an optional filter"""
def __init__(self, zoneType, filter, thenEffects):
"""Initialize the options"""
<|body_0|>
def perform(self, context):
"""Perform the Game Effect"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_030116 | 858 | no_license | [
{
"docstring": "Initialize the options",
"name": "__init__",
"signature": "def __init__(self, zoneType, filter, thenEffects)"
},
{
"docstring": "Perform the Game Effect",
"name": "perform",
"signature": "def perform(self, context)"
}
] | 2 | null | Implement the Python class `Filter` described below.
Class description:
Represents an effect to pick cards from a zone and an optional filter
Method signatures and docstrings:
- def __init__(self, zoneType, filter, thenEffects): Initialize the options
- def perform(self, context): Perform the Game Effect | Implement the Python class `Filter` described below.
Class description:
Represents an effect to pick cards from a zone and an optional filter
Method signatures and docstrings:
- def __init__(self, zoneType, filter, thenEffects): Initialize the options
- def perform(self, context): Perform the Game Effect
<|skeleton|... | 0b5a7573a3cf33430fe61e4ff8a8a7a0ae20b258 | <|skeleton|>
class Filter:
"""Represents an effect to pick cards from a zone and an optional filter"""
def __init__(self, zoneType, filter, thenEffects):
"""Initialize the options"""
<|body_0|>
def perform(self, context):
"""Perform the Game Effect"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Filter:
"""Represents an effect to pick cards from a zone and an optional filter"""
def __init__(self, zoneType, filter, thenEffects):
"""Initialize the options"""
self.zoneType = zoneType
self.filter = filter
self.thenEffects = thenEffects
def perform(self, context):... | the_stack_v2_python_sparse | src/Game/Effects/filter.py | dfwarden/DeckBuilding | train | 0 |
eeb1c03ca48b80c113cd4dd2626fe042363f071b | [
"preprocessor = BinaryChecker(num_variables, phenome_preprocessor)\nTestProblem.__init__(self, leading_ones, num_objectives=1, phenome_preprocessor=preprocessor, **kwargs)\nself.num_variables = num_variables\nself.is_deterministic = True\nself.do_maximize = True",
"assert max_number is None or max_number > 0\nopt... | <|body_start_0|>
preprocessor = BinaryChecker(num_variables, phenome_preprocessor)
TestProblem.__init__(self, leading_ones, num_objectives=1, phenome_preprocessor=preprocessor, **kwargs)
self.num_variables = num_variables
self.is_deterministic = True
self.do_maximize = True
<|end... | Counts the number of contiguous ones from the start of the bit-string. .. note:: In contrast to most other problems in this package, this problem must be maximized. | LeadingOnes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LeadingOnes:
"""Counts the number of contiguous ones from the start of the bit-string. .. note:: In contrast to most other problems in this package, this problem must be maximized."""
def __init__(self, num_variables=30, phenome_preprocessor=None, **kwargs):
"""Constructor. Parameter... | stack_v2_sparse_classes_36k_train_030117 | 7,172 | permissive | [
{
"docstring": "Constructor. Parameters ---------- num_variables : int, optional The search space dimension. phenome_preprocessor : callable, optional A callable potentially applying transformations or checks to the phenome. Modifications should only be applied to a copy of the input. The (modified) phenome mus... | 2 | stack_v2_sparse_classes_30k_train_016030 | Implement the Python class `LeadingOnes` described below.
Class description:
Counts the number of contiguous ones from the start of the bit-string. .. note:: In contrast to most other problems in this package, this problem must be maximized.
Method signatures and docstrings:
- def __init__(self, num_variables=30, phe... | Implement the Python class `LeadingOnes` described below.
Class description:
Counts the number of contiguous ones from the start of the bit-string. .. note:: In contrast to most other problems in this package, this problem must be maximized.
Method signatures and docstrings:
- def __init__(self, num_variables=30, phe... | df14bf0cc263d8fa0ad0a539e94327ac35e33d1c | <|skeleton|>
class LeadingOnes:
"""Counts the number of contiguous ones from the start of the bit-string. .. note:: In contrast to most other problems in this package, this problem must be maximized."""
def __init__(self, num_variables=30, phenome_preprocessor=None, **kwargs):
"""Constructor. Parameter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LeadingOnes:
"""Counts the number of contiguous ones from the start of the bit-string. .. note:: In contrast to most other problems in this package, this problem must be maximized."""
def __init__(self, num_variables=30, phenome_preprocessor=None, **kwargs):
"""Constructor. Parameters ---------- ... | the_stack_v2_python_sparse | pybandit/optproblems/binary.py | chunjenpeng/pyBandit | train | 0 |
91c79bad403ff5fadf03627d5ed6e469179bf43e | [
"text = self.intro_text.get(self.path_str)\nif text:\n self.create_element('intro_text', text)",
"new_section = type(self)(name=title, elements={}, parent=self, **kw)\nnew_section.elements['title'] = rls.Element.from_content(title, heading=True, numbering=numbering, level=self.depth + 1)\nnew_section.insert_in... | <|body_start_0|>
text = self.intro_text.get(self.path_str)
if text:
self.create_element('intro_text', text)
<|end_body_0|>
<|body_start_1|>
new_section = type(self)(name=title, elements={}, parent=self, **kw)
new_section.elements['title'] = rls.Element.from_content(title, he... | rls.Sections subclass to allow adding introductory text (text at beginning of a section) from external file | ISection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ISection:
"""rls.Sections subclass to allow adding introductory text (text at beginning of a section) from external file"""
def insert_intro_text(self):
"""Check if intro text exists for current section and insert as element."""
<|body_0|>
def new_section(self, title, nu... | stack_v2_sparse_classes_36k_train_030118 | 32,542 | no_license | [
{
"docstring": "Check if intro text exists for current section and insert as element.",
"name": "insert_intro_text",
"signature": "def insert_intro_text(self)"
},
{
"docstring": "Create and Return new child Section (subsection).",
"name": "new_section",
"signature": "def new_section(self... | 2 | stack_v2_sparse_classes_30k_train_017097 | Implement the Python class `ISection` described below.
Class description:
rls.Sections subclass to allow adding introductory text (text at beginning of a section) from external file
Method signatures and docstrings:
- def insert_intro_text(self): Check if intro text exists for current section and insert as element.
-... | Implement the Python class `ISection` described below.
Class description:
rls.Sections subclass to allow adding introductory text (text at beginning of a section) from external file
Method signatures and docstrings:
- def insert_intro_text(self): Check if intro text exists for current section and insert as element.
-... | c979f64b295a610333c22d90c50ba9879939db75 | <|skeleton|>
class ISection:
"""rls.Sections subclass to allow adding introductory text (text at beginning of a section) from external file"""
def insert_intro_text(self):
"""Check if intro text exists for current section and insert as element."""
<|body_0|>
def new_section(self, title, nu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ISection:
"""rls.Sections subclass to allow adding introductory text (text at beginning of a section) from external file"""
def insert_intro_text(self):
"""Check if intro text exists for current section and insert as element."""
text = self.intro_text.get(self.path_str)
if text:
... | the_stack_v2_python_sparse | src/report.py | swopet/cmdTestSequence | train | 0 |
27d6ed5f6e1d3ce63ac49e14fd773bd99d53701a | [
"self.positions = positions\nself.num_trials = num_trials\nself.position_value = 1000 / positions",
"cumu_ret = np.zeros(self.num_trials)\nfor trial in range(self.num_trials):\n outcome = 0\n for p in range(self.positions):\n random = np.random.rand()\n if random <= 0.51:\n outcome ... | <|body_start_0|>
self.positions = positions
self.num_trials = num_trials
self.position_value = 1000 / positions
<|end_body_0|>
<|body_start_1|>
cumu_ret = np.zeros(self.num_trials)
for trial in range(self.num_trials):
outcome = 0
for p in range(self.posit... | Create class investment | investment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class investment:
"""Create class investment"""
def __init__(self, positions, num_trials):
"""Constructing the class"""
<|body_0|>
def simulate(self):
"""Simulating outcome of investment"""
<|body_1|>
def output(positions, num_trials):
"""Creating ... | stack_v2_sparse_classes_36k_train_030119 | 1,647 | no_license | [
{
"docstring": "Constructing the class",
"name": "__init__",
"signature": "def __init__(self, positions, num_trials)"
},
{
"docstring": "Simulating outcome of investment",
"name": "simulate",
"signature": "def simulate(self)"
},
{
"docstring": "Creating graph and text file by run... | 3 | null | Implement the Python class `investment` described below.
Class description:
Create class investment
Method signatures and docstrings:
- def __init__(self, positions, num_trials): Constructing the class
- def simulate(self): Simulating outcome of investment
- def output(positions, num_trials): Creating graph and text ... | Implement the Python class `investment` described below.
Class description:
Create class investment
Method signatures and docstrings:
- def __init__(self, positions, num_trials): Constructing the class
- def simulate(self): Simulating outcome of investment
- def output(positions, num_trials): Creating graph and text ... | 5b904060e8bced7f91547ad7f7819773a7450a1e | <|skeleton|>
class investment:
"""Create class investment"""
def __init__(self, positions, num_trials):
"""Constructing the class"""
<|body_0|>
def simulate(self):
"""Simulating outcome of investment"""
<|body_1|>
def output(positions, num_trials):
"""Creating ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class investment:
"""Create class investment"""
def __init__(self, positions, num_trials):
"""Constructing the class"""
self.positions = positions
self.num_trials = num_trials
self.position_value = 1000 / positions
def simulate(self):
"""Simulating outcome of invest... | the_stack_v2_python_sparse | llq205/investment.py | ds-ga-1007/assignment8 | train | 1 |
cea8705b97ff68e8e242163a793f48ac910808f5 | [
"self.f = f\nself.gp = GP(X_init, Y_init, l, sigma_f)\nmin, max = bounds\nX_s = np.linspace(min, max, ac_samples)\nself.X_s = np.sort(X_s).reshape(-1, 1)\nself.xsi = xsi\nself.minimize = minimize",
"mu, sigma = self.gp.predict(self.X_s)\nif self.minimize is True:\n optimize = np.amin(self.gp.Y)\n imp = opti... | <|body_start_0|>
self.f = f
self.gp = GP(X_init, Y_init, l, sigma_f)
min, max = bounds
X_s = np.linspace(min, max, ac_samples)
self.X_s = np.sort(X_s).reshape(-1, 1)
self.xsi = xsi
self.minimize = minimize
<|end_body_0|>
<|body_start_1|>
mu, sigma = self.... | Performs Bayesian optimization | BayesianOptimization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianOptimization:
"""Performs Bayesian optimization"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor"""
<|body_0|>
def acquisition(self):
"""Calculates the next best sample location"""... | stack_v2_sparse_classes_36k_train_030120 | 2,005 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True)"
},
{
"docstring": "Calculates the next best sample location",
"name": "acquisition",
"signature": "def acquisition(sel... | 3 | stack_v2_sparse_classes_30k_train_013490 | Implement the Python class `BayesianOptimization` described below.
Class description:
Performs Bayesian optimization
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): Class constructor
- def acquisition(self): Calculates the next be... | Implement the Python class `BayesianOptimization` described below.
Class description:
Performs Bayesian optimization
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): Class constructor
- def acquisition(self): Calculates the next be... | 9ff78818c132d1233c11b8fc8fd469878b23b14e | <|skeleton|>
class BayesianOptimization:
"""Performs Bayesian optimization"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor"""
<|body_0|>
def acquisition(self):
"""Calculates the next best sample location"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BayesianOptimization:
"""Performs Bayesian optimization"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor"""
self.f = f
self.gp = GP(X_init, Y_init, l, sigma_f)
min, max = bounds
X_s = np.lin... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/5-bayes_opt.py | Nzparra/holbertonschool-machine_learning | train | 0 |
7773e7756d4ab1e5aab18f5fe7722aa5b6badd3d | [
"print('wihtin Liner datetracker ', date_tracker)\nself.date_tracker = date_tracker\nself.roster_days = roster_days\nself.itinerary_builder = ItinBuilder()\nself.line_type = line_type\nmonth = self.date_tracker.month\nyear = self.date_tracker.year\nself.line = Line(month, year)\nself.unrecognized_events = []",
"t... | <|body_start_0|>
print('wihtin Liner datetracker ', date_tracker)
self.date_tracker = date_tracker
self.roster_days = roster_days
self.itinerary_builder = ItinBuilder()
self.line_type = line_type
month = self.date_tracker.month
year = self.date_tracker.year
... | ´Turns a Roster Reader into a bidline | Liner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Liner:
"""´Turns a Roster Reader into a bidline"""
def __init__(self, date_tracker, roster_days, line_type='scheduled'):
"""Mandatory arguments"""
<|body_0|>
def build_line(self):
"""Returns a Line object containing all data read from the text file but now turned... | stack_v2_sparse_classes_36k_train_030121 | 5,879 | no_license | [
{
"docstring": "Mandatory arguments",
"name": "__init__",
"signature": "def __init__(self, date_tracker, roster_days, line_type='scheduled')"
},
{
"docstring": "Returns a Line object containing all data read from the text file but now turned into corresponding objects",
"name": "build_line",... | 5 | stack_v2_sparse_classes_30k_train_002833 | Implement the Python class `Liner` described below.
Class description:
´Turns a Roster Reader into a bidline
Method signatures and docstrings:
- def __init__(self, date_tracker, roster_days, line_type='scheduled'): Mandatory arguments
- def build_line(self): Returns a Line object containing all data read from the tex... | Implement the Python class `Liner` described below.
Class description:
´Turns a Roster Reader into a bidline
Method signatures and docstrings:
- def __init__(self, date_tracker, roster_days, line_type='scheduled'): Mandatory arguments
- def build_line(self): Returns a Line object containing all data read from the tex... | 0be9c5515f7ccd9ac7a07a2958c0d8aa9d19624c | <|skeleton|>
class Liner:
"""´Turns a Roster Reader into a bidline"""
def __init__(self, date_tracker, roster_days, line_type='scheduled'):
"""Mandatory arguments"""
<|body_0|>
def build_line(self):
"""Returns a Line object containing all data read from the text file but now turned... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Liner:
"""´Turns a Roster Reader into a bidline"""
def __init__(self, date_tracker, roster_days, line_type='scheduled'):
"""Mandatory arguments"""
print('wihtin Liner datetracker ', date_tracker)
self.date_tracker = date_tracker
self.roster_days = roster_days
self.... | the_stack_v2_python_sparse | rosterReaders/lineCreator.py | demxic/Orgutrip | train | 0 |
61777ce76fa0aa407cfce3f0c6fc81db02d04523 | [
"super(WeightQuantizerLS2, self).__init__()\nself.register_buffer('v1', torch.tensor([0.0] * size))\nself.register_buffer('v2', torch.tensor([0.0] * size))",
"if self.training:\n v1, v2, w_q = quantization.quantizer_ls_2(w, skip=skip)\n self.v1.copy_(v1)\n self.v2.copy_(v2)\nelse:\n _, _, w_q = quanti... | <|body_start_0|>
super(WeightQuantizerLS2, self).__init__()
self.register_buffer('v1', torch.tensor([0.0] * size))
self.register_buffer('v2', torch.tensor([0.0] * size))
<|end_body_0|>
<|body_start_1|>
if self.training:
v1, v2, w_q = quantization.quantizer_ls_2(w, skip=skip)... | Weight quantizer using least squares, 2 bits. In training mode, the optimal scalars are computed and cached. In eval mode, the cached scalars are used to compute the quantization. | WeightQuantizerLS2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightQuantizerLS2:
"""Weight quantizer using least squares, 2 bits. In training mode, the optimal scalars are computed and cached. In eval mode, the cached scalars are used to compute the quantization."""
def __init__(self, size: int) -> None:
"""Construct a weight quantizer using l... | stack_v2_sparse_classes_36k_train_030122 | 4,037 | no_license | [
{
"docstring": "Construct a weight quantizer using least squares with 2 bits.",
"name": "__init__",
"signature": "def __init__(self, size: int) -> None"
},
{
"docstring": "Forward pass of quantizing weight using least squares 2 bits.",
"name": "forward",
"signature": "def forward(self, w... | 2 | stack_v2_sparse_classes_30k_train_007526 | Implement the Python class `WeightQuantizerLS2` described below.
Class description:
Weight quantizer using least squares, 2 bits. In training mode, the optimal scalars are computed and cached. In eval mode, the cached scalars are used to compute the quantization.
Method signatures and docstrings:
- def __init__(self,... | Implement the Python class `WeightQuantizerLS2` described below.
Class description:
Weight quantizer using least squares, 2 bits. In training mode, the optimal scalars are computed and cached. In eval mode, the cached scalars are used to compute the quantization.
Method signatures and docstrings:
- def __init__(self,... | 39197b5f54cd84ff35022c851dd2dcb753ca6b89 | <|skeleton|>
class WeightQuantizerLS2:
"""Weight quantizer using least squares, 2 bits. In training mode, the optimal scalars are computed and cached. In eval mode, the cached scalars are used to compute the quantization."""
def __init__(self, size: int) -> None:
"""Construct a weight quantizer using l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeightQuantizerLS2:
"""Weight quantizer using least squares, 2 bits. In training mode, the optimal scalars are computed and cached. In eval mode, the cached scalars are used to compute the quantization."""
def __init__(self, size: int) -> None:
"""Construct a weight quantizer using least squares ... | the_stack_v2_python_sparse | quant/binary/weight_quantization.py | mikechen66/ml-quant | train | 0 |
63190e80e3cc9568264807a67f1f545eaa564353 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | A set of methods for managing Snapshot resources. | SnapshotServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnapshotServiceServicer:
"""A set of methods for managing Snapshot resources."""
def Get(self, request, context):
"""Returns the specified Snapshot resource. To get the list of available Snapshot resources, make a [List] request."""
<|body_0|>
def List(self, request, con... | stack_v2_sparse_classes_36k_train_030123 | 12,319 | permissive | [
{
"docstring": "Returns the specified Snapshot resource. To get the list of available Snapshot resources, make a [List] request.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Retrieves the list of Snapshot resources in the specified folder.",
"name": "Lis... | 6 | null | Implement the Python class `SnapshotServiceServicer` described below.
Class description:
A set of methods for managing Snapshot resources.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified Snapshot resource. To get the list of available Snapshot resources, make a [List] reques... | Implement the Python class `SnapshotServiceServicer` described below.
Class description:
A set of methods for managing Snapshot resources.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified Snapshot resource. To get the list of available Snapshot resources, make a [List] reques... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class SnapshotServiceServicer:
"""A set of methods for managing Snapshot resources."""
def Get(self, request, context):
"""Returns the specified Snapshot resource. To get the list of available Snapshot resources, make a [List] request."""
<|body_0|>
def List(self, request, con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnapshotServiceServicer:
"""A set of methods for managing Snapshot resources."""
def Get(self, request, context):
"""Returns the specified Snapshot resource. To get the list of available Snapshot resources, make a [List] request."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
... | the_stack_v2_python_sparse | yandex/cloud/compute/v1/snapshot_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
2befbbdf6cc69112b02c640f885ff35af2e28aa1 | [
"self.x = x\nself.y = y\nself.yaw = yaw\nself.v = v",
"delta = np.clip(delta, -max_steer, max_steer)\nself.x += self.v * np.cos(self.yaw) * dt\nself.y += self.v * np.sin(self.yaw) * dt\nself.yaw += self.v / L * np.tan(delta) * dt\nself.yaw = normalize_angle(self.yaw)\nself.v += acceleration * dt"
] | <|body_start_0|>
self.x = x
self.y = y
self.yaw = yaw
self.v = v
<|end_body_0|>
<|body_start_1|>
delta = np.clip(delta, -max_steer, max_steer)
self.x += self.v * np.cos(self.yaw) * dt
self.y += self.v * np.sin(self.yaw) * dt
self.yaw += self.v / L * np.ta... | State | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class State:
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0):
"""Initialize the state of the vehicle Keyword Arguments: x {float} -- [X-coordinate] (default: {0.0}) y {float} -- [Y-Coordinate] (default: {0.0}) yaw {float} -- [Yaw/heading angle] (default: {0.0}) v {float} -- [velocity] (defaul... | stack_v2_sparse_classes_36k_train_030124 | 5,612 | no_license | [
{
"docstring": "Initialize the state of the vehicle Keyword Arguments: x {float} -- [X-coordinate] (default: {0.0}) y {float} -- [Y-Coordinate] (default: {0.0}) yaw {float} -- [Yaw/heading angle] (default: {0.0}) v {float} -- [velocity] (default: {0.0})",
"name": "__init__",
"signature": "def __init__(s... | 2 | stack_v2_sparse_classes_30k_train_018112 | Implement the Python class `State` described below.
Class description:
Implement the State class.
Method signatures and docstrings:
- def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0): Initialize the state of the vehicle Keyword Arguments: x {float} -- [X-coordinate] (default: {0.0}) y {float} -- [Y-Coordinate] (defau... | Implement the Python class `State` described below.
Class description:
Implement the State class.
Method signatures and docstrings:
- def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0): Initialize the state of the vehicle Keyword Arguments: x {float} -- [X-coordinate] (default: {0.0}) y {float} -- [Y-Coordinate] (defau... | 84388bce6bb8313949e1607782dceed4abf546ea | <|skeleton|>
class State:
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0):
"""Initialize the state of the vehicle Keyword Arguments: x {float} -- [X-coordinate] (default: {0.0}) y {float} -- [Y-Coordinate] (default: {0.0}) yaw {float} -- [Yaw/heading angle] (default: {0.0}) v {float} -- [velocity] (defaul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class State:
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0):
"""Initialize the state of the vehicle Keyword Arguments: x {float} -- [X-coordinate] (default: {0.0}) y {float} -- [Y-Coordinate] (default: {0.0}) yaw {float} -- [Yaw/heading angle] (default: {0.0}) v {float} -- [velocity] (default: {0.0})"""
... | the_stack_v2_python_sparse | study.py | FernCarrera/Localization | train | 0 | |
8e34da39c9691298f95f06704a48502b0b0293de | [
"try:\n return User.objects.get(pk=user_id)\nexcept User.DoesNotExist as e:\n logger.exception(e)\n raise Http404",
"user = self.get_object(kwargs['user_id'])\nserializer = UserSerializer(user, context={'request': Request(request)})\nreturn Response(serializer.data)",
"user = self.get_object(kwargs['us... | <|body_start_0|>
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist as e:
logger.exception(e)
raise Http404
<|end_body_0|>
<|body_start_1|>
user = self.get_object(kwargs['user_id'])
serializer = UserSerializer(user, context={'request': ... | This view handle all requests what comes on endpoint /users/(?P<user_id>[0-9]+)$ | UserDetail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserDetail:
"""This view handle all requests what comes on endpoint /users/(?P<user_id>[0-9]+)$"""
def get_object(user_id: int) -> User:
"""Trying to find user by ID in database and return them :param user_id: user id :return: User object or DoesNotExist exception"""
<|body_0... | stack_v2_sparse_classes_36k_train_030125 | 4,626 | permissive | [
{
"docstring": "Trying to find user by ID in database and return them :param user_id: user id :return: User object or DoesNotExist exception",
"name": "get_object",
"signature": "def get_object(user_id: int) -> User"
},
{
"docstring": "This method handle GET request on base view url and return J... | 4 | stack_v2_sparse_classes_30k_train_018943 | Implement the Python class `UserDetail` described below.
Class description:
This view handle all requests what comes on endpoint /users/(?P<user_id>[0-9]+)$
Method signatures and docstrings:
- def get_object(user_id: int) -> User: Trying to find user by ID in database and return them :param user_id: user id :return: ... | Implement the Python class `UserDetail` described below.
Class description:
This view handle all requests what comes on endpoint /users/(?P<user_id>[0-9]+)$
Method signatures and docstrings:
- def get_object(user_id: int) -> User: Trying to find user by ID in database and return them :param user_id: user id :return: ... | fdb911dfafbd2609b7f96561ab6780b4131a77bd | <|skeleton|>
class UserDetail:
"""This view handle all requests what comes on endpoint /users/(?P<user_id>[0-9]+)$"""
def get_object(user_id: int) -> User:
"""Trying to find user by ID in database and return them :param user_id: user id :return: User object or DoesNotExist exception"""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserDetail:
"""This view handle all requests what comes on endpoint /users/(?P<user_id>[0-9]+)$"""
def get_object(user_id: int) -> User:
"""Trying to find user by ID in database and return them :param user_id: user id :return: User object or DoesNotExist exception"""
try:
retu... | the_stack_v2_python_sparse | users/views.py | Kh-011-WebUIPython/lit | train | 4 |
f1120224241851c19baa225fddf63173832d53ab | [
"try:\n serializer = PatientHistoryFilesSerializers(PatientHistoryFiles.objects.all(), many=True)\n return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)\nexcept Exception as e:\n info_message = 'Internal Server Error'\n logger.error(info_message, e)\n return JsonRespons... | <|body_start_0|>
try:
serializer = PatientHistoryFilesSerializers(PatientHistoryFiles.objects.all(), many=True)
return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)
except Exception as e:
info_message = 'Internal Server Error'
... | PatientHistoryFilesView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatientHistoryFilesView:
def get(self, request):
"""Get all patients"""
<|body_0|>
def post(self, request):
"""Save patient data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
serializer = PatientHistoryFilesSerializers(PatientHist... | stack_v2_sparse_classes_36k_train_030126 | 12,219 | no_license | [
{
"docstring": "Get all patients",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Save patient data",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005568 | Implement the Python class `PatientHistoryFilesView` described below.
Class description:
Implement the PatientHistoryFilesView class.
Method signatures and docstrings:
- def get(self, request): Get all patients
- def post(self, request): Save patient data | Implement the Python class `PatientHistoryFilesView` described below.
Class description:
Implement the PatientHistoryFilesView class.
Method signatures and docstrings:
- def get(self, request): Get all patients
- def post(self, request): Save patient data
<|skeleton|>
class PatientHistoryFilesView:
def get(self... | b63849983a592fd6a1f654191020fd86aa0787ae | <|skeleton|>
class PatientHistoryFilesView:
def get(self, request):
"""Get all patients"""
<|body_0|>
def post(self, request):
"""Save patient data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PatientHistoryFilesView:
def get(self, request):
"""Get all patients"""
try:
serializer = PatientHistoryFilesSerializers(PatientHistoryFiles.objects.all(), many=True)
return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)
except Exce... | the_stack_v2_python_sparse | patient/views.py | RupeshKurlekar/biocare | train | 1 | |
d1d9a992fcc46640e2bc941d57f986c8002d0a41 | [
"self.partyId = partyId\nself.replies = []\nfor oneReply in partyReplies:\n self.replies.append(SingleReply(*oneReply))",
"string = 'partyId=%d ' % self.partyId\nfor reply in self.replies:\n string += '(%d:%d) ' % (reply.inviteeId, reply.status)\nreturn string"
] | <|body_start_0|>
self.partyId = partyId
self.replies = []
for oneReply in partyReplies:
self.replies.append(SingleReply(*oneReply))
<|end_body_0|>
<|body_start_1|>
string = 'partyId=%d ' % self.partyId
for reply in self.replies:
string += '(%d:%d) ' % (re... | Python friendly representation of the replies for one party you're hosting. For now just straight up conversions of values we get from the database Make sure this class can be used on the AI side | PartyReplyInfoBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartyReplyInfoBase:
"""Python friendly representation of the replies for one party you're hosting. For now just straight up conversions of values we get from the database Make sure this class can be used on the AI side"""
def __init__(self, partyId, partyReplies):
"""Construct the pa... | stack_v2_sparse_classes_36k_train_030127 | 1,146 | no_license | [
{
"docstring": "Construct the party info.",
"name": "__init__",
"signature": "def __init__(self, partyId, partyReplies)"
},
{
"docstring": "Return a useful string representation of this object.",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | null | Implement the Python class `PartyReplyInfoBase` described below.
Class description:
Python friendly representation of the replies for one party you're hosting. For now just straight up conversions of values we get from the database Make sure this class can be used on the AI side
Method signatures and docstrings:
- de... | Implement the Python class `PartyReplyInfoBase` described below.
Class description:
Python friendly representation of the replies for one party you're hosting. For now just straight up conversions of values we get from the database Make sure this class can be used on the AI side
Method signatures and docstrings:
- de... | 0e7bfc1fe29fd595df0b982e40f94c30befb1ec7 | <|skeleton|>
class PartyReplyInfoBase:
"""Python friendly representation of the replies for one party you're hosting. For now just straight up conversions of values we get from the database Make sure this class can be used on the AI side"""
def __init__(self, partyId, partyReplies):
"""Construct the pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PartyReplyInfoBase:
"""Python friendly representation of the replies for one party you're hosting. For now just straight up conversions of values we get from the database Make sure this class can be used on the AI side"""
def __init__(self, partyId, partyReplies):
"""Construct the party info."""
... | the_stack_v2_python_sparse | toontown/src/parties/PartyReplyInfo.py | satire6/Anesidora | train | 89 |
54b81d9d7cc5abec98fe953acd3708539b8998bd | [
"if not grid:\n return -1\nif grid and (not isinstance(grid[0], list)):\n return sum(grid)\nm, n = (len(grid), len(grid[0]))\ndp = [[float('inf')] * (n + 1) for _ in range(m + 1)]\ndp[0][1] = 0\nfor i in range(1, m + 1):\n for j in range(1, n + 1):\n dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid... | <|body_start_0|>
if not grid:
return -1
if grid and (not isinstance(grid[0], list)):
return sum(grid)
m, n = (len(grid), len(grid[0]))
dp = [[float('inf')] * (n + 1) for _ in range(m + 1)]
dp[0][1] = 0
for i in range(1, m + 1):
for j in... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minPathSum(self, grid):
"""dp[i][j] 代表 (0,0)->(i-1_最短回文串.py.j-1_最短回文串.py) 最短路径 dp[i][j] = min(dp[i][j-1_最短回文串.py], dp[i-1_最短回文串.py][j]) + grid[i-1_最短回文串.py][j-1_最短回文串.py] dp[0][j] = inf dp[i][0] = inf dp[0][1_最短回文串.py] = 0 res = dp[-1_最短回文串.py][-1_最短回文串.py]"""
<|bod... | stack_v2_sparse_classes_36k_train_030128 | 1,721 | no_license | [
{
"docstring": "dp[i][j] 代表 (0,0)->(i-1_最短回文串.py.j-1_最短回文串.py) 最短路径 dp[i][j] = min(dp[i][j-1_最短回文串.py], dp[i-1_最短回文串.py][j]) + grid[i-1_最短回文串.py][j-1_最短回文串.py] dp[0][j] = inf dp[i][0] = inf dp[0][1_最短回文串.py] = 0 res = dp[-1_最短回文串.py][-1_最短回文串.py]",
"name": "minPathSum",
"signature": "def minPathSum(self... | 2 | stack_v2_sparse_classes_30k_train_020038 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid): dp[i][j] 代表 (0,0)->(i-1_最短回文串.py.j-1_最短回文串.py) 最短路径 dp[i][j] = min(dp[i][j-1_最短回文串.py], dp[i-1_最短回文串.py][j]) + grid[i-1_最短回文串.py][j-1_最短回文串.py] dp[0][... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid): dp[i][j] 代表 (0,0)->(i-1_最短回文串.py.j-1_最短回文串.py) 最短路径 dp[i][j] = min(dp[i][j-1_最短回文串.py], dp[i-1_最短回文串.py][j]) + grid[i-1_最短回文串.py][j-1_最短回文串.py] dp[0][... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Solution:
def minPathSum(self, grid):
"""dp[i][j] 代表 (0,0)->(i-1_最短回文串.py.j-1_最短回文串.py) 最短路径 dp[i][j] = min(dp[i][j-1_最短回文串.py], dp[i-1_最短回文串.py][j]) + grid[i-1_最短回文串.py][j-1_最短回文串.py] dp[0][j] = inf dp[i][0] = inf dp[0][1_最短回文串.py] = 0 res = dp[-1_最短回文串.py][-1_最短回文串.py]"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minPathSum(self, grid):
"""dp[i][j] 代表 (0,0)->(i-1_最短回文串.py.j-1_最短回文串.py) 最短路径 dp[i][j] = min(dp[i][j-1_最短回文串.py], dp[i-1_最短回文串.py][j]) + grid[i-1_最短回文串.py][j-1_最短回文串.py] dp[0][j] = inf dp[i][0] = inf dp[0][1_最短回文串.py] = 0 res = dp[-1_最短回文串.py][-1_最短回文串.py]"""
if not grid:
... | the_stack_v2_python_sparse | 4_LEETCODE/2_DP/网格问题/64_最小路径和.py | fzingithub/SwordRefers2Offer | train | 1 | |
f49ff3d98395dc0f5395b23b0fcbe8566eddadb2 | [
"url = host + '/api/openitem_comment/create'\ndata = {'content': '我家二狗子特别喜欢吃这个东西%s' % random.randrange(1, 1000), 'openitem_id': 224, 'pid': 0}\nr = requests.post(url=url, headers=header, data=data).json()\nout_format('添加评论:', r)\nreturn r",
"url = host + '/api/openitem_comment/index'\ndata = {'size': 10, 'page': ... | <|body_start_0|>
url = host + '/api/openitem_comment/create'
data = {'content': '我家二狗子特别喜欢吃这个东西%s' % random.randrange(1, 1000), 'openitem_id': 224, 'pid': 0}
r = requests.post(url=url, headers=header, data=data).json()
out_format('添加评论:', r)
return r
<|end_body_0|>
<|body_start_... | openitemcomment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class openitemcomment:
def add_comment(self):
"""添加评论 :param:token:用户授权的token :param:content:评论内容 :param:openitem_id:开放商品id :param:pid:父评论id,默认值0----此处传值为0的时候意为此条评论是父评论,不是子评论 :param:at_user: @用户ID,默认值0----此参数非必填"""
<|body_0|>
def comment_list(self):
"""评论列表 :param:token:用户... | stack_v2_sparse_classes_36k_train_030129 | 3,412 | no_license | [
{
"docstring": "添加评论 :param:token:用户授权的token :param:content:评论内容 :param:openitem_id:开放商品id :param:pid:父评论id,默认值0----此处传值为0的时候意为此条评论是父评论,不是子评论 :param:at_user: @用户ID,默认值0----此参数非必填",
"name": "add_comment",
"signature": "def add_comment(self)"
},
{
"docstring": "评论列表 :param:token:用户授权的token :param:... | 5 | stack_v2_sparse_classes_30k_train_020905 | Implement the Python class `openitemcomment` described below.
Class description:
Implement the openitemcomment class.
Method signatures and docstrings:
- def add_comment(self): 添加评论 :param:token:用户授权的token :param:content:评论内容 :param:openitem_id:开放商品id :param:pid:父评论id,默认值0----此处传值为0的时候意为此条评论是父评论,不是子评论 :param:at_user:... | Implement the Python class `openitemcomment` described below.
Class description:
Implement the openitemcomment class.
Method signatures and docstrings:
- def add_comment(self): 添加评论 :param:token:用户授权的token :param:content:评论内容 :param:openitem_id:开放商品id :param:pid:父评论id,默认值0----此处传值为0的时候意为此条评论是父评论,不是子评论 :param:at_user:... | 0ebaae335de2f1633e31c4fc3f60e556220a8bfb | <|skeleton|>
class openitemcomment:
def add_comment(self):
"""添加评论 :param:token:用户授权的token :param:content:评论内容 :param:openitem_id:开放商品id :param:pid:父评论id,默认值0----此处传值为0的时候意为此条评论是父评论,不是子评论 :param:at_user: @用户ID,默认值0----此参数非必填"""
<|body_0|>
def comment_list(self):
"""评论列表 :param:token:用户... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class openitemcomment:
def add_comment(self):
"""添加评论 :param:token:用户授权的token :param:content:评论内容 :param:openitem_id:开放商品id :param:pid:父评论id,默认值0----此处传值为0的时候意为此条评论是父评论,不是子评论 :param:at_user: @用户ID,默认值0----此参数非必填"""
url = host + '/api/openitem_comment/create'
data = {'content': '我家二狗子特别喜欢吃这个东... | the_stack_v2_python_sparse | Atle/interface/framework/base/aOpenitemComment.py | shiqi0128/My_scripts | train | 0 | |
ebfebe543d51a03a04b68ec34fbc4c23dd044692 | [
"if not root:\n return []\nresult = []\nresult.extend([root.val])\nfor child in root.children:\n result.extend(self.preorder(child))\nreturn result",
"nodes = [root]\nresult = []\nwhile nodes:\n node = nodes.pop(0)\n if node:\n result.append(node.val)\n nodes.extend(node.children)\nretur... | <|body_start_0|>
if not root:
return []
result = []
result.extend([root.val])
for child in root.children:
result.extend(self.preorder(child))
return result
<|end_body_0|>
<|body_start_1|>
nodes = [root]
result = []
while nodes:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _preorder(self, root):
""":type root: Node :rtype: List[int]"""
<|body_0|>
def __preorder(self, root):
""":type root: Node :rtype: List[int]"""
<|body_1|>
def preorder(self, root):
""":type root: Node :rtype: List[int]"""
<|... | stack_v2_sparse_classes_36k_train_030130 | 2,228 | permissive | [
{
"docstring": ":type root: Node :rtype: List[int]",
"name": "_preorder",
"signature": "def _preorder(self, root)"
},
{
"docstring": ":type root: Node :rtype: List[int]",
"name": "__preorder",
"signature": "def __preorder(self, root)"
},
{
"docstring": ":type root: Node :rtype: L... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _preorder(self, root): :type root: Node :rtype: List[int]
- def __preorder(self, root): :type root: Node :rtype: List[int]
- def preorder(self, root): :type root: Node :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _preorder(self, root): :type root: Node :rtype: List[int]
- def __preorder(self, root): :type root: Node :rtype: List[int]
- def preorder(self, root): :type root: Node :rtype... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _preorder(self, root):
""":type root: Node :rtype: List[int]"""
<|body_0|>
def __preorder(self, root):
""":type root: Node :rtype: List[int]"""
<|body_1|>
def preorder(self, root):
""":type root: Node :rtype: List[int]"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _preorder(self, root):
""":type root: Node :rtype: List[int]"""
if not root:
return []
result = []
result.extend([root.val])
for child in root.children:
result.extend(self.preorder(child))
return result
def __preorder(s... | the_stack_v2_python_sparse | 589.n-ary-tree-preorder-traversal.py | windard/leeeeee | train | 0 | |
b53e4603b387644eeccbed8a999ac75b4d1f426b | [
"assert da.getDim() == 1\nself.da = da\nself.prob = prob\nself.factor = factor\nself.localX = da.createLocalVec()",
"self.da.globalToLocal(X, self.localX)\nx = self.da.getVecArray(self.localX)\nf = self.da.getVecArray(F)\nmx = self.da.getSizes()[0]\nxs, xe = self.da.getRanges()[0]\nfor i in range(xs, xe):\n if... | <|body_start_0|>
assert da.getDim() == 1
self.da = da
self.prob = prob
self.factor = factor
self.localX = da.createLocalVec()
<|end_body_0|>
<|body_start_1|>
self.da.globalToLocal(X, self.localX)
x = self.da.getVecArray(self.localX)
f = self.da.getVecArra... | Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES | Fisher_reaction | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fisher_reaction:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, prob, factor):
"""Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd) dx: grid spacing in x direction"... | stack_v2_sparse_classes_36k_train_030131 | 16,584 | permissive | [
{
"docstring": "Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd) dx: grid spacing in x direction",
"name": "__init__",
"signature": "def __init__(self, da, prob, factor)"
},
{
"docstring": "Function to evaluate the residual for the Newton solver... | 3 | null | Implement the Python class `Fisher_reaction` described below.
Class description:
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
Method signatures and docstrings:
- def __init__(self, da, prob, factor): Initialization routine Args: da: DMDA object prob: problem instance factor:... | Implement the Python class `Fisher_reaction` described below.
Class description:
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
Method signatures and docstrings:
- def __init__(self, da, prob, factor): Initialization routine Args: da: DMDA object prob: problem instance factor:... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class Fisher_reaction:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, prob, factor):
"""Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd) dx: grid spacing in x direction"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fisher_reaction:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, prob, factor):
"""Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd) dx: grid spacing in x direction"""
as... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/GeneralizedFisher_1D_PETSc.py | Parallel-in-Time/pySDC | train | 30 |
5176b32a3cd5a6a151c5f0076d5d9e4e5946c101 | [
"if not isinstance(data, np.ndarray) or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nif data.shape[1] < 2:\n raise ValueError('data must contain multiple data points')\nself.mean = np.mean(data, axis=1).reshape((data.shape[0], 1))\ndata_t = data.T\nmean = np.mean(data_t, axis=0)... | <|body_start_0|>
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
raise ValueError('data must contain multiple data points')
self.mean = np.mean(data, axis=1).reshape((data.shape[0], 1))
... | class | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""class"""
def __init__(self, data):
"""initializer"""
<|body_0|>
def pdf(self, x):
"""method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError(... | stack_v2_sparse_classes_36k_train_030132 | 1,296 | no_license | [
{
"docstring": "initializer",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "method",
"name": "pdf",
"signature": "def pdf(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005137 | Implement the Python class `MultiNormal` described below.
Class description:
class
Method signatures and docstrings:
- def __init__(self, data): initializer
- def pdf(self, x): method | Implement the Python class `MultiNormal` described below.
Class description:
class
Method signatures and docstrings:
- def __init__(self, data): initializer
- def pdf(self, x): method
<|skeleton|>
class MultiNormal:
"""class"""
def __init__(self, data):
"""initializer"""
<|body_0|>
def ... | b5e8f1253309567ca7be71b9575a150de1be3820 | <|skeleton|>
class MultiNormal:
"""class"""
def __init__(self, data):
"""initializer"""
<|body_0|>
def pdf(self, x):
"""method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiNormal:
"""class"""
def __init__(self, data):
"""initializer"""
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
raise ValueError('data must contain multiple data poin... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | jadsm98/holbertonschool-machine_learning | train | 0 |
e8aaf07a3952cb7f728fe5a5270a84a05bb0bce0 | [
"self.device = config['device']\nloss_scales = config['losses_and_scales']\nif 'fvd' in loss_scales.keys() and config['img_c'] not in [2, 3]:\n warnings.warn(\"'FVD' measure won't be used since image channels needs to be in [2, 3]\")\n loss_scales.pop('fvd')\nself.losses = {k: (LOSS_CLASSES[k](device=self.dev... | <|body_start_0|>
self.device = config['device']
loss_scales = config['losses_and_scales']
if 'fvd' in loss_scales.keys() and config['img_c'] not in [2, 3]:
warnings.warn("'FVD' measure won't be used since image channels needs to be in [2, 3]")
loss_scales.pop('fvd')
... | This class provides bundled access to multiple losses. With this class's :meth:`get_losses()` method, all specified loss values are calculated on the same input prediction and target tensor. Attributes: device (str): A string specifying whether to use the GPU for calculations (`cuda`) or the CPU (`cpu`). losses (dict):... | PredictionLossProvider | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PredictionLossProvider:
"""This class provides bundled access to multiple losses. With this class's :meth:`get_losses()` method, all specified loss values are calculated on the same input prediction and target tensor. Attributes: device (str): A string specifying whether to use the GPU for calcul... | stack_v2_sparse_classes_36k_train_030133 | 2,547 | permissive | [
{
"docstring": "Initializes the provider by extracting device and loss IDs from the provided config dict and instantiating the losses that shall be used. Args: config (dict): A dictionary containing the devices and losses to use. The provided losses come with the scales that should be multiplied by the respecti... | 2 | stack_v2_sparse_classes_30k_train_019779 | Implement the Python class `PredictionLossProvider` described below.
Class description:
This class provides bundled access to multiple losses. With this class's :meth:`get_losses()` method, all specified loss values are calculated on the same input prediction and target tensor. Attributes: device (str): A string speci... | Implement the Python class `PredictionLossProvider` described below.
Class description:
This class provides bundled access to multiple losses. With this class's :meth:`get_losses()` method, all specified loss values are calculated on the same input prediction and target tensor. Attributes: device (str): A string speci... | 391570121b5bd9e3fd23aca9a0945a63c4173a24 | <|skeleton|>
class PredictionLossProvider:
"""This class provides bundled access to multiple losses. With this class's :meth:`get_losses()` method, all specified loss values are calculated on the same input prediction and target tensor. Attributes: device (str): A string specifying whether to use the GPU for calcul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PredictionLossProvider:
"""This class provides bundled access to multiple losses. With this class's :meth:`get_losses()` method, all specified loss values are calculated on the same input prediction and target tensor. Attributes: device (str): A string specifying whether to use the GPU for calculations (`cuda... | the_stack_v2_python_sparse | vp_suite/measure/loss_provider.py | AIS-Bonn/vp-suite | train | 18 |
4f65c9271a52088e10be6c8212ef72bf943ad9f8 | [
"try:\n return codecs.open(filename, 'r', 'utf-8').read()\nexcept IOError as e:\n TextFileReader.logger.exception(e)",
"try:\n return codecs.open(filename, 'r', 'utf-8').readlines()\nexcept IOError as e:\n TextFileReader.logger.exception(e)"
] | <|body_start_0|>
try:
return codecs.open(filename, 'r', 'utf-8').read()
except IOError as e:
TextFileReader.logger.exception(e)
<|end_body_0|>
<|body_start_1|>
try:
return codecs.open(filename, 'r', 'utf-8').readlines()
except IOError as e:
... | This class allows to read string data in utf-8 format from local storage. | TextFileReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextFileReader:
"""This class allows to read string data in utf-8 format from local storage."""
def read(filename):
"""Read entire file contents and return it as as string"""
<|body_0|>
def read_lines(filename):
"""Read all the lines from file and return as a lis... | stack_v2_sparse_classes_36k_train_030134 | 922 | no_license | [
{
"docstring": "Read entire file contents and return it as as string",
"name": "read",
"signature": "def read(filename)"
},
{
"docstring": "Read all the lines from file and return as a list of strings",
"name": "read_lines",
"signature": "def read_lines(filename)"
}
] | 2 | null | Implement the Python class `TextFileReader` described below.
Class description:
This class allows to read string data in utf-8 format from local storage.
Method signatures and docstrings:
- def read(filename): Read entire file contents and return it as as string
- def read_lines(filename): Read all the lines from fil... | Implement the Python class `TextFileReader` described below.
Class description:
This class allows to read string data in utf-8 format from local storage.
Method signatures and docstrings:
- def read(filename): Read entire file contents and return it as as string
- def read_lines(filename): Read all the lines from fil... | 653c1e7a96481c0b16617a8863ff8a56f5024d0a | <|skeleton|>
class TextFileReader:
"""This class allows to read string data in utf-8 format from local storage."""
def read(filename):
"""Read entire file contents and return it as as string"""
<|body_0|>
def read_lines(filename):
"""Read all the lines from file and return as a lis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextFileReader:
"""This class allows to read string data in utf-8 format from local storage."""
def read(filename):
"""Read entire file contents and return it as as string"""
try:
return codecs.open(filename, 'r', 'utf-8').read()
except IOError as e:
TextFi... | the_stack_v2_python_sparse | src/outerspaceaccess/text_file_reader.py | mateuszmidor/DwellingDigger | train | 1 |
c91dd992709d88651fec3722fb89e5d336d91db0 | [
"ans = []\nself.dfs_search(ans, '', num, target, 0, 0, 0)\nreturn ans",
"if pos == len(num):\n if value == target:\n ans.append(path)\n return\nfor i in range(pos + 1, len(num) + 1):\n cur_str, cur_n = (num[pos:i], int(num[pos:i]))\n if i > pos + 1 and num[pos] == '0':\n break\n if po... | <|body_start_0|>
ans = []
self.dfs_search(ans, '', num, target, 0, 0, 0)
return ans
<|end_body_0|>
<|body_start_1|>
if pos == len(num):
if value == target:
ans.append(path)
return
for i in range(pos + 1, len(num) + 1):
cur_str,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addOperators(self, num, target):
"""Once you can understand the solution space tree, you just get it. Refer to: https://discuss.leetcode.com/topic/24523/java-standard-backtrace-ac-solutoin-short-and-clear"""
<|body_0|>
def dfs_search(self, ans, path, num, targe... | stack_v2_sparse_classes_36k_train_030135 | 1,759 | no_license | [
{
"docstring": "Once you can understand the solution space tree, you just get it. Refer to: https://discuss.leetcode.com/topic/24523/java-standard-backtrace-ac-solutoin-short-and-clear",
"name": "addOperators",
"signature": "def addOperators(self, num, target)"
},
{
"docstring": "Put binary oper... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addOperators(self, num, target): Once you can understand the solution space tree, you just get it. Refer to: https://discuss.leetcode.com/topic/24523/java-standard-backtrace-... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addOperators(self, num, target): Once you can understand the solution space tree, you just get it. Refer to: https://discuss.leetcode.com/topic/24523/java-standard-backtrace-... | be331826b490b73f0a176e6abed86ef68ff2dd2b | <|skeleton|>
class Solution:
def addOperators(self, num, target):
"""Once you can understand the solution space tree, you just get it. Refer to: https://discuss.leetcode.com/topic/24523/java-standard-backtrace-ac-solutoin-short-and-clear"""
<|body_0|>
def dfs_search(self, ans, path, num, targe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def addOperators(self, num, target):
"""Once you can understand the solution space tree, you just get it. Refer to: https://discuss.leetcode.com/topic/24523/java-standard-backtrace-ac-solutoin-short-and-clear"""
ans = []
self.dfs_search(ans, '', num, target, 0, 0, 0)
... | the_stack_v2_python_sparse | 125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/DepthFirstSearch/282_ExpressionAddOperators.py | syurskyi/Python_Topics | train | 3 | |
ec5ca21bf6c095e3473ee9736fdb6501f78df077 | [
"self.driver.get(url)\nself.driver.max_window()\nself.driver.find_element(locator.HeaderLocator.Ibuycar).click()\nself.driver.pause(3)\nactual_bjbc = self.driver.find_element(locator.HeaderLocator.BJbuycar).text\nexpect_bjbc = '北京二手车'\ntt_check.assertEqual(expect_bjbc, actual_bjbc, '二手车列表面包屑,期望是%s,实际是%s' % (expect_... | <|body_start_0|>
self.driver.get(url)
self.driver.max_window()
self.driver.find_element(locator.HeaderLocator.Ibuycar).click()
self.driver.pause(3)
actual_bjbc = self.driver.find_element(locator.HeaderLocator.BJbuycar).text
expect_bjbc = '北京二手车'
tt_check.assertEqu... | buycar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class buycar:
def test_Ibuycar(self):
"""测试首页我要买车跳转,@author:xulanzhong"""
<|body_0|>
def test_car_price(self):
"""测试首页我要买车-价格跳转,@author:xulanzhong"""
<|body_1|>
def test_brand_name(self):
"""测试首页我要买车-品牌跳转,@author:xulanzhong"""
<|body_2|>
d... | stack_v2_sparse_classes_36k_train_030136 | 2,569 | no_license | [
{
"docstring": "测试首页我要买车跳转,@author:xulanzhong",
"name": "test_Ibuycar",
"signature": "def test_Ibuycar(self)"
},
{
"docstring": "测试首页我要买车-价格跳转,@author:xulanzhong",
"name": "test_car_price",
"signature": "def test_car_price(self)"
},
{
"docstring": "测试首页我要买车-品牌跳转,@author:xulanzhon... | 4 | null | Implement the Python class `buycar` described below.
Class description:
Implement the buycar class.
Method signatures and docstrings:
- def test_Ibuycar(self): 测试首页我要买车跳转,@author:xulanzhong
- def test_car_price(self): 测试首页我要买车-价格跳转,@author:xulanzhong
- def test_brand_name(self): 测试首页我要买车-品牌跳转,@author:xulanzhong
- def... | Implement the Python class `buycar` described below.
Class description:
Implement the buycar class.
Method signatures and docstrings:
- def test_Ibuycar(self): 测试首页我要买车跳转,@author:xulanzhong
- def test_car_price(self): 测试首页我要买车-价格跳转,@author:xulanzhong
- def test_brand_name(self): 测试首页我要买车-品牌跳转,@author:xulanzhong
- def... | 204856bd33c06d25f2970eba13799db75d4fd4fe | <|skeleton|>
class buycar:
def test_Ibuycar(self):
"""测试首页我要买车跳转,@author:xulanzhong"""
<|body_0|>
def test_car_price(self):
"""测试首页我要买车-价格跳转,@author:xulanzhong"""
<|body_1|>
def test_brand_name(self):
"""测试首页我要买车-品牌跳转,@author:xulanzhong"""
<|body_2|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class buycar:
def test_Ibuycar(self):
"""测试首页我要买车跳转,@author:xulanzhong"""
self.driver.get(url)
self.driver.max_window()
self.driver.find_element(locator.HeaderLocator.Ibuycar).click()
self.driver.pause(3)
actual_bjbc = self.driver.find_element(locator.HeaderLocator.BJ... | the_stack_v2_python_sparse | mc/taochePC/test_crawler/test_homepage/test_buycarlink.py | boeai/mc | train | 0 | |
b3d45fbcfc82240332354bca5dbe5c5e20f7d859 | [
"data = request.form\nuid = g.uid\nuser = User.with_id(uid)\nfor key in data:\n if key not in ('nickname', 'github', 'avatar', 'favorite_public'):\n continue\n setattr(user, key, data[key])\ntry:\n user.save()\nexcept NotUniqueError:\n raise ArgsError(message='昵称已经被使用!')\nelse:\n return {'payl... | <|body_start_0|>
data = request.form
uid = g.uid
user = User.with_id(uid)
for key in data:
if key not in ('nickname', 'github', 'avatar', 'favorite_public'):
continue
setattr(user, key, data[key])
try:
user.save()
except... | UserSettings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSettings:
def post(self):
"""@apiVersion 1.0.0 @api {post} /api/settings 修改个人信息 @apiName UserSettings @apiGroup User @apiParam {String} nickname 昵称 @apiParam {String} github Github @apiParam {String} avatar 头像 @apiParam {Boolean} favorite_public 公开个人收藏 @apiSuccess {Integer} code 0 @a... | stack_v2_sparse_classes_36k_train_030137 | 8,793 | no_license | [
{
"docstring": "@apiVersion 1.0.0 @api {post} /api/settings 修改个人信息 @apiName UserSettings @apiGroup User @apiParam {String} nickname 昵称 @apiParam {String} github Github @apiParam {String} avatar 头像 @apiParam {Boolean} favorite_public 公开个人收藏 @apiSuccess {Integer} code 0 @apiSuccessExample {json} Success-Response:... | 2 | stack_v2_sparse_classes_30k_train_011258 | Implement the Python class `UserSettings` described below.
Class description:
Implement the UserSettings class.
Method signatures and docstrings:
- def post(self): @apiVersion 1.0.0 @api {post} /api/settings 修改个人信息 @apiName UserSettings @apiGroup User @apiParam {String} nickname 昵称 @apiParam {String} github Github @a... | Implement the Python class `UserSettings` described below.
Class description:
Implement the UserSettings class.
Method signatures and docstrings:
- def post(self): @apiVersion 1.0.0 @api {post} /api/settings 修改个人信息 @apiName UserSettings @apiGroup User @apiParam {String} nickname 昵称 @apiParam {String} github Github @a... | 4b7fdfe3f2bcf3d3d0e0bc7c687b75991db1f2df | <|skeleton|>
class UserSettings:
def post(self):
"""@apiVersion 1.0.0 @api {post} /api/settings 修改个人信息 @apiName UserSettings @apiGroup User @apiParam {String} nickname 昵称 @apiParam {String} github Github @apiParam {String} avatar 头像 @apiParam {Boolean} favorite_public 公开个人收藏 @apiSuccess {Integer} code 0 @a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserSettings:
def post(self):
"""@apiVersion 1.0.0 @api {post} /api/settings 修改个人信息 @apiName UserSettings @apiGroup User @apiParam {String} nickname 昵称 @apiParam {String} github Github @apiParam {String} avatar 头像 @apiParam {Boolean} favorite_public 公开个人收藏 @apiSuccess {Integer} code 0 @apiSuccessExamp... | the_stack_v2_python_sparse | app/modules/accounts/apis.py | geasyheart/git-share | train | 0 | |
34c94db1c1bd67f3345968dead180bf9ab2de5ab | [
"ret = {}\nflags_map = {'Desired': {'u': 'Unknown', 'i': 'Install', 'r': 'Remove/Deinstall', 'p': 'Purge', 'h': 'Hold'}, 'Current': {'n': 'Not-installed', 'i': 'Installed', 'c': 'Only config Files are Installed', 'u': 'Unpacked', 'f': 'Configuration Failed (Half-Configured)', 'h': 'Installlation Failed (Half-Instal... | <|body_start_0|>
ret = {}
flags_map = {'Desired': {'u': 'Unknown', 'i': 'Install', 'r': 'Remove/Deinstall', 'p': 'Purge', 'h': 'Hold'}, 'Current': {'n': 'Not-installed', 'i': 'Installed', 'c': 'Only config Files are Installed', 'u': 'Unpacked', 'f': 'Configuration Failed (Half-Configured)', 'h': 'Instal... | Package management class for Ubuntu. | Ubuntu1204PackageImpl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ubuntu1204PackageImpl:
"""Package management class for Ubuntu."""
def are_installed(cls, client_object, packages=None):
"""Determines if the package(s) are installed on the system. @type client_object: BaseClient @param client_object: Used to pass commands to the host. @type packages... | stack_v2_sparse_classes_36k_train_030138 | 5,138 | no_license | [
{
"docstring": "Determines if the package(s) are installed on the system. @type client_object: BaseClient @param client_object: Used to pass commands to the host. @type packages: list @param packages: List of package names to query. @rtype: dict @return: Map from the package name to a tuple of (bool status of i... | 4 | null | Implement the Python class `Ubuntu1204PackageImpl` described below.
Class description:
Package management class for Ubuntu.
Method signatures and docstrings:
- def are_installed(cls, client_object, packages=None): Determines if the package(s) are installed on the system. @type client_object: BaseClient @param client_... | Implement the Python class `Ubuntu1204PackageImpl` described below.
Class description:
Package management class for Ubuntu.
Method signatures and docstrings:
- def are_installed(cls, client_object, packages=None): Determines if the package(s) are installed on the system. @type client_object: BaseClient @param client_... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class Ubuntu1204PackageImpl:
"""Package management class for Ubuntu."""
def are_installed(cls, client_object, packages=None):
"""Determines if the package(s) are installed on the system. @type client_object: BaseClient @param client_object: Used to pass commands to the host. @type packages... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ubuntu1204PackageImpl:
"""Package management class for Ubuntu."""
def are_installed(cls, client_object, packages=None):
"""Determines if the package(s) are installed on the system. @type client_object: BaseClient @param client_object: Used to pass commands to the host. @type packages: list @param... | the_stack_v2_python_sparse | SystemTesting/pylib/vmware/kvm/cmd/ubuntu1204_package_impl.py | Cloudxtreme/MyProject | train | 0 |
b4f094f3acaae113de6b40f75d4c9c2e27982b6a | [
"if isinstance(key, int):\n return Operation(key)\nif key not in Operation._member_map_:\n extend_enum(Operation, key, default)\nreturn Operation[key]",
"if not (isinstance(value, int) and 0 <= value <= 65535):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 26 <= value <= 65534:\n... | <|body_start_0|>
if isinstance(key, int):
return Operation(key)
if key not in Operation._member_map_:
extend_enum(Operation, key, default)
return Operation[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 65535):
r... | Enumeration class for Operation. | Operation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Operation:
"""Enumeration class for Operation."""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_030139 | 3,597 | no_license | [
{
"docstring": "Backport support for original codes.",
"name": "get",
"signature": "def get(key, default=-1)"
},
{
"docstring": "Lookup function used when value is not found.",
"name": "_missing_",
"signature": "def _missing_(cls, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005609 | Implement the Python class `Operation` described below.
Class description:
Enumeration class for Operation.
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found. | Implement the Python class `Operation` described below.
Class description:
Enumeration class for Operation.
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found.
<|skeleton|>
class Operation:
"... | fd43ccca1d032f8f230c4467dcb5df757669ef13 | <|skeleton|>
class Operation:
"""Enumeration class for Operation."""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Operation:
"""Enumeration class for Operation."""
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Operation(key)
if key not in Operation._member_map_:
extend_enum(Operation, key, default)
return O... | the_stack_v2_python_sparse | venv/lib/python3.6/site-packages/pcapkit/const/arp/operation.py | IvanLetteri/MLfeaturesExtractor | train | 0 |
0d52646991053be67e1fadf49adca0d6d2076320 | [
"self._user = None\nif 'user' in kwargs:\n self._user = kwargs.pop('user')\nself._org = None\nif 'org' in kwargs:\n self._org = kwargs.pop('org')\nsuper(NewRepoForm, self).__init__(*args, **kwargs)",
"if self.cleaned_data['survey_json'] is None and self.cleaned_data['xform_file'] is None:\n raise forms.V... | <|body_start_0|>
self._user = None
if 'user' in kwargs:
self._user = kwargs.pop('user')
self._org = None
if 'org' in kwargs:
self._org = kwargs.pop('org')
super(NewRepoForm, self).__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
if self.c... | Validates and creates a new repository based on creation data. Parameters ---------- forms.Form : Form Attributes ---------- name : string name of the form desc : string description of the form privacy survey_json : string, optional The JSON of the form as a string, only if creating a form from scratch xform_file : Fil... | NewRepoForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewRepoForm:
"""Validates and creates a new repository based on creation data. Parameters ---------- forms.Form : Form Attributes ---------- name : string name of the form desc : string description of the form privacy survey_json : string, optional The JSON of the form as a string, only if creati... | stack_v2_sparse_classes_36k_train_030140 | 10,381 | permissive | [
{
"docstring": "We pass in the current user/org to test for the uniqueness of the repository name in that current user's/org's list of repositories. Params ------ user : User org : Organization, optional If a user is acting on behalf of an organization, this needs to be set.",
"name": "__init__",
"signa... | 6 | stack_v2_sparse_classes_30k_train_013704 | Implement the Python class `NewRepoForm` described below.
Class description:
Validates and creates a new repository based on creation data. Parameters ---------- forms.Form : Form Attributes ---------- name : string name of the form desc : string description of the form privacy survey_json : string, optional The JSON ... | Implement the Python class `NewRepoForm` described below.
Class description:
Validates and creates a new repository based on creation data. Parameters ---------- forms.Form : Form Attributes ---------- name : string name of the form desc : string description of the form privacy survey_json : string, optional The JSON ... | 55edda0d8a62b9e5cf94567242aba481c5dc342c | <|skeleton|>
class NewRepoForm:
"""Validates and creates a new repository based on creation data. Parameters ---------- forms.Form : Form Attributes ---------- name : string name of the form desc : string description of the form privacy survey_json : string, optional The JSON of the form as a string, only if creati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewRepoForm:
"""Validates and creates a new repository based on creation data. Parameters ---------- forms.Form : Form Attributes ---------- name : string name of the form desc : string description of the form privacy survey_json : string, optional The JSON of the form as a string, only if creating a form fro... | the_stack_v2_python_sparse | keep_backend/repos/forms.py | ajermaky/keep | train | 0 |
b873dc0076fba7d52605f049c67d9224ed675d03 | [
"createdLocalSession = False\nif len(ids) == 0:\n return None\nif session == None:\n session = LogServiceDao.getSession()\n createdLocalSession = True\nselectedLogService = None\nrs = session.query(LogService).filter(LogService.id in ids)\nlogServices = []\nfor logService in rs:\n logger.debug('--getLog... | <|body_start_0|>
createdLocalSession = False
if len(ids) == 0:
return None
if session == None:
session = LogServiceDao.getSession()
createdLocalSession = True
selectedLogService = None
rs = session.query(LogService).filter(LogService.id in ids)... | classdocs | LogServiceDao | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogServiceDao:
"""classdocs"""
def getLogServices(cls, ids, session=None):
"""gets logsets of given ids from database"""
<|body_0|>
def getLogService(cls, id, session=None):
"""gets logset of given id from database"""
<|body_1|>
def getAllLogServices... | stack_v2_sparse_classes_36k_train_030141 | 3,229 | permissive | [
{
"docstring": "gets logsets of given ids from database",
"name": "getLogServices",
"signature": "def getLogServices(cls, ids, session=None)"
},
{
"docstring": "gets logset of given id from database",
"name": "getLogService",
"signature": "def getLogService(cls, id, session=None)"
},
... | 3 | stack_v2_sparse_classes_30k_train_015026 | Implement the Python class `LogServiceDao` described below.
Class description:
classdocs
Method signatures and docstrings:
- def getLogServices(cls, ids, session=None): gets logsets of given ids from database
- def getLogService(cls, id, session=None): gets logset of given id from database
- def getAllLogServicesForW... | Implement the Python class `LogServiceDao` described below.
Class description:
classdocs
Method signatures and docstrings:
- def getLogServices(cls, ids, session=None): gets logsets of given ids from database
- def getLogService(cls, id, session=None): gets logset of given id from database
- def getAllLogServicesForW... | 20fba1b1fd1a42add223d9e8af2d267665bec493 | <|skeleton|>
class LogServiceDao:
"""classdocs"""
def getLogServices(cls, ids, session=None):
"""gets logsets of given ids from database"""
<|body_0|>
def getLogService(cls, id, session=None):
"""gets logset of given id from database"""
<|body_1|>
def getAllLogServices... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogServiceDao:
"""classdocs"""
def getLogServices(cls, ids, session=None):
"""gets logsets of given ids from database"""
createdLocalSession = False
if len(ids) == 0:
return None
if session == None:
session = LogServiceDao.getSession()
c... | the_stack_v2_python_sparse | db/core/logservice/logservicedao.py | ABV-Hub/qreservoir | train | 0 |
7208702071b0565dfb3a53ba224dc09ca7d527c2 | [
"self.deployed_branch = ''\nself.deployment_templates = []\nself.configurations = []\nself.other_messages = []",
"self.deployed_branch = other_instruction.deployed_branch\nself.deployment_templates = other_instruction.deployment_templates + self.deployment_templates\nself.configurations = other_instruction.config... | <|body_start_0|>
self.deployed_branch = ''
self.deployment_templates = []
self.configurations = []
self.other_messages = []
<|end_body_0|>
<|body_start_1|>
self.deployed_branch = other_instruction.deployed_branch
self.deployment_templates = other_instruction.deployment_t... | Forseti setup instructions. | ForsetiInstructions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForsetiInstructions:
"""Forseti setup instructions."""
def __init__(self):
"""Init."""
<|body_0|>
def merge_head(self, other_instruction):
"""Merge instructions, input instructions will be merged to the head of the current instructions. Args: other_instruction (F... | stack_v2_sparse_classes_36k_train_030142 | 16,066 | permissive | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Merge instructions, input instructions will be merged to the head of the current instructions. Args: other_instruction (ForsetiInstructions): The other instructions.",
"name": "merge_head",
"... | 3 | null | Implement the Python class `ForsetiInstructions` described below.
Class description:
Forseti setup instructions.
Method signatures and docstrings:
- def __init__(self): Init.
- def merge_head(self, other_instruction): Merge instructions, input instructions will be merged to the head of the current instructions. Args:... | Implement the Python class `ForsetiInstructions` described below.
Class description:
Forseti setup instructions.
Method signatures and docstrings:
- def __init__(self): Init.
- def merge_head(self, other_instruction): Merge instructions, input instructions will be merged to the head of the current instructions. Args:... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class ForsetiInstructions:
"""Forseti setup instructions."""
def __init__(self):
"""Init."""
<|body_0|>
def merge_head(self, other_instruction):
"""Merge instructions, input instructions will be merged to the head of the current instructions. Args: other_instruction (F... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ForsetiInstructions:
"""Forseti setup instructions."""
def __init__(self):
"""Init."""
self.deployed_branch = ''
self.deployment_templates = []
self.configurations = []
self.other_messages = []
def merge_head(self, other_instruction):
"""Merge instruct... | the_stack_v2_python_sparse | install/gcp/installer/forseti_installer.py | kevensen/forseti-security | train | 1 |
c605c6e4c7b045e72915821f75547a0c916ce086 | [
"pk = uuid.uuid4()\nrequest = self.context['request']\nif not request.data.get('path'):\n raise serializers.ValidationError('没有上传文件')\nreturn SpecialScheme.objects.create(pk=pk, **validated_data)",
"instance.staff_id = validated_data.get('staff_id', instance.staff_id)\ninstance.name = validated_data.get('name'... | <|body_start_0|>
pk = uuid.uuid4()
request = self.context['request']
if not request.data.get('path'):
raise serializers.ValidationError('没有上传文件')
return SpecialScheme.objects.create(pk=pk, **validated_data)
<|end_body_0|>
<|body_start_1|>
instance.staff_id = validate... | 专项方案序列化器 | SpecialSchemeSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecialSchemeSerializer:
"""专项方案序列化器"""
def create(self, validated_data):
"""新建"""
<|body_0|>
def update(self, instance, validated_data):
"""更新,instance为要更新的对象实例"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pk = uuid.uuid4()
request =... | stack_v2_sparse_classes_36k_train_030143 | 1,636 | no_license | [
{
"docstring": "新建",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "更新,instance为要更新的对象实例",
"name": "update",
"signature": "def update(self, instance, validated_data)"
}
] | 2 | null | Implement the Python class `SpecialSchemeSerializer` described below.
Class description:
专项方案序列化器
Method signatures and docstrings:
- def create(self, validated_data): 新建
- def update(self, instance, validated_data): 更新,instance为要更新的对象实例 | Implement the Python class `SpecialSchemeSerializer` described below.
Class description:
专项方案序列化器
Method signatures and docstrings:
- def create(self, validated_data): 新建
- def update(self, instance, validated_data): 更新,instance为要更新的对象实例
<|skeleton|>
class SpecialSchemeSerializer:
"""专项方案序列化器"""
def create(... | 3645bc3a396727af208db924c6fdee38abc0f894 | <|skeleton|>
class SpecialSchemeSerializer:
"""专项方案序列化器"""
def create(self, validated_data):
"""新建"""
<|body_0|>
def update(self, instance, validated_data):
"""更新,instance为要更新的对象实例"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpecialSchemeSerializer:
"""专项方案序列化器"""
def create(self, validated_data):
"""新建"""
pk = uuid.uuid4()
request = self.context['request']
if not request.data.get('path'):
raise serializers.ValidationError('没有上传文件')
return SpecialScheme.objects.create(pk=pk... | the_stack_v2_python_sparse | ruidun_system/safe/serializers/specialscheme_serializer.py | TingxieLi/django-restframework | train | 0 |
92e8d5dcd5608d4eb55e72d63f16e40e152c3cf7 | [
"c = Counter(tasks)\nheap = [-v for v in c.values()]\nheapq.heapify(heap)\nqueue = deque()\ncurrTime = 0\nwhile heap or queue:\n if heap:\n coolDownTask = heapq.heappop(heap) + 1\n if coolDownTask:\n queue.append((coolDownTask, currTime + n))\n if queue and queue[0][1] == currTime:\n ... | <|body_start_0|>
c = Counter(tasks)
heap = [-v for v in c.values()]
heapq.heapify(heap)
queue = deque()
currTime = 0
while heap or queue:
if heap:
coolDownTask = heapq.heappop(heap) + 1
if coolDownTask:
queue... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
"""Min heap"""
<|body_0|>
def leastInterval(self, tasks: List[str], n: int) -> int:
"""Calculating Idle slots"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
c = Counter(tasks)
... | stack_v2_sparse_classes_36k_train_030144 | 1,296 | no_license | [
{
"docstring": "Min heap",
"name": "leastInterval",
"signature": "def leastInterval(self, tasks: List[str], n: int) -> int"
},
{
"docstring": "Calculating Idle slots",
"name": "leastInterval",
"signature": "def leastInterval(self, tasks: List[str], n: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_003640 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval(self, tasks: List[str], n: int) -> int: Min heap
- def leastInterval(self, tasks: List[str], n: int) -> int: Calculating Idle slots | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval(self, tasks: List[str], n: int) -> int: Min heap
- def leastInterval(self, tasks: List[str], n: int) -> int: Calculating Idle slots
<|skeleton|>
class Solution... | 5b8e974b9541a80dbb9e15055d76f78cd957637f | <|skeleton|>
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
"""Min heap"""
<|body_0|>
def leastInterval(self, tasks: List[str], n: int) -> int:
"""Calculating Idle slots"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
"""Min heap"""
c = Counter(tasks)
heap = [-v for v in c.values()]
heapq.heapify(heap)
queue = deque()
currTime = 0
while heap or queue:
if heap:
coolDownTask ... | the_stack_v2_python_sparse | coding_problems/may/may26.py | happy96026/interview-prep | train | 0 | |
25120cf5b2a9c7655d04e2cfa8d6122356c284ab | [
"if not root:\n return ''\nch = chr(ord('a') + root.val)\nif not root.left and (not root.right):\n return ch\nl = self.smallestFromLeaf(root.left) + ch\nr = self.smallestFromLeaf(root.right) + ch\nreturn min(l, r)",
"if not root:\n return\n\ndef dfs(root, path):\n if not root:\n return\n ch ... | <|body_start_0|>
if not root:
return ''
ch = chr(ord('a') + root.val)
if not root.left and (not root.right):
return ch
l = self.smallestFromLeaf(root.left) + ch
r = self.smallestFromLeaf(root.right) + ch
return min(l, r)
<|end_body_0|>
<|body_star... | 分治法是不对的:min root = min(left, right) + root.val 这是因为,如果left是right的前缀串,这样的话一定是left小,但其实这样是不一定的 所以就只能老老实实计算路径 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""分治法是不对的:min root = min(left, right) + root.val 这是因为,如果left是right的前缀串,这样的话一定是left小,但其实这样是不一定的 所以就只能老老实实计算路径"""
def smallestFromLeaf(self, root):
""":type root: TreeNode :rtype: str"""
<|body_0|>
def smallestFromLeaf(self, root):
""":type root: TreeNod... | stack_v2_sparse_classes_36k_train_030145 | 2,049 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: str",
"name": "smallestFromLeaf",
"signature": "def smallestFromLeaf(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: str",
"name": "smallestFromLeaf",
"signature": "def smallestFromLeaf(self, root)"
},
{
"docstring": ":typ... | 3 | stack_v2_sparse_classes_30k_train_004472 | Implement the Python class `Solution` described below.
Class description:
分治法是不对的:min root = min(left, right) + root.val 这是因为,如果left是right的前缀串,这样的话一定是left小,但其实这样是不一定的 所以就只能老老实实计算路径
Method signatures and docstrings:
- def smallestFromLeaf(self, root): :type root: TreeNode :rtype: str
- def smallestFromLeaf(self, root)... | Implement the Python class `Solution` described below.
Class description:
分治法是不对的:min root = min(left, right) + root.val 这是因为,如果left是right的前缀串,这样的话一定是left小,但其实这样是不一定的 所以就只能老老实实计算路径
Method signatures and docstrings:
- def smallestFromLeaf(self, root): :type root: TreeNode :rtype: str
- def smallestFromLeaf(self, root)... | 31012a004ba14ddfb468a91925d86bc2dfb60dd4 | <|skeleton|>
class Solution:
"""分治法是不对的:min root = min(left, right) + root.val 这是因为,如果left是right的前缀串,这样的话一定是left小,但其实这样是不一定的 所以就只能老老实实计算路径"""
def smallestFromLeaf(self, root):
""":type root: TreeNode :rtype: str"""
<|body_0|>
def smallestFromLeaf(self, root):
""":type root: TreeNod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""分治法是不对的:min root = min(left, right) + root.val 这是因为,如果left是right的前缀串,这样的话一定是left小,但其实这样是不一定的 所以就只能老老实实计算路径"""
def smallestFromLeaf(self, root):
""":type root: TreeNode :rtype: str"""
if not root:
return ''
ch = chr(ord('a') + root.val)
if not root.... | the_stack_v2_python_sparse | tree/SmallestStringStartingFromLeaf.py | yuhangxiaocs/LeetCodePy | train | 1 |
bd8a71e699936dc504bd5d0d9213d6b1e51f137c | [
"active_objects = self.model.objects.all().annotate(number_of_entries=Count('chapter'))\nfor active_object in active_objects:\n yield (str(active_object.pk), ungettext_lazy('%(item)s (%(count)i chapter)', '%(item)s (%(count)i chapters)', active_object.number_of_entries) % {'item': active_object.__unicode__(), 'c... | <|body_start_0|>
active_objects = self.model.objects.all().annotate(number_of_entries=Count('chapter'))
for active_object in active_objects:
yield (str(active_object.pk), ungettext_lazy('%(item)s (%(count)i chapter)', '%(item)s (%(count)i chapters)', active_object.number_of_entries) % {'item... | List filter for EntryAdmin with published authors only. | LanguageFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageFilter:
"""List filter for EntryAdmin with published authors only."""
def lookups(self, request, model_admin):
"""Return published objects with the number of entries."""
<|body_0|>
def queryset(self, request, queryset):
"""Return the object's entries if a... | stack_v2_sparse_classes_36k_train_030146 | 2,151 | no_license | [
{
"docstring": "Return published objects with the number of entries.",
"name": "lookups",
"signature": "def lookups(self, request, model_admin)"
},
{
"docstring": "Return the object's entries if a value is set.",
"name": "queryset",
"signature": "def queryset(self, request, queryset)"
... | 2 | null | Implement the Python class `LanguageFilter` described below.
Class description:
List filter for EntryAdmin with published authors only.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Return published objects with the number of entries.
- def queryset(self, request, queryset): Return the ... | Implement the Python class `LanguageFilter` described below.
Class description:
List filter for EntryAdmin with published authors only.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Return published objects with the number of entries.
- def queryset(self, request, queryset): Return the ... | fff62a14d067bf8a18a0ccc957e6cce6eb099167 | <|skeleton|>
class LanguageFilter:
"""List filter for EntryAdmin with published authors only."""
def lookups(self, request, model_admin):
"""Return published objects with the number of entries."""
<|body_0|>
def queryset(self, request, queryset):
"""Return the object's entries if a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LanguageFilter:
"""List filter for EntryAdmin with published authors only."""
def lookups(self, request, model_admin):
"""Return published objects with the number of entries."""
active_objects = self.model.objects.all().annotate(number_of_entries=Count('chapter'))
for active_objec... | the_stack_v2_python_sparse | book/admin/chapter_admin.py | squallcs12/tangthuvien | train | 0 |
123fed566c7edaf87e49be738b832bd0dfc257e0 | [
"detalle_delivery_compra = get_detalle_delivery_compra_id(id_detalle_delivery_compra)\nif not detalle_delivery_compra:\n api.abort(404)\nelse:\n return detalle_delivery_compra",
"data = request.json\ndetalle_delivery_compra = update_detalle_delivery_compra(id_detalle_delivery_compra, data)\nif not detalle_d... | <|body_start_0|>
detalle_delivery_compra = get_detalle_delivery_compra_id(id_detalle_delivery_compra)
if not detalle_delivery_compra:
api.abort(404)
else:
return detalle_delivery_compra
<|end_body_0|>
<|body_start_1|>
data = request.json
detalle_delivery_... | Detalle_delivery_compra | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Detalle_delivery_compra:
def get(self, id_detalle_delivery_compra):
"""get a detalle_delivery_compra given its identifier"""
<|body_0|>
def put(self, id_detalle_delivery_compra):
"""update a detalle_delivery_compra given its identifier"""
<|body_1|>
def ... | stack_v2_sparse_classes_36k_train_030147 | 2,529 | no_license | [
{
"docstring": "get a detalle_delivery_compra given its identifier",
"name": "get",
"signature": "def get(self, id_detalle_delivery_compra)"
},
{
"docstring": "update a detalle_delivery_compra given its identifier",
"name": "put",
"signature": "def put(self, id_detalle_delivery_compra)"
... | 3 | stack_v2_sparse_classes_30k_train_001954 | Implement the Python class `Detalle_delivery_compra` described below.
Class description:
Implement the Detalle_delivery_compra class.
Method signatures and docstrings:
- def get(self, id_detalle_delivery_compra): get a detalle_delivery_compra given its identifier
- def put(self, id_detalle_delivery_compra): update a ... | Implement the Python class `Detalle_delivery_compra` described below.
Class description:
Implement the Detalle_delivery_compra class.
Method signatures and docstrings:
- def get(self, id_detalle_delivery_compra): get a detalle_delivery_compra given its identifier
- def put(self, id_detalle_delivery_compra): update a ... | e3e6d716102280e73932e5eba65b2ff27eec45e0 | <|skeleton|>
class Detalle_delivery_compra:
def get(self, id_detalle_delivery_compra):
"""get a detalle_delivery_compra given its identifier"""
<|body_0|>
def put(self, id_detalle_delivery_compra):
"""update a detalle_delivery_compra given its identifier"""
<|body_1|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Detalle_delivery_compra:
def get(self, id_detalle_delivery_compra):
"""get a detalle_delivery_compra given its identifier"""
detalle_delivery_compra = get_detalle_delivery_compra_id(id_detalle_delivery_compra)
if not detalle_delivery_compra:
api.abort(404)
else:
... | the_stack_v2_python_sparse | app/main/controller/detalle_delivery_compra_controller.py | Team-3-TCS/api-my-store | train | 1 | |
7034424a1448f2ac99a0906760fe2ccec7c69aee | [
"super(MonotonicMixingNetwork, self).__init__(name=name)\nself._agent_networks = agent_networks\nself._n_agents = n_agents\nself._qmix_hidden_dim = qmix_hidden_dim\nself._num_hypernet_layers = num_hypernet_layers\nself._hypernet_hidden_dim = hypernet_hidden_dim\nself._hypernetworks = HyperNetwork(self._agent_networ... | <|body_start_0|>
super(MonotonicMixingNetwork, self).__init__(name=name)
self._agent_networks = agent_networks
self._n_agents = n_agents
self._qmix_hidden_dim = qmix_hidden_dim
self._num_hypernet_layers = num_hypernet_layers
self._hypernet_hidden_dim = hypernet_hidden_dim... | Multi-agent monotonic mixing architecture. This is the component which can be used to add monotonic mixing to an underlying agent architecture. It currently supports generalised monotonic mixing using hypernetworks (1 or 2 layers) for control of decomposition parameters (QMix). | MonotonicMixingNetwork | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonotonicMixingNetwork:
"""Multi-agent monotonic mixing architecture. This is the component which can be used to add monotonic mixing to an underlying agent architecture. It currently supports generalised monotonic mixing using hypernetworks (1 or 2 layers) for control of decomposition parameters... | stack_v2_sparse_classes_36k_train_030148 | 3,403 | permissive | [
{
"docstring": "Initializes the mixer. Args: state_shape: The state shape as defined by the environment. n_agents: The number of agents (i.e. Q-values) to mix. qmix_hidden_dim: Mixing layers hidden dimensions. num_hypernet_layers: Number of hypernetwork layers. Currently 1 or 2. hypernet_hidden_dim: The number ... | 2 | null | Implement the Python class `MonotonicMixingNetwork` described below.
Class description:
Multi-agent monotonic mixing architecture. This is the component which can be used to add monotonic mixing to an underlying agent architecture. It currently supports generalised monotonic mixing using hypernetworks (1 or 2 layers) ... | Implement the Python class `MonotonicMixingNetwork` described below.
Class description:
Multi-agent monotonic mixing architecture. This is the component which can be used to add monotonic mixing to an underlying agent architecture. It currently supports generalised monotonic mixing using hypernetworks (1 or 2 layers) ... | eacdc81db2fde105b951b84fe2e99f56ef866340 | <|skeleton|>
class MonotonicMixingNetwork:
"""Multi-agent monotonic mixing architecture. This is the component which can be used to add monotonic mixing to an underlying agent architecture. It currently supports generalised monotonic mixing using hypernetworks (1 or 2 layers) for control of decomposition parameters... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MonotonicMixingNetwork:
"""Multi-agent monotonic mixing architecture. This is the component which can be used to add monotonic mixing to an underlying agent architecture. It currently supports generalised monotonic mixing using hypernetworks (1 or 2 layers) for control of decomposition parameters (QMix)."""
... | the_stack_v2_python_sparse | multi-agent RL/Mava-develop/mava/components/tf/networks/monotonic.py | NetColby/DNRL | train | 0 |
bac662a2ecfdd80a4b669b79de86cc2363323e0c | [
"server, validation_resources = self._create_server()\nif CONF.validation.run_validation:\n linux_client = remote_client.RemoteClient(self.get_server_ip(server, validation_resources), self.image_ssh_user, self.image_ssh_password, validation_resources['keypair']['private_key'], server=server, servers_client=self.... | <|body_start_0|>
server, validation_resources = self._create_server()
if CONF.validation.run_validation:
linux_client = remote_client.RemoteClient(self.get_server_ip(server, validation_resources), self.image_ssh_user, self.image_ssh_password, validation_resources['keypair']['private_key'], s... | Test attaching volume to server | AttachVolumeTestJSON | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttachVolumeTestJSON:
"""Test attaching volume to server"""
def test_attach_detach_volume(self):
"""Test attaching and detaching volume from server Stop and Start a server with an attached volume, ensuring that the volume remains attached."""
<|body_0|>
def test_list_get... | stack_v2_sparse_classes_36k_train_030149 | 23,311 | permissive | [
{
"docstring": "Test attaching and detaching volume from server Stop and Start a server with an attached volume, ensuring that the volume remains attached.",
"name": "test_attach_detach_volume",
"signature": "def test_attach_detach_volume(self)"
},
{
"docstring": "Test listing and getting volume... | 2 | null | Implement the Python class `AttachVolumeTestJSON` described below.
Class description:
Test attaching volume to server
Method signatures and docstrings:
- def test_attach_detach_volume(self): Test attaching and detaching volume from server Stop and Start a server with an attached volume, ensuring that the volume remai... | Implement the Python class `AttachVolumeTestJSON` described below.
Class description:
Test attaching volume to server
Method signatures and docstrings:
- def test_attach_detach_volume(self): Test attaching and detaching volume from server Stop and Start a server with an attached volume, ensuring that the volume remai... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class AttachVolumeTestJSON:
"""Test attaching volume to server"""
def test_attach_detach_volume(self):
"""Test attaching and detaching volume from server Stop and Start a server with an attached volume, ensuring that the volume remains attached."""
<|body_0|>
def test_list_get... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttachVolumeTestJSON:
"""Test attaching volume to server"""
def test_attach_detach_volume(self):
"""Test attaching and detaching volume from server Stop and Start a server with an attached volume, ensuring that the volume remains attached."""
server, validation_resources = self._create_se... | the_stack_v2_python_sparse | tempest/api/compute/volumes/test_attach_volume.py | openstack/tempest | train | 270 |
bb9ec6ba0f4c8a09de04c545ffd12c6477dc9617 | [
"self.user_id = user_id\nself.company_id = company_id\nself.modified_time = modified_time\nself.ip_address = ip_address\nself.session_token = session_token\nself.user_agent_string = user_agent_string\nself.metadata = metadata\nself.campaign = campaign\nself.names = {'user_id': 'user_id', 'company_id': 'company_id',... | <|body_start_0|>
self.user_id = user_id
self.company_id = company_id
self.modified_time = modified_time
self.ip_address = ip_address
self.session_token = session_token
self.user_agent_string = user_agent_string
self.metadata = metadata
self.campaign = camp... | Implementation of the 'models.UserModel' model. API Request Attributes: user_id (string): the id of the user. modified_time (DateTime): Time when modification is made. ip_address (string): IP Address of the client if known. session_token (string): session token of the user if known. user_agent_string (string): the stri... | UserModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserModel:
"""Implementation of the 'models.UserModel' model. API Request Attributes: user_id (string): the id of the user. modified_time (DateTime): Time when modification is made. ip_address (string): IP Address of the client if known. session_token (string): session token of the user if known.... | stack_v2_sparse_classes_36k_train_030150 | 3,470 | permissive | [
{
"docstring": "Constructor for the UserModel class",
"name": "__init__",
"signature": "def __init__(self, user_id=None, company_id=None, modified_time=None, ip_address=None, session_token=None, user_agent_string=None, metadata=None, campaign=None)"
},
{
"docstring": "Creates an instance of this... | 2 | stack_v2_sparse_classes_30k_train_001051 | Implement the Python class `UserModel` described below.
Class description:
Implementation of the 'models.UserModel' model. API Request Attributes: user_id (string): the id of the user. modified_time (DateTime): Time when modification is made. ip_address (string): IP Address of the client if known. session_token (strin... | Implement the Python class `UserModel` described below.
Class description:
Implementation of the 'models.UserModel' model. API Request Attributes: user_id (string): the id of the user. modified_time (DateTime): Time when modification is made. ip_address (string): IP Address of the client if known. session_token (strin... | e65347f1c4fe6ef014648db4e3b25d0392f820d0 | <|skeleton|>
class UserModel:
"""Implementation of the 'models.UserModel' model. API Request Attributes: user_id (string): the id of the user. modified_time (DateTime): Time when modification is made. ip_address (string): IP Address of the client if known. session_token (string): session token of the user if known.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserModel:
"""Implementation of the 'models.UserModel' model. API Request Attributes: user_id (string): the id of the user. modified_time (DateTime): Time when modification is made. ip_address (string): IP Address of the client if known. session_token (string): session token of the user if known. user_agent_s... | the_stack_v2_python_sparse | moesifapi/models/user_model.py | Moesif/moesifapi-python | train | 5 |
3935a5406927ee70fe9136c685cba75f7cfb571e | [
"if self.request_token is None:\n redirect_url = build_absolute_uri(self.request, self.callback_url)\n headers = {'X-Accept': 'application/json'}\n data = {'consumer_key': self.consumer_key, 'redirect_uri': redirect_url}\n response = requests.post(url=self.request_token_url, json=data, headers=headers)\... | <|body_start_0|>
if self.request_token is None:
redirect_url = build_absolute_uri(self.request, self.callback_url)
headers = {'X-Accept': 'application/json'}
data = {'consumer_key': self.consumer_key, 'redirect_uri': redirect_url}
response = requests.post(url=self... | PocketOAuthClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PocketOAuthClient:
def _get_request_token(self):
"""Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token"""
<|body_0|>
def get_redirect(self, authorization_url, extra_params):
"""Returns a ``HttpResponseRedi... | stack_v2_sparse_classes_36k_train_030151 | 3,273 | permissive | [
{
"docstring": "Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token",
"name": "_get_request_token",
"signature": "def _get_request_token(self)"
},
{
"docstring": "Returns a ``HttpResponseRedirect`` object to redirect the user to the Po... | 3 | stack_v2_sparse_classes_30k_train_004168 | Implement the Python class `PocketOAuthClient` described below.
Class description:
Implement the PocketOAuthClient class.
Method signatures and docstrings:
- def _get_request_token(self): Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token
- def get_redirec... | Implement the Python class `PocketOAuthClient` described below.
Class description:
Implement the PocketOAuthClient class.
Method signatures and docstrings:
- def _get_request_token(self): Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token
- def get_redirec... | 6b8911a5ebbabda0d446f2743bd4d00d250ed500 | <|skeleton|>
class PocketOAuthClient:
def _get_request_token(self):
"""Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token"""
<|body_0|>
def get_redirect(self, authorization_url, extra_params):
"""Returns a ``HttpResponseRedi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PocketOAuthClient:
def _get_request_token(self):
"""Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token"""
if self.request_token is None:
redirect_url = build_absolute_uri(self.request, self.callback_url)
head... | the_stack_v2_python_sparse | allauth/socialaccount/providers/pocket/client.py | pennersr/django-allauth | train | 7,719 | |
108ef9158003c85fcde1772a5e4a57f7a0e3fd1d | [
"self.bucket_name = bucket_name\nself.file_name = file_name\nself.celebrities = []\nself.orientation_correction = None\nself.recognition_response = None\nself.recognition_service = AWSRekognition()\nsuper(RecognizeCelebrity, self).__init__(prefix='RE', phase_name='Recognition', invocation_id=invocation_id)",
"if ... | <|body_start_0|>
self.bucket_name = bucket_name
self.file_name = file_name
self.celebrities = []
self.orientation_correction = None
self.recognition_response = None
self.recognition_service = AWSRekognition()
super(RecognizeCelebrity, self).__init__(prefix='RE', p... | Celebrity recognition object, responsible for accessing celebrity recognition API using a file storage stored image. Is also responsible for validating and processing the response. | RecognizeCelebrity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecognizeCelebrity:
"""Celebrity recognition object, responsible for accessing celebrity recognition API using a file storage stored image. Is also responsible for validating and processing the response."""
def __init__(self, bucket_name: str, file_name: str, invocation_id: str):
"""... | stack_v2_sparse_classes_36k_train_030152 | 5,253 | no_license | [
{
"docstring": "Constructor of the celebrity recognition object, stores provided and locally generated data, runs main object procedure. :param bucket_name: file storage location. :param file_name: stored file name. :param invocation_id: string containing id of current cloud function invocation to be to be used... | 4 | stack_v2_sparse_classes_30k_train_011006 | Implement the Python class `RecognizeCelebrity` described below.
Class description:
Celebrity recognition object, responsible for accessing celebrity recognition API using a file storage stored image. Is also responsible for validating and processing the response.
Method signatures and docstrings:
- def __init__(self... | Implement the Python class `RecognizeCelebrity` described below.
Class description:
Celebrity recognition object, responsible for accessing celebrity recognition API using a file storage stored image. Is also responsible for validating and processing the response.
Method signatures and docstrings:
- def __init__(self... | 8f1b94518303c4e0a38df1ff6caa0e7326451d67 | <|skeleton|>
class RecognizeCelebrity:
"""Celebrity recognition object, responsible for accessing celebrity recognition API using a file storage stored image. Is also responsible for validating and processing the response."""
def __init__(self, bucket_name: str, file_name: str, invocation_id: str):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecognizeCelebrity:
"""Celebrity recognition object, responsible for accessing celebrity recognition API using a file storage stored image. Is also responsible for validating and processing the response."""
def __init__(self, bucket_name: str, file_name: str, invocation_id: str):
"""Constructor o... | the_stack_v2_python_sparse | Serverless/handlers/sqs_celebrity_recognition/celebrity_recognition.py | RogerVFbr/MyCelebs | train | 0 |
12f6fa59b3629c627673e7e4078a8547a6b87181 | [
"env_names = []\nfor env_name in list(external_dccs.keys()):\n env_data = external_dccs[env_name]\n env_names.append(name_format.replace('%n', env_data['name']).replace('%e', env_data['extensions'][0]))\nreturn env_names",
"if not isinstance(name, str):\n raise TypeError('\"name\" argument in %s.get_env(... | <|body_start_0|>
env_names = []
for env_name in list(external_dccs.keys()):
env_data = external_dccs[env_name]
env_names.append(name_format.replace('%n', env_data['name']).replace('%e', env_data['extensions'][0]))
return env_names
<|end_body_0|>
<|body_start_1|>
... | A factory for External DCCs. A Factory object for DCCs. Generates :class:`ExternalDCC` instances. | ExternalDCCFactory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExternalDCCFactory:
"""A factory for External DCCs. A Factory object for DCCs. Generates :class:`ExternalDCC` instances."""
def get_env_names(cls, name_format='%n'):
"""returns a list of DCC names which it is possible to create one DCC. :param str name_format: A string showing the fo... | stack_v2_sparse_classes_36k_train_030153 | 10,666 | permissive | [
{
"docstring": "returns a list of DCC names which it is possible to create one DCC. :param str name_format: A string showing the format of the output variables: %n : the name of the Environment %e : the extension of the Environment :return list: list",
"name": "get_env_names",
"signature": "def get_env_... | 2 | stack_v2_sparse_classes_30k_train_006626 | Implement the Python class `ExternalDCCFactory` described below.
Class description:
A factory for External DCCs. A Factory object for DCCs. Generates :class:`ExternalDCC` instances.
Method signatures and docstrings:
- def get_env_names(cls, name_format='%n'): returns a list of DCC names which it is possible to create... | Implement the Python class `ExternalDCCFactory` described below.
Class description:
A factory for External DCCs. A Factory object for DCCs. Generates :class:`ExternalDCC` instances.
Method signatures and docstrings:
- def get_env_names(cls, name_format='%n'): returns a list of DCC names which it is possible to create... | 7b4cf60cb17f00435ecc3e03d573a9e2d0b44fe0 | <|skeleton|>
class ExternalDCCFactory:
"""A factory for External DCCs. A Factory object for DCCs. Generates :class:`ExternalDCC` instances."""
def get_env_names(cls, name_format='%n'):
"""returns a list of DCC names which it is possible to create one DCC. :param str name_format: A string showing the fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExternalDCCFactory:
"""A factory for External DCCs. A Factory object for DCCs. Generates :class:`ExternalDCC` instances."""
def get_env_names(cls, name_format='%n'):
"""returns a list of DCC names which it is possible to create one DCC. :param str name_format: A string showing the format of the o... | the_stack_v2_python_sparse | anima/dcc/external.py | eoyilmaz/anima | train | 113 |
1c1abc6534eabe9708d593c81417ce22b16bcb74 | [
"_thread.__init__(self)\nself._thread_loop_interval = 60 * 60\ntry:\n parent.threadsregistry.add('util', self)\nexcept:\n self.log.warning('Not adding to threadsregistry. Wrong context or other issue.')\nself.log = logging.getLogger('autopyfactory')\nself.log.debug('CleanLogs: Initializing object...')\nself.f... | <|body_start_0|>
_thread.__init__(self)
self._thread_loop_interval = 60 * 60
try:
parent.threadsregistry.add('util', self)
except:
self.log.warning('Not adding to threadsregistry. Wrong context or other issue.')
self.log = logging.getLogger('autopyfactory'... | ----------------------------------------------------------------------- Class to handle the log files removal. There are several possibilities to decide which files have to be deleted is: - basic algorithm is just to remove files older than some number of days. - based on disk space usage. We can keep files as long as ... | CleanLogs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CleanLogs:
"""----------------------------------------------------------------------- Class to handle the log files removal. There are several possibilities to decide which files have to be deleted is: - basic algorithm is just to remove files older than some number of days. - based on disk space... | stack_v2_sparse_classes_36k_train_030154 | 8,015 | permissive | [
{
"docstring": "parent is a reference to the Factory object that created the CleanLogs instance",
"name": "__init__",
"signature": "def __init__(self, parent, fcl, qcl=None)"
},
{
"docstring": "Main loop",
"name": "_run",
"signature": "def _run(self)"
},
{
"docstring": "loops ove... | 4 | null | Implement the Python class `CleanLogs` described below.
Class description:
----------------------------------------------------------------------- Class to handle the log files removal. There are several possibilities to decide which files have to be deleted is: - basic algorithm is just to remove files older than som... | Implement the Python class `CleanLogs` described below.
Class description:
----------------------------------------------------------------------- Class to handle the log files removal. There are several possibilities to decide which files have to be deleted is: - basic algorithm is just to remove files older than som... | 9d0d3890b38df2573045111182e45117ed232a46 | <|skeleton|>
class CleanLogs:
"""----------------------------------------------------------------------- Class to handle the log files removal. There are several possibilities to decide which files have to be deleted is: - basic algorithm is just to remove files older than some number of days. - based on disk space... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CleanLogs:
"""----------------------------------------------------------------------- Class to handle the log files removal. There are several possibilities to decide which files have to be deleted is: - basic algorithm is just to remove files older than some number of days. - based on disk space usage. We ca... | the_stack_v2_python_sparse | autopyfactory/cleanlogs.py | PanDAWMS/autopyfactory | train | 2 |
bccae5614247f49da1b5231b6325c11f03d59ebf | [
"self.relations = relations\nself.relations_func = relations_func\nself.pgm_type = pgm_type\nself.working_dir = working_dir + str(uuid.uuid4()) + '/'\nif os.path.exists(self.working_dir):\n shutil.rmtree(self.working_dir)\nos.makedirs(self.working_dir)",
"pgm_class = PSL if self.pgm_type == 'psl' else MRF\npgm... | <|body_start_0|>
self.relations = relations
self.relations_func = relations_func
self.pgm_type = pgm_type
self.working_dir = working_dir + str(uuid.uuid4()) + '/'
if os.path.exists(self.working_dir):
shutil.rmtree(self.working_dir)
os.makedirs(self.working_dir... | High-level class with multiple pgm implementations. | Joint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Joint:
"""High-level class with multiple pgm implementations."""
def __init__(self, relations, relations_func, pgm_type='psl', working_dir='.temp/'):
"""Initialization of joint inference class. Parameters ---------- relations : list (default=None) Relations to use for relational mode... | stack_v2_sparse_classes_36k_train_030155 | 2,186 | no_license | [
{
"docstring": "Initialization of joint inference class. Parameters ---------- relations : list (default=None) Relations to use for relational modeling. relations_func : func (default=None) Domain-dependent helper method to generate pgm files. pgm_type : str (default='psl') {'psl', 'mrf'} Type of PGM to use for... | 3 | stack_v2_sparse_classes_30k_train_011750 | Implement the Python class `Joint` described below.
Class description:
High-level class with multiple pgm implementations.
Method signatures and docstrings:
- def __init__(self, relations, relations_func, pgm_type='psl', working_dir='.temp/'): Initialization of joint inference class. Parameters ---------- relations :... | Implement the Python class `Joint` described below.
Class description:
High-level class with multiple pgm implementations.
Method signatures and docstrings:
- def __init__(self, relations, relations_func, pgm_type='psl', working_dir='.temp/'): Initialization of joint inference class. Parameters ---------- relations :... | e47d2e080edbbb7f8508acc9d7885eebf6f61bd6 | <|skeleton|>
class Joint:
"""High-level class with multiple pgm implementations."""
def __init__(self, relations, relations_func, pgm_type='psl', working_dir='.temp/'):
"""Initialization of joint inference class. Parameters ---------- relations : list (default=None) Relations to use for relational mode... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Joint:
"""High-level class with multiple pgm implementations."""
def __init__(self, relations, relations_func, pgm_type='psl', working_dir='.temp/'):
"""Initialization of joint inference class. Parameters ---------- relations : list (default=None) Relations to use for relational modeling. relatio... | the_stack_v2_python_sparse | EGGS/joint.py | anonymous78023/snspam | train | 0 |
04efef0997f435b033e8571bb0d927d682c68ac0 | [
"with mute_signals(post_save):\n user = UserFactory.create(email='fake@example.com')\ndata = UserSerializer(user).data\nassert data == {'username': user.username, 'email': 'fake@example.com', 'first_name': None, 'last_name': None, 'preferred_name': None, 'social_auth_providers': []}",
"with mute_signals(post_s... | <|body_start_0|>
with mute_signals(post_save):
user = UserFactory.create(email='fake@example.com')
data = UserSerializer(user).data
assert data == {'username': user.username, 'email': 'fake@example.com', 'first_name': None, 'last_name': None, 'preferred_name': None, 'social_auth_prov... | Tests for serializing users. | UserTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserTests:
"""Tests for serializing users."""
def test_basic_user(self):
"""Test serializing a basic user, no profile"""
<|body_0|>
def test_logged_in_user_through_maybe_wrapper(self):
"""Test serialize_maybe_user"""
<|body_1|>
def test_user_with_pro... | stack_v2_sparse_classes_36k_train_030156 | 2,560 | permissive | [
{
"docstring": "Test serializing a basic user, no profile",
"name": "test_basic_user",
"signature": "def test_basic_user(self)"
},
{
"docstring": "Test serialize_maybe_user",
"name": "test_logged_in_user_through_maybe_wrapper",
"signature": "def test_logged_in_user_through_maybe_wrapper(... | 3 | stack_v2_sparse_classes_30k_train_020710 | Implement the Python class `UserTests` described below.
Class description:
Tests for serializing users.
Method signatures and docstrings:
- def test_basic_user(self): Test serializing a basic user, no profile
- def test_logged_in_user_through_maybe_wrapper(self): Test serialize_maybe_user
- def test_user_with_profile... | Implement the Python class `UserTests` described below.
Class description:
Tests for serializing users.
Method signatures and docstrings:
- def test_basic_user(self): Test serializing a basic user, no profile
- def test_logged_in_user_through_maybe_wrapper(self): Test serialize_maybe_user
- def test_user_with_profile... | d6564caca0b7bbfd31e67a751564107fd17d6eb0 | <|skeleton|>
class UserTests:
"""Tests for serializing users."""
def test_basic_user(self):
"""Test serializing a basic user, no profile"""
<|body_0|>
def test_logged_in_user_through_maybe_wrapper(self):
"""Test serialize_maybe_user"""
<|body_1|>
def test_user_with_pro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserTests:
"""Tests for serializing users."""
def test_basic_user(self):
"""Test serializing a basic user, no profile"""
with mute_signals(post_save):
user = UserFactory.create(email='fake@example.com')
data = UserSerializer(user).data
assert data == {'username... | the_stack_v2_python_sparse | micromasters/serializers_test.py | mitodl/micromasters | train | 35 |
59781d4fd0cbfba2d8c0719ea0ffab2033269ac7 | [
"self.scale = scale\nself.bias = bias\nself.rgb = rgb",
"if image.shape[0] != requiredHeight or image.shape[1] != requiredWidth:\n image = cv2.resize(image, (requiredWidth, requiredHeight))\nif self.rgb:\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\nimage = image.astype(np.float32)\nif self.scale is not... | <|body_start_0|>
self.scale = scale
self.bias = bias
self.rgb = rgb
<|end_body_0|>
<|body_start_1|>
if image.shape[0] != requiredHeight or image.shape[1] != requiredWidth:
image = cv2.resize(image, (requiredWidth, requiredHeight))
if self.rgb:
image = cv2... | Preprocessor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Preprocessor:
def __init__(self, scale=None, bias=None, rgb=None):
"""Create a preprocessing object to handle image transformations required for network to run scale : float Scale factor applied to image after conversion to float bias : 3-element np.array Bias applied to image after scal... | stack_v2_sparse_classes_36k_train_030157 | 5,320 | permissive | [
{
"docstring": "Create a preprocessing object to handle image transformations required for network to run scale : float Scale factor applied to image after conversion to float bias : 3-element np.array Bias applied to image after scaling rgb : bool Set to true to convert 3 channel data to RGB (from BGR)",
"... | 2 | stack_v2_sparse_classes_30k_train_006362 | Implement the Python class `Preprocessor` described below.
Class description:
Implement the Preprocessor class.
Method signatures and docstrings:
- def __init__(self, scale=None, bias=None, rgb=None): Create a preprocessing object to handle image transformations required for network to run scale : float Scale factor ... | Implement the Python class `Preprocessor` described below.
Class description:
Implement the Preprocessor class.
Method signatures and docstrings:
- def __init__(self, scale=None, bias=None, rgb=None): Create a preprocessing object to handle image transformations required for network to run scale : float Scale factor ... | 1510ecbbb6b4a43b9f1f9503c87ec66216200677 | <|skeleton|>
class Preprocessor:
def __init__(self, scale=None, bias=None, rgb=None):
"""Create a preprocessing object to handle image transformations required for network to run scale : float Scale factor applied to image after conversion to float bias : 3-element np.array Bias applied to image after scal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Preprocessor:
def __init__(self, scale=None, bias=None, rgb=None):
"""Create a preprocessing object to handle image transformations required for network to run scale : float Scale factor applied to image after conversion to float bias : 3-element np.array Bias applied to image after scaling rgb : bool... | the_stack_v2_python_sparse | deploy_python/openem/models.py | bryan-flywire/openem | train | 0 | |
c207b50467df00b570a8f0ee7f5b59d041097fde | [
"x = sum(nums) - x\nif not x:\n return len(nums)\nsum_ = 0\nmin_steps = float('inf')\nmemo = {0: -1}\nfor i, n in enumerate(nums):\n sum_ += n\n min_steps = min(min_steps, memo.get(sum_ - x, float('inf')) + len(nums) - i)\n memo[sum_] = i\nreturn min_steps if min_steps < float('inf') else -1",
"x = su... | <|body_start_0|>
x = sum(nums) - x
if not x:
return len(nums)
sum_ = 0
min_steps = float('inf')
memo = {0: -1}
for i, n in enumerate(nums):
sum_ += n
min_steps = min(min_steps, memo.get(sum_ - x, float('inf')) + len(nums) - i)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minOperations(self, nums: List[int], x: int) -> int:
"""Computes the minimum number of operations needed to get sum x. Note that the sum of removed numbers is x if the sum of remaining numbers is sum(nums) - x. :param nums: non-empty list of positive integers :param x: sum ... | stack_v2_sparse_classes_36k_train_030158 | 3,104 | no_license | [
{
"docstring": "Computes the minimum number of operations needed to get sum x. Note that the sum of removed numbers is x if the sum of remaining numbers is sum(nums) - x. :param nums: non-empty list of positive integers :param x: sum to be reached :return: minimum number of steps, -1 otherwise Time complexity: ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minOperations(self, nums: List[int], x: int) -> int: Computes the minimum number of operations needed to get sum x. Note that the sum of removed numbers is x if the sum of re... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minOperations(self, nums: List[int], x: int) -> int: Computes the minimum number of operations needed to get sum x. Note that the sum of removed numbers is x if the sum of re... | ee8237b66975fb5584a3d68b311e762c0462c8aa | <|skeleton|>
class Solution:
def minOperations(self, nums: List[int], x: int) -> int:
"""Computes the minimum number of operations needed to get sum x. Note that the sum of removed numbers is x if the sum of remaining numbers is sum(nums) - x. :param nums: non-empty list of positive integers :param x: sum ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minOperations(self, nums: List[int], x: int) -> int:
"""Computes the minimum number of operations needed to get sum x. Note that the sum of removed numbers is x if the sum of remaining numbers is sum(nums) - x. :param nums: non-empty list of positive integers :param x: sum to be reached ... | the_stack_v2_python_sparse | LC1658-Minimum-Operations_to_reduce_X_to_zero.py | kate-melnykova/LeetCode-solutions | train | 2 | |
f8bf74a43aa572e1f351cc68efc5907ad7bbeda8 | [
"context = {}\ncontext['uom'] = move.product_uom.id\ncontext['location'] = move.location_id.id\nproduct = self.pool.get('product.product').browse(cr, uid, move.product_id.id, context=context)\npartial_move = super(stock_partial_picking, self)._partial_move_for(cr, uid, move)\npartial_move.update({'real_qty': produc... | <|body_start_0|>
context = {}
context['uom'] = move.product_uom.id
context['location'] = move.location_id.id
product = self.pool.get('product.product').browse(cr, uid, move.product_id.id, context=context)
partial_move = super(stock_partial_picking, self)._partial_move_for(cr, uid... | stock_partial_picking | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_partial_picking:
def _partial_move_for(self, cr, uid, move):
"""Inherit to add real stock quantity in partial move dict @param move: id of picking move @return: id"""
<|body_0|>
def do_partial(self, cr, uid, ids, context=None):
"""Inherit fuction to add constra... | stack_v2_sparse_classes_36k_train_030159 | 4,543 | no_license | [
{
"docstring": "Inherit to add real stock quantity in partial move dict @param move: id of picking move @return: id",
"name": "_partial_move_for",
"signature": "def _partial_move_for(self, cr, uid, move)"
},
{
"docstring": "Inherit fuction to add constrains in picking @return: super function of ... | 2 | stack_v2_sparse_classes_30k_train_014999 | Implement the Python class `stock_partial_picking` described below.
Class description:
Implement the stock_partial_picking class.
Method signatures and docstrings:
- def _partial_move_for(self, cr, uid, move): Inherit to add real stock quantity in partial move dict @param move: id of picking move @return: id
- def do... | Implement the Python class `stock_partial_picking` described below.
Class description:
Implement the stock_partial_picking class.
Method signatures and docstrings:
- def _partial_move_for(self, cr, uid, move): Inherit to add real stock quantity in partial move dict @param move: id of picking move @return: id
- def do... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class stock_partial_picking:
def _partial_move_for(self, cr, uid, move):
"""Inherit to add real stock quantity in partial move dict @param move: id of picking move @return: id"""
<|body_0|>
def do_partial(self, cr, uid, ids, context=None):
"""Inherit fuction to add constra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class stock_partial_picking:
def _partial_move_for(self, cr, uid, move):
"""Inherit to add real stock quantity in partial move dict @param move: id of picking move @return: id"""
context = {}
context['uom'] = move.product_uom.id
context['location'] = move.location_id.id
produ... | the_stack_v2_python_sparse | v_7/GDS/common_shamil_v3/stock_negative/wizard/stock_partial_picking.py | musabahmed/baba | train | 0 | |
b8b2d0cbe5efbb5ed9f8fc3a2ddfc55a96237ce1 | [
"LOG.info(f'{self.stats_api.binary} --database {self.stats_api.db_uri}add --machine X -u Unaligned {flow_cell_path.as_posix()}')\nif self.dry_run:\n LOG.info('Dry run will not add flow cell stats')\n return\ncgstats_add_parameters = ['--database', self.stats_api.db_uri, 'add', '--machine', 'X', '-u', 'Unalign... | <|body_start_0|>
LOG.info(f'{self.stats_api.binary} --database {self.stats_api.db_uri}add --machine X -u Unaligned {flow_cell_path.as_posix()}')
if self.dry_run:
LOG.info('Dry run will not add flow cell stats')
return
cgstats_add_parameters = ['--database', self.stats_api... | Post demultiplexing API class for Hiseq X flow cell. | DemuxPostProcessingHiseqXAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DemuxPostProcessingHiseqXAPI:
"""Post demultiplexing API class for Hiseq X flow cell."""
def add_to_cgstats(self, flow_cell_path: Path) -> None:
"""Add flow cell to cgstats."""
<|body_0|>
def cgstats_select_project(self, flow_cell_id: str, flow_cell_path: Path) -> None:
... | stack_v2_sparse_classes_36k_train_030160 | 20,731 | no_license | [
{
"docstring": "Add flow cell to cgstats.",
"name": "add_to_cgstats",
"signature": "def add_to_cgstats(self, flow_cell_path: Path) -> None"
},
{
"docstring": "Process selected project using cgstats.",
"name": "cgstats_select_project",
"signature": "def cgstats_select_project(self, flow_c... | 6 | stack_v2_sparse_classes_30k_train_004469 | Implement the Python class `DemuxPostProcessingHiseqXAPI` described below.
Class description:
Post demultiplexing API class for Hiseq X flow cell.
Method signatures and docstrings:
- def add_to_cgstats(self, flow_cell_path: Path) -> None: Add flow cell to cgstats.
- def cgstats_select_project(self, flow_cell_id: str,... | Implement the Python class `DemuxPostProcessingHiseqXAPI` described below.
Class description:
Post demultiplexing API class for Hiseq X flow cell.
Method signatures and docstrings:
- def add_to_cgstats(self, flow_cell_path: Path) -> None: Add flow cell to cgstats.
- def cgstats_select_project(self, flow_cell_id: str,... | d2ec6d25b577dd6938bbf92317aeff1d6b3c5b08 | <|skeleton|>
class DemuxPostProcessingHiseqXAPI:
"""Post demultiplexing API class for Hiseq X flow cell."""
def add_to_cgstats(self, flow_cell_path: Path) -> None:
"""Add flow cell to cgstats."""
<|body_0|>
def cgstats_select_project(self, flow_cell_id: str, flow_cell_path: Path) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DemuxPostProcessingHiseqXAPI:
"""Post demultiplexing API class for Hiseq X flow cell."""
def add_to_cgstats(self, flow_cell_path: Path) -> None:
"""Add flow cell to cgstats."""
LOG.info(f'{self.stats_api.binary} --database {self.stats_api.db_uri}add --machine X -u Unaligned {flow_cell_pat... | the_stack_v2_python_sparse | cg/meta/demultiplex/demux_post_processing.py | Clinical-Genomics/cg | train | 19 |
429f2606ad61f74f38e020b9a380f5626b843b2a | [
"super(QARNNModel, self).__init__()\nself.embedding = embedding\nself.batch_size = batch_size\nself.sequence_length = sequence_length\nself.rnn_input_size = n_in_rnn\nself.rnn_hidden_size = n_hidden_rnn\nself.mlp_input_size = n_in_mlp\nself.mlp_hidden_size = n_hidden_mlp\nself.mlp_out_size = n_out\nself.rnn_layer =... | <|body_start_0|>
super(QARNNModel, self).__init__()
self.embedding = embedding
self.batch_size = batch_size
self.sequence_length = sequence_length
self.rnn_input_size = n_in_rnn
self.rnn_hidden_size = n_hidden_rnn
self.mlp_input_size = n_in_mlp
self.mlp_hi... | RNN model for QA pair. | QARNNModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QARNNModel:
"""RNN model for QA pair."""
def __init__(self, embedding, batch_size, sequence_length, n_in_rnn, n_hidden_rnn, n_in_mlp, n_hidden_mlp, n_out):
"""RNN model init. :param embedding: word embedding :param batch_size: mini_batch size :param sequence_length: sequence_length :... | stack_v2_sparse_classes_36k_train_030161 | 6,002 | permissive | [
{
"docstring": "RNN model init. :param embedding: word embedding :param batch_size: mini_batch size :param sequence_length: sequence_length :param n_in_rnn: input_size for rnn(emb_dim) :param n_hidden_rnn: hidden_size for rnn :param n_in_mlp: input_size for mlp :param n_hidden_mlp: hidden_size for mlp :param n_... | 2 | stack_v2_sparse_classes_30k_train_012238 | Implement the Python class `QARNNModel` described below.
Class description:
RNN model for QA pair.
Method signatures and docstrings:
- def __init__(self, embedding, batch_size, sequence_length, n_in_rnn, n_hidden_rnn, n_in_mlp, n_hidden_mlp, n_out): RNN model init. :param embedding: word embedding :param batch_size: ... | Implement the Python class `QARNNModel` described below.
Class description:
RNN model for QA pair.
Method signatures and docstrings:
- def __init__(self, embedding, batch_size, sequence_length, n_in_rnn, n_hidden_rnn, n_in_mlp, n_hidden_mlp, n_out): RNN model init. :param embedding: word embedding :param batch_size: ... | 56b0a320e4641f46e80db78039d4ca79e9037d7e | <|skeleton|>
class QARNNModel:
"""RNN model for QA pair."""
def __init__(self, embedding, batch_size, sequence_length, n_in_rnn, n_hidden_rnn, n_in_mlp, n_hidden_mlp, n_out):
"""RNN model init. :param embedding: word embedding :param batch_size: mini_batch size :param sequence_length: sequence_length :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QARNNModel:
"""RNN model for QA pair."""
def __init__(self, embedding, batch_size, sequence_length, n_in_rnn, n_hidden_rnn, n_in_mlp, n_hidden_mlp, n_out):
"""RNN model init. :param embedding: word embedding :param batch_size: mini_batch size :param sequence_length: sequence_length :param n_in_rn... | the_stack_v2_python_sparse | torch_models/qa_rnn.py | companionrobot/DBQA | train | 0 |
128bc6d37f288a77ec7a17c7877c1157ec936faa | [
"super().__init__()\nself.margin = margin\nself.reduction = reduction or 'none'",
"diff = embeddings_left - embeddings_right\ndistance_pred = torch.sqrt(torch.sum(torch.pow(diff, 2), 1))\nbs = len(distance_true)\nmargin_distance = self.margin - distance_pred\nmargin_distance = torch.clamp(margin_distance, min=0.0... | <|body_start_0|>
super().__init__()
self.margin = margin
self.reduction = reduction or 'none'
<|end_body_0|>
<|body_start_1|>
diff = embeddings_left - embeddings_right
distance_pred = torch.sqrt(torch.sum(torch.pow(diff, 2), 1))
bs = len(distance_true)
margin_dis... | The Contrastive embedding loss. It has been proposed in `Dimensionality Reduction by Learning an Invariant Mapping`_. .. _Dimensionality Reduction by Learning an Invariant Mapping: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf | ContrastiveEmbeddingLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContrastiveEmbeddingLoss:
"""The Contrastive embedding loss. It has been proposed in `Dimensionality Reduction by Learning an Invariant Mapping`_. .. _Dimensionality Reduction by Learning an Invariant Mapping: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf"""
def __init__(... | stack_v2_sparse_classes_36k_train_030162 | 7,661 | permissive | [
{
"docstring": "Args: margin: margin parameter reduction: criterion reduction type",
"name": "__init__",
"signature": "def __init__(self, margin=1.0, reduction='mean')"
},
{
"docstring": "Forward propagation method for the contrastive loss. Args: embeddings_left: left objects embeddings embeddin... | 2 | stack_v2_sparse_classes_30k_train_012692 | Implement the Python class `ContrastiveEmbeddingLoss` described below.
Class description:
The Contrastive embedding loss. It has been proposed in `Dimensionality Reduction by Learning an Invariant Mapping`_. .. _Dimensionality Reduction by Learning an Invariant Mapping: http://yann.lecun.com/exdb/publis/pdf/hadsell-ch... | Implement the Python class `ContrastiveEmbeddingLoss` described below.
Class description:
The Contrastive embedding loss. It has been proposed in `Dimensionality Reduction by Learning an Invariant Mapping`_. .. _Dimensionality Reduction by Learning an Invariant Mapping: http://yann.lecun.com/exdb/publis/pdf/hadsell-ch... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class ContrastiveEmbeddingLoss:
"""The Contrastive embedding loss. It has been proposed in `Dimensionality Reduction by Learning an Invariant Mapping`_. .. _Dimensionality Reduction by Learning an Invariant Mapping: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf"""
def __init__(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContrastiveEmbeddingLoss:
"""The Contrastive embedding loss. It has been proposed in `Dimensionality Reduction by Learning an Invariant Mapping`_. .. _Dimensionality Reduction by Learning an Invariant Mapping: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf"""
def __init__(self, margin=... | the_stack_v2_python_sparse | catalyst/contrib/losses/contrastive.py | catalyst-team/catalyst | train | 3,038 |
2b95f1484a7e6eadfcceb66050428b71f7794869 | [
"res = 0\nfor i in range(32):\n if n & 1 << i != 0:\n res += 1\nreturn res",
"res = 0\nwhile n != 0:\n n &= n - 1\n res += 1\nreturn res"
] | <|body_start_0|>
res = 0
for i in range(32):
if n & 1 << i != 0:
res += 1
return res
<|end_body_0|>
<|body_start_1|>
res = 0
while n != 0:
n &= n - 1
res += 1
return res
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def hammingWeight0(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = 0
for i in range(32):
if n & 1 << i !=... | stack_v2_sparse_classes_36k_train_030163 | 863 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "hammingWeight",
"signature": "def hammingWeight(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "hammingWeight0",
"signature": "def hammingWeight0(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005834 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n): :type n: int :rtype: int
- def hammingWeight0(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n): :type n: int :rtype: int
- def hammingWeight0(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def hammingWeight(self, n):
... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def hammingWeight0(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
res = 0
for i in range(32):
if n & 1 << i != 0:
res += 1
return res
def hammingWeight0(self, n):
""":type n: int :rtype: int"""
res = 0
while n != 0:
... | the_stack_v2_python_sparse | 剑指 Offer 15. 二进制中1的个数.py | yangyuxiang1996/leetcode | train | 0 | |
11ffc652f007e0182aa10995303ce88299e7e5ac | [
"super().__init__()\nself.do_bg = do_bg\nself.batch_dice = batch_dice\nself.nonlin = nonlin\nself.smooth_nom = smooth_nom\nself.smooth_denom = smooth_denom\nlogger.info(f'Running batch dice {self.batch_dice} and do bg {self.do_bg} in dice loss.')",
"shp_x = inp.shape\nif self.batch_dice:\n axes = [0] + list(ra... | <|body_start_0|>
super().__init__()
self.do_bg = do_bg
self.batch_dice = batch_dice
self.nonlin = nonlin
self.smooth_nom = smooth_nom
self.smooth_denom = smooth_denom
logger.info(f'Running batch dice {self.batch_dice} and do bg {self.do_bg} in dice loss.')
<|end_b... | SoftDiceLoss | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftDiceLoss:
def __init__(self, nonlin: Callable=None, batch_dice: bool=False, do_bg: bool=False, smooth_nom: float=1e-05, smooth_denom: float=1e-05):
"""Soft dice loss Args: nonlin: treat batch as pseudo volume. Defaults to False. do_bg: include background for dice computation. Default... | stack_v2_sparse_classes_36k_train_030164 | 8,471 | permissive | [
{
"docstring": "Soft dice loss Args: nonlin: treat batch as pseudo volume. Defaults to False. do_bg: include background for dice computation. Defaults to True. smooth_nom: smoothing for nominator smooth_denom: smoothing for denominator",
"name": "__init__",
"signature": "def __init__(self, nonlin: Calla... | 2 | stack_v2_sparse_classes_30k_train_014909 | Implement the Python class `SoftDiceLoss` described below.
Class description:
Implement the SoftDiceLoss class.
Method signatures and docstrings:
- def __init__(self, nonlin: Callable=None, batch_dice: bool=False, do_bg: bool=False, smooth_nom: float=1e-05, smooth_denom: float=1e-05): Soft dice loss Args: nonlin: tre... | Implement the Python class `SoftDiceLoss` described below.
Class description:
Implement the SoftDiceLoss class.
Method signatures and docstrings:
- def __init__(self, nonlin: Callable=None, batch_dice: bool=False, do_bg: bool=False, smooth_nom: float=1e-05, smooth_denom: float=1e-05): Soft dice loss Args: nonlin: tre... | 4f41faa7536dcef8fca7b647dcdca25360e5b58a | <|skeleton|>
class SoftDiceLoss:
def __init__(self, nonlin: Callable=None, batch_dice: bool=False, do_bg: bool=False, smooth_nom: float=1e-05, smooth_denom: float=1e-05):
"""Soft dice loss Args: nonlin: treat batch as pseudo volume. Defaults to False. do_bg: include background for dice computation. Default... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SoftDiceLoss:
def __init__(self, nonlin: Callable=None, batch_dice: bool=False, do_bg: bool=False, smooth_nom: float=1e-05, smooth_denom: float=1e-05):
"""Soft dice loss Args: nonlin: treat batch as pseudo volume. Defaults to False. do_bg: include background for dice computation. Defaults to True. smo... | the_stack_v2_python_sparse | nndet/losses/segmentation.py | dboun/nnDetection | train | 1 | |
480d732f5b50ed751c8c87d9d36b2267328abf0f | [
"if '_xml_ns' in kwargs:\n self._xml_ns = kwargs['_xml_ns']\nif '_xml_ns_key' in kwargs:\n self._xml_ns_key = kwargs['_xml_ns_key']\nself.SampleType = SampleType\nself.NumBytesVBP = NumBytesVBP\nself.ArraySize = ArraySize\nsuper(DataType, self).__init__(**kwargs)",
"if self.ArraySize is None:\n return 0\... | <|body_start_0|>
if '_xml_ns' in kwargs:
self._xml_ns = kwargs['_xml_ns']
if '_xml_ns_key' in kwargs:
self._xml_ns_key = kwargs['_xml_ns_key']
self.SampleType = SampleType
self.NumBytesVBP = NumBytesVBP
self.ArraySize = ArraySize
super(DataType, se... | Parameters that describe binary data components contained in the product. | DataType | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataType:
"""Parameters that describe binary data components contained in the product."""
def __init__(self, SampleType=None, NumBytesVBP=None, ArraySize=None, **kwargs):
"""Parameters ---------- SampleType : str NumBytesVBP : int ArraySize : List[ArraySizeType] kwargs"""
<|b... | stack_v2_sparse_classes_36k_train_030165 | 3,405 | permissive | [
{
"docstring": "Parameters ---------- SampleType : str NumBytesVBP : int ArraySize : List[ArraySizeType] kwargs",
"name": "__init__",
"signature": "def __init__(self, SampleType=None, NumBytesVBP=None, ArraySize=None, **kwargs)"
},
{
"docstring": "int: The number of CPHD channels.",
"name": ... | 2 | null | Implement the Python class `DataType` described below.
Class description:
Parameters that describe binary data components contained in the product.
Method signatures and docstrings:
- def __init__(self, SampleType=None, NumBytesVBP=None, ArraySize=None, **kwargs): Parameters ---------- SampleType : str NumBytesVBP : ... | Implement the Python class `DataType` described below.
Class description:
Parameters that describe binary data components contained in the product.
Method signatures and docstrings:
- def __init__(self, SampleType=None, NumBytesVBP=None, ArraySize=None, **kwargs): Parameters ---------- SampleType : str NumBytesVBP : ... | de1b1886f161a83b6c89aadc7a2c7cfc4892ef81 | <|skeleton|>
class DataType:
"""Parameters that describe binary data components contained in the product."""
def __init__(self, SampleType=None, NumBytesVBP=None, ArraySize=None, **kwargs):
"""Parameters ---------- SampleType : str NumBytesVBP : int ArraySize : List[ArraySizeType] kwargs"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataType:
"""Parameters that describe binary data components contained in the product."""
def __init__(self, SampleType=None, NumBytesVBP=None, ArraySize=None, **kwargs):
"""Parameters ---------- SampleType : str NumBytesVBP : int ArraySize : List[ArraySizeType] kwargs"""
if '_xml_ns' in ... | the_stack_v2_python_sparse | sarpy/io/phase_history/cphd0_3_elements/Data.py | ngageoint/sarpy | train | 192 |
e64b1c33bf2cdace64ccf3b713b7680415e3bd3e | [
"if not matrix:\n self.sums = []\nelse:\n row, col = (len(matrix), len(matrix[0]))\n self.sums = [[0] * (col + 1) for _ in range(row + 1)]\n for i in range(1, row + 1):\n for j in range(1, col + 1):\n self.sums[i][j] = self.sums[i][j - 1] + self.sums[i - 1][j] - self.sums[i - 1][j - 1]... | <|body_start_0|>
if not matrix:
self.sums = []
else:
row, col = (len(matrix), len(matrix[0]))
self.sums = [[0] * (col + 1) for _ in range(row + 1)]
for i in range(1, row + 1):
for j in range(1, col + 1):
self.sums[i][j] ... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_36k_train_030166 | 1,331 | no_license | [
{
"docstring": "initialize your data structure here. :type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": "sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtyp... | 2 | stack_v2_sparse_classes_30k_train_007083 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | 14e32f180c3f5eedd101fd2dbb57712498375a9a | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
if not matrix:
self.sums = []
else:
row, col = (len(matrix), len(matrix[0]))
self.sums = [[0] * (col + 1) for _ in range(row + 1)]
... | the_stack_v2_python_sparse | 304RangeSumQuery2D-Immutable.py | xkoma007/leetcode | train | 0 | |
812248a8164863b123be84ff54d8eaf319a53f08 | [
"super().__init__(main_window)\nstacked_layout = QStackedLayout()\nmain_window.communication.item_selected.connect(stacked_layout.setCurrentIndex)\nself.setLayout(stacked_layout)\nself.showEvent = self._get_show_event(main_window)\nfor item in items:\n frame = AttributesFrame(main_window=main_window, item=item)\... | <|body_start_0|>
super().__init__(main_window)
stacked_layout = QStackedLayout()
main_window.communication.item_selected.connect(stacked_layout.setCurrentIndex)
self.setLayout(stacked_layout)
self.showEvent = self._get_show_event(main_window)
for item in items:
... | DataWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataWidget:
def __init__(self, main_window, items):
"""Widget contains items with inputs."""
<|body_0|>
def _get_show_event(main_window):
"""Emit signal to hide ActionButton."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__(main_wind... | stack_v2_sparse_classes_36k_train_030167 | 946 | no_license | [
{
"docstring": "Widget contains items with inputs.",
"name": "__init__",
"signature": "def __init__(self, main_window, items)"
},
{
"docstring": "Emit signal to hide ActionButton.",
"name": "_get_show_event",
"signature": "def _get_show_event(main_window)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004749 | Implement the Python class `DataWidget` described below.
Class description:
Implement the DataWidget class.
Method signatures and docstrings:
- def __init__(self, main_window, items): Widget contains items with inputs.
- def _get_show_event(main_window): Emit signal to hide ActionButton. | Implement the Python class `DataWidget` described below.
Class description:
Implement the DataWidget class.
Method signatures and docstrings:
- def __init__(self, main_window, items): Widget contains items with inputs.
- def _get_show_event(main_window): Emit signal to hide ActionButton.
<|skeleton|>
class DataWidge... | 606e188e88ee3a2b2e1daee60c71948c678228e1 | <|skeleton|>
class DataWidget:
def __init__(self, main_window, items):
"""Widget contains items with inputs."""
<|body_0|>
def _get_show_event(main_window):
"""Emit signal to hide ActionButton."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataWidget:
def __init__(self, main_window, items):
"""Widget contains items with inputs."""
super().__init__(main_window)
stacked_layout = QStackedLayout()
main_window.communication.item_selected.connect(stacked_layout.setCurrentIndex)
self.setLayout(stacked_layout)
... | the_stack_v2_python_sparse | Hospital-Helper-2-master/app/gui/data_widget.py | JoaoBueno/estudos-python | train | 2 | |
bf0330d605d168528c633de4e384e22a73503466 | [
"self.de_domain = de_domain\nself.atmosphere = atmosphere\nself.radius = radius\nif r_width is None:\n self.r_width = radius / 5\nelse:\n self.r_width = r_width\nself.falling = falling\nself.A0 = A0\nif self.falling:\n self.sign = -1\nelse:\n self.sign = 1\nif z_pert is None:\n if self.falling:\n ... | <|body_start_0|>
self.de_domain = de_domain
self.atmosphere = atmosphere
self.radius = radius
if r_width is None:
self.r_width = radius / 5
else:
self.r_width = r_width
self.falling = falling
self.A0 = A0
if self.falling:
... | A class that creates a thermal in a Fully Compressible simulation Attributes ---------- de_domain : DedalusDomain object The domain in which the thermal experiment is being done atmosphere : An IdealGasAtmosphere object The atmosphere in which the thermal is falling. falling : bool If True, do a cold, falling thermal. ... | Thermal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Thermal:
"""A class that creates a thermal in a Fully Compressible simulation Attributes ---------- de_domain : DedalusDomain object The domain in which the thermal experiment is being done atmosphere : An IdealGasAtmosphere object The atmosphere in which the thermal is falling. falling : bool If... | stack_v2_sparse_classes_36k_train_030168 | 3,310 | no_license | [
{
"docstring": "Initialize the thermal class. Inputs are described in the class attributes in the class docstring.",
"name": "__init__",
"signature": "def __init__(self, de_domain, atmosphere, falling=False, radius=1, r_width=None, A0=0.0001, z_pert=None)"
},
{
"docstring": "Put a thermal into t... | 2 | stack_v2_sparse_classes_30k_train_014282 | Implement the Python class `Thermal` described below.
Class description:
A class that creates a thermal in a Fully Compressible simulation Attributes ---------- de_domain : DedalusDomain object The domain in which the thermal experiment is being done atmosphere : An IdealGasAtmosphere object The atmosphere in which th... | Implement the Python class `Thermal` described below.
Class description:
A class that creates a thermal in a Fully Compressible simulation Attributes ---------- de_domain : DedalusDomain object The domain in which the thermal experiment is being done atmosphere : An IdealGasAtmosphere object The atmosphere in which th... | 39d765ad3d0549e26621a9d018ea46c55f48b2a3 | <|skeleton|>
class Thermal:
"""A class that creates a thermal in a Fully Compressible simulation Attributes ---------- de_domain : DedalusDomain object The domain in which the thermal experiment is being done atmosphere : An IdealGasAtmosphere object The atmosphere in which the thermal is falling. falling : bool If... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Thermal:
"""A class that creates a thermal in a Fully Compressible simulation Attributes ---------- de_domain : DedalusDomain object The domain in which the thermal experiment is being done atmosphere : An IdealGasAtmosphere object The atmosphere in which the thermal is falling. falling : bool If True, do a c... | the_stack_v2_python_sparse | stratified_thermals_code/nondim_FC_stratified_thermals/logic/thermal.py | evanhanders/entropyrain_thermals_paper2019 | train | 2 |
0582fe1d0c3100afd8d4baa29f0fbca1dbf47097 | [
"super(PreAggGraphConv, self).__init__(activity_regularizer=activity_regularizer, **kwargs)\nself.units = int(units)\n\ndef normalize(x):\n \"\"\"Row-normalization of the matrix.\"\"\"\n rowsum = tf.math.reduce_sum(x, axis=1)\n rowsum = tf.math.maximum(rowsum, 1e-12)\n rowinv = rowsum ** (-1)\n retur... | <|body_start_0|>
super(PreAggGraphConv, self).__init__(activity_regularizer=activity_regularizer, **kwargs)
self.units = int(units)
def normalize(x):
"""Row-normalization of the matrix."""
rowsum = tf.math.reduce_sum(x, axis=1)
rowsum = tf.math.maximum(rowsum... | Implements Pre-Aggregation Graph Convolution. Reference: Liu et al. A Comprehensive Study of Weight Sharing in Graph Networks for 3D Human Pose Estimation. http://www.ecva.net/papers/eccv_2020/papers_ECCV/papers/123550324.pdf. | PreAggGraphConv | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreAggGraphConv:
"""Implements Pre-Aggregation Graph Convolution. Reference: Liu et al. A Comprehensive Study of Weight Sharing in Graph Networks for 3D Human Pose Estimation. http://www.ecva.net/papers/eccv_2020/papers_ECCV/papers/123550324.pdf."""
def __init__(self, units, affinity_matrix,... | stack_v2_sparse_classes_36k_train_030169 | 30,548 | permissive | [
{
"docstring": "Initializer. Args: units: An integer for the output dimension of the layer. affinity_matrix: A tensor for the keypoint affinity matrix. activation: Activation function to use. use_bias: A boolean for whether the layer uses a bias vector. kernel_initializer: Initializer for the kernel weights mat... | 3 | null | Implement the Python class `PreAggGraphConv` described below.
Class description:
Implements Pre-Aggregation Graph Convolution. Reference: Liu et al. A Comprehensive Study of Weight Sharing in Graph Networks for 3D Human Pose Estimation. http://www.ecva.net/papers/eccv_2020/papers_ECCV/papers/123550324.pdf.
Method sig... | Implement the Python class `PreAggGraphConv` described below.
Class description:
Implements Pre-Aggregation Graph Convolution. Reference: Liu et al. A Comprehensive Study of Weight Sharing in Graph Networks for 3D Human Pose Estimation. http://www.ecva.net/papers/eccv_2020/papers_ECCV/papers/123550324.pdf.
Method sig... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class PreAggGraphConv:
"""Implements Pre-Aggregation Graph Convolution. Reference: Liu et al. A Comprehensive Study of Weight Sharing in Graph Networks for 3D Human Pose Estimation. http://www.ecva.net/papers/eccv_2020/papers_ECCV/papers/123550324.pdf."""
def __init__(self, units, affinity_matrix,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PreAggGraphConv:
"""Implements Pre-Aggregation Graph Convolution. Reference: Liu et al. A Comprehensive Study of Weight Sharing in Graph Networks for 3D Human Pose Estimation. http://www.ecva.net/papers/eccv_2020/papers_ECCV/papers/123550324.pdf."""
def __init__(self, units, affinity_matrix, activation=N... | the_stack_v2_python_sparse | poem/cv_mim/models.py | Jimmy-INL/google-research | train | 1 |
64799d89297002eb74cf8ef4955df277ec65a943 | [
"self.hc = 0\nself.c = Counter()\nself.times = deque()",
"self.hc += 1\nself.c[timestamp] += 1\nself.times.append(timestamp)\nwhile self.times[0] + 300 <= timestamp:\n t = self.times.popleft()\n self.hc -= self.c[t]\n del self.c[t]",
"self.times.append(timestamp)\nwhile self.times[0] + 300 <= timestamp... | <|body_start_0|>
self.hc = 0
self.c = Counter()
self.times = deque()
<|end_body_0|>
<|body_start_1|>
self.hc += 1
self.c[timestamp] += 1
self.times.append(timestamp)
while self.times[0] + 300 <= timestamp:
t = self.times.popleft()
self.hc ... | HitCounter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: in... | stack_v2_sparse_classes_36k_train_030170 | 1,214 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Record a hit. @param timestamp - The current timestamp (in seconds granularity).",
"name": "hit",
"signature": "def hit(self, timestamp: int) -> None"
},
{
... | 3 | null | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari... | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari... | 96e086d4ee6169c0f83fff3819f38f32b8f17c98 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
self.hc = 0
self.c = Counter()
self.times = deque()
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
self... | the_stack_v2_python_sparse | leetcode/362 Design Hit Counter.py | DeshErBojhaa/sports_programming | train | 1 | |
daf7590bcb63b94adba1746befec5aa7d4099be7 | [
"data = data_input('data/aoc_06_data_test_1.txt')\norbits = calc_orbits(data)\nresult = orbit_counter(orbits, 'D', 0)\nself.assertEqual(result, 3)",
"data = data_input('data/aoc_06_data_test_1.txt')\nresult = part_1(data)\nself.assertEqual(result, 42)",
"data = data_input('data/aoc_06_data_test_2.txt')\norbits ... | <|body_start_0|>
data = data_input('data/aoc_06_data_test_1.txt')
orbits = calc_orbits(data)
result = orbit_counter(orbits, 'D', 0)
self.assertEqual(result, 3)
<|end_body_0|>
<|body_start_1|>
data = data_input('data/aoc_06_data_test_1.txt')
result = part_1(data)
... | () | TestAoC06 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAoC06:
"""()"""
def test_orbit_counter(self):
"""()"""
<|body_0|>
def test_part_1(self):
"""()"""
<|body_1|>
def test_orbit_chain(self):
"""()"""
<|body_2|>
def test_part_2(self):
"""()"""
<|body_3|>
<|end_sk... | stack_v2_sparse_classes_36k_train_030171 | 1,303 | no_license | [
{
"docstring": "()",
"name": "test_orbit_counter",
"signature": "def test_orbit_counter(self)"
},
{
"docstring": "()",
"name": "test_part_1",
"signature": "def test_part_1(self)"
},
{
"docstring": "()",
"name": "test_orbit_chain",
"signature": "def test_orbit_chain(self)"... | 4 | stack_v2_sparse_classes_30k_train_015873 | Implement the Python class `TestAoC06` described below.
Class description:
()
Method signatures and docstrings:
- def test_orbit_counter(self): ()
- def test_part_1(self): ()
- def test_orbit_chain(self): ()
- def test_part_2(self): () | Implement the Python class `TestAoC06` described below.
Class description:
()
Method signatures and docstrings:
- def test_orbit_counter(self): ()
- def test_part_1(self): ()
- def test_orbit_chain(self): ()
- def test_part_2(self): ()
<|skeleton|>
class TestAoC06:
"""()"""
def test_orbit_counter(self):
... | 4c49273b8f9846ccd2df54c2249a63bb4f8a4ddd | <|skeleton|>
class TestAoC06:
"""()"""
def test_orbit_counter(self):
"""()"""
<|body_0|>
def test_part_1(self):
"""()"""
<|body_1|>
def test_orbit_chain(self):
"""()"""
<|body_2|>
def test_part_2(self):
"""()"""
<|body_3|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAoC06:
"""()"""
def test_orbit_counter(self):
"""()"""
data = data_input('data/aoc_06_data_test_1.txt')
orbits = calc_orbits(data)
result = orbit_counter(orbits, 'D', 0)
self.assertEqual(result, 3)
def test_part_1(self):
"""()"""
data = dat... | the_stack_v2_python_sparse | test_aoc_06.py | iveL91/Advent-of-Code-2019 | train | 0 |
5193ab9bd668ca7611d6102a17c85328da53b738 | [
"if not self.path.exists():\n raise MissingFileError(self.path)\nif self.md5:\n logger.info(f'File {self.path}: checking md5')\n md5 = _md5(self.path)\n logger.debug(f'{md5} vs expected {self.md5}')\n if md5 != self.md5:\n raise ChecksumError(self.path, self.md5, md5)",
"try:\n self.check... | <|body_start_0|>
if not self.path.exists():
raise MissingFileError(self.path)
if self.md5:
logger.info(f'File {self.path}: checking md5')
md5 = _md5(self.path)
logger.debug(f'{md5} vs expected {self.md5}')
if md5 != self.md5:
ra... | Object storing local path, remote URL (optional), and MD5 sum (optional) for a SNEWPY model file. If the requested file is already present locally, open it. Otherwise, download it from the remote URL to the desired local path. | FileHandle | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileHandle:
"""Object storing local path, remote URL (optional), and MD5 sum (optional) for a SNEWPY model file. If the requested file is already present locally, open it. Otherwise, download it from the remote URL to the desired local path."""
def check(self) -> None:
"""Check if th... | stack_v2_sparse_classes_36k_train_030172 | 5,872 | permissive | [
{
"docstring": "Check if the given file exists locally and has a correct md5 sum. Raises ------ :class:`MissingFileError` if the local copy of the file is missing :class:`ChecksumError` if the local file exists, but the checksum is wrong",
"name": "check",
"signature": "def check(self) -> None"
},
{... | 2 | stack_v2_sparse_classes_30k_train_019172 | Implement the Python class `FileHandle` described below.
Class description:
Object storing local path, remote URL (optional), and MD5 sum (optional) for a SNEWPY model file. If the requested file is already present locally, open it. Otherwise, download it from the remote URL to the desired local path.
Method signatur... | Implement the Python class `FileHandle` described below.
Class description:
Object storing local path, remote URL (optional), and MD5 sum (optional) for a SNEWPY model file. If the requested file is already present locally, open it. Otherwise, download it from the remote URL to the desired local path.
Method signatur... | feb3a6c46d7dc4e999446994025001de77768e1d | <|skeleton|>
class FileHandle:
"""Object storing local path, remote URL (optional), and MD5 sum (optional) for a SNEWPY model file. If the requested file is already present locally, open it. Otherwise, download it from the remote URL to the desired local path."""
def check(self) -> None:
"""Check if th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileHandle:
"""Object storing local path, remote URL (optional), and MD5 sum (optional) for a SNEWPY model file. If the requested file is already present locally, open it. Otherwise, download it from the remote URL to the desired local path."""
def check(self) -> None:
"""Check if the given file ... | the_stack_v2_python_sparse | python/snewpy/_model_downloader.py | SNEWS2/snewpy | train | 22 |
3e0fa2e54938d72afe0ee795890c28920402d6dc | [
"if self.kill:\n return\nif self.text_timer[index].IsRunning():\n self.text_timer[index].Stop()\nelse:\n self.saved_text = self.GetStatusText(index)\nself.SetStatusText(text, index)\nself.text_timer[index].Start(3000, oneShot=True)",
"if self.kill:\n return\nif self.text_timer[index].IsRunning():\n ... | <|body_start_0|>
if self.kill:
return
if self.text_timer[index].IsRunning():
self.text_timer[index].Stop()
else:
self.saved_text = self.GetStatusText(index)
self.SetStatusText(text, index)
self.text_timer[index].Start(3000, oneShot=True)
<|end_... | Timed status in status bar. | TimedStatusExtension | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimedStatusExtension:
"""Timed status in status bar."""
def set_timed_status(self, text, index=0):
"""Set the status for a short time. Save the previous status for restore when the timed status completes."""
<|body_0|>
def cancel_timed_status(self, index=0):
"""C... | stack_v2_sparse_classes_36k_train_030173 | 9,581 | permissive | [
{
"docstring": "Set the status for a short time. Save the previous status for restore when the timed status completes.",
"name": "set_timed_status",
"signature": "def set_timed_status(self, text, index=0)"
},
{
"docstring": "Cancel running timed status.",
"name": "cancel_timed_status",
"... | 6 | stack_v2_sparse_classes_30k_train_015433 | Implement the Python class `TimedStatusExtension` described below.
Class description:
Timed status in status bar.
Method signatures and docstrings:
- def set_timed_status(self, text, index=0): Set the status for a short time. Save the previous status for restore when the timed status completes.
- def cancel_timed_sta... | Implement the Python class `TimedStatusExtension` described below.
Class description:
Timed status in status bar.
Method signatures and docstrings:
- def set_timed_status(self, text, index=0): Set the status for a short time. Save the previous status for restore when the timed status completes.
- def cancel_timed_sta... | 95129ca054384a4c59a4effdb3fe32a7a66af6ff | <|skeleton|>
class TimedStatusExtension:
"""Timed status in status bar."""
def set_timed_status(self, text, index=0):
"""Set the status for a short time. Save the previous status for restore when the timed status completes."""
<|body_0|>
def cancel_timed_status(self, index=0):
"""C... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimedStatusExtension:
"""Timed status in status bar."""
def set_timed_status(self, text, index=0):
"""Set the status for a short time. Save the previous status for restore when the timed status completes."""
if self.kill:
return
if self.text_timer[index].IsRunning():
... | the_stack_v2_python_sparse | rummage/lib/gui/controls/custom_statusbar.py | facelessuser/Rummage | train | 70 |
8fe3138fad3edf956c5cc348482824d02fca4c9a | [
"ns = db.ConfigNamespace.find_one(ConfigNamespace.namespace_prefix == namespacePrefix)\nif not ns:\n return self.make_response('No such namespace: {}'.format(namespacePrefix), HTTP.NOT_FOUND)\nreturn self.make_response({'message': None, 'namespace': ns})",
"self.reqparse.add_argument('name', type=str, required... | <|body_start_0|>
ns = db.ConfigNamespace.find_one(ConfigNamespace.namespace_prefix == namespacePrefix)
if not ns:
return self.make_response('No such namespace: {}'.format(namespacePrefix), HTTP.NOT_FOUND)
return self.make_response({'message': None, 'namespace': ns})
<|end_body_0|>
<... | NamespaceGet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NamespaceGet:
def get(self, namespacePrefix):
"""Get a specific configuration namespace"""
<|body_0|>
def put(self, namespacePrefix):
"""Update a specific configuration namespace"""
<|body_1|>
def delete(self, namespacePrefix):
"""Delete a specif... | stack_v2_sparse_classes_36k_train_030174 | 10,137 | permissive | [
{
"docstring": "Get a specific configuration namespace",
"name": "get",
"signature": "def get(self, namespacePrefix)"
},
{
"docstring": "Update a specific configuration namespace",
"name": "put",
"signature": "def put(self, namespacePrefix)"
},
{
"docstring": "Delete a specific c... | 3 | null | Implement the Python class `NamespaceGet` described below.
Class description:
Implement the NamespaceGet class.
Method signatures and docstrings:
- def get(self, namespacePrefix): Get a specific configuration namespace
- def put(self, namespacePrefix): Update a specific configuration namespace
- def delete(self, name... | Implement the Python class `NamespaceGet` described below.
Class description:
Implement the NamespaceGet class.
Method signatures and docstrings:
- def get(self, namespacePrefix): Get a specific configuration namespace
- def put(self, namespacePrefix): Update a specific configuration namespace
- def delete(self, name... | 29a26c705381fdba3538b4efedb25b9e09b387ed | <|skeleton|>
class NamespaceGet:
def get(self, namespacePrefix):
"""Get a specific configuration namespace"""
<|body_0|>
def put(self, namespacePrefix):
"""Update a specific configuration namespace"""
<|body_1|>
def delete(self, namespacePrefix):
"""Delete a specif... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NamespaceGet:
def get(self, namespacePrefix):
"""Get a specific configuration namespace"""
ns = db.ConfigNamespace.find_one(ConfigNamespace.namespace_prefix == namespacePrefix)
if not ns:
return self.make_response('No such namespace: {}'.format(namespacePrefix), HTTP.NOT_FO... | the_stack_v2_python_sparse | backend/cloud_inquisitor/plugins/views/config.py | RiotGames/cloud-inquisitor | train | 468 | |
2ff5b6ee6db9c2697aad5021343f01c1469c48cc | [
"f = open(os.path.join(self.path, filename), 'rb')\nlines = f.readlines()\nf.close()\nreturn lines",
"if filename not in self.db_config:\n f = open(os.path.join(self.path, 'db', filename), 'rb')\n self.db_config[filename] = f.readlines()\n f.close()\nreturn self.db_config[filename]",
"if name is None:\... | <|body_start_0|>
f = open(os.path.join(self.path, filename), 'rb')
lines = f.readlines()
f.close()
return lines
<|end_body_0|>
<|body_start_1|>
if filename not in self.db_config:
f = open(os.path.join(self.path, 'db', filename), 'rb')
self.db_config[filen... | Encapsulates key information of a repository: its NAME, PATH, SHARD_SIZE, HEAD revision and MIN_UNPACKED_REV. | Repository | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-other-permissive",
"X11",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"HPND-Markus-Kuhn",
"LicenseRef-scancode-unicode",
"Apache-2.0",
"FSFAP"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Repository:
"""Encapsulates key information of a repository: its NAME, PATH, SHARD_SIZE, HEAD revision and MIN_UNPACKED_REV."""
def _read_repo_file(self, filename):
"""Read and return all lines from FILENAME in REPO."""
<|body_0|>
def _read_config(self, filename):
... | stack_v2_sparse_classes_36k_train_030175 | 6,496 | permissive | [
{
"docstring": "Read and return all lines from FILENAME in REPO.",
"name": "_read_repo_file",
"signature": "def _read_repo_file(self, filename)"
},
{
"docstring": "Read and return all lines from FILENAME. This will be used to read 'format', 'current' etc. .",
"name": "_read_config",
"sig... | 5 | stack_v2_sparse_classes_30k_train_007230 | Implement the Python class `Repository` described below.
Class description:
Encapsulates key information of a repository: its NAME, PATH, SHARD_SIZE, HEAD revision and MIN_UNPACKED_REV.
Method signatures and docstrings:
- def _read_repo_file(self, filename): Read and return all lines from FILENAME in REPO.
- def _rea... | Implement the Python class `Repository` described below.
Class description:
Encapsulates key information of a repository: its NAME, PATH, SHARD_SIZE, HEAD revision and MIN_UNPACKED_REV.
Method signatures and docstrings:
- def _read_repo_file(self, filename): Read and return all lines from FILENAME in REPO.
- def _rea... | dd957c4991e61bde23cc60d13449ea8b65f80c43 | <|skeleton|>
class Repository:
"""Encapsulates key information of a repository: its NAME, PATH, SHARD_SIZE, HEAD revision and MIN_UNPACKED_REV."""
def _read_repo_file(self, filename):
"""Read and return all lines from FILENAME in REPO."""
<|body_0|>
def _read_config(self, filename):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Repository:
"""Encapsulates key information of a repository: its NAME, PATH, SHARD_SIZE, HEAD revision and MIN_UNPACKED_REV."""
def _read_repo_file(self, filename):
"""Read and return all lines from FILENAME in REPO."""
f = open(os.path.join(self.path, filename), 'rb')
lines = f.r... | the_stack_v2_python_sparse | contrib/server-side/fsfsfixer/fixer/find_good_id.py | apache/subversion | train | 520 |
3eed0dbe5dfc1f9c42fd70b48af55f4ed024c046 | [
"config = json.load(open(tasks_config_file))\nworlds = dict(((world_id, self.instantiate_world(world_config['type'])) for world_id, world_config in config['worlds'].items()))\ntasks = dict(((task_id, self.instantiate_task(task_config['type'], worlds, task_config.get('world', None))) for task_id, task_config in conf... | <|body_start_0|>
config = json.load(open(tasks_config_file))
worlds = dict(((world_id, self.instantiate_world(world_config['type'])) for world_id, world_config in config['worlds'].items()))
tasks = dict(((task_id, self.instantiate_task(task_config['type'], worlds, task_config.get('world', None))... | Loads a set of tasks and a schedule for them from a JSON file:: { "tasks": { "<task_id>": { "type": "<task_class>", }, "<task_id>": { "type": "<task_class>", "world": "<world_id>" } "...": "..." }, "worlds": { "<world_id>": { "type": "<world_class>", } }, "scheduler": { "type": "<scheduler_class>", "args": { "<schedule... | JSONConfigLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSONConfigLoader:
"""Loads a set of tasks and a schedule for them from a JSON file:: { "tasks": { "<task_id>": { "type": "<task_class>", }, "<task_id>": { "type": "<task_class>", "world": "<world_id>" } "...": "..." }, "worlds": { "<world_id>": { "type": "<world_class>", } }, "scheduler": { "type... | stack_v2_sparse_classes_36k_train_030176 | 5,363 | no_license | [
{
"docstring": "Given a json configuartion file, it returns a scheduler object set up as described in the file.",
"name": "create_tasks",
"signature": "def create_tasks(self, tasks_config_file)"
},
{
"docstring": "Return a world object given the world class",
"name": "instantiate_world",
... | 3 | null | Implement the Python class `JSONConfigLoader` described below.
Class description:
Loads a set of tasks and a schedule for them from a JSON file:: { "tasks": { "<task_id>": { "type": "<task_class>", }, "<task_id>": { "type": "<task_class>", "world": "<world_id>" } "...": "..." }, "worlds": { "<world_id>": { "type": "<w... | Implement the Python class `JSONConfigLoader` described below.
Class description:
Loads a set of tasks and a schedule for them from a JSON file:: { "tasks": { "<task_id>": { "type": "<task_class>", }, "<task_id>": { "type": "<task_class>", "world": "<world_id>" } "...": "..." }, "worlds": { "<world_id>": { "type": "<w... | d494b3041069d377d6a7a9c296a14334f2fa5acc | <|skeleton|>
class JSONConfigLoader:
"""Loads a set of tasks and a schedule for them from a JSON file:: { "tasks": { "<task_id>": { "type": "<task_class>", }, "<task_id>": { "type": "<task_class>", "world": "<world_id>" } "...": "..." }, "worlds": { "<world_id>": { "type": "<world_class>", } }, "scheduler": { "type... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JSONConfigLoader:
"""Loads a set of tasks and a schedule for them from a JSON file:: { "tasks": { "<task_id>": { "type": "<task_class>", }, "<task_id>": { "type": "<task_class>", "world": "<world_id>" } "...": "..." }, "worlds": { "<world_id>": { "type": "<world_class>", } }, "scheduler": { "type": "<schedule... | the_stack_v2_python_sparse | python/facebookresearch_CommAI-env/CommAI-env-master/src/core/config_loader.py | LiuFang816/SALSTM_py_data | train | 10 |
89e28e49b5385f7d8edb59509235eeac2487684f | [
"super(InputManager_Radix, self).__init__(config, is_inference)\nc = self.config\nmax_word_len = len(ops.number_to_base(len(c.wtoi), c.radix_base))\nself.buckets = [b * max_word_len for b in self.buckets]\nself.radix_wtoi = {}\nassert c.wtoi['<PAD>'] == -1\nfor k in c.wtoi:\n if k == '<GO>':\n idx = [c.ra... | <|body_start_0|>
super(InputManager_Radix, self).__init__(config, is_inference)
c = self.config
max_word_len = len(ops.number_to_base(len(c.wtoi), c.radix_base))
self.buckets = [b * max_word_len for b in self.buckets]
self.radix_wtoi = {}
assert c.wtoi['<PAD>'] == -1
... | Input Manager object for Radix-token models. | InputManager_Radix | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputManager_Radix:
"""Input Manager object for Radix-token models."""
def __init__(self, config, is_inference=False):
"""Loads the h5 file containing caption data and corresponding image paths."""
<|body_0|>
def _gen(self, data, is_training=True):
"""Generator f... | stack_v2_sparse_classes_36k_train_030177 | 19,609 | permissive | [
{
"docstring": "Loads the h5 file containing caption data and corresponding image paths.",
"name": "__init__",
"signature": "def __init__(self, config, is_inference=False)"
},
{
"docstring": "Generator fn, yields the image filepath and word IDs. Handles dataset shuffling.",
"name": "_gen",
... | 2 | stack_v2_sparse_classes_30k_train_012305 | Implement the Python class `InputManager_Radix` described below.
Class description:
Input Manager object for Radix-token models.
Method signatures and docstrings:
- def __init__(self, config, is_inference=False): Loads the h5 file containing caption data and corresponding image paths.
- def _gen(self, data, is_traini... | Implement the Python class `InputManager_Radix` described below.
Class description:
Input Manager object for Radix-token models.
Method signatures and docstrings:
- def __init__(self, config, is_inference=False): Loads the h5 file containing caption data and corresponding image paths.
- def _gen(self, data, is_traini... | 73165e0aac2816e89732571814f978801958e1ac | <|skeleton|>
class InputManager_Radix:
"""Input Manager object for Radix-token models."""
def __init__(self, config, is_inference=False):
"""Loads the h5 file containing caption data and corresponding image paths."""
<|body_0|>
def _gen(self, data, is_training=True):
"""Generator f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InputManager_Radix:
"""Input Manager object for Radix-token models."""
def __init__(self, config, is_inference=False):
"""Loads the h5 file containing caption data and corresponding image paths."""
super(InputManager_Radix, self).__init__(config, is_inference)
c = self.config
... | the_stack_v2_python_sparse | common/inputs/manager_image_caption.py | jiahuei/COMIC-Compact-Image-Captioning-with-Attention | train | 10 |
e231b5e86acffc23ea9f76f27416facedbaa43cd | [
"super().__init__()\nself.type_name = type_name\nself.argument_declarations = argument_declarations\nself.output_type_name = output_type_name\nself.description = None",
"variables = [var_declaration.execute(session, context) for var_declaration in reversed(self.argument_declarations)]\nself.type_name.namespace = ... | <|body_start_0|>
super().__init__()
self.type_name = type_name
self.argument_declarations = argument_declarations
self.output_type_name = output_type_name
self.description = None
<|end_body_0|>
<|body_start_1|>
variables = [var_declaration.execute(session, context) for v... | TypeDeclaration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TypeDeclaration:
def __init__(self, type_name, argument_declarations, output_type_name):
"""The type declaration :param type_name: the type name :type type_name: TypeName :param argument_declarations: the list of argument declarations :type argument_declarations: List[ArgumentDeclaration... | stack_v2_sparse_classes_36k_train_030178 | 3,531 | permissive | [
{
"docstring": "The type declaration :param type_name: the type name :type type_name: TypeName :param argument_declarations: the list of argument declarations :type argument_declarations: List[ArgumentDeclaration] :param output_type_name: the type_name as output, default to boolean :type output_type_name: TypeN... | 2 | null | Implement the Python class `TypeDeclaration` described below.
Class description:
Implement the TypeDeclaration class.
Method signatures and docstrings:
- def __init__(self, type_name, argument_declarations, output_type_name): The type declaration :param type_name: the type name :type type_name: TypeName :param argume... | Implement the Python class `TypeDeclaration` described below.
Class description:
Implement the TypeDeclaration class.
Method signatures and docstrings:
- def __init__(self, type_name, argument_declarations, output_type_name): The type declaration :param type_name: the type name :type type_name: TypeName :param argume... | ff76e030d7cebdca51c72d5d7e789d90f0e1e565 | <|skeleton|>
class TypeDeclaration:
def __init__(self, type_name, argument_declarations, output_type_name):
"""The type declaration :param type_name: the type name :type type_name: TypeName :param argument_declarations: the list of argument declarations :type argument_declarations: List[ArgumentDeclaration... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TypeDeclaration:
def __init__(self, type_name, argument_declarations, output_type_name):
"""The type declaration :param type_name: the type name :type type_name: TypeName :param argument_declarations: the list of argument declarations :type argument_declarations: List[ArgumentDeclaration] :param outpu... | the_stack_v2_python_sparse | norm/executable/declaration.py | xumiao/supernorm | train | 0 | |
98ac2cc232c35db50f48ce1d2987ecfc30d45643 | [
"self.dataset = dataset\nself.preprocess = preprocess\nself.steps_per_epoch = steps_per_epoch\nif preprocess is not None and use_cache:\n cache_dir = getattr(dataset.cfg, 'cache_dir')\n assert cache_dir is not None, 'cache directory is not given'\n self.cache_convert = Cache(preprocess, cache_dir=cache_dir... | <|body_start_0|>
self.dataset = dataset
self.preprocess = preprocess
self.steps_per_epoch = steps_per_epoch
if preprocess is not None and use_cache:
cache_dir = getattr(dataset.cfg, 'cache_dir')
assert cache_dir is not None, 'cache directory is not given'
... | This class allows you to load datasets for a PyTorch framework. Example: This example loads the SemanticKITTI dataset using the Torch dataloader: import torch from torch.utils.data import Dataset, DataLoader train_split = TorchDataloader(dataset=dataset.get_split('training')) | TorchDataloader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TorchDataloader:
"""This class allows you to load datasets for a PyTorch framework. Example: This example loads the SemanticKITTI dataset using the Torch dataloader: import torch from torch.utils.data import Dataset, DataLoader train_split = TorchDataloader(dataset=dataset.get_split('training'))"... | stack_v2_sparse_classes_36k_train_030179 | 3,452 | permissive | [
{
"docstring": "Initialize. Args: dataset: The 3D ML dataset class. You can use the base dataset, sample datasets , or a custom dataset. preprocess: The model's pre-process method. transform: The model's transform method. use_cache: Indicates if preprocessed data should be cached. steps_per_epoch: The number of... | 3 | null | Implement the Python class `TorchDataloader` described below.
Class description:
This class allows you to load datasets for a PyTorch framework. Example: This example loads the SemanticKITTI dataset using the Torch dataloader: import torch from torch.utils.data import Dataset, DataLoader train_split = TorchDataloader(... | Implement the Python class `TorchDataloader` described below.
Class description:
This class allows you to load datasets for a PyTorch framework. Example: This example loads the SemanticKITTI dataset using the Torch dataloader: import torch from torch.utils.data import Dataset, DataLoader train_split = TorchDataloader(... | 51482281dc180786e7563c73c12ac5df89289748 | <|skeleton|>
class TorchDataloader:
"""This class allows you to load datasets for a PyTorch framework. Example: This example loads the SemanticKITTI dataset using the Torch dataloader: import torch from torch.utils.data import Dataset, DataLoader train_split = TorchDataloader(dataset=dataset.get_split('training'))"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TorchDataloader:
"""This class allows you to load datasets for a PyTorch framework. Example: This example loads the SemanticKITTI dataset using the Torch dataloader: import torch from torch.utils.data import Dataset, DataLoader train_split = TorchDataloader(dataset=dataset.get_split('training'))"""
def _... | the_stack_v2_python_sparse | ml3d/torch/dataloaders/torch_dataloader.py | CosmosHua/Open3D-ML | train | 0 |
67a38ae7286286c9128a2453a05fac46b3f96458 | [
"cur_start_idx = -1\ncandidates = []\nfor i in range(vector.shape[0]):\n if vector[i] == val:\n if cur_start_idx == -1:\n cur_start_idx = i\n else:\n if cur_start_idx == -1:\n continue\n if i - cur_start_idx + 1 > thresh:\n candidates.append([cur_start_idx... | <|body_start_0|>
cur_start_idx = -1
candidates = []
for i in range(vector.shape[0]):
if vector[i] == val:
if cur_start_idx == -1:
cur_start_idx = i
else:
if cur_start_idx == -1:
continue
... | Unsupervised sleep duration predictor from http://ieeexplore.ieee.org/document/6563918/ | SleepUnsupervisedPredictor | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SleepUnsupervisedPredictor:
"""Unsupervised sleep duration predictor from http://ieeexplore.ieee.org/document/6563918/"""
def find_longest_subvector(self, vector: object, val: object, thresh: object=8, gap: object=4) -> object:
""":rtype: object :param vector: :param val: :param thre... | stack_v2_sparse_classes_36k_train_030180 | 6,759 | permissive | [
{
"docstring": ":rtype: object :param vector: :param val: :param thresh: :param gap: :return:",
"name": "find_longest_subvector",
"signature": "def find_longest_subvector(self, vector: object, val: object, thresh: object=8, gap: object=4) -> object"
},
{
"docstring": ":rtype: object :param a: :p... | 6 | stack_v2_sparse_classes_30k_train_013519 | Implement the Python class `SleepUnsupervisedPredictor` described below.
Class description:
Unsupervised sleep duration predictor from http://ieeexplore.ieee.org/document/6563918/
Method signatures and docstrings:
- def find_longest_subvector(self, vector: object, val: object, thresh: object=8, gap: object=4) -> obje... | Implement the Python class `SleepUnsupervisedPredictor` described below.
Class description:
Unsupervised sleep duration predictor from http://ieeexplore.ieee.org/document/6563918/
Method signatures and docstrings:
- def find_longest_subvector(self, vector: object, val: object, thresh: object=8, gap: object=4) -> obje... | 73f5ea2430bc7c23de422dccb7b65ef9f8917595 | <|skeleton|>
class SleepUnsupervisedPredictor:
"""Unsupervised sleep duration predictor from http://ieeexplore.ieee.org/document/6563918/"""
def find_longest_subvector(self, vector: object, val: object, thresh: object=8, gap: object=4) -> object:
""":rtype: object :param vector: :param val: :param thre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SleepUnsupervisedPredictor:
"""Unsupervised sleep duration predictor from http://ieeexplore.ieee.org/document/6563918/"""
def find_longest_subvector(self, vector: object, val: object, thresh: object=8, gap: object=4) -> object:
""":rtype: object :param vector: :param val: :param thresh: :param ga... | the_stack_v2_python_sparse | core/feature/sleep_duration/SleepUnsupervisedPredictor.py | MD2Korg/CerebralCortex-DataAnalysis | train | 1 |
d7cafd62100b8d9670cddc9a1aa6f603226fd085 | [
"self.value: str | None = None\nself.hass = hass\nself.command = command\nself.timeout = command_timeout",
"command = self.command\nif ' ' not in command:\n prog = command\n args = None\n args_compiled = None\nelse:\n prog, args = command.split(' ', 1)\n args_compiled = Template(args, self.hass)\ni... | <|body_start_0|>
self.value: str | None = None
self.hass = hass
self.command = command
self.timeout = command_timeout
<|end_body_0|>
<|body_start_1|>
command = self.command
if ' ' not in command:
prog = command
args = None
args_compile... | The class for handling the data retrieval. | CommandSensorData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandSensorData:
"""The class for handling the data retrieval."""
def __init__(self, hass: HomeAssistant, command: str, command_timeout: int) -> None:
"""Initialize the data object."""
<|body_0|>
def update(self) -> None:
"""Get the latest data with a shell com... | stack_v2_sparse_classes_36k_train_030181 | 9,547 | permissive | [
{
"docstring": "Initialize the data object.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, command: str, command_timeout: int) -> None"
},
{
"docstring": "Get the latest data with a shell command.",
"name": "update",
"signature": "def update(self) -> None"
... | 2 | null | Implement the Python class `CommandSensorData` described below.
Class description:
The class for handling the data retrieval.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, command: str, command_timeout: int) -> None: Initialize the data object.
- def update(self) -> None: Get the latest ... | Implement the Python class `CommandSensorData` described below.
Class description:
The class for handling the data retrieval.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, command: str, command_timeout: int) -> None: Initialize the data object.
- def update(self) -> None: Get the latest ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class CommandSensorData:
"""The class for handling the data retrieval."""
def __init__(self, hass: HomeAssistant, command: str, command_timeout: int) -> None:
"""Initialize the data object."""
<|body_0|>
def update(self) -> None:
"""Get the latest data with a shell com... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommandSensorData:
"""The class for handling the data retrieval."""
def __init__(self, hass: HomeAssistant, command: str, command_timeout: int) -> None:
"""Initialize the data object."""
self.value: str | None = None
self.hass = hass
self.command = command
self.tim... | the_stack_v2_python_sparse | homeassistant/components/command_line/sensor.py | home-assistant/core | train | 35,501 |
49ce6e2a0ecf10003ba26fdd3def56ec42be51db | [
"mro = self.CustomError.mro()\nassert 'RuntimeError' == mro[1].__name__\nassert 'Exception' == mro[2].__name__\nassert 'BaseException' == mro[3].__name__",
"result = None\ntry:\n self.fail('Oops')\nexcept Exception as e:\n result = 'exception handled'\n e2 = e\nassert 'exception handled' == result\nasser... | <|body_start_0|>
mro = self.CustomError.mro()
assert 'RuntimeError' == mro[1].__name__
assert 'Exception' == mro[2].__name__
assert 'BaseException' == mro[3].__name__
<|end_body_0|>
<|body_start_1|>
result = None
try:
self.fail('Oops')
except Exceptio... | 파이썬으로 코딩을 할 때 피할 수는 있지만 피하기 어려운 것이 에러입니다. 파이썬에서는 이들을 예외 (Exception) 이라고 부릅니다. pyt 이번에는 파이썬의 예외 처리는 어떻게 하고 어떤 예외들이 있는지 등 보겠습니다. | PythonExceptions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PythonExceptions:
"""파이썬으로 코딩을 할 때 피할 수는 있지만 피하기 어려운 것이 에러입니다. 파이썬에서는 이들을 예외 (Exception) 이라고 부릅니다. pyt 이번에는 파이썬의 예외 처리는 어떻게 하고 어떤 예외들이 있는지 등 보겠습니다."""
def test_about_exception_inheritance(self):
"""여기에서 나오는 `mro` 에 대해서는 자세히 아실 필요는 없습니다. 다만 해당 테스트를 통과하면서 어떤 것들이 나오는지 살펴보시면 될 것 같습니다. 직접... | stack_v2_sparse_classes_36k_train_030182 | 21,323 | no_license | [
{
"docstring": "여기에서 나오는 `mro` 에 대해서는 자세히 아실 필요는 없습니다. 다만 해당 테스트를 통과하면서 어떤 것들이 나오는지 살펴보시면 될 것 같습니다. 직접 파이썬으로 확인해 보시면서 테스트를 통과해주세요",
"name": "test_about_exception_inheritance",
"signature": "def test_about_exception_inheritance(self)"
},
{
"docstring": "try... except 는 파이썬에서 예외처리할 때 사용되는 매우 중요한 기... | 5 | stack_v2_sparse_classes_30k_train_007769 | Implement the Python class `PythonExceptions` described below.
Class description:
파이썬으로 코딩을 할 때 피할 수는 있지만 피하기 어려운 것이 에러입니다. 파이썬에서는 이들을 예외 (Exception) 이라고 부릅니다. pyt 이번에는 파이썬의 예외 처리는 어떻게 하고 어떤 예외들이 있는지 등 보겠습니다.
Method signatures and docstrings:
- def test_about_exception_inheritance(self): 여기에서 나오는 `mro` 에 대해서는 자세히 아실 ... | Implement the Python class `PythonExceptions` described below.
Class description:
파이썬으로 코딩을 할 때 피할 수는 있지만 피하기 어려운 것이 에러입니다. 파이썬에서는 이들을 예외 (Exception) 이라고 부릅니다. pyt 이번에는 파이썬의 예외 처리는 어떻게 하고 어떤 예외들이 있는지 등 보겠습니다.
Method signatures and docstrings:
- def test_about_exception_inheritance(self): 여기에서 나오는 `mro` 에 대해서는 자세히 아실 ... | 8dbd1eea6195df8b0dc1798d1ba2e27929c4eda7 | <|skeleton|>
class PythonExceptions:
"""파이썬으로 코딩을 할 때 피할 수는 있지만 피하기 어려운 것이 에러입니다. 파이썬에서는 이들을 예외 (Exception) 이라고 부릅니다. pyt 이번에는 파이썬의 예외 처리는 어떻게 하고 어떤 예외들이 있는지 등 보겠습니다."""
def test_about_exception_inheritance(self):
"""여기에서 나오는 `mro` 에 대해서는 자세히 아실 필요는 없습니다. 다만 해당 테스트를 통과하면서 어떤 것들이 나오는지 살펴보시면 될 것 같습니다. 직접... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PythonExceptions:
"""파이썬으로 코딩을 할 때 피할 수는 있지만 피하기 어려운 것이 에러입니다. 파이썬에서는 이들을 예외 (Exception) 이라고 부릅니다. pyt 이번에는 파이썬의 예외 처리는 어떻게 하고 어떤 예외들이 있는지 등 보겠습니다."""
def test_about_exception_inheritance(self):
"""여기에서 나오는 `mro` 에 대해서는 자세히 아실 필요는 없습니다. 다만 해당 테스트를 통과하면서 어떤 것들이 나오는지 살펴보시면 될 것 같습니다. 직접 파이썬으로 확인해 보시... | the_stack_v2_python_sparse | Python/src/Part_2.py | effection00/Study-Record | train | 0 |
5bce473350076a4b36778b6a885ec49b6fd68e36 | [
"super(PairMPN, self).__init__()\nself.args = args\nself.atom_fdim = atom_fdim or get_atom_fdim(args)\nself.bond_fdim = bond_fdim or get_bond_fdim(args) + (not args.atom_messages) * self.atom_fdim\nself.graph_input = graph_input\nself.encoder = PairMPNEncoder(self.args, self.atom_fdim, self.bond_fdim)",
"if not s... | <|body_start_0|>
super(PairMPN, self).__init__()
self.args = args
self.atom_fdim = atom_fdim or get_atom_fdim(args)
self.bond_fdim = bond_fdim or get_bond_fdim(args) + (not args.atom_messages) * self.atom_fdim
self.graph_input = graph_input
self.encoder = PairMPNEncoder(s... | A message passing neural network for encoding a molecule. | PairMPN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PairMPN:
"""A message passing neural network for encoding a molecule."""
def __init__(self, args: Namespace, atom_fdim: int=None, bond_fdim: int=None, graph_input: bool=False):
"""Initializes the MPN. :param args: Arguments. :param atom_fdim: Atom features dimension. :param bond_fdim... | stack_v2_sparse_classes_36k_train_030183 | 26,669 | no_license | [
{
"docstring": "Initializes the MPN. :param args: Arguments. :param atom_fdim: Atom features dimension. :param bond_fdim: Bond features dimension. :param graph_input: If true, expects BatchMolGraph as input. Otherwise expects a list of smiles strings as input.",
"name": "__init__",
"signature": "def __i... | 2 | stack_v2_sparse_classes_30k_train_003213 | Implement the Python class `PairMPN` described below.
Class description:
A message passing neural network for encoding a molecule.
Method signatures and docstrings:
- def __init__(self, args: Namespace, atom_fdim: int=None, bond_fdim: int=None, graph_input: bool=False): Initializes the MPN. :param args: Arguments. :p... | Implement the Python class `PairMPN` described below.
Class description:
A message passing neural network for encoding a molecule.
Method signatures and docstrings:
- def __init__(self, args: Namespace, atom_fdim: int=None, bond_fdim: int=None, graph_input: bool=False): Initializes the MPN. :param args: Arguments. :p... | 1851765edfd77f4a1ebd1702b32a11a6e8e8f01d | <|skeleton|>
class PairMPN:
"""A message passing neural network for encoding a molecule."""
def __init__(self, args: Namespace, atom_fdim: int=None, bond_fdim: int=None, graph_input: bool=False):
"""Initializes the MPN. :param args: Arguments. :param atom_fdim: Atom features dimension. :param bond_fdim... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PairMPN:
"""A message passing neural network for encoding a molecule."""
def __init__(self, args: Namespace, atom_fdim: int=None, bond_fdim: int=None, graph_input: bool=False):
"""Initializes the MPN. :param args: Arguments. :param atom_fdim: Atom features dimension. :param bond_fdim: Bond featur... | the_stack_v2_python_sparse | MIRACLE/models/mpn.py | aabbccgithub/MIRACLE | train | 0 |
2f80ec6c290ed313b7e4d82773ec91abd68701e8 | [
"slow = 0\nfor fast in range(len(nums)):\n if nums[fast] != val:\n nums[slow] = nums[fast]\n slow += 1\nreturn slow",
"l = 0\nr = len(nums) - 1\nwhile l <= r:\n if nums[l] == val:\n nums[l] = nums[r]\n r = r - 1\n else:\n l += 1\nreturn l",
"if len(nums) == 0:\n re... | <|body_start_0|>
slow = 0
for fast in range(len(nums)):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
return slow
<|end_body_0|>
<|body_start_1|>
l = 0
r = len(nums) - 1
while l <= r:
if nums[l] == val:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
"""快慢指针,遍历一次,不管后面的元素"""
<|body_0|>
def removeElement_modify(self, nums: List[int], val: int) -> int:
"""首尾指针"""
<|body_1|>
def removeElement_del(self, nums: List[int], val: int) -> int:... | stack_v2_sparse_classes_36k_train_030184 | 1,524 | no_license | [
{
"docstring": "快慢指针,遍历一次,不管后面的元素",
"name": "removeElement",
"signature": "def removeElement(self, nums: List[int], val: int) -> int"
},
{
"docstring": "首尾指针",
"name": "removeElement_modify",
"signature": "def removeElement_modify(self, nums: List[int], val: int) -> int"
},
{
"do... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums: List[int], val: int) -> int: 快慢指针,遍历一次,不管后面的元素
- def removeElement_modify(self, nums: List[int], val: int) -> int: 首尾指针
- def removeElement_del(self... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums: List[int], val: int) -> int: 快慢指针,遍历一次,不管后面的元素
- def removeElement_modify(self, nums: List[int], val: int) -> int: 首尾指针
- def removeElement_del(self... | e5b680db40de95f8f4b47e9b399942369c2081d9 | <|skeleton|>
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
"""快慢指针,遍历一次,不管后面的元素"""
<|body_0|>
def removeElement_modify(self, nums: List[int], val: int) -> int:
"""首尾指针"""
<|body_1|>
def removeElement_del(self, nums: List[int], val: int) -> int:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
"""快慢指针,遍历一次,不管后面的元素"""
slow = 0
for fast in range(len(nums)):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
return slow
def removeElement_modify(self... | the_stack_v2_python_sparse | leetcode/array/27.py | YutingYao/leetcode-3 | train | 0 | |
fdaaa14690f95a12a8e9fa260bd7eaca88d6d290 | [
"n -= 1\nstart_point = 0\nend_point = 26\nwidth = 1\npows = 676\nwhile n >= end_point:\n end_point = end_point + pows\n pows *= 26\n width += 1\nstart_point = end_point - int(pows // 26)\nreturn self.range_0_convert(n - start_point, width)",
"chap_dict0 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nlist_s = []\nprint(... | <|body_start_0|>
n -= 1
start_point = 0
end_point = 26
width = 1
pows = 676
while n >= end_point:
end_point = end_point + pows
pows *= 26
width += 1
start_point = end_point - int(pows // 26)
return self.range_0_convert(n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def convertToTitle(self, n):
""":type n: int :rtype: str"""
<|body_0|>
def range_0_convert(self, x, width):
"""标准的进制转换函数 由于需要用字符表示结果,所以需要用width来 指定结果的宽度 保证高位在数值上为0时用字符A来填充"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n -= 1
star... | stack_v2_sparse_classes_36k_train_030185 | 1,281 | no_license | [
{
"docstring": ":type n: int :rtype: str",
"name": "convertToTitle",
"signature": "def convertToTitle(self, n)"
},
{
"docstring": "标准的进制转换函数 由于需要用字符表示结果,所以需要用width来 指定结果的宽度 保证高位在数值上为0时用字符A来填充",
"name": "range_0_convert",
"signature": "def range_0_convert(self, x, width)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010686 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def convertToTitle(self, n): :type n: int :rtype: str
- def range_0_convert(self, x, width): 标准的进制转换函数 由于需要用字符表示结果,所以需要用width来 指定结果的宽度 保证高位在数值上为0时用字符A来填充 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def convertToTitle(self, n): :type n: int :rtype: str
- def range_0_convert(self, x, width): 标准的进制转换函数 由于需要用字符表示结果,所以需要用width来 指定结果的宽度 保证高位在数值上为0时用字符A来填充
<|skeleton|>
class Solu... | 7a1c3aba65f338f6e11afd2864dabd2b26142b6c | <|skeleton|>
class Solution:
def convertToTitle(self, n):
""":type n: int :rtype: str"""
<|body_0|>
def range_0_convert(self, x, width):
"""标准的进制转换函数 由于需要用字符表示结果,所以需要用width来 指定结果的宽度 保证高位在数值上为0时用字符A来填充"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def convertToTitle(self, n):
""":type n: int :rtype: str"""
n -= 1
start_point = 0
end_point = 26
width = 1
pows = 676
while n >= end_point:
end_point = end_point + pows
pows *= 26
width += 1
start_po... | the_stack_v2_python_sparse | exercise/leetcode/python_src/by2017_Sep/Leet168.py | SS4G/AlgorithmTraining | train | 2 | |
07472fe25e1c1205c149c43d7409473aadc31caf | [
"if stm_queue is None:\n self._stm_queue = multiprocessing.Queue()\nelse:\n self._stm_queue = stm_queue\nif solver_id is None:\n self._solver_id = uuid.uuid4()\nelse:\n self._solver_id = solver_id\nself._mts_queue = multiprocessing.Queue()\nself._process = SolverProcess(parse, prepare(command, root, tas... | <|body_start_0|>
if stm_queue is None:
self._stm_queue = multiprocessing.Queue()
else:
self._stm_queue = stm_queue
if solver_id is None:
self._solver_id = uuid.uuid4()
else:
self._solver_id = solver_id
self._mts_queue = multiprocess... | In-progress solver process. | RunningSolver | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunningSolver:
"""In-progress solver process."""
def __init__(self, parse, command, root, task_path, stm_queue=None, solver_id=None):
"""Initialize."""
<|body_0|>
def __call__(self, budget):
"""Unpause the solver, block for some limit, and terminate it."""
... | stack_v2_sparse_classes_36k_train_030186 | 6,006 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, parse, command, root, task_path, stm_queue=None, solver_id=None)"
},
{
"docstring": "Unpause the solver, block for some limit, and terminate it.",
"name": "__call__",
"signature": "def __call__(self, budge... | 4 | stack_v2_sparse_classes_30k_train_003608 | Implement the Python class `RunningSolver` described below.
Class description:
In-progress solver process.
Method signatures and docstrings:
- def __init__(self, parse, command, root, task_path, stm_queue=None, solver_id=None): Initialize.
- def __call__(self, budget): Unpause the solver, block for some limit, and te... | Implement the Python class `RunningSolver` described below.
Class description:
In-progress solver process.
Method signatures and docstrings:
- def __init__(self, parse, command, root, task_path, stm_queue=None, solver_id=None): Initialize.
- def __call__(self, budget): Unpause the solver, block for some limit, and te... | 62982bd3babe627f5579e428ec9543a9103073bb | <|skeleton|>
class RunningSolver:
"""In-progress solver process."""
def __init__(self, parse, command, root, task_path, stm_queue=None, solver_id=None):
"""Initialize."""
<|body_0|>
def __call__(self, budget):
"""Unpause the solver, block for some limit, and terminate it."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunningSolver:
"""In-progress solver process."""
def __init__(self, parse, command, root, task_path, stm_queue=None, solver_id=None):
"""Initialize."""
if stm_queue is None:
self._stm_queue = multiprocessing.Queue()
else:
self._stm_queue = stm_queue
... | the_stack_v2_python_sparse | src/python/borg/solver_io.py | buhman/borg | train | 0 |
6d13594c616df7afaa64c093578aa4e4c3c64b01 | [
"dp = [0] * len(books)\ndp[0] = books[0][1]\nfor i, (w, h) in enumerate(books[1:], start=1):\n ti = i - 1\n mxh = h\n dp[i] = h + dp[ti]\n while ti > -1 and w + books[ti][0] <= shelf_width:\n mxh = max(mxh, books[ti][1])\n dp[i] = min(dp[i], mxh + (dp[ti - 1] if ti > 0 else 0))\n w ... | <|body_start_0|>
dp = [0] * len(books)
dp[0] = books[0][1]
for i, (w, h) in enumerate(books[1:], start=1):
ti = i - 1
mxh = h
dp[i] = h + dp[ti]
while ti > -1 and w + books[ti][0] <= shelf_width:
mxh = max(mxh, books[ti][1])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minHeightShelves(self, books, shelf_width):
""":type books: List[List[int]] :type shelf_width: int :rtype: int"""
<|body_0|>
def minHeightShelves2(self, books, shelf_width):
""":type books: List[List[int]] :type shelf_width: int :rtype: int"""
<... | stack_v2_sparse_classes_36k_train_030187 | 4,978 | no_license | [
{
"docstring": ":type books: List[List[int]] :type shelf_width: int :rtype: int",
"name": "minHeightShelves",
"signature": "def minHeightShelves(self, books, shelf_width)"
},
{
"docstring": ":type books: List[List[int]] :type shelf_width: int :rtype: int",
"name": "minHeightShelves2",
"s... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minHeightShelves(self, books, shelf_width): :type books: List[List[int]] :type shelf_width: int :rtype: int
- def minHeightShelves2(self, books, shelf_width): :type books: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minHeightShelves(self, books, shelf_width): :type books: List[List[int]] :type shelf_width: int :rtype: int
- def minHeightShelves2(self, books, shelf_width): :type books: Li... | dbdb227e12f329e4ca064b338f1fbdca42f3a848 | <|skeleton|>
class Solution:
def minHeightShelves(self, books, shelf_width):
""":type books: List[List[int]] :type shelf_width: int :rtype: int"""
<|body_0|>
def minHeightShelves2(self, books, shelf_width):
""":type books: List[List[int]] :type shelf_width: int :rtype: int"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minHeightShelves(self, books, shelf_width):
""":type books: List[List[int]] :type shelf_width: int :rtype: int"""
dp = [0] * len(books)
dp[0] = books[0][1]
for i, (w, h) in enumerate(books[1:], start=1):
ti = i - 1
mxh = h
dp[i]... | the_stack_v2_python_sparse | LC1105.py | Qiao-Liang/LeetCode | train | 0 | |
52dc1724098928eb9c09b7f46de960d5d87b9879 | [
"super().__init__(*args, **kwargs)\nfor cog in cogs:\n try:\n self.load_extension(cog)\n except Exception as e:\n print('Failed to load extension ' + cog + '.')\n print(e)",
"if not hasattr(self, 'uptime'):\n self.uptime = datetime.datetime.now()\nprint('-' * 30)\nprint('Logged in as... | <|body_start_0|>
super().__init__(*args, **kwargs)
for cog in cogs:
try:
self.load_extension(cog)
except Exception as e:
print('Failed to load extension ' + cog + '.')
print(e)
<|end_body_0|>
<|body_start_1|>
if not hasattr... | DungeonBot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DungeonBot:
def __init__(self, *args, **kwargs):
"""Main bot object. This is used to play the game through discord."""
<|body_0|>
async def on_ready(self):
"""Function that runs when the bot starts."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
su... | stack_v2_sparse_classes_36k_train_030188 | 1,548 | no_license | [
{
"docstring": "Main bot object. This is used to play the game through discord.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Function that runs when the bot starts.",
"name": "on_ready",
"signature": "async def on_ready(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007538 | Implement the Python class `DungeonBot` described below.
Class description:
Implement the DungeonBot class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Main bot object. This is used to play the game through discord.
- async def on_ready(self): Function that runs when the bot starts. | Implement the Python class `DungeonBot` described below.
Class description:
Implement the DungeonBot class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Main bot object. This is used to play the game through discord.
- async def on_ready(self): Function that runs when the bot starts.
<|sk... | 0484df39ebd5eb0c2cbc8ad0e1863182751e5d72 | <|skeleton|>
class DungeonBot:
def __init__(self, *args, **kwargs):
"""Main bot object. This is used to play the game through discord."""
<|body_0|>
async def on_ready(self):
"""Function that runs when the bot starts."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DungeonBot:
def __init__(self, *args, **kwargs):
"""Main bot object. This is used to play the game through discord."""
super().__init__(*args, **kwargs)
for cog in cogs:
try:
self.load_extension(cog)
except Exception as e:
print('... | the_stack_v2_python_sparse | bot.py | emiipo/discord-and-dragons | train | 0 | |
b6880a38e4b3c47987ace83bf5be200767f17ec0 | [
"self.name = name\nself.type = self.RSC_TYPE_MAP.get(type, None)\nif not self.type:\n raise HOTError('Unknown resource type: ' + type)\nself.prop = prop or {}\nself.metadata = metadata\nself.depends_on = depends_on",
"rsc = OrderedDict()\nrsc[self.TYPE] = self.type\nif self.prop:\n rsc[self.PROPERTIES] = se... | <|body_start_0|>
self.name = name
self.type = self.RSC_TYPE_MAP.get(type, None)
if not self.type:
raise HOTError('Unknown resource type: ' + type)
self.prop = prop or {}
self.metadata = metadata
self.depends_on = depends_on
<|end_body_0|>
<|body_start_1|>
... | HOT Resource Attr | Resource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resource:
"""HOT Resource Attr"""
def __init__(self, name, type=None, prop=None, metadata=None, depends_on=None):
"""Init a HOT resource"""
<|body_0|>
def get_output_dict(self):
"""Output a resource as a nested dict"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_030189 | 6,215 | no_license | [
{
"docstring": "Init a HOT resource",
"name": "__init__",
"signature": "def __init__(self, name, type=None, prop=None, metadata=None, depends_on=None)"
},
{
"docstring": "Output a resource as a nested dict",
"name": "get_output_dict",
"signature": "def get_output_dict(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010672 | Implement the Python class `Resource` described below.
Class description:
HOT Resource Attr
Method signatures and docstrings:
- def __init__(self, name, type=None, prop=None, metadata=None, depends_on=None): Init a HOT resource
- def get_output_dict(self): Output a resource as a nested dict | Implement the Python class `Resource` described below.
Class description:
HOT Resource Attr
Method signatures and docstrings:
- def __init__(self, name, type=None, prop=None, metadata=None, depends_on=None): Init a HOT resource
- def get_output_dict(self): Output a resource as a nested dict
<|skeleton|>
class Resour... | 103d9ffb67e98c6e912a5861b73ad0f06d9df80c | <|skeleton|>
class Resource:
"""HOT Resource Attr"""
def __init__(self, name, type=None, prop=None, metadata=None, depends_on=None):
"""Init a HOT resource"""
<|body_0|>
def get_output_dict(self):
"""Output a resource as a nested dict"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Resource:
"""HOT Resource Attr"""
def __init__(self, name, type=None, prop=None, metadata=None, depends_on=None):
"""Init a HOT resource"""
self.name = name
self.type = self.RSC_TYPE_MAP.get(type, None)
if not self.type:
raise HOTError('Unknown resource type: '... | the_stack_v2_python_sparse | sfc-ostack/sfcostack/hot.py | stevelorenz/sfc-ostack | train | 4 |
428b05d296b485f838d53df768c07baab42c40c3 | [
"self.ad_options = ad_options\nself.credentials = credentials\nself.mount_and_restore = mount_and_restore\nself.port = port",
"if dictionary is None:\n return None\nad_options = cohesity_management_sdk.models.ad_restore_options.AdRestoreOptions.from_dictionary(dictionary.get('adOptions')) if dictionary.get('ad... | <|body_start_0|>
self.ad_options = ad_options
self.credentials = credentials
self.mount_and_restore = mount_and_restore
self.port = port
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
ad_options = cohesity_management_sdk.models.ad_restore_... | Implementation of the 'AdRestoreParameters' model. Specifies the parameters specific to Application domain controller. Attributes: ad_options (AdRestoreOptions): Specifies the Active Directory options for the Restore task. credentials (Credentials): Specifies the credentials which are needed to connect to Production AD... | AdRestoreParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdRestoreParameters:
"""Implementation of the 'AdRestoreParameters' model. Specifies the parameters specific to Application domain controller. Attributes: ad_options (AdRestoreOptions): Specifies the Active Directory options for the Restore task. credentials (Credentials): Specifies the credentia... | stack_v2_sparse_classes_36k_train_030190 | 2,767 | permissive | [
{
"docstring": "Constructor for the AdRestoreParameters class",
"name": "__init__",
"signature": "def __init__(self, ad_options=None, credentials=None, mount_and_restore=None, port=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dict... | 2 | null | Implement the Python class `AdRestoreParameters` described below.
Class description:
Implementation of the 'AdRestoreParameters' model. Specifies the parameters specific to Application domain controller. Attributes: ad_options (AdRestoreOptions): Specifies the Active Directory options for the Restore task. credentials... | Implement the Python class `AdRestoreParameters` described below.
Class description:
Implementation of the 'AdRestoreParameters' model. Specifies the parameters specific to Application domain controller. Attributes: ad_options (AdRestoreOptions): Specifies the Active Directory options for the Restore task. credentials... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class AdRestoreParameters:
"""Implementation of the 'AdRestoreParameters' model. Specifies the parameters specific to Application domain controller. Attributes: ad_options (AdRestoreOptions): Specifies the Active Directory options for the Restore task. credentials (Credentials): Specifies the credentia... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdRestoreParameters:
"""Implementation of the 'AdRestoreParameters' model. Specifies the parameters specific to Application domain controller. Attributes: ad_options (AdRestoreOptions): Specifies the Active Directory options for the Restore task. credentials (Credentials): Specifies the credentials which are ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/ad_restore_parameters.py | cohesity/management-sdk-python | train | 24 |
55cee0c79828634ce854677b362a947dfa2286e0 | [
"if len(nums) == 0:\n return []\nresult = [0]\nself.root = Node(nums[-1])\nfor i in range(len(nums) - 2, -1, -1):\n self.addNum(nums[i], result)\nresult.reverse()\nreturn result",
"smaller = 0\nnode = self.root\nwhile True:\n if num < node.val:\n node.smallAmount += 1\n if node.left:\n ... | <|body_start_0|>
if len(nums) == 0:
return []
result = [0]
self.root = Node(nums[-1])
for i in range(len(nums) - 2, -1, -1):
self.addNum(nums[i], result)
result.reverse()
return result
<|end_body_0|>
<|body_start_1|>
smaller = 0
no... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countSmaller(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def addNum(self, num, result):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len... | stack_v2_sparse_classes_36k_train_030191 | 942 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "countSmaller",
"signature": "def countSmaller(self, nums)"
},
{
"docstring": "Adds a num into the data structure. :type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num, result)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSmaller(self, nums): :type nums: List[int] :rtype: List[int]
- def addNum(self, num, result): Adds a num into the data structure. :type num: int :rtype: void | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSmaller(self, nums): :type nums: List[int] :rtype: List[int]
- def addNum(self, num, result): Adds a num into the data structure. :type num: int :rtype: void
<|skeleton... | 15f012927dc34b5d751af6633caa5e8882d26ff7 | <|skeleton|>
class Solution:
def countSmaller(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def addNum(self, num, result):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countSmaller(self, nums):
""":type nums: List[int] :rtype: List[int]"""
if len(nums) == 0:
return []
result = [0]
self.root = Node(nums[-1])
for i in range(len(nums) - 2, -1, -1):
self.addNum(nums[i], result)
result.reverse(... | the_stack_v2_python_sparse | python/315.CountOfSmallerNumbersAfterSelf.py | MaxPoon/Leetcode | train | 15 | |
1bebf5d0ceac2ebb9379f272ee52d5b9dac018d6 | [
"key = LibraryLocatorV2.from_string(lib_key_str)\napi.require_permission_for_library_key(key, request.user, permissions.CAN_EDIT_THIS_CONTENT_LIBRARY_TEAM)\nserializer = ContentLibraryPermissionLevelSerializer(data=request.data)\nserializer.is_valid(raise_exception=True)\nuser = get_object_or_404(User, username=use... | <|body_start_0|>
key = LibraryLocatorV2.from_string(lib_key_str)
api.require_permission_for_library_key(key, request.user, permissions.CAN_EDIT_THIS_CONTENT_LIBRARY_TEAM)
serializer = ContentLibraryPermissionLevelSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
... | View to add/remove/edit an individual user's permissions for a content library. | LibraryTeamUserView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LibraryTeamUserView:
"""View to add/remove/edit an individual user's permissions for a content library."""
def put(self, request, lib_key_str, username):
"""Add a user to this content library, with permissions specified in the request body."""
<|body_0|>
def get(self, re... | stack_v2_sparse_classes_36k_train_030192 | 42,120 | permissive | [
{
"docstring": "Add a user to this content library, with permissions specified in the request body.",
"name": "put",
"signature": "def put(self, request, lib_key_str, username)"
},
{
"docstring": "Gets the current permissions settings for a particular user.",
"name": "get",
"signature": ... | 3 | null | Implement the Python class `LibraryTeamUserView` described below.
Class description:
View to add/remove/edit an individual user's permissions for a content library.
Method signatures and docstrings:
- def put(self, request, lib_key_str, username): Add a user to this content library, with permissions specified in the ... | Implement the Python class `LibraryTeamUserView` described below.
Class description:
View to add/remove/edit an individual user's permissions for a content library.
Method signatures and docstrings:
- def put(self, request, lib_key_str, username): Add a user to this content library, with permissions specified in the ... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class LibraryTeamUserView:
"""View to add/remove/edit an individual user's permissions for a content library."""
def put(self, request, lib_key_str, username):
"""Add a user to this content library, with permissions specified in the request body."""
<|body_0|>
def get(self, re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LibraryTeamUserView:
"""View to add/remove/edit an individual user's permissions for a content library."""
def put(self, request, lib_key_str, username):
"""Add a user to this content library, with permissions specified in the request body."""
key = LibraryLocatorV2.from_string(lib_key_st... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/content_libraries/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
28b2d67b6584d79dcc907f6282c07027b59eac75 | [
"with tf.Graph().as_default():\n lp_dict = layer_collection.LayerParametersDict()\n x = tf.constant(0)\n y0 = tf.constant(0)\n y1 = tf.constant(0)\n z0 = tf.constant(0)\n z1 = tf.constant(0)\n keys = [x, (y0, y1), [z0, z1]]\n for key in keys:\n lp_dict[key] = key\n for key in keys:... | <|body_start_0|>
with tf.Graph().as_default():
lp_dict = layer_collection.LayerParametersDict()
x = tf.constant(0)
y0 = tf.constant(0)
y1 = tf.constant(0)
z0 = tf.constant(0)
z1 = tf.constant(0)
keys = [x, (y0, y1), [z0, z1]]
... | LayerParametersDictTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerParametersDictTest:
def testSetItem(self):
"""Ensure insertion, contains, retrieval works for supported key types."""
<|body_0|>
def testSetItemOverlap(self):
"""Ensure insertion fails if key overlaps with existing key."""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_030193 | 22,448 | permissive | [
{
"docstring": "Ensure insertion, contains, retrieval works for supported key types.",
"name": "testSetItem",
"signature": "def testSetItem(self)"
},
{
"docstring": "Ensure insertion fails if key overlaps with existing key.",
"name": "testSetItemOverlap",
"signature": "def testSetItemOve... | 2 | stack_v2_sparse_classes_30k_train_006512 | Implement the Python class `LayerParametersDictTest` described below.
Class description:
Implement the LayerParametersDictTest class.
Method signatures and docstrings:
- def testSetItem(self): Ensure insertion, contains, retrieval works for supported key types.
- def testSetItemOverlap(self): Ensure insertion fails i... | Implement the Python class `LayerParametersDictTest` described below.
Class description:
Implement the LayerParametersDictTest class.
Method signatures and docstrings:
- def testSetItem(self): Ensure insertion, contains, retrieval works for supported key types.
- def testSetItemOverlap(self): Ensure insertion fails i... | ddad6375bbdebfae809bccfd3a5c3db073128764 | <|skeleton|>
class LayerParametersDictTest:
def testSetItem(self):
"""Ensure insertion, contains, retrieval works for supported key types."""
<|body_0|>
def testSetItemOverlap(self):
"""Ensure insertion fails if key overlaps with existing key."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LayerParametersDictTest:
def testSetItem(self):
"""Ensure insertion, contains, retrieval works for supported key types."""
with tf.Graph().as_default():
lp_dict = layer_collection.LayerParametersDict()
x = tf.constant(0)
y0 = tf.constant(0)
y1 = ... | the_stack_v2_python_sparse | kfac/python/kernel_tests/layer_collection_test.py | tensorflow/kfac | train | 193 | |
51d979ea01e43043b216ba828ebb768104c74327 | [
"wx.Panel.__init__(self, parent, id, size=(300, 180), style=wx.BORDER_SUNKEN)\nself.id = id\ntotaal = wx.BoxSizer(wx.VERTICAL)\ntotaal.Add(self.TextPaneel(), 1, wx.EXPAND | wx.ALL)\ntotaal.Add(self.RadioPaneel(), 1, wx.EXPAND | wx.ALL)\nself.SetSizer(totaal)",
"box = wx.BoxSizer(wx.VERTICAL)\nself.TekstPaneel = S... | <|body_start_0|>
wx.Panel.__init__(self, parent, id, size=(300, 180), style=wx.BORDER_SUNKEN)
self.id = id
totaal = wx.BoxSizer(wx.VERTICAL)
totaal.Add(self.TextPaneel(), 1, wx.EXPAND | wx.ALL)
totaal.Add(self.RadioPaneel(), 1, wx.EXPAND | wx.ALL)
self.SetSizer(totaal)
<|... | Klasse maakt een module die gebruikt kan worden om de gebruiker te vragen om een bestand op te slaan. Ook heeft de module een get() methode om een bestandsnaam op te halen en een set() methode om een waarschuwing aan te zetten. | OpslaanPaneel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpslaanPaneel:
"""Klasse maakt een module die gebruikt kan worden om de gebruiker te vragen om een bestand op te slaan. Ook heeft de module een get() methode om een bestandsnaam op te halen en een set() methode om een waarschuwing aan te zetten."""
def __init__(self, parent, id):
"""... | stack_v2_sparse_classes_36k_train_030194 | 5,633 | no_license | [
{
"docstring": "Maakt opslaan paneel met daarop een radiobox, txtctrl en text. De __init__ methode heeft 2 parameters. parent De ouder van het paneel id De id voor het paneel en het maken van widgets. De init roept de volgende methodes aan: TextPaneel() RadioPaneel() De methode maakt als eerste een paneel aan w... | 6 | stack_v2_sparse_classes_30k_train_013731 | Implement the Python class `OpslaanPaneel` described below.
Class description:
Klasse maakt een module die gebruikt kan worden om de gebruiker te vragen om een bestand op te slaan. Ook heeft de module een get() methode om een bestandsnaam op te halen en een set() methode om een waarschuwing aan te zetten.
Method sign... | Implement the Python class `OpslaanPaneel` described below.
Class description:
Klasse maakt een module die gebruikt kan worden om de gebruiker te vragen om een bestand op te slaan. Ook heeft de module een get() methode om een bestandsnaam op te halen en een set() methode om een waarschuwing aan te zetten.
Method sign... | 6093fb23294f0a5d42f61113e607d3c1fb94542f | <|skeleton|>
class OpslaanPaneel:
"""Klasse maakt een module die gebruikt kan worden om de gebruiker te vragen om een bestand op te slaan. Ook heeft de module een get() methode om een bestandsnaam op te halen en een set() methode om een waarschuwing aan te zetten."""
def __init__(self, parent, id):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpslaanPaneel:
"""Klasse maakt een module die gebruikt kan worden om de gebruiker te vragen om een bestand op te slaan. Ook heeft de module een get() methode om een bestandsnaam op te halen en een set() methode om een waarschuwing aan te zetten."""
def __init__(self, parent, id):
"""Maakt opslaan... | the_stack_v2_python_sparse | DNA-Mastermind-application/OpslaanPaneel.py | sdevriend/Student-Portfolio | train | 0 |
d424df40745d721af56378752862d40ed6d8a0b6 | [
"super(Classifier, self).__init__()\nself.num_keys = num_keys\nself.structure = structure\nclassifier = []\nfor layer_size in self.structure:\n classifier.append(layers.Dense(layer_size))\n classifier.append(layers.ReLU())\nclassifier.append(layers.Dense(num_keys))\nself.classifier = keras.Sequential(classifi... | <|body_start_0|>
super(Classifier, self).__init__()
self.num_keys = num_keys
self.structure = structure
classifier = []
for layer_size in self.structure:
classifier.append(layers.Dense(layer_size))
classifier.append(layers.ReLU())
classifier.append... | The classifier used in some learned decomposition experiments. Used for classifing the midi data from the decomposed representation. Multiple keys can be active at once. Hence, we use a sigmoid activation, not softmax. | Classifier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Classifier:
"""The classifier used in some learned decomposition experiments. Used for classifing the midi data from the decomposed representation. Multiple keys can be active at once. Hence, we use a sigmoid activation, not softmax."""
def __init__(self, num_keys, structure=[512, 128, 100])... | stack_v2_sparse_classes_36k_train_030195 | 6,582 | permissive | [
{
"docstring": "The initilizer for the Classifier model. Args: num_keys: The number of musical notes to classify in the midi data. structure: An array of dense layer sizes (int), one for each dense layer in the classifier structure.",
"name": "__init__",
"signature": "def __init__(self, num_keys, struct... | 2 | stack_v2_sparse_classes_30k_train_010681 | Implement the Python class `Classifier` described below.
Class description:
The classifier used in some learned decomposition experiments. Used for classifing the midi data from the decomposed representation. Multiple keys can be active at once. Hence, we use a sigmoid activation, not softmax.
Method signatures and d... | Implement the Python class `Classifier` described below.
Class description:
The classifier used in some learned decomposition experiments. Used for classifing the midi data from the decomposed representation. Multiple keys can be active at once. Hence, we use a sigmoid activation, not softmax.
Method signatures and d... | 732abbbe0953553d3e3c6d52f99abc5ef10612fc | <|skeleton|>
class Classifier:
"""The classifier used in some learned decomposition experiments. Used for classifing the midi data from the decomposed representation. Multiple keys can be active at once. Hence, we use a sigmoid activation, not softmax."""
def __init__(self, num_keys, structure=[512, 128, 100])... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Classifier:
"""The classifier used in some learned decomposition experiments. Used for classifing the midi data from the decomposed representation. Multiple keys can be active at once. Hence, we use a sigmoid activation, not softmax."""
def __init__(self, num_keys, structure=[512, 128, 100]):
"""... | the_stack_v2_python_sparse | structures/learned_basis_function.py | googleinterns/audio_synthesis | train | 0 |
79fc6a1fda36ac7cc0ab0c296780db2c3fcd26a9 | [
"from poHomework.page.contact_page import Contact\nself.driver.find_element_by_id('username').send_keys('jiang2')\nself.driver.find_element_by_id('memberAdd_acctid').send_keys('jiang2')\nself.driver.find_element_by_id('memberAdd_phone').send_keys('15010236359')\nself.driver.execute_script('window.scrollTo(0,documen... | <|body_start_0|>
from poHomework.page.contact_page import Contact
self.driver.find_element_by_id('username').send_keys('jiang2')
self.driver.find_element_by_id('memberAdd_acctid').send_keys('jiang2')
self.driver.find_element_by_id('memberAdd_phone').send_keys('15010236359')
self.... | AddMember | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddMember:
def add_member(self):
"""保存成员信息 :return:"""
<|body_0|>
def add_member_fail(self, acctid, phone):
"""添加成员报错 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from poHomework.page.contact_page import Contact
self.driver.find_... | stack_v2_sparse_classes_36k_train_030196 | 1,281 | no_license | [
{
"docstring": "保存成员信息 :return:",
"name": "add_member",
"signature": "def add_member(self)"
},
{
"docstring": "添加成员报错 :return:",
"name": "add_member_fail",
"signature": "def add_member_fail(self, acctid, phone)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018997 | Implement the Python class `AddMember` described below.
Class description:
Implement the AddMember class.
Method signatures and docstrings:
- def add_member(self): 保存成员信息 :return:
- def add_member_fail(self, acctid, phone): 添加成员报错 :return: | Implement the Python class `AddMember` described below.
Class description:
Implement the AddMember class.
Method signatures and docstrings:
- def add_member(self): 保存成员信息 :return:
- def add_member_fail(self, acctid, phone): 添加成员报错 :return:
<|skeleton|>
class AddMember:
def add_member(self):
"""保存成员信息 :r... | bd677551a324887bed4c3919b4645ebdeff107d1 | <|skeleton|>
class AddMember:
def add_member(self):
"""保存成员信息 :return:"""
<|body_0|>
def add_member_fail(self, acctid, phone):
"""添加成员报错 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddMember:
def add_member(self):
"""保存成员信息 :return:"""
from poHomework.page.contact_page import Contact
self.driver.find_element_by_id('username').send_keys('jiang2')
self.driver.find_element_by_id('memberAdd_acctid').send_keys('jiang2')
self.driver.find_element_by_id('... | the_stack_v2_python_sparse | poHomework/page/add_memeber_page.py | jyl4944204/study-homework | train | 0 | |
8d3c118a12c611f0920fa78ba72e8a550b9d02db | [
"cls.logger.debug('In GET: user_id = %r', user_id)\nif user_id is not None:\n with cherrypy.HTTPError.handle(ValueError, 400, 'Expected user id %r to be an integer' % user_id):\n user_id = int(user_id)\nwith cherrypy.HTTPError.handle(NoResultFound, 404, 'No user with id %s' % user_id), cherrypy.HTTPError.... | <|body_start_0|>
cls.logger.debug('In GET: user_id = %r', user_id)
if user_id is not None:
with cherrypy.HTTPError.handle(ValueError, 400, 'Expected user id %r to be an integer' % user_id):
user_id = int(user_id)
with cherrypy.HTTPError.handle(NoResultFound, 404, 'No ... | Users RESTful API. | UsersAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsersAPI:
"""Users RESTful API."""
def GET(cls, user_id=None):
"""REST GET method."""
<|body_0|>
def PUT(cls, user_id, admin):
"""REST Put method."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cls.logger.debug('In GET: user_id = %r', user_id)
... | stack_v2_sparse_classes_36k_train_030197 | 14,924 | permissive | [
{
"docstring": "REST GET method.",
"name": "GET",
"signature": "def GET(cls, user_id=None)"
},
{
"docstring": "REST Put method.",
"name": "PUT",
"signature": "def PUT(cls, user_id, admin)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019421 | Implement the Python class `UsersAPI` described below.
Class description:
Users RESTful API.
Method signatures and docstrings:
- def GET(cls, user_id=None): REST GET method.
- def PUT(cls, user_id, admin): REST Put method. | Implement the Python class `UsersAPI` described below.
Class description:
Users RESTful API.
Method signatures and docstrings:
- def GET(cls, user_id=None): REST GET method.
- def PUT(cls, user_id, admin): REST Put method.
<|skeleton|>
class UsersAPI:
"""Users RESTful API."""
def GET(cls, user_id=None):
... | 43225a155a985a7a56402df23dd550e48e22b436 | <|skeleton|>
class UsersAPI:
"""Users RESTful API."""
def GET(cls, user_id=None):
"""REST GET method."""
<|body_0|>
def PUT(cls, user_id, admin):
"""REST Put method."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UsersAPI:
"""Users RESTful API."""
def GET(cls, user_id=None):
"""REST GET method."""
cls.logger.debug('In GET: user_id = %r', user_id)
if user_id is not None:
with cherrypy.HTTPError.handle(ValueError, 400, 'Expected user id %r to be an integer' % user_id):
... | the_stack_v2_python_sparse | productionsystem/webapp/services/RESTfulAPI.py | alexanderrichards/ProductionSystem | train | 0 |
cd354ea8c06e5b48e82969baacce495e223e0817 | [
"self.es_analyser_by_language_static = {}\nself.es_analyser_by_language_regex = {}\nfor language in es_analyser_by_language.keys():\n if '*' in language:\n reg = language.replace('*', '(.*)')\n self.es_analyser_by_language_regex[reg] = es_analyser_by_language[language]\n else:\n self.es_a... | <|body_start_0|>
self.es_analyser_by_language_static = {}
self.es_analyser_by_language_regex = {}
for language in es_analyser_by_language.keys():
if '*' in language:
reg = language.replace('*', '(.*)')
self.es_analyser_by_language_regex[reg] = es_analy... | Manages languages by making sure there is an associated analyser. | LanguageManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageManager:
"""Manages languages by making sure there is an associated analyser."""
def __init__(self, es_analyser_by_language: dict):
""":param es_analyser_by_language: Dictionary which maps a custom language field to an es analyser. wildcards can be used at the end of language... | stack_v2_sparse_classes_36k_train_030198 | 1,844 | no_license | [
{
"docstring": ":param es_analyser_by_language: Dictionary which maps a custom language field to an es analyser. wildcards can be used at the end of language. Example en_* will match with en_EN and en-UK and en_whatever.",
"name": "__init__",
"signature": "def __init__(self, es_analyser_by_language: dic... | 3 | stack_v2_sparse_classes_30k_train_014575 | Implement the Python class `LanguageManager` described below.
Class description:
Manages languages by making sure there is an associated analyser.
Method signatures and docstrings:
- def __init__(self, es_analyser_by_language: dict): :param es_analyser_by_language: Dictionary which maps a custom language field to an ... | Implement the Python class `LanguageManager` described below.
Class description:
Manages languages by making sure there is an associated analyser.
Method signatures and docstrings:
- def __init__(self, es_analyser_by_language: dict): :param es_analyser_by_language: Dictionary which maps a custom language field to an ... | 07f5aacb57db4bba813c987b3d22448f90cbc58e | <|skeleton|>
class LanguageManager:
"""Manages languages by making sure there is an associated analyser."""
def __init__(self, es_analyser_by_language: dict):
""":param es_analyser_by_language: Dictionary which maps a custom language field to an es analyser. wildcards can be used at the end of language... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LanguageManager:
"""Manages languages by making sure there is an associated analyser."""
def __init__(self, es_analyser_by_language: dict):
""":param es_analyser_by_language: Dictionary which maps a custom language field to an es analyser. wildcards can be used at the end of language. Example en_... | the_stack_v2_python_sparse | jassrealtime/core/language_manager.py | crim-ca/RACS | train | 0 |
3eee3c20521da9edd15910b1581b27b1cb60cd9a | [
"super(SigprocReadBlock, self).__init__()\nself.filename = filename\nself.gulp_nframe = gulp_nframe\nself.core = core",
"with SigprocFile().open(self.filename, 'rb') as ifile:\n ifile.read_header()\n ohdr = {}\n ohdr['frame_shape'] = (ifile.nchans, ifile.nifs)\n ohdr['frame_size'] = ifile.nchans * ifi... | <|body_start_0|>
super(SigprocReadBlock, self).__init__()
self.filename = filename
self.gulp_nframe = gulp_nframe
self.core = core
<|end_body_0|>
<|body_start_1|>
with SigprocFile().open(self.filename, 'rb') as ifile:
ifile.read_header()
ohdr = {}
... | This block reads in a sigproc filterbank (.fil) file into a ring buffer | SigprocReadBlock | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SigprocReadBlock:
"""This block reads in a sigproc filterbank (.fil) file into a ring buffer"""
def __init__(self, filename, gulp_nframe=4096, core=-1):
"""@param[in] filename filterbank file to read @param[in] gulp_nframe Time samples to read in at a time @param[in] core Which CPU c... | stack_v2_sparse_classes_36k_train_030199 | 49,813 | permissive | [
{
"docstring": "@param[in] filename filterbank file to read @param[in] gulp_nframe Time samples to read in at a time @param[in] core Which CPU core to bind to (-1) is any",
"name": "__init__",
"signature": "def __init__(self, filename, gulp_nframe=4096, core=-1)"
},
{
"docstring": "Read in the s... | 2 | null | Implement the Python class `SigprocReadBlock` described below.
Class description:
This block reads in a sigproc filterbank (.fil) file into a ring buffer
Method signatures and docstrings:
- def __init__(self, filename, gulp_nframe=4096, core=-1): @param[in] filename filterbank file to read @param[in] gulp_nframe Time... | Implement the Python class `SigprocReadBlock` described below.
Class description:
This block reads in a sigproc filterbank (.fil) file into a ring buffer
Method signatures and docstrings:
- def __init__(self, filename, gulp_nframe=4096, core=-1): @param[in] filename filterbank file to read @param[in] gulp_nframe Time... | 5a93e5d4e906694cf754ac4f1015640a710ffc02 | <|skeleton|>
class SigprocReadBlock:
"""This block reads in a sigproc filterbank (.fil) file into a ring buffer"""
def __init__(self, filename, gulp_nframe=4096, core=-1):
"""@param[in] filename filterbank file to read @param[in] gulp_nframe Time samples to read in at a time @param[in] core Which CPU c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SigprocReadBlock:
"""This block reads in a sigproc filterbank (.fil) file into a ring buffer"""
def __init__(self, filename, gulp_nframe=4096, core=-1):
"""@param[in] filename filterbank file to read @param[in] gulp_nframe Time samples to read in at a time @param[in] core Which CPU core to bind t... | the_stack_v2_python_sparse | python/bifrost/block.py | ledatelescope/bifrost | train | 66 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.