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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2ea436f30a73cb05c3e4638b0860ae76553ad758 | [
"super(FlowToPix, self).__init__()\nself.batch_size = batch_size\nself.height = height\nself.width = width\nmeshgrid = np.meshgrid(range(self.width), range(self.height), indexing='xy')\nself.id_coords = np.stack(meshgrid, axis=0).astype(np.float32)\nself.id_coords = nn.Parameter(torch.from_numpy(self.id_coords))\ns... | <|body_start_0|>
super(FlowToPix, self).__init__()
self.batch_size = batch_size
self.height = height
self.width = width
meshgrid = np.meshgrid(range(self.width), range(self.height), indexing='xy')
self.id_coords = np.stack(meshgrid, axis=0).astype(np.float32)
self... | Layer to transform flow into camera pixel coordiantes | FlowToPix | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlowToPix:
"""Layer to transform flow into camera pixel coordiantes"""
def __init__(self, batch_size, height, width):
"""Prepare regular grid (Nx2xHxW)"""
<|body_0|>
def forward(self, flow, normalized=True):
"""Forward Args: flow (tensor, [Nx2xHxW]): [x, y] norma... | stack_v2_sparse_classes_36k_train_023900 | 13,421 | permissive | [
{
"docstring": "Prepare regular grid (Nx2xHxW)",
"name": "__init__",
"signature": "def __init__(self, batch_size, height, width)"
},
{
"docstring": "Forward Args: flow (tensor, [Nx2xHxW]): [x, y] normalized (bool): normalized to [-1, 1] if True; otherwise [0, H-1 or W-1] Returns: pix_coords (ten... | 2 | stack_v2_sparse_classes_30k_train_008509 | Implement the Python class `FlowToPix` described below.
Class description:
Layer to transform flow into camera pixel coordiantes
Method signatures and docstrings:
- def __init__(self, batch_size, height, width): Prepare regular grid (Nx2xHxW)
- def forward(self, flow, normalized=True): Forward Args: flow (tensor, [Nx... | Implement the Python class `FlowToPix` described below.
Class description:
Layer to transform flow into camera pixel coordiantes
Method signatures and docstrings:
- def __init__(self, batch_size, height, width): Prepare regular grid (Nx2xHxW)
- def forward(self, flow, normalized=True): Forward Args: flow (tensor, [Nx... | 50e6ffa9b5164a0dfb34d3215e86cc2288df256d | <|skeleton|>
class FlowToPix:
"""Layer to transform flow into camera pixel coordiantes"""
def __init__(self, batch_size, height, width):
"""Prepare regular grid (Nx2xHxW)"""
<|body_0|>
def forward(self, flow, normalized=True):
"""Forward Args: flow (tensor, [Nx2xHxW]): [x, y] norma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlowToPix:
"""Layer to transform flow into camera pixel coordiantes"""
def __init__(self, batch_size, height, width):
"""Prepare regular grid (Nx2xHxW)"""
super(FlowToPix, self).__init__()
self.batch_size = batch_size
self.height = height
self.width = width
... | the_stack_v2_python_sparse | libs/deep_models/depth/monodepth2/layers.py | Huangying-Zhan/DF-VO | train | 494 |
6e704f65fcb9c9cc3e1a188e613c2ba7fa0d64fb | [
"if x < 0:\n out = int(''.join(reversed(str(x * -1))))\n return 0 if (out > 2 ** 31 - 1) | (out < -2 ** 31) else -1 * out\nelse:\n out = int(''.join(reversed(str(x))))\n return 0 if (out > 2 ** 31 - 1) | (out < -2 ** 31) else out",
"if x == 0:\n return 0\nelif (x > 2 ** 31 - 1) | (x < -2 ** 31):\n ... | <|body_start_0|>
if x < 0:
out = int(''.join(reversed(str(x * -1))))
return 0 if (out > 2 ** 31 - 1) | (out < -2 ** 31) else -1 * out
else:
out = int(''.join(reversed(str(x))))
return 0 if (out > 2 ** 31 - 1) | (out < -2 ** 31) else out
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse_myfirst(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x < 0:
out = int(''.join(reversed(str(x * -1))))
... | stack_v2_sparse_classes_36k_train_023901 | 1,126 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "reverse",
"signature": "def reverse(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "reverse_myfirst",
"signature": "def reverse_myfirst(self, x)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse_myfirst(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse_myfirst(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def reverse(self, x):
""":type ... | f0d9070fa292ca36971a465a805faddb12025482 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse_myfirst(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
if x < 0:
out = int(''.join(reversed(str(x * -1))))
return 0 if (out > 2 ** 31 - 1) | (out < -2 ** 31) else -1 * out
else:
out = int(''.join(reversed(str(x))))
return 0 if (ou... | the_stack_v2_python_sparse | 7.ReverseInteger.py | JerryRoc/leetcode | train | 0 | |
e91d9cb1c951ee22dd863dcb1a6c9ec726b20a0f | [
"postal = Postal.query.filter_by(id=postal_id, active=True).first()\nif postal:\n return (postal, 200)\nabort(404, message='No postal found with specified ID')",
"arguments = request.get_json(force=True)\nname = arguments.get('name').strip()\npostal = Postal.query.filter_by(id=postal_id, active=True).first()\n... | <|body_start_0|>
postal = Postal.query.filter_by(id=postal_id, active=True).first()
if postal:
return (postal, 200)
abort(404, message='No postal found with specified ID')
<|end_body_0|>
<|body_start_1|>
arguments = request.get_json(force=True)
name = arguments.get('... | SinglePostalEndpoint | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SinglePostalEndpoint:
def get(self, postal_id):
"""Retrieve individual postal with given postal_id"""
<|body_0|>
def put(self, postal_id):
"""Update postal with given postal_id"""
<|body_1|>
def delete(self, postal_id):
"""Delete postal with post... | stack_v2_sparse_classes_36k_train_023902 | 10,081 | permissive | [
{
"docstring": "Retrieve individual postal with given postal_id",
"name": "get",
"signature": "def get(self, postal_id)"
},
{
"docstring": "Update postal with given postal_id",
"name": "put",
"signature": "def put(self, postal_id)"
},
{
"docstring": "Delete postal with postal_id ... | 3 | stack_v2_sparse_classes_30k_val_000863 | Implement the Python class `SinglePostalEndpoint` described below.
Class description:
Implement the SinglePostalEndpoint class.
Method signatures and docstrings:
- def get(self, postal_id): Retrieve individual postal with given postal_id
- def put(self, postal_id): Update postal with given postal_id
- def delete(self... | Implement the Python class `SinglePostalEndpoint` described below.
Class description:
Implement the SinglePostalEndpoint class.
Method signatures and docstrings:
- def get(self, postal_id): Retrieve individual postal with given postal_id
- def put(self, postal_id): Update postal with given postal_id
- def delete(self... | 652c156b622e679fa2e68d2fb4b0f87180b3ca11 | <|skeleton|>
class SinglePostalEndpoint:
def get(self, postal_id):
"""Retrieve individual postal with given postal_id"""
<|body_0|>
def put(self, postal_id):
"""Update postal with given postal_id"""
<|body_1|>
def delete(self, postal_id):
"""Delete postal with post... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SinglePostalEndpoint:
def get(self, postal_id):
"""Retrieve individual postal with given postal_id"""
postal = Postal.query.filter_by(id=postal_id, active=True).first()
if postal:
return (postal, 200)
abort(404, message='No postal found with specified ID')
def ... | the_stack_v2_python_sparse | app/api/v1/postal.py | Enkya/ims_beta | train | 0 | |
12c80f0717d8304b1fb9d3b0466ff9ed0c072302 | [
"def dfs(node):\n if node:\n vals.append(str(node.val))\n dfs(node.left)\n dfs(node.right)\n else:\n vals.append('#')\nvals = []\ndfs(root)\nreturn ' '.join(vals)",
"def dfs():\n val = next(vals)\n if val == '#':\n return None\n node = TreeNode(int(val))\n node... | <|body_start_0|>
def dfs(node):
if node:
vals.append(str(node.val))
dfs(node.left)
dfs(node.right)
else:
vals.append('#')
vals = []
dfs(root)
return ' '.join(vals)
<|end_body_0|>
<|body_start_1|>
... | 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_023903 | 2,379 | 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_000161 | 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:... | a08b44323b04fc7d488708b0ffbe94dafc47eb18 | <|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"""
def dfs(node):
if node:
vals.append(str(node.val))
dfs(node.left)
dfs(node.right)
else:
vals.appen... | the_stack_v2_python_sparse | Tree/serilizeAndDeserilizeBT.py | DiracSea/LC | train | 0 | |
daf365354aefaeb001cdb1bc063169889b79ffcf | [
"self.paused = False\nself.playing = True\nself.round = round.Round()\nself.timer = 260\nself.font = font",
"self.paused = True\ntext = self.font.render('PAUSED', 0, (200, 255, 200), (0, 0, 0))\nscreen.blit(text, (15, 100))",
"if not self.paused:\n self.round.update(screen)\n if self.round.boo > 0:\n ... | <|body_start_0|>
self.paused = False
self.playing = True
self.round = round.Round()
self.timer = 260
self.font = font
<|end_body_0|>
<|body_start_1|>
self.paused = True
text = self.font.render('PAUSED', 0, (200, 255, 200), (0, 0, 0))
screen.blit(text, (15... | Game | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
def __init__(self, font):
"""new game instance"""
<|body_0|>
def pause(self, screen):
"""pause game and display paused graphic"""
<|body_1|>
def update(self, screen):
"""update current game instance"""
<|body_2|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_023904 | 1,737 | no_license | [
{
"docstring": "new game instance",
"name": "__init__",
"signature": "def __init__(self, font)"
},
{
"docstring": "pause game and display paused graphic",
"name": "pause",
"signature": "def pause(self, screen)"
},
{
"docstring": "update current game instance",
"name": "update... | 3 | stack_v2_sparse_classes_30k_train_017614 | Implement the Python class `Game` described below.
Class description:
Implement the Game class.
Method signatures and docstrings:
- def __init__(self, font): new game instance
- def pause(self, screen): pause game and display paused graphic
- def update(self, screen): update current game instance | Implement the Python class `Game` described below.
Class description:
Implement the Game class.
Method signatures and docstrings:
- def __init__(self, font): new game instance
- def pause(self, screen): pause game and display paused graphic
- def update(self, screen): update current game instance
<|skeleton|>
class ... | 05beacb278b0406ef71b1479396954b0ffb9d2d3 | <|skeleton|>
class Game:
def __init__(self, font):
"""new game instance"""
<|body_0|>
def pause(self, screen):
"""pause game and display paused graphic"""
<|body_1|>
def update(self, screen):
"""update current game instance"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Game:
def __init__(self, font):
"""new game instance"""
self.paused = False
self.playing = True
self.round = round.Round()
self.timer = 260
self.font = font
def pause(self, screen):
"""pause game and display paused graphic"""
self.paused = T... | the_stack_v2_python_sparse | breakout/game.py | dsmith94/breakout | train | 0 | |
64be7b63fe73434be9d0f771faf85ec51e86d8c7 | [
"assert_is_instance(l_plus, np.ndarray, 'L plus has to be a np array')\nassert_is_instance(l_minus, np.ndarray, 'L minus has to be a np array')\nassert_condition(l_plus.shape == l_minus.shape, TypeError, 'It is not an splitting')\nassert_is_instance(level, IMultigridLevel, 'Not the right level')\nself.order = kwarg... | <|body_start_0|>
assert_is_instance(l_plus, np.ndarray, 'L plus has to be a np array')
assert_is_instance(l_minus, np.ndarray, 'L minus has to be a np array')
assert_condition(l_plus.shape == l_minus.shape, TypeError, 'It is not an splitting')
assert_is_instance(level, IMultigridLevel, '... | A general Smoothing class which arises from splitting the main stencil This class of smoothers is easy to derive and really broad, it is statically linked to a certain level. | SplitSmoother | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SplitSmoother:
"""A general Smoothing class which arises from splitting the main stencil This class of smoothers is easy to derive and really broad, it is statically linked to a certain level."""
def __init__(self, l_plus, l_minus, level, *args, **kwargs):
"""init method of the split... | stack_v2_sparse_classes_36k_train_023905 | 9,259 | no_license | [
{
"docstring": "init method of the split smoother l_plus and l_minus have to be centralized",
"name": "__init__",
"signature": "def __init__(self, l_plus, l_minus, level, *args, **kwargs)"
},
{
"docstring": "Does the relaxation step several times on the lvl the hardship in this case is to use th... | 2 | stack_v2_sparse_classes_30k_train_012087 | Implement the Python class `SplitSmoother` described below.
Class description:
A general Smoothing class which arises from splitting the main stencil This class of smoothers is easy to derive and really broad, it is statically linked to a certain level.
Method signatures and docstrings:
- def __init__(self, l_plus, l... | Implement the Python class `SplitSmoother` described below.
Class description:
A general Smoothing class which arises from splitting the main stencil This class of smoothers is easy to derive and really broad, it is statically linked to a certain level.
Method signatures and docstrings:
- def __init__(self, l_plus, l... | 90aed34cf43d633e44f56444f6c5d4fa39619663 | <|skeleton|>
class SplitSmoother:
"""A general Smoothing class which arises from splitting the main stencil This class of smoothers is easy to derive and really broad, it is statically linked to a certain level."""
def __init__(self, l_plus, l_minus, level, *args, **kwargs):
"""init method of the split... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SplitSmoother:
"""A general Smoothing class which arises from splitting the main stencil This class of smoothers is easy to derive and really broad, it is statically linked to a certain level."""
def __init__(self, l_plus, l_minus, level, *args, **kwargs):
"""init method of the split smoother l_p... | the_stack_v2_python_sparse | pypint/plugins/multigrid/multigrid_smoother.py | Parallel-in-Time/PyPinT | train | 0 |
42d3e388d7845bf16da6358a3d157645b8179287 | [
"def findsub(nums):\n if len(nums) == 0:\n return 0\n if nums[0] == min(nums):\n return findsub(nums[1:])\n if nums[-1] == max(nums):\n return findsub(nums[:-1])\n return len(nums)\nreturn findsub(nums)",
"snums = sorted(nums)\ns = 0\ne = len(nums) - 1\ni = 0\nwhile i < len(nums):... | <|body_start_0|>
def findsub(nums):
if len(nums) == 0:
return 0
if nums[0] == min(nums):
return findsub(nums[1:])
if nums[-1] == max(nums):
return findsub(nums[:-1])
return len(nums)
return findsub(nums)
<|en... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findUnsortedSubarray1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findUnsortedSubarray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def findsub(nums):
... | stack_v2_sparse_classes_36k_train_023906 | 926 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findUnsortedSubarray1",
"signature": "def findUnsortedSubarray1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findUnsortedSubarray",
"signature": "def findUnsortedSubarray(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray1(self, nums): :type nums: List[int] :rtype: int
- def findUnsortedSubarray(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray1(self, nums): :type nums: List[int] :rtype: int
- def findUnsortedSubarray(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def findUnsortedSubarray1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findUnsortedSubarray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findUnsortedSubarray1(self, nums):
""":type nums: List[int] :rtype: int"""
def findsub(nums):
if len(nums) == 0:
return 0
if nums[0] == min(nums):
return findsub(nums[1:])
if nums[-1] == max(nums):
... | the_stack_v2_python_sparse | py/leetcode/581.py | wfeng1991/learnpy | train | 0 | |
2aa6b0330d3cc8239442815f6d2062ffebc1deaf | [
"parsed_url = URL(url)\nschema = parsed_url.drivername\nif '+' in schema:\n dialect, driver = schema.split('+')\nelse:\n dialect, driver = (schema, 'base')\ndialect = dialect.strip().lower()\ndriver = driver.strip()\narguments = {'echo': self._echo}\nif dialect == 'sqlite':\n arguments['module'] = sqlite3.... | <|body_start_0|>
parsed_url = URL(url)
schema = parsed_url.drivername
if '+' in schema:
dialect, driver = schema.split('+')
else:
dialect, driver = (schema, 'base')
dialect = dialect.strip().lower()
driver = driver.strip()
arguments = {'ech... | Data Access Object base class. @type _url: sqlalchemy.url.URL @ivar _url: Database connection URL. @type _dialect: str @ivar _dialect: SQL dialect currently being used. @type _driver: str @ivar _driver: Name of the database driver currently being used. To get the actual Python module use L{_url}.get_driver() instead. @... | BaseDAO | [
"EPL-1.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseDAO:
"""Data Access Object base class. @type _url: sqlalchemy.url.URL @ivar _url: Database connection URL. @type _dialect: str @ivar _dialect: SQL dialect currently being used. @type _driver: str @ivar _driver: Name of the database driver currently being used. To get the actual Python module ... | stack_v2_sparse_classes_36k_train_023907 | 34,997 | permissive | [
{
"docstring": "Connect to the database using the given connection URL. The current implementation uses SQLAlchemy and so it will support whatever database said module supports. @type url: str @param url: URL that specifies the database to connect to. Some examples: - Opening an SQLite file: C{dao = CrashDAO(\"... | 2 | null | Implement the Python class `BaseDAO` described below.
Class description:
Data Access Object base class. @type _url: sqlalchemy.url.URL @ivar _url: Database connection URL. @type _dialect: str @ivar _dialect: SQL dialect currently being used. @type _driver: str @ivar _driver: Name of the database driver currently being... | Implement the Python class `BaseDAO` described below.
Class description:
Data Access Object base class. @type _url: sqlalchemy.url.URL @ivar _url: Database connection URL. @type _dialect: str @ivar _dialect: SQL dialect currently being used. @type _driver: str @ivar _driver: Name of the database driver currently being... | 05dbd4575d01a213f3f4d69aa4968473f2536142 | <|skeleton|>
class BaseDAO:
"""Data Access Object base class. @type _url: sqlalchemy.url.URL @ivar _url: Database connection URL. @type _dialect: str @ivar _dialect: SQL dialect currently being used. @type _driver: str @ivar _driver: Name of the database driver currently being used. To get the actual Python module ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseDAO:
"""Data Access Object base class. @type _url: sqlalchemy.url.URL @ivar _url: Database connection URL. @type _dialect: str @ivar _dialect: SQL dialect currently being used. @type _driver: str @ivar _driver: Name of the database driver currently being used. To get the actual Python module use L{_url}.g... | the_stack_v2_python_sparse | python/helpers/pydev/pydevd_attach_to_process/winappdbg/sql.py | JetBrains/intellij-community | train | 16,288 |
ffeb6cd0973d382ad59ca4f0a6e37259c13b4aea | [
"if default is None:\n default = DEFAULT.copy()\n default.update(IMAGE_DEFAULT)\nsuper().__init__(default=default, config=config, pipecal_config=pipecal_config)\nself.merge_opt = ['CENTROID', 'XCOR', 'NOSHIFT', 'WCS', 'USER']",
"if self.pipecal_config is not None:\n self.current[step_index].set_value('fi... | <|body_start_0|>
if default is None:
default = DEFAULT.copy()
default.update(IMAGE_DEFAULT)
super().__init__(default=default, config=config, pipecal_config=pipecal_config)
self.merge_opt = ['CENTROID', 'XCOR', 'NOSHIFT', 'WCS', 'USER']
<|end_body_0|>
<|body_start_1|>
... | Reduction parameters for the FLITECAM Imaging pipeline. | FLITECAMImagingParameters | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FLITECAMImagingParameters:
"""Reduction parameters for the FLITECAM Imaging pipeline."""
def __init__(self, default=None, config=None, pipecal_config=None):
"""Initialize parameters with default values. The various config files are used to override certain parameter defaults for part... | stack_v2_sparse_classes_36k_train_023908 | 13,783 | permissive | [
{
"docstring": "Initialize parameters with default values. The various config files are used to override certain parameter defaults for particular observation modes, or dates, etc. Parameters ---------- config : dict-like, optional Reduction mode and auxiliary file configuration mapping, as returned from the so... | 2 | null | Implement the Python class `FLITECAMImagingParameters` described below.
Class description:
Reduction parameters for the FLITECAM Imaging pipeline.
Method signatures and docstrings:
- def __init__(self, default=None, config=None, pipecal_config=None): Initialize parameters with default values. The various config files... | Implement the Python class `FLITECAMImagingParameters` described below.
Class description:
Reduction parameters for the FLITECAM Imaging pipeline.
Method signatures and docstrings:
- def __init__(self, default=None, config=None, pipecal_config=None): Initialize parameters with default values. The various config files... | 493700340cd34d5f319af6f3a562a82135bb30dd | <|skeleton|>
class FLITECAMImagingParameters:
"""Reduction parameters for the FLITECAM Imaging pipeline."""
def __init__(self, default=None, config=None, pipecal_config=None):
"""Initialize parameters with default values. The various config files are used to override certain parameter defaults for part... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FLITECAMImagingParameters:
"""Reduction parameters for the FLITECAM Imaging pipeline."""
def __init__(self, default=None, config=None, pipecal_config=None):
"""Initialize parameters with default values. The various config files are used to override certain parameter defaults for particular observ... | the_stack_v2_python_sparse | sofia_redux/pipeline/sofia/parameters/flitecam_imaging_parameters.py | SOFIA-USRA/sofia_redux | train | 12 |
73418aad3190f1151b847d09a56011d724ec868b | [
"self.nctrsTMconn = False\nself.nctrsTMport = UTIL.SYS.s_configuration.NCTRS_TM_SERVER_PORT\nself.nctrsTCconn = False\nself.nctrsTCport = UTIL.SYS.s_configuration.NCTRS_TC_SERVER_PORT\nself.nctrsAdminConn = False\nself.nctrsAdminPort = UTIL.SYS.s_configuration.NCTRS_ADMIN_SERVER_PORT\nself.grndAck1 = ENABLE_ACK\nse... | <|body_start_0|>
self.nctrsTMconn = False
self.nctrsTMport = UTIL.SYS.s_configuration.NCTRS_TM_SERVER_PORT
self.nctrsTCconn = False
self.nctrsTCport = UTIL.SYS.s_configuration.NCTRS_TC_SERVER_PORT
self.nctrsAdminConn = False
self.nctrsAdminPort = UTIL.SYS.s_configuration.... | Server Configuration | Configuration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Configuration:
"""Server Configuration"""
def __init__(self):
"""Initialise the connection relevant informations"""
<|body_0|>
def dump(self):
"""Dumps the status of the configuration attributes"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
se... | stack_v2_sparse_classes_36k_train_023909 | 5,270 | permissive | [
{
"docstring": "Initialise the connection relevant informations",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Dumps the status of the configuration attributes",
"name": "dump",
"signature": "def dump(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005576 | Implement the Python class `Configuration` described below.
Class description:
Server Configuration
Method signatures and docstrings:
- def __init__(self): Initialise the connection relevant informations
- def dump(self): Dumps the status of the configuration attributes | Implement the Python class `Configuration` described below.
Class description:
Server Configuration
Method signatures and docstrings:
- def __init__(self): Initialise the connection relevant informations
- def dump(self): Dumps the status of the configuration attributes
<|skeleton|>
class Configuration:
"""Serve... | c94415e9d85519f345fc56938198ac2537c0c6d0 | <|skeleton|>
class Configuration:
"""Server Configuration"""
def __init__(self):
"""Initialise the connection relevant informations"""
<|body_0|>
def dump(self):
"""Dumps the status of the configuration attributes"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Configuration:
"""Server Configuration"""
def __init__(self):
"""Initialise the connection relevant informations"""
self.nctrsTMconn = False
self.nctrsTMport = UTIL.SYS.s_configuration.NCTRS_TM_SERVER_PORT
self.nctrsTCconn = False
self.nctrsTCport = UTIL.SYS.s_conf... | the_stack_v2_python_sparse | GRND/IF.py | khawatkom/SpacePyLibrary | train | 1 |
9f20acdf38992d8a639986af8b5202072131f0b1 | [
"tuples = self.fscd_tester.machine.read_sensors(self.fscd_tester.sensors, None)\ncount = len(tuples['slot1'])\nself.assertEqual(count, 41, 'Incorrect sensor tupple count')",
"tuples = self.fscd_tester.machine.read_fans(self.fscd_tester.fans)\ncount = len(tuples)\nself.assertEqual(count, 3, 'Incorrect fan tupple c... | <|body_start_0|>
tuples = self.fscd_tester.machine.read_sensors(self.fscd_tester.sensors, None)
count = len(tuples['slot1'])
self.assertEqual(count, 41, 'Incorrect sensor tupple count')
<|end_body_0|>
<|body_start_1|>
tuples = self.fscd_tester.machine.read_fans(self.fscd_tester.fans)
... | FscdBmcMachineUnitTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FscdBmcMachineUnitTest:
def test_sensor_read(self):
"""Test if sensor tuples are getting built. 'linear_dimm' has a source that reads a file and dumps data like from platform."""
<|body_0|>
def test_fan_read(self):
"""Test if fan tuples are getting built. 'fan 2' has... | stack_v2_sparse_classes_36k_train_023910 | 4,109 | no_license | [
{
"docstring": "Test if sensor tuples are getting built. 'linear_dimm' has a source that reads a file and dumps data like from platform.",
"name": "test_sensor_read",
"signature": "def test_sensor_read(self)"
},
{
"docstring": "Test if fan tuples are getting built. 'fan 2' has a source that read... | 2 | stack_v2_sparse_classes_30k_train_007416 | Implement the Python class `FscdBmcMachineUnitTest` described below.
Class description:
Implement the FscdBmcMachineUnitTest class.
Method signatures and docstrings:
- def test_sensor_read(self): Test if sensor tuples are getting built. 'linear_dimm' has a source that reads a file and dumps data like from platform.
-... | Implement the Python class `FscdBmcMachineUnitTest` described below.
Class description:
Implement the FscdBmcMachineUnitTest class.
Method signatures and docstrings:
- def test_sensor_read(self): Test if sensor tuples are getting built. 'linear_dimm' has a source that reads a file and dumps data like from platform.
-... | 32777c66a8410d767eae15baabf71c61a0bef13c | <|skeleton|>
class FscdBmcMachineUnitTest:
def test_sensor_read(self):
"""Test if sensor tuples are getting built. 'linear_dimm' has a source that reads a file and dumps data like from platform."""
<|body_0|>
def test_fan_read(self):
"""Test if fan tuples are getting built. 'fan 2' has... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FscdBmcMachineUnitTest:
def test_sensor_read(self):
"""Test if sensor tuples are getting built. 'linear_dimm' has a source that reads a file and dumps data like from platform."""
tuples = self.fscd_tester.machine.read_sensors(self.fscd_tester.sensors, None)
count = len(tuples['slot1'])... | the_stack_v2_python_sparse | common/recipes-core/fscd3/fscd/fscd_test/fsc_bmc_machine_tester.py | facebook/openbmc | train | 684 | |
b12f50a63657bb28db93a7f86ac75242eaa17641 | [
"res = []\n\ndef addTolist(node, dep):\n if not node:\n return\n if dep >= len(res):\n res.append([])\n res[dep].append(node.val)\n if node.left:\n addTolist(node.left, dep + 1)\n if node.right:\n addTolist(node.right, dep + 1)\naddTolist(root, 0)\nres.reverse()\nreturn re... | <|body_start_0|>
res = []
def addTolist(node, dep):
if not node:
return
if dep >= len(res):
res.append([])
res[dep].append(node.val)
if node.left:
addTolist(node.left, dep + 1)
if node.right:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrderBottom(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrderBottom2(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
... | stack_v2_sparse_classes_36k_train_023911 | 1,682 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrderBottom",
"signature": "def levelOrderBottom(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrderBottom2",
"signature": "def levelOrderBottom2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014276 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBottom(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrderBottom2(self, root): :type root: TreeNode :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBottom(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrderBottom2(self, root): :type root: TreeNode :rtype: List[List[int]]
<|skeleton|>
cla... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def levelOrderBottom(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrderBottom2(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def levelOrderBottom(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
res = []
def addTolist(node, dep):
if not node:
return
if dep >= len(res):
res.append([])
res[dep].append(node.val)
... | the_stack_v2_python_sparse | 107. Binary Tree Level Order Traversal II/level_order.py | Macielyoung/LeetCode | train | 1 | |
8469a8aebcaad6f103eec9c98f31ead992183c71 | [
"with tf.variable_scope('interatomic_dists'):\n dists = tf.sqrt(tf.reduce_sum(tf.square(R[:, None, :, :] - R[:, :, None, :]), axis=-1))\nreturn dists",
"with tf.variable_scope('gauss_grid'):\n num = int(np.ceil((mu_max - mu_min) / delta_mu))\n remainder = num * delta_mu - (mu_max - mu_min)\n mu = self... | <|body_start_0|>
with tf.variable_scope('interatomic_dists'):
dists = tf.sqrt(tf.reduce_sum(tf.square(R[:, None, :, :] - R[:, :, None, :]), axis=-1))
return dists
<|end_body_0|>
<|body_start_1|>
with tf.variable_scope('gauss_grid'):
num = int(np.ceil((mu_max - mu_min) / ... | MolecularPreprocessingMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MolecularPreprocessingMixin:
def _interatomic_dists(self, R):
"""transforms absolute coordinates in data matrix R to pairwise distance matrices params: R - matrix of shape (n_points, n_atoms, 3) returns - pairwise distance matrix of shape (n_points, n_atoms, n_atoms)"""
<|body_0|... | stack_v2_sparse_classes_36k_train_023912 | 18,572 | no_license | [
{
"docstring": "transforms absolute coordinates in data matrix R to pairwise distance matrices params: R - matrix of shape (n_points, n_atoms, 3) returns - pairwise distance matrix of shape (n_points, n_atoms, n_atoms)",
"name": "_interatomic_dists",
"signature": "def _interatomic_dists(self, R)"
},
... | 2 | stack_v2_sparse_classes_30k_test_000838 | Implement the Python class `MolecularPreprocessingMixin` described below.
Class description:
Implement the MolecularPreprocessingMixin class.
Method signatures and docstrings:
- def _interatomic_dists(self, R): transforms absolute coordinates in data matrix R to pairwise distance matrices params: R - matrix of shape ... | Implement the Python class `MolecularPreprocessingMixin` described below.
Class description:
Implement the MolecularPreprocessingMixin class.
Method signatures and docstrings:
- def _interatomic_dists(self, R): transforms absolute coordinates in data matrix R to pairwise distance matrices params: R - matrix of shape ... | b54a80ce4be5b89a1b2c5bf3ebc0308d12e4c9b6 | <|skeleton|>
class MolecularPreprocessingMixin:
def _interatomic_dists(self, R):
"""transforms absolute coordinates in data matrix R to pairwise distance matrices params: R - matrix of shape (n_points, n_atoms, 3) returns - pairwise distance matrix of shape (n_points, n_atoms, n_atoms)"""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MolecularPreprocessingMixin:
def _interatomic_dists(self, R):
"""transforms absolute coordinates in data matrix R to pairwise distance matrices params: R - matrix of shape (n_points, n_atoms, 3) returns - pairwise distance matrix of shape (n_points, n_atoms, n_atoms)"""
with tf.variable_scope(... | the_stack_v2_python_sparse | networks/neuralnet.py | qk/unn | train | 1 | |
bba4634fb9d35cce790010d4d057a4be4ea00b86 | [
"qs = self.queryset.filter(expiry_date__gt=timezone.now())\nif not self.request.user.groups.filter(name=REGISTRIES_VIEWER_ROLE).exists():\n qs = qs.filter(Q(applications__current_status__code='A'), Q(applications__removal_date__isnull=True))\nreturn qs",
"instance = self.get_object()\ninstance.expiry_date = ti... | <|body_start_0|>
qs = self.queryset.filter(expiry_date__gt=timezone.now())
if not self.request.user.groups.filter(name=REGISTRIES_VIEWER_ROLE).exists():
qs = qs.filter(Q(applications__current_status__code='A'), Q(applications__removal_date__isnull=True))
return qs
<|end_body_0|>
<|b... | get: Returns the specified person put: Replaces the specified person record with a new one patch: Updates a person with the fields/values provided in the request body delete: Removes the specified person record | PersonDetailView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonDetailView:
"""get: Returns the specified person put: Replaces the specified person record with a new one patch: Updates a person with the fields/values provided in the request body delete: Removes the specified person record"""
def get_queryset(self):
"""Returns only registere... | stack_v2_sparse_classes_36k_train_023913 | 35,975 | permissive | [
{
"docstring": "Returns only registered people (i.e. drillers with active registration) to anonymous users",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Set expiry_date to current date",
"name": "destroy",
"signature": "def destroy(self, request, *arg... | 2 | stack_v2_sparse_classes_30k_val_000842 | Implement the Python class `PersonDetailView` described below.
Class description:
get: Returns the specified person put: Replaces the specified person record with a new one patch: Updates a person with the fields/values provided in the request body delete: Removes the specified person record
Method signatures and doc... | Implement the Python class `PersonDetailView` described below.
Class description:
get: Returns the specified person put: Replaces the specified person record with a new one patch: Updates a person with the fields/values provided in the request body delete: Removes the specified person record
Method signatures and doc... | 6be3701a8e0085d0c6fa199b2672b7f9f1266a03 | <|skeleton|>
class PersonDetailView:
"""get: Returns the specified person put: Replaces the specified person record with a new one patch: Updates a person with the fields/values provided in the request body delete: Removes the specified person record"""
def get_queryset(self):
"""Returns only registere... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersonDetailView:
"""get: Returns the specified person put: Replaces the specified person record with a new one patch: Updates a person with the fields/values provided in the request body delete: Removes the specified person record"""
def get_queryset(self):
"""Returns only registered people (i.e... | the_stack_v2_python_sparse | app/backend/registries/views.py | bcgov/gwells | train | 39 |
9ab1cefcb2a737b7d0802758ac44959f8ef65119 | [
"key_str = None\nwhile True:\n try:\n key_str = _generate_random_key()\n self.get(key=key_str)\n except ObjectDoesNotExist:\n break\nnew_key = self.create(user=user, key=key_str, action_flag=action_flag)\nkeys = self.filter(user=user, action_flag=action_flag).exclude(key=key_str)\nfor key... | <|body_start_0|>
key_str = None
while True:
try:
key_str = _generate_random_key()
self.get(key=key_str)
except ObjectDoesNotExist:
break
new_key = self.create(user=user, key=key_str, action_flag=action_flag)
keys = s... | TempKeyManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TempKeyManager:
def create_key(self, user, action_flag):
"""Create a new temp key."""
<|body_0|>
def authenticate(self, key_str):
"""Authenticate key Return TempKey object if key_str is exact and not expired. Return None if key_str is not exact or expired."""
... | stack_v2_sparse_classes_36k_train_023914 | 2,570 | no_license | [
{
"docstring": "Create a new temp key.",
"name": "create_key",
"signature": "def create_key(self, user, action_flag)"
},
{
"docstring": "Authenticate key Return TempKey object if key_str is exact and not expired. Return None if key_str is not exact or expired.",
"name": "authenticate",
"... | 2 | stack_v2_sparse_classes_30k_train_010579 | Implement the Python class `TempKeyManager` described below.
Class description:
Implement the TempKeyManager class.
Method signatures and docstrings:
- def create_key(self, user, action_flag): Create a new temp key.
- def authenticate(self, key_str): Authenticate key Return TempKey object if key_str is exact and not ... | Implement the Python class `TempKeyManager` described below.
Class description:
Implement the TempKeyManager class.
Method signatures and docstrings:
- def create_key(self, user, action_flag): Create a new temp key.
- def authenticate(self, key_str): Authenticate key Return TempKey object if key_str is exact and not ... | 8f6a35dde214e809cdd6cbfebd8d913bafd68fb2 | <|skeleton|>
class TempKeyManager:
def create_key(self, user, action_flag):
"""Create a new temp key."""
<|body_0|>
def authenticate(self, key_str):
"""Authenticate key Return TempKey object if key_str is exact and not expired. Return None if key_str is not exact or expired."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TempKeyManager:
def create_key(self, user, action_flag):
"""Create a new temp key."""
key_str = None
while True:
try:
key_str = _generate_random_key()
self.get(key=key_str)
except ObjectDoesNotExist:
break
... | the_stack_v2_python_sparse | accounts/models.py | pymmrd/tuangou | train | 0 | |
df20a5ae94b92f6045167b95caf1eedef296b3d9 | [
"super().__init__(cols, tab_width=tab_width, column_borders=column_borders, padding=padding, border_fg=border_fg, border_bg=border_bg, header_bg=header_bg)\nself.row_num = 1\nself.odd_bg = odd_bg\nself.even_bg = even_bg",
"if self.row_num % 2 == 0 and self.even_bg is not None:\n return ansi.style(value, bg=sel... | <|body_start_0|>
super().__init__(cols, tab_width=tab_width, column_borders=column_borders, padding=padding, border_fg=border_fg, border_bg=border_bg, header_bg=header_bg)
self.row_num = 1
self.odd_bg = odd_bg
self.even_bg = even_bg
<|end_body_0|>
<|body_start_1|>
if self.row_nu... | Implementation of BorderedTable which uses background colors to distinguish between rows instead of row border lines. This class can be used to create the whole table at once or one row at a time. To nest an AlternatingTable within another AlternatingTable, set style_data_text to False on the Column which contains the ... | AlternatingTable | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlternatingTable:
"""Implementation of BorderedTable which uses background colors to distinguish between rows instead of row border lines. This class can be used to create the whole table at once or one row at a time. To nest an AlternatingTable within another AlternatingTable, set style_data_tex... | stack_v2_sparse_classes_36k_train_023915 | 47,543 | permissive | [
{
"docstring": "AlternatingTable initializer Note: Specify background colors using subclasses of BgColor (e.g. Bg, EightBitBg, RgbBg) :param cols: column definitions for this table :param tab_width: all tabs will be replaced with this many spaces. If a row's fill_char is a tab, then it will be converted to one ... | 4 | stack_v2_sparse_classes_30k_train_003445 | Implement the Python class `AlternatingTable` described below.
Class description:
Implementation of BorderedTable which uses background colors to distinguish between rows instead of row border lines. This class can be used to create the whole table at once or one row at a time. To nest an AlternatingTable within anoth... | Implement the Python class `AlternatingTable` described below.
Class description:
Implementation of BorderedTable which uses background colors to distinguish between rows instead of row border lines. This class can be used to create the whole table at once or one row at a time. To nest an AlternatingTable within anoth... | 9886b82c71face043e1fac871a6cdbebbf0e864c | <|skeleton|>
class AlternatingTable:
"""Implementation of BorderedTable which uses background colors to distinguish between rows instead of row border lines. This class can be used to create the whole table at once or one row at a time. To nest an AlternatingTable within another AlternatingTable, set style_data_tex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlternatingTable:
"""Implementation of BorderedTable which uses background colors to distinguish between rows instead of row border lines. This class can be used to create the whole table at once or one row at a time. To nest an AlternatingTable within another AlternatingTable, set style_data_text to False on... | the_stack_v2_python_sparse | cmd2/table_creator.py | python-cmd2/cmd2 | train | 571 |
975272fb32d6b908e02ef46ab80f47a3c88b4f48 | [
"mod = 10 ** 9 + 7\ndp = [[0] * (k + 1) for _ in range(n + 1)]\nfor i in range(n + 1):\n dp[i][0] = 1\nfor i in range(2, n + 1):\n for j in range(1, k + 1):\n for p in range(max(j - i + 1, 0), j + 1):\n dp[i][j] += dp[i - 1][p]\nreturn dp[n][k] % mod",
"mod = 10 ** 9 + 7\ndp = [[0] * (k + ... | <|body_start_0|>
mod = 10 ** 9 + 7
dp = [[0] * (k + 1) for _ in range(n + 1)]
for i in range(n + 1):
dp[i][0] = 1
for i in range(2, n + 1):
for j in range(1, k + 1):
for p in range(max(j - i + 1, 0), j + 1):
dp[i][j] += dp[i - 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kInversePairs(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_0|>
def kInversePairs_(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
mod = 10 ** 9 + 7
dp = [... | stack_v2_sparse_classes_36k_train_023916 | 1,427 | no_license | [
{
"docstring": ":type n: int :type k: int :rtype: int",
"name": "kInversePairs",
"signature": "def kInversePairs(self, n, k)"
},
{
"docstring": ":type n: int :type k: int :rtype: int",
"name": "kInversePairs_",
"signature": "def kInversePairs_(self, n, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004546 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kInversePairs(self, n, k): :type n: int :type k: int :rtype: int
- def kInversePairs_(self, n, k): :type n: int :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kInversePairs(self, n, k): :type n: int :type k: int :rtype: int
- def kInversePairs_(self, n, k): :type n: int :type k: int :rtype: int
<|skeleton|>
class Solution:
de... | 768edc4a5526c8972fec66c6a71a38c0b24a1451 | <|skeleton|>
class Solution:
def kInversePairs(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_0|>
def kInversePairs_(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kInversePairs(self, n, k):
""":type n: int :type k: int :rtype: int"""
mod = 10 ** 9 + 7
dp = [[0] * (k + 1) for _ in range(n + 1)]
for i in range(n + 1):
dp[i][0] = 1
for i in range(2, n + 1):
for j in range(1, k + 1):
... | the_stack_v2_python_sparse | leetcode(多线程,DP,贪心,SQL)/二刷DP与贪心LeetCode/动态规划/629. K个逆序对数组/solution.py | faker-hong/testOne | train | 1 | |
58a562ca3a21a8f19249454712500186291077b3 | [
"chex.assert_equal_shape((policy, mask))\ndo_finetune = jnp.logical_and(self.from_learner_steps >= 0, learner_steps > self.from_learner_steps)\nreturn jnp.where(do_finetune, self.post_process_policy(policy, mask), policy)",
"chex.assert_equal_shape((policy, mask))\npolicy = self._threshold(policy, mask)\npolicy =... | <|body_start_0|>
chex.assert_equal_shape((policy, mask))
do_finetune = jnp.logical_and(self.from_learner_steps >= 0, learner_steps > self.from_learner_steps)
return jnp.where(do_finetune, self.post_process_policy(policy, mask), policy)
<|end_body_0|>
<|body_start_1|>
chex.assert_equal_s... | Fine tuning options, aka policy post-processing. Even when fully trained, the resulting softmax-based policy may put a small probability mass on bad actions. This results in an agent waiting for the opponent (itself in self-play) to commit an error. To address that the policy is post-processed using: - thresholding: an... | FineTuning | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FineTuning:
"""Fine tuning options, aka policy post-processing. Even when fully trained, the resulting softmax-based policy may put a small probability mass on bad actions. This results in an agent waiting for the opponent (itself in self-play) to commit an error. To address that the policy is po... | stack_v2_sparse_classes_36k_train_023917 | 40,121 | permissive | [
{
"docstring": "A configurable fine tuning of a policy.",
"name": "__call__",
"signature": "def __call__(self, policy: chex.Array, mask: chex.Array, learner_steps: int) -> chex.Array"
},
{
"docstring": "Unconditionally post process a given masked policy.",
"name": "post_process_policy",
... | 5 | null | Implement the Python class `FineTuning` described below.
Class description:
Fine tuning options, aka policy post-processing. Even when fully trained, the resulting softmax-based policy may put a small probability mass on bad actions. This results in an agent waiting for the opponent (itself in self-play) to commit an ... | Implement the Python class `FineTuning` described below.
Class description:
Fine tuning options, aka policy post-processing. Even when fully trained, the resulting softmax-based policy may put a small probability mass on bad actions. This results in an agent waiting for the opponent (itself in self-play) to commit an ... | ee149736f7d85e16c119a463eee338c6d4c2ceb0 | <|skeleton|>
class FineTuning:
"""Fine tuning options, aka policy post-processing. Even when fully trained, the resulting softmax-based policy may put a small probability mass on bad actions. This results in an agent waiting for the opponent (itself in self-play) to commit an error. To address that the policy is po... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FineTuning:
"""Fine tuning options, aka policy post-processing. Even when fully trained, the resulting softmax-based policy may put a small probability mass on bad actions. This results in an agent waiting for the opponent (itself in self-play) to commit an error. To address that the policy is post-processed ... | the_stack_v2_python_sparse | open_spiel/python/algorithms/rnad/rnad.py | lanctot/open_spiel | train | 1 |
8099d6e0003613f125e4831fc65ba8684820cec3 | [
"self.sums = {}\nif len(nums) > 0:\n self.sums[0] = nums[0]\n for i in range(1, len(nums)):\n self.sums[i] = self.sums[i - 1] + nums[i]",
"if len(self.sums) == 0 or j >= len(self.sums):\n return None\nreturn self.sums[j] if i == 0 else self.sums[j] - self.sums[i - 1]"
] | <|body_start_0|>
self.sums = {}
if len(nums) > 0:
self.sums[0] = nums[0]
for i in range(1, len(nums)):
self.sums[i] = self.sums[i - 1] + nums[i]
<|end_body_0|>
<|body_start_1|>
if len(self.sums) == 0 or j >= len(self.sums):
return None
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sums = {}
if len(nums) > 0:
self.s... | stack_v2_sparse_classes_36k_train_023918 | 645 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001567 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | 1d0572efd88f9ad7eccccefe3fe170e92a9b6487 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.sums = {}
if len(nums) > 0:
self.sums[0] = nums[0]
for i in range(1, len(nums)):
self.sums[i] = self.sums[i - 1] + nums[i]
def sumRange(self, i, j):
""":type i: int... | the_stack_v2_python_sparse | Python3/Range Sum Query - Immutable.py | alexfy/LeetCode | train | 0 | |
0d6e5ee3cc02ede6de613b9c96492372e087416d | [
"if distr == 'norm':\n self.intvSampler = NormalSampler(intvMean, intvScale)\nelif distr == 'expo':\n rate = 1.0 / intvScale\n self.intvSampler = ExponentialSampler(rate)\nelse:\n raise ValueError('invalid distribution')\nself.spikeSampler = NormalSampler(spikeValueMean, spikeValueStd)\nself.spikeMaxDur... | <|body_start_0|>
if distr == 'norm':
self.intvSampler = NormalSampler(intvMean, intvScale)
elif distr == 'expo':
rate = 1.0 / intvScale
self.intvSampler = ExponentialSampler(rate)
else:
raise ValueError('invalid distribution')
self.spikeSam... | samples spikey data | SpikeyDataSampler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpikeyDataSampler:
"""samples spikey data"""
def __init__(self, intvMean, intvScale, distr, spikeValueMean, spikeValueStd, spikeMaxDuration, baseValue=0):
"""initializer Parameters intvMean : interval mean intvScale : interval std dev distr : type of distr for interval spikeValueMean... | stack_v2_sparse_classes_36k_train_023919 | 32,264 | permissive | [
{
"docstring": "initializer Parameters intvMean : interval mean intvScale : interval std dev distr : type of distr for interval spikeValueMean : spike value mean spikeValueStd : spike value std dev spikeMaxDuration : max duration for spike baseValue : base or offset value",
"name": "__init__",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_007340 | Implement the Python class `SpikeyDataSampler` described below.
Class description:
samples spikey data
Method signatures and docstrings:
- def __init__(self, intvMean, intvScale, distr, spikeValueMean, spikeValueStd, spikeMaxDuration, baseValue=0): initializer Parameters intvMean : interval mean intvScale : interval ... | Implement the Python class `SpikeyDataSampler` described below.
Class description:
samples spikey data
Method signatures and docstrings:
- def __init__(self, intvMean, intvScale, distr, spikeValueMean, spikeValueStd, spikeMaxDuration, baseValue=0): initializer Parameters intvMean : interval mean intvScale : interval ... | 861fd06b6b7abaffe5e8ca795136ab0fbb2234b5 | <|skeleton|>
class SpikeyDataSampler:
"""samples spikey data"""
def __init__(self, intvMean, intvScale, distr, spikeValueMean, spikeValueStd, spikeMaxDuration, baseValue=0):
"""initializer Parameters intvMean : interval mean intvScale : interval std dev distr : type of distr for interval spikeValueMean... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpikeyDataSampler:
"""samples spikey data"""
def __init__(self, intvMean, intvScale, distr, spikeValueMean, spikeValueStd, spikeMaxDuration, baseValue=0):
"""initializer Parameters intvMean : interval mean intvScale : interval std dev distr : type of distr for interval spikeValueMean : spike valu... | the_stack_v2_python_sparse | matumizi/matumizi/sampler.py | pranab/whakapai | train | 18 |
17af770d19b13bf3966e0867d49c3280d13c0059 | [
"try:\n code = pickle.dumps(activity_compile)\n obj = AES.new(AES_KEY, AES.MODE_ECB)\n code = code + '=' * (16 - len(code) % 16)\n code = obj.encrypt(code)\n code = base64.urlsafe_b64encode(code)\n return code\nexcept Exception as e:\n logging.error('encrypt_activity_compile_to_code error')\n ... | <|body_start_0|>
try:
code = pickle.dumps(activity_compile)
obj = AES.new(AES_KEY, AES.MODE_ECB)
code = code + '=' * (16 - len(code) % 16)
code = obj.encrypt(code)
code = base64.urlsafe_b64encode(code)
return code
except Exception a... | ActivityCompile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivityCompile:
def encrypt_activity_compile_to_code(activity_compile):
"""deprecated later"""
<|body_0|>
def decrypt_code_to_activity_compile(code):
"""deprecated later"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
code = pickle... | stack_v2_sparse_classes_36k_train_023920 | 1,840 | no_license | [
{
"docstring": "deprecated later",
"name": "encrypt_activity_compile_to_code",
"signature": "def encrypt_activity_compile_to_code(activity_compile)"
},
{
"docstring": "deprecated later",
"name": "decrypt_code_to_activity_compile",
"signature": "def decrypt_code_to_activity_compile(code)"... | 2 | stack_v2_sparse_classes_30k_train_000959 | Implement the Python class `ActivityCompile` described below.
Class description:
Implement the ActivityCompile class.
Method signatures and docstrings:
- def encrypt_activity_compile_to_code(activity_compile): deprecated later
- def decrypt_code_to_activity_compile(code): deprecated later | Implement the Python class `ActivityCompile` described below.
Class description:
Implement the ActivityCompile class.
Method signatures and docstrings:
- def encrypt_activity_compile_to_code(activity_compile): deprecated later
- def decrypt_code_to_activity_compile(code): deprecated later
<|skeleton|>
class Activity... | 0cd69ba5bf3c962c491fb7a814539929112def8f | <|skeleton|>
class ActivityCompile:
def encrypt_activity_compile_to_code(activity_compile):
"""deprecated later"""
<|body_0|>
def decrypt_code_to_activity_compile(code):
"""deprecated later"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActivityCompile:
def encrypt_activity_compile_to_code(activity_compile):
"""deprecated later"""
try:
code = pickle.dumps(activity_compile)
obj = AES.new(AES_KEY, AES.MODE_ECB)
code = code + '=' * (16 - len(code) % 16)
code = obj.encrypt(code)
... | the_stack_v2_python_sparse | app/models/activity_compile.py | flyakite/tracker | train | 0 | |
5bdbf11c4cfcb9a0185228801e2ea77cc24271a0 | [
"self.directions = self._listify_input(input_string.lower())\nself.steps = [0, 0, 0, 0]\nself.facing = 0\nself.locations = [(0, 0)]\nself.new_loc = (0, 0)",
"stripped_string = re.sub('\\\\s+', '', input_string.strip())\nsplit_list = stripped_string.split(',')\nreturn [(x[0], int(x[1:])) for x in split_list]",
"... | <|body_start_0|>
self.directions = self._listify_input(input_string.lower())
self.steps = [0, 0, 0, 0]
self.facing = 0
self.locations = [(0, 0)]
self.new_loc = (0, 0)
<|end_body_0|>
<|body_start_1|>
stripped_string = re.sub('\\s+', '', input_string.strip())
split... | Class for turning walking directions into distance from start. | Walker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Walker:
"""Class for turning walking directions into distance from start."""
def __init__(self, input_string):
"""Initialize."""
<|body_0|>
def _listify_input(self, input_string):
"""Turn a string of inputs into a list."""
<|body_1|>
def make_rotatio... | stack_v2_sparse_classes_36k_train_023921 | 2,294 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, input_string)"
},
{
"docstring": "Turn a string of inputs into a list.",
"name": "_listify_input",
"signature": "def _listify_input(self, input_string)"
},
{
"docstring": "Turn left or right, and u... | 6 | stack_v2_sparse_classes_30k_train_003366 | Implement the Python class `Walker` described below.
Class description:
Class for turning walking directions into distance from start.
Method signatures and docstrings:
- def __init__(self, input_string): Initialize.
- def _listify_input(self, input_string): Turn a string of inputs into a list.
- def make_rotation(se... | Implement the Python class `Walker` described below.
Class description:
Class for turning walking directions into distance from start.
Method signatures and docstrings:
- def __init__(self, input_string): Initialize.
- def _listify_input(self, input_string): Turn a string of inputs into a list.
- def make_rotation(se... | 17c729af2af5f1d95ba6ff68771a82ca6d00b05d | <|skeleton|>
class Walker:
"""Class for turning walking directions into distance from start."""
def __init__(self, input_string):
"""Initialize."""
<|body_0|>
def _listify_input(self, input_string):
"""Turn a string of inputs into a list."""
<|body_1|>
def make_rotatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Walker:
"""Class for turning walking directions into distance from start."""
def __init__(self, input_string):
"""Initialize."""
self.directions = self._listify_input(input_string.lower())
self.steps = [0, 0, 0, 0]
self.facing = 0
self.locations = [(0, 0)]
... | the_stack_v2_python_sparse | 2016/day01_no_time_for_a_taxicab/python/src/part2.py | tlake/advent-of-code | train | 0 |
964d1be65af658a3eb477f7c43be299042093370 | [
"res = []\n\ndef dfs(left, right, s):\n if left == n and right == n:\n res.append(s)\n return\n if left < n:\n dfs(left + 1, right, s + '(')\n if right < left:\n dfs(left, right + 1, s + ')')\ndfs(0, 0, '')\nreturn res",
"dp = [[] for _ in range(n + 1)]\ndp[0] = ''\nfor i in r... | <|body_start_0|>
res = []
def dfs(left, right, s):
if left == n and right == n:
res.append(s)
return
if left < n:
dfs(left + 1, right, s + '(')
if right < left:
dfs(left, right + 1, s + ')')
dfs(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
"""递归方法 :param n: :return:"""
<|body_0|>
def generateParenthesis1(self, n: int) -> List[str]:
"""动态规划 第一对括号一定是‘()’ ,后面的括号只能是在这个括号中间或者右面 因此有状态转移方程dp[i] = "(" + 【i=p时所有括号的排列组合】 + ")" + 【i=q时所有括号的排列组合】 p + q ... | stack_v2_sparse_classes_36k_train_023922 | 1,695 | no_license | [
{
"docstring": "递归方法 :param n: :return:",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n: int) -> List[str]"
},
{
"docstring": "动态规划 第一对括号一定是‘()’ ,后面的括号只能是在这个括号中间或者右面 因此有状态转移方程dp[i] = \"(\" + 【i=p时所有括号的排列组合】 + \")\" + 【i=q时所有括号的排列组合】 p + q = n - 1 参考题解: https://leet... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n: int) -> List[str]: 递归方法 :param n: :return:
- def generateParenthesis1(self, n: int) -> List[str]: 动态规划 第一对括号一定是‘()’ ,后面的括号只能是在这个括号中间或者右面 因此有状态转移方... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n: int) -> List[str]: 递归方法 :param n: :return:
- def generateParenthesis1(self, n: int) -> List[str]: 动态规划 第一对括号一定是‘()’ ,后面的括号只能是在这个括号中间或者右面 因此有状态转移方... | 578cacff5851c5c2522981693c34e3c318002d30 | <|skeleton|>
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
"""递归方法 :param n: :return:"""
<|body_0|>
def generateParenthesis1(self, n: int) -> List[str]:
"""动态规划 第一对括号一定是‘()’ ,后面的括号只能是在这个括号中间或者右面 因此有状态转移方程dp[i] = "(" + 【i=p时所有括号的排列组合】 + ")" + 【i=q时所有括号的排列组合】 p + q ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def generateParenthesis(self, n: int) -> List[str]:
"""递归方法 :param n: :return:"""
res = []
def dfs(left, right, s):
if left == n and right == n:
res.append(s)
return
if left < n:
dfs(left + 1, right, s +... | the_stack_v2_python_sparse | 括号生成.py | cjrzs/MyLeetCode | train | 8 | |
f16c84514defbbc1319eead11515ff60d318300d | [
"if interp not in {'linear', 'nearest'}:\n raise ValueError('interp must be one of {linear, nearest}')\nself.scale = list(scale)\nself.reference = reference\nself.interp = interp",
"if X.pixeltype != 'float':\n raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float')\ni... | <|body_start_0|>
if interp not in {'linear', 'nearest'}:
raise ValueError('interp must be one of {linear, nearest}')
self.scale = list(scale)
self.reference = reference
self.interp = interp
<|end_body_0|>
<|body_start_1|>
if X.pixeltype != 'float':
raise ... | Scale an image in physical space. This function calls highly optimized ITK/C++ code. | ScaleImage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScaleImage:
"""Scale an image in physical space. This function calls highly optimized ITK/C++ code."""
def __init__(self, scale, reference=None, interp='linear'):
"""Initialize a TranslateImage transform Arguments --------- scale : list, tuple, or numpy.ndarray relative scaling along... | stack_v2_sparse_classes_36k_train_023923 | 24,297 | permissive | [
{
"docstring": "Initialize a TranslateImage transform Arguments --------- scale : list, tuple, or numpy.ndarray relative scaling along each axis reference : ANTsImage (optional) image which provides the reference physical space in which to perform the transform interp : string type of interpolation to use optio... | 2 | null | Implement the Python class `ScaleImage` described below.
Class description:
Scale an image in physical space. This function calls highly optimized ITK/C++ code.
Method signatures and docstrings:
- def __init__(self, scale, reference=None, interp='linear'): Initialize a TranslateImage transform Arguments --------- sca... | Implement the Python class `ScaleImage` described below.
Class description:
Scale an image in physical space. This function calls highly optimized ITK/C++ code.
Method signatures and docstrings:
- def __init__(self, scale, reference=None, interp='linear'): Initialize a TranslateImage transform Arguments --------- sca... | 41f2dd3fcf72654f284dac1a9448033e963f0afb | <|skeleton|>
class ScaleImage:
"""Scale an image in physical space. This function calls highly optimized ITK/C++ code."""
def __init__(self, scale, reference=None, interp='linear'):
"""Initialize a TranslateImage transform Arguments --------- scale : list, tuple, or numpy.ndarray relative scaling along... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScaleImage:
"""Scale an image in physical space. This function calls highly optimized ITK/C++ code."""
def __init__(self, scale, reference=None, interp='linear'):
"""Initialize a TranslateImage transform Arguments --------- scale : list, tuple, or numpy.ndarray relative scaling along each axis re... | the_stack_v2_python_sparse | ants/contrib/sampling/transforms.py | ANTsX/ANTsPy | train | 483 |
01b190add20f8cce1f784c3292f2c9e8634de606 | [
"if root is None:\n return 0\nreturn 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))",
"\"\"\" Do a BFS \"\"\"\nimport collections\nq = collections.deque()\ndepth = 0\nq.append(root)\nwhile q:\n levelSize = len(q)\n depth += 1\n for i in range(levelSize):\n node = q.popleft()\n ... | <|body_start_0|>
if root is None:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
<|end_body_0|>
<|body_start_1|>
""" Do a BFS """
import collections
q = collections.deque()
depth = 0
q.append(root)
while q:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
return 0
return ... | stack_v2_sparse_classes_36k_train_023924 | 971 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003978 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def maxDepth(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def maxDepth(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def maxDepth(self, root... | 5714fdb2d8a89a68d68d07f7ffd3f6bcff5b2ccf | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
if root is None:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
""" Do a BFS """
... | the_stack_v2_python_sparse | Python/tree/104_max_depth.py | 01-Jacky/PracticeProblems | train | 0 | |
b3da686604b9a13ab480f251b59cbcc2b1bea1d3 | [
"try:\n float(s)\nexcept ValueError:\n return False\nelse:\n return True",
"state = [{}, {'blank': 1, 'sign': 2, 'digit': 3, '.': 4}, {'digit': 3, '.': 4}, {'digit': 3, '.': 5, 'e': 6, 'blank': 9}, {'digit': 5}, {'digit': 5, 'e': 6, 'blank': 9}, {'sign': 7, 'digit': 8}, {'digit': 8}, {'digit': 8, 'blank'... | <|body_start_0|>
try:
float(s)
except ValueError:
return False
else:
return True
<|end_body_0|>
<|body_start_1|>
state = [{}, {'blank': 1, 'sign': 2, 'digit': 3, '.': 4}, {'digit': 3, '.': 4}, {'digit': 3, '.': 5, 'e': 6, 'blank': 9}, {'digit': 5}, {'... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isNumber(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isNumber2(self, s):
"""https://discuss.leetcode.com/topic/30058/a-simple-solution-in-python-based-on-dfa :param s: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_023925 | 1,800 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "isNumber",
"signature": "def isNumber(self, s)"
},
{
"docstring": "https://discuss.leetcode.com/topic/30058/a-simple-solution-in-python-based-on-dfa :param s: :return:",
"name": "isNumber2",
"signature": "def isNumber2(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isNumber(self, s): :type s: str :rtype: bool
- def isNumber2(self, s): https://discuss.leetcode.com/topic/30058/a-simple-solution-in-python-based-on-dfa :param s: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isNumber(self, s): :type s: str :rtype: bool
- def isNumber2(self, s): https://discuss.leetcode.com/topic/30058/a-simple-solution-in-python-based-on-dfa :param s: :return:
<... | 2526f8c0dec7101123123740e146ee4081e979ee | <|skeleton|>
class Solution:
def isNumber(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isNumber2(self, s):
"""https://discuss.leetcode.com/topic/30058/a-simple-solution-in-python-based-on-dfa :param s: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isNumber(self, s):
""":type s: str :rtype: bool"""
try:
float(s)
except ValueError:
return False
else:
return True
def isNumber2(self, s):
"""https://discuss.leetcode.com/topic/30058/a-simple-solution-in-python-base... | the_stack_v2_python_sparse | 065. Valid Number.py | zhangpengGenedock/leetcode_python | train | 1 | |
098f4a68571c592ab452b243c06c946d55810bc5 | [
"super(RNN, self).__init__()\nself.output_size = output_size\nself.n_layers = n_layers\nself.hidden_dim = hidden_dim\nself.embed = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim)\nself.lstm = nn.LSTM(input_size=embedding_dim, hidden_size=hidden_dim, num_layers=n_layers, dropout=dropout, batch_f... | <|body_start_0|>
super(RNN, self).__init__()
self.output_size = output_size
self.n_layers = n_layers
self.hidden_dim = hidden_dim
self.embed = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim)
self.lstm = nn.LSTM(input_size=embedding_dim, hidden_size=hi... | RNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNN:
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):
"""Initialize the PyTorch RNN module :param vocab_size: The number of input dimensions of the neural network (size of the vocabulary) :param output_size: The number of output dimensions of... | stack_v2_sparse_classes_36k_train_023926 | 11,328 | no_license | [
{
"docstring": "Initialize the PyTorch RNN module :param vocab_size: The number of input dimensions of the neural network (size of the vocabulary) :param output_size: The number of output dimensions of the neural network :param embedding_dim: The size of the embeddings :param hidden_dim: The size of the hidden ... | 3 | stack_v2_sparse_classes_30k_train_016165 | Implement the Python class `RNN` described below.
Class description:
Implement the RNN class.
Method signatures and docstrings:
- def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5): Initialize the PyTorch RNN module :param vocab_size: The number of input dimensions of the ne... | Implement the Python class `RNN` described below.
Class description:
Implement the RNN class.
Method signatures and docstrings:
- def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5): Initialize the PyTorch RNN module :param vocab_size: The number of input dimensions of the ne... | 727cedd3e3aca715b9326f625548bedb5a0c1b9b | <|skeleton|>
class RNN:
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):
"""Initialize the PyTorch RNN module :param vocab_size: The number of input dimensions of the neural network (size of the vocabulary) :param output_size: The number of output dimensions of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNN:
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):
"""Initialize the PyTorch RNN module :param vocab_size: The number of input dimensions of the neural network (size of the vocabulary) :param output_size: The number of output dimensions of the neural ne... | the_stack_v2_python_sparse | recurring_neural_network/tv_script_generation/tv_script_generation.py | sivaneshl/deep_learning_course | train | 0 | |
f43f2bac27c2efe86f61879ebfb619c0aa6ac03a | [
"self.id = id\nself.name = name\nself.created_time = APIHelper.RFC3339DateTime(created_time) if created_time else None\nself.completed_time = APIHelper.RFC3339DateTime(completed_time) if completed_time else None\nself.conference_event_url = conference_event_url\nself.conference_event_method = conference_event_metho... | <|body_start_0|>
self.id = id
self.name = name
self.created_time = APIHelper.RFC3339DateTime(created_time) if created_time else None
self.completed_time = APIHelper.RFC3339DateTime(completed_time) if completed_time else None
self.conference_event_url = conference_event_url
... | Implementation of the 'ConferenceState' model. TODO: type model description here. Attributes: id (string): TODO: type description here. name (string): TODO: type description here. created_time (datetime): TODO: type description here. completed_time (datetime): TODO: type description here. conference_event_url (string):... | ConferenceState | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConferenceState:
"""Implementation of the 'ConferenceState' model. TODO: type model description here. Attributes: id (string): TODO: type description here. name (string): TODO: type description here. created_time (datetime): TODO: type description here. completed_time (datetime): TODO: type descr... | stack_v2_sparse_classes_36k_train_023927 | 3,911 | permissive | [
{
"docstring": "Constructor for the ConferenceState class",
"name": "__init__",
"signature": "def __init__(self, id=None, name=None, created_time=None, completed_time=None, conference_event_url=None, conference_event_method=None, tag=None, active_members=None)"
},
{
"docstring": "Creates an inst... | 2 | null | Implement the Python class `ConferenceState` described below.
Class description:
Implementation of the 'ConferenceState' model. TODO: type model description here. Attributes: id (string): TODO: type description here. name (string): TODO: type description here. created_time (datetime): TODO: type description here. comp... | Implement the Python class `ConferenceState` described below.
Class description:
Implementation of the 'ConferenceState' model. TODO: type model description here. Attributes: id (string): TODO: type description here. name (string): TODO: type description here. created_time (datetime): TODO: type description here. comp... | 447df3cc8cb7acaf3361d842630c432a9c31ce6e | <|skeleton|>
class ConferenceState:
"""Implementation of the 'ConferenceState' model. TODO: type model description here. Attributes: id (string): TODO: type description here. name (string): TODO: type description here. created_time (datetime): TODO: type description here. completed_time (datetime): TODO: type descr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConferenceState:
"""Implementation of the 'ConferenceState' model. TODO: type model description here. Attributes: id (string): TODO: type description here. name (string): TODO: type description here. created_time (datetime): TODO: type description here. completed_time (datetime): TODO: type description here. ... | the_stack_v2_python_sparse | bandwidth/voice/models/conference_state.py | Bandwidth/python-sdk | train | 10 |
8409d138c9e86fa71bdf4bd6bb2bb38f844eda1f | [
"self._is_transient = is_transient\nself._max_attempts = max_attempts\nself._sleep = sleep",
"failures = 0\nwhile True:\n try:\n return callback()\n except Exception as e:\n failures += 1\n if failures == self._max_attempts or not self._is_transient(e):\n raise\n tf.lo... | <|body_start_0|>
self._is_transient = is_transient
self._max_attempts = max_attempts
self._sleep = sleep
<|end_body_0|>
<|body_start_1|>
failures = 0
while True:
try:
return callback()
except Exception as e:
failures += 1
... | Helper class for retrying things with exponential back-off. | Retrier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Retrier:
"""Helper class for retrying things with exponential back-off."""
def __init__(self, is_transient, max_attempts=8, sleep=time.sleep):
"""Creates new instance. :type is_transient: (Exception) -> bool :type max_attempts: int :type sleep: (float) -> None"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_023928 | 16,613 | permissive | [
{
"docstring": "Creates new instance. :type is_transient: (Exception) -> bool :type max_attempts: int :type sleep: (float) -> None",
"name": "__init__",
"signature": "def __init__(self, is_transient, max_attempts=8, sleep=time.sleep)"
},
{
"docstring": "Invokes callback, retrying on transient ex... | 2 | null | Implement the Python class `Retrier` described below.
Class description:
Helper class for retrying things with exponential back-off.
Method signatures and docstrings:
- def __init__(self, is_transient, max_attempts=8, sleep=time.sleep): Creates new instance. :type is_transient: (Exception) -> bool :type max_attempts:... | Implement the Python class `Retrier` described below.
Class description:
Helper class for retrying things with exponential back-off.
Method signatures and docstrings:
- def __init__(self, is_transient, max_attempts=8, sleep=time.sleep): Creates new instance. :type is_transient: (Exception) -> bool :type max_attempts:... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class Retrier:
"""Helper class for retrying things with exponential back-off."""
def __init__(self, is_transient, max_attempts=8, sleep=time.sleep):
"""Creates new instance. :type is_transient: (Exception) -> bool :type max_attempts: int :type sleep: (float) -> None"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Retrier:
"""Helper class for retrying things with exponential back-off."""
def __init__(self, is_transient, max_attempts=8, sleep=time.sleep):
"""Creates new instance. :type is_transient: (Exception) -> bool :type max_attempts: int :type sleep: (float) -> None"""
self._is_transient = is_t... | the_stack_v2_python_sparse | Keras_tensorflow_nightly/source2.7/tensorboard/util.py | ryfeus/lambda-packs | train | 1,283 |
e916f319a9ea6edeb6986e97ddea0ce4e4ed27cc | [
"if resolver_helper.type_indicator not in cls._resolver_helpers:\n raise KeyError(f'Resolver helper object not set for type indicator: {resolver_helper.type_indicator:s}.')\ndel cls._resolver_helpers[resolver_helper.type_indicator]",
"if type_indicator not in cls._resolver_helpers:\n raise KeyError(f'Resolv... | <|body_start_0|>
if resolver_helper.type_indicator not in cls._resolver_helpers:
raise KeyError(f'Resolver helper object not set for type indicator: {resolver_helper.type_indicator:s}.')
del cls._resolver_helpers[resolver_helper.type_indicator]
<|end_body_0|>
<|body_start_1|>
if typ... | Path specification resolver helper manager. | ResolverHelperManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResolverHelperManager:
"""Path specification resolver helper manager."""
def DeregisterHelper(cls, resolver_helper):
"""Deregisters a path specification resolver helper. Args: resolver_helper (ResolverHelper): resolver helper. Raises: KeyError: if resolver helper object is not set fo... | stack_v2_sparse_classes_36k_train_023929 | 1,928 | permissive | [
{
"docstring": "Deregisters a path specification resolver helper. Args: resolver_helper (ResolverHelper): resolver helper. Raises: KeyError: if resolver helper object is not set for the corresponding type indicator.",
"name": "DeregisterHelper",
"signature": "def DeregisterHelper(cls, resolver_helper)"
... | 3 | null | Implement the Python class `ResolverHelperManager` described below.
Class description:
Path specification resolver helper manager.
Method signatures and docstrings:
- def DeregisterHelper(cls, resolver_helper): Deregisters a path specification resolver helper. Args: resolver_helper (ResolverHelper): resolver helper. ... | Implement the Python class `ResolverHelperManager` described below.
Class description:
Path specification resolver helper manager.
Method signatures and docstrings:
- def DeregisterHelper(cls, resolver_helper): Deregisters a path specification resolver helper. Args: resolver_helper (ResolverHelper): resolver helper. ... | 28756d910e951a22c5f0b2bcf5184f055a19d544 | <|skeleton|>
class ResolverHelperManager:
"""Path specification resolver helper manager."""
def DeregisterHelper(cls, resolver_helper):
"""Deregisters a path specification resolver helper. Args: resolver_helper (ResolverHelper): resolver helper. Raises: KeyError: if resolver helper object is not set fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResolverHelperManager:
"""Path specification resolver helper manager."""
def DeregisterHelper(cls, resolver_helper):
"""Deregisters a path specification resolver helper. Args: resolver_helper (ResolverHelper): resolver helper. Raises: KeyError: if resolver helper object is not set for the corresp... | the_stack_v2_python_sparse | dfvfs/resolver_helpers/manager.py | log2timeline/dfvfs | train | 197 |
9a87cb3d5ae9d0065db3c9714197f9e78f270757 | [
"super().__init__(cluster, endpoint)\nif self.cluster.endpoint.model == 'lumi.motion.ac02':\n self.ZCL_INIT_ATTRS = {'detection_interval': True, 'motion_sensitivity': True, 'trigger_indicator': True}\nelif self.cluster.endpoint.model == 'lumi.motion.agl04':\n self.ZCL_INIT_ATTRS = {'detection_interval': True,... | <|body_start_0|>
super().__init__(cluster, endpoint)
if self.cluster.endpoint.model == 'lumi.motion.ac02':
self.ZCL_INIT_ATTRS = {'detection_interval': True, 'motion_sensitivity': True, 'trigger_indicator': True}
elif self.cluster.endpoint.model == 'lumi.motion.agl04':
se... | Opple cluster handler. | OppleRemote | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OppleRemote:
"""Opple cluster handler."""
def __init__(self, cluster: zigpy.zcl.Cluster, endpoint: Endpoint) -> None:
"""Initialize Opple cluster handler."""
<|body_0|>
async def async_initialize_cluster_handler_specific(self, from_cache: bool) -> None:
"""Initia... | stack_v2_sparse_classes_36k_train_023930 | 13,186 | permissive | [
{
"docstring": "Initialize Opple cluster handler.",
"name": "__init__",
"signature": "def __init__(self, cluster: zigpy.zcl.Cluster, endpoint: Endpoint) -> None"
},
{
"docstring": "Initialize cluster handler specific.",
"name": "async_initialize_cluster_handler_specific",
"signature": "a... | 2 | null | Implement the Python class `OppleRemote` described below.
Class description:
Opple cluster handler.
Method signatures and docstrings:
- def __init__(self, cluster: zigpy.zcl.Cluster, endpoint: Endpoint) -> None: Initialize Opple cluster handler.
- async def async_initialize_cluster_handler_specific(self, from_cache: ... | Implement the Python class `OppleRemote` described below.
Class description:
Opple cluster handler.
Method signatures and docstrings:
- def __init__(self, cluster: zigpy.zcl.Cluster, endpoint: Endpoint) -> None: Initialize Opple cluster handler.
- async def async_initialize_cluster_handler_specific(self, from_cache: ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OppleRemote:
"""Opple cluster handler."""
def __init__(self, cluster: zigpy.zcl.Cluster, endpoint: Endpoint) -> None:
"""Initialize Opple cluster handler."""
<|body_0|>
async def async_initialize_cluster_handler_specific(self, from_cache: bool) -> None:
"""Initia... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OppleRemote:
"""Opple cluster handler."""
def __init__(self, cluster: zigpy.zcl.Cluster, endpoint: Endpoint) -> None:
"""Initialize Opple cluster handler."""
super().__init__(cluster, endpoint)
if self.cluster.endpoint.model == 'lumi.motion.ac02':
self.ZCL_INIT_ATTRS =... | the_stack_v2_python_sparse | homeassistant/components/zha/core/cluster_handlers/manufacturerspecific.py | home-assistant/core | train | 35,501 |
4b0341f4952bf77825858b09db9c60a4693e64ad | [
"if key is not None:\n self.key = key\n self.conf = self.get_train_obj(key)",
"try:\n graph_id = str(graph_id)\n query_set = models.AUTO_ML_RULE.objects.all()\n query_set = serial.serialize('json', query_set)\n query_set = json.loads(query_set)\n ids = []\n for row in query_set:\n g... | <|body_start_0|>
if key is not None:
self.key = key
self.conf = self.get_train_obj(key)
<|end_body_0|>
<|body_start_1|>
try:
graph_id = str(graph_id)
query_set = models.AUTO_ML_RULE.objects.all()
query_set = serial.serialize('json', query_set)... | Auto ML related conf get/set common methos | AutoMlRule | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoMlRule:
"""Auto ML related conf get/set common methos"""
def __init__(self, key=None):
"""init key variable :param key: :return:"""
<|body_0|>
def get_graph_type_list(self, graph_id):
"""get view data for net config :return:"""
<|body_1|>
def get... | stack_v2_sparse_classes_36k_train_023931 | 3,528 | permissive | [
{
"docstring": "init key variable :param key: :return:",
"name": "__init__",
"signature": "def __init__(self, key=None)"
},
{
"docstring": "get view data for net config :return:",
"name": "get_graph_type_list",
"signature": "def get_graph_type_list(self, graph_id)"
},
{
"docstrin... | 5 | stack_v2_sparse_classes_30k_train_001542 | Implement the Python class `AutoMlRule` described below.
Class description:
Auto ML related conf get/set common methos
Method signatures and docstrings:
- def __init__(self, key=None): init key variable :param key: :return:
- def get_graph_type_list(self, graph_id): get view data for net config :return:
- def get_gra... | Implement the Python class `AutoMlRule` described below.
Class description:
Auto ML related conf get/set common methos
Method signatures and docstrings:
- def __init__(self, key=None): init key variable :param key: :return:
- def get_graph_type_list(self, graph_id): get view data for net config :return:
- def get_gra... | 6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f | <|skeleton|>
class AutoMlRule:
"""Auto ML related conf get/set common methos"""
def __init__(self, key=None):
"""init key variable :param key: :return:"""
<|body_0|>
def get_graph_type_list(self, graph_id):
"""get view data for net config :return:"""
<|body_1|>
def get... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoMlRule:
"""Auto ML related conf get/set common methos"""
def __init__(self, key=None):
"""init key variable :param key: :return:"""
if key is not None:
self.key = key
self.conf = self.get_train_obj(key)
def get_graph_type_list(self, graph_id):
"""g... | the_stack_v2_python_sparse | master/automl/automl_rule.py | yurimkoo/tensormsa | train | 1 |
761d059bc51ee29c9b235411e3002479972c7202 | [
"adm = ProjectAdministration()\nprojtyp = adm.get_project_type_by_id(project_type_id)\nreturn projtyp",
"adm = ProjectAdministration()\nprojtyp = adm.get_project_type_by_id(project_type_id)\nif projtyp is not None:\n adm.delete_project_type(projtyp)\n return ('gelöscht', 200)\nelse:\n return ('', 500)",
... | <|body_start_0|>
adm = ProjectAdministration()
projtyp = adm.get_project_type_by_id(project_type_id)
return projtyp
<|end_body_0|>
<|body_start_1|>
adm = ProjectAdministration()
projtyp = adm.get_project_type_by_id(project_type_id)
if projtyp is not None:
adm... | ProjectTypeOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectTypeOperations:
def get(self, project_type_id):
"""Auslesen eines bestimmten ProjectType-Objektes, welches durch die project_type_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, project_type_id):
"""Löschen eines bestimmten ProjectType-Objektes, we... | stack_v2_sparse_classes_36k_train_023932 | 44,493 | no_license | [
{
"docstring": "Auslesen eines bestimmten ProjectType-Objektes, welches durch die project_type_id in dem URI bestimmt wird.",
"name": "get",
"signature": "def get(self, project_type_id)"
},
{
"docstring": "Löschen eines bestimmten ProjectType-Objektes, welches durch die project_type_id in dem UR... | 3 | stack_v2_sparse_classes_30k_train_020064 | Implement the Python class `ProjectTypeOperations` described below.
Class description:
Implement the ProjectTypeOperations class.
Method signatures and docstrings:
- def get(self, project_type_id): Auslesen eines bestimmten ProjectType-Objektes, welches durch die project_type_id in dem URI bestimmt wird.
- def delete... | Implement the Python class `ProjectTypeOperations` described below.
Class description:
Implement the ProjectTypeOperations class.
Method signatures and docstrings:
- def get(self, project_type_id): Auslesen eines bestimmten ProjectType-Objektes, welches durch die project_type_id in dem URI bestimmt wird.
- def delete... | 4b2826225525ae855e15e1174f5cf90466097021 | <|skeleton|>
class ProjectTypeOperations:
def get(self, project_type_id):
"""Auslesen eines bestimmten ProjectType-Objektes, welches durch die project_type_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, project_type_id):
"""Löschen eines bestimmten ProjectType-Objektes, we... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectTypeOperations:
def get(self, project_type_id):
"""Auslesen eines bestimmten ProjectType-Objektes, welches durch die project_type_id in dem URI bestimmt wird."""
adm = ProjectAdministration()
projtyp = adm.get_project_type_by_id(project_type_id)
return projtyp
def d... | the_stack_v2_python_sparse | src/main.py | KieserChristian/SW_Praktikum_Gruppe1 | train | 0 | |
f1cdf7019152846912025f3c694bce0b8f46ef28 | [
"json_obj = json.loads(json_string)\nnew_op = cls.__new__(cls)\nnew_op.__dict__ = json_obj\nif 'transforms' in json_obj.keys():\n transforms = []\n for json_op in json_obj['transforms']:\n transforms.append(getattr(sys.modules.get(json_op.get('python_module')), json_op.get('tensor_op_name')).from_json(... | <|body_start_0|>
json_obj = json.loads(json_string)
new_op = cls.__new__(cls)
new_op.__dict__ = json_obj
if 'transforms' in json_obj.keys():
transforms = []
for json_op in json_obj['transforms']:
transforms.append(getattr(sys.modules.get(json_op.ge... | Base Python Tensor Operations class | PyTensorOperation | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"OpenSSL",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause-Open-MPI",
"MIT",
"MPL-2.0-no-copyleft-exception",
"NTP",
"BSD-3-Clause",
"GPL-1.0-or-later",
"0BSD",
"MPL-2.0",
"LicenseRef-scancode-f... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyTensorOperation:
"""Base Python Tensor Operations class"""
def from_json(cls, json_string):
"""Base from_json for Python tensor operations class"""
<|body_0|>
def to_json(self):
"""Base to_json for Python tensor operations class"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_023933 | 15,590 | permissive | [
{
"docstring": "Base from_json for Python tensor operations class",
"name": "from_json",
"signature": "def from_json(cls, json_string)"
},
{
"docstring": "Base to_json for Python tensor operations class",
"name": "to_json",
"signature": "def to_json(self)"
}
] | 2 | null | Implement the Python class `PyTensorOperation` described below.
Class description:
Base Python Tensor Operations class
Method signatures and docstrings:
- def from_json(cls, json_string): Base from_json for Python tensor operations class
- def to_json(self): Base to_json for Python tensor operations class | Implement the Python class `PyTensorOperation` described below.
Class description:
Base Python Tensor Operations class
Method signatures and docstrings:
- def from_json(cls, json_string): Base from_json for Python tensor operations class
- def to_json(self): Base to_json for Python tensor operations class
<|skeleton... | 54acb15d435533c815ee1bd9f6dc0b56b4d4cf83 | <|skeleton|>
class PyTensorOperation:
"""Base Python Tensor Operations class"""
def from_json(cls, json_string):
"""Base from_json for Python tensor operations class"""
<|body_0|>
def to_json(self):
"""Base to_json for Python tensor operations class"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PyTensorOperation:
"""Base Python Tensor Operations class"""
def from_json(cls, json_string):
"""Base from_json for Python tensor operations class"""
json_obj = json.loads(json_string)
new_op = cls.__new__(cls)
new_op.__dict__ = json_obj
if 'transforms' in json_obj... | the_stack_v2_python_sparse | mindspore/python/mindspore/dataset/transforms/py_transforms.py | mindspore-ai/mindspore | train | 4,178 |
eb299685a7600c50392160f2b05fcf206e69b985 | [
"path = path or tempfile.mkdtemp()\nwith open(os.path.join(path, cls.MODEL_FILENAME), 'wb') as f:\n cpickle.dump(estimator, f)\ncheckpoint = cls.from_directory(path)\nif preprocessor:\n checkpoint.set_preprocessor(preprocessor)\nreturn checkpoint",
"with self.as_directory() as checkpoint_path:\n estimato... | <|body_start_0|>
path = path or tempfile.mkdtemp()
with open(os.path.join(path, cls.MODEL_FILENAME), 'wb') as f:
cpickle.dump(estimator, f)
checkpoint = cls.from_directory(path)
if preprocessor:
checkpoint.set_preprocessor(preprocessor)
return checkpoint
<... | A :py:class:`~ray.train.Checkpoint` with sklearn-specific functionality. | SklearnCheckpoint | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SklearnCheckpoint:
"""A :py:class:`~ray.train.Checkpoint` with sklearn-specific functionality."""
def from_estimator(cls, estimator: BaseEstimator, *, path: Union[str, os.PathLike]=None, preprocessor: Optional['Preprocessor']=None) -> 'SklearnCheckpoint':
"""Create a :py:class:`~ray.... | stack_v2_sparse_classes_36k_train_023934 | 2,206 | permissive | [
{
"docstring": "Create a :py:class:`~ray.train.Checkpoint` that stores an sklearn ``Estimator``. Args: estimator: The ``Estimator`` to store in the checkpoint. path: The directory where the checkpoint will be stored. Defaults to a temporary directory. preprocessor: A fitted preprocessor to be applied before inf... | 2 | null | Implement the Python class `SklearnCheckpoint` described below.
Class description:
A :py:class:`~ray.train.Checkpoint` with sklearn-specific functionality.
Method signatures and docstrings:
- def from_estimator(cls, estimator: BaseEstimator, *, path: Union[str, os.PathLike]=None, preprocessor: Optional['Preprocessor'... | Implement the Python class `SklearnCheckpoint` described below.
Class description:
A :py:class:`~ray.train.Checkpoint` with sklearn-specific functionality.
Method signatures and docstrings:
- def from_estimator(cls, estimator: BaseEstimator, *, path: Union[str, os.PathLike]=None, preprocessor: Optional['Preprocessor'... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class SklearnCheckpoint:
"""A :py:class:`~ray.train.Checkpoint` with sklearn-specific functionality."""
def from_estimator(cls, estimator: BaseEstimator, *, path: Union[str, os.PathLike]=None, preprocessor: Optional['Preprocessor']=None) -> 'SklearnCheckpoint':
"""Create a :py:class:`~ray.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SklearnCheckpoint:
"""A :py:class:`~ray.train.Checkpoint` with sklearn-specific functionality."""
def from_estimator(cls, estimator: BaseEstimator, *, path: Union[str, os.PathLike]=None, preprocessor: Optional['Preprocessor']=None) -> 'SklearnCheckpoint':
"""Create a :py:class:`~ray.train.Checkpo... | the_stack_v2_python_sparse | python/ray/train/sklearn/sklearn_checkpoint.py | ray-project/ray | train | 29,482 |
0ec8e98f3306748e63dca28e61be7ec2269591fa | [
"super().__init__(classes=classes, pred_dir=pred_dir, gt_dir=gt_dir, target_metric=target_metric, save_dir=save_dir)\nself.evaluator_cls = BoxEvaluator\nself.ensembler_cls = ensembler_cls",
"state, sweep_params = self.ensembler_cls.sweep_parameters()\nnum_cases = self.ensembler_cls.get_case_ids(self.pred_dir)\nlo... | <|body_start_0|>
super().__init__(classes=classes, pred_dir=pred_dir, gt_dir=gt_dir, target_metric=target_metric, save_dir=save_dir)
self.evaluator_cls = BoxEvaluator
self.ensembler_cls = ensembler_cls
<|end_body_0|>
<|body_start_1|>
state, sweep_params = self.ensembler_cls.sweep_parame... | BoxSweeper | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BoxSweeper:
def __init__(self, classes: Sequence[str], pred_dir: Pathlike, gt_dir: Pathlike, target_metric: str, ensembler_cls: Callable, save_dir: Optional[Pathlike]=None) -> None:
"""Run sweep over parameters and select the best Args: classes: classes present in dataset pred_dir: direc... | stack_v2_sparse_classes_36k_train_023935 | 7,907 | permissive | [
{
"docstring": "Run sweep over parameters and select the best Args: classes: classes present in dataset pred_dir: directory where predictions are saved gt_dir: directory where ground truth is saved target_metric: metric to optimize ensembler_cls: ensembler class used during prediction save_dir: Directory to sav... | 4 | null | Implement the Python class `BoxSweeper` described below.
Class description:
Implement the BoxSweeper class.
Method signatures and docstrings:
- def __init__(self, classes: Sequence[str], pred_dir: Pathlike, gt_dir: Pathlike, target_metric: str, ensembler_cls: Callable, save_dir: Optional[Pathlike]=None) -> None: Run ... | Implement the Python class `BoxSweeper` described below.
Class description:
Implement the BoxSweeper class.
Method signatures and docstrings:
- def __init__(self, classes: Sequence[str], pred_dir: Pathlike, gt_dir: Pathlike, target_metric: str, ensembler_cls: Callable, save_dir: Optional[Pathlike]=None) -> None: Run ... | 4f41faa7536dcef8fca7b647dcdca25360e5b58a | <|skeleton|>
class BoxSweeper:
def __init__(self, classes: Sequence[str], pred_dir: Pathlike, gt_dir: Pathlike, target_metric: str, ensembler_cls: Callable, save_dir: Optional[Pathlike]=None) -> None:
"""Run sweep over parameters and select the best Args: classes: classes present in dataset pred_dir: direc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BoxSweeper:
def __init__(self, classes: Sequence[str], pred_dir: Pathlike, gt_dir: Pathlike, target_metric: str, ensembler_cls: Callable, save_dir: Optional[Pathlike]=None) -> None:
"""Run sweep over parameters and select the best Args: classes: classes present in dataset pred_dir: directory where pre... | the_stack_v2_python_sparse | nndet/inference/sweeper.py | dboun/nnDetection | train | 1 | |
6793dbbd0be10530ea0fd011e6b097a6813cb588 | [
"vulnerability = CVESearchVulnerabilityResult()\nvulnerability.published = data.get('Published')\nvulnerability.access = data.get('access')\nvulnerability.impact = data.get('impact')\nvulnerability.summary = data.get('summary')\nvulnerability.cwe = data.get('cwe')\nvulnerability.cvss = data.get('cvss')\nvulnerabili... | <|body_start_0|>
vulnerability = CVESearchVulnerabilityResult()
vulnerability.published = data.get('Published')
vulnerability.access = data.get('access')
vulnerability.impact = data.get('impact')
vulnerability.summary = data.get('summary')
vulnerability.cwe = data.get('cw... | CVE-search output parser. Supports both text and json (default) outputs. | CVESearchParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CVESearchParser:
"""CVE-search output parser. Supports both text and json (default) outputs."""
def dict_to_result(cls, data):
"""Convert cve-search result dict to CVESearchVulnerabilityResult object Args: data (dict): Returns: CVESearchVulnerabilityResult"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_023936 | 1,731 | permissive | [
{
"docstring": "Convert cve-search result dict to CVESearchVulnerabilityResult object Args: data (dict): Returns: CVESearchVulnerabilityResult",
"name": "dict_to_result",
"signature": "def dict_to_result(cls, data)"
},
{
"docstring": "Convert list of cve-search result dicts to CVESearchVulnerabi... | 2 | null | Implement the Python class `CVESearchParser` described below.
Class description:
CVE-search output parser. Supports both text and json (default) outputs.
Method signatures and docstrings:
- def dict_to_result(cls, data): Convert cve-search result dict to CVESearchVulnerabilityResult object Args: data (dict): Returns:... | Implement the Python class `CVESearchParser` described below.
Class description:
CVE-search output parser. Supports both text and json (default) outputs.
Method signatures and docstrings:
- def dict_to_result(cls, data): Convert cve-search result dict to CVESearchVulnerabilityResult object Args: data (dict): Returns:... | bb21ff02965ed0cca5a55ee559eae77856d9866c | <|skeleton|>
class CVESearchParser:
"""CVE-search output parser. Supports both text and json (default) outputs."""
def dict_to_result(cls, data):
"""Convert cve-search result dict to CVESearchVulnerabilityResult object Args: data (dict): Returns: CVESearchVulnerabilityResult"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CVESearchParser:
"""CVE-search output parser. Supports both text and json (default) outputs."""
def dict_to_result(cls, data):
"""Convert cve-search result dict to CVESearchVulnerabilityResult object Args: data (dict): Returns: CVESearchVulnerabilityResult"""
vulnerability = CVESearchVuln... | the_stack_v2_python_sparse | tools/cve_search/parsers.py | collectivesense/aucote | train | 0 |
b114ff774ffe001908778283966049f9264b9797 | [
"super(TestCase, self).setUp()\ntest_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)\ntry:\n test_timeout = int(test_timeout)\nexcept ValueError:\n test_timeout = 0\nif test_timeout > 0:\n self.useFixture(fixtures.Timeout(test_timeout, gentle=True))\nself.useFixture(fixtures.NestedTempfile())\nself.useFixtu... | <|body_start_0|>
super(TestCase, self).setUp()
test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
try:
test_timeout = int(test_timeout)
except ValueError:
test_timeout = 0
if test_timeout > 0:
self.useFixture(fixtures.Timeout(test_timeout, gen... | Test case base class for all unit tests. | TestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCase:
"""Test case base class for all unit tests."""
def setUp(self):
"""Run before each test method to initialize test environment."""
<|body_0|>
def tearDown(self):
"""Runs after each test method to tear down test environment."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_023937 | 2,975 | permissive | [
{
"docstring": "Run before each test method to initialize test environment.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Runs after each test method to tear down test environment.",
"name": "tearDown",
"signature": "def tearDown(self)"
}
] | 2 | null | Implement the Python class `TestCase` described below.
Class description:
Test case base class for all unit tests.
Method signatures and docstrings:
- def setUp(self): Run before each test method to initialize test environment.
- def tearDown(self): Runs after each test method to tear down test environment. | Implement the Python class `TestCase` described below.
Class description:
Test case base class for all unit tests.
Method signatures and docstrings:
- def setUp(self): Run before each test method to initialize test environment.
- def tearDown(self): Runs after each test method to tear down test environment.
<|skelet... | 4ce169d5be1c3e8614e5e6f198d3593eb904b97d | <|skeleton|>
class TestCase:
"""Test case base class for all unit tests."""
def setUp(self):
"""Run before each test method to initialize test environment."""
<|body_0|>
def tearDown(self):
"""Runs after each test method to tear down test environment."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCase:
"""Test case base class for all unit tests."""
def setUp(self):
"""Run before each test method to initialize test environment."""
super(TestCase, self).setUp()
test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
try:
test_timeout = int(test_timeout)
... | the_stack_v2_python_sparse | hdcs_manager/source/hsm/hsm/test.py | xuechendi/HDCS | train | 1 |
e930e6ce5281096bb5732f966375276cc81468ad | [
"result = []\nself.accumulatePathSum(root, sum, [], result)\nreturn result",
"if not root:\n return\nsum = sum - root.val\ncur_path.append(root.val)\nif sum == 0 and root.left is None and (root.right is None):\n result.append(list(cur_path))\n return\nif root.left:\n self.accumulatePathSum(root.left, ... | <|body_start_0|>
result = []
self.accumulatePathSum(root, sum, [], result)
return result
<|end_body_0|>
<|body_start_1|>
if not root:
return
sum = sum - root.val
cur_path.append(root.val)
if sum == 0 and root.left is None and (root.right is None):
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
""":param root: TreeNode :param sum: integer :return: a list of lists of integers"""
<|body_0|>
def accumulatePathSum(self, root, sum, cur_path, result):
"""DFS Similar to previous path sum"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_023938 | 1,497 | permissive | [
{
"docstring": ":param root: TreeNode :param sum: integer :return: a list of lists of integers",
"name": "pathSum",
"signature": "def pathSum(self, root, sum)"
},
{
"docstring": "DFS Similar to previous path sum",
"name": "accumulatePathSum",
"signature": "def accumulatePathSum(self, roo... | 2 | stack_v2_sparse_classes_30k_train_011331 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): :param root: TreeNode :param sum: integer :return: a list of lists of integers
- def accumulatePathSum(self, root, sum, cur_path, result): DFS Simil... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): :param root: TreeNode :param sum: integer :return: a list of lists of integers
- def accumulatePathSum(self, root, sum, cur_path, result): DFS Simil... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
""":param root: TreeNode :param sum: integer :return: a list of lists of integers"""
<|body_0|>
def accumulatePathSum(self, root, sum, cur_path, result):
"""DFS Similar to previous path sum"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pathSum(self, root, sum):
""":param root: TreeNode :param sum: integer :return: a list of lists of integers"""
result = []
self.accumulatePathSum(root, sum, [], result)
return result
def accumulatePathSum(self, root, sum, cur_path, result):
"""DFS Sim... | the_stack_v2_python_sparse | 113 Path Sum II.py | Aminaba123/LeetCode | train | 1 | |
ff196a93c2dc14676a82c82f7aa16557fd6518ee | [
"keys = set()\nif request.can_read_body:\n try:\n wanted_keys = await request.json()\n except JSONDecodeError:\n response = {'status': 'failed', 'reason': 'JSON Decoding failed'}\n return web.json_response(data=response, status=400)\n if isinstance(wanted_keys, list):\n keys.upd... | <|body_start_0|>
keys = set()
if request.can_read_body:
try:
wanted_keys = await request.json()
except JSONDecodeError:
response = {'status': 'failed', 'reason': 'JSON Decoding failed'}
return web.json_response(data=response, status... | ConfigEndpoint | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-3.0-only",
"GPL-3.0-or-later",
"LGPL-2.1-or-later",
"GPL-1.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigEndpoint:
async def get(self, request) -> web.Response:
"""Get complete ledfx config. You may ask for a specific key/keys in the request body eg. "audio" will return audio config eg. ["audio", "melbanks"] will return audio and melbanks config"""
<|body_0|>
async def de... | stack_v2_sparse_classes_36k_train_023939 | 7,480 | permissive | [
{
"docstring": "Get complete ledfx config. You may ask for a specific key/keys in the request body eg. \"audio\" will return audio config eg. [\"audio\", \"melbanks\"] will return audio and melbanks config",
"name": "get",
"signature": "async def get(self, request) -> web.Response"
},
{
"docstri... | 4 | null | Implement the Python class `ConfigEndpoint` described below.
Class description:
Implement the ConfigEndpoint class.
Method signatures and docstrings:
- async def get(self, request) -> web.Response: Get complete ledfx config. You may ask for a specific key/keys in the request body eg. "audio" will return audio config ... | Implement the Python class `ConfigEndpoint` described below.
Class description:
Implement the ConfigEndpoint class.
Method signatures and docstrings:
- async def get(self, request) -> web.Response: Get complete ledfx config. You may ask for a specific key/keys in the request body eg. "audio" will return audio config ... | 3146ba9e9d10a2d01cdd4cb15ea37fc0c7bd020f | <|skeleton|>
class ConfigEndpoint:
async def get(self, request) -> web.Response:
"""Get complete ledfx config. You may ask for a specific key/keys in the request body eg. "audio" will return audio config eg. ["audio", "melbanks"] will return audio and melbanks config"""
<|body_0|>
async def de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigEndpoint:
async def get(self, request) -> web.Response:
"""Get complete ledfx config. You may ask for a specific key/keys in the request body eg. "audio" will return audio config eg. ["audio", "melbanks"] will return audio and melbanks config"""
keys = set()
if request.can_read_b... | the_stack_v2_python_sparse | ledfx/api/config.py | THATDONFC/LedFx | train | 0 | |
619e841050b05e41f34952274311ffea92a5aebc | [
"freq = 0\nfor line in self.lines:\n freq += int(line)\nprint(f'Final freq: {freq}')",
"found = False\nfreq = 0\nfreqs_hit = {freq}\nwhile not found:\n for line in self.lines:\n freq += int(line)\n if freq in freqs_hit:\n found = True\n break\n freqs_hit.add(freq)\... | <|body_start_0|>
freq = 0
for line in self.lines:
freq += int(line)
print(f'Final freq: {freq}')
<|end_body_0|>
<|body_start_1|>
found = False
freq = 0
freqs_hit = {freq}
while not found:
for line in self.lines:
freq += int... | Day 1 challenges | Challenge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Challenge:
"""Day 1 challenges"""
def challenge1(self):
"""Day 1 challenge 1"""
<|body_0|>
def challenge2(self):
"""Day 1 challenge 2"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
freq = 0
for line in self.lines:
freq += in... | stack_v2_sparse_classes_36k_train_023940 | 726 | permissive | [
{
"docstring": "Day 1 challenge 1",
"name": "challenge1",
"signature": "def challenge1(self)"
},
{
"docstring": "Day 1 challenge 2",
"name": "challenge2",
"signature": "def challenge2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009000 | Implement the Python class `Challenge` described below.
Class description:
Day 1 challenges
Method signatures and docstrings:
- def challenge1(self): Day 1 challenge 1
- def challenge2(self): Day 1 challenge 2 | Implement the Python class `Challenge` described below.
Class description:
Day 1 challenges
Method signatures and docstrings:
- def challenge1(self): Day 1 challenge 1
- def challenge2(self): Day 1 challenge 2
<|skeleton|>
class Challenge:
"""Day 1 challenges"""
def challenge1(self):
"""Day 1 challe... | 6671ef8c16a837f697bb3fb91004d1bd892814ba | <|skeleton|>
class Challenge:
"""Day 1 challenges"""
def challenge1(self):
"""Day 1 challenge 1"""
<|body_0|>
def challenge2(self):
"""Day 1 challenge 2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Challenge:
"""Day 1 challenges"""
def challenge1(self):
"""Day 1 challenge 1"""
freq = 0
for line in self.lines:
freq += int(line)
print(f'Final freq: {freq}')
def challenge2(self):
"""Day 1 challenge 2"""
found = False
freq = 0
... | the_stack_v2_python_sparse | 2018/day1/challenge.py | ericgreveson/adventofcode | train | 0 |
5686a2065f0aaabf7d28fce95e3c3adf675fd5e9 | [
"card = Desk()\ncard = card.issue_cards(3)\nself.assertEqual(amount_task(card), 3, 'Неправильное количество в колоде')",
"card = {'П': ['7'], 'К': [], 'Б': [], 'Ч': []}\ncard1 = '7П'\nself.assertEqual(cart_in_desk(card, card1), True, 'Карта не в колоде')"
] | <|body_start_0|>
card = Desk()
card = card.issue_cards(3)
self.assertEqual(amount_task(card), 3, 'Неправильное количество в колоде')
<|end_body_0|>
<|body_start_1|>
card = {'П': ['7'], 'К': [], 'Б': [], 'Ч': []}
card1 = '7П'
self.assertEqual(cart_in_desk(card, card1), Tr... | создание класса тестирования | Test_Light | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_Light:
"""создание класса тестирования"""
def test_amount_desk(self):
"""тест на количество карт"""
<|body_0|>
def test_cart_desk(self):
"""тест на то, что карта в колоде"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
card = Desk()
... | stack_v2_sparse_classes_36k_train_023941 | 1,673 | permissive | [
{
"docstring": "тест на количество карт",
"name": "test_amount_desk",
"signature": "def test_amount_desk(self)"
},
{
"docstring": "тест на то, что карта в колоде",
"name": "test_cart_desk",
"signature": "def test_cart_desk(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009863 | Implement the Python class `Test_Light` described below.
Class description:
создание класса тестирования
Method signatures and docstrings:
- def test_amount_desk(self): тест на количество карт
- def test_cart_desk(self): тест на то, что карта в колоде | Implement the Python class `Test_Light` described below.
Class description:
создание класса тестирования
Method signatures and docstrings:
- def test_amount_desk(self): тест на количество карт
- def test_cart_desk(self): тест на то, что карта в колоде
<|skeleton|>
class Test_Light:
"""создание класса тестировани... | 7e4c7f84016f9a9c2b899990862f0cc8d8c85297 | <|skeleton|>
class Test_Light:
"""создание класса тестирования"""
def test_amount_desk(self):
"""тест на количество карт"""
<|body_0|>
def test_cart_desk(self):
"""тест на то, что карта в колоде"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_Light:
"""создание класса тестирования"""
def test_amount_desk(self):
"""тест на количество карт"""
card = Desk()
card = card.issue_cards(3)
self.assertEqual(amount_task(card), 3, 'Неправильное количество в колоде')
def test_cart_desk(self):
"""тест на то... | the_stack_v2_python_sparse | lesson_10/test_ultralight.py | windn19/Python_Developer | train | 2 |
19fd0ca77cd41a98e6a210043cfae33477396ccb | [
"super().__init__(device)\nself.cross_entropy = CrossEntropy(device, **crossentropy_params)\nself.T = T\nself.alpha = alpha\nself.teacher = self._create_teacher(teacher_model_name, teacher_model_params)",
"teacher = model_utils.get_model(teacher_model_name, teacher_model_params).to(self.device)\nprefix = os.path.... | <|body_start_0|>
super().__init__(device)
self.cross_entropy = CrossEntropy(device, **crossentropy_params)
self.T = T
self.alpha = alpha
self.teacher = self._create_teacher(teacher_model_name, teacher_model_params)
<|end_body_0|>
<|body_start_1|>
teacher = model_utils.ge... | Hinton KLD Loss accepting soft labels. Reference: Distilling the Knowledge in a Neural Network(https://arxiv.org/pdf/1503.02531.pdf) Attributes: T (float): Hinton loss param, temperature(>0). alpha (float): Hinton loss param, alpha(0~1). cross_entropy (CrossEntropy): cross entropy loss. teacher (nn.Module): teacher mod... | HintonKLD | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HintonKLD:
"""Hinton KLD Loss accepting soft labels. Reference: Distilling the Knowledge in a Neural Network(https://arxiv.org/pdf/1503.02531.pdf) Attributes: T (float): Hinton loss param, temperature(>0). alpha (float): Hinton loss param, alpha(0~1). cross_entropy (CrossEntropy): cross entropy l... | stack_v2_sparse_classes_36k_train_023942 | 7,808 | permissive | [
{
"docstring": "Initialize cross entropy loss.",
"name": "__init__",
"signature": "def __init__(self, device: torch.device, T: float, alpha: float, teacher_model_name: str, teacher_model_params: Dict[str, Any], crossentropy_params: Dict[str, Any]) -> None"
},
{
"docstring": "Create teacher netwo... | 4 | stack_v2_sparse_classes_30k_test_000805 | Implement the Python class `HintonKLD` described below.
Class description:
Hinton KLD Loss accepting soft labels. Reference: Distilling the Knowledge in a Neural Network(https://arxiv.org/pdf/1503.02531.pdf) Attributes: T (float): Hinton loss param, temperature(>0). alpha (float): Hinton loss param, alpha(0~1). cross_... | Implement the Python class `HintonKLD` described below.
Class description:
Hinton KLD Loss accepting soft labels. Reference: Distilling the Knowledge in a Neural Network(https://arxiv.org/pdf/1503.02531.pdf) Attributes: T (float): Hinton loss param, temperature(>0). alpha (float): Hinton loss param, alpha(0~1). cross_... | 88bcff70e93dd68058a5cf0dfeac119a57abc6de | <|skeleton|>
class HintonKLD:
"""Hinton KLD Loss accepting soft labels. Reference: Distilling the Knowledge in a Neural Network(https://arxiv.org/pdf/1503.02531.pdf) Attributes: T (float): Hinton loss param, temperature(>0). alpha (float): Hinton loss param, alpha(0~1). cross_entropy (CrossEntropy): cross entropy l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HintonKLD:
"""Hinton KLD Loss accepting soft labels. Reference: Distilling the Knowledge in a Neural Network(https://arxiv.org/pdf/1503.02531.pdf) Attributes: T (float): Hinton loss param, temperature(>0). alpha (float): Hinton loss param, alpha(0~1). cross_entropy (CrossEntropy): cross entropy loss. teacher ... | the_stack_v2_python_sparse | src/criterions.py | scott-mao/DenseDepth_Pruning | train | 1 |
da9db3325f7188be0893a669adc8e558f411835e | [
"super().setUp()\nself.client = Client()\nself.ping_url = reverse('status.service.celery.ping')",
"response = self.client.get(self.ping_url)\nassert response.status_code == 200\nresult_dict = json.loads(response.content.decode('utf-8'))\nassert result_dict['success']\nassert result_dict['value'] == 'pong'\nassert... | <|body_start_0|>
super().setUp()
self.client = Client()
self.ping_url = reverse('status.service.celery.ping')
<|end_body_0|>
<|body_start_1|>
response = self.client.get(self.ping_url)
assert response.status_code == 200
result_dict = json.loads(response.content.decode('ut... | Test that we can get a response from Celery | CeleryConfigTest | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CeleryConfigTest:
"""Test that we can get a response from Celery"""
def setUp(self):
"""Create a django test client"""
<|body_0|>
def test_ping(self):
"""Try to ping celery."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().setUp()
... | stack_v2_sparse_classes_36k_train_023943 | 1,342 | permissive | [
{
"docstring": "Create a django test client",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Try to ping celery.",
"name": "test_ping",
"signature": "def test_ping(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013601 | Implement the Python class `CeleryConfigTest` described below.
Class description:
Test that we can get a response from Celery
Method signatures and docstrings:
- def setUp(self): Create a django test client
- def test_ping(self): Try to ping celery. | Implement the Python class `CeleryConfigTest` described below.
Class description:
Test that we can get a response from Celery
Method signatures and docstrings:
- def setUp(self): Create a django test client
- def test_ping(self): Try to ping celery.
<|skeleton|>
class CeleryConfigTest:
"""Test that we can get a ... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class CeleryConfigTest:
"""Test that we can get a response from Celery"""
def setUp(self):
"""Create a django test client"""
<|body_0|>
def test_ping(self):
"""Try to ping celery."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CeleryConfigTest:
"""Test that we can get a response from Celery"""
def setUp(self):
"""Create a django test client"""
super().setUp()
self.client = Client()
self.ping_url = reverse('status.service.celery.ping')
def test_ping(self):
"""Try to ping celery."""
... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/service_status/test.py | luque/better-ways-of-thinking-about-software | train | 3 |
d3076f357c7ba8fa3d1d33199cbb74411a6e5590 | [
"assert isinstance(response, scrapy.http.response.html.HtmlResponse)\nURLS = ['https://www.charterboats-uk.co.uk/wales?page=1', 'https://www.charterboats-uk.co.uk/wales?page=2', 'https://www.charterboats-uk.co.uk/wales?page=3', 'https://www.charterboats-uk.co.uk/wales?page=4', 'https://www.charterboats-uk.co.uk/sco... | <|body_start_0|>
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
URLS = ['https://www.charterboats-uk.co.uk/wales?page=1', 'https://www.charterboats-uk.co.uk/wales?page=2', 'https://www.charterboats-uk.co.uk/wales?page=3', 'https://www.charterboats-uk.co.uk/wales?page=4', 'https://ww... | scrape all the text in on the boat details tab to write to ugc | CharterBoatUKBoatWalesScotlandTextSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CharterBoatUKBoatWalesScotlandTextSpider:
"""scrape all the text in on the boat details tab to write to ugc"""
def parse(self, response):
"""generate links to pages in a board"""
<|body_0|>
def crawl_boats(self, response):
"""each page with links to 10 boats deta... | stack_v2_sparse_classes_36k_train_023944 | 17,953 | no_license | [
{
"docstring": "generate links to pages in a board",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "each page with links to 10 boats details",
"name": "crawl_boats",
"signature": "def crawl_boats(self, response)"
},
{
"docstring": "crawl",
"name"... | 3 | stack_v2_sparse_classes_30k_train_003116 | Implement the Python class `CharterBoatUKBoatWalesScotlandTextSpider` described below.
Class description:
scrape all the text in on the boat details tab to write to ugc
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board
- def crawl_boats(self, response): each page with l... | Implement the Python class `CharterBoatUKBoatWalesScotlandTextSpider` described below.
Class description:
scrape all the text in on the boat details tab to write to ugc
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board
- def crawl_boats(self, response): each page with l... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class CharterBoatUKBoatWalesScotlandTextSpider:
"""scrape all the text in on the boat details tab to write to ugc"""
def parse(self, response):
"""generate links to pages in a board"""
<|body_0|>
def crawl_boats(self, response):
"""each page with links to 10 boats deta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CharterBoatUKBoatWalesScotlandTextSpider:
"""scrape all the text in on the boat details tab to write to ugc"""
def parse(self, response):
"""generate links to pages in a board"""
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
URLS = ['https://www.charterboats-... | the_stack_v2_python_sparse | imgscrape/spiders/charterboatuk.py | gmonkman/python | train | 0 |
458a9c1bcfbad838e32131bc43236e48ecb6fd87 | [
"expectation = {'bool': {'must': [{'query_string': {'query': 'polly'}}], 'must_not': [{'term': {u'loglevel.raw': 'AUDIT'}}]}}\npolyresource = PolyResource(native_name='polly')\nresult = polyresource.logs().to_dict()\nself.assertDictEqual(expectation, result['query'])\nexpectation = [{'@timestamp': {'order': 'desc'}... | <|body_start_0|>
expectation = {'bool': {'must': [{'query_string': {'query': 'polly'}}], 'must_not': [{'term': {u'loglevel.raw': 'AUDIT'}}]}}
polyresource = PolyResource(native_name='polly')
result = polyresource.logs().to_dict()
self.assertDictEqual(expectation, result['query'])
... | Test the PolyResourceModel. | PolyResourceModelTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PolyResourceModelTests:
"""Test the PolyResourceModel."""
def test_logs(self):
"""Test that the logs method returns an appropriate search object."""
<|body_0|>
def test_events(self):
"""test that the events method returns an appropriate search object."""
... | stack_v2_sparse_classes_36k_train_023945 | 22,971 | permissive | [
{
"docstring": "Test that the logs method returns an appropriate search object.",
"name": "test_logs",
"signature": "def test_logs(self)"
},
{
"docstring": "test that the events method returns an appropriate search object.",
"name": "test_events",
"signature": "def test_events(self)"
}... | 2 | stack_v2_sparse_classes_30k_train_015397 | Implement the Python class `PolyResourceModelTests` described below.
Class description:
Test the PolyResourceModel.
Method signatures and docstrings:
- def test_logs(self): Test that the logs method returns an appropriate search object.
- def test_events(self): test that the events method returns an appropriate searc... | Implement the Python class `PolyResourceModelTests` described below.
Class description:
Test the PolyResourceModel.
Method signatures and docstrings:
- def test_logs(self): Test that the logs method returns an appropriate search object.
- def test_events(self): test that the events method returns an appropriate searc... | 73d334a9f0df7c044c06989977a9a22dd2ff9b7a | <|skeleton|>
class PolyResourceModelTests:
"""Test the PolyResourceModel."""
def test_logs(self):
"""Test that the logs method returns an appropriate search object."""
<|body_0|>
def test_events(self):
"""test that the events method returns an appropriate search object."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PolyResourceModelTests:
"""Test the PolyResourceModel."""
def test_logs(self):
"""Test that the logs method returns an appropriate search object."""
expectation = {'bool': {'must': [{'query_string': {'query': 'polly'}}], 'must_not': [{'term': {u'loglevel.raw': 'AUDIT'}}]}}
polyres... | the_stack_v2_python_sparse | goldstone/core/tests.py | bhuvan-rk/goldstone-server | train | 0 |
3b3fb37436e3c9589741c0d12cdfd51ddd664c19 | [
"if not nums:\n return []\nres = []\ndict = Counter(nums)\nfor i in range(k):\n for key, value in dict.items():\n if value == max(dict.values()):\n res.append(key)\n dict.pop(key)\n break\nreturn res",
"if not nums:\n return []\nres = []\ndict = Counter(nums)\nfor ... | <|body_start_0|>
if not nums:
return []
res = []
dict = Counter(nums)
for i in range(k):
for key, value in dict.items():
if value == max(dict.values()):
res.append(key)
dict.pop(key)
break... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def topKFrequent2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
def topKFrequent3(self, nums, k):
... | stack_v2_sparse_classes_36k_train_023946 | 45,719 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "topKFrequent",
"signature": "def topKFrequent(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "topKFrequent2",
"signature": "def topKFrequent2(self, nums, k)"... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def topKFrequent2(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- d... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def topKFrequent2(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- d... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def topKFrequent2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
def topKFrequent3(self, nums, k):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
if not nums:
return []
res = []
dict = Counter(nums)
for i in range(k):
for key, value in dict.items():
if value == max(dict.val... | the_stack_v2_python_sparse | 347. Top K Frequent Elements/frequent.py | Macielyoung/LeetCode | train | 1 | |
c67758c8c1b703c11caf0955d82095fcaa4273bb | [
"if not root:\n return ''\nstack = []\nstack.append((0, root))\nfresult = []\nfresult.append(stack[:])\nmystr = []\nmystr.append('0' + '+' + str(root.val))\nwhile stack:\n result = []\n strstack = []\n while stack:\n i, tmp = stack.pop(0)\n left = (2 * i, tmp.left)\n right = (2 * i ... | <|body_start_0|>
if not root:
return ''
stack = []
stack.append((0, root))
fresult = []
fresult.append(stack[:])
mystr = []
mystr.append('0' + '+' + str(root.val))
while stack:
result = []
strstack = []
while... | Codec1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec1:
def serialize(self, root):
"""Encodes a tree to a single string. BFS :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_train_023947 | 4,836 | no_license | [
{
"docstring": "Encodes a tree to a single string. BFS :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 deseri... | 2 | null | Implement the Python class `Codec1` described below.
Class description:
Implement the Codec1 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. BFS :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :... | Implement the Python class `Codec1` described below.
Class description:
Implement the Codec1 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. BFS :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :... | 690adf05774a1c500d6c9160223dab7bcc38ccc1 | <|skeleton|>
class Codec1:
def serialize(self, root):
"""Encodes a tree to a single string. BFS :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 Codec1:
def serialize(self, root):
"""Encodes a tree to a single string. BFS :type root: TreeNode :rtype: str"""
if not root:
return ''
stack = []
stack.append((0, root))
fresult = []
fresult.append(stack[:])
mystr = []
mystr.append('... | the_stack_v2_python_sparse | 297. Serialize and Deserialize Binary Tree.py | supersj/LeetCode | train | 2 | |
bf9bb0a3dd0ac9795ffddc691e796e1291b54b0d | [
"super().__init__()\nself.n_tasks = n_tasks\nn = torch.tensor(n_tasks)\nself.MAX_ITER = max_iter\nSTOP_CRIT = torch.tensor(stop_crit)\ngrammian = torch.empty((n_tasks, n_tasks), dtype=torch.float32)\nsol = torch.empty((n_tasks,), dtype=torch.float32)\nnew_sol = torch.empty((n_tasks,), dtype=torch.float32)\nself.reg... | <|body_start_0|>
super().__init__()
self.n_tasks = n_tasks
n = torch.tensor(n_tasks)
self.MAX_ITER = max_iter
STOP_CRIT = torch.tensor(stop_crit)
grammian = torch.empty((n_tasks, n_tasks), dtype=torch.float32)
sol = torch.empty((n_tasks,), dtype=torch.float32)
... | Wrapper over series of algorithms for solving min-norm tasks. | MinNormSolverFW | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinNormSolverFW:
"""Wrapper over series of algorithms for solving min-norm tasks."""
def __init__(self, n_tasks, max_iter=250, stop_crit=1e-06):
"""Stuffs we don't want to re-define too much times"""
<|body_0|>
def line_solver(self, v1v1, v1v2, v2v2):
"""Analytic... | stack_v2_sparse_classes_36k_train_023948 | 39,694 | no_license | [
{
"docstring": "Stuffs we don't want to re-define too much times",
"name": "__init__",
"signature": "def __init__(self, n_tasks, max_iter=250, stop_crit=1e-06)"
},
{
"docstring": "Analytical solution for the min-norm problem",
"name": "line_solver",
"signature": "def line_solver(self, v1... | 3 | null | Implement the Python class `MinNormSolverFW` described below.
Class description:
Wrapper over series of algorithms for solving min-norm tasks.
Method signatures and docstrings:
- def __init__(self, n_tasks, max_iter=250, stop_crit=1e-06): Stuffs we don't want to re-define too much times
- def line_solver(self, v1v1, ... | Implement the Python class `MinNormSolverFW` described below.
Class description:
Wrapper over series of algorithms for solving min-norm tasks.
Method signatures and docstrings:
- def __init__(self, n_tasks, max_iter=250, stop_crit=1e-06): Stuffs we don't want to re-define too much times
- def line_solver(self, v1v1, ... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class MinNormSolverFW:
"""Wrapper over series of algorithms for solving min-norm tasks."""
def __init__(self, n_tasks, max_iter=250, stop_crit=1e-06):
"""Stuffs we don't want to re-define too much times"""
<|body_0|>
def line_solver(self, v1v1, v1v2, v2v2):
"""Analytic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MinNormSolverFW:
"""Wrapper over series of algorithms for solving min-norm tasks."""
def __init__(self, n_tasks, max_iter=250, stop_crit=1e-06):
"""Stuffs we don't want to re-define too much times"""
super().__init__()
self.n_tasks = n_tasks
n = torch.tensor(n_tasks)
... | the_stack_v2_python_sparse | generated/test_hav4ik_Hydra.py | jansel/pytorch-jit-paritybench | train | 35 |
19c9bcf19d67e868f2b5c68808f5f8201bfd4dc7 | [
"try:\n return (int(key[0] // 16), int(key[1] // 16))\nexcept ValueError:\n return KeyError(\"Key %s isn't usable here!\" % repr(key))",
"minx, innerx = divmod(key[0], 16)\nminz, innerz = divmod(key[1], 16)\nminx = int(minx)\nminz = int(minz)\nmaxx = minx + 1\nmaxz = minz + 1\nif innerx <= radius:\n minx... | <|body_start_0|>
try:
return (int(key[0] // 16), int(key[1] // 16))
except ValueError:
return KeyError("Key %s isn't usable here!" % repr(key))
<|end_body_0|>
<|body_start_1|>
minx, innerx = divmod(key[0], 16)
minz, innerz = divmod(key[1], 16)
minx = int(... | Class for tracking blocks in the XZ-plane. | Block2DSpatialDict | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Block2DSpatialDict:
"""Class for tracking blocks in the XZ-plane."""
def key_for_bucket(self, key):
"""Partition keys into chunk-sized buckets."""
<|body_0|>
def keys_near(self, key, radius):
"""Get all bucket keys "near" this key. This method may return a genera... | stack_v2_sparse_classes_36k_train_023949 | 5,213 | permissive | [
{
"docstring": "Partition keys into chunk-sized buckets.",
"name": "key_for_bucket",
"signature": "def key_for_bucket(self, key)"
},
{
"docstring": "Get all bucket keys \"near\" this key. This method may return a generator.",
"name": "keys_near",
"signature": "def keys_near(self, key, ra... | 2 | stack_v2_sparse_classes_30k_train_011055 | Implement the Python class `Block2DSpatialDict` described below.
Class description:
Class for tracking blocks in the XZ-plane.
Method signatures and docstrings:
- def key_for_bucket(self, key): Partition keys into chunk-sized buckets.
- def keys_near(self, key, radius): Get all bucket keys "near" this key. This metho... | Implement the Python class `Block2DSpatialDict` described below.
Class description:
Class for tracking blocks in the XZ-plane.
Method signatures and docstrings:
- def key_for_bucket(self, key): Partition keys into chunk-sized buckets.
- def keys_near(self, key, radius): Get all bucket keys "near" this key. This metho... | 7be5d792871a8447499911fa1502c6a7c1437dc3 | <|skeleton|>
class Block2DSpatialDict:
"""Class for tracking blocks in the XZ-plane."""
def key_for_bucket(self, key):
"""Partition keys into chunk-sized buckets."""
<|body_0|>
def keys_near(self, key, radius):
"""Get all bucket keys "near" this key. This method may return a genera... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Block2DSpatialDict:
"""Class for tracking blocks in the XZ-plane."""
def key_for_bucket(self, key):
"""Partition keys into chunk-sized buckets."""
try:
return (int(key[0] // 16), int(key[1] // 16))
except ValueError:
return KeyError("Key %s isn't usable her... | the_stack_v2_python_sparse | bravo/utilities/spatial.py | CyberFlameGO/bravo | train | 0 |
4b612ccddcca123d374e51540159ac2215f18f3c | [
"current_identity = import_user()\ncontainers = []\nfor c in lxc.list_containers():\n container = Container.query.filter_by(name=c).first()\n if container.id in current_identity.containers or current_identity.admin:\n infos = lwp.ct_infos(c)\n container_json = container.__jsonapi__()\n co... | <|body_start_0|>
current_identity = import_user()
containers = []
for c in lxc.list_containers():
container = Container.query.filter_by(name=c).first()
if container.id in current_identity.containers or current_identity.admin:
infos = lwp.ct_infos(c)
... | ContainersList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContainersList:
def get(self):
"""Get containers list"""
<|body_0|>
def post(self):
"""Create container"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
current_identity = import_user()
containers = []
for c in lxc.list_containers():
... | stack_v2_sparse_classes_36k_train_023950 | 46,738 | permissive | [
{
"docstring": "Get containers list",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create container",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001281 | Implement the Python class `ContainersList` described below.
Class description:
Implement the ContainersList class.
Method signatures and docstrings:
- def get(self): Get containers list
- def post(self): Create container | Implement the Python class `ContainersList` described below.
Class description:
Implement the ContainersList class.
Method signatures and docstrings:
- def get(self): Get containers list
- def post(self): Create container
<|skeleton|>
class ContainersList:
def get(self):
"""Get containers list"""
... | 3439a2dd0bd527c5d604801fec3a5aac904a72e2 | <|skeleton|>
class ContainersList:
def get(self):
"""Get containers list"""
<|body_0|>
def post(self):
"""Create container"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContainersList:
def get(self):
"""Get containers list"""
current_identity = import_user()
containers = []
for c in lxc.list_containers():
container = Container.query.filter_by(name=c).first()
if container.id in current_identity.containers or current_iden... | the_stack_v2_python_sparse | app/views.py | taidos/lxc-rest | train | 0 | |
22a60725b00e3dcdf96c58fae81969a0508687f2 | [
"self.path_connectomist = path_connectomist\nself.environment = os.environ\ncmd = '%s --help' % self.path_connectomist\nprocess = subprocess.Popen(cmd, shell=True, env=self.environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nself.stdout, self.stderr = process.communicate()\nself.exitcode = process.returnc... | <|body_start_0|>
self.path_connectomist = path_connectomist
self.environment = os.environ
cmd = '%s --help' % self.path_connectomist
process = subprocess.Popen(cmd, shell=True, env=self.environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.stdout, self.stderr = proces... | Parent class for the wrapping of Connectomist functions. | ConnectomistWrapper | [
"LicenseRef-scancode-cecill-b-en"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectomistWrapper:
"""Parent class for the wrapping of Connectomist functions."""
def __init__(self, path_connectomist='/i2bm/local/Ubuntu-14.04-x86_64/ptk/bin/connectomist'):
"""Initialize the ConnectomistWrapper class by setting properly the environment. Parameters ---------- pat... | stack_v2_sparse_classes_36k_train_023951 | 8,020 | permissive | [
{
"docstring": "Initialize the ConnectomistWrapper class by setting properly the environment. Parameters ---------- path_connectomist: str (optional) path to the Connectomist executable. Raises ------ ConnectomistConfigurationError: If Connectomist is not configured.",
"name": "__init__",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_017285 | Implement the Python class `ConnectomistWrapper` described below.
Class description:
Parent class for the wrapping of Connectomist functions.
Method signatures and docstrings:
- def __init__(self, path_connectomist='/i2bm/local/Ubuntu-14.04-x86_64/ptk/bin/connectomist'): Initialize the ConnectomistWrapper class by se... | Implement the Python class `ConnectomistWrapper` described below.
Class description:
Parent class for the wrapping of Connectomist functions.
Method signatures and docstrings:
- def __init__(self, path_connectomist='/i2bm/local/Ubuntu-14.04-x86_64/ptk/bin/connectomist'): Initialize the ConnectomistWrapper class by se... | 3105d2b1e4458c3be398391436be54bf59949a34 | <|skeleton|>
class ConnectomistWrapper:
"""Parent class for the wrapping of Connectomist functions."""
def __init__(self, path_connectomist='/i2bm/local/Ubuntu-14.04-x86_64/ptk/bin/connectomist'):
"""Initialize the ConnectomistWrapper class by setting properly the environment. Parameters ---------- pat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConnectomistWrapper:
"""Parent class for the wrapping of Connectomist functions."""
def __init__(self, path_connectomist='/i2bm/local/Ubuntu-14.04-x86_64/ptk/bin/connectomist'):
"""Initialize the ConnectomistWrapper class by setting properly the environment. Parameters ---------- path_connectomis... | the_stack_v2_python_sparse | clindmri/extensions/connectomist/wrappers.py | neurospin/caps-clindmri | train | 0 |
585b71a9e393a4c0e3a0024be7b922017e1685a3 | [
"def backTracking(res, tmp, candidates, target, j):\n if target < 0:\n return\n elif target == 0:\n t = tmp.copy()\n if t not in res:\n res.append(t)\n else:\n for i in range(j, len(candidates)):\n tmp.append(candidates[i])\n backTracking(res, tm... | <|body_start_0|>
def backTracking(res, tmp, candidates, target, j):
if target < 0:
return
elif target == 0:
t = tmp.copy()
if t not in res:
res.append(t)
else:
for i in range(j, len(candidates... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum2(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def combinationSum20(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""... | stack_v2_sparse_classes_36k_train_023952 | 1,658 | no_license | [
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]",
"name": "combinationSum2",
"signature": "def combinationSum2(self, candidates, target)"
},
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]",
"name": "combinationSum20... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum2(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]]
- def combinationSum20(self, candidates, target): :type candi... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum2(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]]
- def combinationSum20(self, candidates, target): :type candi... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def combinationSum2(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def combinationSum20(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSum2(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
def backTracking(res, tmp, candidates, target, j):
if target < 0:
return
elif target == 0:
t = tmp.copy()... | the_stack_v2_python_sparse | PythonCode/src/0040_Combination_Sum_II.py | oneyuan/CodeforFun | train | 0 | |
4b2eac6f553af3085ab970dad457b97b7cf495e4 | [
"self.include_extras = None\nself.include_all_extras = None\nself.extra_pkgs = []",
"include_extras = self.include_extras.split(',')\ntry:\n for name, pkgs in self.distribution.extras_require.items():\n if self.include_all_extras or name in include_extras:\n self.extra_pkgs.extend(pkgs)\nexce... | <|body_start_0|>
self.include_extras = None
self.include_all_extras = None
self.extra_pkgs = []
<|end_body_0|>
<|body_start_1|>
include_extras = self.include_extras.split(',')
try:
for name, pkgs in self.distribution.extras_require.items():
if self.in... | A custom command to list the dependencies of the current. | GenerateRequirementFile | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenerateRequirementFile:
"""A custom command to list the dependencies of the current."""
def initialize_options(self):
"""Initialize this command's options."""
<|body_0|>
def finalize_options(self):
"""Finalize this command's options."""
<|body_1|>
d... | stack_v2_sparse_classes_36k_train_023953 | 23,915 | permissive | [
{
"docstring": "Initialize this command's options.",
"name": "initialize_options",
"signature": "def initialize_options(self)"
},
{
"docstring": "Finalize this command's options.",
"name": "finalize_options",
"signature": "def finalize_options(self)"
},
{
"docstring": "Execute th... | 3 | null | Implement the Python class `GenerateRequirementFile` described below.
Class description:
A custom command to list the dependencies of the current.
Method signatures and docstrings:
- def initialize_options(self): Initialize this command's options.
- def finalize_options(self): Finalize this command's options.
- def r... | Implement the Python class `GenerateRequirementFile` described below.
Class description:
A custom command to list the dependencies of the current.
Method signatures and docstrings:
- def initialize_options(self): Initialize this command's options.
- def finalize_options(self): Finalize this command's options.
- def r... | 0c1c805fd5dfce465a8955ee3faf81037023a23e | <|skeleton|>
class GenerateRequirementFile:
"""A custom command to list the dependencies of the current."""
def initialize_options(self):
"""Initialize this command's options."""
<|body_0|>
def finalize_options(self):
"""Finalize this command's options."""
<|body_1|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenerateRequirementFile:
"""A custom command to list the dependencies of the current."""
def initialize_options(self):
"""Initialize this command's options."""
self.include_extras = None
self.include_all_extras = None
self.extra_pkgs = []
def finalize_options(self):
... | the_stack_v2_python_sparse | artifacts/old_dataset_versions/original_commits/ProjectQ/ProjectQ#408/after/setup.py | MattePalte/Bugs-Quantum-Computing-Platforms | train | 4 |
b1c7bd0c25b6456e76be4e4dd33a42ec2539d435 | [
"queryset = Lesson.objects.all()\nlesson = get_object_or_404(queryset, pk=pk)\nlesson.lesson_moderator.add(request.data.get('id'))\nqueryset2 = Profile.objects.all()\nuser = get_object_or_404(queryset2, pk=request.data.get('id'))\nlesson.save()\nreturn Response('Moderator {} has been successfully added to lesson {}... | <|body_start_0|>
queryset = Lesson.objects.all()
lesson = get_object_or_404(queryset, pk=pk)
lesson.lesson_moderator.add(request.data.get('id'))
queryset2 = Profile.objects.all()
user = get_object_or_404(queryset2, pk=request.data.get('id'))
lesson.save()
return R... | AdminViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminViewSet:
def add_moderator(self, request, pk):
"""Додавання модераторів(id в body) до предмету(id в url)"""
<|body_0|>
def remove_moderator(self, request, pk):
"""Видалення модератора(id в body) від предмету(id в url)"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_023954 | 8,171 | no_license | [
{
"docstring": "Додавання модераторів(id в body) до предмету(id в url)",
"name": "add_moderator",
"signature": "def add_moderator(self, request, pk)"
},
{
"docstring": "Видалення модератора(id в body) від предмету(id в url)",
"name": "remove_moderator",
"signature": "def remove_moderator... | 2 | stack_v2_sparse_classes_30k_train_013199 | Implement the Python class `AdminViewSet` described below.
Class description:
Implement the AdminViewSet class.
Method signatures and docstrings:
- def add_moderator(self, request, pk): Додавання модераторів(id в body) до предмету(id в url)
- def remove_moderator(self, request, pk): Видалення модератора(id в body) ві... | Implement the Python class `AdminViewSet` described below.
Class description:
Implement the AdminViewSet class.
Method signatures and docstrings:
- def add_moderator(self, request, pk): Додавання модераторів(id в body) до предмету(id в url)
- def remove_moderator(self, request, pk): Видалення модератора(id в body) ві... | c21c0df4974ff625f78cb967edb86ec18e2d062d | <|skeleton|>
class AdminViewSet:
def add_moderator(self, request, pk):
"""Додавання модераторів(id в body) до предмету(id в url)"""
<|body_0|>
def remove_moderator(self, request, pk):
"""Видалення модератора(id в body) від предмету(id в url)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdminViewSet:
def add_moderator(self, request, pk):
"""Додавання модераторів(id в body) до предмету(id в url)"""
queryset = Lesson.objects.all()
lesson = get_object_or_404(queryset, pk=pk)
lesson.lesson_moderator.add(request.data.get('id'))
queryset2 = Profile.objects.a... | the_stack_v2_python_sparse | OpenEduApi/Lessons/views.py | AkiroToshira/OpenEdu | train | 0 | |
12deb2bb1228e7def0e31cee67b300cdade87d1d | [
"self.input_dim = input_dim\nself.output_dim = 2 * input_dim\nself.n_iters = n_iters\nself.n_layers = n_layers",
"seqlen = 1\nh = L.fill_constant_batch_size_like(feat, [1, self.n_layers, self.input_dim], 'float32', 0)\nh = L.transpose(h, [1, 0, 2])\nc = h\nq_star = L.fill_constant_batch_size_like(feat, [1, seqlen... | <|body_start_0|>
self.input_dim = input_dim
self.output_dim = 2 * input_dim
self.n_iters = n_iters
self.n_layers = n_layers
<|end_body_0|>
<|body_start_1|>
seqlen = 1
h = L.fill_constant_batch_size_like(feat, [1, self.n_layers, self.input_dim], 'float32', 0)
h = ... | Implementation of set2set pooling operator. This is an implementation of the paper ORDER MATTERS: SEQUENCE TO SEQUENCE FOR SETS (https://arxiv.org/pdf/1511.06391.pdf). | Set2Set | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Set2Set:
"""Implementation of set2set pooling operator. This is an implementation of the paper ORDER MATTERS: SEQUENCE TO SEQUENCE FOR SETS (https://arxiv.org/pdf/1511.06391.pdf)."""
def __init__(self, input_dim, n_iters, n_layers):
"""Args: input_dim: hidden size of input data. n_it... | stack_v2_sparse_classes_36k_train_023955 | 3,004 | permissive | [
{
"docstring": "Args: input_dim: hidden size of input data. n_iters: number of set2set iterations. n_layers: number of lstm layers.",
"name": "__init__",
"signature": "def __init__(self, input_dim, n_iters, n_layers)"
},
{
"docstring": "Args: feat: input feature with shape [batch, n_edges, dim].... | 2 | stack_v2_sparse_classes_30k_train_004294 | Implement the Python class `Set2Set` described below.
Class description:
Implementation of set2set pooling operator. This is an implementation of the paper ORDER MATTERS: SEQUENCE TO SEQUENCE FOR SETS (https://arxiv.org/pdf/1511.06391.pdf).
Method signatures and docstrings:
- def __init__(self, input_dim, n_iters, n_... | Implement the Python class `Set2Set` described below.
Class description:
Implementation of set2set pooling operator. This is an implementation of the paper ORDER MATTERS: SEQUENCE TO SEQUENCE FOR SETS (https://arxiv.org/pdf/1511.06391.pdf).
Method signatures and docstrings:
- def __init__(self, input_dim, n_iters, n_... | 7a55649d46d7ad93de31eb9b3ebf71b82d1fcffb | <|skeleton|>
class Set2Set:
"""Implementation of set2set pooling operator. This is an implementation of the paper ORDER MATTERS: SEQUENCE TO SEQUENCE FOR SETS (https://arxiv.org/pdf/1511.06391.pdf)."""
def __init__(self, input_dim, n_iters, n_layers):
"""Args: input_dim: hidden size of input data. n_it... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Set2Set:
"""Implementation of set2set pooling operator. This is an implementation of the paper ORDER MATTERS: SEQUENCE TO SEQUENCE FOR SETS (https://arxiv.org/pdf/1511.06391.pdf)."""
def __init__(self, input_dim, n_iters, n_layers):
"""Args: input_dim: hidden size of input data. n_iters: number o... | the_stack_v2_python_sparse | legacy/pgl/layers/set2set.py | PaddlePaddle/PGL | train | 1,719 |
cc15c1862e71198d442b53395aa4b545857c9cbd | [
"self.env = env\nself.env_info = env_info\nself.hyper_params = hyper_params\nself.learner_cfg = learner_cfg\nself.worker_cfg = worker_cfg\nself.logger_cfg = logger_cfg\nself.comm_cfg = comm_cfg\nself.log_cfg = log_cfg\nself.is_test = is_test\nself.load_from = load_from\nself.is_render = is_render\nself.render_after... | <|body_start_0|>
self.env = env
self.env_info = env_info
self.hyper_params = hyper_params
self.learner_cfg = learner_cfg
self.worker_cfg = worker_cfg
self.logger_cfg = logger_cfg
self.comm_cfg = comm_cfg
self.log_cfg = log_cfg
self.is_test = is_tes... | General Ape-X architecture for distributed training. Attributes: rank (int): rank (ID) of worker env_info (ConfigDict): information about environment hyper_params (ConfigDict): algorithm hyperparameters learner_cfg (ConfigDict): configs for learner class worker_cfg (ConfigDict): configs for worker class logger_cfg (Con... | ApeX | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApeX:
"""General Ape-X architecture for distributed training. Attributes: rank (int): rank (ID) of worker env_info (ConfigDict): information about environment hyper_params (ConfigDict): algorithm hyperparameters learner_cfg (ConfigDict): configs for learner class worker_cfg (ConfigDict): configs ... | stack_v2_sparse_classes_36k_train_023956 | 7,394 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, env: gym.Env, env_info: ConfigDict, hyper_params: ConfigDict, learner_cfg: ConfigDict, worker_cfg: ConfigDict, logger_cfg: ConfigDict, comm_cfg: ConfigDict, log_cfg: ConfigDict, is_test: bool, load_from: str, is_render: b... | 4 | null | Implement the Python class `ApeX` described below.
Class description:
General Ape-X architecture for distributed training. Attributes: rank (int): rank (ID) of worker env_info (ConfigDict): information about environment hyper_params (ConfigDict): algorithm hyperparameters learner_cfg (ConfigDict): configs for learner ... | Implement the Python class `ApeX` described below.
Class description:
General Ape-X architecture for distributed training. Attributes: rank (int): rank (ID) of worker env_info (ConfigDict): information about environment hyper_params (ConfigDict): algorithm hyperparameters learner_cfg (ConfigDict): configs for learner ... | fdfac4e7056ee5a9d5b48b7b9653ce844a03ca22 | <|skeleton|>
class ApeX:
"""General Ape-X architecture for distributed training. Attributes: rank (int): rank (ID) of worker env_info (ConfigDict): information about environment hyper_params (ConfigDict): algorithm hyperparameters learner_cfg (ConfigDict): configs for learner class worker_cfg (ConfigDict): configs ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApeX:
"""General Ape-X architecture for distributed training. Attributes: rank (int): rank (ID) of worker env_info (ConfigDict): information about environment hyper_params (ConfigDict): algorithm hyperparameters learner_cfg (ConfigDict): configs for learner class worker_cfg (ConfigDict): configs for worker cl... | the_stack_v2_python_sparse | rl_algorithms/common/apex/architecture.py | medipixel/rl_algorithms | train | 525 |
b1e3ba9c6e949f0365103fde7b54af2f24adc2f1 | [
"readable_objs = self.get_images_async(coordinates, radius=radius, max_rms=max_rms, band=band, get_uvfits=get_uvfits, verbose=verbose, get_query_payload=get_query_payload, show_progress=show_progress)\nif get_query_payload:\n return readable_objs\nfilelist = [obj.get_fits() for obj in readable_objs]\nreturn file... | <|body_start_0|>
readable_objs = self.get_images_async(coordinates, radius=radius, max_rms=max_rms, band=band, get_uvfits=get_uvfits, verbose=verbose, get_query_payload=get_query_payload, show_progress=show_progress)
if get_query_payload:
return readable_objs
filelist = [obj.get_fits... | NvasClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NvasClass:
def get_images(self, coordinates, *, radius=0.25 * u.arcmin, max_rms=10000, band='all', get_uvfits=False, verbose=True, get_query_payload=False, show_progress=True):
"""Get an image around a target/ coordinates from the NVAS image archive. Parameters ---------- coordinates : s... | stack_v2_sparse_classes_36k_train_023957 | 9,862 | permissive | [
{
"docstring": "Get an image around a target/ coordinates from the NVAS image archive. Parameters ---------- coordinates : str or `astropy.coordinates` object The target around which to search. It may be specified as a string in which case it is resolved using online services or as the appropriate `astropy.coor... | 4 | stack_v2_sparse_classes_30k_train_015131 | Implement the Python class `NvasClass` described below.
Class description:
Implement the NvasClass class.
Method signatures and docstrings:
- def get_images(self, coordinates, *, radius=0.25 * u.arcmin, max_rms=10000, band='all', get_uvfits=False, verbose=True, get_query_payload=False, show_progress=True): Get an ima... | Implement the Python class `NvasClass` described below.
Class description:
Implement the NvasClass class.
Method signatures and docstrings:
- def get_images(self, coordinates, *, radius=0.25 * u.arcmin, max_rms=10000, band='all', get_uvfits=False, verbose=True, get_query_payload=False, show_progress=True): Get an ima... | 51316d7417d7daf01a8b29d1df99037b9227c2bc | <|skeleton|>
class NvasClass:
def get_images(self, coordinates, *, radius=0.25 * u.arcmin, max_rms=10000, band='all', get_uvfits=False, verbose=True, get_query_payload=False, show_progress=True):
"""Get an image around a target/ coordinates from the NVAS image archive. Parameters ---------- coordinates : s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NvasClass:
def get_images(self, coordinates, *, radius=0.25 * u.arcmin, max_rms=10000, band='all', get_uvfits=False, verbose=True, get_query_payload=False, show_progress=True):
"""Get an image around a target/ coordinates from the NVAS image archive. Parameters ---------- coordinates : str or `astropy... | the_stack_v2_python_sparse | astroquery/nvas/core.py | astropy/astroquery | train | 636 | |
c5f8242ca7ae688e8dc295cf6bd41919a0a38745 | [
"self.found = found\nself.displaying = displaying\nself.more_available = more_available\nself.from_date = from_date\nself.to_date = to_date\nself.sort = sort\nself.transactions = transactions\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nfound = dictionary.get('fo... | <|body_start_0|>
self.found = found
self.displaying = displaying
self.more_available = more_available
self.from_date = from_date
self.to_date = to_date
self.sort = sort
self.transactions = transactions
self.additional_properties = additional_properties
<|e... | Implementation of the 'Get Transactions Response' model. TODO: type model description here. Attributes: found (string): Total number of records matching search criteria displaying (string): Number of records in this response more_available (bool): true if this response does not contain the last record in the result set... | GetTransactionsResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetTransactionsResponse:
"""Implementation of the 'Get Transactions Response' model. TODO: type model description here. Attributes: found (string): Total number of records matching search criteria displaying (string): Number of records in this response more_available (bool): true if this response... | stack_v2_sparse_classes_36k_train_023958 | 3,647 | permissive | [
{
"docstring": "Constructor for the GetTransactionsResponse class",
"name": "__init__",
"signature": "def __init__(self, found=None, displaying=None, more_available=None, from_date=None, to_date=None, sort=None, transactions=None, additional_properties={})"
},
{
"docstring": "Creates an instance... | 2 | null | Implement the Python class `GetTransactionsResponse` described below.
Class description:
Implementation of the 'Get Transactions Response' model. TODO: type model description here. Attributes: found (string): Total number of records matching search criteria displaying (string): Number of records in this response more_... | Implement the Python class `GetTransactionsResponse` described below.
Class description:
Implementation of the 'Get Transactions Response' model. TODO: type model description here. Attributes: found (string): Total number of records matching search criteria displaying (string): Number of records in this response more_... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class GetTransactionsResponse:
"""Implementation of the 'Get Transactions Response' model. TODO: type model description here. Attributes: found (string): Total number of records matching search criteria displaying (string): Number of records in this response more_available (bool): true if this response... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetTransactionsResponse:
"""Implementation of the 'Get Transactions Response' model. TODO: type model description here. Attributes: found (string): Total number of records matching search criteria displaying (string): Number of records in this response more_available (bool): true if this response does not con... | the_stack_v2_python_sparse | finicityapi/models/get_transactions_response.py | monarchmoney/finicity-python | train | 0 |
f89139c2774cece69f0e7269000d6edd245210ef | [
"tests = [((8, 8), 1, [(8, 8)]), ((8, 8), 2, [(8, 8), (4, 4)]), ((8, 8), 3, [(8, 8), (4, 4), (2, 2)]), ((8, 8), 4, [(8, 8), (4, 4), (2, 2), (1, 1)])]\nfor i, ((width, height), levels, want_layers) in enumerate(tests):\n image = Image()\n image.create(width, height)\n pyramid = Pyramid(image, levels)\n h... | <|body_start_0|>
tests = [((8, 8), 1, [(8, 8)]), ((8, 8), 2, [(8, 8), (4, 4)]), ((8, 8), 3, [(8, 8), (4, 4), (2, 2)]), ((8, 8), 4, [(8, 8), (4, 4), (2, 2), (1, 1)])]
for i, ((width, height), levels, want_layers) in enumerate(tests):
image = Image()
image.create(width, height)
... | Tests for the Pyramid class. | TestPyramid | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPyramid:
"""Tests for the Pyramid class."""
def test_init(self):
"""Tests the Pyramid.__init__() function."""
<|body_0|>
def test_reconstruct(self):
"""Tests the Pyramid.reconstruct() function."""
<|body_1|>
def test_items(self):
"""Tests... | stack_v2_sparse_classes_36k_train_023959 | 2,570 | permissive | [
{
"docstring": "Tests the Pyramid.__init__() function.",
"name": "test_init",
"signature": "def test_init(self)"
},
{
"docstring": "Tests the Pyramid.reconstruct() function.",
"name": "test_reconstruct",
"signature": "def test_reconstruct(self)"
},
{
"docstring": "Tests the Pyram... | 3 | stack_v2_sparse_classes_30k_train_018866 | Implement the Python class `TestPyramid` described below.
Class description:
Tests for the Pyramid class.
Method signatures and docstrings:
- def test_init(self): Tests the Pyramid.__init__() function.
- def test_reconstruct(self): Tests the Pyramid.reconstruct() function.
- def test_items(self): Tests the Pyramid.__... | Implement the Python class `TestPyramid` described below.
Class description:
Tests for the Pyramid class.
Method signatures and docstrings:
- def test_init(self): Tests the Pyramid.__init__() function.
- def test_reconstruct(self): Tests the Pyramid.reconstruct() function.
- def test_items(self): Tests the Pyramid.__... | 7e7282698befd53383cbd6566039340babb0a289 | <|skeleton|>
class TestPyramid:
"""Tests for the Pyramid class."""
def test_init(self):
"""Tests the Pyramid.__init__() function."""
<|body_0|>
def test_reconstruct(self):
"""Tests the Pyramid.reconstruct() function."""
<|body_1|>
def test_items(self):
"""Tests... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPyramid:
"""Tests for the Pyramid class."""
def test_init(self):
"""Tests the Pyramid.__init__() function."""
tests = [((8, 8), 1, [(8, 8)]), ((8, 8), 2, [(8, 8), (4, 4)]), ((8, 8), 3, [(8, 8), (4, 4), (2, 2)]), ((8, 8), 4, [(8, 8), (4, 4), (2, 2), (1, 1)])]
for i, ((width, he... | the_stack_v2_python_sparse | sandbox/image/pyramid_test.py | Mandrenkov/SVBRDF-Texture-Synthesis | train | 3 |
c8ecb49d1a179e181737268c08ff51f9bdf5f29e | [
"self.res = []\nself.pathSumRecur(root, sum, [])\nreturn self.res",
"if root == None:\n return\nelif root.left == None and root.right == None and (root.val == sum):\n self.res.append(path + [root.val])\nelse:\n sum -= root.val\n self.pathSumRecur(root.left, sum, path + [root.val])\n self.pathSumRec... | <|body_start_0|>
self.res = []
self.pathSumRecur(root, sum, [])
return self.res
<|end_body_0|>
<|body_start_1|>
if root == None:
return
elif root.left == None and root.right == None and (root.val == sum):
self.res.append(path + [root.val])
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: List[List[int]]"""
<|body_0|>
def pathSumRecur(self, root, sum, path):
""":type root: TreeNode :type sum: int :type path: List[int] :rtype: void"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_023960 | 1,955 | no_license | [
{
"docstring": ":type root: TreeNode :type sum: int :rtype: List[List[int]]",
"name": "pathSum",
"signature": "def pathSum(self, root, sum)"
},
{
"docstring": ":type root: TreeNode :type sum: int :type path: List[int] :rtype: void",
"name": "pathSumRecur",
"signature": "def pathSumRecur(... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: List[List[int]]
- def pathSumRecur(self, root, sum, path): :type root: TreeNode :type sum: int :type pat... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: List[List[int]]
- def pathSumRecur(self, root, sum, path): :type root: TreeNode :type sum: int :type pat... | 8cda0518440488992d7e2c70cb8555ec7b34083f | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: List[List[int]]"""
<|body_0|>
def pathSumRecur(self, root, sum, path):
""":type root: TreeNode :type sum: int :type path: List[int] :rtype: void"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: List[List[int]]"""
self.res = []
self.pathSumRecur(root, sum, [])
return self.res
def pathSumRecur(self, root, sum, path):
""":type root: TreeNode :type sum: int :type path: List... | the_stack_v2_python_sparse | 113/main.py | szhongren/leetcode | train | 0 | |
5945c55c1e4223f6fbccbde9fc7b8c364968db77 | [
"raw_dict = self.raw_statistics_dict()\nparsed_dict = {}\nfields = (('hit_count', 'hit_count', '^(\\\\d+)$', int), ('miss_count', 'miss_count', '^(\\\\d+)$', int), ('hit_ratio', 'hit_ratio', '^(\\\\d+)%$', int), ('item_count', 'item_count', '^(\\\\d+) item\\\\(s\\\\)$', int), ('total_cache_size_bytes', 'total_cache... | <|body_start_0|>
raw_dict = self.raw_statistics_dict()
parsed_dict = {}
fields = (('hit_count', 'hit_count', '^(\\d+)$', int), ('miss_count', 'miss_count', '^(\\d+)$', int), ('hit_ratio', 'hit_ratio', '^(\\d+)%$', int), ('item_count', 'item_count', '^(\\d+) item\\(s\\)$', int), ('total_cache_siz... | An API for the contents of /memcache as structured data. | Memcache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Memcache:
"""An API for the contents of /memcache as structured data."""
def statistics_dict(self):
"""A parsed representation of memcache statistics. Raises ValueError if unable to parse elements of the raw summary. For example if input like '1024 byte(s)' later changes to '1 kiloby... | stack_v2_sparse_classes_36k_train_023961 | 12,694 | no_license | [
{
"docstring": "A parsed representation of memcache statistics. Raises ValueError if unable to parse elements of the raw summary. For example if input like '1024 byte(s)' later changes to '1 kilobyte(s)' a ValueError will be raised. Returns: A dict with fields like this: {'hit_count': 12345, 'miss_count': 123, ... | 2 | stack_v2_sparse_classes_30k_train_000584 | Implement the Python class `Memcache` described below.
Class description:
An API for the contents of /memcache as structured data.
Method signatures and docstrings:
- def statistics_dict(self): A parsed representation of memcache statistics. Raises ValueError if unable to parse elements of the raw summary. For exampl... | Implement the Python class `Memcache` described below.
Class description:
An API for the contents of /memcache as structured data.
Method signatures and docstrings:
- def statistics_dict(self): A parsed representation of memcache statistics. Raises ValueError if unable to parse elements of the raw summary. For exampl... | d6546e4fa01902a6a3675c7b423d0ba75cf20b29 | <|skeleton|>
class Memcache:
"""An API for the contents of /memcache as structured data."""
def statistics_dict(self):
"""A parsed representation of memcache statistics. Raises ValueError if unable to parse elements of the raw summary. For example if input like '1024 byte(s)' later changes to '1 kiloby... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Memcache:
"""An API for the contents of /memcache as structured data."""
def statistics_dict(self):
"""A parsed representation of memcache statistics. Raises ValueError if unable to parse elements of the raw summary. For example if input like '1024 byte(s)' later changes to '1 kilobyte(s)' a Valu... | the_stack_v2_python_sparse | src/gae_dashboard/parsers.py | prantik/analytics | train | 1 |
99268751a52b09775f7f6370fca356b6c1d04d81 | [
"self.input = [1, 2, 3]\nself.output = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]\nreturn (self.input, self.output)",
"input_list, correct_output = self.SetUp()\noutput = powerset(input_list)\nself.assertEqual(output, correct_output)",
"input_list, correct_output = self.SetUp()\noutput = powerset_re... | <|body_start_0|>
self.input = [1, 2, 3]
self.output = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
return (self.input, self.output)
<|end_body_0|>
<|body_start_1|>
input_list, correct_output = self.SetUp()
output = powerset(input_list)
self.assertEqual(output, ... | Class with unittests for Powerset.py | test_Powerset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_Powerset:
"""Class with unittests for Powerset.py"""
def SetUp(self):
"""Set Up input list."""
<|body_0|>
def test_Iterative_method(self):
"""Checks if output is correct."""
<|body_1|>
def test_Recurency_method(self):
"""Checks if output... | stack_v2_sparse_classes_36k_train_023962 | 1,176 | no_license | [
{
"docstring": "Set Up input list.",
"name": "SetUp",
"signature": "def SetUp(self)"
},
{
"docstring": "Checks if output is correct.",
"name": "test_Iterative_method",
"signature": "def test_Iterative_method(self)"
},
{
"docstring": "Checks if output is correct.",
"name": "te... | 3 | null | Implement the Python class `test_Powerset` described below.
Class description:
Class with unittests for Powerset.py
Method signatures and docstrings:
- def SetUp(self): Set Up input list.
- def test_Iterative_method(self): Checks if output is correct.
- def test_Recurency_method(self): Checks if output is correct. | Implement the Python class `test_Powerset` described below.
Class description:
Class with unittests for Powerset.py
Method signatures and docstrings:
- def SetUp(self): Set Up input list.
- def test_Iterative_method(self): Checks if output is correct.
- def test_Recurency_method(self): Checks if output is correct.
<... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_Powerset:
"""Class with unittests for Powerset.py"""
def SetUp(self):
"""Set Up input list."""
<|body_0|>
def test_Iterative_method(self):
"""Checks if output is correct."""
<|body_1|>
def test_Recurency_method(self):
"""Checks if output... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_Powerset:
"""Class with unittests for Powerset.py"""
def SetUp(self):
"""Set Up input list."""
self.input = [1, 2, 3]
self.output = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
return (self.input, self.output)
def test_Iterative_method(self):
""... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Medium/Powerset/test_Powerset.py | JakubKazimierski/PythonPortfolio | train | 9 |
e6749f90b63b7c0f4bd20ac5bef3e2d3abf781fe | [
"self.version = version\nself.inputs = [] if inputs is None else inputs\nself.outputs = [] if outputs is None else outputs\nself.signatures = [] if signatures is None else signatures",
"res = self.version.to_bytes(1, 'big')\nres += len(self.inputs).to_bytes(1)\nfor address, origin in self.inputs:\n res += addr... | <|body_start_0|>
self.version = version
self.inputs = [] if inputs is None else inputs
self.outputs = [] if outputs is None else outputs
self.signatures = [] if signatures is None else signatures
<|end_body_0|>
<|body_start_1|>
res = self.version.to_bytes(1, 'big')
res +... | Tx | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tx:
def __init__(self, version=0, inputs=None, outputs=None, signatures=None):
"""Initialise a transaction object. :param version: int :param inputs: Input list :param outputs: Output list :param signatures: Signature list"""
<|body_0|>
def body(self):
"""Raw represe... | stack_v2_sparse_classes_36k_train_023963 | 12,435 | permissive | [
{
"docstring": "Initialise a transaction object. :param version: int :param inputs: Input list :param outputs: Output list :param signatures: Signature list",
"name": "__init__",
"signature": "def __init__(self, version=0, inputs=None, outputs=None, signatures=None)"
},
{
"docstring": "Raw repre... | 3 | stack_v2_sparse_classes_30k_train_000696 | Implement the Python class `Tx` described below.
Class description:
Implement the Tx class.
Method signatures and docstrings:
- def __init__(self, version=0, inputs=None, outputs=None, signatures=None): Initialise a transaction object. :param version: int :param inputs: Input list :param outputs: Output list :param s... | Implement the Python class `Tx` described below.
Class description:
Implement the Tx class.
Method signatures and docstrings:
- def __init__(self, version=0, inputs=None, outputs=None, signatures=None): Initialise a transaction object. :param version: int :param inputs: Input list :param outputs: Output list :param s... | d48f1013d4f4149ce3c53996ff966074ae45dc89 | <|skeleton|>
class Tx:
def __init__(self, version=0, inputs=None, outputs=None, signatures=None):
"""Initialise a transaction object. :param version: int :param inputs: Input list :param outputs: Output list :param signatures: Signature list"""
<|body_0|>
def body(self):
"""Raw represe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tx:
def __init__(self, version=0, inputs=None, outputs=None, signatures=None):
"""Initialise a transaction object. :param version: int :param inputs: Input list :param outputs: Output list :param signatures: Signature list"""
self.version = version
self.inputs = [] if inputs is None el... | the_stack_v2_python_sparse | blockchain.py | busybox11/Discorn | train | 1 | |
ce90d42e0d2fc96e568a70e6811dccc86708ce46 | [
"self.Wz = np.random.normal(size=(i + h, h))\nself.Wr = np.random.normal(size=(i + h, h))\nself.Wh = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bz = np.zeros((1, h))\nself.bz = np.zeros((1, h))\nself.br = np.zeros((1, h))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))"... | <|body_start_0|>
self.Wz = np.random.normal(size=(i + h, h))
self.Wr = np.random.normal(size=(i + h, h))
self.Wh = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bz = np.zeros((1, h))
self.bz = np.zeros((1, h))
self.br = np.zeros((1... | Class that represents a gated recurrent unit | GRUCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRUCell:
"""Class that represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""class constructor i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs Creates the public instance attributes Wz, Wr, Wh, Wy, ... | stack_v2_sparse_classes_36k_train_023964 | 2,659 | no_license | [
{
"docstring": "class constructor i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs Creates the public instance attributes Wz, Wr, Wh, Wy, bz, br, bh, by that represent the weights and biases of the cell Wz and bz are for the update gate Wr an... | 2 | null | Implement the Python class `GRUCell` described below.
Class description:
Class that represents a gated recurrent unit
Method signatures and docstrings:
- def __init__(self, i, h, o): class constructor i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the output... | Implement the Python class `GRUCell` described below.
Class description:
Class that represents a gated recurrent unit
Method signatures and docstrings:
- def __init__(self, i, h, o): class constructor i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the output... | e8a98d85b3bfd5665cb04bec9ee8c3eb23d6bd58 | <|skeleton|>
class GRUCell:
"""Class that represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""class constructor i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs Creates the public instance attributes Wz, Wr, Wh, Wy, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GRUCell:
"""Class that represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""class constructor i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs Creates the public instance attributes Wz, Wr, Wh, Wy, bz, br, bh, b... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/2-gru_cell.py | AndrewMiranda/holbertonschool-machine_learning-1 | train | 0 |
73059f924a3cfc761f7f2860e15b2c4bffd8a2d4 | [
"super().__init__(*args, **kwargs)\nfor field in self.fields:\n if field in self.fields_not_required:\n self.fields[field].required = False\n else:\n self.fields[field].required = True\n if field in self.fields_hidden:\n self.fields[field].widget = forms.HiddenInput()",
"precio = sel... | <|body_start_0|>
super().__init__(*args, **kwargs)
for field in self.fields:
if field in self.fields_not_required:
self.fields[field].required = False
else:
self.fields[field].required = True
if field in self.fields_hidden:
... | Formulario base para crear y actualizar anuncios. Este Form no se instancia directamente NUNCA. type_anuncio es relativo, por eso esta en campos no requeridos. @ver: BaseAnuncioViviendaForm.clean_estado_inmueble Las subclases que se creen, el nombre ha de ser AnuncioXxxxxForm, donde Xxxxx la categoría del anuncio. @ver... | BaseAnuncioForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseAnuncioForm:
"""Formulario base para crear y actualizar anuncios. Este Form no se instancia directamente NUNCA. type_anuncio es relativo, por eso esta en campos no requeridos. @ver: BaseAnuncioViviendaForm.clean_estado_inmueble Las subclases que se creen, el nombre ha de ser AnuncioXxxxxForm,... | stack_v2_sparse_classes_36k_train_023965 | 8,207 | no_license | [
{
"docstring": "Recorre los campos del form y los añade como required, etc. Utiliza las propiedades: - fields_not_required: Campos que no serán obligatorios. - fields_hidden: Campos que serán ocultos.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "El ... | 4 | null | Implement the Python class `BaseAnuncioForm` described below.
Class description:
Formulario base para crear y actualizar anuncios. Este Form no se instancia directamente NUNCA. type_anuncio es relativo, por eso esta en campos no requeridos. @ver: BaseAnuncioViviendaForm.clean_estado_inmueble Las subclases que se creen... | Implement the Python class `BaseAnuncioForm` described below.
Class description:
Formulario base para crear y actualizar anuncios. Este Form no se instancia directamente NUNCA. type_anuncio es relativo, por eso esta en campos no requeridos. @ver: BaseAnuncioViviendaForm.clean_estado_inmueble Las subclases que se creen... | 44b8d2934105ccbf02ff6c20896aa8c2b1746eaa | <|skeleton|>
class BaseAnuncioForm:
"""Formulario base para crear y actualizar anuncios. Este Form no se instancia directamente NUNCA. type_anuncio es relativo, por eso esta en campos no requeridos. @ver: BaseAnuncioViviendaForm.clean_estado_inmueble Las subclases que se creen, el nombre ha de ser AnuncioXxxxxForm,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseAnuncioForm:
"""Formulario base para crear y actualizar anuncios. Este Form no se instancia directamente NUNCA. type_anuncio es relativo, por eso esta en campos no requeridos. @ver: BaseAnuncioViviendaForm.clean_estado_inmueble Las subclases que se creen, el nombre ha de ser AnuncioXxxxxForm, donde Xxxxx ... | the_stack_v2_python_sparse | src/apps/anuncios/forms.py | snicoper/ofervivienda | train | 1 |
0c6d9fb1858ee8ae2901adf5edecdd443aa4181b | [
"wavegan_state_dict = torch.load(checkpoint_path)\nself.wavegan = ParallelWaveGANGenerator(**generator_params)\nself.wavegan.load_state_dict(wavegan_state_dict['model']['generator'])\nself.wavegan.remove_weight_norm()\nself.wavegan.eval()\nself.wavegan_scaler = StandardScaler()\nself.wavegan_scaler.mean_ = read_hdf... | <|body_start_0|>
wavegan_state_dict = torch.load(checkpoint_path)
self.wavegan = ParallelWaveGANGenerator(**generator_params)
self.wavegan.load_state_dict(wavegan_state_dict['model']['generator'])
self.wavegan.remove_weight_norm()
self.wavegan.eval()
self.wavegan_scaler =... | Synthesizer with ParallelWaveGAN This code is implemented for used with this repo: https://github.com/kan-bayashi/ParallelWaveGAN | PWGSynthesizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PWGSynthesizer:
"""Synthesizer with ParallelWaveGAN This code is implemented for used with this repo: https://github.com/kan-bayashi/ParallelWaveGAN"""
def __init__(self, checkpoint_path, stats_file, generator_params):
"""Initialize PWG Args: checkpoint_path: Parallel WaveGAN checkpo... | stack_v2_sparse_classes_36k_train_023966 | 1,839 | no_license | [
{
"docstring": "Initialize PWG Args: checkpoint_path: Parallel WaveGAN checkpoint file stats_file: statistic file (h5)",
"name": "__init__",
"signature": "def __init__(self, checkpoint_path, stats_file, generator_params)"
},
{
"docstring": "Synthesize waveform Args: mel (ndarray): log Mel-spectr... | 2 | stack_v2_sparse_classes_30k_train_012545 | Implement the Python class `PWGSynthesizer` described below.
Class description:
Synthesizer with ParallelWaveGAN This code is implemented for used with this repo: https://github.com/kan-bayashi/ParallelWaveGAN
Method signatures and docstrings:
- def __init__(self, checkpoint_path, stats_file, generator_params): Initi... | Implement the Python class `PWGSynthesizer` described below.
Class description:
Synthesizer with ParallelWaveGAN This code is implemented for used with this repo: https://github.com/kan-bayashi/ParallelWaveGAN
Method signatures and docstrings:
- def __init__(self, checkpoint_path, stats_file, generator_params): Initi... | a3749810fae3f8b4f9ff052521eb3b15db01e13c | <|skeleton|>
class PWGSynthesizer:
"""Synthesizer with ParallelWaveGAN This code is implemented for used with this repo: https://github.com/kan-bayashi/ParallelWaveGAN"""
def __init__(self, checkpoint_path, stats_file, generator_params):
"""Initialize PWG Args: checkpoint_path: Parallel WaveGAN checkpo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PWGSynthesizer:
"""Synthesizer with ParallelWaveGAN This code is implemented for used with this repo: https://github.com/kan-bayashi/ParallelWaveGAN"""
def __init__(self, checkpoint_path, stats_file, generator_params):
"""Initialize PWG Args: checkpoint_path: Parallel WaveGAN checkpoint file stat... | the_stack_v2_python_sparse | utils/synthesizer.py | tuanvu92/VCC2020 | train | 22 |
76782d495114de1f1b7006976adf26f57a44c34d | [
"Bullet.__init__(self, lifetime, alpha, beta, x, y)\nself.r = r\nself.color = color",
"self.ax = -self.alpha * self.vx - self.beta * self.vx * abs(self.vx)\nself.ay = self.g - self.alpha * self.vy - self.beta * self.vy * abs(self.vy)\nself.vx += self.ax / self.fps\nself.vy += self.ay / self.fps\nif self.r < self.... | <|body_start_0|>
Bullet.__init__(self, lifetime, alpha, beta, x, y)
self.r = r
self.color = color
<|end_body_0|>
<|body_start_1|>
self.ax = -self.alpha * self.vx - self.beta * self.vx * abs(self.vx)
self.ay = self.g - self.alpha * self.vy - self.beta * self.vy * abs(self.vy)
... | Ball | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ball:
def __init__(self, color, lifetime=ball_lifetime, r=ball_r, x=0, y=0, alpha=ball_alpha, beta=ball_beta):
"""Конструктор класса мячей, которыми стреляет пушка :param color: цвет мяча :param lifetime: время жизни мяча в секундах :param alpha: параметр a в формуле силы трения F = -av ... | stack_v2_sparse_classes_36k_train_023967 | 9,588 | no_license | [
{
"docstring": "Конструктор класса мячей, которыми стреляет пушка :param color: цвет мяча :param lifetime: время жизни мяча в секундах :param alpha: параметр a в формуле силы трения F = -av - bv^2 :param beta: параметр b в формуле силы трения F = -av - bv^2 :param r: радиус мяча :param x: начальная координата ц... | 3 | stack_v2_sparse_classes_30k_train_019371 | Implement the Python class `Ball` described below.
Class description:
Implement the Ball class.
Method signatures and docstrings:
- def __init__(self, color, lifetime=ball_lifetime, r=ball_r, x=0, y=0, alpha=ball_alpha, beta=ball_beta): Конструктор класса мячей, которыми стреляет пушка :param color: цвет мяча :param ... | Implement the Python class `Ball` described below.
Class description:
Implement the Ball class.
Method signatures and docstrings:
- def __init__(self, color, lifetime=ball_lifetime, r=ball_r, x=0, y=0, alpha=ball_alpha, beta=ball_beta): Конструктор класса мячей, которыми стреляет пушка :param color: цвет мяча :param ... | 19d00443e953a487e762676d6682579a537f55f0 | <|skeleton|>
class Ball:
def __init__(self, color, lifetime=ball_lifetime, r=ball_r, x=0, y=0, alpha=ball_alpha, beta=ball_beta):
"""Конструктор класса мячей, которыми стреляет пушка :param color: цвет мяча :param lifetime: время жизни мяча в секундах :param alpha: параметр a в формуле силы трения F = -av ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ball:
def __init__(self, color, lifetime=ball_lifetime, r=ball_r, x=0, y=0, alpha=ball_alpha, beta=ball_beta):
"""Конструктор класса мячей, которыми стреляет пушка :param color: цвет мяча :param lifetime: время жизни мяча в секундах :param alpha: параметр a в формуле силы трения F = -av - bv^2 :param ... | the_stack_v2_python_sparse | Лаба 8/modules/bullets.py | VladimirMolunov/molunov_infa_2021 | train | 0 | |
3cfb68aaa101f3627c306cb1bffcc16277743d46 | [
"self._observable_callback = observable_update_callback\nself._sender_callback = sender_callback\nself._own_ip = host_ip\nself._logger = Log.get_logger(self.__class__.__name__)\nBaseRequestHandler.__init__(self, *args, **keys)",
"data = str(self.request[0], 'utf-8')\nif not self.is_kickback(self.client_address[0]... | <|body_start_0|>
self._observable_callback = observable_update_callback
self._sender_callback = sender_callback
self._own_ip = host_ip
self._logger = Log.get_logger(self.__class__.__name__)
BaseRequestHandler.__init__(self, *args, **keys)
<|end_body_0|>
<|body_start_1|>
... | This class represents a Threaded-UDP-Multicast-Requesthandler. This means, that it defines methods and attributes, which will be used to handle a udp-multicast-request. The handle method is called by the super-class (BaseRequestHandler) as a new request has been received. | ThreadedUDPMulticastRequestHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadedUDPMulticastRequestHandler:
"""This class represents a Threaded-UDP-Multicast-Requesthandler. This means, that it defines methods and attributes, which will be used to handle a udp-multicast-request. The handle method is called by the super-class (BaseRequestHandler) as a new request has ... | stack_v2_sparse_classes_36k_train_023968 | 3,338 | permissive | [
{
"docstring": "Shall initialize the given parameters as attributes and call the constructor of the super class. The observable_update_callback is in fact the update method of the observable implementation (in this case it may be UDPUpdateObservable). This method is called as a request is precessed by the handl... | 3 | stack_v2_sparse_classes_30k_train_010711 | Implement the Python class `ThreadedUDPMulticastRequestHandler` described below.
Class description:
This class represents a Threaded-UDP-Multicast-Requesthandler. This means, that it defines methods and attributes, which will be used to handle a udp-multicast-request. The handle method is called by the super-class (Ba... | Implement the Python class `ThreadedUDPMulticastRequestHandler` described below.
Class description:
This class represents a Threaded-UDP-Multicast-Requesthandler. This means, that it defines methods and attributes, which will be used to handle a udp-multicast-request. The handle method is called by the super-class (Ba... | a4d8112d1201d210f74e465a9381c68ec59b7ae3 | <|skeleton|>
class ThreadedUDPMulticastRequestHandler:
"""This class represents a Threaded-UDP-Multicast-Requesthandler. This means, that it defines methods and attributes, which will be used to handle a udp-multicast-request. The handle method is called by the super-class (BaseRequestHandler) as a new request has ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreadedUDPMulticastRequestHandler:
"""This class represents a Threaded-UDP-Multicast-Requesthandler. This means, that it defines methods and attributes, which will be used to handle a udp-multicast-request. The handle method is called by the super-class (BaseRequestHandler) as a new request has been received... | the_stack_v2_python_sparse | broadcast/receiver/requesthandler.py | nico-osd/osd_repo | train | 1 |
db21eaabc1a1319d1e994172a07e5587c1c0cb48 | [
"yield mlist.posting_address\nfor destination in sorted(SUBDESTINATIONS):\n yield '{}-{}@{}'.format(mlist.list_name, destination, mlist.mail_host)",
"yield mlist.list_name\nfor destination in sorted(SUBDESTINATIONS):\n yield '{}-{}'.format(mlist.list_name, destination)"
] | <|body_start_0|>
yield mlist.posting_address
for destination in sorted(SUBDESTINATIONS):
yield '{}-{}@{}'.format(mlist.list_name, destination, mlist.mail_host)
<|end_body_0|>
<|body_start_1|>
yield mlist.list_name
for destination in sorted(SUBDESTINATIONS):
yield... | Utility for generating all the aliases of a mailing list. | MailTransportAgentAliases | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MailTransportAgentAliases:
"""Utility for generating all the aliases of a mailing list."""
def aliases(self, mlist):
"""See `IMailTransportAgentAliases`."""
<|body_0|>
def destinations(self, mlist):
"""See `IMailTransportAgentAliases`."""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k_train_023969 | 1,771 | no_license | [
{
"docstring": "See `IMailTransportAgentAliases`.",
"name": "aliases",
"signature": "def aliases(self, mlist)"
},
{
"docstring": "See `IMailTransportAgentAliases`.",
"name": "destinations",
"signature": "def destinations(self, mlist)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019707 | Implement the Python class `MailTransportAgentAliases` described below.
Class description:
Utility for generating all the aliases of a mailing list.
Method signatures and docstrings:
- def aliases(self, mlist): See `IMailTransportAgentAliases`.
- def destinations(self, mlist): See `IMailTransportAgentAliases`. | Implement the Python class `MailTransportAgentAliases` described below.
Class description:
Utility for generating all the aliases of a mailing list.
Method signatures and docstrings:
- def aliases(self, mlist): See `IMailTransportAgentAliases`.
- def destinations(self, mlist): See `IMailTransportAgentAliases`.
<|ske... | 7edf8148e34b9f73ca6433ceb43a1770f4fa32c1 | <|skeleton|>
class MailTransportAgentAliases:
"""Utility for generating all the aliases of a mailing list."""
def aliases(self, mlist):
"""See `IMailTransportAgentAliases`."""
<|body_0|>
def destinations(self, mlist):
"""See `IMailTransportAgentAliases`."""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MailTransportAgentAliases:
"""Utility for generating all the aliases of a mailing list."""
def aliases(self, mlist):
"""See `IMailTransportAgentAliases`."""
yield mlist.posting_address
for destination in sorted(SUBDESTINATIONS):
yield '{}-{}@{}'.format(mlist.list_name,... | the_stack_v2_python_sparse | libs/Mailman/mailman/mta/aliases.py | masomel/py-import-analysis | train | 1 |
457e43be3cf777024a1c15063d29943fc449ae23 | [
"self.transport = transport\nself.address = transport.get_extra_info('peername')\nself.data = b''\nprint('accepted connection from {}'.format(self.address))",
"self.data += data\nif self.data.endswith(b'?'):\n answer = zen_utils.get_answer(self.data)\n self.transport.write(answer)\n self.data = b''",
"... | <|body_start_0|>
self.transport = transport
self.address = transport.get_extra_info('peername')
self.data = b''
print('accepted connection from {}'.format(self.address))
<|end_body_0|>
<|body_start_1|>
self.data += data
if self.data.endswith(b'?'):
answer = z... | ZenServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZenServer:
def connection_made(self, transport):
"""负责连接套接字建立后的准备工作"""
<|body_0|>
def data_received(self, data):
"""负责数据的接收、处理和发送,可以会被调用多次"""
<|body_1|>
def connection_lost(self, exc):
"""负责一次连接结束后的清理工作"""
<|body_2|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_023970 | 1,953 | no_license | [
{
"docstring": "负责连接套接字建立后的准备工作",
"name": "connection_made",
"signature": "def connection_made(self, transport)"
},
{
"docstring": "负责数据的接收、处理和发送,可以会被调用多次",
"name": "data_received",
"signature": "def data_received(self, data)"
},
{
"docstring": "负责一次连接结束后的清理工作",
"name": "conn... | 3 | stack_v2_sparse_classes_30k_train_005607 | Implement the Python class `ZenServer` described below.
Class description:
Implement the ZenServer class.
Method signatures and docstrings:
- def connection_made(self, transport): 负责连接套接字建立后的准备工作
- def data_received(self, data): 负责数据的接收、处理和发送,可以会被调用多次
- def connection_lost(self, exc): 负责一次连接结束后的清理工作 | Implement the Python class `ZenServer` described below.
Class description:
Implement the ZenServer class.
Method signatures and docstrings:
- def connection_made(self, transport): 负责连接套接字建立后的准备工作
- def data_received(self, data): 负责数据的接收、处理和发送,可以会被调用多次
- def connection_lost(self, exc): 负责一次连接结束后的清理工作
<|skeleton|>
cla... | 9d766f06b0d4b30f640fe7f0d7deabea99ba5eeb | <|skeleton|>
class ZenServer:
def connection_made(self, transport):
"""负责连接套接字建立后的准备工作"""
<|body_0|>
def data_received(self, data):
"""负责数据的接收、处理和发送,可以会被调用多次"""
<|body_1|>
def connection_lost(self, exc):
"""负责一次连接结束后的清理工作"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZenServer:
def connection_made(self, transport):
"""负责连接套接字建立后的准备工作"""
self.transport = transport
self.address = transport.get_extra_info('peername')
self.data = b''
print('accepted connection from {}'.format(self.address))
def data_received(self, data):
""... | the_stack_v2_python_sparse | pynetwork/第七章-服务器架构/srv_asyncio1.py | nick-fang/pynetwork | train | 1 | |
de7cc41b4e888c9db58afecd4785490925423896 | [
"sql = ' SELECT `ao_datastreams`.`id`\\n , COUNT(`ao_datastreams`.`id`) AS `total`\\n FROM `ao_users`\\n INNER JOIN `ao_datastreams` ON (`ao_datastreams`.`user_id` = `ao_users`.`id`)\\n INNER JOIN `ao_datastream_hits` ON (`ao_datastrea... | <|body_start_0|>
sql = ' SELECT `ao_datastreams`.`id`\n , COUNT(`ao_datastreams`.`id`) AS `total`\n FROM `ao_users`\n INNER JOIN `ao_datastreams` ON (`ao_datastreams`.`user_id` = `ao_users`.`id`)\n INNER JOIN `ao_datastream_hits` O... | DataStreamManager | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataStreamManager:
def get_top(self, account_id, limit=5):
"""Return the Top DSs Ids."""
<|body_0|>
def get_last(self, account_id, limit=5):
"""Return the last DSs Ids."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sql = ' SELECT `ao_datastreams... | stack_v2_sparse_classes_36k_train_023971 | 14,332 | permissive | [
{
"docstring": "Return the Top DSs Ids.",
"name": "get_top",
"signature": "def get_top(self, account_id, limit=5)"
},
{
"docstring": "Return the last DSs Ids.",
"name": "get_last",
"signature": "def get_last(self, account_id, limit=5)"
}
] | 2 | null | Implement the Python class `DataStreamManager` described below.
Class description:
Implement the DataStreamManager class.
Method signatures and docstrings:
- def get_top(self, account_id, limit=5): Return the Top DSs Ids.
- def get_last(self, account_id, limit=5): Return the last DSs Ids. | Implement the Python class `DataStreamManager` described below.
Class description:
Implement the DataStreamManager class.
Method signatures and docstrings:
- def get_top(self, account_id, limit=5): Return the Top DSs Ids.
- def get_last(self, account_id, limit=5): Return the last DSs Ids.
<|skeleton|>
class DataStre... | 0b16529d11417b965b1be0ba93305a7bbe5fb502 | <|skeleton|>
class DataStreamManager:
def get_top(self, account_id, limit=5):
"""Return the Top DSs Ids."""
<|body_0|>
def get_last(self, account_id, limit=5):
"""Return the last DSs Ids."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataStreamManager:
def get_top(self, account_id, limit=5):
"""Return the Top DSs Ids."""
sql = ' SELECT `ao_datastreams`.`id`\n , COUNT(`ao_datastreams`.`id`) AS `total`\n FROM `ao_users`\n INNER JOIN `ao_datastreams` ON (`ao_datast... | the_stack_v2_python_sparse | core/managers.py | EscuelaDeDatos/datal | train | 0 | |
16367ec38c05343d95f5a2067fda49233c4dc7e8 | [
"@lru_cache(maxsize=None)\ndef lps(i, j):\n if i > j:\n return 0\n if i == j:\n return 1\n if s[i] == s[j]:\n return lps(i + 1, j - 1) + 2\n return max(lps(i + 1, j), lps(i, j - 1))\nreturn len(s) - lps(0, len(s) - 1)",
"@lru_cache(maxsize=None)\ndef lps(i, j):\n if i >= j:\n ... | <|body_start_0|>
@lru_cache(maxsize=None)
def lps(i, j):
if i > j:
return 0
if i == j:
return 1
if s[i] == s[j]:
return lps(i + 1, j - 1) + 2
return max(lps(i + 1, j), lps(i, j - 1))
return len(s) - l... | Runtime: 796 ms, faster than 78.99% of Python3 online submissions for Minimum Insertion Steps to Make a String Palindrome. Memory Usage: 169.6 MB, less than 100.00% of Python3 online submissions for Minimum Insertion Steps to Make a String Palindrome. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Runtime: 796 ms, faster than 78.99% of Python3 online submissions for Minimum Insertion Steps to Make a String Palindrome. Memory Usage: 169.6 MB, less than 100.00% of Python3 online submissions for Minimum Insertion Steps to Make a String Palindrome."""
def minInsertions(self, ... | stack_v2_sparse_classes_36k_train_023972 | 2,052 | no_license | [
{
"docstring": "Given a string s. In one step you can insert any character at any index of the string. Return the minimum number of steps to make s palindrome. A Palindrome String is one that reads the same backward as well as forward. Example 1: Input: s = \"zzazz\" Output: 0 Explanation: The string \"zzazz\" ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Runtime: 796 ms, faster than 78.99% of Python3 online submissions for Minimum Insertion Steps to Make a String Palindrome. Memory Usage: 169.6 MB, less than 100.00% of Python3 online submissions for Minimum Insertion Steps to Make a String Palin... | Implement the Python class `Solution` described below.
Class description:
Runtime: 796 ms, faster than 78.99% of Python3 online submissions for Minimum Insertion Steps to Make a String Palindrome. Memory Usage: 169.6 MB, less than 100.00% of Python3 online submissions for Minimum Insertion Steps to Make a String Palin... | 01fe893ba2e37c9bda79e3081c556698f0b6d2f0 | <|skeleton|>
class Solution:
"""Runtime: 796 ms, faster than 78.99% of Python3 online submissions for Minimum Insertion Steps to Make a String Palindrome. Memory Usage: 169.6 MB, less than 100.00% of Python3 online submissions for Minimum Insertion Steps to Make a String Palindrome."""
def minInsertions(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Runtime: 796 ms, faster than 78.99% of Python3 online submissions for Minimum Insertion Steps to Make a String Palindrome. Memory Usage: 169.6 MB, less than 100.00% of Python3 online submissions for Minimum Insertion Steps to Make a String Palindrome."""
def minInsertions(self, s: str) -> in... | the_stack_v2_python_sparse | LeetCode/1312_minimum_insertion_steps_to_make_a_string_palindrome.py | KKosukeee/CodingQuestions | train | 1 |
1e33c702767336518cfa8ceb88e4edd034f3dbf6 | [
"self.marker_size = size\nself.marker_scale = scale\nself.type = 'Chessboard'",
"if flags is None:\n flags = 0\n flags |= cv2.CALIB_CB_ADAPTIVE_THRESH\n flags |= cv2.CALIB_CB_FAST_CHECK\n flags |= cv2.CALIB_CB_NORMALIZE_IMAGE\nret, corners = cv2.findChessboardCorners(gray, self.marker_size, flags=flag... | <|body_start_0|>
self.marker_size = size
self.marker_scale = scale
self.type = 'Chessboard'
<|end_body_0|>
<|body_start_1|>
if flags is None:
flags = 0
flags |= cv2.CALIB_CB_ADAPTIVE_THRESH
flags |= cv2.CALIB_CB_FAST_CHECK
flags |= cv2.CAL... | ChessboardFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChessboardFinder:
def __init__(self, size, scale):
"""size: pattern of chess board, tuple(rows, columns) scale: real-world dimension of square side, example, 2 cm (0.02 m)"""
<|body_0|>
def find(self, gray, flags=None):
"""Given an image, this will return the corners... | stack_v2_sparse_classes_36k_train_023973 | 1,909 | no_license | [
{
"docstring": "size: pattern of chess board, tuple(rows, columns) scale: real-world dimension of square side, example, 2 cm (0.02 m)",
"name": "__init__",
"signature": "def __init__(self, size, scale)"
},
{
"docstring": "Given an image, this will return the corners. Optionally you can enter fla... | 4 | stack_v2_sparse_classes_30k_train_003907 | Implement the Python class `ChessboardFinder` described below.
Class description:
Implement the ChessboardFinder class.
Method signatures and docstrings:
- def __init__(self, size, scale): size: pattern of chess board, tuple(rows, columns) scale: real-world dimension of square side, example, 2 cm (0.02 m)
- def find(... | Implement the Python class `ChessboardFinder` described below.
Class description:
Implement the ChessboardFinder class.
Method signatures and docstrings:
- def __init__(self, size, scale): size: pattern of chess board, tuple(rows, columns) scale: real-world dimension of square side, example, 2 cm (0.02 m)
- def find(... | 1d6342d5516e5110f4ee5186431d9b4e2f75b734 | <|skeleton|>
class ChessboardFinder:
def __init__(self, size, scale):
"""size: pattern of chess board, tuple(rows, columns) scale: real-world dimension of square side, example, 2 cm (0.02 m)"""
<|body_0|>
def find(self, gray, flags=None):
"""Given an image, this will return the corners... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChessboardFinder:
def __init__(self, size, scale):
"""size: pattern of chess board, tuple(rows, columns) scale: real-world dimension of square side, example, 2 cm (0.02 m)"""
self.marker_size = size
self.marker_scale = scale
self.type = 'Chessboard'
def find(self, gray, fl... | the_stack_v2_python_sparse | venv/Lib/site-packages/opencv_camera/targets/chessboard.py | yuchen556/E3845_ZQ | train | 0 | |
95cd16cff31facdfaa49c1cc3e68f83b0ddd4db7 | [
"self.myClick(self.find_uiautomator(self.get_mtz_name(), 'text'))\nself.boolean_login_state()\nself.login_by_sms(self.localReadConfig().getMobileInfo('mobile1'))\nself.swipe_to_down(2)\nself.myClick(self.find_element('个人中心', *self.iv_my_icon_id))\nself.assertEqual(self.find_element('个人中心title', *self.personal_info)... | <|body_start_0|>
self.myClick(self.find_uiautomator(self.get_mtz_name(), 'text'))
self.boolean_login_state()
self.login_by_sms(self.localReadConfig().getMobileInfo('mobile1'))
self.swipe_to_down(2)
self.myClick(self.find_element('个人中心', *self.iv_my_icon_id))
self.assertEq... | Test_login_by_sms | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_login_by_sms:
def test_sms(self):
"""使用验证码登录并且退出登录"""
<|body_0|>
def test_sms_error(self):
"""验证码输入错误"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.myClick(self.find_uiautomator(self.get_mtz_name(), 'text'))
self.boolean_login_st... | stack_v2_sparse_classes_36k_train_023974 | 1,409 | no_license | [
{
"docstring": "使用验证码登录并且退出登录",
"name": "test_sms",
"signature": "def test_sms(self)"
},
{
"docstring": "验证码输入错误",
"name": "test_sms_error",
"signature": "def test_sms_error(self)"
}
] | 2 | null | Implement the Python class `Test_login_by_sms` described below.
Class description:
Implement the Test_login_by_sms class.
Method signatures and docstrings:
- def test_sms(self): 使用验证码登录并且退出登录
- def test_sms_error(self): 验证码输入错误 | Implement the Python class `Test_login_by_sms` described below.
Class description:
Implement the Test_login_by_sms class.
Method signatures and docstrings:
- def test_sms(self): 使用验证码登录并且退出登录
- def test_sms_error(self): 验证码输入错误
<|skeleton|>
class Test_login_by_sms:
def test_sms(self):
"""使用验证码登录并且退出登录""... | b2066139eb0723eff69d971589b283b4b776c84c | <|skeleton|>
class Test_login_by_sms:
def test_sms(self):
"""使用验证码登录并且退出登录"""
<|body_0|>
def test_sms_error(self):
"""验证码输入错误"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_login_by_sms:
def test_sms(self):
"""使用验证码登录并且退出登录"""
self.myClick(self.find_uiautomator(self.get_mtz_name(), 'text'))
self.boolean_login_state()
self.login_by_sms(self.localReadConfig().getMobileInfo('mobile1'))
self.swipe_to_down(2)
self.myClick(self.find... | the_stack_v2_python_sparse | TestCase/4_5/TC_login/test_login_by_sms.py | testerSunshine/auto_md | train | 4 | |
08ee8af2a642026a5ac04b616443b33f4105fc4e | [
"with tf.name_scope('fast_rcnn_loss'):\n _, _, num_classes = class_outputs.get_shape().as_list()\n class_targets = tf.to_int32(class_targets)\n class_targets_one_hot = tf.one_hot(class_targets, num_classes)\n return self._fast_rcnn_class_loss(class_outputs, class_targets_one_hot)",
"with tf.name_scope... | <|body_start_0|>
with tf.name_scope('fast_rcnn_loss'):
_, _, num_classes = class_outputs.get_shape().as_list()
class_targets = tf.to_int32(class_targets)
class_targets_one_hot = tf.one_hot(class_targets, num_classes)
return self._fast_rcnn_class_loss(class_outputs... | Fast R-CNN classification loss function. | FastrcnnClassLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastrcnnClassLoss:
"""Fast R-CNN classification loss function."""
def __call__(self, class_outputs, class_targets):
"""Computes the class loss (Fast-RCNN branch) of Mask-RCNN. This function implements the classification loss of the Fast-RCNN. The classification loss is softmax on all... | stack_v2_sparse_classes_36k_train_023975 | 23,841 | permissive | [
{
"docstring": "Computes the class loss (Fast-RCNN branch) of Mask-RCNN. This function implements the classification loss of the Fast-RCNN. The classification loss is softmax on all RoIs. Reference: https://github.com/facebookresearch/Detectron/blob/master/detectron/modeling/fast_rcnn_heads.py # pylint: disable... | 2 | null | Implement the Python class `FastrcnnClassLoss` described below.
Class description:
Fast R-CNN classification loss function.
Method signatures and docstrings:
- def __call__(self, class_outputs, class_targets): Computes the class loss (Fast-RCNN branch) of Mask-RCNN. This function implements the classification loss of... | Implement the Python class `FastrcnnClassLoss` described below.
Class description:
Fast R-CNN classification loss function.
Method signatures and docstrings:
- def __call__(self, class_outputs, class_targets): Computes the class loss (Fast-RCNN branch) of Mask-RCNN. This function implements the classification loss of... | 0f7adb97a93ec3e3485c261d030c507eb16b33e4 | <|skeleton|>
class FastrcnnClassLoss:
"""Fast R-CNN classification loss function."""
def __call__(self, class_outputs, class_targets):
"""Computes the class loss (Fast-RCNN branch) of Mask-RCNN. This function implements the classification loss of the Fast-RCNN. The classification loss is softmax on all... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FastrcnnClassLoss:
"""Fast R-CNN classification loss function."""
def __call__(self, class_outputs, class_targets):
"""Computes the class loss (Fast-RCNN branch) of Mask-RCNN. This function implements the classification loss of the Fast-RCNN. The classification loss is softmax on all RoIs. Refere... | the_stack_v2_python_sparse | models/official/detection/modeling/losses.py | tensorflow/tpu | train | 5,627 |
c39b4d70c93bcee8c63c0fde257c3f47b46e47ad | [
"super().__init__(env)\nassert 0 <= lam <= 1\nself.env = env\nself.q = LinearWeights(x=features, w=weights)\nself.policy = self.q.derive_policy(EpsilonGreedyPolicy, env.valid_actions_from, epsilon=lambda s: 0.05)\nself.lam = lam\nself.eta = eta\nself.x = features\nself.w = weights\nself.gamma = gamma",
"q, w, x, ... | <|body_start_0|>
super().__init__(env)
assert 0 <= lam <= 1
self.env = env
self.q = LinearWeights(x=features, w=weights)
self.policy = self.q.derive_policy(EpsilonGreedyPolicy, env.valid_actions_from, epsilon=lambda s: 0.05)
self.lam = lam
self.eta = eta
s... | Sarsa Lambda agent using linear function approximation | SarsaLambda | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SarsaLambda:
"""Sarsa Lambda agent using linear function approximation"""
def __init__(self, env: FiniteActionEnvironment, features: callable, weights, lam: float=0.2, eta: float=0.01, gamma: float=1.0):
"""Create a new SarsaLambda Agent :param env: The environment the agent will lea... | stack_v2_sparse_classes_36k_train_023976 | 4,928 | permissive | [
{
"docstring": "Create a new SarsaLambda Agent :param env: The environment the agent will learn from :param features: A function that, when given an input state-action pair, computes a feature vector :param weights: An array of weights corresponding to each feature :param lam: The lambda parameter :param eta: S... | 2 | stack_v2_sparse_classes_30k_train_001533 | Implement the Python class `SarsaLambda` described below.
Class description:
Sarsa Lambda agent using linear function approximation
Method signatures and docstrings:
- def __init__(self, env: FiniteActionEnvironment, features: callable, weights, lam: float=0.2, eta: float=0.01, gamma: float=1.0): Create a new SarsaLa... | Implement the Python class `SarsaLambda` described below.
Class description:
Sarsa Lambda agent using linear function approximation
Method signatures and docstrings:
- def __init__(self, env: FiniteActionEnvironment, features: callable, weights, lam: float=0.2, eta: float=0.01, gamma: float=1.0): Create a new SarsaLa... | 7663a84371ee49668eb667f8f73a46d0262425ab | <|skeleton|>
class SarsaLambda:
"""Sarsa Lambda agent using linear function approximation"""
def __init__(self, env: FiniteActionEnvironment, features: callable, weights, lam: float=0.2, eta: float=0.01, gamma: float=1.0):
"""Create a new SarsaLambda Agent :param env: The environment the agent will lea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SarsaLambda:
"""Sarsa Lambda agent using linear function approximation"""
def __init__(self, env: FiniteActionEnvironment, features: callable, weights, lam: float=0.2, eta: float=0.01, gamma: float=1.0):
"""Create a new SarsaLambda Agent :param env: The environment the agent will learn from :para... | the_stack_v2_python_sparse | agents/linear_func_approx.py | KunBB/RL_project_common | train | 0 |
9b1d3d2a6ed6937e1777dc5febdc255565927800 | [
"def traverse(root):\n nonlocal tmp\n if not root:\n tmp.append('#')\n return\n tmp.append(str(root.val))\n traverse(root.left)\n traverse(root.right)\ntmp = []\ntraverse(root)\nreturn ','.join(tmp)",
"if not data:\n return None\ndata = data.split(',')\n\ndef ff():\n nonlocal da... | <|body_start_0|>
def traverse(root):
nonlocal tmp
if not root:
tmp.append('#')
return
tmp.append(str(root.val))
traverse(root.left)
traverse(root.right)
tmp = []
traverse(root)
return ','.join(tmp... | 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_023977 | 2,910 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | b700852c0c50cf2ab03ec9e1b203119366ec91af | <|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"""
def traverse(root):
nonlocal tmp
if not root:
tmp.append('#')
return
tmp.append(str(root.val))
traverse(ro... | the_stack_v2_python_sparse | pkm/lbld/297.二叉树的序列化与反序列化.py | riverszxc/riverplum | train | 0 | |
03ef1fdbabe2639106eb3eaec0b2c5972a3e6a55 | [
"self.field = str(field)\nself.is_floating = bool(floating)\nself.derivative_order = int(derivative_order)\nsuper().__init__(channel_group=channel_group, gain_provider=gain_provider, name=name)",
"values = getattr(integration.frames, self.field, None)\nif values is None:\n values = np.zeros(integration.size, d... | <|body_start_0|>
self.field = str(field)
self.is_floating = bool(floating)
self.derivative_order = int(derivative_order)
super().__init__(channel_group=channel_group, gain_provider=gain_provider, name=name)
<|end_body_0|>
<|body_start_1|>
values = getattr(integration.frames, sel... | FieldResponse | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FieldResponse:
def __init__(self, channel_group=None, gain_provider=None, name=None, floating=False, field=None, derivative_order=0):
"""Returns a field response mode. The field response mode is designed to return a signal based of a data field in the integration frame data. Parameters -... | stack_v2_sparse_classes_36k_train_023978 | 2,728 | permissive | [
{
"docstring": "Returns a field response mode. The field response mode is designed to return a signal based of a data field in the integration frame data. Parameters ---------- channel_group : ChannelGroup, optional The channel group owned by the mode. gain_provider : str or GainProvider, optional If a string i... | 2 | stack_v2_sparse_classes_30k_train_016185 | Implement the Python class `FieldResponse` described below.
Class description:
Implement the FieldResponse class.
Method signatures and docstrings:
- def __init__(self, channel_group=None, gain_provider=None, name=None, floating=False, field=None, derivative_order=0): Returns a field response mode. The field response... | Implement the Python class `FieldResponse` described below.
Class description:
Implement the FieldResponse class.
Method signatures and docstrings:
- def __init__(self, channel_group=None, gain_provider=None, name=None, floating=False, field=None, derivative_order=0): Returns a field response mode. The field response... | 493700340cd34d5f319af6f3a562a82135bb30dd | <|skeleton|>
class FieldResponse:
def __init__(self, channel_group=None, gain_provider=None, name=None, floating=False, field=None, derivative_order=0):
"""Returns a field response mode. The field response mode is designed to return a signal based of a data field in the integration frame data. Parameters -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FieldResponse:
def __init__(self, channel_group=None, gain_provider=None, name=None, floating=False, field=None, derivative_order=0):
"""Returns a field response mode. The field response mode is designed to return a signal based of a data field in the integration frame data. Parameters ---------- chan... | the_stack_v2_python_sparse | sofia_redux/scan/channels/mode/field_response.py | SOFIA-USRA/sofia_redux | train | 12 | |
81151641791bbf4c62f625eb49c5b1bf9ff61073 | [
"exploration = FakeExploration()\nUSER_ID = 'user_id'\nexploration.state_ids = []\nwith self.assertRaisesRegexp(utils.ValidationError, 'exploration has no states'):\n exp_services.save_exploration(USER_ID, exploration)\nexploration.state_ids = ['A string']\nwith self.assertRaisesRegexp(utils.ValidationError, 'In... | <|body_start_0|>
exploration = FakeExploration()
USER_ID = 'user_id'
exploration.state_ids = []
with self.assertRaisesRegexp(utils.ValidationError, 'exploration has no states'):
exp_services.save_exploration(USER_ID, exploration)
exploration.state_ids = ['A string']
... | Test the exploration domain object. | ExplorationDomainUnitTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExplorationDomainUnitTests:
"""Test the exploration domain object."""
def test_validation(self):
"""Test validation of explorations."""
<|body_0|>
def test_init_state_property(self):
"""Test the init_state property."""
<|body_1|>
def test_is_demo_pro... | stack_v2_sparse_classes_36k_train_023979 | 5,716 | permissive | [
{
"docstring": "Test validation of explorations.",
"name": "test_validation",
"signature": "def test_validation(self)"
},
{
"docstring": "Test the init_state property.",
"name": "test_init_state_property",
"signature": "def test_init_state_property(self)"
},
{
"docstring": "Test ... | 5 | stack_v2_sparse_classes_30k_train_001627 | Implement the Python class `ExplorationDomainUnitTests` described below.
Class description:
Test the exploration domain object.
Method signatures and docstrings:
- def test_validation(self): Test validation of explorations.
- def test_init_state_property(self): Test the init_state property.
- def test_is_demo_propert... | Implement the Python class `ExplorationDomainUnitTests` described below.
Class description:
Test the exploration domain object.
Method signatures and docstrings:
- def test_validation(self): Test validation of explorations.
- def test_init_state_property(self): Test the init_state property.
- def test_is_demo_propert... | 3d97903a5155ec67f135b1aa2c02f3bb39eb02e7 | <|skeleton|>
class ExplorationDomainUnitTests:
"""Test the exploration domain object."""
def test_validation(self):
"""Test validation of explorations."""
<|body_0|>
def test_init_state_property(self):
"""Test the init_state property."""
<|body_1|>
def test_is_demo_pro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExplorationDomainUnitTests:
"""Test the exploration domain object."""
def test_validation(self):
"""Test validation of explorations."""
exploration = FakeExploration()
USER_ID = 'user_id'
exploration.state_ids = []
with self.assertRaisesRegexp(utils.ValidationError... | the_stack_v2_python_sparse | core/domain/exp_domain_test.py | willingc/oh-missions-oppia-beta | train | 0 |
09edbca588c9f98d3cce5ccd814e25ecb37f08d7 | [
"super(GraphBasedModel, self).__init__(name=name)\nself._n_recurrences = n_recurrences\nif mlp_kwargs is None:\n mlp_kwargs = {}\nmodel_fn = functools.partial(snt.nets.MLP, output_sizes=mlp_sizes, activate_final=True, **mlp_kwargs)\nfinal_model_fn = functools.partial(snt.nets.MLP, output_sizes=mlp_sizes + (1,), ... | <|body_start_0|>
super(GraphBasedModel, self).__init__(name=name)
self._n_recurrences = n_recurrences
if mlp_kwargs is None:
mlp_kwargs = {}
model_fn = functools.partial(snt.nets.MLP, output_sizes=mlp_sizes, activate_final=True, **mlp_kwargs)
final_model_fn = functool... | Graph based model which predicts particle mobilities from their positions. This network encodes the nodes and edges of the input graph independently, and then performs message-passing on this graph, updating its edges based on their associated nodes, then updating the nodes based on the input nodes' features and their ... | GraphBasedModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphBasedModel:
"""Graph based model which predicts particle mobilities from their positions. This network encodes the nodes and edges of the input graph independently, and then performs message-passing on this graph, updating its edges based on their associated nodes, then updating the nodes ba... | stack_v2_sparse_classes_36k_train_023980 | 6,797 | permissive | [
{
"docstring": "Creates a new GraphBasedModel object. Args: n_recurrences: the number of message passing steps in the graph network. mlp_sizes: the number of neurons in each layer of the MLP. mlp_kwargs: additional keyword aguments passed to the MLP. name: the name of the Sonnet module.",
"name": "__init__"... | 2 | stack_v2_sparse_classes_30k_train_006459 | Implement the Python class `GraphBasedModel` described below.
Class description:
Graph based model which predicts particle mobilities from their positions. This network encodes the nodes and edges of the input graph independently, and then performs message-passing on this graph, updating its edges based on their assoc... | Implement the Python class `GraphBasedModel` described below.
Class description:
Graph based model which predicts particle mobilities from their positions. This network encodes the nodes and edges of the input graph independently, and then performs message-passing on this graph, updating its edges based on their assoc... | 0d8c06196bb46dc50de3661157dbcf3732d6e1c7 | <|skeleton|>
class GraphBasedModel:
"""Graph based model which predicts particle mobilities from their positions. This network encodes the nodes and edges of the input graph independently, and then performs message-passing on this graph, updating its edges based on their associated nodes, then updating the nodes ba... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphBasedModel:
"""Graph based model which predicts particle mobilities from their positions. This network encodes the nodes and edges of the input graph independently, and then performs message-passing on this graph, updating its edges based on their associated nodes, then updating the nodes based on the in... | the_stack_v2_python_sparse | glassy_dynamics/graph_model.py | alvarosg/deepmind-research | train | 1 |
5622e491fc9a9ebd1c6c658ea1e1e6d97b634291 | [
"extension = extension or ''\nif extension and (not extension.startswith('.')):\n extension = '.' + extension\nstamp = stamp or to_timestamp(self.uploaded_on)\nreturn f'{self.file_depository.pk}/depositedfile/{self.pk}/{stamp}{extension}'",
"if 'extension' in extra_parameters:\n self.extension = extra_param... | <|body_start_0|>
extension = extension or ''
if extension and (not extension.startswith('.')):
extension = '.' + extension
stamp = stamp or to_timestamp(self.uploaded_on)
return f'{self.file_depository.pk}/depositedfile/{self.pk}/{stamp}{extension}'
<|end_body_0|>
<|body_sta... | Model representing a file in a file depository. | DepositedFile | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DepositedFile:
"""Model representing a file in a file depository."""
def get_source_s3_key(self, stamp=None, extension=None):
"""Compute the S3 key in the source bucket. It is built from the file deposit ID + ID of the deposited file + version stamp. Parameters ---------- stamp: Type... | stack_v2_sparse_classes_36k_train_023981 | 7,033 | permissive | [
{
"docstring": "Compute the S3 key in the source bucket. It is built from the file deposit ID + ID of the deposited file + version stamp. Parameters ---------- stamp: Type[string] Passing a value for this argument will return the source S3 key for the deposited file assuming its active stamp is set to this valu... | 2 | null | Implement the Python class `DepositedFile` described below.
Class description:
Model representing a file in a file depository.
Method signatures and docstrings:
- def get_source_s3_key(self, stamp=None, extension=None): Compute the S3 key in the source bucket. It is built from the file deposit ID + ID of the deposite... | Implement the Python class `DepositedFile` described below.
Class description:
Model representing a file in a file depository.
Method signatures and docstrings:
- def get_source_s3_key(self, stamp=None, extension=None): Compute the S3 key in the source bucket. It is built from the file deposit ID + ID of the deposite... | f767f1bdc12c9712f26ea17cb8b19f536389f0ed | <|skeleton|>
class DepositedFile:
"""Model representing a file in a file depository."""
def get_source_s3_key(self, stamp=None, extension=None):
"""Compute the S3 key in the source bucket. It is built from the file deposit ID + ID of the deposited file + version stamp. Parameters ---------- stamp: Type... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DepositedFile:
"""Model representing a file in a file depository."""
def get_source_s3_key(self, stamp=None, extension=None):
"""Compute the S3 key in the source bucket. It is built from the file deposit ID + ID of the deposited file + version stamp. Parameters ---------- stamp: Type[string] Pass... | the_stack_v2_python_sparse | src/backend/marsha/deposit/models.py | openfun/marsha | train | 92 |
be6e2cdfe8eac6023f1ebabf2f66b3a2bcf77554 | [
"if isinstance(value, (basestring, bool, int, long, float, None.__class__)):\n return value\nif isinstance(value, JsonSnapshotable):\n value = snapshot.make_entity_for_data(value)\nif isinstance(value, SnapshotEntity):\n return {'_type': 'EntityReference', '_id': value.id}\nif isinstance(value, list):\n ... | <|body_start_0|>
if isinstance(value, (basestring, bool, int, long, float, None.__class__)):
return value
if isinstance(value, JsonSnapshotable):
value = snapshot.make_entity_for_data(value)
if isinstance(value, SnapshotEntity):
return {'_type': 'EntityReferen... | Helper class for implementing JsonSnapshotable. | JsonSnapshotHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonSnapshotHelper:
"""Helper class for implementing JsonSnapshotable."""
def ToJsonSnapshotValue(cls, value, snapshot):
"""Convert value into snapshot equivalent. For the most part, this is the identity if value is a primitive type. However lists and dictionaries may reference other... | stack_v2_sparse_classes_36k_train_023982 | 25,744 | permissive | [
{
"docstring": "Convert value into snapshot equivalent. For the most part, this is the identity if value is a primitive type. However lists and dictionaries may reference other entities that need to be snapshotted. For example references to other entities, or other object types that need to be converted.",
... | 3 | stack_v2_sparse_classes_30k_train_010489 | Implement the Python class `JsonSnapshotHelper` described below.
Class description:
Helper class for implementing JsonSnapshotable.
Method signatures and docstrings:
- def ToJsonSnapshotValue(cls, value, snapshot): Convert value into snapshot equivalent. For the most part, this is the identity if value is a primitive... | Implement the Python class `JsonSnapshotHelper` described below.
Class description:
Helper class for implementing JsonSnapshotable.
Method signatures and docstrings:
- def ToJsonSnapshotValue(cls, value, snapshot): Convert value into snapshot equivalent. For the most part, this is the identity if value is a primitive... | af959f88885f003fc2e6724e2e0bea6657274db5 | <|skeleton|>
class JsonSnapshotHelper:
"""Helper class for implementing JsonSnapshotable."""
def ToJsonSnapshotValue(cls, value, snapshot):
"""Convert value into snapshot equivalent. For the most part, this is the identity if value is a primitive type. However lists and dictionaries may reference other... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JsonSnapshotHelper:
"""Helper class for implementing JsonSnapshotable."""
def ToJsonSnapshotValue(cls, value, snapshot):
"""Convert value into snapshot equivalent. For the most part, this is the identity if value is a primitive type. However lists and dictionaries may reference other entities tha... | the_stack_v2_python_sparse | citest/base/snapshot.py | lwander/citest | train | 0 |
975296a4650182c30efa9be0b715349428d05f5b | [
"lst = []\nfor i in range(1, n + 1):\n s = str(i)\n for j in s:\n lst.append(j)\nreturn int(lst[n - 1])",
"groups = [9, 180, 2700, 36000, 450000, 5400000, 63000000, 720000000, 8100000000]\ng = bisect.bisect_left(groups, n)\nnth = n - sum(groups[:g]) - 1\nd, m = divmod(nth, g + 1)\nnumber = d + pow(10... | <|body_start_0|>
lst = []
for i in range(1, n + 1):
s = str(i)
for j in s:
lst.append(j)
return int(lst[n - 1])
<|end_body_0|>
<|body_start_1|>
groups = [9, 180, 2700, 36000, 450000, 5400000, 63000000, 720000000, 8100000000]
g = bisect.bis... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findNthDigit1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def findNthDigit(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
lst = []
for i in range(1, n + 1):
s = str(i)
... | stack_v2_sparse_classes_36k_train_023983 | 3,069 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "findNthDigit1",
"signature": "def findNthDigit1(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "findNthDigit",
"signature": "def findNthDigit(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010413 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findNthDigit1(self, n): :type n: int :rtype: int
- def findNthDigit(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 findNthDigit1(self, n): :type n: int :rtype: int
- def findNthDigit(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def findNthDigit1(self, n):
... | a57282895fb213b68e5d81db301903721a92d80f | <|skeleton|>
class Solution:
def findNthDigit1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def findNthDigit(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 findNthDigit1(self, n):
""":type n: int :rtype: int"""
lst = []
for i in range(1, n + 1):
s = str(i)
for j in s:
lst.append(j)
return int(lst[n - 1])
def findNthDigit(self, n):
""":type n: int :rtype: int"""
... | the_stack_v2_python_sparse | Python/400_nth-digit.py | antonylu/leetcode2 | train | 0 | |
63fa50353147f9fd00fa3fabb30cd86cbed0388f | [
"for operation in self.get_operations(context):\n result = operation(context)\n if result is not False:\n return result\nreturn False",
"operations = []\nfor hook in FacilityDataSyncHook.registered_hooks:\n operations.extend(hook.get_sync_operations(context))\nreturn sorted(operations, reverse=Tru... | <|body_start_0|>
for operation in self.get_operations(context):
result = operation(context)
if result is not False:
return result
return False
<|end_body_0|>
<|body_start_1|>
operations = []
for hook in FacilityDataSyncHook.registered_hooks:
... | Proxy class for Morango sync operations which allows customized behavior through Kolibri plugins | KolibriSyncOperations | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KolibriSyncOperations:
"""Proxy class for Morango sync operations which allows customized behavior through Kolibri plugins"""
def handle(self, context):
"""Kolibri plugins can register transfer operations to alter the behavior of the sync. The operations have more control over the sy... | stack_v2_sparse_classes_36k_train_023984 | 8,862 | permissive | [
{
"docstring": "Kolibri plugins can register transfer operations to alter the behavior of the sync. The operations have more control over the sync process, such as blocking it or bypassing certain aspects. :type context: morango.sync.context.SessionContext :return: False or transfer stage status",
"name": "... | 2 | null | Implement the Python class `KolibriSyncOperations` described below.
Class description:
Proxy class for Morango sync operations which allows customized behavior through Kolibri plugins
Method signatures and docstrings:
- def handle(self, context): Kolibri plugins can register transfer operations to alter the behavior ... | Implement the Python class `KolibriSyncOperations` described below.
Class description:
Proxy class for Morango sync operations which allows customized behavior through Kolibri plugins
Method signatures and docstrings:
- def handle(self, context): Kolibri plugins can register transfer operations to alter the behavior ... | cc9da2a6acd139acac3cd71c4cb05c15d4465712 | <|skeleton|>
class KolibriSyncOperations:
"""Proxy class for Morango sync operations which allows customized behavior through Kolibri plugins"""
def handle(self, context):
"""Kolibri plugins can register transfer operations to alter the behavior of the sync. The operations have more control over the sy... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KolibriSyncOperations:
"""Proxy class for Morango sync operations which allows customized behavior through Kolibri plugins"""
def handle(self, context):
"""Kolibri plugins can register transfer operations to alter the behavior of the sync. The operations have more control over the sync process, s... | the_stack_v2_python_sparse | kolibri/core/auth/sync_operations.py | learningequality/kolibri | train | 689 |
ff9694ad78dfb898ae3265f5f52c650e13633d35 | [
"self.data = data\nself.event = event\nself.id = id\nself.retry = retry\nself.comment = comment\nself.DEFAULT_SEPARATOR = '\\r\\n'\nself.LINE_SEP_EXPR = re.compile('\\\\r\\\\n|\\\\r|\\\\n')\nself._sep = sep if sep is not None else self.DEFAULT_SEPARATOR",
"buffer = io.StringIO()\nif self.comment is not None:\n ... | <|body_start_0|>
self.data = data
self.event = event
self.id = id
self.retry = retry
self.comment = comment
self.DEFAULT_SEPARATOR = '\r\n'
self.LINE_SEP_EXPR = re.compile('\\r\\n|\\r|\\n')
self._sep = sep if sep is not None else self.DEFAULT_SEPARATOR
<|e... | Class to manage Server-Sent Events | ServerSentEvent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerSentEvent:
"""Class to manage Server-Sent Events"""
def __init__(self, data: Optional[Any]=None, *, event: Optional[str]=None, id: Optional[int]=None, retry: Optional[int]=None, comment: Optional[str]=None, sep: Optional[str]=None) -> None:
"""Send data using EventSource protoc... | stack_v2_sparse_classes_36k_train_023985 | 13,447 | permissive | [
{
"docstring": "Send data using EventSource protocol # noqa: DAR101 :param data: The data field for the message. :param event: The event's type. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the web site would use addEventListener() to listen for ... | 2 | stack_v2_sparse_classes_30k_val_000663 | Implement the Python class `ServerSentEvent` described below.
Class description:
Class to manage Server-Sent Events
Method signatures and docstrings:
- def __init__(self, data: Optional[Any]=None, *, event: Optional[str]=None, id: Optional[int]=None, retry: Optional[int]=None, comment: Optional[str]=None, sep: Option... | Implement the Python class `ServerSentEvent` described below.
Class description:
Class to manage Server-Sent Events
Method signatures and docstrings:
- def __init__(self, data: Optional[Any]=None, *, event: Optional[str]=None, id: Optional[int]=None, retry: Optional[int]=None, comment: Optional[str]=None, sep: Option... | 23c7b8c78fc4ad67d16d83fc0c9f0eae9e935e71 | <|skeleton|>
class ServerSentEvent:
"""Class to manage Server-Sent Events"""
def __init__(self, data: Optional[Any]=None, *, event: Optional[str]=None, id: Optional[int]=None, retry: Optional[int]=None, comment: Optional[str]=None, sep: Optional[str]=None) -> None:
"""Send data using EventSource protoc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServerSentEvent:
"""Class to manage Server-Sent Events"""
def __init__(self, data: Optional[Any]=None, *, event: Optional[str]=None, id: Optional[int]=None, retry: Optional[int]=None, comment: Optional[str]=None, sep: Optional[str]=None) -> None:
"""Send data using EventSource protocol # noqa: DA... | the_stack_v2_python_sparse | jina/serve/networking/sse.py | jina-ai/jina | train | 20,687 |
c3da19c7a90d5da564b74312fc2ce33bcd0d56b9 | [
"min_dist = len(words)\nfor i in range(len(words)):\n if words[i] == word1:\n for j in range(len(words)):\n if words[j] == word2:\n dist = abs(j - i)\n min_dist = min(dist, min_dist)\nreturn min_dist",
"pointer_1 = -1\npointer_2 = -1\nmin_dist = len(words)\nfor i... | <|body_start_0|>
min_dist = len(words)
for i in range(len(words)):
if words[i] == word1:
for j in range(len(words)):
if words[j] == word2:
dist = abs(j - i)
min_dist = min(dist, min_dist)
return min_d... | ---------------------- Brute Force O(n^2) ------------------------- | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""---------------------- Brute Force O(n^2) -------------------------"""
def shortestDistance(self, words, word1, word2):
""":type words: List[str] :type word1: str :type word2: str :rtype: int"""
<|body_0|>
def shortestDistance_Linear(self, words, word1, word... | stack_v2_sparse_classes_36k_train_023986 | 1,435 | no_license | [
{
"docstring": ":type words: List[str] :type word1: str :type word2: str :rtype: int",
"name": "shortestDistance",
"signature": "def shortestDistance(self, words, word1, word2)"
},
{
"docstring": ":type words: List[str] :type word1: str :type word2: str :rtype: int",
"name": "shortestDistanc... | 2 | stack_v2_sparse_classes_30k_train_013819 | Implement the Python class `Solution` described below.
Class description:
---------------------- Brute Force O(n^2) -------------------------
Method signatures and docstrings:
- def shortestDistance(self, words, word1, word2): :type words: List[str] :type word1: str :type word2: str :rtype: int
- def shortestDistance... | Implement the Python class `Solution` described below.
Class description:
---------------------- Brute Force O(n^2) -------------------------
Method signatures and docstrings:
- def shortestDistance(self, words, word1, word2): :type words: List[str] :type word1: str :type word2: str :rtype: int
- def shortestDistance... | a9b2de06306f3929a82ef4e6613c972e9a2c2200 | <|skeleton|>
class Solution:
"""---------------------- Brute Force O(n^2) -------------------------"""
def shortestDistance(self, words, word1, word2):
""":type words: List[str] :type word1: str :type word2: str :rtype: int"""
<|body_0|>
def shortestDistance_Linear(self, words, word1, word... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""---------------------- Brute Force O(n^2) -------------------------"""
def shortestDistance(self, words, word1, word2):
""":type words: List[str] :type word1: str :type word2: str :rtype: int"""
min_dist = len(words)
for i in range(len(words)):
if words[i]... | the_stack_v2_python_sparse | Practice_3/Shortest_Word_Distance.py | anantvir/Leetcode-Problems | train | 1 |
fe699ee0cbe2831fdfd71707a98ae51fba00b641 | [
"logging.info('## SETUP METHOD ##')\nlogging.info('# Initializing the webdriver.')\nself.chprofile = self.create_chprofile()\nself.driver = webdriver.Chrome(self.chprofile)\nself.driver.maximize_window()\nself.driver.implicitly_wait(5)\nself.driver.get('http://the-internet.herokuapp.com/')",
"logging.info('## TEA... | <|body_start_0|>
logging.info('## SETUP METHOD ##')
logging.info('# Initializing the webdriver.')
self.chprofile = self.create_chprofile()
self.driver = webdriver.Chrome(self.chprofile)
self.driver.maximize_window()
self.driver.implicitly_wait(5)
self.driver.get('... | This class is for instantiating web driver instances. | DriverManagerChrome | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DriverManagerChrome:
"""This class is for instantiating web driver instances."""
def setUp(self):
"""This method is to instantiate the web driver instance."""
<|body_0|>
def tearDown(self):
"""This is teardown method. It is to capture the screenshots for failed t... | stack_v2_sparse_classes_36k_train_023987 | 3,946 | permissive | [
{
"docstring": "This method is to instantiate the web driver instance.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "This is teardown method. It is to capture the screenshots for failed test cases, & to remove web driver object.",
"name": "tearDown",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_021176 | Implement the Python class `DriverManagerChrome` described below.
Class description:
This class is for instantiating web driver instances.
Method signatures and docstrings:
- def setUp(self): This method is to instantiate the web driver instance.
- def tearDown(self): This is teardown method. It is to capture the scr... | Implement the Python class `DriverManagerChrome` described below.
Class description:
This class is for instantiating web driver instances.
Method signatures and docstrings:
- def setUp(self): This method is to instantiate the web driver instance.
- def tearDown(self): This is teardown method. It is to capture the scr... | 65513cb85eccb1ae3fae4ac3625d0e6878720ec8 | <|skeleton|>
class DriverManagerChrome:
"""This class is for instantiating web driver instances."""
def setUp(self):
"""This method is to instantiate the web driver instance."""
<|body_0|>
def tearDown(self):
"""This is teardown method. It is to capture the screenshots for failed t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DriverManagerChrome:
"""This class is for instantiating web driver instances."""
def setUp(self):
"""This method is to instantiate the web driver instance."""
logging.info('## SETUP METHOD ##')
logging.info('# Initializing the webdriver.')
self.chprofile = self.create_chpr... | the_stack_v2_python_sparse | attic/2019/contributions-2019/open/mudaliar-yptu/PWAF/utility/drivermanager.py | Agriad/devops-course | train | 0 |
faee9a4c2ba1a6d07fecfc1a6ad31f443b03ed70 | [
"reg_l = self.read_holding_registers(address, number * 2)\nif reg_l:\n return [decode_ieee(f) for f in word_list_to_long(reg_l)]\nelse:\n return None",
"b32_l = [encode_ieee(f) for f in floats_list]\nb16_l = long_list_to_word(b32_l)\nreturn self.write_multiple_registers(address, b16_l)"
] | <|body_start_0|>
reg_l = self.read_holding_registers(address, number * 2)
if reg_l:
return [decode_ieee(f) for f in word_list_to_long(reg_l)]
else:
return None
<|end_body_0|>
<|body_start_1|>
b32_l = [encode_ieee(f) for f in floats_list]
b16_l = long_list... | A ModbusClient class with float support | FloatModbusClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FloatModbusClient:
"""A ModbusClient class with float support"""
def read_float(self, address, number=1):
"""Read float(s) with read holding registers"""
<|body_0|>
def write_float(self, address, floats_list):
"""Write float(s) with write multiple registers"""
... | stack_v2_sparse_classes_36k_train_023988 | 832 | permissive | [
{
"docstring": "Read float(s) with read holding registers",
"name": "read_float",
"signature": "def read_float(self, address, number=1)"
},
{
"docstring": "Write float(s) with write multiple registers",
"name": "write_float",
"signature": "def write_float(self, address, floats_list)"
}... | 2 | null | Implement the Python class `FloatModbusClient` described below.
Class description:
A ModbusClient class with float support
Method signatures and docstrings:
- def read_float(self, address, number=1): Read float(s) with read holding registers
- def write_float(self, address, floats_list): Write float(s) with write mul... | Implement the Python class `FloatModbusClient` described below.
Class description:
A ModbusClient class with float support
Method signatures and docstrings:
- def read_float(self, address, number=1): Read float(s) with read holding registers
- def write_float(self, address, floats_list): Write float(s) with write mul... | 2790384d5fef8fbbe93fb9764d8ec275d9aba3b7 | <|skeleton|>
class FloatModbusClient:
"""A ModbusClient class with float support"""
def read_float(self, address, number=1):
"""Read float(s) with read holding registers"""
<|body_0|>
def write_float(self, address, floats_list):
"""Write float(s) with write multiple registers"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FloatModbusClient:
"""A ModbusClient class with float support"""
def read_float(self, address, number=1):
"""Read float(s) with read holding registers"""
reg_l = self.read_holding_registers(address, number * 2)
if reg_l:
return [decode_ieee(f) for f in word_list_to_lon... | the_stack_v2_python_sparse | hmi/nano/flow_valve/lib/modbus.py | sourceperl/sandbox | train | 0 |
64bdf35534a45a39de93b39983ae1b728e6f6e94 | [
"self.id = id_\nself.log_group_id = log_group_id\nself.user = user\nself.message = message\nself.time = time_",
"with new_session() as session:\n event = models.Log_group_event(log_group_id=log_group_id, user_id=user_id, message=message, time=datetime.utcnow())\n session.add(event)\n return True",
"if ... | <|body_start_0|>
self.id = id_
self.log_group_id = log_group_id
self.user = user
self.message = message
self.time = time_
<|end_body_0|>
<|body_start_1|>
with new_session() as session:
event = models.Log_group_event(log_group_id=log_group_id, user_id=user_id,... | Log_group_event | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Log_group_event:
def __init__(self, id_, log_group_id, user, message, time_):
""":param id_: int :param log_group_id: int :param user: tlog.base.user.User :param message: str :param time_: Datetime"""
<|body_0|>
def new(cls, log_group_id, user_id, message):
"""Create... | stack_v2_sparse_classes_36k_train_023989 | 2,347 | no_license | [
{
"docstring": ":param id_: int :param log_group_id: int :param user: tlog.base.user.User :param message: str :param time_: Datetime",
"name": "__init__",
"signature": "def __init__(self, id_, log_group_id, user, message, time_)"
},
{
"docstring": "Creates a new event for a log group. :param log... | 3 | stack_v2_sparse_classes_30k_train_002451 | Implement the Python class `Log_group_event` described below.
Class description:
Implement the Log_group_event class.
Method signatures and docstrings:
- def __init__(self, id_, log_group_id, user, message, time_): :param id_: int :param log_group_id: int :param user: tlog.base.user.User :param message: str :param ti... | Implement the Python class `Log_group_event` described below.
Class description:
Implement the Log_group_event class.
Method signatures and docstrings:
- def __init__(self, id_, log_group_id, user, message, time_): :param id_: int :param log_group_id: int :param user: tlog.base.user.User :param message: str :param ti... | 3f331c7169c90d1fac0d1922b011b56eebbd086a | <|skeleton|>
class Log_group_event:
def __init__(self, id_, log_group_id, user, message, time_):
""":param id_: int :param log_group_id: int :param user: tlog.base.user.User :param message: str :param time_: Datetime"""
<|body_0|>
def new(cls, log_group_id, user_id, message):
"""Create... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Log_group_event:
def __init__(self, id_, log_group_id, user, message, time_):
""":param id_: int :param log_group_id: int :param user: tlog.base.user.User :param message: str :param time_: Datetime"""
self.id = id_
self.log_group_id = log_group_id
self.user = user
self.... | the_stack_v2_python_sparse | src/tlog/base/event.py | thomaserlang/TLog | train | 2 | |
be79d4855410adc45f01cd9cc1b1c2cabe5650fe | [
"try:\n ticket_id = args[0]\nexcept IndexError:\n return self.Get.no_param_ticket_id()\ntickets = Tickets.objects.filter(id=ticket_id, owner=request.user).only('id')[:1]\nif not tickets:\n return self.Get.no_such_ticket()\nticket = tickets[0]\nreturn self.Get.ok(ticket)",
"try:\n ticket_id = int(args[... | <|body_start_0|>
try:
ticket_id = args[0]
except IndexError:
return self.Get.no_param_ticket_id()
tickets = Tickets.objects.filter(id=ticket_id, owner=request.user).only('id')[:1]
if not tickets:
return self.Get.no_such_ticket()
ticket = ticket... | Messages | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Messages:
def get(self, request, *args):
"""Returns JSON-response with all messages of ticket ith id from url. For the response format see the code. Params: ticket_id (url, pos=0): id of the ticket."""
<|body_0|>
def post(self, request, *args):
"""Params: ticket_id -... | stack_v2_sparse_classes_36k_train_023990 | 9,638 | no_license | [
{
"docstring": "Returns JSON-response with all messages of ticket ith id from url. For the response format see the code. Params: ticket_id (url, pos=0): id of the ticket.",
"name": "get",
"signature": "def get(self, request, *args)"
},
{
"docstring": "Params: ticket_id - (url, pos=0) message - m... | 2 | null | Implement the Python class `Messages` described below.
Class description:
Implement the Messages class.
Method signatures and docstrings:
- def get(self, request, *args): Returns JSON-response with all messages of ticket ith id from url. For the response format see the code. Params: ticket_id (url, pos=0): id of the ... | Implement the Python class `Messages` described below.
Class description:
Implement the Messages class.
Method signatures and docstrings:
- def get(self, request, *args): Returns JSON-response with all messages of ticket ith id from url. For the response format see the code. Params: ticket_id (url, pos=0): id of the ... | c060941b16c36d258989206f9c2143b5179b4acd | <|skeleton|>
class Messages:
def get(self, request, *args):
"""Returns JSON-response with all messages of ticket ith id from url. For the response format see the code. Params: ticket_id (url, pos=0): id of the ticket."""
<|body_0|>
def post(self, request, *args):
"""Params: ticket_id -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Messages:
def get(self, request, *args):
"""Returns JSON-response with all messages of ticket ith id from url. For the response format see the code. Params: ticket_id (url, pos=0): id of the ticket."""
try:
ticket_id = args[0]
except IndexError:
return self.Get.... | the_stack_v2_python_sparse | apps/cabinet/api/sellers/support/ajax.py | HaySayCheese/mappino | train | 0 | |
e9297151bd31b8478efe2aa9f54f0842f2642211 | [
"self.context_features_config = {'patientId': tf.VarLenFeature(tf.string), 'label.readmission': tf.FixedLenFeature([1], tf.int64), 'label.expired': tf.FixedLenFeature([1], tf.int64)}\nself.sequence_features_config = {'dx_ints': tf.VarLenFeature(tf.int64), 'proc_ints': tf.VarLenFeature(tf.int64), 'prior_indices': tf... | <|body_start_0|>
self.context_features_config = {'patientId': tf.VarLenFeature(tf.string), 'label.readmission': tf.FixedLenFeature([1], tf.int64), 'label.expired': tf.FixedLenFeature([1], tf.int64)}
self.sequence_features_config = {'dx_ints': tf.VarLenFeature(tf.int64), 'proc_ints': tf.VarLenFeature(tf.... | A very simple SequenceExample parser for eICU data. This Parser class is intended to be used for eICU SequenceExamples obtained from process_eicu.py. This class will not work with synthetic samples obtained from process_synthetic.py, because synthetic samples contain a different set of features and labels than eICU sam... | SequenceExampleParser | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceExampleParser:
"""A very simple SequenceExample parser for eICU data. This Parser class is intended to be used for eICU SequenceExamples obtained from process_eicu.py. This class will not work with synthetic samples obtained from process_synthetic.py, because synthetic samples contain a d... | stack_v2_sparse_classes_36k_train_023991 | 32,334 | permissive | [
{
"docstring": "Init function.",
"name": "__init__",
"signature": "def __init__(self, batch_size, num_map_threads=4)"
},
{
"docstring": "Parse function. Args: tfrecord_path: Path to TFRecord of SequenceExamples. training: Boolean value to indicate whether the model if training. Returns: Dataset ... | 2 | stack_v2_sparse_classes_30k_train_019919 | Implement the Python class `SequenceExampleParser` described below.
Class description:
A very simple SequenceExample parser for eICU data. This Parser class is intended to be used for eICU SequenceExamples obtained from process_eicu.py. This class will not work with synthetic samples obtained from process_synthetic.py... | Implement the Python class `SequenceExampleParser` described below.
Class description:
A very simple SequenceExample parser for eICU data. This Parser class is intended to be used for eICU SequenceExamples obtained from process_eicu.py. This class will not work with synthetic samples obtained from process_synthetic.py... | 0672299d78a24a7c299499d4a79102a7e1192cd9 | <|skeleton|>
class SequenceExampleParser:
"""A very simple SequenceExample parser for eICU data. This Parser class is intended to be used for eICU SequenceExamples obtained from process_eicu.py. This class will not work with synthetic samples obtained from process_synthetic.py, because synthetic samples contain a d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequenceExampleParser:
"""A very simple SequenceExample parser for eICU data. This Parser class is intended to be used for eICU SequenceExamples obtained from process_eicu.py. This class will not work with synthetic samples obtained from process_synthetic.py, because synthetic samples contain a different set ... | the_stack_v2_python_sparse | graph-convolutional-transformer/graph_convolutional_transformer.py | drskaf/Graph-Convolutional-Transformer | train | 0 |
a9f187228de29ab695ec509016128a19d23883dc | [
"re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])\nresult = re\nAssertions().assert_in_text(result, expect['mockCarInMessage'])",
"re = Information(userLogin).getPresentCar(send_data['parkName'], send_data['carNum'])\nresult = re\nAssertions().assert_in_text(result, expect... | <|body_start_0|>
re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMessage'])
<|end_body_0|>
<|body_start_1|>
re = Information(userLogin).getPresentCar(send_data['parkName'], send_da... | 临时车宽进,不需缴费宽出 | TestCarLightRuleInOutNoPay | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCarLightRuleInOutNoPay:
"""临时车宽进,不需缴费宽出"""
def test_mockCarIn(self, send_data, expect):
"""模拟进场"""
<|body_0|>
def test_presentCar(self, userLogin, send_data, expect):
"""查看在场记录"""
<|body_1|>
def test_mockCarOut(self, send_data, expect):
"... | stack_v2_sparse_classes_36k_train_023992 | 1,885 | no_license | [
{
"docstring": "模拟进场",
"name": "test_mockCarIn",
"signature": "def test_mockCarIn(self, send_data, expect)"
},
{
"docstring": "查看在场记录",
"name": "test_presentCar",
"signature": "def test_presentCar(self, userLogin, send_data, expect)"
},
{
"docstring": "模拟离场",
"name": "test_mo... | 4 | stack_v2_sparse_classes_30k_test_000576 | Implement the Python class `TestCarLightRuleInOutNoPay` described below.
Class description:
临时车宽进,不需缴费宽出
Method signatures and docstrings:
- def test_mockCarIn(self, send_data, expect): 模拟进场
- def test_presentCar(self, userLogin, send_data, expect): 查看在场记录
- def test_mockCarOut(self, send_data, expect): 模拟离场
- def te... | Implement the Python class `TestCarLightRuleInOutNoPay` described below.
Class description:
临时车宽进,不需缴费宽出
Method signatures and docstrings:
- def test_mockCarIn(self, send_data, expect): 模拟进场
- def test_presentCar(self, userLogin, send_data, expect): 查看在场记录
- def test_mockCarOut(self, send_data, expect): 模拟离场
- def te... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestCarLightRuleInOutNoPay:
"""临时车宽进,不需缴费宽出"""
def test_mockCarIn(self, send_data, expect):
"""模拟进场"""
<|body_0|>
def test_presentCar(self, userLogin, send_data, expect):
"""查看在场记录"""
<|body_1|>
def test_mockCarOut(self, send_data, expect):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCarLightRuleInOutNoPay:
"""临时车宽进,不需缴费宽出"""
def test_mockCarIn(self, send_data, expect):
"""模拟进场"""
re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMessage'])
... | the_stack_v2_python_sparse | test_suite/parkingConfig/freeParking/lightRuleChannel/test_carLightRuleInOut_noPay.py | oyebino/pomp_api | train | 1 |
cd46006ce73c8e211d25c066e48fbe241d6f708a | [
"if left == right == n:\n self.res_lst.append(res)\n return res\nif left < n:\n self.generate(left + 1, right, n, res + '(')\nif left > right:\n self.generate(left, right + 1, n, res + ')')",
"self.res_lst = list()\nself.generate(left=0, right=0, n=n, res='')\nreturn self.res_lst"
] | <|body_start_0|>
if left == right == n:
self.res_lst.append(res)
return res
if left < n:
self.generate(left + 1, right, n, res + '(')
if left > right:
self.generate(left, right + 1, n, res + ')')
<|end_body_0|>
<|body_start_1|>
self.res_ls... | 思路与算法 任何一个括号序列都一定是由 ( 开头,并且第一个 ( 一定有一个唯一与之对应的 )。这样一来,每一个括号序列可以用 (a)b 来表示,其中 a 与 b 分别是一个合法的括号序列(可以为空)。 那么,要生成所有长度为 2 * n 的括号序列,我们定义一个函数 generate(n) 来返回所有可能的括号序列。那么在函数 generate(n) 的过程中: 我们需要枚举与第一个 ( 对应的 ) 的位置 2 * i + 1; 递归调用 generate(i) 即可计算 a 的所有可能性; 递归调用 generate(n - i - 1) 即可计算 b 的所有可能性; 遍历 a 与 b 的所有可能性并拼接,即可得到所有长度为 2... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""思路与算法 任何一个括号序列都一定是由 ( 开头,并且第一个 ( 一定有一个唯一与之对应的 )。这样一来,每一个括号序列可以用 (a)b 来表示,其中 a 与 b 分别是一个合法的括号序列(可以为空)。 那么,要生成所有长度为 2 * n 的括号序列,我们定义一个函数 generate(n) 来返回所有可能的括号序列。那么在函数 generate(n) 的过程中: 我们需要枚举与第一个 ( 对应的 ) 的位置 2 * i + 1; 递归调用 generate(i) 即可计算 a 的所有可能性; 递归调用 generate(n - i - 1) 即可计算 b 的所... | stack_v2_sparse_classes_36k_train_023993 | 2,063 | no_license | [
{
"docstring": ":param left: :param right: :param n: 配额总数 :param res: :return:",
"name": "generate",
"signature": "def generate(self, left, right, n, res)"
},
{
"docstring": ":param n: :return:",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009111 | Implement the Python class `Solution` described below.
Class description:
思路与算法 任何一个括号序列都一定是由 ( 开头,并且第一个 ( 一定有一个唯一与之对应的 )。这样一来,每一个括号序列可以用 (a)b 来表示,其中 a 与 b 分别是一个合法的括号序列(可以为空)。 那么,要生成所有长度为 2 * n 的括号序列,我们定义一个函数 generate(n) 来返回所有可能的括号序列。那么在函数 generate(n) 的过程中: 我们需要枚举与第一个 ( 对应的 ) 的位置 2 * i + 1; 递归调用 generate(i) 即可计算 a 的所有... | Implement the Python class `Solution` described below.
Class description:
思路与算法 任何一个括号序列都一定是由 ( 开头,并且第一个 ( 一定有一个唯一与之对应的 )。这样一来,每一个括号序列可以用 (a)b 来表示,其中 a 与 b 分别是一个合法的括号序列(可以为空)。 那么,要生成所有长度为 2 * n 的括号序列,我们定义一个函数 generate(n) 来返回所有可能的括号序列。那么在函数 generate(n) 的过程中: 我们需要枚举与第一个 ( 对应的 ) 的位置 2 * i + 1; 递归调用 generate(i) 即可计算 a 的所有... | 47d5eaef3cf1adccaf42eb463a5c4548e003cb59 | <|skeleton|>
class Solution:
"""思路与算法 任何一个括号序列都一定是由 ( 开头,并且第一个 ( 一定有一个唯一与之对应的 )。这样一来,每一个括号序列可以用 (a)b 来表示,其中 a 与 b 分别是一个合法的括号序列(可以为空)。 那么,要生成所有长度为 2 * n 的括号序列,我们定义一个函数 generate(n) 来返回所有可能的括号序列。那么在函数 generate(n) 的过程中: 我们需要枚举与第一个 ( 对应的 ) 的位置 2 * i + 1; 递归调用 generate(i) 即可计算 a 的所有可能性; 递归调用 generate(n - i - 1) 即可计算 b 的所... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""思路与算法 任何一个括号序列都一定是由 ( 开头,并且第一个 ( 一定有一个唯一与之对应的 )。这样一来,每一个括号序列可以用 (a)b 来表示,其中 a 与 b 分别是一个合法的括号序列(可以为空)。 那么,要生成所有长度为 2 * n 的括号序列,我们定义一个函数 generate(n) 来返回所有可能的括号序列。那么在函数 generate(n) 的过程中: 我们需要枚举与第一个 ( 对应的 ) 的位置 2 * i + 1; 递归调用 generate(i) 即可计算 a 的所有可能性; 递归调用 generate(n - i - 1) 即可计算 b 的所有可能性; 遍历 a 与 ... | the_stack_v2_python_sparse | Week_03/22_括号生成.py | wffeige/algorithm015 | train | 0 |
8d94b495c90407e9b61f0f39f720209b64bde3e3 | [
"if not editor:\n if 'EDITOR' in os.environ:\n self.editor = os.environ['EDITOR']\n else:\n self.editor = 'vi'",
"_, path = mkstemp(prefix='CSE-')\nPopen('%s %s' % (self.editor, path), shell=True).wait()\nf = open(path)\noutput = f.read()\nf.close()\nos.remove(f.name)\nreturn output"
] | <|body_start_0|>
if not editor:
if 'EDITOR' in os.environ:
self.editor = os.environ['EDITOR']
else:
self.editor = 'vi'
<|end_body_0|>
<|body_start_1|>
_, path = mkstemp(prefix='CSE-')
Popen('%s %s' % (self.editor, path), shell=True).wait()... | An editor with which to edit blocks of text. | Editor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Editor:
"""An editor with which to edit blocks of text."""
def __init__(self, editor=None):
"""Initialize the editor. If editor is None, a sensible editor will be chosen from the environment."""
<|body_0|>
def compose(self):
"""Compose a block of text and return ... | stack_v2_sparse_classes_36k_train_023994 | 881 | permissive | [
{
"docstring": "Initialize the editor. If editor is None, a sensible editor will be chosen from the environment.",
"name": "__init__",
"signature": "def __init__(self, editor=None)"
},
{
"docstring": "Compose a block of text and return it.",
"name": "compose",
"signature": "def compose(s... | 2 | stack_v2_sparse_classes_30k_train_018381 | Implement the Python class `Editor` described below.
Class description:
An editor with which to edit blocks of text.
Method signatures and docstrings:
- def __init__(self, editor=None): Initialize the editor. If editor is None, a sensible editor will be chosen from the environment.
- def compose(self): Compose a bloc... | Implement the Python class `Editor` described below.
Class description:
An editor with which to edit blocks of text.
Method signatures and docstrings:
- def __init__(self, editor=None): Initialize the editor. If editor is None, a sensible editor will be chosen from the environment.
- def compose(self): Compose a bloc... | 0e9bc521e30684247d5d19717a5a938d31151fe3 | <|skeleton|>
class Editor:
"""An editor with which to edit blocks of text."""
def __init__(self, editor=None):
"""Initialize the editor. If editor is None, a sensible editor will be chosen from the environment."""
<|body_0|>
def compose(self):
"""Compose a block of text and return ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Editor:
"""An editor with which to edit blocks of text."""
def __init__(self, editor=None):
"""Initialize the editor. If editor is None, a sensible editor will be chosen from the environment."""
if not editor:
if 'EDITOR' in os.environ:
self.editor = os.environ... | the_stack_v2_python_sparse | py_lib/editor.py | fretboardfreak/code | train | 1 |
522ad8a3e6bfd81317e3e4030df5854a9048788e | [
"r = s[::-1]\nfor i in range(len(s) + 1):\n if s.startswith(r[i:]):\n return r[:i] + s",
"if not s:\n return s\nr = s[::-1]\nfor i in range(len(s)):\n s2 = s[:len(s) - i]\n if s2 == s2[::-1]:\n return s[len(s) - i:][::-1] + s"
] | <|body_start_0|>
r = s[::-1]
for i in range(len(s) + 1):
if s.startswith(r[i:]):
return r[:i] + s
<|end_body_0|>
<|body_start_1|>
if not s:
return s
r = s[::-1]
for i in range(len(s)):
s2 = s[:len(s) - i]
if s2 == s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def shortestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def shortestPalindrome_v2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
r = s[::-1]
for i in range(len(s) + 1):
... | stack_v2_sparse_classes_36k_train_023995 | 2,158 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "shortestPalindrome",
"signature": "def shortestPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "shortestPalindrome_v2",
"signature": "def shortestPalindrome_v2(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestPalindrome(self, s): :type s: str :rtype: str
- def shortestPalindrome_v2(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestPalindrome(self, s): :type s: str :rtype: str
- def shortestPalindrome_v2(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def shortestPalindrome... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def shortestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def shortestPalindrome_v2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def shortestPalindrome(self, s):
""":type s: str :rtype: str"""
r = s[::-1]
for i in range(len(s) + 1):
if s.startswith(r[i:]):
return r[:i] + s
def shortestPalindrome_v2(self, s):
""":type s: str :rtype: str"""
if not s:
... | the_stack_v2_python_sparse | src/lt_214.py | oxhead/CodingYourWay | train | 0 | |
1c0665372e79a83ee7c08b36d35b7471595eecfd | [
"updated_topic_model = topic_services.populate_topic_model_fields(topic_model, migrated_topic)\ntopic_rights_model = topic_models.TopicRightsModel.get(migrated_topic.id)\nchange_dicts = [change.to_dict() for change in topic_changes]\nwith datastore_services.get_ndb_context():\n models_to_put = updated_topic_mode... | <|body_start_0|>
updated_topic_model = topic_services.populate_topic_model_fields(topic_model, migrated_topic)
topic_rights_model = topic_models.TopicRightsModel.get(migrated_topic.id)
change_dicts = [change.to_dict() for change in topic_changes]
with datastore_services.get_ndb_context()... | Job that migrates Topic models. | MigrateTopicJob | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MigrateTopicJob:
"""Job that migrates Topic models."""
def _update_topic(topic_model: topic_models.TopicModel, migrated_topic: topic_domain.Topic, topic_changes: Sequence[topic_domain.TopicChange]) -> Sequence[base_models.BaseModel]:
"""Generates newly updated topic models. Args: top... | stack_v2_sparse_classes_36k_train_023996 | 13,939 | permissive | [
{
"docstring": "Generates newly updated topic models. Args: topic_model: TopicModel. The topic which should be updated. migrated_topic: Topic. The migrated topic domain object. topic_changes: TopicChange. The topic changes to apply. Returns: sequence(BaseModel). Sequence of models which should be put into the d... | 3 | null | Implement the Python class `MigrateTopicJob` described below.
Class description:
Job that migrates Topic models.
Method signatures and docstrings:
- def _update_topic(topic_model: topic_models.TopicModel, migrated_topic: topic_domain.Topic, topic_changes: Sequence[topic_domain.TopicChange]) -> Sequence[base_models.Ba... | Implement the Python class `MigrateTopicJob` described below.
Class description:
Job that migrates Topic models.
Method signatures and docstrings:
- def _update_topic(topic_model: topic_models.TopicModel, migrated_topic: topic_domain.Topic, topic_changes: Sequence[topic_domain.TopicChange]) -> Sequence[base_models.Ba... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class MigrateTopicJob:
"""Job that migrates Topic models."""
def _update_topic(topic_model: topic_models.TopicModel, migrated_topic: topic_domain.Topic, topic_changes: Sequence[topic_domain.TopicChange]) -> Sequence[base_models.BaseModel]:
"""Generates newly updated topic models. Args: top... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MigrateTopicJob:
"""Job that migrates Topic models."""
def _update_topic(topic_model: topic_models.TopicModel, migrated_topic: topic_domain.Topic, topic_changes: Sequence[topic_domain.TopicChange]) -> Sequence[base_models.BaseModel]:
"""Generates newly updated topic models. Args: topic_model: Top... | the_stack_v2_python_sparse | core/jobs/batch_jobs/topic_migration_jobs.py | oppia/oppia | train | 6,172 |
8630cbd8e8ab0ae73391492f27b365950f89a599 | [
"ObjectManager.__init__(self)\nself.getters.update({'closed': 'get_general', 'forum': 'get_foreign_key', 'name': 'get_general', 'posts': 'get_many_to_many', 'sticky': 'get_general'})\nself.setters.update({'closed': 'set_general', 'forum': 'set_foreign_key', 'name': 'set_general', 'sticky': 'set_general'})\nself.my_... | <|body_start_0|>
ObjectManager.__init__(self)
self.getters.update({'closed': 'get_general', 'forum': 'get_foreign_key', 'name': 'get_general', 'posts': 'get_many_to_many', 'sticky': 'get_general'})
self.setters.update({'closed': 'set_general', 'forum': 'set_foreign_key', 'name': 'set_general', '... | Manage Topics in the Power Reg system | ForumTopicManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForumTopicManager:
"""Manage Topics in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name, forum, optional_attributes=None):
"""Create a new Topic @param name name of the Topic @type name string @param forum... | stack_v2_sparse_classes_36k_train_023997 | 1,845 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a new Topic @param name name of the Topic @type name string @param forum forum FK @type forum int @return a reference to the newly created Topic",
"name": "create",
"signature": ... | 2 | null | Implement the Python class `ForumTopicManager` described below.
Class description:
Manage Topics in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name, forum, optional_attributes=None): Create a new Topic @param name name of the Topic @type nam... | Implement the Python class `ForumTopicManager` described below.
Class description:
Manage Topics in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name, forum, optional_attributes=None): Create a new Topic @param name name of the Topic @type nam... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class ForumTopicManager:
"""Manage Topics in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name, forum, optional_attributes=None):
"""Create a new Topic @param name name of the Topic @type name string @param forum... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ForumTopicManager:
"""Manage Topics in the Power Reg system"""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.getters.update({'closed': 'get_general', 'forum': 'get_foreign_key', 'name': 'get_general', 'posts': 'get_many_to_many', 'sticky': 'get_general'})... | the_stack_v2_python_sparse | forum/managers/topic.py | ninemoreminutes/openassign-server | train | 0 |
c8b07211370c3be9387017c9972b29c7c02acdc7 | [
"super(Net, self).__init__()\nself.cfgs = cfgs\nself.simclr = SimCLR(cfgs)\nself.backbone = BAN(cfgs)\nlayers = [weight_norm(nn.Linear(cfgs.hidden_size, cfgs.flat_out_size), dim=None), nn.ReLU(), nn.Dropout(cfgs.classifer_dropout_r, inplace=True)]\nself.flatten = nn.Sequential(*layers)\nlayers_classifer = [weight_n... | <|body_start_0|>
super(Net, self).__init__()
self.cfgs = cfgs
self.simclr = SimCLR(cfgs)
self.backbone = BAN(cfgs)
layers = [weight_norm(nn.Linear(cfgs.hidden_size, cfgs.flat_out_size), dim=None), nn.ReLU(), nn.Dropout(cfgs.classifer_dropout_r, inplace=True)]
self.flatten... | Net | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Net:
def __init__(self, cfgs):
""":param cfgs: configurations of XTQA. :param pretrained_emb: :param token_size: the size of vocabulary table."""
<|body_0|>
def forward(self, que_emb, dia_f, opt_emb, dia_matrix, dia_node_emb, cfg):
""":param que_ix: the index of ques... | stack_v2_sparse_classes_36k_train_023998 | 2,507 | no_license | [
{
"docstring": ":param cfgs: configurations of XTQA. :param pretrained_emb: :param token_size: the size of vocabulary table.",
"name": "__init__",
"signature": "def __init__(self, cfgs)"
},
{
"docstring": ":param que_ix: the index of questions :param opt_ix: the index of options :param dia: the ... | 2 | stack_v2_sparse_classes_30k_train_006952 | Implement the Python class `Net` described below.
Class description:
Implement the Net class.
Method signatures and docstrings:
- def __init__(self, cfgs): :param cfgs: configurations of XTQA. :param pretrained_emb: :param token_size: the size of vocabulary table.
- def forward(self, que_emb, dia_f, opt_emb, dia_matr... | Implement the Python class `Net` described below.
Class description:
Implement the Net class.
Method signatures and docstrings:
- def __init__(self, cfgs): :param cfgs: configurations of XTQA. :param pretrained_emb: :param token_size: the size of vocabulary table.
- def forward(self, que_emb, dia_f, opt_emb, dia_matr... | 7b2d913fa70e3520d9055c9493ca640cf30892b9 | <|skeleton|>
class Net:
def __init__(self, cfgs):
""":param cfgs: configurations of XTQA. :param pretrained_emb: :param token_size: the size of vocabulary table."""
<|body_0|>
def forward(self, que_emb, dia_f, opt_emb, dia_matrix, dia_node_emb, cfg):
""":param que_ix: the index of ques... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Net:
def __init__(self, cfgs):
""":param cfgs: configurations of XTQA. :param pretrained_emb: :param token_size: the size of vocabulary table."""
super(Net, self).__init__()
self.cfgs = cfgs
self.simclr = SimCLR(cfgs)
self.backbone = BAN(cfgs)
layers = [weight_n... | the_stack_v2_python_sparse | model/ban_csdia/net.py | dr-majie/2019-mytqa | train | 3 | |
de652ebf388e3ced877abf6411340b5fab44e4fe | [
"shift_x = constants.all_shifts[direction_index]['x']\nshift_y = constants.all_shifts[direction_index]['y']\nreturn (shift_x, shift_y)",
"shift_x, shift_y = Utilities.get_shift_by_direction(direction_index)\nnew_x, new_y = (shift_x + x, shift_y + y)\nreturn (new_x, new_y)"
] | <|body_start_0|>
shift_x = constants.all_shifts[direction_index]['x']
shift_y = constants.all_shifts[direction_index]['y']
return (shift_x, shift_y)
<|end_body_0|>
<|body_start_1|>
shift_x, shift_y = Utilities.get_shift_by_direction(direction_index)
new_x, new_y = (shift_x + x, ... | Utilities | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Utilities:
def get_shift_by_direction(direction_index):
"""Function return shift depending on direction. Args: direction_index(int): index specified direction Returns: (int, int): shift by columns and rows"""
<|body_0|>
def get_new_coordinates(direction_index, x, y):
... | stack_v2_sparse_classes_36k_train_023999 | 1,224 | permissive | [
{
"docstring": "Function return shift depending on direction. Args: direction_index(int): index specified direction Returns: (int, int): shift by columns and rows",
"name": "get_shift_by_direction",
"signature": "def get_shift_by_direction(direction_index)"
},
{
"docstring": "Function returns ne... | 2 | null | Implement the Python class `Utilities` described below.
Class description:
Implement the Utilities class.
Method signatures and docstrings:
- def get_shift_by_direction(direction_index): Function return shift depending on direction. Args: direction_index(int): index specified direction Returns: (int, int): shift by c... | Implement the Python class `Utilities` described below.
Class description:
Implement the Utilities class.
Method signatures and docstrings:
- def get_shift_by_direction(direction_index): Function return shift depending on direction. Args: direction_index(int): index specified direction Returns: (int, int): shift by c... | 291592e97b6d8fe9f9e6627dc0023875918d3463 | <|skeleton|>
class Utilities:
def get_shift_by_direction(direction_index):
"""Function return shift depending on direction. Args: direction_index(int): index specified direction Returns: (int, int): shift by columns and rows"""
<|body_0|>
def get_new_coordinates(direction_index, x, y):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Utilities:
def get_shift_by_direction(direction_index):
"""Function return shift depending on direction. Args: direction_index(int): index specified direction Returns: (int, int): shift by columns and rows"""
shift_x = constants.all_shifts[direction_index]['x']
shift_y = constants.all_... | the_stack_v2_python_sparse | Dmytro_Skorobohatskyi/batch_10/dungeon_game_stereotype_pkg/build/lib/dungeon_game_stereotype_pkg/utilities.py | SmischenkoB/campus_2018_python | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.